<commit_before>#!/usr/bin/env node
var ArgumentParser = require ('argparse').ArgumentParser;
var Scaffolder = require('./scaffolder');
var sb = require('string-builder');
var path = require('path');
var fs = require('fs.extra');

var parser = new ArgumentParser({
    version: '0.0.1',
    addHelp:true,
    description: 'Argparse example'
});

parser.addArgument(
    [ '-s', '--source' ],
    {
        help: 'The RAML file from which the whole code will be generated\n' +
            'It\'s the user responsibility to link the files and !includes on the filesystem or the internet'
    }
);

parser.addArgument(
    [ '-t', '--target' ],
    {
        help: 'The target directory where the project will be created: [target]/[name]\n' +
            'Note: If not specified, the project will be generated in ./[name]'
    }
);

parser.addArgument(
    [ '-n', '--name' ],
    {
        help: 'The generated project name. It will be used the following way:\n' +
            '- A subfolder of [target]\n' +
            '- The main project file [name].ino'
    }
);

parser.addArgument(
    [ '-il', '--installLibraries' ],
    {
        help: 'Include this option and indicate the Arduino Installation folder. Ex: "... -il ~/Documents/Arduino/libraries" if you need Nobel to install the required libraries (Webduino, android-resource, and Flash)'
    }
);

// Option for generating one method per resource with case, or one method per resource + method

var err = false;
options = parser.parseArgs();

if (options.source==null) {
    sb.appendLine("- The Source file must be specified");
    err = true;
}

if (options.name==null) {
    sb.appendLine("- The Project Name must be specified.");
    err = true;
}

if (!isChar(options.name)) {
    sb.appendLine("- The Project Name only accepts letters.");
    err = true;
}

if (err) {
    console.log("Please, check the following errors (nobel -h or nobel --help for the User Guide)");
    console.log(sb.toString());
    return;
}

if (options.installLibraries!=null) {

    if (!fs.existsSync(options.installLibraries)) {
        console.log("ERR: "+ options.installLibraries+" does not exist. Libraries installation is skipped");
        return;
    }

    installDependency(options.installLibraries, "arduino-resource");
    installDependency(options.installLibraries, "Flash");
    installDependency(options.installLibraries, "Webduino");
}

function installDependency(libFolder, dependencyName) {

    if (!fs.existsSync(path.join(libFolder, dependencyName))) {
        fs.copyRecursive(path.join(__dirname, 'arduinoModules', dependencyName), path.join(libFolder, dependencyName),
            function(e) {
                if (e) {
                    console.log(e);
                } else {
                    fs.unlinkSync(path.join(libFolder, dependencyName,'.git'));
                }

            }
        );
    } else {
        console.log("INFO: Omitting "+ dependencyName +" because it was already installed");
    }

}

var targetFolder = options.target || process.cwd();
if (fs.existsSync(targetFolder)) {
    console.log("WARN: The target "+ targetFolder +" folder already exists");
} else {
    fs.mkdirSync(targetFolder)
    console.log("INFO: Creating" + targetFolder);
}

targetFolder = path.join(targetFolder, options.name);

if (fs.existsSync(targetFolder)) {
    if(fs.readdirSync(targetFolder).length > 0) {
        console.log("ERR: The project "+ targetFolder +" already exists and it's not empty");
        return;
    } else {
        console.log("WARN: The project folder"+ targetFolder +" already exists but it' empty. The new project will reuse this folder");
    }
} else {
    fs.mkdirSync(targetFolder)
    console.log("INFO: Creating project folder" + targetFolder);
}

options.target = targetFolder;

scaffolder = new Scaffolder();
scaffolder.generate(options);

function isChar(str) {
    return /^[a-zA-Z]+$/.test(str);
}<commit_msg>Add verbose for library installation<commit_after>#!/usr/bin/env node
var ArgumentParser = require ('argparse').ArgumentParser;
var Scaffolder = require('./scaffolder');
var sb = require('string-builder');
var path = require('path');
var fs = require('fs.extra');

var parser = new ArgumentParser({
    version: '0.0.1',
    addHelp:true,
    description: 'Argparse example'
});

parser.addArgument(
    [ '-s', '--source' ],
    {
        help: 'The RAML file from which the whole code will be generated\n' +
            'It\'s the user responsibility to link the files and !includes on the filesystem or the internet'
    }
);

parser.addArgument(
    [ '-t', '--target' ],
    {
        help: 'The target directory where the project will be created: [target]/[name]\n' +
            'Note: If not specified, the project will be generated in ./[name]'
    }
);

parser.addArgument(
    [ '-n', '--name' ],
    {
        help: 'The generated project name. It will be used the following way:\n' +
            '- A subfolder of [target]\n' +
            '- The main project file [name].ino'
    }
);

parser.addArgument(
    [ '-il', '--installLibraries' ],
    {
        help: 'Include this option and indicate the Arduino Installation folder. Ex: "... -il ~/Documents/Arduino/libraries" if you need Nobel to install the required libraries (Webduino, android-resource, and Flash)'
    }
);

// Option for generating one method per resource with case, or one method per resource + method

var err = false;
options = parser.parseArgs();

if (options.source==null) {
    sb.appendLine("- The Source file must be specified");
    err = true;
}

if (options.name==null) {
    sb.appendLine("- The Project Name must be specified.");
    err = true;
}

if (!isChar(options.name)) {
    sb.appendLine("- The Project Name only accepts letters.");
    err = true;
}

if (err) {
    console.log("Please, check the following errors (nobel -h or nobel --help for the User Guide)");
    console.log(sb.toString());
    return;
}

if (options.installLibraries!=null) {

    if (!fs.existsSync(options.installLibraries)) {
        console.log("ERR: "+ options.installLibraries+" does not exist. Libraries installation is skipped");
        return;
    }

    installDependency(options.installLibraries, "arduino_nobel_resource");
    installDependency(options.installLibraries, "Flash");
    installDependency(options.installLibraries, "Webduino");

}

function installDependency(libFolder, dependencyName) {

    if (!fs.existsSync(path.join(libFolder, dependencyName))) {
        fs.copyRecursive(path.join(__dirname, 'arduinoModules', dependencyName), path.join(libFolder, dependencyName),
            function(e) {
                if (e) {
                    console.log(e);
                } else {
                    fs.unlinkSync(path.join(libFolder, dependencyName,'.git'));
                    console.log("INFO: " + dependencyName + " was successfully installed");
                }

            }
        );
    } else {
        console.log("INFO: Omitting "+ dependencyName +" because it was already installed");
    }

}

var targetFolder = options.target || process.cwd();
if (fs.existsSync(targetFolder)) {
    console.log("WARN: The target "+ targetFolder +" folder already exists");
} else {
    fs.mkdirSync(targetFolder)
    console.log("INFO: Creating" + targetFolder);
}

targetFolder = path.join(targetFolder, options.name);

if (fs.existsSync(targetFolder)) {
    if(fs.readdirSync(targetFolder).length > 0) {
        console.log("ERR: The project "+ targetFolder +" already exists and it's not empty");
        return;
    } else {
        console.log("WARN: The project folder"+ targetFolder +" already exists but it' empty. The new project will reuse this folder");
    }
} else {
    fs.mkdirSync(targetFolder)
    console.log("INFO: Creating project folder" + targetFolder);
}

options.target = targetFolder;

scaffolder = new Scaffolder();
scaffolder.generate(options);

function isChar(str) {
    return /^[a-zA-Z]+$/.test(str);
}<|endoftext|>


<commit_before>/*globals require, module */

'use strict';

var check, walk, events;

check = require('check-types');
walk = require('./walk');
events = require('./events');

module.exports = parse;

function parse (json, callback) {
    var emitter, scopes, errors, done, key;

    check.assert.maybe.function(callback, 'Callback must be a function.');

    emitter = walk(json);
    scopes = [];
    errors = [];
    done = false;

    emitter.on(events.array, array);
    emitter.on(events.object, object);
    emitter.on(events.property, property);
    emitter.on(events.string, value);
    emitter.on(events.number, value);
    emitter.on(events.literal, value);
    emitter.on(events.endArray, endScope);
    emitter.on(events.endObject, endScope);
    emitter.on(events.end, end);
    emitter.on(events.error, error);

    if (callback) {
        return;
    }

    while (!done) {
        /*jshint noempty:false */
    }

    if (errors.length > 0) {
        return errors[0];
    }

    return scopes[0];

    function array () {
        beginScope([]);
    }

    function beginScope (parsed) {
        if (scopes.length > 0) {
            value(parsed);
        }

        scopes.push(parsed);
    }

    function value (v) {
        var scope = scopes[scopes.length - 1];

        if (key) {
            scope[key] = v;
            key = undefined;
        } else {
            scope.push(v);
        }
    }

    function object () {
        beginScope({});
    }

    function property (name) {
        key = name;
    }

    function endScope () {
        scopes.pop();
    }

    function end () {
        if (callback) {
            return callback(errors[0], scopes[0]);
        }

        done = true;
    }

    function error (error) {
        errors.push(error);
    }
}

<commit_msg>Return a promise from parse, use new walk implementation.<commit_after>/*globals require, module, Promise */

'use strict';

var check, walk, events;

check = require('check-types');
walk = require('./walk');
events = require('./events');

module.exports = parse;

function parse (stream, options) {
    var walker, scopes, errors, resolve, reject, key;

    walker = walk(options);
    stream.pipe(walkable.stream);

    scopes = [];
    errors = [];

    walker.emitter.on(events.array, array);
    walker.emitter.on(events.object, object);
    walker.emitter.on(events.property, property);
    walker.emitter.on(events.string, value);
    walker.emitter.on(events.number, value);
    walker.emitter.on(events.literal, value);
    walker.emitter.on(events.endArray, endScope);
    walker.emitter.on(events.endObject, endScope);
    walker.emitter.on(events.end, end);
    walker.emitter.on(events.error, error);

    return new Promise(function (res, rej) {
        resolve = res;
        reject = rej;
    });

    function array () {
        beginScope([]);
    }

    function beginScope (parsed) {
        if (scopes.length > 0) {
            value(parsed);
        }

        scopes.push(parsed);
    }

    function value (v) {
        var scope = scopes[scopes.length - 1];

        if (key) {
            scope[key] = v;
            key = undefined;
        } else {
            scope.push(v);
        }
    }

    function object () {
        beginScope({});
    }

    function property (name) {
        key = name;
    }

    function endScope () {
        scopes.pop();
    }

    function end () {
        if (errors.length > 0) {
            return reject(errors[0]);
        }

        resolve(scopes[0]);
    }

    function error (e) {
        errors.push(e);
    }
}

<|endoftext|>


<commit_before>import Random from 'random-seed'
import {ZERO_POINT, INFINITY_POINT, traverse, traversalDistance, min as minPoint} from './point-helpers'
import {getExtent} from './text-helpers'
import Iterator from './iterator'

export default class Patch {
  constructor (seed = Date.now()) {
    this.randomGenerator = new Random(seed)
    this.root = null
    this.iterator = new Iterator(this)
  }

  spliceWithText (start, replacedExtent, replacementText) {
    this.splice(start, replacedExtent, getExtent(replacementText), {text: replacementText})
  }

  splice (outputStart, replacedExtent, replacementExtent, options) {
    let outputOldEnd = traverse(outputStart, replacedExtent)
    let outputNewEnd = traverse(outputStart, replacementExtent)

    let {startNode, prefix} = this.iterator.insertSpliceStart(outputStart)
    let {endNode, suffix, suffixExtent} = this.iterator.insertSpliceEnd(outputOldEnd)
    startNode.priority = -1
    this.bubbleNodeUp(startNode)
    endNode.priority = -2
    this.bubbleNodeUp(endNode)

    startNode.right = null
    startNode.inputExtent = startNode.inputLeftExtent
    startNode.outputExtent = startNode.outputLeftExtent

    let endNodeOutputRightExtent = traversalDistance(endNode.outputExtent, endNode.outputLeftExtent)
    endNode.outputLeftExtent = traverse(outputNewEnd, suffixExtent)
    endNode.outputExtent = traverse(endNode.outputLeftExtent, endNodeOutputRightExtent)
    endNode.changeText = prefix + options.text + suffix

    startNode.priority = this.generateRandom()
    this.bubbleNodeDown(startNode)
    endNode.priority = this.generateRandom()
    this.bubbleNodeDown(endNode)
  }

  spliceInput (inputStart, replacedExtent, replacementExtent) {
    let inputOldEnd = traverse(inputStart, replacedExtent)
    let inputNewEnd = traverse(inputStart, replacementExtent)

    let startNode = this.iterator.insertSpliceInputBoundary(inputStart, true)
    let endNode = this.iterator.insertSpliceInputBoundary(inputOldEnd, false)

    startNode.priority = -1
    this.bubbleNodeUp(startNode)
    endNode.priority = -2
    this.bubbleNodeUp(endNode)

    startNode.right = null
    startNode.inputExtent = startNode.inputLeftExtent
    startNode.outputExtent = startNode.outputLeftExtent

    let endNodeInputRightExtent = traversalDistance(endNode.inputExtent, endNode.inputLeftExtent)
    let endNodeOutputRightExtent = traversalDistance(endNode.outputExtent, endNode.outputLeftExtent)
    endNode.inputLeftExtent = inputNewEnd
    endNode.inputExtent = traverse(endNode.inputLeftExtent, endNodeInputRightExtent)
    endNode.outputLeftExtent = traverse(startNode.outputLeftExtent, replacementExtent)
    endNode.outputExtent = traverse(endNode.outputLeftExtent, endNodeOutputRightExtent)

    if (startNode.isChangeStart) {
      this.deleteNode(startNode)
    } else {
      startNode.priority = this.generateRandom()
      this.bubbleNodeDown(startNode)
    }

    if (endNode.isChangeStart) {
      endNode.priority = this.generateRandom()
      this.bubbleNodeDown(endNode)
    } else {
      this.deleteNode(endNode)
    }
  }

  isChangedAtInputPosition (inputPosition) {
    this.iterator.seekToInputPosition(inputPosition)
    return this.iterator.inChange()
  }

  isChangedAtOutputPosition (outputPosition) {
    this.iterator.seekToOutputPosition(outputPosition)
    return this.iterator.inChange()
  }

  translateInputPosition (inputPosition) {
    this.iterator.seekToInputPosition(inputPosition)
    let overshoot = traversalDistance(inputPosition, this.iterator.getInputStart())
    return traverse(this.iterator.getOutputStart(), minPoint(overshoot, this.iterator.getOutputExtent()))
  }

  translateOutputPosition (outputPosition) {
    this.iterator.seekToOutputPosition(outputPosition)
    let overshoot = traversalDistance(outputPosition, this.iterator.getOutputStart())
    return traverse(this.iterator.getInputStart(), minPoint(overshoot, this.iterator.getInputExtent()))
  }

  getChanges () {
    return this.iterator.getChanges()
  }

  deleteNode (node) {
    node.priority = Infinity
    this.bubbleNodeDown(node)
    if (node.parent) {
      if (node.parent.left === node) {
        node.parent.left = null
      } else {
        node.parent.right = null
        node.parent.inputExtent = node.parent.inputLeftExtent
        node.parent.outputExtent = node.parent.outputLeftExtent
        let ancestor = node.parent
        while (ancestor.parent && ancestor.parent.right === ancestor) {
          ancestor.parent.inputExtent = traverse(ancestor.parent.inputLeftExtent, ancestor.inputExtent)
          ancestor.parent.outputExtent = traverse(ancestor.parent.outputLeftExtent, ancestor.outputExtent)
          ancestor = ancestor.parent
        }
      }
    } else {
      this.root = null
    }
  }

  bubbleNodeUp (node) {
    while (node.parent && node.priority < node.parent.priority) {
      if (node === node.parent.left) {
        this.rotateNodeRight(node)
      } else {
        this.rotateNodeLeft(node)
      }
    }
  }

  bubbleNodeDown (node) {
    while (true) {
      let leftChildPriority = node.left ? node.left.priority : Infinity
      let rightChildPriority = node.right ? node.right.priority : Infinity

      if (leftChildPriority < rightChildPriority && leftChildPriority < node.priority) {
        this.rotateNodeRight(node.left)
      } else if (rightChildPriority < node.priority) {
        this.rotateNodeLeft(node.right)
      } else {
        break
      }
    }
  }

  rotateNodeLeft (pivot) {
    let root = pivot.parent

    if (root.parent) {
      if (root === root.parent.left) {
        root.parent.left = pivot
      } else {
        root.parent.right = pivot
      }
    } else {
      this.root = pivot
    }
    pivot.parent = root.parent

    root.right = pivot.left
    if (root.right) {
      root.right.parent = root
    }

    pivot.left = root
    pivot.left.parent = pivot

    pivot.inputLeftExtent = traverse(root.inputLeftExtent, pivot.inputLeftExtent)
    pivot.inputExtent = traverse(pivot.inputLeftExtent, (pivot.right ? pivot.right.inputExtent : ZERO_POINT))
    root.inputExtent = traverse(root.inputLeftExtent, (root.right ? root.right.inputExtent : ZERO_POINT))

    pivot.outputLeftExtent = traverse(root.outputLeftExtent, pivot.outputLeftExtent)
    pivot.outputExtent = traverse(pivot.outputLeftExtent, (pivot.right ? pivot.right.outputExtent : ZERO_POINT))
    root.outputExtent = traverse(root.outputLeftExtent, (root.right ? root.right.outputExtent : ZERO_POINT))
  }

  rotateNodeRight (pivot) {
    let root = pivot.parent

    if (root.parent) {
      if (root === root.parent.left) {
        root.parent.left = pivot
      } else {
        root.parent.right = pivot
      }
    } else {
      this.root = pivot
    }
    pivot.parent = root.parent

    root.left = pivot.right
    if (root.left) {
      root.left.parent = root
    }

    pivot.right = root
    pivot.right.parent = pivot

    root.inputLeftExtent = traversalDistance(root.inputLeftExtent, pivot.inputLeftExtent)
    root.inputExtent = traversalDistance(root.inputExtent, pivot.inputLeftExtent)
    pivot.inputExtent = traverse(pivot.inputLeftExtent, root.inputExtent)

    root.outputLeftExtent = traversalDistance(root.outputLeftExtent, pivot.outputLeftExtent)
    root.outputExtent = traversalDistance(root.outputExtent, pivot.outputLeftExtent)
    pivot.outputExtent = traverse(pivot.outputLeftExtent, root.outputExtent)
  }

  generateRandom () {
    return this.randomGenerator.random()
  }
}
<commit_msg>Simplify position translation<commit_after>import Random from 'random-seed'
import {ZERO_POINT, INFINITY_POINT, traverse, traversalDistance, min as minPoint} from './point-helpers'
import {getExtent} from './text-helpers'
import Iterator from './iterator'

export default class Patch {
  constructor (seed = Date.now()) {
    this.randomGenerator = new Random(seed)
    this.root = null
    this.iterator = new Iterator(this)
  }

  spliceWithText (start, replacedExtent, replacementText) {
    this.splice(start, replacedExtent, getExtent(replacementText), {text: replacementText})
  }

  splice (outputStart, replacedExtent, replacementExtent, options) {
    let outputOldEnd = traverse(outputStart, replacedExtent)
    let outputNewEnd = traverse(outputStart, replacementExtent)

    let {startNode, prefix} = this.iterator.insertSpliceStart(outputStart)
    let {endNode, suffix, suffixExtent} = this.iterator.insertSpliceEnd(outputOldEnd)
    startNode.priority = -1
    this.bubbleNodeUp(startNode)
    endNode.priority = -2
    this.bubbleNodeUp(endNode)

    startNode.right = null
    startNode.inputExtent = startNode.inputLeftExtent
    startNode.outputExtent = startNode.outputLeftExtent

    let endNodeOutputRightExtent = traversalDistance(endNode.outputExtent, endNode.outputLeftExtent)
    endNode.outputLeftExtent = traverse(outputNewEnd, suffixExtent)
    endNode.outputExtent = traverse(endNode.outputLeftExtent, endNodeOutputRightExtent)
    endNode.changeText = prefix + options.text + suffix

    startNode.priority = this.generateRandom()
    this.bubbleNodeDown(startNode)
    endNode.priority = this.generateRandom()
    this.bubbleNodeDown(endNode)
  }

  spliceInput (inputStart, replacedExtent, replacementExtent) {
    let inputOldEnd = traverse(inputStart, replacedExtent)
    let inputNewEnd = traverse(inputStart, replacementExtent)

    let startNode = this.iterator.insertSpliceInputBoundary(inputStart, true)
    let endNode = this.iterator.insertSpliceInputBoundary(inputOldEnd, false)

    startNode.priority = -1
    this.bubbleNodeUp(startNode)
    endNode.priority = -2
    this.bubbleNodeUp(endNode)

    startNode.right = null
    startNode.inputExtent = startNode.inputLeftExtent
    startNode.outputExtent = startNode.outputLeftExtent

    let endNodeInputRightExtent = traversalDistance(endNode.inputExtent, endNode.inputLeftExtent)
    let endNodeOutputRightExtent = traversalDistance(endNode.outputExtent, endNode.outputLeftExtent)
    endNode.inputLeftExtent = inputNewEnd
    endNode.inputExtent = traverse(endNode.inputLeftExtent, endNodeInputRightExtent)
    endNode.outputLeftExtent = traverse(startNode.outputLeftExtent, replacementExtent)
    endNode.outputExtent = traverse(endNode.outputLeftExtent, endNodeOutputRightExtent)

    if (startNode.isChangeStart) {
      this.deleteNode(startNode)
    } else {
      startNode.priority = this.generateRandom()
      this.bubbleNodeDown(startNode)
    }

    if (endNode.isChangeStart) {
      endNode.priority = this.generateRandom()
      this.bubbleNodeDown(endNode)
    } else {
      this.deleteNode(endNode)
    }
  }

  isChangedAtInputPosition (inputPosition) {
    this.iterator.seekToInputPosition(inputPosition)
    return this.iterator.inChange()
  }

  isChangedAtOutputPosition (outputPosition) {
    this.iterator.seekToOutputPosition(outputPosition)
    return this.iterator.inChange()
  }

  translateInputPosition (inputPosition) {
    this.iterator.seekToInputPosition(inputPosition)
    let overshoot = traversalDistance(inputPosition, this.iterator.getInputStart())
    return minPoint(traverse(this.iterator.getOutputStart(), overshoot), this.iterator.getOutputEnd())
  }

  translateOutputPosition (outputPosition) {
    this.iterator.seekToOutputPosition(outputPosition)
    let overshoot = traversalDistance(outputPosition, this.iterator.getOutputStart())
    return minPoint(traverse(this.iterator.getInputStart(), overshoot), this.iterator.getInputEnd())
  }

  getChanges () {
    return this.iterator.getChanges()
  }

  deleteNode (node) {
    node.priority = Infinity
    this.bubbleNodeDown(node)
    if (node.parent) {
      if (node.parent.left === node) {
        node.parent.left = null
      } else {
        node.parent.right = null
        node.parent.inputExtent = node.parent.inputLeftExtent
        node.parent.outputExtent = node.parent.outputLeftExtent
        let ancestor = node.parent
        while (ancestor.parent && ancestor.parent.right === ancestor) {
          ancestor.parent.inputExtent = traverse(ancestor.parent.inputLeftExtent, ancestor.inputExtent)
          ancestor.parent.outputExtent = traverse(ancestor.parent.outputLeftExtent, ancestor.outputExtent)
          ancestor = ancestor.parent
        }
      }
    } else {
      this.root = null
    }
  }

  bubbleNodeUp (node) {
    while (node.parent && node.priority < node.parent.priority) {
      if (node === node.parent.left) {
        this.rotateNodeRight(node)
      } else {
        this.rotateNodeLeft(node)
      }
    }
  }

  bubbleNodeDown (node) {
    while (true) {
      let leftChildPriority = node.left ? node.left.priority : Infinity
      let rightChildPriority = node.right ? node.right.priority : Infinity

      if (leftChildPriority < rightChildPriority && leftChildPriority < node.priority) {
        this.rotateNodeRight(node.left)
      } else if (rightChildPriority < node.priority) {
        this.rotateNodeLeft(node.right)
      } else {
        break
      }
    }
  }

  rotateNodeLeft (pivot) {
    let root = pivot.parent

    if (root.parent) {
      if (root === root.parent.left) {
        root.parent.left = pivot
      } else {
        root.parent.right = pivot
      }
    } else {
      this.root = pivot
    }
    pivot.parent = root.parent

    root.right = pivot.left
    if (root.right) {
      root.right.parent = root
    }

    pivot.left = root
    pivot.left.parent = pivot

    pivot.inputLeftExtent = traverse(root.inputLeftExtent, pivot.inputLeftExtent)
    pivot.inputExtent = traverse(pivot.inputLeftExtent, (pivot.right ? pivot.right.inputExtent : ZERO_POINT))
    root.inputExtent = traverse(root.inputLeftExtent, (root.right ? root.right.inputExtent : ZERO_POINT))

    pivot.outputLeftExtent = traverse(root.outputLeftExtent, pivot.outputLeftExtent)
    pivot.outputExtent = traverse(pivot.outputLeftExtent, (pivot.right ? pivot.right.outputExtent : ZERO_POINT))
    root.outputExtent = traverse(root.outputLeftExtent, (root.right ? root.right.outputExtent : ZERO_POINT))
  }

  rotateNodeRight (pivot) {
    let root = pivot.parent

    if (root.parent) {
      if (root === root.parent.left) {
        root.parent.left = pivot
      } else {
        root.parent.right = pivot
      }
    } else {
      this.root = pivot
    }
    pivot.parent = root.parent

    root.left = pivot.right
    if (root.left) {
      root.left.parent = root
    }

    pivot.right = root
    pivot.right.parent = pivot

    root.inputLeftExtent = traversalDistance(root.inputLeftExtent, pivot.inputLeftExtent)
    root.inputExtent = traversalDistance(root.inputExtent, pivot.inputLeftExtent)
    pivot.inputExtent = traverse(pivot.inputLeftExtent, root.inputExtent)

    root.outputLeftExtent = traversalDistance(root.outputLeftExtent, pivot.outputLeftExtent)
    root.outputExtent = traversalDistance(root.outputExtent, pivot.outputLeftExtent)
    pivot.outputExtent = traverse(pivot.outputLeftExtent, root.outputExtent)
  }

  generateRandom () {
    return this.randomGenerator.random()
  }
}
<|endoftext|>


<commit_before>class Pixel {
  constructor(event, timestamp, optional) {
    this.params = [];
    this.event = event;
    this.timestamp = timestamp;
    this.optional = optionalData(optional);
    this.buildParams();
    this.send();
  }

  buildParams() {
    const attr = this.getAttribute();
    for (var index in attr) {
      if (attr.hasOwnProperty(index)) {
        this.setParam(index, attr[index](index));
      }
    }
  }

  getAttribute() {
    return {
      id:           () => Config.id, // website Id
      uid:          () => Cookie.get('uid'), // user Id
      ev:           () => this.event, // event being triggered
      ed:           () => this.optional, // any event data to pass along
      v:            () => Config.version, // openpixel.js version
      dl:           () => window.location.href, // document location
      rl:           () => document.referrer, // referrer location
      ts:           () => this.timestamp, // timestamp when event was triggered
      de:           () => document.characterSet, // document encoding
      sr:           () => window.screen.width + 'x' + window.screen.height, // screen resolution
      vp:           () => window.innerWidth + 'x' + window.innerHeight, // viewport size
      cd:           () => window.screen.colorDepth, // color depth
      dt:           () => document.title, // document title
      bn:           () => Browser.nameAndVersion(), // browser name and version number
      md:           () => Browser.isMobile(), // is a mobile device?
      ua:           () => Browser.userAgent(), // user agent
      tz:           () => (new Date()).getTimezoneOffset(), // timezone
      utm_source:   key => Cookie.getUtm(key), // get the utm source
      utm_medium:   key => Cookie.getUtm(key), // get the utm medium
      utm_term:     key => Cookie.getUtm(key), // get the utm term
      utm_content:  key => Cookie.getUtm(key), // get the utm concent
      utm_campaign: key => Cookie.getUtm(key), // get the utm campaign
    }
  }

  setParam(key, val) {
    if (isset(val)) {
      this.params.push(`${key}=${encodeURIComponent(val)}`);
    } else {
      this.params.push(`${key}=`);
    }
  }

  send() {
    window.navigator.sendBeacon ? this.sendBeacon() : this.sendImage();
  }

  sendBeacon() {
    window.navigator.sendBeacon(this.getSourceUrl());
  }

  sendImage() {
    this.img = document.createElement('img');
    this.img.src = this.getSourceUrl();
    this.img.style.display = 'none';
    this.img.width = '1';
    this.img.height = '1';
    document.getElementsByTagName('body')[0].appendChild(this.img);
  }

  getSourceUrl() {
    return `${pixelEndpoint}?${this.params.join('&')}`;
  }
}
<commit_msg>Fix typo in pixel.js comment (#63)<commit_after>class Pixel {
  constructor(event, timestamp, optional) {
    this.params = [];
    this.event = event;
    this.timestamp = timestamp;
    this.optional = optionalData(optional);
    this.buildParams();
    this.send();
  }

  buildParams() {
    const attr = this.getAttribute();
    for (var index in attr) {
      if (attr.hasOwnProperty(index)) {
        this.setParam(index, attr[index](index));
      }
    }
  }

  getAttribute() {
    return {
      id:           () => Config.id, // website Id
      uid:          () => Cookie.get('uid'), // user Id
      ev:           () => this.event, // event being triggered
      ed:           () => this.optional, // any event data to pass along
      v:            () => Config.version, // openpixel.js version
      dl:           () => window.location.href, // document location
      rl:           () => document.referrer, // referrer location
      ts:           () => this.timestamp, // timestamp when event was triggered
      de:           () => document.characterSet, // document encoding
      sr:           () => window.screen.width + 'x' + window.screen.height, // screen resolution
      vp:           () => window.innerWidth + 'x' + window.innerHeight, // viewport size
      cd:           () => window.screen.colorDepth, // color depth
      dt:           () => document.title, // document title
      bn:           () => Browser.nameAndVersion(), // browser name and version number
      md:           () => Browser.isMobile(), // is a mobile device?
      ua:           () => Browser.userAgent(), // user agent
      tz:           () => (new Date()).getTimezoneOffset(), // timezone
      utm_source:   key => Cookie.getUtm(key), // get the utm source
      utm_medium:   key => Cookie.getUtm(key), // get the utm medium
      utm_term:     key => Cookie.getUtm(key), // get the utm term
      utm_content:  key => Cookie.getUtm(key), // get the utm content
      utm_campaign: key => Cookie.getUtm(key), // get the utm campaign
    }
  }

  setParam(key, val) {
    if (isset(val)) {
      this.params.push(`${key}=${encodeURIComponent(val)}`);
    } else {
      this.params.push(`${key}=`);
    }
  }

  send() {
    window.navigator.sendBeacon ? this.sendBeacon() : this.sendImage();
  }

  sendBeacon() {
    window.navigator.sendBeacon(this.getSourceUrl());
  }

  sendImage() {
    this.img = document.createElement('img');
    this.img.src = this.getSourceUrl();
    this.img.style.display = 'none';
    this.img.width = '1';
    this.img.height = '1';
    document.getElementsByTagName('body')[0].appendChild(this.img);
  }

  getSourceUrl() {
    return `${pixelEndpoint}?${this.params.join('&')}`;
  }
}
<|endoftext|>


<commit_before>/**
Gather from the nearest source.
@param {Creep} creep
*/
function gatherFromClosestSource(creep) {
  let sources = creep.room.find(FIND_SOURCES);
  if (creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
    creep.moveTo(sources[0], {
      visualizePathStyle: {
        stroke: '#ffaa00'
      }
    });
  }
}

/**
Drop off energy at a structure that is not full of energy. Prioritizes spawns.
@param {Creep} creep
*/
function dropOffEnergyAtNearbyStructure(creep) {
  let targets = creep.room.find(FIND_STRUCTURES, {
    filter: (structure) => {
      return (structure.structureType == STRUCTURE_EXTENSION ||
          structure.structureType == STRUCTURE_SPAWN ||
          structure.structureType == STRUCTURE_TOWER ||
          structure.structureType == STRUCTURE_CONTAINER) &&
        structure.energy < structure.energyCapacity ||
        (structure.store && structure.store[RESOURCE_ENERGY] < structure.storeCapacity);
    }
  });

  if (targets.length > 0) {
    let target = targets[0];
    for (let i = 1; i < targets.length; i++) {
      if (targets[i].structureType == STRUCTURE_SPAWN ||
        targets[i].structureType == STRUCTURE_EXTENSION) {
        target = targets[i];
      }
    }
    if (creep.transfer(target, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
      creep.moveTo(target, {
        visualizePathStyle: {
          stroke: '#ffffff'
        }
      });
    }
  }
}

/**
Find the biggest dropped pile of energy in the room and pick it up.
@param {Creep} creep
*/
function pickupBiggestEnergyPile(creep) {
  let droppedResources = creep.room.find(FIND_DROPPED_RESOURCES, {
    filter: {
      resourceType: RESOURCE_ENERGY
    }
  });
  if (droppedResources.length) {
    //determine which pile of resources is biggest
    let biggestResource = droppedResources[0];
    if (droppedResources.length > 1) {
      for (let i = 1; i < droppedResources.length; i++) {
        if (droppedResources[i].amount > biggestResource.amount) {
          biggestResource = droppedResources[i];
        }
      }
    }
    if (creep.pickup(biggestResource) == ERR_NOT_IN_RANGE) {
      creep.moveTo(biggestResource, {
        visualizePathStyle: {
          stroke: '#ffaa00'
        }
      });
    }
  }
}

/**
Upgrade this rooms controller.
@param {Creep} creep
*/
function upgradeRoomController(creep) {
  creep.upgradeController(creep.room.controller);
  if (!creep.pos.isNearTo(creep.room.controller)) {
    creep.moveTo(creep.room.controller, {
      visualizePathStyle: {
        stroke: '#ffffff'
      }
    });
  }
}

/**
Retrieve energy from an upgrader container. If one is not found,
retrieve energy from spawn.
@param {Creep} creep
*/
function retrieveEnergyForUpgrading(creep) {
  let upContainer = getUpContainer(creep);
  if (getUpContainer) {
    if (creep.withdraw(upContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
      creep.moveTo(upContainer, {
        visualizePathStyle: {
          stroke: '#ffaa00'
        }
      });
    }
  } else {
    //if not found, check for spawn and retrieve from there.
    let spawns = creep.room.find(FIND_MY_STRUCTURES, {
      filter: {
        structureType: STRUCTURE_SPAWN
      }
    });
    if (creep.withdraw(spawns[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
      creep.moveTo(spawns[0], {
        visualizePathStyle: {
          stroke: '#ffaa00'
        }
      });
    }
  }
}

/**
returns the upContainer for the creep's room. If there is no upContainer,
returns 0.
@param {Creep} creep
*/
function getUpContainer(creep) {
  let upContainerFlagPos = Memory.flags[creep.room.name + " upContainer"];
  let lookResults = creep.room.lookForAt(LOOK_STRUCTURES,
    upContainerFlagPos.x,
    upContainerFlagPos.y);

  if (lookResults.length) {
    let upContainer = lookResults[0];
    return upContainer;
  }

  return 0;
}

/**
Repair the upContainer. Note that this function does not move the creep towards
the upContainer.
@param {Creep} creep
*/
function repairUpContainer(creep) {
  let upContainer = getUpContainer(creep);
  if (upContainer && upContainer.hits < upContainer.hitsMax) {
    creep.repair(upContainer);
  }
}

module.exports = {
  gatherFromClosestSource,
  dropOffEnergyAtNearbyStructure,
  pickupBiggestEnergyPile,
  upgradeRoomController,
  retrieveEnergyForUpgrading,
  getUpContainer,
  repairUpContainer
};
<commit_msg>Added check in getUpContainer for whether or not a flag was found.<commit_after>/**
Gather from the nearest source.
@param {Creep} creep
*/
function gatherFromClosestSource(creep) {
  let sources = creep.room.find(FIND_SOURCES);
  if (creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
    creep.moveTo(sources[0], {
      visualizePathStyle: {
        stroke: '#ffaa00'
      }
    });
  }
}

/**
Drop off energy at a structure that is not full of energy. Prioritizes spawns.
@param {Creep} creep
*/
function dropOffEnergyAtNearbyStructure(creep) {
  let targets = creep.room.find(FIND_STRUCTURES, {
    filter: (structure) => {
      return (structure.structureType == STRUCTURE_EXTENSION ||
          structure.structureType == STRUCTURE_SPAWN ||
          structure.structureType == STRUCTURE_TOWER ||
          structure.structureType == STRUCTURE_CONTAINER) &&
        structure.energy < structure.energyCapacity ||
        (structure.store && structure.store[RESOURCE_ENERGY] < structure.storeCapacity);
    }
  });

  if (targets.length > 0) {
    let target = targets[0];
    for (let i = 1; i < targets.length; i++) {
      if (targets[i].structureType == STRUCTURE_SPAWN ||
        targets[i].structureType == STRUCTURE_EXTENSION) {
        target = targets[i];
      }
    }
    if (creep.transfer(target, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
      creep.moveTo(target, {
        visualizePathStyle: {
          stroke: '#ffffff'
        }
      });
    }
  }
}

/**
Find the biggest dropped pile of energy in the room and pick it up.
@param {Creep} creep
*/
function pickupBiggestEnergyPile(creep) {
  let droppedResources = creep.room.find(FIND_DROPPED_RESOURCES, {
    filter: {
      resourceType: RESOURCE_ENERGY
    }
  });
  if (droppedResources.length) {
    //determine which pile of resources is biggest
    let biggestResource = droppedResources[0];
    if (droppedResources.length > 1) {
      for (let i = 1; i < droppedResources.length; i++) {
        if (droppedResources[i].amount > biggestResource.amount) {
          biggestResource = droppedResources[i];
        }
      }
    }
    if (creep.pickup(biggestResource) == ERR_NOT_IN_RANGE) {
      creep.moveTo(biggestResource, {
        visualizePathStyle: {
          stroke: '#ffaa00'
        }
      });
    }
  }
}

/**
Upgrade this rooms controller.
@param {Creep} creep
*/
function upgradeRoomController(creep) {
  creep.upgradeController(creep.room.controller);
  if (!creep.pos.isNearTo(creep.room.controller)) {
    creep.moveTo(creep.room.controller, {
      visualizePathStyle: {
        stroke: '#ffffff'
      }
    });
  }
}

/**
Retrieve energy from an upgrader container. If one is not found,
retrieve energy from spawn.
@param {Creep} creep
*/
function retrieveEnergyForUpgrading(creep) {
  let upContainer = getUpContainer(creep);
  if (getUpContainer) {
    if (creep.withdraw(upContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
      creep.moveTo(upContainer, {
        visualizePathStyle: {
          stroke: '#ffaa00'
        }
      });
    }
  } else {
    //if not found, check for spawn and retrieve from there.
    let spawns = creep.room.find(FIND_MY_STRUCTURES, {
      filter: {
        structureType: STRUCTURE_SPAWN
      }
    });
    if (creep.withdraw(spawns[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
      creep.moveTo(spawns[0], {
        visualizePathStyle: {
          stroke: '#ffaa00'
        }
      });
    }
  }
}

/**
returns the upContainer for the creep's room. If there is no upContainer,
returns 0.
@param {Creep} creep
*/
function getUpContainer(creep) {
  let upContainerFlagPos = Memory.flags[creep.room.name + " upContainer"];
  if (upContainerFlagPos) {
    let lookResults = creep.room.lookForAt(LOOK_STRUCTURES,
      upContainerFlagPos.x,
      upContainerFlagPos.y);

    if (lookResults.length) {
      let upContainer = lookResults[0];
      return upContainer;
    }
  }

  return 0;
}

/**
Repair the upContainer. Note that this function does not move the creep towards
the upContainer.
@param {Creep} creep
*/
function repairUpContainer(creep) {
  let upContainer = getUpContainer(creep);
  if (upContainer && upContainer.hits < upContainer.hitsMax) {
    creep.repair(upContainer);
  }
}

module.exports = {
  gatherFromClosestSource,
  dropOffEnergyAtNearbyStructure,
  pickupBiggestEnergyPile,
  upgradeRoomController,
  retrieveEnergyForUpgrading,
  getUpContainer,
  repairUpContainer
};
<|endoftext|>


<commit_before>module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  reporters: ['default', 'jest-junit'],
  collectCoverage: true,
  transformIgnorePatterns: ['node_modules/(?!(argo-ui)/)'],
  globals: {
    'window': {localStorage: { getItem: () => '{}', setItem: () => null }},
    'ts-jest': {
      isolatedModules: true,
    },
  },
  moduleNameMapper: {
    // https://github.com/facebook/jest/issues/3094
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/__mocks__/fileMock.js',
    '.+\\.(css|styl|less|sass|scss)$': 'jest-transform-css',
  },
};

const localStorageMock = (() => {
  const store = {};
  return {
    getItem: (key) => store[key],
    setItem: (key, value) => {
      store[key] = value.toString();
    },
    clear: () => {
      store = {};
    },
    removeItem: (key) => {
      delete store[key];
    }
  };
})();
global.localStorage = localStorageMock;<commit_msg>fix: Correct this attempt to modify const 'store' variable (#7145)<commit_after>module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  reporters: ['default', 'jest-junit'],
  collectCoverage: true,
  transformIgnorePatterns: ['node_modules/(?!(argo-ui)/)'],
  globals: {
    'window': {localStorage: { getItem: () => '{}', setItem: () => null }},
    'ts-jest': {
      isolatedModules: true,
    },
  },
  moduleNameMapper: {
    // https://github.com/facebook/jest/issues/3094
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/__mocks__/fileMock.js',
    '.+\\.(css|styl|less|sass|scss)$': 'jest-transform-css',
  },
};

const localStorageMock = (() => {
  let store = {};
  return {
    getItem: (key) => store[key],
    setItem: (key, value) => {
      store[key] = value.toString();
    },
    clear: () => {
      store = {};
    },
    removeItem: (key) => {
      delete store[key];
    }
  };
})();
global.localStorage = localStorageMock;<|endoftext|>


<commit_before>/* jshint strict:false */
module.exports = function(grunt) {

    // RequireJS task settings
    //
    // If we're compiling asimov-core then we only need to compile the one file
    // If we're compiling themes or components we need to walk directories to
    // find what modules we need to build
    var path = require('path'),
        _ = require('lodash'),
        fs = require('fs'),
        pkg = grunt.config.get('asimov.pkg'),
        bower = grunt.config.get('asimov.bower'),
        isTheme = bower.name.indexOf('-theme-') !== -1,
        options = {
            options: {
                logLevel: 3,
                optimize: 'none',
                keepBuildDir: true,
                removeCombined: true,
                shim: pkg.asimov.requirejs.shim || {},
                paths: pkg.asimov.requirejs.paths || {}
            }
        }
    ;

    // Are we're compiling a asimov-core?
    //
    // Then we only need to compile core.js

    if (bower.name === 'asimov-core') {
        options = { all: _.merge({
            options: {
                baseUrl: 'src/js',
                name: 'asimov/core',
                out: 'dist/js/asimov/core.js'
            }
        }, options) };
    }

    // Are we're compiling something theme-like?
    //
    // Then we create requirejs modules for file to be compiled.
    // To do this we need to check all the installed components
    // to see if they have any javascript to compile.

    else {

        // Find all the root level javascript files in each component
        //
        // These are the files we'll actually compile. They should be resolving
        // their dependencies locally given the paths and metadata at correct.

        options = _.merge(
            options, require('../lib/requirejs-components')(grunt, options)
        );
    }

    // Are we're compiling a component?
    //
    // We compile all the root level javascript files as modules.
    // This is what themes do, but they do it for all components.

    // I'm not sure this works since this refactor, and since no components
    // currently expect this behaviour I've disabled it for now.

    // else {
    //     options = { all: _.merge({
    //         options: {
    //             baseUrl: '<%= paths.js.src %>',
    //             dir: '<%= paths.js.dist %>',
    //             paths: pkg.asimov.requirejs.paths,
    //             modules: grunt.file.expand({ cwd: 'src/js' }, '*.js')
    //                 .map(function (file) {
    //                     return { name: file.replace(/\.js$/, '') };
    //                 })
    //         }
    //     }, options) };
    // }

    grunt.config('requirejs', options);

};
<commit_msg>feat(requirejs): merge options with existing requirejs options<commit_after>/* jshint strict:false */
module.exports = function(grunt) {

    // RequireJS task settings
    //
    // If we're compiling asimov-core then we only need to compile the one file
    // If we're compiling themes or components we need to walk directories to
    // find what modules we need to build
    var path = require('path'),
        _ = require('lodash'),
        fs = require('fs'),
        pkg = grunt.config.get('asimov.pkg'),
        bower = grunt.config.get('asimov.bower'),
        isTheme = bower.name.indexOf('-theme-') !== -1,
        options = {
            options: _.merge({
                logLevel: 3,
                optimize: 'none',
                keepBuildDir: true,
                removeCombined: true,
                shim: pkg.asimov.requirejs.shim || {},
                paths: pkg.asimov.requirejs.paths || {}
            }, grunt.config('requirejs.options'))
        }
    ;

    // Are we're compiling a asimov-core?
    //
    // Then we only need to compile core.js

    if (bower.name === 'asimov-core') {
        options = { all: _.merge({
            options: {
                baseUrl: 'src/js',
                name: 'asimov/core',
                out: 'dist/js/asimov/core.js'
            }
        }, options) };
    }

    // Are we're compiling something theme-like?
    //
    // Then we create requirejs modules for file to be compiled.
    // To do this we need to check all the installed components
    // to see if they have any javascript to compile.

    else {

        // Find all the root level javascript files in each component
        //
        // These are the files we'll actually compile. They should be resolving
        // their dependencies locally given the paths and metadata at correct.

        options = _.merge(
            options, require('../lib/requirejs-components')(grunt, options)
        );
    }

    // Are we're compiling a component?
    //
    // We compile all the root level javascript files as modules.
    // This is what themes do, but they do it for all components.

    // I'm not sure this works since this refactor, and since no components
    // currently expect this behaviour I've disabled it for now.

    // else {
    //     options = { all: _.merge({
    //         options: {
    //             baseUrl: '<%= paths.js.src %>',
    //             dir: '<%= paths.js.dist %>',
    //             paths: pkg.asimov.requirejs.paths,
    //             modules: grunt.file.expand({ cwd: 'src/js' }, '*.js')
    //                 .map(function (file) {
    //                     return { name: file.replace(/\.js$/, '') };
    //                 })
    //         }
    //     }, options) };
    // }

    grunt.config('requirejs', options);

};
<|endoftext|>


<commit_before>//author: Blair Vanderhoof
//https://github.com/blairvanderhoof/gist-embed
$(function(){
  var gistMarkerId = 'gist-';

  //find all code elements containing "gist-" the id attribute.
  $('code[id*="'+gistMarkerId+'"]').each(function(){
    var $elem = $(this),
      id,
      url,
      file,
      line,
      data = {};

    id = $elem.attr('id') || '';
    file = $elem.attr('data-file');
    line = $elem.attr('data-line');
    splittedFileName = file.split('.').join('-');

    if(file){
      data.file = file;
    }

    //if the id doesn't begin with 'gist-', then ignore the code block
    if (!id || id.indexOf('gist-') !== 0) return false;

    //make block level so loading text shows properly
    $elem.css('display', 'block');

    //get the numeric id from the id attribute of the element holder
    id = id.substr(0, gistMarkerId.length) === gistMarkerId ? id.replace(gistMarkerId, '') : null;

    //make sure result is a numeric id
    if(!isNaN(parseInt(id, 10))){
      url = 'https://gist.github.com/' + id + '.json';
      //loading
      $elem.html('Loading gist ' + url + (data.file ? ', file: ' + data.file : '') + '...');
      //request the json version of this gist
      $.ajax({
        url: url,
        data: data,
        dataType: 'jsonp',
        timeout: 10000,
        success: function(response){
          //the html payload is in the div property
          if(response && response.div){
            //add the stylesheet if it does not exist
            if(response.stylesheet && $('link[href="' + response.stylesheet + '"]').length === 0){
              var l = document.createElement("link"),
                head = document.getElementsByTagName("head")[0];

              l.type = "text/css";
              l.rel = "stylesheet";
              l.href = response.stylesheet;
              head.insertBefore(l, head.firstChild);
            }
            if(line){
              var lineNumbers = getLineNumbers(line);
              console.log(lineNumbers);
              var lineCodes = new Array(lineNumbers.length);

              for(var i = 0; i < lineNumbers.length; i++){
                if($(response.div).find('#file-' + splittedFileName + '-LC' + lineNumbers[i])[0]){
                  lineCodes[i] = $(response.div).find('#file-' + splittedFileName + '-LC' + lineNumbers[i])[0].innerHTML;
                }
              }
              $elem.html(basicStructureForMultipleLines(id, lineCodes, splittedFileName));
            }
            else{
              $elem.html(response.div);
            }
          }else{
            $elem.html('Failed loading gist ' + url);
          }
        },
        error: function(){
          $elem.html('Failed loading gist ' + url);
        }
      });
    }else{
      $elem.html('Failed loading gist with incorrect id format: ' + $elem.attr('id'));
    }
  });
});

function getLineNumbers(lineRangeString){
  var lineNumbers = new Array();
  var lineNumberSections = lineRangeString.split(',');
  for(var k = 0; k < lineNumberSections.length; k++){
    var range = lineNumberSections[k].split('-');
    if(range.length == 2){
      for(var i = range[0]; i <= range[1]; i++){
        lineNumbers.push(i);
      }
    }
    else if(range.length == 1){
      lineNumbers.push(range[0]);
    }
  }
  return lineNumbers;
}

function basicStructureForMultipleLines(gistId, lineCodes, splittedFileName){
  html = '

' +
         '

' +
         '
' +
         '

';
  for(var i = 0; i < lineCodes.length; i++){
    html += '
' +
    lineCodes[i] + '
';
  }
  html += '

';
}
<commit_msg>debugging<commit_after>//author: Blair Vanderhoof
//https://github.com/blairvanderhoof/gist-embed
$(function(){
  var gistMarkerId = 'gist-';

  //find all code elements containing "gist-" the id attribute.
  $('code[id*="'+gistMarkerId+'"]').each(function(){
    var $elem = $(this),
      id,
      url,
      file,
      line,
      data = {};

    id = $elem.attr('id') || '';
    file = $elem.attr('data-file');
    line = $elem.attr('data-line');
    splittedFileName = file.split('.').join('-');

    if(file){
      data.file = file;
    }

    //if the id doesn't begin with 'gist-', then ignore the code block
    if (!id || id.indexOf('gist-') !== 0) return false;

    //make block level so loading text shows properly
    $elem.css('display', 'block');

    //get the numeric id from the id attribute of the element holder
    id = id.substr(0, gistMarkerId.length) === gistMarkerId ? id.replace(gistMarkerId, '') : null;

    //make sure result is a numeric id
    if(!isNaN(parseInt(id, 10))){
      url = 'https://gist.github.com/' + id + '.json';
      //loading
      $elem.html('Loading gist ' + url + (data.file ? ', file: ' + data.file : '') + '...');
      //request the json version of this gist
      $.ajax({
        url: url,
        data: data,
        dataType: 'jsonp',
        timeout: 10000,
        success: function(response){
          //the html payload is in the div property
          if(response && response.div){
            //add the stylesheet if it does not exist
            if(response.stylesheet && $('link[href="' + response.stylesheet + '"]').length === 0){
              var l = document.createElement("link"),
                head = document.getElementsByTagName("head")[0];

              l.type = "text/css";
              l.rel = "stylesheet";
              l.href = response.stylesheet;
              head.insertBefore(l, head.firstChild);
            }
            if(line){
              var lineNumbers = getLineNumbers(line);
              var lineCodes = new Array(lineNumbers.length);

              for(var i = 0; i < lineNumbers.length; i++){
                if($(response.div).find('#file-' + splittedFileName + '-LC' + lineNumbers[i])[0]){
                  lineCodes[i] = $(response.div).find('#file-' + splittedFileName + '-LC' + lineNumbers[i])[0].innerHTML;
                  console.log(lineCodes[i]);
                }
              }
              $elem.html(basicStructureForMultipleLines(id, lineCodes, splittedFileName));
            }
            else{
              $elem.html(response.div);
            }
          }else{
            $elem.html('Failed loading gist ' + url);
          }
        },
        error: function(){
          $elem.html('Failed loading gist ' + url);
        }
      });
    }else{
      $elem.html('Failed loading gist with incorrect id format: ' + $elem.attr('id'));
    }
  });
});

function getLineNumbers(lineRangeString){
  var lineNumbers = new Array();
  var lineNumberSections = lineRangeString.split(',');
  for(var k = 0; k < lineNumberSections.length; k++){
    var range = lineNumberSections[k].split('-');
    if(range.length == 2){
      for(var i = range[0]; i <= range[1]; i++){
        lineNumbers.push(i);
      }
    }
    else if(range.length == 1){
      lineNumbers.push(range[0]);
    }
  }
  return lineNumbers;
}

function basicStructureForMultipleLines(gistId, lineCodes, splittedFileName){
  html = '

' +
         '

' +
         '
' +
         '

';
  for(var i = 0; i < lineCodes.length; i++){
    html += '
' +
    lineCodes[i] + '
';
  }
  html += '

';
}
<|endoftext|>


<commit_before>'use strict';

// PowJS Template engine https://github.com/powjs/powjs
// MIT License https://github.com/powjs/powjs/blob/master/LICENSE

const TEXT_NODE = 3,
	COMMENT_NODE = 8,
	// 因 toScript 有硬依赖, 该次序不能变
	TAG = 0,
	ATTRS = 1,
	CHILDS = 2,
	FN = 3,
	toString = Object.prototype.toString,
	TMPL = /{{|}}/m,
	directives = Object.create(null);

directives.args = function(args) {
	throw new Error('never used');
}

directives.if = function(exp) {
	throw new Error('never used');
}

directives.let = function(exp) {
	return exp && 'var ' + exp + ';' || ';';
}
directives.do = function(exp) {
	return exp + ';';
}
directives.text = function(exp) {
	return 'return this.text(' + exp + ');'
}
directives.html = function(exp) {
	return 'return this.html(' + exp + ');'
}

directives.skip = function(exp) {
	return !exp && 'return;' ||
		'if(' + exp + ') return;';
}
directives.end = function(exp) {
	return !exp && 'return this.end();' ||
		'if(' + exp + ') return this.end();';
}
directives.render = function(args) {
	return 'return this.render(' + args + ')';
}
directives.each = function(args) {
	return 'return this.each(' + args + ')';
}

module.exports = function Pow(source, mixed, renderArgs) {
	let view = [],
		prefix = '',
		discard = [];

	if (typeof mixed === 'object') {
		prefix = mixed.prefix || '';
		discard = !mixed.discard ? discard :
			(typeof mixed.discard === 'string' && [mixed.discard] ||
			Array.isArray(mixed.discard) && mixed.discard || []);
	}

	if (typeof source === 'string')
		source = firstChild(source);

	if (source instanceof Node)
		compile(view, source, prefix, discard, 'v,k');
	else if (Array.isArray(source))
		view = source;
	let pow = new PowJS(
		document.createDocumentFragment()
			.appendChild(document.createElement('BODY')),
		view,
		typeof mixed === 'object' && mixed || Object.create(null)
	);

	if (Array.isArray(renderArgs) || mixed instanceof Node) {
		pow.render.apply(pow, renderArgs);
		if (mixed instanceof Node &&
			typeof mixed.replaceWith === 'function')
			mixed.replaceWith(pow.firstChild());
	}
	return pow;
}

function firstChild(source) {
	let b = document.createDocumentFragment()
		.appendChild(document.createElement('BODY'));

	b.innerHTML = source.trim();
	return b.firstChild;
}

function PowJS(parent, view, context) {
	context.node = null;
	this.parent = parent;
	this.view = view;
	this.$ = context;
}

function toScript(_, view) {
	// 固定次序 [TAG,ATTRS,CHILDS,FN]
	return '["' + view[TAG] + '",' +

		JSON.stringify(view[ATTRS]) +

		(view[CHILDS] && view[CHILDS].length &&
		',[' + view[CHILDS].reduce(toScript, '') + '],' || ',null,') +

		(view[FN] && view[FN].toString()
			.replace(/^function anonymous\(/, 'function (')
			.replace("\n/*``*/", '')) + ']' || 'null';
}

PowJS.prototype.export = function() {
	return (this.view && this.view.length) &&
		toScript('', this.view) || '[]';
}

PowJS.prototype.childNodes = function() {
	return this.parent.childNodes;
}

PowJS.prototype.firstChild = function() {
	return this.parent.firstChild;
}

PowJS.prototype.node = function() {
	return this.$.node
}

PowJS.prototype.create = function() {
	let tag = this.view[TAG],
		attrs = this.view[ATTRS];

	this.$.node = this.parent.appendChild(
		tag == '#text' &&
		document.createTextNode('') ||
		document.createElement(tag)
	);

	for (let key in attrs)
		this.$.node.setAttribute(key, attrs[key]);
}

PowJS.prototype.render = function(...args) {
	let node = this.$.node;
	// 根调用, 自创建
	if (!node)
		return this.view[FN].apply(this, args);
	// 渲染子节点
	for (let view of this.view[CHILDS] || []) {
		if (this.$.flag) break;
		new PowJS(node, view, this.$).render(...args);
	}
	// 恢复
	this.$.node = node;
	if (this.$.flag != -1)
		this.$.flag = 0;
}

PowJS.prototype.each = function(iterator, ...args) {
	let k = 0,
		i = args.length;

	// 根调用
	if (!this.$.node) {
		this.$.flag = 1;
		this.view[FN].apply(this, args);
	}

	args = args.concat([null, null]);

	if (toString.call(iterator) == '[object Object]') {
		for (k in iterator) {
			if (this.$.flag) break;
			args[i] = iterator[k];
			args[i + 1] = k;
			this.render.apply(this, args);
		}
	} else {
		for (let v of iterator) {
			if (this.$.flag) break;
			args[i] = v;
			args[i + 1] = k++;
			this.render.apply(this, args);
		}
	}
	if (this.$.flag != 1)
		this.$.flag = 0;
}

PowJS.prototype.text = function(text) {
	if (text == null)
		return this.$.node.textContent;
	this.$.node.textContent = text + '';
}

PowJS.prototype.html = function(html) {
	let node = this.node();
	if (html == null)
		return node.innerHTML || node.textContent;

	if (node.nodeType == TEXT_NODE)
		this.$.node.textContent = html + '';
	else
		this.$.node.innerHTML = html + '';
}

PowJS.prototype.end = function() {
	this.$.flag = -1
}

PowJS.prototype.attr = function(key, val) {
	if (typeof key !== 'string') return;
	if (val === undefined)
		return this.$.node.hasAttribute(key)
			? this.$.node.getAttribute(key)
			: this.$.node[key];
	this.$.node.setAttribute(key, val);
}

PowJS.prototype.slice = function(array, start, end) {
	return Array.prototype.slice.call(array, start, end)
}

function compile(view, node, prefix, discard, args) {
	let body = '',
		render = '',
		each = '';

	if (node.nodeType === TEXT_NODE) {
		body = parseTemplate(node.textContent.trim());
		if (body) {
			view[TAG] = '#text';
			view[ATTRS] = view[CHILDS] = null;
			view[FN] = Function(
				args,
				'this.create();' + body);
		}
		return;
	}

	view[TAG] = node.nodeName;
	view[ATTRS] = view[CHILDS] = null;
	if (node.hasAttribute(prefix + 'args')) {
		args = (node.getAttribute(prefix + 'args') || '').trim();
	}

	if (node.hasAttribute(prefix + 'if')) {
		body = (node.getAttribute(prefix + 'if') || '').trim();

		body = 'if(!(' + (body || '0') + ')) return;';
	}
	body += 'this.create();';

	for (let i = 0; i < node.attributes.length; i++) {
		let attr = node.attributes[i],
			di = directives[
				prefix && attr.name.startsWith(prefix) ?
					attr.name.slice(prefix.length) : attr.name],

			name = !di && attr.name || attr.name.slice(prefix.length),
			val = attr.value.trim();

		if (!di) {
			if (discard && discard.indexOf(name) == -1) {
				view[ATTRS] = view[ATTRS] || Object.create(null);
				view[ATTRS][name] = val;
			}
			continue;
		}
		if (name == 'if' || name == 'args') continue;

		if (!each && !render) {
			render = name == 'render' && val || '';
			each = name == 'each' && val || '';
		}

		body += di(val);
	}

	if (!render && !each)
		body += directives.render(args);
	view[FN] = new Function(args, body);
	for (let i = 0; i < node.childNodes.length; i++) {
		if (node.childNodes[i].nodeType == COMMENT_NODE)
			continue;

		let v = [];
		compile(v, node.childNodes[i], prefix, discard, args);
		if (v.length) {
			view[CHILDS] = view[CHILDS] || [];
			view[CHILDS].push(v);
		}
	}
}

function parseTemplate(txt) {
	if (!txt) return '';

	if (txt.indexOf('{{') == -1)
		return directives.text(JSON.stringify(txt));
	let a = txt.split(TMPL);
	if (a.length & 1 == 0)
		throw new Error('The symbols "{{}}" unpaired: ' + txt);
	txt = '';
	for (let i = 0; i < a.length; i++) {
		if (!a[i]) continue;
		txt += '+' + (i & 1 ? '(' + a[i] + ')' : JSON.stringify(a[i]));
	}

	return directives.text(txt.slice(1));
}
<commit_msg>bug, each and export<commit_after>'use strict';

// PowJS Template engine https://github.com/powjs/powjs
// MIT License https://github.com/powjs/powjs/blob/master/LICENSE

const TEXT_NODE = 3,
	COMMENT_NODE = 8,
	// 因 toScript 有硬依赖, 该次序不能变
	TAG = 0,
	ATTRS = 1,
	CHILDS = 2,
	FN = 3,
	toString = Object.prototype.toString,
	slice = Array.prototype.slice,
	TMPL = /{{|}}/m,
	directives = Object.create(null);

directives.param = function(args) {
	return args;
}

directives.if = function(exp) {
	return 'if(!(' + (exp || '0') + ')) return;';
}

directives.let = function(exp) {
	return exp && 'var ' + exp + ';' || ';';
}
directives.do = function(exp) {
	return exp + ';';
}
directives.text = function(exp) {
	return 'return this.text(' + exp + ');'
}
directives.html = function(exp) {
	return 'return this.html(' + exp + ');'
}

directives.skip = function(exp) {
	return !exp && 'return;' ||
		'if(' + exp + ') return;';
}
directives.end = function(exp) {
	return !exp && 'return this.end();' ||
		'if(' + exp + ') return this.end();';
}
directives.render = function(args) {
	return 'return this.render(' + args + ')';
}
directives.each = function(args) {
	return 'return this.each(' + args + ')';
}

module.exports = function Pow(source, mixed, renderArgs) {
	let view = [],
		prefix = '',
		discard = [];

	if (typeof mixed === 'object') {
		prefix = mixed.prefix || '';
		discard = !mixed.discard ? discard :
			(typeof mixed.discard === 'string' && [mixed.discard] ||
			Array.isArray(mixed.discard) && mixed.discard || []);
	}

	if (typeof source === 'string')
		source = firstChild(source);

	if (source instanceof Node)
		compile(view, source, prefix, discard, 'v,k');
	else if (Array.isArray(source))
		view = source;
	let pow = new PowJS(
		document.createDocumentFragment()
			.appendChild(document.createElement('BODY')),
		view,
		typeof mixed === 'object' && mixed || Object.create(null)
	);

	if (Array.isArray(renderArgs) || mixed instanceof Node) {
		pow.render.apply(pow, renderArgs);
		if (mixed instanceof Node &&
			typeof mixed.replaceWith === 'function')
			mixed.replaceWith(pow.firstChild());
	}
	return pow;
}

function firstChild(source) {
	let b = document.createDocumentFragment()
		.appendChild(document.createElement('BODY'));

	b.innerHTML = source.trim();
	return b.firstChild;
}

function PowJS(parent, view, context) {
	context.node = null;
	context.flag = 0;
	this.parent = parent;
	this.view = view;
	this.$ = context;
}

function toScript(sum, view) {
	// 固定次序 [TAG,ATTRS,CHILDS,FN]
	return sum + (!!sum && ',' || '') + '["' + view[TAG] + '",' +

		JSON.stringify(view[ATTRS]) +

		(view[CHILDS] && view[CHILDS].length &&
		',[' + view[CHILDS].reduce(toScript, '') + '],' || ',null,') +

		(view[FN] && view[FN].toString()
			.replace(/^function anonymous\(/, 'function (')
			.replace("\n/*``*/", '') || 'null') + ']';
}

PowJS.prototype.export = function() {
	return (this.view && this.view.length) &&
		toScript('', this.view) || 'null';
}

PowJS.prototype.childNodes = function() {
	return this.parent.childNodes;
}

PowJS.prototype.firstChild = function() {
	return this.parent.firstChild;
}

PowJS.prototype.node = function() {
	return this.$.node
}

PowJS.prototype.create = function() {
	let tag = this.view[TAG],
		attrs = this.view[ATTRS];

	this.$.node = this.parent.appendChild(
		tag == '#text' &&
		document.createTextNode('') ||
		document.createElement(tag)
	);

	for (let key in attrs)
		this.$.node.setAttribute(key, attrs[key]);
}

PowJS.prototype.render = function() {
	let args = slice.call(arguments, 0);

	if (!this.$.node)
		return this.view[FN].apply(this, args);
	each(this.$, this.view[CHILDS], args);
}

function each($, views, args) {
	let node = $.node;
	views && views.some(function(view) {
		if ($.flag) return true;
		let pow = new PowJS(node, view, $);
		pow.render.apply(pow, args);
	})
	$.node = node;
}

PowJS.prototype.each = function(iterator) {
	let k = 0,
		views = this.view[CHILDS],
		args = slice.call(arguments, 1),
		i = args.length;

	// 根调用
	if (!this.$.node) {
		this.view[CHILDS] = null;
		this.view[FN].apply(this, args);
		this.view[CHILDS] = views;
	}

	args = args.concat([null, null]);

	if (toString.call(iterator) == '[object Object]') {
		for (k in iterator) {
			if (this.$.flag) break;
			args[i] = iterator[k];
			args[i + 1] = k;
			each(this.$, views, args);
		}
	} else {
		for (let v of iterator) {
			if (this.$.flag) break;
			args[i] = v;
			args[i + 1] = k++;
			each(this.$, views, args);
		}
	}
}

PowJS.prototype.text = function(text) {
	if (text == null)
		return this.$.node.textContent;
	this.$.node.textContent = text + '';
}

PowJS.prototype.html = function(html) {
	let node = this.node();
	if (html == null)
		return node.innerHTML || node.textContent;

	if (node.nodeType == TEXT_NODE)
		this.$.node.textContent = html + '';
	else
		this.$.node.innerHTML = html + '';
}

PowJS.prototype.end = function() {
	this.$.flag = -1
}

PowJS.prototype.attr = function(key, val) {
	if (typeof key !== 'string') return;
	if (val === undefined)
		return this.$.node.hasAttribute(key)
			? this.$.node.getAttribute(key)
			: this.$.node[key];
	this.$.node.setAttribute(key, val);
}

PowJS.prototype.slice = function(array, start, end) {
	return slice.call(array, start, end)
}

function compile(view, node, prefix, discard, args) {
	let body = '',
		render = '',
		each = '';

	if (node.nodeType === TEXT_NODE) {
		body = parseTemplate(node.textContent.trim());
		if (body) {
			view[TAG] = '#text';
			view[ATTRS] = view[CHILDS] = null;
			view[FN] = Function(
				args,
				'this.create();' + body);
		}
		return;
	}

	view[TAG] = node.nodeName;
	view[ATTRS] = view[CHILDS] = null;
	if (node.hasAttribute(prefix + 'param')) {
		args = directives.param((node.getAttribute(prefix + 'param') || '').trim());
	}

	if (node.hasAttribute(prefix + 'if')) {
		body = directives.if((node.getAttribute(prefix + 'if') || '').trim() || '0');
	}

	body += 'this.create();';

	for (let i = 0; i < node.attributes.length; i++) {
		let attr = node.attributes[i],
			di = directives[
				prefix && attr.name.startsWith(prefix) ?
					attr.name.slice(prefix.length) : attr.name],

			name = !di && attr.name || attr.name.slice(prefix.length),
			val = attr.value.trim();

		if (!di) {
			if (discard && discard.indexOf(name) == -1) {
				view[ATTRS] = view[ATTRS] || Object.create(null);
				view[ATTRS][name] = val;
			}
			continue;
		}
		if (name == 'if' || name == 'param') continue;

		if (!each && !render) {
			render = name == 'render' && val || '';
			each = name == 'each' && val || '';
		}

		body += di(val);
	}

	if (!render && !each)
		body += directives.render(args);

	view[FN] = new Function(args, body);
	for (let i = 0; i < node.childNodes.length; i++) {
		if (node.childNodes[i].nodeType == COMMENT_NODE)
			continue;

		let v = [];
		compile(v, node.childNodes[i], prefix, discard, args);
		if (v.length) {
			view[CHILDS] = view[CHILDS] || [];
			view[CHILDS].push(v);
		}
	}
}

function parseTemplate(txt) {
	if (!txt) return '';

	if (txt.indexOf('{{') == -1)
		return directives.text(JSON.stringify(txt));
	let a = txt.split(TMPL);
	if (a.length & 1 == 0)
		throw new Error('The symbols "{{}}" unpaired: ' + txt);
	txt = '';
	for (let i = 0; i < a.length; i++) {
		if (!a[i]) continue;
		txt += '+' + (i & 1 ? '(' + a[i] + ')' : JSON.stringify(a[i]));
	}

	return directives.text(txt.slice(1));
}
<|endoftext|>


<commit_before>(function(host) {

    var outputLineSeparator = "\n",
        directivesStack = [];

    function getOutputLineSeparator(input) {
        return input.indexOf("\r\n") >= 0 ? "\r\n" : "\n";
    }

    function getDirectiveStackRepresentation() {
        return directivesStack.map(function(directive) {
            return directive.definition;
        }).join(",");
    }

    function IfDirective(definition, definedVariables, parentIfDirective) {
        var directiveMatch = /#ifdef +(\S*)?/.exec(definition);

        this.definition = definition;
        this.variableName = directiveMatch[1].toUpperCase();
        this.ignoreContent = (definedVariables.indexOf(this.variableName) < 0);

        if (parentIfDirective) {
            this.ignoreContent = this.ignoreContent || parentIfDirective.ignoreContent;
        }
    }

    IfDirective.prototype.processLine = function(line) {
        return this.ignoreContent ? "" : line + outputLineSeparator;
    };

    var exported = {
        preprocess: function(input, definedVariables) {
            var lines = input.split(/\r?\n/),
                output = "";

            if (typeof definedVariables == "string") {
                definedVariables = [definedVariables];
            }

            outputLineSeparator = getOutputLineSeparator(input);

            definedVariables = definedVariables.map(function(str) {
                return str.toUpperCase();
            });
            for (var i = 0; i < lines.length; i++) {
                var line = lines[i],
                    topIfDirective = directivesStack[directivesStack.length - 1];

                if (/#ifdef/.exec(line)) {
                    directivesStack.push(new IfDirective(line, definedVariables, topIfDirective));
                } else if (/#endif/.exec(line)) {
                    if (directivesStack.length == 0) {
                        throw new Error("Found #endif without opening directive");
                    }
                    directivesStack.pop();
                } else {
                    line = topIfDirective ? topIfDirective.processLine(line) : line + outputLineSeparator;

                    output = output + line;
                }
            };

            if (directivesStack.length > 0) {
                throw new Error("Unclosed if directives found " + getDirectiveStackRepresentation());
            };

            return output.substring(0, output.length - outputLineSeparator.length);
        }
    };

    if (module) {
        module.exports = exported;
    } else {
        host.prepr = exported;
    }
})(this);<commit_msg>Re-factored the implementation so that it can run asynchronously by multiple clients at the same time (which was the case when running the Jasmine specs in the Node environment) and even concurrently.<commit_after>(function(host) {

    function IfDirective(definition, definedVariables, outputLineSeparator, parentIfDirective) {
        var directiveMatch = /#ifdef +(\S*)?/.exec(definition);

        this.definition = definition;
        this.variableName = directiveMatch[1].toUpperCase();
        this.ignoreContent = (definedVariables.indexOf(this.variableName) < 0);
        this.outputLineSeparator = outputLineSeparator;

        if (parentIfDirective) {
            this.ignoreContent = this.ignoreContent || parentIfDirective.ignoreContent;
        }
    }

    IfDirective.prototype.processLine = function(line) {
        return this.ignoreContent ? "" : line + this.outputLineSeparator;
    };

    function Preprocessor(input, definedVariables) {
        this.input = input;

        if (typeof definedVariables == "string") {
            definedVariables = [definedVariables];
        }
        this.definedVariables = definedVariables.map(function(str) {
            return str.toUpperCase();
        });

        this.outputLineSeparator = input.indexOf("\r\n") >= 0 ? "\r\n" : "\n",
        this.directivesStack = [];
    }

    Preprocessor.prototype.run = function() {
        var lines = this.input.split(/\r?\n/),
            output = "";

        for (var i = 0; i < lines.length; i++) {
            var line = lines[i],
                topIfDirective = this.directivesStack[this.directivesStack.length - 1];

            if (/#ifdef/.exec(line)) {
                this.directivesStack.push(new IfDirective(line, this.definedVariables, this.outputLineSeparator, topIfDirective));
            } else if (/#endif/.exec(line)) {
                if (this.directivesStack.length == 0) {
                    throw new Error("Found #endif without opening directive");
                }
                this.directivesStack.pop();
            } else {
                line = topIfDirective ? topIfDirective.processLine(line) : line + this.outputLineSeparator;

                output = output + line;
            }
        };

        if (this.directivesStack.length > 0) {
            throw new Error("Unclosed if directives found " + this.getDirectiveStackRepresentation());
        };

        return output.substring(0, output.length - this.outputLineSeparator.length);
    };

    Preprocessor.prototype.getDirectiveStackRepresentation = function() {
        return this.directivesStack.map(function(directive) {
            return directive.definition;
        }).join(",");
    };

    var exported = {
        preprocess: function(input, definedVariables) {
            return new Preprocessor(input, definedVariables).run();
        }
    };

    if (module) {
        module.exports = exported;
    } else {
        host.prepr = exported;
    }
})(this);<|endoftext|>


<commit_before>import * as THREE from './lib/three';
import { loadModel } from './utils/three';
import settings from './settings';
import { recordCostumeColor, highlightColor } from './theme/colors';

import wallUrl from './public/models/obj/new-rooms/vr/first-wall.obj';

import roomUrl from './public/models/obj/new-rooms/vr/horizontal-room.obj';
// import roomTextureUrl from './public/models/obj/new-rooms/vr/bake/horizontal-room-AOMap.jpg';

import isometricWallUrl from './public/models/obj/new-rooms/first-wall.obj';
import isometricRoomUrl from './public/models/obj/new-rooms/horizontal-room.obj';
// import isometricRoomTextureUrl from './public/models/obj/new-rooms/bake/horizontal-room-AOMap.jpg';

const {
  Mesh,
  MeshLambertMaterial,
  MeshBasicMaterial,
  ConeBufferGeometry,
  CylinderBufferGeometry,
  SphereGeometry,
  GridHelper,
  Group,
} = THREE;

const controllerMaterial = new MeshLambertMaterial({ color: recordCostumeColor });

const props = {
  perspectiveWall: [wallUrl],
  perspectiveRoom: [roomUrl], // roomTextureUrl],
  orthographicWall: [isometricWallUrl],
  orthographicRoom: [isometricRoomUrl], // isometricRoomTextureUrl],
  hand: (function createHand() {
    const radius = 0.02;
    const height = 0.2;
    const segments = 32;
    const cylinder = new Mesh(
      new CylinderBufferGeometry(radius, radius, height, segments),
      new MeshLambertMaterial({ color: recordCostumeColor }),
    );

    cylinder.rotation.x = Math.PI * 0.5 * 7;
    cylinder.updateMatrix();
    cylinder.geometry.applyMatrix(cylinder.matrix);
    cylinder.castShadow = true;
    return cylinder;
  }()),

  controller: (function createHand() {
    const radius = 0.02;
    const height = 0.2;
    const segments = 32;
    const cylinder = new Mesh(
      new CylinderBufferGeometry(radius, radius, height, segments),
      controllerMaterial,
    );
    cylinder.rotation.x = Math.PI * 0.5 * 7;
    cylinder.updateMatrix();

    const thumbpadRadius = 0.015;
    const thumbpadHeight = 0.02;
    const thumbpad = new THREE.Mesh(
      new CylinderBufferGeometry(thumbpadRadius, thumbpadRadius, thumbpadHeight, segments),
      new MeshLambertMaterial({ color: settings.textColor })
    );
    thumbpad.name = 'button';
    thumbpad.position.z = -0.05;
    thumbpad.position.y = 0.01;
    thumbpad.updateMatrix();

    const group = new Group();

    group.add(cylinder, thumbpad);

    return group;
  }()),

  head: (function createHead() {
    const radius = 0.12;
    const height = 0.2;
    const segments = 32;
    const cone = new Mesh(
      new ConeBufferGeometry(radius, height, segments),
      new MeshLambertMaterial({ color: recordCostumeColor }),
    );

    cone.rotation.x = Math.PI * 0.5 * 7;
    cone.updateMatrix();
    cone.geometry.applyMatrix(cone.matrix);
    cone.castShadow = true;
    return cone;
  }()),

  sphere: (function createSphere() {
    const segments = 32;
    const geometry = new SphereGeometry(
      settings.sphereRadius,
      segments,
      segments,
    );
    const material = new MeshBasicMaterial({
      color: highlightColor.clone(),
    });
    const mesh = new Mesh(geometry, material);
    return mesh;
  }()),

  grid: (function createGrid() {
    return new GridHelper(50, 50, 0xaaaa00, 0xaaaa00);
  }()),

  prepare: () => Promise.all(
    Object.keys(props)
      .filter(id => Array.isArray(props[id]))
      .map(
        (id) => loadModel(props[id])
          .then((model) => {
            props[id] = model;
          })
      )
  ),
};

export default props;
<commit_msg>add room & wall textures<commit_after>import * as THREE from './lib/three';
import { loadModel } from './utils/three';
import settings from './settings';
import { recordCostumeColor, highlightColor } from './theme/colors';

import wallUrl from './public/models/obj/new-rooms/vr/first-wall.obj';

import roomUrl from './public/models/obj/new-rooms/vr/horizontal-room.obj';
import roomTextureUrl from './public/models/obj/new-rooms/vr/bake/horizontal-room-AOMap.jpg';

import isometricWallUrl from './public/models/obj/new-rooms/first-wall.obj';
import isometricRoomUrl from './public/models/obj/new-rooms/horizontal-room.obj';
import isometricRoomTextureUrl from './public/models/obj/new-rooms/bake/horizontal-room-AOMap.jpg';

const {
  Mesh,
  MeshLambertMaterial,
  MeshBasicMaterial,
  ConeBufferGeometry,
  CylinderBufferGeometry,
  SphereGeometry,
  GridHelper,
  Group,
} = THREE;

const controllerMaterial = new MeshLambertMaterial({ color: recordCostumeColor });

const props = {
  perspectiveWall: [wallUrl],
  perspectiveRoom: [roomUrl, roomTextureUrl],
  orthographicWall: [isometricWallUrl],
  orthographicRoom: [isometricRoomUrl, isometricRoomTextureUrl],
  hand: (function createHand() {
    const radius = 0.02;
    const height = 0.2;
    const segments = 32;
    const cylinder = new Mesh(
      new CylinderBufferGeometry(radius, radius, height, segments),
      new MeshLambertMaterial({ color: recordCostumeColor }),
    );

    cylinder.rotation.x = Math.PI * 0.5 * 7;
    cylinder.updateMatrix();
    cylinder.geometry.applyMatrix(cylinder.matrix);
    cylinder.castShadow = true;
    return cylinder;
  }()),

  controller: (function createHand() {
    const radius = 0.02;
    const height = 0.2;
    const segments = 32;
    const cylinder = new Mesh(
      new CylinderBufferGeometry(radius, radius, height, segments),
      controllerMaterial,
    );
    cylinder.rotation.x = Math.PI * 0.5 * 7;
    cylinder.updateMatrix();

    const thumbpadRadius = 0.015;
    const thumbpadHeight = 0.02;
    const thumbpad = new THREE.Mesh(
      new CylinderBufferGeometry(thumbpadRadius, thumbpadRadius, thumbpadHeight, segments),
      new MeshLambertMaterial({ color: settings.textColor })
    );
    thumbpad.name = 'button';
    thumbpad.position.z = -0.05;
    thumbpad.position.y = 0.01;
    thumbpad.updateMatrix();

    const group = new Group();

    group.add(cylinder, thumbpad);

    return group;
  }()),

  head: (function createHead() {
    const radius = 0.12;
    const height = 0.2;
    const segments = 32;
    const cone = new Mesh(
      new ConeBufferGeometry(radius, height, segments),
      new MeshLambertMaterial({ color: recordCostumeColor }),
    );

    cone.rotation.x = Math.PI * 0.5 * 7;
    cone.updateMatrix();
    cone.geometry.applyMatrix(cone.matrix);
    cone.castShadow = true;
    return cone;
  }()),

  sphere: (function createSphere() {
    const segments = 32;
    const geometry = new SphereGeometry(
      settings.sphereRadius,
      segments,
      segments,
    );
    const material = new MeshBasicMaterial({
      color: highlightColor.clone(),
    });
    const mesh = new Mesh(geometry, material);
    return mesh;
  }()),

  grid: (function createGrid() {
    return new GridHelper(50, 50, 0xaaaa00, 0xaaaa00);
  }()),

  prepare: () => Promise.all(
    Object.keys(props)
      .filter(id => Array.isArray(props[id]))
      .map(
        (id) => loadModel(props[id])
          .then((model) => {
            props[id] = model;
          })
      )
  ),
};

export default props;
<|endoftext|>


<commit_before>'use strict'

import Aliases from 'aliases.js';
import EventEmitter from 'event-emitter.js';

const RESPONSE = {
    array : 'arrayBuffer',
    blob : 'blob',
    form : 'formData',
    json : 'json',
    text : 'text'
}

const ATTR_LIST = {
    'container': ['psxhr-container', 'container'],
    'event': ['psxhr-event'],
    'observ': ['psxhr-observ'],
    'href':  ['psxhr-href', 'href', 'action'],
    'method': ['psxhr-method', 'method'],
    'state': ['psxhr-state'],
    'callback': ['psxhr-callback'],
    'interval': ['psxhr-interval'],
    'time': ['psxhr-time'],
    'response': ['psxhr-response',],
    'promise': ['psxhr-promise']
}

class PSXhr {

    static init() {

        Array.from(document.querySelectorAll('[psxhr="true"]'))
            .forEach( node => {
                let psxhr = new PSXhr(node);
                psxhr.start();
            });

    }

    constructor(node) {

        this._attr = {};
        this._events = new EventEmitter();
        this._events = {
            before: new EventEmitter(),
            after: new EventEmitter(),
            error: new EventEmitter(),
        }
        this._node = node;

    }

    set before(callback) {
        this._events.before.push(callback);
    }

    set after(callback) {
        this._events.after.push(callback);
    }

    set error(callback) {
        this._events.error.push(callback);
    }

    set container(container) { this._attr.container = container; }
    set event(event) { this._attr.event = event; }
    set observ(callback) { this._attr.observ = callback; }
    set href(href) { this._attr.href = href; }
    set method(method) { this._attr.method = method; }
    set state(bool) { this._attr.method = bool; }
    set callback(callback) { this._attr.callback = callback; }
    set interval(time) { this._attr.interval = time; }
    set time(time) { this._attr.time = time; }
    set response(responseType) { this._attr.response = responseType; }
    set promise(callback) { this._attr.promise = callback; }

    start() {

        this._checkAttribute(this._node);
        if (this._attr.observ) this._setObservServer();
        this._setEvent();

    }

    _setObservServer() {

        let pool = [];
        let callback = this._attr.observ;

        if (!this._callbackExsists(callback))
            return false;
        else
            callback = this._getCallback(callback);

        if (!this._attr.container)
            pool.push(this._node);
        else {

            let container = document.querySelectorAll(this._attr.container);

            if (!container) return false;

            Array.from(container).forEach( node => {
                pool.push(node);
            })

        }

        let mo = new MutationObserver( m => { callback(m); });

        let config = { attributes: true, childList: true, characterData: true };

        pool.forEach( node => {
            mo.observe(node, config);
        })

    }

    _checkAttribute() {

        let result = {};

        Object.keys(ATTR_LIST).map( attr => {
            let alias = new Aliases(attr, ATTR_LIST[attr]);
            let name = alias.check(attr, this._checkAlias.bind(this));
            result[attr] = name ? this._node.getAttribute(name) : false;
        })

        this._attr = Object.assign(result, this._attr);

    }

    _checkAlias(aliases) {

        let attributes = this._node.attributes;
        for (var alias of aliases)
            if (attributes.getNamedItem(alias)) return alias;
        return false;

    }

    _isForm() { return this._node.tagName == 'FORM'; }

    _setData() { this._data = new FormData(this.node); }

    _setEvent() {

        if (this._attr.event) {

            let eventList = this._attr.event.split(',');
            let node = this._node;

            eventList.map( event => {
                node.addEventListener(event, this._eventWrapper.bind(this), false);
            });

        }

        if (this._attr.time) {
            setTimeout(this._eventWrapper.bind(this), this._attr.time);
            this._attr.interval = false;
        }

        if (this._attr.interval)
            setInterval(this._eventWrapper.bind(this), this._attr.time);

    }

    _eventWrapper(e) {

        this._request();

        if (e) e.preventDefault();

    }

    _request() {

        let attr = this._attr;

        let data = {
            method: attr.method ? attr.method : 'GET',
            headers: {'X-REQUESTED-WITH': 'XMLHttpRequest'},
            credentials: 'same-origin'
        };

        if (data.method == 'POST') data.body = new FormData();
        else if (data.method == 'POST' && this._isForm())
            data.body = new FormData(this._node);

        var href = attr.href
            ? attr.href
            : window.location.href;

        if (JSON.parse(attr.state))
            history.pushState(null, '', href);

        let responseType = RESPONSE[attr.response]
            ? RESPONSE[attr.response]
            : 'text';

        fetch(href, data)
            .then( response => {

                if (this._events.before.emit(response) === false)
                    throw('Stop PSXhr');

                return response[responseType]();

            })
            .then( response => {

                if (this._dispatchCallback('callback', response))
                    return false;
                else
                    this._defaultHandler(response);

                return response;

            })
            .then( response => {

                this._events.after.emit(response)

            })
            .catch( error => {
                this._events.error.emit(error);
                console.log(error);
            });

    }

    _dispatchCallback(name, params) {

        let callback = this._attr[name];

        if (callback) {
            let fn = this._getCallback(callback);
            fn(params);
            return true;
        } else return false;

    }

    _callbackExsists(callbackName) {

        return typeof window[callbackName] === 'function' || typeof callbackName;

    }

    _getCallback(callbackName) {

        if (typeof callbackName === 'function')
            return callbackName;
        else if (typeof window[callbackName] == 'function')
            return window[callbackName];

    }

    _defaultHandler(res) {

        if (!this._attr.container) this._node.innerHTML = res;
        else {

            let container = document.querySelectorAll(this._attr.container);
            if (!container) return false;

            Array.from(container).forEach( node => {
                node.innerHTML = res;
            })

        }

    }

}

window.PSXhr = PSXhr;
<commit_msg>Deprecated callback for promise<commit_after>'use strict'

import Aliases from 'aliases.js';
import EventEmitter from 'event-emitter.js';

const RESPONSE = {
    array : 'arrayBuffer',
    blob : 'blob',
    form : 'formData',
    json : 'json',
    text : 'text'
}

const ATTR_LIST = {
    'container': ['psxhr-container', 'container'],
    'event': ['psxhr-event'],
    'observ': ['psxhr-observ'],
    'href':  ['psxhr-href', 'href', 'action'],
    'method': ['psxhr-method', 'method'],
    'state': ['psxhr-state'],
    'callback': ['psxhr-callback'],
    'interval': ['psxhr-interval'],
    'time': ['psxhr-time'],
    'response': ['psxhr-response',],
}

class PSXhr {

    static init() {

        Array.from(document.querySelectorAll('[psxhr="true"]'))
            .forEach( node => {
                let psxhr = new PSXhr(node);
                psxhr.start();
            });

    }

    constructor(node) {

        this._attr = {};
        this._events = new EventEmitter();
        this._events = {
            before: new EventEmitter(),
            after: new EventEmitter(),
            error: new EventEmitter(),
        }
        this._node = node;

    }

    set before(callback) {
        this._events.before.push(callback);
    }

    set after(callback) {
        this._events.after.push(callback);
    }

    set error(callback) {
        this._events.error.push(callback);
    }

    set container(container) { this._attr.container = container; }
    set event(event) { this._attr.event = event; }
    set observ(callback) { this._attr.observ = callback; }
    set href(href) { this._attr.href = href; }
    set method(method) { this._attr.method = method; }
    set state(bool) { this._attr.method = bool; }
    set callback(callback) { this._attr.callback = callback; }
    set interval(time) { this._attr.interval = time; }
    set time(time) { this._attr.time = time; }
    set response(responseType) { this._attr.response = responseType; }

    start() {

        this._checkAttribute(this._node);
        if (this._attr.observ) this._setObservServer();
        this._setEvent();

    }

    _setObservServer() {

        let pool = [];
        let callback = this._attr.observ;

        if (!this._callbackExsists(callback))
            return false;
        else
            callback = this._getCallback(callback);

        if (!this._attr.container)
            pool.push(this._node);
        else {

            let container = document.querySelectorAll(this._attr.container);

            if (!container) return false;

            Array.from(container).forEach( node => {
                pool.push(node);
            })

        }

        let mo = new MutationObserver( m => { callback(m); });

        let config = { attributes: true, childList: true, characterData: true };

        pool.forEach( node => {
            mo.observe(node, config);
        })

    }

    _checkAttribute() {

        let result = {};

        Object.keys(ATTR_LIST).map( attr => {
            let alias = new Aliases(attr, ATTR_LIST[attr]);
            let name = alias.check(attr, this._checkAlias.bind(this));
            result[attr] = name ? this._node.getAttribute(name) : false;
        })

        this._attr = Object.assign(result, this._attr);

    }

    _checkAlias(aliases) {

        let attributes = this._node.attributes;
        for (var alias of aliases)
            if (attributes.getNamedItem(alias)) return alias;
        return false;

    }

    _isForm() { return this._node.tagName == 'FORM'; }

    _setData() { this._data = new FormData(this.node); }

    _setEvent() {

        if (this._attr.event) {

            let eventList = this._attr.event.split(',');
            let node = this._node;

            eventList.map( event => {
                node.addEventListener(event, this._eventWrapper.bind(this), false);
            });

        }

        if (this._attr.time) {
            setTimeout(this._eventWrapper.bind(this), this._attr.time);
            this._attr.interval = false;
        }

        if (this._attr.interval)
            setInterval(this._eventWrapper.bind(this), this._attr.time);

    }

    _eventWrapper(e) {

        this._request();

        if (e) e.preventDefault();

    }

    _request() {

        let attr = this._attr;

        let data = {
            method: attr.method ? attr.method : 'GET',
            headers: {'X-REQUESTED-WITH': 'XMLHttpRequest'},
            credentials: 'same-origin'
        };

        if (data.method == 'POST') data.body = new FormData();
        else if (data.method == 'POST' && this._isForm())
            data.body = new FormData(this._node);

        var href = attr.href
            ? attr.href
            : window.location.href;

        if (JSON.parse(attr.state))
            history.pushState(null, '', href);

        let responseType = RESPONSE[attr.response]
            ? RESPONSE[attr.response]
            : 'text';

        fetch(href, data)
            .then( response => {

                if (this._events.before.emit(response) === false)
                    throw('Stop PSXhr');

                return response[responseType]();

            })
            .then( response => {

                if (this._dispatchCallback('callback', response))
                    return false;
                else
                    this._defaultHandler(response);

                return response;

            })
            .then( response => {

                this._events.after.emit(response)

            })
            .catch( error => {
                this._events.error.emit(error);
                console.log(error);
            });

    }

    _dispatchCallback(name, params) {

        let callback = this._attr[name];

        if (callback) {
            let fn = this._getCallback(callback);
            fn(params);
            return true;
        } else return false;

    }

    _callbackExsists(callbackName) {

        return typeof window[callbackName] === 'function' || typeof callbackName;

    }

    _getCallback(callbackName) {

        if (typeof callbackName === 'function')
            return callbackName;
        else if (typeof window[callbackName] == 'function')
            return window[callbackName];

    }

    _defaultHandler(res) {

        if (!this._attr.container) this._node.innerHTML = res;
        else {

            let container = document.querySelectorAll(this._attr.container);
            if (!container) return false;

            Array.from(container).forEach( node => {
                node.innerHTML = res;
            })

        }

    }

}

window.PSXhr = PSXhr;
<|endoftext|>