text:
'use strict';

var Packet = require('./packet');

// TODO: created something more flexible to load this on demand
var nodeTypes = {
 xNode: require('./node'),
 polymer: require('./node/polymer')
};
var xLink = require('./link');
var util = require('util');
var uuid = require('uuid').v4;
var Run = require('./run');
var Connector = require('./connector');
var validate = require('./validate');
var DefaultContextProvider = require('../lib/context/defaultProvider');
var IoMapHandler = require('../lib/io/mapHandler');
var DefaultProcessManager  = require('../lib/process/defaultManager');
var MultiSort = require('../lib/multisort');
var EventEmitter = require('events').EventEmitter;
var validate = require('./validate');

var Status = {};
Status.STOPPED = 'stopped';
Status.RUNNING = 'running';

/**
 *
 * Actor
 *
 * The Actor is responsible of managing a flow
 * it links and it's nodes.
 *
 * A node contains the actual programming logic.
 *
 * @api public
 * @author Rob Halff <rob.halff@gmail.com>
 * @constructor
 */
function Actor() {

  EventEmitter.apply(this, arguments);

  this.ioHandler      = undefined;
  this.processManager = undefined;
  this.nodes          = {};
  this.links          = {};
  this.iips           = {};
  this.view           = [];
  this.status         = undefined;

  this.type           = 'flow';

  /**
   *
   * Added by default.
   *
   * If others need to be used they should be set before addMap();
   *
   */
  this.addIoHandler(new IoMapHandler());
  this.addProcessManager(new DefaultProcessManager());

}

util.inherits(Actor, EventEmitter);

/**
 *
 * Validate the map against the node definitions
 *
 * @param {Object} map
 * @api public
 */
Actor.prototype.validateMap = function(map) {
  validate.flow(map);
};

/**
 *
 * Create/instantiate  a node
 *
 * Node at this stage is nothing more then:
 *
 *  { ns: "fs", name: "readFile" }
 *
 * @param {Object} node - Node as defined within a map
 * @param {Object} def  - Node Definition
 *
 * @api public
 */
Actor.prototype.createNode = function(node, def) {

  var self = this;

  if (!def) {
    throw new Error(
      util.format(
        'Failed to get node definition for %s:%s', node.ns, node.name
      )
    );
  }

  if (!node.id) {
    throw Error('Node should have an id');
  }

  if (!def.ports) {
    def.ports = {};
  }

  // merges expose, persist etc, with port definitions.
  // This is not needed with proper inheritance
  for (var type in node.ports) {
    if (node.ports.hasOwnProperty(type) &&
       def.ports.hasOwnProperty(type)
       ) {
      for (var name in node.ports[type]) {
        if (node.ports[type].hasOwnProperty(name) &&
          def.ports[type].hasOwnProperty(name)
          ) {

          for (var property in node.ports[type][name]) {
            if (node.ports[type][name].hasOwnProperty(property)) {
              // add or overwrite it.
              def.ports[type][name][property] =
                node.ports[type][name][property];
            }
          }
        }
      }
    }
  }

  // allow instance to overwrite other node definition data also.
  // probably make much more overwritable, although many
  // should not be overwritten, so maybe just keep it this way.
  if (node.title) {
    def.title = node.title;
  }

  if (node.description) {
    def.description = node.description;
  }

  var identifier = node.title || [
    node.ns, '::', node.name, '-',
    Object.keys(this.nodes).length
  ].join('');

  if (def.type === 'flow') {

    var xFlow = require('./flow'); // solve circular reference.

    validate.flow(def);

    this.nodes[node.id] = new xFlow(
      node.id,
      def,
      identifier,
      this.loader,        // single(ton) instance (TODO: di)
      this.ioHandler,     // single(ton) instance
      this.processManager // single(ton) instance
    );

  } else {

    var cls = def.type || 'xNode';

    if (nodeTypes.hasOwnProperty(cls)) {

      validate.nodeDefinition(def);

      this.nodes[node.id] = new nodeTypes[cls](
        node.id,
        def,
        identifier,
        this.ioHandler.CHI
      );

      // register and set pid, xFlow/actor adds itself to it (hack)
      this.processManager.register(this.nodes[node.id]);

    } else {

      throw Error(
        util.format('Unknown node type: `%s`', cls)
      );

    }

  }

  // add parent to both xflow's and node's
  // not very pure seperation, but it's just very convenient
  this.nodes[node.id].setParent(this);

  if (node.provider) {
    this.nodes[node.id].provider = node.provider;
  }

  // TODO: move this to something more general.
  // not on every node creation.
  if (!this.contextProvider) {
    this.addContextProvider(new DefaultContextProvider());
  }

  this.contextProvider.addContext(
    this.nodes[node.id],
    node.context
  );

  this.nodes[node.id].on('output',
    this.ioHandler.output.bind(this.ioHandler)
  );

  this.nodes[node.id].on('freePort', function(event) {

    var links;
    var i;

    // get all current port connections
    links = this.portGetConnections(event.port);

    if (links.length) {

      for (i = 0; i < links.length; i++) {

        var link = links[i];

        // unlock if it was locked
        if (self.ioHandler.queueManager.isLocked(link.ioid)) {
          self.ioHandler.queueManager.unlock(link.ioid);
        }

      }

      if (event.link) {

        // remove the link belonging to this event
        if (event.link.has('dispose')) {

          // TODO: remove cyclic all together, just use core/forEach
          //  this will cause bugs if you send multiple cyclics because
          //  the port is never unplugged..
          if (!event.link.target.has('cyclic')) {
            self.removeLink(event.link);
          }
        }

      }

    }

  });

  this.emit('addNode', {node: this.nodes[node.id]});

  return this.nodes[node.id];

};

/**
 *
 * Plugs a source into a target node
 *
 *
 * @param {Link} link
 */
Actor.prototype.plugNode = function(link) {

  this.getNode(link.target.id).plug(link);

  return this;

};

/**
 *
 * Unplugs a port for the node specified.
 *
 * @param {Link} link
 */
Actor.prototype.unplugNode = function(link) {

  // could be gone, if called from freePort
  // when nodes are being removed.
  if (this.hasNode(link.target.id)) {
    this.getNode(link.target.id).unplug(link);
  }

  return this;

};

/**
 *
 * Holds a Node
 *
 * @param {String} id
 * @api public
 */
Actor.prototype.hold = function(id) {

  this.getNode(id).hold();

  return this;

};

/**
 *
 * Starts the actor
 *
 * @param {Boolean} push
 * @api public
 */
Actor.prototype.start = function(push) {

  this.status = Status.RUNNING;

  // TODO: this means IIPs should be send after start.
  //       enforce this..
  this.clearIIPs();

  // start all nodes
  // (could also be started during addMap
  // runtime is skipping addMap.
  // so make sure start() is restartable.
  for (var id in this.nodes) {
    if (this.nodes.hasOwnProperty(id)) {
      this.getNode(id).start();
    }
  }

  if (push !== false) {
    this.push();
  }

  // there are many other ways to start
  // so this does not ensure much.
  // however the process manager listens to this.
  // Real determination if something is started or stopped
  // includes the ioHandler.
  // So let's just inform the io handler we are started.

  this.emit('start', {
    node: this
  });

  return this;

};

/**
 *
 * Stops the actor
 *
 * Use a callback to make sure it is stopped.
 *
 * @api public
 */
Actor.prototype.stop = function(cb) {

  var self = this;

  this.status = Status.STOPPED;

  if (this.ioHandler) {

    this.ioHandler.reset(function() {

      // close ports opened by iips
      self.clearIIPs();

      self.emit('stop', {
        node: self
      });

      if (cb) {
        cb();
      }

    });

  }

};

Actor.prototype.pause = function() {

  this.status = Status.STOPPED;

  for (var id in this.nodes) {
    if (this.nodes.hasOwnProperty(id)) {
      this.getNode(id).hold();
    }
  }

  return this;

};

/**
 *
 * Resumes the actor
 *
 * All nodes which are on hold will resume again.
 *
 * @api public
 */
Actor.prototype.resume = function() {

  this.status = Status.RUNNING;

  for (var id in this.nodes) {
    if (this.nodes.hasOwnProperty(id)) {
      this.getNode(id).release();
    }
  }

  return this;

};

/**
 *
 * Get the current status
 *
 * @api public
 */
Actor.prototype.getStatus = function() {
  return this.status;
};

/**
 *
 * Create an actor
 *
 * @api public
 */
Actor.create = function(map, loader, ioHandler, processManager) {

  var actor = new Actor();
  ioHandler = ioHandler ? ioHandler : new IoMapHandler();
  actor.addLoader(loader);
  actor.addIoHandler(ioHandler);
  actor.addProcessManager(processManager);
  actor.addMap(map);

  return actor;
};

/**
 *
 * Releases a node if it was on hold
 *
 * @param {String} id
 * @api public
 */
Actor.prototype.release = function(id) {
  this.getNode(id).release();
  return this;
};

/**
 *
 * Pushes the Actor
 *
 * Will send :start to all nodes without input
 * and all nodes which have all their input ports
 * filled by context already.
 *
 * @api public
 */
Actor.prototype.push = function() {

  this.status = Status.RUNNING;

  for (var id in this.nodes) {
    if (this.nodes.hasOwnProperty(id)) {
      var node = this.getNode(id);
      if (node.isStartable()) {
        var iip =  new Connector();
        iip.plug(id, ':start');
        this.sendIIP(iip, '');
      }
    }
  }

  return this;
};

/**
 *
 * Adds the definition Loader
 *
 * This provides an api to get the required node definitions.
 *
 * The loader should already be init'ed
 *
 * e.g. the remote loader will already have loaded the definitions.
 * and is ready to respond to getNodeDefinition(ns, name, type, provider)
 *
 * e.g. An async loader could do something like this:
 *
 *   loader(flow, function() { actor.addLoader(loader); }
 *
 * With a sync loader it will just look like:
 *
 * actor.addLoader(loader);
 *
 * @api public
 */
Actor.prototype.addLoader = function(loader) {

  this.loader = loader;

  return this;

};

/**
 *
 * Validate and read map
 *
 * @param {Object} map
 * @api public
 *
 */
Actor.prototype.addMap = function(map) {

  var i;
  var self = this;

  if (typeof map === 'undefined') {
    throw new Error('map is not defined');
  }

  if (map !== Object(map)) {
    throw new Error('addMap expects an object');
  }

  try {
    validate.flow(map);
  } catch (e) {
    if (map.title) {
      throw Error(
        util.format('Flow `%s`: %s', map.title, e.message)
      );
    } else {
      throw Error(
        util.format('Flow %s:%s: %s', map.ns, map.name, e.message)
      );
    }
  }

  if (!this.id) {
    // xFlow contains it, direct actors don't perse
    this.id = map.id || uuid();
  }

  // add ourselves (actor/xFlow) to the processmanager
  // this way links can store our id and pid
  // must be done *before* adding our nodes.
  // otherwise our nodes will be registered before ourselves.
  if (!this.pid) { // re-run
    this.processManager.register(this);
  }

  // add nodes and links one by one so there is more control
  map.nodes.forEach(function(node) {

    if (!node.id) {
      throw new Error(
        util.format('Node lacks an id: %s:%s', node.ns, node.name)
      );
    }

    // give the node a default provider.
    if (!node.provider) {
      if (map.providers && map.providers.hasOwnProperty('@')) {
        node.provider = map.providers['@'].url;
      }
    }

    var def = self.loader.getNodeDefinition(node, map);
    if (!def) {

      throw new Error(
        util.format(
          'Failed to get node definition for %s:%s', node.ns, node.name
        )
      );
    }

    self.createNode(node, def);

  });

  // this.ensureConnectionNumbering(map);

  if (map.hasOwnProperty('links')) {
    map.links.forEach(function(link) {
      self.addLink(
       self.createLink(link)
      );
    });
  }

  for (i = 0; i < map.nodes.length; i++) {
    this.view.push(map.nodes[i].id);
  }

  // all nodes & links setup, run start method on node
  for (var id in this.nodes) {
    if (this.nodes.hasOwnProperty(id)) {
      this.getNode(id).start();
    }
  }

  return this;

};

/**
 *
 * Used by the process manager to set our id
 *
 */
Actor.prototype.setPid = function(pid) {
  this.pid = pid;
};

/**
 *
 * Adds a node to the map.
 *
 * The object format is like it's defined within a map.
 *
 * Right now this is only used during map loading.
 *
 * For dynamic loading care should be taken to make
 * this node resolvable by the loader.
 *
 * Which means the definition should either be found
 * at the default location defined within the map.
 * Or the node itself should carry provider information.
 *
 * A provider can be defined as:
 *
 *  - url:        https://serve.rhcloud.com/flows/{ns}/{name}
 *  - file:       ./{ns}/{name}
 *  - namespace:  MyNs
 *
 * Namespaces are defined within the map, so MyNs will point to
 * either the full url or filesystem location.
 *
 * Once a map is loaded _all_ nodes will carry the full url individually.
 * The namespace is just their to simplify the json format and for ease
 * of maintainance.
 *
 *
 * @param {Object} node
 * @api public
 *
 */
Actor.prototype.addNode = function(node) {

  this.createNode(node);

  return this;
};

/**
 *
 * Creates a new connection/link
 *
 * Basically takes a plain link object
 * and creates a proper xLink from it.
 *
 * The internal map holds xLinks, whereas
 * the source map is just plain JSON.
 *
 * Structurewise they are almost the same.
 *
 * @param {Object} ln
 * @return {xLink} link
 * @api public
 *
 */
Actor.prototype.createLink = function(ln) {

  // auto creates id if there is none.
  // not sure if that's desired.
  var link = xLink.create(ln.id);

  if (!ln.source) {
    throw Error('Create link expects a source');
  }

  if (!ln.target) {
    throw Error('Create link expects a target');
  }

  link.setSource(
    ln.source.id,
    ln.source.port,
    ln.source.setting,
    ln.source.action
  );

  link.setTarget(
    ln.target.id,
    ln.target.port,
    ln.target.setting,
    ln.target.action
  );

  return link;

};

/**
 *
 * Adds a link
 *
 * @param {xLink} link
 */
Actor.prototype.addLink = function(link) {

  if (link.constructor.name !== 'Link') {
    throw Error('Link must be of type Link');
  }

  if (link.source.id !== this.id) { // Warn: IIP has our own id
    var sourceNode = this.getNode(link.source.id);
    if (!sourceNode.portExists('output', link.source.port)) {
      throw Error(util.format(
        'Source node (%s:%s) does not have an output port named `%s`\n\n' +
        '\tOutput ports available:\t%s\n',
        sourceNode.ns,
        sourceNode.name,
        link.source.port,
        Object.keys(sourceNode.ports.output).join(', ')
      ));
    }
  }

  var targetNode = this.getNode(link.target.id);
  if (link.target.port !== ':start' &&
      !targetNode.portExists('input', link.target.port)
    ) {
    throw Error(
      util.format(
        'Target node (%s:%s) does not have an input port named `%s`\n\n' +
        '\tInput ports available:\t%s\n',
        targetNode.ns,
        targetNode.name,
        link.target.port,
        Object.keys(targetNode.ports.input).join(', ')
      )
    );
  }

  // var targetNode = this.getNode(link.target.id);

  // FIXME: rewriting sync property
  // to contain the process id of the node it's pointing
  // to not just the nodeId defined within the graph
  if (link.target.has('sync')) {
    link.target.set('sync', this.getNode(link.target.get('sync')).pid);
  }

  link.graphId  = this.id;
  link.graphPid = this.pid;

  var self = this;

  var dataHandler = function dataHandler(p) {
    if (!this.ioid) {
      throw Error('LINK MISSING IOID');
    }

    self.__input(this, p);
  };

  link.on('data', dataHandler);

  if (link.source.id) {
    if (link.source.id === this.id) {
      link.setSourcePid(this.pid || this.id);
    } else {
      link.setSourcePid(this.getNode(link.source.id).pid);
    }
  }

  link.setTargetPid(this.getNode(link.target.id).pid);

  // remember our own links, so we can remove them
  // if it has data it's an iip
  if (undefined !== link.data) {
    this.iips[link.id] = link;
  } else {
    this.links[link.id] = link;
  }

  this.ioHandler.connect(link);

  this.plugNode(link);

  // bit inconsistent with event.node
  // should be event.link
  this.emit('addLink', link);

  // this.ensureConnectionNumbering();
  return link;

};

Actor.prototype.__input = function(link, p) {

  var self = this;

  var targetNode = this.getNode(link.target.id);

  var ret = targetNode.inputPortAvailable(link.target);

  if (util.isError(ret) || ret === false) {

    self.ioHandler.reject(ret, link, p);

  } else {

    ret = targetNode.fill(link.target, p);

    if (util.isError(ret)) {

      // set node in error state and output error to ioManager
      targetNode.error(ret);

      self.ioHandler.reject(ret, link, p);

    } else {

      self.ioHandler.accept(link, p);
    }

  }

};

Actor.prototype.clearIIP = function(link) {

  var id;
  var oldLink;

  for (id in this.iips) {

    if (this.iips.hasOwnProperty(id)) {

      oldLink = this.iips[id];

      // source is always us so do not have to check it.
      if ((
          oldLink.source.port === ':iip' ||
          oldLink.target.port === link.target.port ||
          oldLink.target.port === ':start' // huge uglyness
         ) &&
         oldLink.target.id   === link.target.id) {

        this.unplugNode(oldLink);

        this.ioHandler.disconnect(oldLink);

        delete this.iips[oldLink.id];

        // TODO: just rename this to clearIIP
        this.emit('removeIIP', oldLink);

      }

    }
  }

  // io handler could do this.
  // removelink on the top-level actor/graph
  // is not very useful

};

/**
*
* Clear IIPs
*
* If target is specified, only those iips will be cleared.
*
*/
Actor.prototype.clearIIPs = function(target) {

  var id;
  var iip;
  for (id in this.iips) {
    if (this.iips.hasOwnProperty(id)) {
      iip = this.iips[id];
      if (!target ||
        (target.id === iip.target.id && target.port === iip.target.port)) {
        this.clearIIP(this.iips[id]);
      }
    }
  }
};

/**
 *
 * Removes a node from the map
 *
 * @param {string} nodeId
 * @param {function} cb
 * @api public
 */
Actor.prototype.removeNode = function(nodeId, cb) {

  // removed the links
  // TODO: there is no this.map anymore.
  // notify IO handler we are gone.
  var id;
  var ln;
  var self = this;
  for (id in this.links) {
    if (this.links.hasOwnProperty(id)) {

      ln  = this.links[id];

      if (ln.source.id === nodeId ||
        ln.target.id === nodeId) {
        this.removeLink(ln);
      }

    }

  }

  // should wait for IO, especially there is a chance
  // system events are still spitting.

  // register and set pid
  this.processManager.unregister(this.getNode(nodeId), function() {

    var oldNode = self.nodes[nodeId].export();

    delete self.nodes[nodeId];

    self.emit('removeNode', {
      node: oldNode
    });

    if (cb) {
      cb();
    }

  });

  // not used
  // return this;

};

Actor.prototype.removeNodes = function() {

  this.clear();

};

Actor.prototype.setMeta = function(nodeId, key, value) {

  var node = this.getNode(nodeId);

  node.setMeta(key, value);

  this.emit('metadata', {
    id: this.id,
    node: node.export()
  });

};

/**
 *
 * Removes link
 *
 * @param {Link} ln
 * @api public
 *
 */
Actor.prototype.removeLink = function(ln) {

  // we should be able to find a link without id.
  var link;
  var what = 'links';

  link = this.links[ln.id];
  if (!link) {
    link = this.iips[ln.id];
    if (!link) {
      //throw Error('Cannot find link');
      // TODO: Seems to happen with ip directly to subgraph (non-fatal)
      console.warn('FIXME: cannot find link');
      return;
    }
    what = 'iips';
  }

  this.unplugNode(link);

  this.ioHandler.disconnect(link);

  // io handler could do this.
  // removelink on the top-level actor/graph
  // is not very useful

  var oldLink = this[what][link.id];

  delete this[what][link.id];

  this.emit('removeLink', oldLink);

  return this;

};

/**
 *
 * Adds a port
 *
 * NOT IMPLEMENTED
 *
 * @api public
 */
Actor.prototype.addPort = function() {

  return this;

};

/**
 *
 * Removes a port
 *
 * NOT IMPLEMENTED
 *
 * @api public
 */
Actor.prototype.removePort = function() {

  return this;

};

/**
 *
 * Resets this instance so it can be re-used
 *
 * Note: The registered loader is left untouched.
 *
 * @api public
 *
 */
Actor.prototype.reset = function() {

  var id;

  for (id in this.nodes) {
    if (this.nodes.hasOwnProperty(id)) {
      this.getNode(id).reset();
    }
  }

  // if nothing has started yet
  // there is no ioHandler
  if (this.ioHandler) {
    this.ioHandler.reset();
  }

  return this;

};

Actor.prototype.clear = function(cb) {

  if (!cb) {
    throw Error('clear expects a callback');
  }

  var self = this;
  var nodeId;
  var cnt = 0;
  var total = Object.keys(this.nodes).length;

  if (total === 0) {
    cb();
  }

  function removeNodeHandler() {
    cnt++;
    if (cnt === total) {
      self.nodes = {};
      cb();
    }
  }
  // remove node will automatically remove all links
  for (nodeId in this.nodes) {
    if (this.nodes.hasOwnProperty(nodeId)) {
      // will remove links also.
      this.removeNode(nodeId, removeNodeHandler);
    }
  }

};

/**
 *
 * Add IO Handler.
 *
 * The IO Handler handles all the input and output.
 *
 * @param {IOHandler} handler
 * @api public
 *
 */
Actor.prototype.addIoHandler = function(handler) {

  this.ioHandler = handler;

  return this;

};

/**
 *
 * Add Process Manager.
 *
 * The Process Manager holds all processes.
 *
 * @param {Object} manager
 * @api public
 *
 */
Actor.prototype.addProcessManager = function(manager) {

  this.processManager = manager;

  return this;

};

/**
 *
 * Add a new context provider.
 *
 * A context provider pre-processes the raw context
 *
 * This is useful for example when using the command line.
 * All nodes which do not have context set can be asked for context.
 *
 * E.g. database credentials could be prompted for after which all
 *      input is fullfilled and the flow will start to run.
 *
 * @param {ContextProvider} provider
 * @api private
 *
 */
Actor.prototype.addContextProvider = function(provider) {
  this.contextProvider = provider;

  return this;

};

/**
 *
 * Explains what input and output ports are
 * available for interaction.
 *
 */
Actor.prototype.help = function() {

};

/**
 *
 * Send IIPs
 *
 * Optionally with `options` for the port:
 *
 * e.g. { persist: true }
 *
 * Optionally with `source` information
 *
 * e.g. { index: 1 } // index for array port
 *
 * @param {Object} iips
 * @api public
 */
Actor.prototype.sendIIPs = function(iips) {

  var self = this;

  var links = [];

  iips.forEach(function(iip) {

    var xLink = self.createLink({
       source: {
         id: self.id, // we are the sender
         port: ':iip'
       },
       target: iip.target
    });

    // dispose after fill
    xLink.set('dispose', true);

    if (iip.data === undefined) {
      throw Error('IIP data is `undefined`');
    }

    xLink.data = iip.data;

    links.push(xLink);

  });

  links.forEach(function(iip) {

    // TODO: this doesn't happen anymore it's always a link.
    // make sure settings are always set also.
    if (iip.target.constructor.name !== 'Connector') {
      var target = new Connector();
      target.plug(iip.target.id, iip.target.port);
      for (var key in iip.target.setting) {
        if (iip.target.setting.hasOwnProperty(key)) {
          target.set(key, iip.target.setting[key]);
        }
      }
      iip.target = target;
    }

    if (!self.id) {
      throw Error('Actor must contain an id');
    }

    self.addLink(iip);

  });

  links.forEach(function(link) {

    self.ioHandler.emit('send', link);

    var p = new Packet(JSON.parse(JSON.stringify(link.data)));

    // a bit too direct, ioHandler should do this..
    self.ioHandler.queueManager.queue(link.ioid, p);

    // remove data bit.
    delete link.data;
  });

  return links;

};

/*
 * Send a single IIP to a port.
 *
 * Note: If multiple IIPs have to be send use sendIIPs instead.
 *
 * Source is mainly for testing, but essentially it allows you
 * to imposter a sender as long as you send along the right
 * id and source port name.
 *
 * Source is also used to set an index[] for array ports.
 * However, if you send multiple iips for an array port
 * they should be send as a group using sendIIPs
 *
 * This is because they should be added in reverse order.
 * Otherwise the process will start too early.
 *
 * @param {Connector} target
 * @param {Object} data
 * @api public
 */
Actor.prototype.sendIIP = function(target, data) {

  if (!this.id) {
    throw Error('Actor must contain an id');
  }

  if (undefined === data) {
    throw Error('Refused to send IIP without data');
  }

  var ln = {
    source: {
      id: this.id, // we are the sender
      pid: this.pid,
      port: ':iip'
    },
    target: target
  };

  var xLink = this.createLink(ln);
  xLink.data = data;

  // dispose after fill
  xLink.set('dispose', true);

  // makes use of xLink.data
  this.addLink(xLink);

  this.ioHandler.emit('send', xLink);

  var p = new Packet(JSON.parse(JSON.stringify(xLink.data)));

  this.ioHandler.queueManager.queue(xLink.ioid, p);

  // remove data bit.
  delete xLink.data;

  return xLink;

};

/**
 *
 * Retrieve a node by it's process id
 *
 * @param {String} pid - Process ID
 * @return {Object} node
 * @api public
 */
Actor.prototype.getNodeByPid = function(pid) {

  var id;
  var node;

  for (id in this.nodes) {
    if (this.nodes.hasOwnProperty(id)) {
      node = this.getNode(id);
      if (node.pid === pid) {
        return node;
      }
    }
  }

  return;
};

/**
 *
 * Get all node ids this node depends on.
 *
 * @param {String} nodeId
 * @return {Array} nodes
 * @api public
 */
Actor.prototype.getAncestorIds = function(nodeId) {

  var self = this;

  var pids = this.ioHandler.getAncestorPids(
    this.getNode(nodeId).pid
  );

  var ids = [];
  pids.forEach(function(pid) {
    ids.push(self.getNodeByPid(pid).id);
  });
  return ids;

};

/**
 *
 * Get the entire node branch this node depends on
 *
 * @param {String} nodeId
 * @return {Array} nodes
 * @api public
 */
Actor.prototype.getAncestorNodes = function(nodeId) {
  var i;
  var nodes = [];
  var ids = this.getAncestorIds(nodeId);

  for (i = 0; i < ids.length; i++) {
    nodes.push(this.getNode(ids[i]));
  }

  return nodes;
};

/**
 *
 * Get all node ids that target this node.
 *
 * @param {String} nodeId
 * @return {Array} ids
 * @api public
 */
Actor.prototype.getSourceIds = function(nodeId) {

  var self = this;
  var ids = [];

  var pids = this.ioHandler.getSourcePids(
    this.getNode(nodeId).pid
  );

  pids.forEach(function(pid) {
    var node = self.getNodeByPid(pid);
    if (node) { // iips will not be found
      ids.push(node.id);
    }
  });
  return ids;

};

/**
 *
 * Get all nodes that target this node.
 *
 * @param {String} nodeId
 * @return {Array} nodes
 * @api public
 */
Actor.prototype.getSourceNodes = function(nodeId) {

  var i;
  var nodes = [];
  var ids = this.getSourceIds(nodeId);

  for (i = 0; i < ids.length; i++) {
    nodes.push(this.getNode(ids[i]));
  }

  return nodes;

};

/**
 *
 * Get all nodes that use this node as a source .
 *
 * @param {String} nodeId
 * @return {Array} ids
 * @api public
 */
Actor.prototype.getTargetIds = function(nodeId) {

  var self = this;

  var pids = this.ioHandler.getTargetPids(
    this.getNode(nodeId).pid
  );

  var ids = [];
  pids.forEach(function(pid) {
    ids.push(self.getNodeByPid(pid).id);
  });
  return ids;

};

/**
 *
 * Use is a generic way of creating a new instance of self
 * And only act upon a subset of our map.
 *
 *
 */
Actor.prototype.use = function(/*name, context*/) {

  throw Error('TODO: reimplement actions');
/*
  var i;
  var action;
  var map = {};
  var sub = new this.constructor();

  // Use this handlers events also on the action.
  sub._events = this._events;

  // Find our action
  if (!this.map.actions) {
    throw new Error('This flow has no actions');
  }

  if (!this.map.actions.hasOwnProperty(name)) {
    throw new Error('Action not found');
  }

  action = this.map.actions[name];

  // Create a reduced map
  map.env = this.map.env;
  map.title =  action.title;
  map.description = action.description;
  map.ports = this.map.ports;
  map.nodes = [];
  map.links = [];

  for (i = 0; i < this.map.nodes.length; i++) {
    if (action.nodes.indexOf(this.map.nodes[i].id) >= 0) {
      map.nodes.push(this.map.nodes[i]);
    }
  }

  for (i = 0; i < this.map.links.length; i++) {
    if (
      action.nodes.indexOf(this.map.links[i].source.id) >= 0 &&
      action.nodes.indexOf(this.map.links[i].target.id) >= 0) {
      map.links.push(this.map.links[i]);
    }
  }

  // re-use the loader
  sub.addLoader(this.loader);

  // add the nodes to our newly instantiated Actor
  sub.addMap(map);

  // hack to autostart it during run()
  // this only makes sense with actions.
  // TODO: doesn work anymore
  // sub.trigger = action.nodes[0];

  return sub;
*/

};

/**
 *
 * Run the current flow
 *
 * The flow starts by providing the ports with their context.
 *
 * Nodes which have all their ports filled by context will run immediatly.
 *
 * Others will wait until their unfilled ports are filled by connections.
 *
 * Internally the node will be set to a `contextGiven` state.
 * It's a method to tell the node we expect it to have enough
 * information to start running.
 *
 * If a port is not required and context was given and there are
 * no connections on it, it will not block the node from running.
 *
 * If a map has actions defined, run expects an action name to run.
 *
 * Combinations:
 *
 *   - run()
 *     run flow without callback
 *
 *   - run(callback)
 *     run with callback
 *
 *   - action('actionName').run()
 *     run action without callback
 *
 *   - action('actionName').run(callback)
 *     run action with callback
 *
 * The callback will receive the output of the (last) node(s)
 * Determined by which output ports are exposed.
 *
 * If we pass the exposed output, it can contain output from anywhere.
 *
 * If a callback is defined but there are no exposed output ports.
 * The callback will never fire.
 *
 * @api public
 */
Actor.prototype.run = function(callback) {

  return new Run(this, callback);

};
/**
 *
 * Need to do it like this, we want the new sub actor
 * to be returned to place events on etc.
 *
 * Otherwise it's hidden within the actor itself
 *
 * Usage: Actor.action('action').run(callback);
 *
 */
Actor.prototype.action = function(action, context) {

  var sub = this.use(action, context);
  return sub;

};

/**
 *
 * Get all nodes.
 *
 * TODO: unnecessary method
 *
 * @return {Object} nodes
 * @api public
 *
 */
Actor.prototype.getNodes = function() {

  return this.nodes;

};

/**
 *
 * Check if this node exists
 *
 * @param {String} id
 * @return {Object} node
 * @api public
 */
Actor.prototype.hasNode = function(id) {

  return this.nodes.hasOwnProperty(id);

};

/**
 *
 * Get a node by it's id.
 *
 * @param {String} id
 * @return {Object} node
 * @api public
 */
Actor.prototype.getNode = function(id) {

  if (this.nodes.hasOwnProperty(id)) {
    return this.nodes[id];
  } else {
    throw new Error(util.format('Node %s does not exist', id));
  }

};

/**
 *
 * JSON Status report about the nodes.
 *
 * Mainly meant to debug after shutdown.
 *
 * Should handle all stuff one can think of
 * why `it` doesn't work.
 *
 */
Actor.prototype.report = function() {

  var link;
  var node;
  var id;
  var size;
  var qm = this.ioHandler.queueManager;

  var report = {
    ok: true,
    flow: this.id,
    nodes: [],
    queues: []
  };

  for (id in this.nodes) {
    if (this.nodes.hasOwnProperty(id)) {
      node = this.nodes[id];
      if (node.status !== 'complete') {
        report.ok = false;
        report.nodes.push({
          node: node.report()
        });
      }
    }
  }

  for (id in this.links) {
    if (this.links.hasOwnProperty(id)) {
      link = this.links[id];
      if (qm.hasQueue(link.ioid)) {
        size = qm.size(link.ioid);
        report.ok = false;
        report.queues.push({
          link: link.toJSON(),
          port: link.target.port,
          // super weird, will be undefined if called here.
          // size: qm.size(link.ioid),
          size: size,
          node: this.getNode(link.target.id).report()
        });
      }
    }
  }

  return report;

};

/**
 *
 * If there are multiple connections to one port
 * the connections are numbered.
 *
 * If there is a index specified by using the
 * [] property, it will be considered.
 *
 * If it's not specified although there are
 * multiple connections to one port, it will be added.
 *
 * The sort takes care of adding connections where
 * [] is undefined to be placed last.
 *
 * The second loop makes sure they are correctly numbered.
 *
 * If connections are defined like:
 *
 *   undefined, [4],undefined, [3],[2]
 *
 * The corrected result will be:
 *
 * [2]        -> [0]
 * [3]        -> [1]
 * [4]        -> [2]
 * undefined  -> [3]
 * undefined  -> [4]
 *
 * Ports which only have one connection will be left unmodified.
 *
 */
Actor.prototype.ensureConnectionNumbering = function(map) {

  var c = 0;
  var i;
  var link;
  var last = {};
  var node;

  // first sort so order of appearance of
  // target.in is correct
  //
  // FIX: seems like multisort is messing up the array.
  // target suddenly has unknown input ports...
  if (map.links.length) {
    MultiSort(map.links, ['target', 'in', 'index']);
  }

  for (i = 0; i < map.links.length; i++) {

    link = map.links[i];

    // Weird, the full node is not build yet here?
    // so have to look at the nodeDefinitions ns and name _is_
    // known at this point.
    node = this.nodes[link.target.id];

    if (this.nodeDefinitions[node.ns][node.name]
      .ports.input[link.target.port].type === 'array') {

      if (last.target.id === link.target.id &&
        last.target.port === link.target.port) {
        last.index = c++;
        link.index = c;
      } else {
        c = 0; // reset
      }
      last = link;

    }
  }

};

Actor.prototype.hasParent = function() {
  return false;
};

module.exports = Actor;


text:
<!DOCTYPE html>

  <meta charset='UTF-8'>
  <title>CoffeeScript API Documentation</title>

  <link rel='stylesheet' href='../stylesheets/application.css' type='text/css'>

      Mongoose-plugins-created-by

    »

      Index

    »
    CoffeeMaker

        Class:
        CoffeeMaker

          Defined in:
          node_modules/codo/node_modules/haml-coffee/src/cli/coffee-maker.coffee

Class Method Summary

        .
(void)
compileFile(filename, compilerOptions = {}, namespace = null, templateName = null)

      Compiles a Haml-Coffee file to a JavaScript template.

        .
(void)
compile(source, templateName, namespace = null, compilerOptions = {})

      Compiles a Haml-Coffee file to a JavaScript template.

        .
(void)
renderFile(filename, compilerOptions = {})

        .
(void)
render(source, compilerOptions = {})

Class Method Details

      .
(void)
compileFile(filename, compilerOptions = {}, namespace = null, templateName = null)

Compiles a Haml-Coffee file to a JavaScript template.
When the output template is omitted, it will be derived from the file name.

Parameters:

      filename

        (<tt>String</tt>)

      —
      the Haml coffee file to compile

      compilerOptions

        (<tt>Object</tt>)

      —
      the compiler options

      namespace

        (<tt>String</tt>)

      —
      the template namespace

      templateName

        (<tt>String</tt>)

      —
      the name of the output template

      .
(void)
compile(source, templateName, namespace = null, compilerOptions = {})

Compiles a Haml-Coffee file to a JavaScript template.
When the output template is omitted, it will be derived from the file name.

Parameters:

      source

        (<tt>String</tt>)

      —
      the template source code

      templateName

        (<tt>String</tt>)

      —
      the name of the output template

      namespace

        (<tt>String</tt>)

      —
      the template namespace

      compilerOptions

        (<tt>Object</tt>)

      —
      the compiler options

      .
(void)
renderFile(filename, compilerOptions = {})

      .
(void)
render(source, compilerOptions = {})

  December 08, 13 09:52:41 by

    Codo

  2.0.2
  ✲
  Press H to see the keyboard shortcuts
  ✲
  @netzpirat
  ✲
  @_inossidabile
  ✲
  mksoft.ch

  <input type='text'>

    Quickly fuzzy find classes, mixins, methods, file:

      T
      Open fuzzy finder dialog

    Control the navigation frame:

      L
      Toggle list view

      C
      Show class list

      I
      Show mixin list

      F
      Show file list

      M
      Show method list

      E
      Show extras list

    You can focus and blur the search input:

      S
      Focus search input

      Esc
      Blur search input

redpajama_set_name: RedPajamaGithub


text:
namespace sandbox {

namespace {

using CreateProcessWFunction = decltype(&::CreateProcessW);

using CreateProcessAFunction = decltype(&::CreateProcessA);

using CreateThreadFunction = decltype(&::CreateThread);

using GetUserDefaultLCIDFunction = decltype(&::GetUserDefaultLCID);

}  // namespace

extern "C" {

// Interception of NtOpenThread on the child process.
SANDBOX_INTERCEPT NTSTATUS WINAPI
TargetNtOpenThread(NtOpenThreadFunction orig_OpenThread,
                   PHANDLE thread,
                   ACCESS_MASK desired_access,
                   POBJECT_ATTRIBUTES object_attributes,
                   PCLIENT_ID client_id);

// Interception of NtOpenProcess on the child process.
SANDBOX_INTERCEPT NTSTATUS WINAPI
TargetNtOpenProcess(NtOpenProcessFunction orig_OpenProcess,
                    PHANDLE process,
                    ACCESS_MASK desired_access,
                    POBJECT_ATTRIBUTES object_attributes,
                    PCLIENT_ID client_id);

// Interception of NtOpenProcessToken on the child process.
SANDBOX_INTERCEPT NTSTATUS WINAPI
TargetNtOpenProcessToken(NtOpenProcessTokenFunction orig_OpenProcessToken,
                         HANDLE process,
                         ACCESS_MASK desired_access,
                         PHANDLE token);

// Interception of NtOpenProcessTokenEx on the child process.
SANDBOX_INTERCEPT NTSTATUS WINAPI
TargetNtOpenProcessTokenEx(NtOpenProcessTokenExFunction orig_OpenProcessTokenEx,
                           HANDLE process,
                           ACCESS_MASK desired_access,
                           ULONG handle_attributes,
                           PHANDLE token);

// Interception of CreateProcessW and A in kernel32.dll.
SANDBOX_INTERCEPT BOOL WINAPI
TargetCreateProcessW(CreateProcessWFunction orig_CreateProcessW,
                     LPCWSTR application_name,
                     LPWSTR command_line,
                     LPSECURITY_ATTRIBUTES process_attributes,
                     LPSECURITY_ATTRIBUTES thread_attributes,
                     BOOL inherit_handles,
                     DWORD flags,
                     LPVOID environment,
                     LPCWSTR current_directory,
                     LPSTARTUPINFOW startup_info,
                     LPPROCESS_INFORMATION process_information);

SANDBOX_INTERCEPT BOOL WINAPI
TargetCreateProcessA(CreateProcessAFunction orig_CreateProcessA,
                     LPCSTR application_name,
                     LPSTR command_line,
                     LPSECURITY_ATTRIBUTES process_attributes,
                     LPSECURITY_ATTRIBUTES thread_attributes,
                     BOOL inherit_handles,
                     DWORD flags,
                     LPVOID environment,
                     LPCSTR current_directory,
                     LPSTARTUPINFOA startup_info,
                     LPPROCESS_INFORMATION process_information);

// Interception of CreateThread in kernel32.dll.
SANDBOX_INTERCEPT HANDLE WINAPI
TargetCreateThread(CreateThreadFunction orig_CreateThread,
                   LPSECURITY_ATTRIBUTES thread_attributes,
                   SIZE_T stack_size,
                   LPTHREAD_START_ROUTINE start_address,
                   LPVOID parameter,
                   DWORD creation_flags,
                   LPDWORD thread_id);

}  // extern "C"

}  // namespace sandbox

#endif  // SANDBOX_WIN_SRC_PROCESS_THREAD_INTERCEPTION_H_


text:
using System;
using System.Collections.Generic;

namespace Platform.Xml.Serialization
{
	public class TypeSerializerCache
	{
		private readonly TypeSerializerFactory typeSerializerFactory;
		private readonly Dictionary<Pair<Type, object>, TypeSerializer> cache;

		/// <summary>
		///
		/// </summary>
		/// <param name="typeSerializerFactory"></param>
		public TypeSerializerCache(TypeSerializerFactory typeSerializerFactory)
		{
			this.typeSerializerFactory = typeSerializerFactory;
			cache = new Dictionary<Pair<Type, object>, TypeSerializer>();
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="serializer"></param>
		public void Add(TypeSerializer serializer)
		{
			if (!serializer.MemberBound)
			{
				cache[new Pair<Type, object>(serializer.SupportedType, null)] = serializer;
			}
			else
			{
				throw new ArgumentException("Use TypeSerializerCache.Add(TypeSerializer, MemberInfo) with member bound serializers.");
			}
		}

		public virtual void Add(TypeSerializer serializer, object key)
		{
			cache[new Pair<Type, object>(serializer.SupportedType, key)] = serializer;
		}

		public virtual void Add(TypeSerializer serializer, SerializationMemberInfo memberInfo)
		{
			if (serializer.MemberBound)
			{
				Add(serializer, (object)memberInfo);
			}
			else
			{
				Add(serializer);
			}
		}

		public TypeSerializer GetTypeSerializerBySerializerType(Type type)
		{
			var serializer = this.typeSerializerFactory.NewTypeSerializerBySerializerType(type, this);

			Add(serializer);

			return serializer;
		}

		public TypeSerializer GetTypeSerializerBySerializerType(Type type, SerializationMemberInfo memberInfo)
		{
			var serializer = typeSerializerFactory.NewTypeSerializerBySerializerType(type, memberInfo, this);

			Add(serializer, memberInfo);

			return serializer;
		}

		public TypeSerializer GetTypeSerializerBySupportedType(Type type)
		{
			TypeSerializer serializer;

			if (cache.TryGetValue(new Pair<Type, object>(type, null), out serializer))
			{
				return serializer;
			}

			serializer = typeSerializerFactory.NewTypeSerializerBySupportedType(type, this);

			Add(serializer);

			return serializer;
		}

		public TypeSerializer GetTypeSerializerBySupportedType(Type type, SerializationMemberInfo memberInfo)
		{
			TypeSerializer serializer;

			if (cache.TryGetValue(new Pair<Type, object>(type, null), out serializer))
			{
				return serializer;
			}

			if (cache.TryGetValue(new Pair<Type, object>(type, memberInfo), out serializer))
			{
				return serializer;
			}

			serializer = typeSerializerFactory.NewTypeSerializerBySupportedType(type, memberInfo, this);

			Add(serializer, memberInfo);

			return serializer;
		}
	}
}


text:
use std::path::Path;

use crate::support::{database, project};

#[test]
fn setup_creates_database() {
    let p = project("setup_creates_database").build();
    let db = database(&p.database_url());

    // sanity check
    assert!(!db.exists());

    let result = p.command("setup").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(db.exists());
}

#[test]
fn setup_creates_migrations_directory() {
    let p = project("setup_creates_migrations_directory").build();

    // make sure the project builder doesn't create it for us
    assert!(!p.has_file("migrations"));

    let result = p.command("setup").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(p.has_file("migrations"));
}

#[test]
#[cfg(feature = "postgres")]
fn setup_initial_migration_returns_nothing_to_console() {
    let p = project("setup_initial_migration_returns_nothing_to_console").build();

    let result = p.command("setup").run();

    assert!(!result.stdout().contains("Running migration"));
}

#[test]
#[cfg(feature = "postgres")]
fn setup_creates_default_migration_file() {
    let p = project("setup_creates_default_migration_file").build();

    let result = p.command("setup").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(p.has_file(Path::new("migrations").join("00000000000000_diesel_initial_setup")));
}

#[test]
#[cfg(feature = "postgres")]
fn setup_creates_default_migration_file_if_project_is_otherwise_setup() {
    let p = project("setup_creates_default_migration_file_if_project_is_otherwise_setup").build();

    let initial_migration_path =
        Path::new("migrations").join("00000000000000_diesel_initial_setup");
    let result = p.command("setup").run();
    assert!(result.is_success(), "Result was unsuccessful {:?}", result);

    p.delete_file(&initial_migration_path);
    let result = p.command("setup").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(p.has_file(&initial_migration_path));
}

#[test]
fn setup_creates_schema_table() {
    let p = project("setup_creates_schema_table").build();
    let db = database(&p.database_url());
    let result = p.command("setup").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(db.table_exists("__diesel_schema_migrations"));
}

#[test]
fn setup_runs_migrations_if_no_schema_table() {
    let p = project("setup_runs_migrations_if_no_schema_table")
        .folder("migrations")
        .build();
    let db = database(&p.database_url());

    p.create_migration(
        "12345_create_users_table",
        "CREATE TABLE users ( id INTEGER )",
        Some("DROP TABLE users"),
    );

    // sanity check
    assert!(!db.exists());

    let result = p.command("setup").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(
        result.stdout().contains("Running migration 12345"),
        "Unexpected stdout {}",
        result.stdout()
    );
    assert!(db.table_exists("users"));
}

#[test]
fn setup_doesnt_run_migrations_if_schema_table_exists() {
    let p = project("setup_doesnt_run_migrations_if_schema_table_exists")
        .folder("migrations")
        .build();
    let db = database(&p.database_url()).create();
    db.execute("CREATE TABLE __diesel_schema_migrations ( version INTEGER )");

    p.create_migration(
        "12345_create_users_table",
        "CREATE TABLE users ( id INTEGER )",
        Some("DROP TABLE users"),
    );

    let result = p.command("setup").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(!db.table_exists("users"));
}

#[test]
fn setup_notifies_when_creating_a_database() {
    let p = project("setup_notifies").build();

    let result = p.command("setup").run();

    assert!(
        result.stdout().contains("Creating database:"),
        "Unexpected stdout {}",
        result.stdout()
    );
}

#[test]
#[allow(unused_variables)]
fn setup_doesnt_notify_when_not_creating_a_database() {
    let p = project("setup_doesnt_notify").build();
    let db = database(&p.database_url()).create();

    let result = p.command("setup").run();

    assert!(
        !result.stdout().contains("Creating database:"),
        "Unexpected stdout {}",
        result.stdout()
    );
}

#[test]
fn setup_works_with_migration_dir_by_arg() {
    let p = project("setup_works_with_migration_dir_by_arg").build();

    // make sure the project builder doesn't create it for us
    assert!(!p.has_file("migrations"));
    assert!(!p.has_file("foo"));

    let result = p.command("setup").arg("--migration-dir=foo").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(!p.has_file("migrations"));
    assert!(p.has_file("foo"));
}

#[test]
fn setup_works_with_migration_dir_by_env() {
    let p = project("setup_works_with_migration_dir_by_env").build();

    // make sure the project builder doesn't create it for us
    assert!(!p.has_file("migrations"));
    assert!(!p.has_file("bar"));

    let result = p.command("setup").env("MIGRATION_DIRECTORY", "bar").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(!p.has_file("migrations"));
    assert!(p.has_file("bar"));
}

#[test]
fn setup_creates_config_file() {
    let p = project("setup_creates_config_file").build();

    // Make sure the project builder didn't create the file
    assert!(!p.has_file("diesel.toml"));

    let result = p.command("setup").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(p.has_file("diesel.toml"));
    assert!(p
        .file_contents("diesel.toml")
        .contains("diesel.rs/guides/configuring-diesel-cli"));
}

#[test]
fn setup_can_take_config_file_by_env() {
    let p = project("setup_can_take_config_file_by_env").build();

    // Make sure the project builder didn't create the file
    assert!(!p.has_file("diesel.toml"));
    assert!(!p.has_file("foo"));

    let result = p.command("setup").env("DIESEL_CONFIG_FILE", "foo").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(!p.has_file("diesel.toml"));
    assert!(p.has_file("foo"));
    assert!(p
        .file_contents("foo")
        .contains("diesel.rs/guides/configuring-diesel-cli"));
}

#[test]
fn setup_can_take_config_file_by_param() {
    let p = project("setup_can_take_config_file_by_param").build();

    // Make sure the project builder didn't create the file
    assert!(!p.has_file("diesel.toml"));
    assert!(!p.has_file("foo"));
    assert!(!p.has_file("bar"));

    let result = p
        .command("setup")
        .env("DIESEL_CONFIG_FILE", "foo")
        .arg("--config-file=bar")
        .run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(!p.has_file("diesel.toml"));
    assert!(!p.has_file("foo"));
    assert!(p.has_file("bar"));
    assert!(p
        .file_contents("bar")
        .contains("diesel.rs/guides/configuring-diesel-cli"));
}

#[test]
fn setup_respects_migrations_dir_from_diesel_toml() {
    let p = project("setup_respects_migration_dir_from_diesel_toml")
        .file(
            "diesel.toml",
            r#"
            [migrations_directory]
            dir = "custom_migrations"
            "#,
        )
        .build();

    assert!(!p.has_file("custom_migrations"));

    let result = p.command("setup").run();

    assert!(result.is_success(), "Result was unsuccessful {:?}", result);
    assert!(p.has_file("custom_migrations"));
}


text:
package io.quarkus.jaxrs.client.reactive.runtime;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.function.Supplier;

public class ParameterAnnotationsSupplier implements Supplier<Annotation[][]> {

    private final Method method;
    private volatile Annotation[][] value;

    public ParameterAnnotationsSupplier(Method method) {
        this.method = method;
    }

    @Override
    public Annotation[][] get() {
        if (value == null) {
            value = method.getParameterAnnotations();
        }
        return value;
    }
}


text:
<?php
/**
 * Automatically generated
 *
 * @author: Viskov Sergey
 * @date: 07.05.15
 */

namespace LTDBeget\apacheConfigurator\directives\available;

use LTDBeget\apacheConfigurator\ConfigurationFile;
use LTDBeget\apacheConfigurator\directives\Directive;

class LanguagePriority extends Directive
{
    /**
     * Return link to full description of apache directive
     * @return String
     */
    public static function getApacheDocLink()
    {
        return Directive::$apacheSite."/docs/2.4/mod/mod_negotiation.html#languagepriority";
    }

    /**
     * the source module which defines the directive
     * @return String
     */
    public static function getModule()
    {
        return "mod_negotiation";
    }

    /**
     * Return text description of apache directive
     * @return String
     */
    public static function getDescription()
    {
        return "The precendence of language variants for cases where the client does not express a preference";
    }

    /**
     * Return Apache directive Syntax
     * @return String
     */
    public static function getSyntax()
    {
        return 'LanguagePriority MIME-lang [MIME-lang] ...';
    }

    /**
     * is this directive can include inner directives
     * @return boolean
     */
    public function isSection()
    {
        return false;
    }

    /**
     * Set allowed context of concrete directive
     */
    protected function setAllowedContext()
    {
        $this->allowedContext = [
            ConfigurationFile::SERVER_CONFIG,
            VirtualHost::getFullName(),
            Directory::getFullName(),
            ConfigurationFile::HTACCESS,
        ];
    }

}


text:
package com.cloudera.spark.cloud.s3

import com.cloudera.spark.cloud.common.DataFrameTests
import com.cloudera.spark.cloud.operations.CloudDataFrames

/**
 * Test the [S3DataFrames] logic.
 */
class S3ADataFrameSuite extends DataFrameTests with S3ATestSetup {

  init()

  def init(): Unit = {
    // propagate S3 credentials
    if (enabled) {
      initFS()
    }
  }

  override protected val instance: CloudDataFrames = S3ADataFrames

}


text:
package aws

import (
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ses"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsSesDomainDkim() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsSesDomainDkimCreate,
		Read:   resourceAwsSesDomainDkimRead,
		Delete: resourceAwsSesDomainDkimDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"domain": {
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},
			"dkim_tokens": {
				Type:     schema.TypeList,
				Computed: true,
				Elem:     &schema.Schema{Type: schema.TypeString},
			},
		},
	}
}

func resourceAwsSesDomainDkimCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).sesConn

	domainName := d.Get("domain").(string)

	createOpts := &ses.VerifyDomainDkimInput{
		Domain: aws.String(domainName),
	}

	_, err := conn.VerifyDomainDkim(createOpts)
	if err != nil {
		return fmt.Errorf("Error requesting SES domain identity verification: %s", err)
	}

	d.SetId(domainName)

	return resourceAwsSesDomainDkimRead(d, meta)
}

func resourceAwsSesDomainDkimRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).sesConn

	domainName := d.Id()
	d.Set("domain", domainName)

	readOpts := &ses.GetIdentityDkimAttributesInput{
		Identities: []*string{
			aws.String(domainName),
		},
	}

	response, err := conn.GetIdentityDkimAttributes(readOpts)
	if err != nil {
		log.Printf("[WARN] Error fetching identity verification attributes for %s: %s", d.Id(), err)
		return err
	}

	verificationAttrs, ok := response.DkimAttributes[domainName]
	if !ok {
		log.Printf("[WARN] Domain not listed in response when fetching verification attributes for %s", d.Id())
		d.SetId("")
		return nil
	}

	d.Set("dkim_tokens", aws.StringValueSlice(verificationAttrs.DkimTokens))
	return nil
}

func resourceAwsSesDomainDkimDelete(d *schema.ResourceData, meta interface{}) error {

	return nil
}


text:
package com.opengamma.security.user;

/**
 * A permission granted to users.
 *

 * Permissions can include viewing a portfolio or a class of portfolios, modifying a portfolio,
 * viewing market data, etc.
 *

 * Permissions can be regular expressions, for example /MarketData/Bloomberg/*/View, which would
 * grant its holders the right to view any Bloomberg market data. See {@link PathMatcher}.
 *

 * Note that Authorities are technically granted to {@link UserGroup}. Each
 * {@link User} belongs to a number of UserGroups. This reduces the need to modify individual
 * permissions when users move within a company.
 */
public class Authority {

  /**
   * The database id.
   */
  private Long _id;

  /**
   * A regular expression in Ant format
   **/
  private String _regex;

  /**
   * Creates an instance of an authority.
   * @param id  the database id
   * @param regex  the regex
   */
  public Authority(final Long id, final String regex) {
    _id = id;
    _regex = regex;
  }

  /**
   * Creates an instance of an authority.
   * @param regex  the regex
   */
  public Authority(final String regex) {
    this(null, regex);
  }

  /**
   * Restricted constructor for tools.
   */
  protected Authority() {
  }

  //-------------------------------------------------------------------------
  /**
   * Gets the database id.
   *
   * @return  the id
   */
  public Long getId() {
    return _id;
  }

  /**
   * Sets the database id.
   *
   * @param id  the id
   */
  public void setId(final Long id) {
    _id = id;
  }

  /**
   * Gets the matcher regex.
   *
   * @return  the regex
   */
  public String getRegex() {
    return _regex;
  }

  /**
   * Sets the matcher regex.
   *
   * @param regex  the regex
   */
  public void setRegex(final String regex) {
    this._regex = regex;
  }

  //-------------------------------------------------------------------------
  /**
   * Returns whether this Authority can be used to grant the requested permission.
   *
   * @param requestedPermission The requested permission, for example /MarketData/Bloomberg/AAPL/View
   * @return Whether the regular expression pattern stored in this Authority,
   * for example /MarketData/Bloomberg/*/View, matches the requested permission
   */
  public boolean matches(final String requestedPermission) {
    return PathMatcher.matches(requestedPermission, _regex);
  }

  //-------------------------------------------------------------------------
  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final Authority other = (Authority) obj;
    if (_id == null) {
      if (other._id != null) {
        return false;
      }
    } else if (!_id.equals(other._id)) {
      return false;
    }
    return true;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (_id == null ? 0 : _id.hashCode());
    return result;
  }

  @Override
  public String toString() {
    return _regex;
  }

}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="unify">
        <note>
            Frames file for 'unify' based on sentences in wsj.  Verbnet entry
            22.2, Framenet entry Amalgamate.
        </note>

        <roleset id="unify.01" name="join together" vncls="22.2">
            <roles>
                <role descr="joiner, agent" n="0">
                    <vnrole vncls="22.2" vntheta="Agent"/>
                </role>
                <role descr="(first) thing(s) being unified" n="1">
                    <vnrole vncls="22.2" vntheta="Patient1"/>
                </role>
                <role descr="other things, if separate from arg1" n="2">
                    <vnrole vncls="22.2" vntheta="Patient2"/>
                </role>
                <role descr="unified whole" n="3"/>
            </roles>

            <example name="simple transitive">
                <inflection aspect="ns" form="infinitive" person="ns" tense="ns" voice="ns"/>
                <text>
                    Arguing that the separate financial marketplaces acted as one,
                    and concluding that the crash had ``raised the possibility of a
                    full-scale financial system breakdown,'' the presidential task
                    force called for establishing [a super-regulator]-1 to oversee the
                    markets, to make margins consistent across markets, *trace*-1 to
                    unify clearing systems and to install circuit breakers.
                </text>
                <arg n="0">*trace*</arg>
                <rel>unify</rel>
                <arg n="1">clearing systems</arg>
            </example>

            <example name="separate things">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    John unified his sense of fair play with Mary's violent tendencies.
                </text>
                <arg n="0">John</arg>
                <rel>unified</rel>
                <arg n="1">his sense of fair play</arg>
                <arg n="2">with Mary's violent tendencies</arg>
            </example>

            <example name="pieces and whole">
                <inflection aspect="ns" form="participle" person="ns" tense="past" voice="passive"/>
                <text>
                    [John's sense of fair play and Mary's violent tendencies]-1 were
                    unified *trace*-1 into a very unhealthy living situation.
                </text>
                <rel>unified</rel>
                <arg n="1">*trace*</arg>
                <arg n="3">into a very unhealthy living situation</arg>
            </example>

            <example name="adjectival">
                <inflection aspect="ns" form="participle" person="ns" tense="ns" voice="passive"/>
                <text>
                    That's why ``we have been working hard to develop a single, more
                    unified presence in Europe,'' said A.J.C. Smith, Marsh &
                    McLennan's president, at a London news conference yesterday.
                </text>
                <arg f="EXT" n="M">more</arg>
                <rel>unified</rel>
                <arg n="1">presence</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>


text:
package org.slc.sli.ingestion.processors;

import java.util.Map;

import org.springframework.core.io.Resource;

/**
 *
 * Utility class which provides an XSD Resource from an XML IngestionFileEntry.
 *
 * @author tshewchuk
 *
 */
public class XsdSelector {

    private Map<String, Resource> xsdList;

    /**
    * Provides an XSD Resource from an XML IngestionFileEntry.

    * @param xmlFile
    *        IngestionFileEntry representing the XML file.
    *
    * @return Resource
    *         Resource representing the XSD file schema for the XML file,
    *         or null if no matching schema can be found.
    */
    public Resource provideXsdResource(String fileName) {
        Resource xsdResource = xsdList.get(fileName);
        return xsdResource;
    }

    public Map<String, Resource> getXsdList() {
        return xsdList;
    }

    public void setXsdList(Map<String, Resource> xsdList) {
        this.xsdList = xsdList;
    }

}


text:
<?php

use Timekit\Performance\Http\Middleware\PerformanceTracking;
use Timekit\Performance\QueryContainer;

class MiddlewareTest extends PHPUnit_Framework_TestCase
{

    /**
    * @test
    * @group new
    *
    */
    public function the_query_is_saved_at_termination()
    {
        // Given
        $mock = Mockery::mock(QueryContainer::class);
        $mock->shouldReceive('save');

        $middleware = new PerformanceTracking($mock);

        // When
        $middleware->terminate(null, null);

        // Then
        $mock->shouldHaveReceived('save')->once();
        $this->assertTrue(true);
    }

    /**
     * @test
     * @group new
     *
     */
    public function the_handle_method_does_not_break_anything()
    {
        // Given
        $mock = Mockery::mock(QueryContainer::class);
        $middleware = new PerformanceTracking($mock);

        // When
        $output = $middleware->handle(null, function($request){
            return true;
        });

        // Then
        $this->assertTrue($output);
    }
}


text:
package org.basex.util;

import static org.basex.util.Token.*;
import static org.junit.Assert.*;

import org.junit.*;

/**
 * EXPath package API: Version tests.
 *
 * @author BaseX Team 2005-16, BSD License
 * @author Rositsa Shadura
 */
public final class VersionTest {
  /**
   * Tests method isCompatible.
   */
  @Test
  public void compatible() {
    // case 1: template = 3
    final Version semVer1 = new Version(token("3"));
    assertTrue(new Version(token("3.0")).isCompatible(semVer1));
    assertTrue(new Version(token("3.1")).isCompatible(semVer1));
    assertTrue(new Version(token("3.9")).isCompatible(semVer1));
    assertTrue(new Version(token("3.2.4")).isCompatible(semVer1));
    assertTrue(new Version(token("3.9.89")).isCompatible(semVer1));
    assertFalse(new Version(token("4")).isCompatible(semVer1));
    assertFalse(new Version(token("2.7.4")).isCompatible(semVer1));

    // case 2: template = 3.5
    final Version semVer2 = new Version(token("3.5"));
    assertTrue(new Version(token("3.5")).isCompatible(semVer2));
    assertTrue(new Version(token("3.5.45")).isCompatible(semVer2));
    assertFalse(new Version(token("3.6")).isCompatible(semVer2));
    assertFalse(new Version(token("2.7.4")).isCompatible(semVer2));
    assertFalse(new Version(token("3.4")).isCompatible(semVer2));

    // case 3: template = 3.4.7
    final Version semVer3 = new Version(token("3.4.7"));
    assertTrue(new Version(token("3.4.7")).isCompatible(semVer3));
    assertFalse(new Version(token("3.4")).isCompatible(semVer3));
    assertFalse(new Version(token("3.4.8")).isCompatible(semVer3));
    assertFalse(new Version(token("3")).isCompatible(semVer3));
  }

  /**
   * Tests comparison between version, which is compatible to and greater than a
   * given version template.
   */
  @Test
  public void compatGreater() {
    // case 1: template = 3
    final Version semVer1 = new Version(token("3"));
    final Version v1 = new Version(token("3"));
    assertTrue(v1.isCompatible(semVer1) || v1.compareTo(semVer1) > 0);
    final Version v2 = new Version(token("3.4"));
    assertTrue(v2.isCompatible(semVer1) || v2.compareTo(semVer1) > 0);
    final Version v3 = new Version(token("3.4.55"));
    assertTrue(v3.isCompatible(semVer1) || v3.compareTo(semVer1) > 0);
    final Version v4 = new Version(token("2.6"));
    assertFalse(v4.isCompatible(semVer1) || v4.compareTo(semVer1) > 0);

    // case 2: template = 3.5
    final Version semVer2 = new Version(token("3.5"));
    final Version vv1 = new Version(token("3.5"));
    assertTrue(vv1.isCompatible(semVer2) || vv1.compareTo(semVer2) > 0);
    final Version vv2 = new Version(token("3.5.6"));
    assertTrue(vv2.isCompatible(semVer2) || vv2.compareTo(semVer2) > 0);
    final Version vv3 = new Version(token("9"));
    assertTrue(vv3.isCompatible(semVer2) || vv3.compareTo(semVer2) > 0);
    final Version vv4 = new Version(token("3.4"));
    assertFalse(vv4.isCompatible(semVer2) || vv4.compareTo(semVer2) > 0);
    final Version vv5 = new Version(token("3.6"));
    assertTrue(vv5.isCompatible(semVer2) || vv5.compareTo(semVer2) > 0);

    // case 3: template = 3.4.7
    final Version semVer3 = new Version(token("3.4.7"));
    final Version vvv1 = new Version(token("3.4.7"));
    assertTrue(vvv1.isCompatible(semVer3) || vvv1.compareTo(semVer3) > 0);
    final Version vvv2 = new Version(token("3.4.77"));
    assertTrue(vvv2.isCompatible(semVer3) || vvv2.compareTo(semVer3) > 0);
    final Version vvv3 = new Version(token("3.6"));
    assertTrue(vvv3.isCompatible(semVer3) || vvv3.compareTo(semVer3) > 0);
    final Version vvv4 = new Version(token("101"));
    assertTrue(vvv4.isCompatible(semVer3) || vvv4.compareTo(semVer3) > 0);
    final Version vvv5 = new Version(token("3.4"));
    assertFalse(vvv5.isCompatible(semVer3) || vvv5.compareTo(semVer3) > 0);
    final Version vvv6 = new Version(token("3.4.0"));
    assertFalse(vvv6.isCompatible(semVer3) || vvv6.compareTo(semVer3) > 0);
    final Version vvv7 = new Version(token("3.2"));
    assertFalse(vvv7.isCompatible(semVer3) || vvv7.compareTo(semVer3) > 0);
    final Version vvv8 = new Version(token("1.0"));
    assertFalse(vvv8.isCompatible(semVer3) || vvv8.compareTo(semVer3) > 0);
  }

  /**
   * Tests comparison between version, which is compatible to and smaller than a
   * given version template.
   */
  @Test
  public void compatSmaller() {
    // case 1: template = 3
    final Version semVer1 = new Version(token("3"));
    final Version v1 = new Version(token("3"));
    assertTrue(v1.isCompatible(semVer1) || v1.compareTo(semVer1) < 0);
    final Version v2 = new Version(token("2.4"));
    assertTrue(v2.isCompatible(semVer1) || v2.compareTo(semVer1) < 0);
    final Version v3 = new Version(token("2"));
    assertTrue(v3.isCompatible(semVer1) || v3.compareTo(semVer1) < 0);
    final Version v4 = new Version(token("4.6.55"));
    assertFalse(v4.isCompatible(semVer1) || v4.compareTo(semVer1) < 0);

    // case 2: template = 3.5
    final Version semVer2 = new Version(token("3.5"));
    final Version vv1 = new Version(token("3.5"));
    assertTrue(vv1.isCompatible(semVer2) || vv1.compareTo(semVer2) < 0);
    final Version vv2 = new Version(token("3.5.0"));
    assertTrue(vv2.isCompatible(semVer2) || vv2.compareTo(semVer2) < 0);
    final Version vv3 = new Version(token("2"));
    assertTrue(vv3.isCompatible(semVer2) || vv3.compareTo(semVer2) < 0);
    final Version vv4 = new Version(token("3.6"));
    assertFalse(vv4.isCompatible(semVer2) || vv4.compareTo(semVer2) < 0);
    final Version vv5 = new Version(token("3.4.66"));
    assertTrue(vv5.isCompatible(semVer2) || vv5.compareTo(semVer2) < 0);
    final Version vv6 = new Version(token("6"));
    assertFalse(vv6.isCompatible(semVer2) || vv6.compareTo(semVer2) < 0);

    // case 3: template = 3.4.7
    final Version semVer3 = new Version(token("3.4.7"));
    final Version vvv1 = new Version(token("3.4.7"));
    assertTrue(vvv1.isCompatible(semVer3) || vvv1.compareTo(semVer3) < 0);
    final Version vvv2 = new Version(token("3.4.6"));
    assertTrue(vvv2.isCompatible(semVer3) || vvv2.compareTo(semVer3) < 0);
    final Version vvv3 = new Version(token("3.3"));
    assertTrue(vvv3.isCompatible(semVer3) || vvv3.compareTo(semVer3) < 0);
    final Version vvv4 = new Version(token("1"));
    assertTrue(vvv4.isCompatible(semVer3) || vvv4.compareTo(semVer3) < 0);
    final Version vvv5 = new Version(token("3.4.8"));
    assertFalse(vvv5.isCompatible(semVer3) || vvv5.compareTo(semVer3) < 0);
    final Version vvv6 = new Version(token("3.5.0"));
    assertFalse(vvv6.isCompatible(semVer3) || vvv6.compareTo(semVer3) < 0);
    final Version vvv8 = new Version(token("3.4.0"));
    assertTrue(vvv8.isCompatible(semVer3) || vvv8.compareTo(semVer3) < 0);
  }

  /**
   * Tests if a version is in a given interval.
   */
  @Test
  public void interval() {
    final Version semVerMin1 = new Version(token("3"));
    final Version semVerMax1 = new Version(token("7"));
    final Version test1 = new Version(token("3.0"));
    assertTrue(test1.compareTo(semVerMin1) > 0
        && test1.compareTo(semVerMax1) < 0);
    final Version test2 = new Version(token("3.5"));
    assertTrue(test2.compareTo(semVerMin1) > 0
        && test2.compareTo(semVerMax1) < 0);
    final Version test3 = new Version(token("6.9"));
    assertTrue(test3.compareTo(semVerMin1) > 0
        && test3.compareTo(semVerMax1) < 0);
    final Version test4 = new Version(token("7.0"));
    assertFalse(test4.compareTo(semVerMin1) > 0
        && test4.compareTo(semVerMax1) < 0);
    final Version test5 = new Version(token("7.6.0"));
    assertFalse(test5.compareTo(semVerMin1) > 0
        && test5.compareTo(semVerMax1) < 0);
    final Version test6 = new Version(token("2.0"));
    assertFalse(test6.compareTo(semVerMin1) > 0
        && test6.compareTo(semVerMax1) < 0);
  }

}


text:
#include "AppClass.h"
void AppClass::ProcessKeyboard(void)
{
	bool bModifier = false;
	float fSpeed = 0.2f;

#pragma region ON PRESS/RELEASE DEFINITION
	static bool	bLastF1 = false, bLastF2 = false, bLastF3 = false, bLastF4 = false, bLastF5 = false,
				bLastF6 = false, bLastF7 = false, bLastF8 = false, bLastF9 = false, bLastF10 = false,
				bLastEscape = false, bLastF = false, bLastSpace = false, bLastC = false;
#define ON_KEY_PRESS_RELEASE(key, pressed_action, released_action){  \
			bool pressed = sf::Keyboard::isKeyPressed(sf::Keyboard::key);			\
			if(pressed){											\
				if(!bLast##key) pressed_action;}/*Just pressed? */\
			else if(bLast##key) released_action;/*Just released?*/\
			bLast##key = pressed; } //remember the state
#pragma endregion

#pragma region Modifiers
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::LShift) || sf::Keyboard::isKeyPressed(sf::Keyboard::RShift))
		bModifier = true;
#pragma endregion

#pragma region Camera Positioning
	if(bModifier)
		fSpeed *= 10.0f;
	if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
		m_pCameraMngr->MoveForward(fSpeed);

	if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
		m_pCameraMngr->MoveForward(-fSpeed);

	if(sf::Keyboard::isKeyPressed(sf::Keyboard::A))
		m_pCameraMngr->MoveSideways(-fSpeed);

	if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
		m_pCameraMngr->MoveSideways(fSpeed);

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q))
		m_pCameraMngr->MoveVertical(-fSpeed);

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
		m_pCameraMngr->MoveVertical(fSpeed);

	//Alternative rot controls
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::I)) //pitch up
	{
		m_pCameraMngr->ChangePitch(fSpeed *50.0f);
	}
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::K)) //pitch down
	{
		m_pCameraMngr->ChangePitch(fSpeed * -50.0f);
	}
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::J)) //yaw left
	{
		m_pCameraMngr->ChangeYaw(fSpeed * 50.0f);
	}
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::L)) //yaw right
	{
		m_pCameraMngr->ChangeYaw(fSpeed * -50.0f);
	}
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::U)) //roll left
	{
		m_pCameraMngr->ChangeRoll(fSpeed * 50.0f);
	}
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::O)) //roll right
	{
		m_pCameraMngr->ChangeRoll(fSpeed * -50.0f);
	}
#pragma endregion

#pragma region Creeper Control
	if (bModifier)
		fSpeed *= 10.0f;
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
		m_v3PosPokeCube.x -= 0.1f;

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
		m_v3PosPokeCube.x += 0.1f;

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
		m_v3PosPokeCube.y -= 0.1f;

	if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
		m_v3PosPokeCube.y += 0.1f;
#pragma endregion

#pragma region A10 actions
	//disable for new BOManager... would have to reimplement acordingly
	//....
	//toggle bounding box visibility
	/*if (sf::Keyboard::isKeyPressed(sf::Keyboard::B)){

		//toggle off
		if (m_pBndObjMngr->boVisible){
			m_pBndObjMngr->SetBOVisible("Steve", false);
			m_pBndObjMngr->SetBOVisible("Creeper", false);
		}

		//toggle on
		else if (!(m_pBndObjMngr->boVisible)){
			m_pBndObjMngr->SetBOVisible("Steve", true);
			m_pBndObjMngr->SetBOVisible("Creeper", true);
		}
	}

	//toggle bounding box visibility
	if (sf::Keyboard::isKeyPressed(sf::Keyboard::V)){

		//toggle off
		if (m_pBndObjMngr->aabbVisible){
			m_pBndObjMngr->SetAABBVisible(false);
			m_pBndObjMngr->SetAABBVisible(false);
		}

		//toggle on
		else if (!(m_pBndObjMngr->aabbVisible)){
			m_pBndObjMngr->SetAABBVisible( true);
			m_pBndObjMngr->SetAABBVisible( true);
		}
	}*/
#pragma endregion

#pragma region Other Actions
	ON_KEY_PRESS_RELEASE(Escape, NULL, PostMessage(m_pWindow->GetHandler(), WM_QUIT, NULL, NULL));
	ON_KEY_PRESS_RELEASE(F1, NULL, m_pCameraMngr->SetCameraMode(CAMPERSP));
	ON_KEY_PRESS_RELEASE(F2, NULL, m_pCameraMngr->SetCameraMode(CAMROTHOZ));
	ON_KEY_PRESS_RELEASE(F3, NULL, m_pCameraMngr->SetCameraMode(CAMROTHOY));
	ON_KEY_PRESS_RELEASE(F4, NULL, m_pCameraMngr->SetCameraMode(CAMROTHOX));
	static bool bFPSControll = false;
	ON_KEY_PRESS_RELEASE(F, bFPSControll = !bFPSControll, m_pCameraMngr->SetFPS(bFPSControll));

	ON_KEY_PRESS_RELEASE(Space, ThrowPokecube(), NULL);
	ON_KEY_PRESS_RELEASE(C, ToggleCamera(), NULL);
#pragma endregion
}
void AppClass::ProcessMouse(void)
{
	m_bArcBall = false;
	m_bFPC = false;

	if(sf::Mouse::isButtonPressed(sf::Mouse::Button::Middle))
		m_bArcBall = true;

	if(sf::Mouse::isButtonPressed(sf::Mouse::Button::Right))
		m_bFPC = true;
}


text:
.. _api:

Basic API
=========

The basic API included the application framework and routing system (provided
by :mod:`werkzeug.routing`) of Brownant.

brownant.app
------------

.. autoclass:: brownant.app.Brownant
   :members:
   :inherited-members:

.. autofunction:: brownant.app.redirect

brownant.request
----------------

.. autoclass:: brownant.request.Request
   :members:
   :inherited-members:

brownant.site
-------------

.. autoclass:: brownant.site.Site
   :members:
   :inherited-members:

brownant.exceptions
-------------------

.. autoexception:: brownant.exceptions.BrownantException

.. autoexception:: brownant.exceptions.NotSupported
   :show-inheritance:

brownant.utils
--------------

.. autofunction:: brownant.utils.to_bytes_safe

Declarative API
===============

The declarative API is around the "dinergate" and "pipeline property".

brownant.dinergate
------------------

.. autoclass:: brownant.dinergate.Dinergate
   :members:
   :inherited-members:

.. autoclass:: brownant.dinergate.DinergateType
   :show-inheritance:

brownant.pipeline.base
----------------------

.. autoclass:: brownant.pipeline.base.PipelineProperty
   :members:
   :inherited-members:
   :show-inheritance:

   .. method:: provide_value(obj)

      The abstruct method which should be implemented by subclasses. It provide
      the value expected by us from the subject instance.

      :param obj: the subject instance.
      :type obj: :class:`~brownant.dinergate.Dinergate`

brownant.pipeline.network
-------------------------

.. autoclass:: brownant.pipeline.network.URLQueryProperty
   :members:

.. autoclass:: brownant.pipeline.network.TextResponseProperty
   :members:

brownant.pipeline.html
----------------------

.. autoclass:: brownant.pipeline.html.ElementTreeProperty
   :members:

.. autoclass:: brownant.pipeline.html.XPathTextProperty
   :members:


text:
package client

import (
	"fmt"
)

// GetUserWorkHistoryHyUserWorkHistoryPath returns the URL path to the hy_userWorkHistory service getUserWorkHistory HTTP endpoint.
func GetUserWorkHistoryHyUserWorkHistoryPath(userID int) string {
	return fmt.Sprintf("/api/user/%v/workhistory", userID)
}


text:
STRING_COLUMNS_COUNT = 25

def db_adapter
  ENV['DATABASE_URL'].split(":")[0]
end

def db_setup(script:)
  Dir.chdir("../../support/setup") do
    `DATABASE_URL=#{ENV.fetch("DATABASE_URL")} BUNDLE_GEMFILE=Gemfile ruby #{script}`
  end
end


text:
layout: page
title: "JavaScript bcround function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/bcround:873
- /functions/view/bcround
- /functions/view/873
- /functions/bcround:873
- /functions/873
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's bcround

{% codeblock bc/bcround.js lang:js https://raw.github.com/kvz/phpjs/master/functions/bc/bcround.js raw on github %}
function bcround (val, precision) {
  // http://kevin.vanzonneveld.net
  // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
  // -    depends on: _phpjs_shared_bc
  // *     example 1: bcround(1, 2);
  // *     returns 1: 3
  //  @todo: implement these testcases
  //        bcscale(0);
  //
  //        bcmath.test.result('bcround', 1, '-2', bcround('-1.5', 0));
  //        bcmath.test.result('bcround', 2, '-1.1235', bcround('-1.1234567', 4));
  //        bcmath.test.result('bcround', 3, '2', bcround('1.5', 0));
  //        bcmath.test.result('bcround', 4, '1.1235', bcround('1.1234567', 4));
  //        bcmath.test.result('bcround', 5, '1', bcround('1.499999999', 0));
  //        bcmath.test.result('bcround', 6, '2', bcround('1.5555555555555555555', 0));
  //        bcmath.test.result('bcround', 7, '1.44', bcround('1.444999', 2));
  //        bcmath.test.result('bcround', 8, '-1.44', bcround('-1.444999', 2));
  var libbcmath = this._phpjs_shared_bc();

  var temp, result, digit;
  var right_operand;

  // create number
  temp = libbcmath.bc_init_num();
  temp = libbcmath.php_str2num(val.toString());

  // check if any rounding needs
  if (precision >= temp.n_scale) {
    // nothing to round, just add the zeros.
    while (temp.n_scale < precision) {
      temp.n_value[temp.n_len + temp.n_scale] = 0;
      temp.n_scale++;
    }
    return temp.toString();
  }

  // get the digit we are checking (1 after the precision)
  // loop through digits after the precision marker
  digit = temp.n_value[temp.n_len + precision];

  right_operand = libbcmath.bc_init_num();
  right_operand = libbcmath.bc_new_num(1, precision);

  if (digit >= 5) {
    //round away from zero by adding 1 (or -1) at the "precision".. ie 1.44999 @ 3dp = (1.44999 + 0.001).toString().substr(0,5)
    right_operand.n_value[right_operand.n_len + right_operand.n_scale - 1] = 1;
    if (temp.n_sign == libbcmath.MINUS) {
      // round down
      right_operand.n_sign = libbcmath.MINUS;
    }
    result = libbcmath.bc_add(temp, right_operand, precision);
  } else {
    // leave-as-is.. just truncate it.
    result = temp;
  }

  if (result.n_scale > precision) {
    result.n_scale = precision;
  }
  return result.toString();
}
{% endcodeblock %}

 - [view on github](https://github.com/kvz/phpjs/blob/master/functions/bc/bcround.js)
 - [edit on github](https://github.com/kvz/phpjs/edit/master/functions/bc/bcround.js)

### Example 1
This code
{% codeblock lang:js example %}
bcround(1, 2);
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
3
{% endcodeblock %}

### Other PHP functions in the bc extension
{% render_partial _includes/custom/bc.html %}


text:
package nl.infcomtec.jparticle;

import java.util.Date;
import java.util.TreeMap;
import org.json.JSONObject;

/**
 *
 * @author walter
 */
public class Event {

    public String deviceName="?";
    final public String eventName;
    final public String coreId;
    final public String data;
    final public Date publishedAt;
    final public long ttl;

    public Event(final TreeMap<String, Device> devices, final String eventName, final JSONObject jo) {
        this.eventName = eventName;
        this.coreId = jo.getString("coreid");
        for (Device d : devices.values()) {
            if (d.id.equals(coreId)) {
                this.deviceName = d.name;
                break;
            }
        }
        this.data = jo.getString("data");
        this.publishedAt = Cloud.parseDateTime(jo.getString("published_at"));
        long _ttl = jo.getLong("ttl") * 1000L;
        this.ttl = Math.min(60000L, _ttl);
    }

    public Date expires() {
        return new Date(publishedAt.getTime() + ttl);
    }

    @Override
    public String toString() {
        return "Event{" + "deviceName=" + deviceName + ", eventName=" + eventName + ", coreId=" + coreId + ", data=" + data + ", publishedAt=" + publishedAt + ", ttl=" + ttl + '}';
    }

}


text:
class CalculateAgriculturalHolidayEntitlementFlow < SmartAnswer::Flow
  def define
    content_id "8834bc7c-7ac7-4d45-8a57-1d5a5dcd70a0"
    name "calculate-agricultural-holiday-entitlement"
    status :published

    radio :work_the_same_number_of_days_each_week? do
      option "same-number-of-days"
      option "different-number-of-days"

      on_response do
        self.calculator = SmartAnswer::Calculators::AgriculturalHolidayEntitlementCalculator.new
      end

      next_node do |response|
        case response
        when "same-number-of-days"
          question :how_many_days_per_week?
        when "different-number-of-days"
          question :what_date_does_holiday_start?
        end
      end
    end

    radio :how_many_days_per_week? do
      option "7-days"
      option "6-days"
      option "5-days"
      option "4-days"
      option "3-days"
      option "2-days"
      option "1-day"

      on_response do |response|
        # XXX: this is a bit nasty and takes advantage of the fact that
        # to_i only looks for the very first integer
        calculator.days_worked_per_week = response.to_i
      end

      next_node do
        question :worked_for_same_employer?
      end
    end

    date_question :what_date_does_holiday_start? do
      on_response do |response|
        calculator.holiday_starts_on = response
      end

      next_node do
        question :how_many_total_days?
      end
    end

    radio :worked_for_same_employer? do
      option "same-employer"
      option "multiple-employers"

      next_node do |response|
        case response
        when "same-employer"
          outcome :done
        when "multiple-employers"
          question :how_many_weeks_at_current_employer?
        end
      end
    end

    value_question :how_many_total_days?, parse: Integer do
      on_response do |response|
        calculator.total_days_worked = response
      end

      validate { calculator.valid_total_days_worked? }

      next_node do
        question :worked_for_same_employer?
      end
    end

    value_question :how_many_weeks_at_current_employer?, parse: Integer do
      # Has to be less than a full year
      validate { calculator.valid_weeks_at_current_employer? }

      on_response do |response|
        calculator.weeks_at_current_employer = response
      end

      next_node do
        outcome :done_with_number_formatting
      end
    end

    outcome :done
    outcome :done_with_number_formatting
  end
end


text:
package org.apache.pig.builtin;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.apache.pig.Accumulator;
import org.apache.pig.Algebraic;
import org.apache.pig.EvalFunc;
import org.apache.pig.PigException;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.schema.Schema;

/**
 * Generates the count of the values of the first field of a tuple. This class is Algebraic in
 * implemenation, so if possible the execution will be split into a local and global functions
 */
public class COUNT extends EvalFunc<Long> implements Algebraic, Accumulator<Long>{
    private static TupleFactory mTupleFactory = TupleFactory.getInstance();

    @Override
    public Long exec(Tuple input) throws IOException {
        try {
            DataBag bag = (DataBag)input.get(0);
            Iterator it = bag.iterator();
            long cnt = 0;
            while (it.hasNext()){
                    Tuple t = (Tuple)it.next();
                    if (t != null && t.size() > 0 && t.get(0) != null )
                            cnt++;
            }
            return cnt;
        } catch (ExecException ee) {
            throw ee;
        } catch (Exception e) {
            int errCode = 2106;
            String msg = "Error while computing count in " + this.getClass().getSimpleName();
            throw new ExecException(msg, errCode, PigException.BUG, e);
        }
    }

    public String getInitial() {
        return Initial.class.getName();
    }

    public String getIntermed() {
        return Intermediate.class.getName();
    }

    public String getFinal() {
        return Final.class.getName();
    }

    static public class Initial extends EvalFunc<Tuple> {

        @Override
        public Tuple exec(Tuple input) throws IOException {
            // Since Initial is guaranteed to be called
            // only in the map, it will be called with an
            // input of a bag with a single tuple - the
            // count should always be 1 if bag is non empty
            DataBag bag = (DataBag)input.get(0);
            Iterator it = bag.iterator();
            if (it.hasNext()){
                Tuple t = (Tuple)it.next();
                if (t != null && t.size() > 0 && t.get(0) != null)
                    return mTupleFactory.newTuple(Long.valueOf(1));
            }
            return mTupleFactory.newTuple(Long.valueOf(0));
        }
    }

    static public class Intermediate extends EvalFunc<Tuple> {

        @Override
        public Tuple exec(Tuple input) throws IOException {
            try {
                return mTupleFactory.newTuple(sum(input));
            } catch (ExecException ee) {
                throw ee;
            } catch (Exception e) {
                int errCode = 2106;
                String msg = "Error while computing count in " + this.getClass().getSimpleName();
                throw new ExecException(msg, errCode, PigException.BUG, e);
            }
        }
    }

    static public class Final extends EvalFunc<Long> {
        @Override
        public Long exec(Tuple input) throws IOException {
            try {
                return sum(input);
            } catch (Exception ee) {
                int errCode = 2106;
                String msg = "Error while computing count in " + this.getClass().getSimpleName();
                throw new ExecException(msg, errCode, PigException.BUG, ee);
            }
        }
    }

    static protected Long sum(Tuple input) throws ExecException, NumberFormatException {
        DataBag values = (DataBag)input.get(0);
        long sum = 0;
        for (Iterator<Tuple> it = values.iterator(); it.hasNext();) {
            Tuple t = it.next();
            // Have faith here.  Checking each value before the cast is
            // just too much.
            sum += (Long)t.get(0);
        }
        return sum;
    }

    @Override
    public Schema outputSchema(Schema input) {
        return new Schema(new Schema.FieldSchema(null, DataType.LONG));
    }

    /* Accumulator interface implementation */
    private long intermediateCount = 0L;

    @Override
    public void accumulate(Tuple b) throws IOException {
        try {
            DataBag bag = (DataBag)b.get(0);
            Iterator it = bag.iterator();
            while (it.hasNext()){
                Tuple t = (Tuple)it.next();
                if (t != null && t.size() > 0 && t.get(0) != null) {
                    intermediateCount += 1;
                }
            }
        } catch (ExecException ee) {
            throw ee;
        } catch (Exception e) {
            int errCode = 2106;
            String msg = "Error while computing min in " + this.getClass().getSimpleName();
            throw new ExecException(msg, errCode, PigException.BUG, e);
        }
    }

    @Override
    public void cleanup() {
        intermediateCount = 0L;
    }

    @Override
    public Long getValue() {
        return intermediateCount;
    }

}


text:
<?php

if (CM_Db_Db::existsColumn('cm_languageKey', 'accessStamp')) {
    CM_Db_Db::exec('ALTER TABLE  `cm_languageKey` CHANGE  `accessStamp`  `updateCountResetVersion` int(10) unsigned DEFAULT NULL');
}


text:
/home/ubuntu/workspace/src/a.out "(echo hello world) #######first test"
/home/ubuntu/workspace/src/a.out "(ls && echo this is a test) || (cal; date)"
/home/ubuntu/workspace/src/a.out "clear && (echo A && echo B) || (echo C && echo D)"
/home/ubuntu/workspace/src/a.out "(ls -l && echo A) || (echo B && ls -a"
/home/ubuntu/workspace/src/a.out "(echo hello; echo world) && (echo this is a test && cal)"
/home/ubuntu/workspace/src/a.out "(cal || date +%D) && cal 12 2016 #testing"
/home/ubuntu/workspace/src/a.out "(mkdir temp_test && echo made temporary directory) || exit"
/home/ubuntu/workspace/src/a.out "rm -r temp_test && (echo removed temporary directory && ls) || (echo directory could not be removed; exit)"
/home/ubuntu/workspace/src/a.out "test -e main.cpp && ((echo A && echo B) || (echo C && echo D))"
/home/ubuntu/workspace/src/a.out "(clear && exit) || exit ####last test"


text:
'use strict';

describe("ShipmentDisplay", function () {

    beforeEach(module('umbraco'));

    it ("should be possible to set the 'to' address",
        inject(function(shipmentDisplayBuilder, genericModelBuilder, addressMocks) {

        //// Arrange
        var shipment = shipmentDisplayBuilder.createDefault();
        var address = addressMocks.getRandomAddress(genericModelBuilder);

        //// Act
        shipment.setDestinationAddress(address);

        //// Assert
        expect (shipment.toName).toBe(address.name);
        expect (shipment.toAddress1).toBe(address.address1);
        expect (shipment.toAddress2).toBe(address.address2)
        expect (shipment.toLocality).toBe(address.locality);
        expect (shipment.toRegion).toBe(address.region);
        expect (shipment.toPostalCode).toBe(address.postalCode);
        expect (shipment.toCountryCode).toBe(address.countryCode);
        expect (shipment.phone).toBe(address.phone);
        expect (shipment.email).toBe(address.email);
    }));

    it ('should be possible to get the destination as an address', inject(function(shipmentDisplayBuilder, genericModelBuilder, addressMocks) {

        //// Arrange
        var shipment = shipmentDisplayBuilder.createDefault();
        var address = addressMocks.getRandomAddress(genericModelBuilder);
        shipment.setDestinationAddress(address);

        //// Act
        var destination = shipment.getDestinationAddress();

        //// Assert
        expect (_.isEqual(address, destination));
    }));

    it ('should be possible to set the origin address', inject(function(shipmentDisplayBuilder, genericModelBuilder, addressMocks) {

        //// Arrange
        var shipment = shipmentDisplayBuilder.createDefault();
        var address = addressMocks.getRandomAddress(genericModelBuilder);

        //// Act
        shipment.setOriginAddress(address);

        //// Assert
        expect (shipment.fromName).toBe(address.name);
        expect (shipment.fromAddress1).toBe(address.address1);
        expect (shipment.fromAddress2).toBe(address.address2)
        expect (shipment.fromLocality).toBe(address.locality);
        expect (shipment.fromRegion).toBe(address.region);
        expect (shipment.fromPostalCode).toBe(address.postalCode);
        expect (shipment.fromCountryCode).toBe(address.countryCode);
    }));

    it ('should be possible to get the origin address from a shipment', inject(function(shipmentDisplayBuilder, genericModelBuilder, addressMocks) {

        //// Arrange
        var shipment = shipmentDisplayBuilder.createDefault();
        var address = addressMocks.getRandomAddress(genericModelBuilder);
        shipment.setOriginAddress(address);

        //// Act
        var origin = shipment.getOriginAddress();
        address.addressType = 'shipping'; // this is set in the prototype method

        //// Assert
        expect (_.isEqual(origin, address)).toBe(true);
    }));
});