<commit_before>/* eslint-disable react/prop-types */
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { expect } from 'chai';
import { transforms } from '../src';

const { edit, sort, toFormatter } = transforms;

describe('edit', function () {
  it('activates editing', function () {
    const testProperty = 'test';
    let receivedProperty;
    const editor = edit({
      isEditing() {},
      onActivate({ property }) {
        receivedProperty = property;
      },
      onValue() {}
    });
    const result = editor('div')('foo', {
      rowData: {},
      property: testProperty
    });

    result.onClick();

    expect(receivedProperty).to.equal(testProperty);
  });

  it('returns an editor', function () {
    const editor = edit({
      isEditing() {
        return true;
      },
      onActivate: () => {},
      onValue: () => {}
    });
    const value = 'foo';
    const editorElement = 'div';
    const result = editor(editorElement)(value, {
      rowData: {},
      property: 'foo'
    });

    expect(result.children.type).to.equal(editorElement);
    expect(result.children.props.value).to.equal(value);
  });

  it('passes onValue to an editor', function () {
    let receivedValue;
    let receivedProperty;
    const editor = edit({
      isEditing() {
        return true;
      },
      onActivate() {},
      onValue({ value, property }) {
        receivedValue = value;
        receivedProperty = property;
      }
    });
    const editorProperty = 'foo';
    const editorValue = 'foobar';
    const result = editor('div')('foo', {
      rowData: {},
      property: editorProperty
    });

    result.children.props.onValue(editorValue);

    expect(receivedValue).to.equal(editorValue);
    expect(receivedProperty).to.equal(editorProperty);
  });

  it('throws an error if isEditing is not passed', function () {
    expect(edit.bind(null, {
      onActivate: () => {},
      onValue: () => {}
    })).to.throw(Error);
  });

  it('throws an error if onActivate is not passed', function () {
    expect(edit.bind(null, {
      isEditing: () => {},
      onValue: () => {}
    })).to.throw(Error);
  });

  it('throws an error if onValue is not passed', function () {
    expect(edit.bind(null, {
      isEditing: () => {},
      onActivate: () => {}
    })).to.throw(Error);
  });

  it('throws an error if editor is not passed', function () {
    expect(edit({
      isEditing: () => {},
      onActivate: () => {},
      onValue: () => {}
    }).bind(null)).to.throw(Error);
  });
});

describe('sort', function () {
  it('defaults to sort-none class', function () {
    const sorter = sort();
    const result = sorter('testValue', { columnIndex: 0 });

    expect(result.className).to.equal('sort sort-none');
  });

  it('sets sorting class', function () {
    const testColumnIndex = 0;
    const sortDirection = 'asc';
    const sorter = sort({
      getSortingColumns() {
        return {
          [testColumnIndex]: {
            direction: sortDirection,
            position: 0
          }
        };
      }
    });
    const result = sorter('testValue', {
      columnIndex: testColumnIndex
    });

    expect(result.className).to.equal(`sort sort-${sortDirection}`);
  });

  it('triggers sorting on click', function () {
    const testColumnIndex = 0;
    let sorted;
    const sorter = sort({
      onSort(columnIndex) {
        sorted = columnIndex;
      }
    });
    const result = sorter('testValue', {
      columnIndex: testColumnIndex
    });

    result.onClick();

    expect(sorted).to.equal(testColumnIndex);
  });
});

describe('toFormatter', function () {
  it('converts edit to a formatter', function () {
    const editor = edit({
      isEditing: () => {},
      onActivate: () => {},
      onValue: () => {}
    })('div');
    const formatter = toFormatter(editor());

    expect(React.isValidElement(formatter)).to.equal(true);
  });

  it('converts sort to a formatter', function () {
    const sorter = sort();
    const formatter = toFormatter(
      sorter(
        'testValue',
        {
          columnIndex: 0
        }
      )
    );

    expect(React.isValidElement(formatter)).to.equal(true);
  });

  it('converted sort accepts props', function () {
    const className = 'demo-class';
    const sorter = sort();
    const formatter = toFormatter(
      sorter(
        'testValue', {
          columnIndex: 0
        },
        {
          className
        }
      )
    );
    const element = TestUtils.renderIntoDocument(
      React.createElement(Wrapper, {}, formatter)
    );
    const elem = TestUtils.findRenderedDOMComponentWithClass(
      element, className
    );

    expect(elem).to.exist;
  });
});

class Wrapper extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    return React.createElement('div', this.props);
  }
}
<commit_msg>transforms - Test `edit.getEditValue`<commit_after>/* eslint-disable react/prop-types */
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { expect } from 'chai';
import { transforms } from '../src';

const { edit, sort, toFormatter } = transforms;

describe('edit', function () {
  it('activates editing', function () {
    const testProperty = 'test';
    let receivedProperty;
    const editor = edit({
      isEditing() {},
      onActivate({ property }) {
        receivedProperty = property;
      },
      onValue() {}
    });
    const result = editor('div')('foo', {
      rowData: {},
      property: testProperty
    });

    result.onClick();

    expect(receivedProperty).to.equal(testProperty);
  });

  it('returns an editor', function () {
    const editor = edit({
      isEditing() {
        return true;
      },
      onActivate: () => {},
      onValue: () => {}
    });
    const value = 'foo';
    const editorElement = 'div';
    const result = editor(editorElement)(value, {
      rowData: {},
      property: 'foo'
    });

    expect(result.children.type).to.equal(editorElement);
    expect(result.children.props.value).to.equal(value);
  });

  it('passes onValue to an editor', function () {
    let receivedValue;
    let receivedProperty;
    const editor = edit({
      isEditing() {
        return true;
      },
      onActivate() {},
      onValue({ value, property }) {
        receivedValue = value;
        receivedProperty = property;
      }
    });
    const editorProperty = 'foo';
    const editorValue = 'foobar';
    const result = editor('div')('foo', {
      rowData: {},
      property: editorProperty
    });

    result.children.props.onValue(editorValue);

    expect(receivedValue).to.equal(editorValue);
    expect(receivedProperty).to.equal(editorProperty);
  });

  it('allows value passed to edit to be shaped', function () {
    let receivedValue;
    let receivedProperty;
    const editor = edit({
      isEditing() {
        return true;
      },
      onActivate() {},
      onValue({ value, property }) {
        receivedValue = value;
        receivedProperty = property;
      },
      getEditValue: v => v.value
    });
    const editorProperty = 'foo';
    const editorValue = 'foobar';
    const result = editor('div')({ value: editorValue }, {
      rowData: {},
      property: editorProperty
    });

    result.children.props.onValue(editorValue);

    expect(receivedValue).to.equal(editorValue);
    expect(receivedProperty).to.equal(editorProperty);
  });

  it('throws an error if isEditing is not passed', function () {
    expect(edit.bind(null, {
      onActivate: () => {},
      onValue: () => {}
    })).to.throw(Error);
  });

  it('throws an error if onActivate is not passed', function () {
    expect(edit.bind(null, {
      isEditing: () => {},
      onValue: () => {}
    })).to.throw(Error);
  });

  it('throws an error if onValue is not passed', function () {
    expect(edit.bind(null, {
      isEditing: () => {},
      onActivate: () => {}
    })).to.throw(Error);
  });

  it('throws an error if editor is not passed', function () {
    expect(edit({
      isEditing: () => {},
      onActivate: () => {},
      onValue: () => {}
    }).bind(null)).to.throw(Error);
  });
});

describe('sort', function () {
  it('defaults to sort-none class', function () {
    const sorter = sort();
    const result = sorter('testValue', { columnIndex: 0 });

    expect(result.className).to.equal('sort sort-none');
  });

  it('sets sorting class', function () {
    const testColumnIndex = 0;
    const sortDirection = 'asc';
    const sorter = sort({
      getSortingColumns() {
        return {
          [testColumnIndex]: {
            direction: sortDirection,
            position: 0
          }
        };
      }
    });
    const result = sorter('testValue', {
      columnIndex: testColumnIndex
    });

    expect(result.className).to.equal(`sort sort-${sortDirection}`);
  });

  it('triggers sorting on click', function () {
    const testColumnIndex = 0;
    let sorted;
    const sorter = sort({
      onSort(columnIndex) {
        sorted = columnIndex;
      }
    });
    const result = sorter('testValue', {
      columnIndex: testColumnIndex
    });

    result.onClick();

    expect(sorted).to.equal(testColumnIndex);
  });
});

describe('toFormatter', function () {
  it('converts edit to a formatter', function () {
    const editor = edit({
      isEditing: () => {},
      onActivate: () => {},
      onValue: () => {}
    })('div');
    const formatter = toFormatter(editor());

    expect(React.isValidElement(formatter)).to.equal(true);
  });

  it('converts sort to a formatter', function () {
    const sorter = sort();
    const formatter = toFormatter(
      sorter(
        'testValue',
        {
          columnIndex: 0
        }
      )
    );

    expect(React.isValidElement(formatter)).to.equal(true);
  });

  it('converted sort accepts props', function () {
    const className = 'demo-class';
    const sorter = sort();
    const formatter = toFormatter(
      sorter(
        'testValue', {
          columnIndex: 0
        },
        {
          className
        }
      )
    );
    const element = TestUtils.renderIntoDocument(
      React.createElement(Wrapper, {}, formatter)
    );
    const elem = TestUtils.findRenderedDOMComponentWithClass(
      element, className
    );

    expect(elem).to.exist;
  });
});

class Wrapper extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    return React.createElement('div', this.props);
  }
}
<|endoftext|>


<commit_before>/*
 * Created by matthias on 26/10/15.
 * VERSION: Scenario 1
 */
 'use strict';

// Required modules
var cheerio = require('cheerio'),
    clone = require('clone'),
    kuler = require('kuler'),
    async = require('async');

module.exports = function (options, config) {

  options = options || {};
  config = config.get() || {};

  var maxProcess =  config.concurrency || 1,
      delay =  config.delay || 100;

  return function (input, submit) {

    //Load Cheerio on xml DOC input
    var $ = cheerio.load(input.content.xml, {
      normalizeWhitespace: true,
      xmlMode: true
    });
    // Get only span in right spanGrp that have righ attrbs (OBJ)
    var words = $('spanGrp[type="candidatsTermes"] span').filter('[ana~="#DM4"],[ana~="#DAOn"]').toArray();

    if(words.length == "0"){
      return submit(null , input);
    }

    var filtr = $("body div ,text front div[lang='fr'], text front div:not([lang]),  teiHeader fileDesc titleStmt title[lang='fr'], teiHeader fileDesc titleStmt title:not([lang])");

    var attribut;
    $('hi').each(function (i,el) {
      if ($(this).attr('rend')) {
        attribut = $(this).attr('rend');
        $(this).children().each(function () {
          $(this).attr('rend' , attribut);
        });
      }
      $(this).replaceWith($(this).children());
    });
    // Remove big & useless XML in input
    delete input.content.xml;
    var qe;

    //For each span in file ~ Seems does not work
    async.eachSeries(words, function (word, next) {

      // Build clone of input file
      var obj = clone(input,false);

      var firstWord,
          endWord,
          para,
          sentence,
          target,
          corresp,
          lemma,
          prevAllW,
          nextAllW,
          prevW,
          nextW,
          wBefore = "",
          wAfter = "",
          askedWord = "";

      target = ($(word).attr("target") || '').replace(/#/g , "").split(" ");
      firstWord = $('[xml\\:id="' + target[0] + '"]');

      var isInFiltr = filtr.find(firstWord).length

      // If word not in body balise continue with other span
      if (isInFiltr < 1) {
        return next();
      }
      // filtr.find('[nb]').removeAttr('nb');

      endWord = (target.length > 1) ? $('[xml\\:id="' + target[target.length - 1] + '"]') : firstWord;
      corresp = $(word).attr("corresp");
      lemma   = ($(word).attr("lemma") || '').toString();

      if((corresp.indexOf("#TS2.0") > (-1)) && (corresp.indexOf("#TS1.4") > (-1))){
         corresp = corresp.replace(/-#TS1.4-entry-.*$|#TS2.0-entry-/g, "").toString();
      }
      else if(corresp.indexOf("#TS2.0") > (-1)){
        corresp = corresp.replace(/#TS2.0-entry-/g, "").toString();
      }
      else if(corresp.indexOf("#TS1.4") > (-1)){
        corresp = corresp.replace(/#TS1.4-entry-/g, "").toString();
      }

      var nbSiblings = firstWord.siblings();
      var nbParaChildren = firstWord.closest("p").children(),
          content,
          reg = /\B[^\w\s\n\t]\B/,
          pc = $('<pc>ex</pc>'),
          element;

      para = (nbSiblings.length < 11 && nbParaChildren.length > 12) ? nbParaChildren.clone() : firstWord.parent().clone();
      para.find("w").each(function(index, el){
        element = para.find(el);
        if(element.contents()[0].type == "text"){
          content = element.contents().text();
          if (reg.test(content)) {
            pc.attr("xml:id" , element.attr("xml:id"));
            pc.text(content);
            // console.info("pc : " , pc.toString());
            element.replaceWith(pc.toString());
            // console.info(element);
          }
        }
      });

      var word2Add;
      //Create asked words and add attribut nb
      for (var i = 0 ; i < target.length ; i++) {
        word2Add = para.find('[xml\\:id="' + target[i] + '"]');
        if(word2Add[0] && word2Add[0].next){
          if(word2Add[0].next.type == "text"){
           word2Add.attr("wsAfter", "true");
          }
        }
        askedWord = askedWord + word2Add.attr("nb" , "0");
      }

      sentence = para.clone();
      sentence.find('note').remove();

      prevAllW = sentence.find('[xml\\:id="' + target[0] + '"]').prevAll();
      nextAllW = sentence.find('[xml\\:id="' + target[target.length - 1] + '"]').nextAll();

      for (var nbWBefore = 0, nbWAfter = 0, index = 0; (nbWBefore < 5 || nbWAfter < 5) ; index++) {
        prevW = (prevAllW[index]) ? prevAllW.filter(prevAllW[index]) : null;
        nextW = (nextAllW[index]) ? nextAllW.filter(nextAllW[index]) : null;
        if(prevW){
          if(prevW.is('w')){
            prevW = prevW.attr("nb", ++nbWBefore);
          }
          if (!(prevW.is('note'))) {
            if(prevW[0] && prevW[0].next){
              if(prevW[0].next.type == "text"){
               prevW.attr("wsAfter", "true");
              }
            }
            wBefore = prevW + wBefore;
          }
        }
        else{
          nbWBefore = 5;
        }
        if(nextW){
          if(nextW.is('w')){
            nextW = nextW.attr("nb", ++nbWAfter);
          }
          if (!(nextW.is('note'))) {
            if(nextW[0] && nextW[0].next){
              if(nextW[0].next.type == "text"){
                nextW.attr("wsAfter", "true");
              }
            }
            wAfter = wAfter + nextW ;
          }
        }
        else{
          nbWAfter = 5;
        }
      }

      /* Create sentence */
      sentence = '' + wBefore + '' + '' + askedWord + '' +  '' + wAfter + '' ;

      para = para.toString();
      para = para.replace(/<head/g, "<div");
      para = para.replace(/<\/head>/g, "
");
      para = para.replace(/<title/g, "<h4");
      para = para.replace(/<\/title>/g, "
");
      para = para.replace(/<hi/g, "<i");
      para = para.replace(/<\/hi>/g, "");
      para = para.replace(/<note/g, "<div");
      para = para.replace(/<\/note>/g, "
");

      // Add elements to OBJ
      obj.content.corresp = corresp;
      obj.content.target = target;
      obj.content.sentence = sentence;
      obj.content.para = para;
      obj.content.lemma = lemma;
      obj.content.words = askedWord.toString();

      qe = submit(obj);

      if (qe.length() >= maxProcess) {
        setTimeout(function () {
          return next();
        }, delay * qe.length());
      } else {
        return next();
      }
    },
    function (err) {
      if (err) {
        console.info(kuler("\n " + err + " \n" , "red"));
      }
      // the last callback means that all documents have been submitted
      submit();
    })
  }
};
<commit_msg>Indication version dans le corresp<commit_after>/*
 * Created by matthias on 26/10/15.
 * VERSION: Scenario 1
 */
 'use strict';

// Required modules
var cheerio = require('cheerio'),
    clone = require('clone'),
    kuler = require('kuler'),
    async = require('async');

module.exports = function (options, config) {

  options = options || {};
  config = config.get() || {};

  var maxProcess =  config.concurrency || 1,
      delay =  config.delay || 100;

  return function (input, submit) {

    //Load Cheerio on xml DOC input
    var $ = cheerio.load(input.content.xml, {
      normalizeWhitespace: true,
      xmlMode: true
    });
    // Get only span in right spanGrp that have righ attrbs (OBJ)
    var words = $('spanGrp[type="candidatsTermes"] span').filter('[ana~="#DM4"],[ana~="#DAOn"]').toArray();

    if(words.length == "0"){
      return submit(null , input);
    }

    var filtr = $("body div ,text front div[lang='fr'], text front div:not([lang]),  teiHeader fileDesc titleStmt title[lang='fr'], teiHeader fileDesc titleStmt title:not([lang])");

    var attribut;
    $('hi').each(function (i,el) {
      if ($(this).attr('rend')) {
        attribut = $(this).attr('rend');
        $(this).children().each(function () {
          $(this).attr('rend' , attribut);
        });
      }
      $(this).replaceWith($(this).children());
    });
    // Remove big & useless XML in input
    delete input.content.xml;
    var qe;

    //For each span in file ~ Seems does not work
    async.eachSeries(words, function (word, next) {

      // Build clone of input file
      var obj = clone(input,false);

      var firstWord,
          endWord,
          para,
          sentence,
          target,
          corresp,
          lemma,
          prevAllW,
          nextAllW,
          prevW,
          nextW,
          wBefore = "",
          wAfter = "",
          askedWord = "";

      target = ($(word).attr("target") || '').replace(/#/g , "").split(" ");
      firstWord = $('[xml\\:id="' + target[0] + '"]');

      var isInFiltr = filtr.find(firstWord).length

      // If word not in body balise continue with other span
      if (isInFiltr < 1) {
        return next();
      }
      // filtr.find('[nb]').removeAttr('nb');

      endWord = (target.length > 1) ? $('[xml\\:id="' + target[target.length - 1] + '"]') : firstWord;
      corresp = $(word).attr("corresp");
      lemma   = ($(word).attr("lemma") || '').toString();

      if((corresp.indexOf("#TS2.0") > (-1)) && (corresp.indexOf("#TS1.4") > (-1))){
         corresp = "2.0-" + corresp.replace(/-#TS1.4-entry-.*$|#TS2.0-entry-/g, "").toString();
      }
      else if(corresp.indexOf("#TS2.0") > (-1)){
        corresp = "2.0-" + corresp.replace(/#TS2.0-entry-/g, "").toString();
      }
      else if(corresp.indexOf("#TS1.4") > (-1)){
        corresp = "1.4-" + corresp.replace(/#TS1.4-entry-/g, "").toString();
      }

      var nbSiblings = firstWord.siblings();
      var nbParaChildren = firstWord.closest("p").children(),
          content,
          reg = /\B[^\w\s\n\t]\B/,
          pc = $('<pc>ex</pc>'),
          element;

      para = (nbSiblings.length < 11 && nbParaChildren.length > 12) ? nbParaChildren.clone() : firstWord.parent().clone();
      para.find("w").each(function(index, el){
        element = para.find(el);
        if(element.contents()[0].type == "text"){
          content = element.contents().text();
          if (reg.test(content)) {
            pc.attr("xml:id" , element.attr("xml:id"));
            pc.text(content);
            // console.info("pc : " , pc.toString());
            element.replaceWith(pc.toString());
            // console.info(element);
          }
        }
      });

      var word2Add;
      //Create asked words and add attribut nb
      for (var i = 0 ; i < target.length ; i++) {
        word2Add = para.find('[xml\\:id="' + target[i] + '"]');
        if(word2Add[0] && word2Add[0].next){
          if(word2Add[0].next.type == "text"){
           word2Add.attr("wsAfter", "true");
          }
        }
        askedWord = askedWord + word2Add.attr("nb" , "0");
      }

      sentence = para.clone();
      sentence.find('note').remove();

      prevAllW = sentence.find('[xml\\:id="' + target[0] + '"]').prevAll();
      nextAllW = sentence.find('[xml\\:id="' + target[target.length - 1] + '"]').nextAll();

      for (var nbWBefore = 0, nbWAfter = 0, index = 0; (nbWBefore < 5 || nbWAfter < 5) ; index++) {
        prevW = (prevAllW[index]) ? prevAllW.filter(prevAllW[index]) : null;
        nextW = (nextAllW[index]) ? nextAllW.filter(nextAllW[index]) : null;
        if(prevW){
          if(prevW.is('w')){
            prevW = prevW.attr("nb", ++nbWBefore);
          }
          if (!(prevW.is('note'))) {
            if(prevW[0] && prevW[0].next){
              if(prevW[0].next.type == "text"){
               prevW.attr("wsAfter", "true");
              }
            }
            wBefore = prevW + wBefore;
          }
        }
        else{
          nbWBefore = 5;
        }
        if(nextW){
          if(nextW.is('w')){
            nextW = nextW.attr("nb", ++nbWAfter);
          }
          if (!(nextW.is('note'))) {
            if(nextW[0] && nextW[0].next){
              if(nextW[0].next.type == "text"){
                nextW.attr("wsAfter", "true");
              }
            }
            wAfter = wAfter + nextW ;
          }
        }
        else{
          nbWAfter = 5;
        }
      }

      /* Create sentence */
      sentence = '' + wBefore + '' + '' + askedWord + '' +  '' + wAfter + '' ;

      para = para.toString();
      para = para.replace(/<head/g, "<div");
      para = para.replace(/<\/head>/g, "
");
      para = para.replace(/<title/g, "<h4");
      para = para.replace(/<\/title>/g, "
");
      para = para.replace(/<hi/g, "<i");
      para = para.replace(/<\/hi>/g, "");
      para = para.replace(/<note/g, "<div");
      para = para.replace(/<\/note>/g, "
");

      // Add elements to OBJ
      obj.content.corresp = corresp;
      obj.content.target = target;
      obj.content.sentence = sentence;
      obj.content.para = para;
      obj.content.lemma = lemma;
      obj.content.words = askedWord.toString();

      qe = submit(obj);

      if (qe.length() >= maxProcess) {
        setTimeout(function () {
          return next();
        }, delay * qe.length());
      } else {
        return next();
      }
    },
    function (err) {
      if (err) {
        console.info(kuler("\n " + err + " \n" , "red"));
      }
      // the last callback means that all documents have been submitted
      submit();
    })
  }
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013 Craig Condon
 * Copyright (c) 2015 Jared Allard
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 **/
var mdeps  = require("module-deps"),
insertGlobals = require('insert-module-globals'),
path       = require("path"),
fs         = require("fs"),
through    = require("through"),
async      = require("async"),
browserify = require('browserify'),
builtins   = require("builtins"),
_log     = require("./log");

/**
 * User browserify to create a "packed" file.
 *
 * @param {string} input - input file
 * @param {string} nc - node compiler dir
 * @param {function} complete - next function to call (async)
 **/
function bundle (input, nc, complete) {
  var igv = '__filename,__dirname';
  insertGlobalVars = igv.split(',').reduce(function (vars, x) { // borrowed from browserify
    vars[x] = insertGlobals.vars[x];
    return vars;
  }, {});

  var b = browserify(input, {
    builtins: false,
    commondir:false,
    detectGlobals: false,
    insertGlobals: '__filename,__dirname',
    insertGlobalVars: insertGlobalVars,
    browserField: false
  });
  var bundlePath = path.join(nc, "lib", "nexe.js");
  var ws = fs.createWriteStream(bundlePath);

  /*if(fs.existsSync(bundlePath)) {
    fs.unlinkSync(bundlePath);
  }*/

  var bfs = b.bundle(); // open the bundle stream.

  bfs.pipe(ws); // pipe it to the write stream we created earlier

  ws.on('error', function(err) {
    console.log(err);
  })

  ws.on('close', function() {
    var source = fs.readFileSync(bundlePath, 'utf8');
    source = source.replace(/[^\x00-\x7F]/g, "");
    fs.writeFileSync(bundlePath, source, 'utf8');

    complete();
  })
}

module.exports = bundle;
<commit_msg>use browserify cli to do this...<commit_after>/**
 * Copyright (c) 2013 Craig Condon
 * Copyright (c) 2015 Jared Allard
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 **/
var mdeps  = require("module-deps"),
path       = require("path"),
spawn      = require('child_process').spawn,
fs         = require("fs"),
through    = require("through"),
async      = require("async"),
browserify = require('browserify'),
builtins   = require("builtins"),
_log     = require("./log");

/**
 * User browserify to create a "packed" file.
 *
 * @param {string} input - input file
 * @param {string} nc - node compiler dir
 * @param {function} complete - next function to call (async)
 **/
function bundle (input, nc, complete) {
  var bundlePath = path.join(nc, "lib", "nexe.js");
  var ws = fs.createWriteStream(bundlePath);
  var proc = spawn('node', ['node_modules/browserify/bin/cmd.js', '--node', input ]);

  proc.stdout.pipe(ws);

  proc.on('close', function(code) {
    console.log("browserify finished")
  })

  ws.on('error', function(err) {
    console.log(err);
  })

  ws.on('close', function() {
    var source = fs.readFileSync(bundlePath, 'utf8');
    source = source.replace(/[^\x00-\x7F]/g, "");
    fs.writeFileSync(bundlePath, source, 'utf8');

    complete();
  });
}

module.exports = bundle;
<|endoftext|>


<commit_before>// ========================================================================
// SC.Array Unit Tests
// ========================================================================
/*globals module test ok isObj equals expects */

var arrays, observer ; // global variables

// Test the SproutCore Array interface on a custom object.
DummyArray = SC.Object.extend(SC.Array, {

  length: 0,

  content: null,

  replace: function(idx, amt, objects) {
    if (!this.content) this.content = [] ;

    this.beginPropertyChanges() ;
    this.content.replace(idx,amt,objects) ;

    this.set('length', this.content.length) ;
    this.enumerableContentDidChange() ;
    this.endPropertyChanges() ;
  },

  objectAt: function(idx) {
    if (!this.content) this.content = [] ;
    return this.content[idx] ;
  }

});

// This is a generic set of tests.  To apply these, create a new contact, and
// call this function passing in a factory function to build your element.
module("Array, DummyArray and SC.SparseArray", {

  setup: function() {
    arrays = [[], DummyArray.create(), SC.SparseArray.create()] ;

    // this will record observed changes.
    observer = SC.Object.create({

      init: function() {
        arguments.callee.base.apply(this, arguments) ; // sc_super() ;

        var that = this ;
        this.observer = function(target, key, value) {
          that.notified[key] = true ;
          that.notifiedValue[key] = value ;
        }.bind(this) ;

        this.resetObservers = function() {
          this.notified = {} ;
          this.notifiedValue = {} ;
        } ;

        this.observe = function() {
          var keys = SC.$A(arguments) ;
          var loc = keys.length ;
          while(--loc >= 0) {
            this.a.addObserver(keys[loc], this, this.observer) ;
          }
        };

        this.didNotify = function(key) {
          return this.notified[key] == true ;
        } ;

        this.resetObservers() ;
      }
    });
  }

});

test("[].replace(0,0,'X') => ['X'] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.observe('[]') ;
    observer.a.replace(0,0,['X']) ;

    equals(observer.a.length, 1) ;
    equals(observer.a.objectAt(0), 'X') ;
    equals(YES, observer.didNotify('[]'), 'didNotify([])') ;
  }
});

test("[A,B,C,D].replace(1,2,X) => [A,X,D] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C D')) ;
    observer.observe('[]') ;

    observer.a.replace(1,2,['X']) ;

    equals(observer.a.get('length'), 3) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals(observer.a.objectAt(1), 'X') ;
    equals(observer.a.objectAt(2), 'D') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[A,B,C,D].replace(1,2,[X,Y]) => [A,X,Y,D] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C D')) ;
    observer.observe('[]') ;

    observer.a.replace(1,2, $w('X Y')) ;

    equals(observer.a.get('length'), 4) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals(observer.a.objectAt(1), 'X') ;
    equals(observer.a.objectAt(2), 'Y') ;
    equals(observer.a.objectAt(3), 'D') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[A,B].replace(1,0,[X,Y]) => [A,X,Y,B] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B')) ;
    observer.observe('[]') ;

    observer.a.replace(1,0, $w('X Y')) ;

    equals(observer.a.get('length'), 4) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals(observer.a.objectAt(1), 'X') ;
    equals(observer.a.objectAt(2), 'Y') ;
    equals(observer.a.objectAt(3), 'B') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[A,B,C,D].replace(2,2) => [A,B] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C D')) ;
    observer.observe('[]') ;

    observer.a.replace(2,2) ;

    equals(observer.a.get('length'), 2) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals(observer.a.objectAt(1), 'B') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[].insertAt(0,X) => [X] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.observe('[]') ;

    observer.a.insertAt(0,['X']) ;

    equals(observer.a.get('length'), 1) ;
    equals(observer.a.objectAt(0), 'X') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[].removeObject(obj) should remove regardless of index position", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    // spec for bug in Rev:402 where removeObject was skipping index 0 when scanning the array
    observer.a.set('[]', $w('A B C')) ;
    equals(observer.a.get('length'), 3) ;

    observer.a.removeObject('C') ;
    equals(observer.a.get('length'), 2) ;
    observer.a.removeObject('B') ;
    equals(observer.a.get('length'), 1) ;
    observer.a.removeObject('A') ;
    equals(observer.a.get('length'), 0) ;
  }
});

test("[].objectAt(0) => undefined", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    equals(observer.a.get('length'), 0) ;
    equals((observer.a.objectAt(0) === undefined), YES) ;
  }
});

test("[A,B,C].objectAt(5) => undefined", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    equals(observer.a.get('length'), 0) ;
    observer.a.set('[]', $w('A B C')) ;
    equals(observer.a.get('length'), 3) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals((observer.a.objectAt(5) === undefined), YES) ;
  }
});

test("[A,B,C].set('[]',[X,Y]) => [X,Y] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C')) ;
    observer.observe('[]') ;

    observer.a.set('[]', $w('X Y')) ;

    equals(observer.a.get('length'), 2) ;
    equals(observer.a.objectAt(0), 'X') ;
    equals(observer.a.objectAt(1), 'Y') ;
    equals(observer.didNotify('[]'), YES) ;
  }
});

test("[A,B,C] should be Enumerable", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0, 0, $w('A B C')) ;

    var cnt = 0 ;
    var items = [] ;
    observer.a.forEach(function( item, idx ) {
      items.push(item) ;
      cnt++ ;
    }) ;
    equals(cnt, observer.a.get('length')) ;
    equals('A', items[0]) ;
    equals('B', items[1]) ;
    equals('C',items[2]) ;
  }
});

test("ary.isEqual() should return true when array contents match", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C')) ;

    var ary = $w('A B C') ; // test against a different object.
    equals(observer.a.isEqual(ary), true) ;

    ary = $w('A B') ;
    equals(observer.a.isEqual(ary), false) ;

    ary = $w('X Y Z') ;
    equals(observer.a.isEqual(ary), false) ;

    equals(observer.a.isEqual(observer.a), true) ;
  }
});

// // Test the SproutCore Array interface on native arrays.
// Test.context("SC.Array", ArrayTests(function() { return []; })) ;
//
//
// Test.context("DummyArray", ArrayTests(function() {
//   return DummyArray.create()  ;
// }));

// // This is a generic set of tests.  To apply these, create a new contact, and
// // call this function passing in a factory function to build your element.
// ArrayTests = function(factoryFunc) {
//   return {
//
//     setup: function() {
//       this.a = factoryFunc() ;
//
//       // this will record observed changes.
//       var that = this ;
//       this.observer = function(target, key, value) {
//         that.notified[key] = true ;
//         that.notifiedValue[key] = value ;
//       }.bind(this) ;
//
//       this.resetObservers = function() {
//         this.notified = {} ;
//         this.notifiedValue = {} ;
//       } ;
//
//       this.observe = function() {
//         var keys = SC.$A(arguments) ;
//         var loc = keys.length ;
//         while(--loc >= 0) {
//           this.a.addObserver(keys[loc], this, this.observer) ;
//         }
//       };
//
//       this.didNotify = function(key) {
//         return this.notified[key] == true ;
//       } ;
//
//       this.resetObservers() ;
//     },
//
//     "[].replace(0,0,'X') => ['X'] + notify": function() {
//       this.observe('[]') ;
//       this.a.replace(0,0,['X']) ;
//
//       this.a.length.shouldEqual(1) ;
//       this.a.objectAt(0).shouldEqual('X') ;
//       assertEqual(YES, this.didNotify('[]'), 'didNotify([])') ;
//     },
//
//     "[A,B,C,D].replace(1,2,X) => [A,X,D] + notify": function() {
//       this.a.replace(0,0, $w('A B C D')) ;
//       this.observe('[]') ;
//
//       this.a.replace(1,2,['X']) ;
//
//       this.a.get('length').shouldEqual(3) ;
//       this.a.objectAt(0).shouldEqual('A') ;
//       this.a.objectAt(1).shouldEqual('X') ;
//       this.a.objectAt(2).shouldEqual('D') ;
//       this.didNotify("[]").shouldEqual(YES) ;
//     },
//
//     "[A,B,C,D].replace(1,2,[X,Y]) => [A,X,Y,D] + notify": function() {
//       this.a.replace(0,0, $w('A B C D')) ;
//       this.observe('[]') ;
//
//       this.a.replace(1,2, $w('X Y')) ;
//
//       this.a.get('length').shouldEqual(4) ;
//       this.a.objectAt(0).shouldEqual('A') ;
//       this.a.objectAt(1).shouldEqual('X') ;
//       this.a.objectAt(2).shouldEqual('Y') ;
//       this.a.objectAt(3).shouldEqual('D') ;
//       this.didNotify("[]").shouldEqual(YES) ;
//     },
//
//     "[A,B].replace(1,0,[X,Y]) => [A,X,Y,B] + notify": function() {
//       this.a.replace(0,0, $w('A B')) ;
//       this.observe('[]') ;
//
//       this.a.replace(1,0, $w('X Y')) ;
//
//       this.a.get('length').shouldEqual(4) ;
//       this.a.objectAt(0).shouldEqual('A') ;
//       this.a.objectAt(1).shouldEqual('X') ;
//       this.a.objectAt(2).shouldEqual('Y') ;
//       this.a.objectAt(3).shouldEqual('B') ;
//       this.didNotify("[]").shouldEqual(YES) ;
//     },
//
//     "[A,B,C,D].replace(2,2) => [A,B] + notify": function() {
//       this.a.replace(0,0, $w('A B C D')) ;
//       this.observe('[]') ;
//
//       this.a.replace(2,2) ;
//
//       this.a.get('length').shouldEqual(2) ;
//       this.a.objectAt(0).shouldEqual('A') ;
//       this.a.objectAt(1).shouldEqual('B') ;
//       this.didNotify("[]").shouldEqual(YES) ;
//     },
//
//     "[].insertAt(0,X) => [X] + notify": function() {
//       this.observe('[]') ;
//       this.a.insertAt(0,['X']) ;
//       this.a.get('length').shouldEqual(1) ;
//       this.a.objectAt(0).shouldEqual('X') ;
//       this.didNotify("[]").shouldEqual(YES) ;
//     },
//
//     "[].removeObject(obj) should remove regardless of index position": function()
//     {
//       // spec for bug in Rev:402 where removeObject was skipping index 0 when scanning the array
//       this.a.set('[]', $w('A B C'));
//       this.a.get('length').shouldEqual(3);
//
//       this.a.removeObject('C');
//       this.a.get('length').shouldEqual(2);
//       this.a.removeObject('B');
//       this.a.get('length').shouldEqual(1);
//       this.a.removeObject('A');
//       this.a.get('length').shouldEqual(0);
//     },
//
//
//     "[].objectAt(0) => undefined": function()
//     {
//       this.a.get('length').shouldEqual(0);
//       (this.a.objectAt(0) === undefined).shouldEqual(YES);
//     },
//     "[A,B,C].objectAt(5) => undefined": function()
//     {
//       this.a.get('length').shouldEqual(0);
//       this.a.set('[]', $w('A B C')) ;
//       this.a.get('length').shouldEqual(3) ;
//       this.a.objectAt(0).shouldEqual('A');
//       (this.a.objectAt(5) === undefined).shouldEqual(YES);
//     },
//
//     "[A,B,C].set('[]',[X,Y]) => [X,Y] + notify": function() {
//       this.a.replace(0,0, $w('A B C')) ;
//       this.observe('[]') ;
//
//       this.a.set('[]', $w('X Y')) ;
//
//       this.a.get('length').shouldEqual(2) ;
//       this.a.objectAt(0).shouldEqual('X') ;
//       this.a.objectAt(1).shouldEqual('Y') ;
//       this.didNotify('[]').shouldEqual(YES) ;
//     },
//
//     "[A,B,C] should be Enumerable": function() {
//       this.a.replace(0, 0, $w('A B C')) ;
//
//       var cnt = 0 ;
//       var items = [] ;
//       this.a.forEach(function( item, idx ) {
//         items.push(item) ;
//         cnt++ ;
//       }) ;
//       cnt.shouldEqual(this.a.get('length')) ;
//       assertEqual('A', items[0]) ;
//       assertEqual('B', items[1]) ;
//       assertEqual('C',items[2]) ;
//     },
//
//     "ary.isEqual() should return true when array contents match": function() {
//       this.a.replace(0,0, $w('A B C')) ;
//
//       var ary = $w('A B C') ; // test against a different object.
//       this.a.isEqual(ary).shouldEqual(true) ;
//
//       ary = $w('A B') ;
//       this.a.isEqual(ary).shouldEqual(false) ;
//
//       ary = $w('X Y Z') ;
//       this.a.isEqual(ary).shouldEqual(false) ;
//
//       this.a.isEqual(this.a).shouldEqual(true) ;
//     }
//   } ;
// } ;
//
// // Test the SproutCore Array interface on native arrays.
// Test.context("SC.Array", ArrayTests(function() { return []; })) ;
//
// // Test the SproutCore Array interface on a custom object.
// DummyArray = SC.Object.extend(SC.Array, {
//
//   length: 0,
//
//   content: null,
//
//   replace: function(idx, amt, objects) {
//     if (!this.content) this.content = [] ;
//
//     this.beginPropertyChanges() ;
//     this.content.replace(idx,amt,objects) ;
//
//     this.set('length', this.content.length) ;
//     this.enumerableContentDidChange() ;
//     this.endPropertyChanges() ;
//   },
//
//   objectAt: function(idx) {
//     if (!this.content) this.content = [] ;
//     return this.content[idx] ;
//   }
// }) ;
//
// Test.context("DummyArray", ArrayTests(function() {
//   return DummyArray.create()  ;
// }));
<commit_msg>remove commented out code, out-of-date comments<commit_after>// ========================================================================
// SC.Array Unit Tests
// ========================================================================
/*globals module test ok isObj equals expects */

var arrays, observer ; // global variables

// Test the SproutCore Array interface on a custom object.
DummyArray = SC.Object.extend(SC.Array, {

  length: 0,

  content: null,

  replace: function(idx, amt, objects) {
    if (!this.content) this.content = [] ;

    this.beginPropertyChanges() ;
    this.content.replace(idx,amt,objects) ;

    this.set('length', this.content.length) ;
    this.enumerableContentDidChange() ;
    this.endPropertyChanges() ;
  },

  objectAt: function(idx) {
    if (!this.content) this.content = [] ;
    return this.content[idx] ;
  }

});

module("Array, DummyArray and SC.SparseArray", {

  setup: function() {
    arrays = [[], DummyArray.create(), SC.SparseArray.create()] ;

    // this will record observed changes.
    observer = SC.Object.create({

      init: function() {
        arguments.callee.base.apply(this, arguments) ; // sc_super() ;

        var that = this ;
        this.observer = function(target, key, value) {
          that.notified[key] = true ;
          that.notifiedValue[key] = value ;
        }.bind(this) ;

        this.resetObservers = function() {
          this.notified = {} ;
          this.notifiedValue = {} ;
        } ;

        this.observe = function() {
          var keys = SC.$A(arguments) ;
          var loc = keys.length ;
          while(--loc >= 0) {
            this.a.addObserver(keys[loc], this, this.observer) ;
          }
        };

        this.didNotify = function(key) {
          return this.notified[key] == true ;
        } ;

        this.resetObservers() ;
      }
    });
  }

});

test("[].replace(0,0,'X') => ['X'] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.observe('[]') ;
    observer.a.replace(0,0,['X']) ;

    equals(observer.a.length, 1) ;
    equals(observer.a.objectAt(0), 'X') ;
    equals(YES, observer.didNotify('[]'), 'didNotify([])') ;
  }
});

test("[A,B,C,D].replace(1,2,X) => [A,X,D] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C D')) ;
    observer.observe('[]') ;

    observer.a.replace(1,2,['X']) ;

    equals(observer.a.get('length'), 3) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals(observer.a.objectAt(1), 'X') ;
    equals(observer.a.objectAt(2), 'D') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[A,B,C,D].replace(1,2,[X,Y]) => [A,X,Y,D] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C D')) ;
    observer.observe('[]') ;

    observer.a.replace(1,2, $w('X Y')) ;

    equals(observer.a.get('length'), 4) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals(observer.a.objectAt(1), 'X') ;
    equals(observer.a.objectAt(2), 'Y') ;
    equals(observer.a.objectAt(3), 'D') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[A,B].replace(1,0,[X,Y]) => [A,X,Y,B] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B')) ;
    observer.observe('[]') ;

    observer.a.replace(1,0, $w('X Y')) ;

    equals(observer.a.get('length'), 4) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals(observer.a.objectAt(1), 'X') ;
    equals(observer.a.objectAt(2), 'Y') ;
    equals(observer.a.objectAt(3), 'B') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[A,B,C,D].replace(2,2) => [A,B] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C D')) ;
    observer.observe('[]') ;

    observer.a.replace(2,2) ;

    equals(observer.a.get('length'), 2) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals(observer.a.objectAt(1), 'B') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[].insertAt(0,X) => [X] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.observe('[]') ;

    observer.a.insertAt(0,['X']) ;

    equals(observer.a.get('length'), 1) ;
    equals(observer.a.objectAt(0), 'X') ;
    equals(observer.didNotify("[]"), YES) ;
  }
});

test("[].removeObject(obj) should remove regardless of index position", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    // spec for bug in Rev:402 where removeObject was skipping index 0 when scanning the array
    observer.a.set('[]', $w('A B C')) ;
    equals(observer.a.get('length'), 3) ;

    observer.a.removeObject('C') ;
    equals(observer.a.get('length'), 2) ;
    observer.a.removeObject('B') ;
    equals(observer.a.get('length'), 1) ;
    observer.a.removeObject('A') ;
    equals(observer.a.get('length'), 0) ;
  }
});

test("[].objectAt(0) => undefined", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    equals(observer.a.get('length'), 0) ;
    equals((observer.a.objectAt(0) === undefined), YES) ;
  }
});

test("[A,B,C].objectAt(5) => undefined", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    equals(observer.a.get('length'), 0) ;
    observer.a.set('[]', $w('A B C')) ;
    equals(observer.a.get('length'), 3) ;
    equals(observer.a.objectAt(0), 'A') ;
    equals((observer.a.objectAt(5) === undefined), YES) ;
  }
});

test("[A,B,C].set('[]',[X,Y]) => [X,Y] + notify", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C')) ;
    observer.observe('[]') ;

    observer.a.set('[]', $w('X Y')) ;

    equals(observer.a.get('length'), 2) ;
    equals(observer.a.objectAt(0), 'X') ;
    equals(observer.a.objectAt(1), 'Y') ;
    equals(observer.didNotify('[]'), YES) ;
  }
});

test("[A,B,C] should be Enumerable", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0, 0, $w('A B C')) ;

    var cnt = 0 ;
    var items = [] ;
    observer.a.forEach(function( item, idx ) {
      items.push(item) ;
      cnt++ ;
    }) ;
    equals(cnt, observer.a.get('length')) ;
    equals('A', items[0]) ;
    equals('B', items[1]) ;
    equals('C',items[2]) ;
  }
});

test("ary.isEqual() should return true when array contents match", function() {
  var ary2 = arrays ;
  for (var idx2=0, len2=ary2.length; idx2<len2; idx2++) {
    observer.a = ary2[idx2] ;
    observer.a.replace(0,0, $w('A B C')) ;

    var ary = $w('A B C') ; // test against a different object.
    equals(observer.a.isEqual(ary), true) ;

    ary = $w('A B') ;
    equals(observer.a.isEqual(ary), false) ;

    ary = $w('X Y Z') ;
    equals(observer.a.isEqual(ary), false) ;

    equals(observer.a.isEqual(observer.a), true) ;
  }
});
<|endoftext|>


<commit_before>// Load in dependencies
var assert = require('assert');
var ndarray = require('ndarray');
var exporters = require('./exporters').exporters;

// Define our canvas constructor
function Canvas(width, height) {
  // Calculate and save dimensions/data for later
  var len = width * height * 4;
  this.width = width;
  console.log('sup2');
  this.height = height;
  this.data = new global.Uint8ClampedArray(len);
  this.ndarray = new ndarray(this.data, [height, width, 4]);

  // Create a store for images
  console.log('sup');
  this.images = [];
}
Canvas.prototype = {
  addImage: function addImage (img, x, y) {
    // Save the image for later
    this.images.push({
      img: img,
      x: x,
      y: y
    });
  },
  'export': function exportFn (options, cb) {
    // Grab the exporter
    var format = options.format || 'png';
    var exporter = exporters[format];

    // Assert it exists
    assert(exporter, 'Exporter ' + format + ' does not exist for spritesmith\'s png engine');

    // Render the item
    exporter.call(this, options, cb);
  }
};

// Define an async constructor for our canvas
function createCanvas(width, height, cb) {
  // Create a new canvas and callback
  var canvas = new Canvas(width, height);
  cb(null, canvas);
}

// Expose Canvas and createCanvas to engine
module.exports = {
  Canvas: Canvas,
  createCanvas: createCanvas
};
<commit_msg>Cleaned up dev console.logs<commit_after>// Load in dependencies
var assert = require('assert');
var ndarray = require('ndarray');
var exporters = require('./exporters').exporters;

// Define our canvas constructor
function Canvas(width, height) {
  // Calculate and save dimensions/data for later
  var len = width * height * 4;
  this.width = width;
  this.height = height;
  this.data = new global.Uint8ClampedArray(len);
  this.ndarray = new ndarray(this.data, [height, width, 4]);

  // Create a store for images
  this.images = [];
}
Canvas.prototype = {
  addImage: function addImage (img, x, y) {
    // Save the image for later
    this.images.push({
      img: img,
      x: x,
      y: y
    });
  },
  'export': function exportFn (options, cb) {
    // Grab the exporter
    var format = options.format || 'png';
    var exporter = exporters[format];

    // Assert it exists
    assert(exporter, 'Exporter ' + format + ' does not exist for spritesmith\'s png engine');

    // Render the item
    exporter.call(this, options, cb);
  }
};

// Define an async constructor for our canvas
function createCanvas(width, height, cb) {
  // Create a new canvas and callback
  var canvas = new Canvas(width, height);
  cb(null, canvas);
}

// Expose Canvas and createCanvas to engine
module.exports = {
  Canvas: Canvas,
  createCanvas: createCanvas
};
<|endoftext|>


<commit_before>import Component from '@glimmer/component';
import {action} from '@ember/object';
import {tracked} from '@glimmer/tracking';

class MemberActivity {
    eventProperties = {
        sent: {
            icon: 'send-email',
            iconClass: 'midgrey',
            tooltip: 'Sent email'
        },
        opened: {
            icon: 'eye',
            iconClass: 'green-d2',
            tooltip: 'Opened email'
        },
        failed: {
            icon: 'cross-circle',
            iconClass: 'red-d2',
            tooltip: 'Email delivery failed'
        },
        unsubscribed: {
            icon: 'unsubscribed',
            iconClass: 'red-d2',
            message: 'Automatically unsubscribed due to permanent delivery failure'
        }
    }

    constructor(props) {
        Object.assign(this, props);
    }

    get icon() {
        return this.eventProperties[this.event].icon;
    }

    get iconClass() {
        return this.eventProperties[this.event].iconClass;
    }

    get tooltip() {
        return this.eventProperties[this.event].tooltip;
    }

    get message() {
        if (this.email) {
            return this.email.subject;
        }

        return this.eventProperties[this.event].message;
    }
}

export default class MemberActivityFeedComponent extends Component {
    @tracked emailPreview;
    @tracked isShowingAll = false;

    get activities() {
        const activities = [];

        (this.args.emailRecipients || []).forEach((emailRecipient) => {
            if (emailRecipient.openedAtUTC) {
                activities.push(new MemberActivity({
                    event: 'opened',
                    email: emailRecipient.email,
                    timestamp: emailRecipient.openedAtUTC,
                    action: this.openEmailPreview.bind(this, emailRecipient.email)
                }));
            } else if (emailRecipient.failedAtUTC) {
                activities.push(new MemberActivity({
                    event: 'failed',
                    email: emailRecipient.email,
                    timestamp: emailRecipient.failedAtUTC,
                    action: this.openEmailPreview.bind(this, emailRecipient.email)
                }));

                activities.push(new MemberActivity({
                    event: 'unsubscribed',
                    timestamp: emailRecipient.failedAtUTC.add(1, 'second')
                }));
            } else if (emailRecipient.processedAtUTC) {
                activities.push(new MemberActivity({
                    event: 'sent',
                    email: emailRecipient.email,
                    timestamp: emailRecipient.processedAtUTC,
                    action: this.openEmailPreview.bind(this, emailRecipient.email)
                }));
            }
        });

        return activities.sort((a, b) => {
            return b.timestamp.valueOf() - a.timestamp.valueOf();
        });
    }

    get firstActivities() {
        return this.activities.slice(0, 5);
    }

    get remainingActivities() {
        return this.activities.slice(5, this.activities.length);
    }

    @action
    showAll() {
        this.isShowingAll = true;
    }

    @action
    openEmailPreview(email) {
        this.emailPreview = email;
    }

    @action
    closeEmailPreview() {
        this.emailPreview = null;
    }
}
<commit_msg>Removed "unsubscribed" events from member activity feed<commit_after>import Component from '@glimmer/component';
import {action} from '@ember/object';
import {tracked} from '@glimmer/tracking';

class MemberActivity {
    eventProperties = {
        sent: {
            icon: 'send-email',
            iconClass: 'midgrey',
            tooltip: 'Sent email'
        },
        opened: {
            icon: 'eye',
            iconClass: 'green-d2',
            tooltip: 'Opened email'
        },
        failed: {
            icon: 'cross-circle',
            iconClass: 'red-d2',
            tooltip: 'Email delivery failed'
        }
    }

    constructor(props) {
        Object.assign(this, props);
    }

    get icon() {
        return this.eventProperties[this.event].icon;
    }

    get iconClass() {
        return this.eventProperties[this.event].iconClass;
    }

    get tooltip() {
        return this.eventProperties[this.event].tooltip;
    }

    get message() {
        if (this.email) {
            return this.email.subject;
        }

        return this.eventProperties[this.event].message;
    }
}

export default class MemberActivityFeedComponent extends Component {
    @tracked emailPreview;
    @tracked isShowingAll = false;

    get activities() {
        const activities = [];

        (this.args.emailRecipients || []).forEach((emailRecipient) => {
            if (emailRecipient.openedAtUTC) {
                activities.push(new MemberActivity({
                    event: 'opened',
                    email: emailRecipient.email,
                    timestamp: emailRecipient.openedAtUTC,
                    action: this.openEmailPreview.bind(this, emailRecipient.email)
                }));
            } else if (emailRecipient.failedAtUTC) {
                activities.push(new MemberActivity({
                    event: 'failed',
                    email: emailRecipient.email,
                    timestamp: emailRecipient.failedAtUTC,
                    action: this.openEmailPreview.bind(this, emailRecipient.email)
                }));
            } else if (emailRecipient.processedAtUTC) {
                activities.push(new MemberActivity({
                    event: 'sent',
                    email: emailRecipient.email,
                    timestamp: emailRecipient.processedAtUTC,
                    action: this.openEmailPreview.bind(this, emailRecipient.email)
                }));
            }
        });

        return activities.sort((a, b) => {
            return b.timestamp.valueOf() - a.timestamp.valueOf();
        });
    }

    get firstActivities() {
        return this.activities.slice(0, 5);
    }

    get remainingActivities() {
        return this.activities.slice(5, this.activities.length);
    }

    @action
    showAll() {
        this.isShowingAll = true;
    }

    @action
    openEmailPreview(email) {
        this.emailPreview = email;
    }

    @action
    closeEmailPreview() {
        this.emailPreview = null;
    }
}
<|endoftext|>


<commit_before>var express = require('express');
var offeranswer = require('offeranswer');

module.exports = function(cfg){
  var app = express();

  var oarApp = offeranswer(cfg);

  app.use(oarApp);

  app.get('/offers/:phrase', function (req,res,next) {
    oarApp.offerGet(req.params.phrase, req, res, next);
  });

  app.post('/offers/:phrase', function (req,res,next) {
    oarApp.offerPost(req.params.phrase, req, res, next);
  });
};
<commit_msg>Fix offeranswer require call<commit_after>var express = require('express');
var offeranswer = require('./offeranswer.js');

module.exports = function(cfg){
  var app = express();

  var oarApp = offeranswer(cfg);

  app.use(oarApp);

  app.get('/offers/:phrase', function (req,res,next) {
    oarApp.offerGet(req.params.phrase, req, res, next);
  });

  app.post('/offers/:phrase', function (req,res,next) {
    oarApp.offerPost(req.params.phrase, req, res, next);
  });
};
<|endoftext|>


<commit_before>/**
 * Test ammo.js library
 * @type {exports}
 */

var utils = require('./test-utils.js');
var Ammo = require('../lib/ammo.js');
var THREE = require('../lib/three.js');
var factory = require('../factory.js');
var _ = require('../lib/underscore.js');

factory.addLibrary(Ammo);
factory.addLibrary(THREE);

var test = {
  'shape.box': function () {
    var obj = {};
    var pars = {dx: 4, dy: 3, dz: 6};
    var titlePrefix = 'shape.box';
    factory.extendFromDescription(obj, 'shape', 'box', pars);
    utils.checkValues(obj, pars, titlePrefix + ' property values');
    utils.checkKeys(obj.ammo, ['setLocalScaling', 'calculateLocalInertia'], titlePrefix + '.ammo keys');
    utils.checkKeys(obj.three, ['vertices', 'boundingBox'], titlePrefix + '.three keys');
    utils.instanceOf(obj.ammo, Ammo.btBoxShape, titlePrefix + '.ammo is btBoxShape');
    utils.instanceOf(obj.three, THREE.BoxGeometry, titlePrefix + '.three is BoxGeometry');
  },
  'physics.velocity': function () {
    var obj = {};
    var pars = {x: 4, y: 3, dz: 1};
    var titlePrefix = 'physics.velocity';
    factory.extendFromDescription(obj, 'physics', 'velocity', pars);
    utils.checkValues(obj, pars, titlePrefix + ' property values');
    utils.checkKeys(obj.ammo, ['x', 'y', 'z'], titlePrefix + '.ammo keys');
    utils.checkKeys(obj.three, ['x', 'y', 'z'], titlePrefix + '.three keys');
    utils.instanceOf(obj.ammo, Ammo.btVector3, titlePrefix + '.ammo is btVector3');
    utils.instanceOf(obj.three, THREE.Vector3, titlePrefix + '.three is Vector3');
  },
  'material.phong': function () {
    var obj = {};
    var pars = {color: utils.randomColor(), friction: 0.12, restitution: 0.11};
    var titlePrefix = 'material.phong';
    factory.extendFromDescription(obj, 'material', 'phong', pars);
    utils.checkValues(obj, pars, titlePrefix + ' property values');
    utils.checkKeys(obj.three, ['color', 'ambient', 'specular','metal'], titlePrefix + '.three keys');
    utils.instanceOf(obj.three, THREE.MeshPhongMaterial, titlePrefix + '.three is MeshPhongMaterial');
  }
};

test.all = utils.all(test);
utils.run(test, process.argv, __filename);

<commit_msg>correct test-factory<commit_after>/**
 * Test ammo.js library
 * @type {exports}
 */

var utils = require('./test-utils.js');
var Ammo = require('../lib/ammo.js');
var THREE = require('../lib/three.js');
var factory = require('../factory.js');
var _ = require('../lib/underscore.js');

factory.addLibrary(Ammo);
factory.addLibrary(THREE);

var test = {
  'shape.box': function () {
    var obj = {};
    var pars = {dx: 4, dy: 3, dz: 6};
    var titlePrefix = 'shape.box';
    factory.extendFromDescription(obj, 'shape', 'box', pars);
    utils.checkValues(obj, pars, titlePrefix + ' property values');
    utils.checkKeys(obj.ammo, ['setLocalScaling', 'calculateLocalInertia'], titlePrefix + '.ammo keys');
    utils.checkKeys(obj.three, ['vertices', 'boundingBox'], titlePrefix + '.three keys');
    utils.instanceOf(obj.ammo, Ammo.btBoxShape, titlePrefix + '.ammo is btBoxShape');
    utils.instanceOf(obj.three, THREE.BoxGeometry, titlePrefix + '.three is BoxGeometry');
  },
  'physics.velocity': function () {
    var obj = {};
    var pars = {x: 4, y: 3, z: 1.1};
    var titlePrefix = 'physics.velocity';
    factory.extendFromDescription(obj, 'physics', 'velocity', pars);
    utils.checkValues(obj, pars, titlePrefix + ' property values');
    utils.checkKeys(obj.ammo, ['x', 'y', 'z'], titlePrefix + '.ammo keys');
    utils.checkKeys(obj.three, ['x', 'y', 'z'], titlePrefix + '.three keys');
    utils.instanceOf(obj.ammo, Ammo.btVector3, titlePrefix + '.ammo is btVector3');
    utils.instanceOf(obj.three, THREE.Vector3, titlePrefix + '.three is Vector3');
  },
  'material.phong': function () {
    var obj = {};
    var pars = {color: utils.randomColor(), friction: 0.12, restitution: 0.11};
    var titlePrefix = 'material.phong';
    factory.extendFromDescription(obj, 'material', 'phong', pars);
    utils.checkValues(obj, pars, titlePrefix + ' property values');
    utils.checkKeys(obj.three, ['color', 'ambient', 'specular','metal'], titlePrefix + '.three keys');
    utils.instanceOf(obj.three, THREE.MeshPhongMaterial, titlePrefix + '.three is MeshPhongMaterial');
  }
};

test.all = utils.all(test);
utils.run(test, process.argv, __filename);

<|endoftext|>


<commit_before>$( document ).ready(function() {
    console.log( "ready!" );

    $('.empty').click(function(concert) {
      $('.empty').slideUp(2000);
    });

    $('.menu').hide();
    $('.menu-items').hide();

  $('#city-submit').click(function(evt) {
    $('#city-name-wrapper h1').empty();
    $('ul').empty();
    $('#map').toggle();

    var map = new GMaps({
          div: '#map',
          lat: 0,
          lng: 0,
          zoom: 12
        });
      var cityname = $('#address').val().toUpperCase();
      $('#city-name-wrapper h1').append(cityname);

    $.ajax({
      method: "GET",
      url: "http://ws.audioscrobbler.com/2.0/?method=geo.getEvents&location=" + cityname + "&api_key=2e8b4c0a324101689acd8d782097b1fc&format=json",
      dataType: "json",

      success: function(data) {
        console.log(data);

        for (var i = 0; i < 10; i++) {
          var concert = data.events.event[i];
          $("ul").append("
" + concert.title + "
 " + concert.venue.name + "
  " + formatDate(concert.startDate) + "

");
          $("ul").append("");

          var lat = concert.venue.location['geo:point']['geo:lat'];
          var long = concert.venue.location['geo:point']['geo:long'];

              map.setCenter(lat, long);
              map.addMarker({
                 lat: lat,
                 lng: long,
                 title: cityname,
                 click: function(e) {
                   alert('You clicked in this marker');
                 }
                });

        }

      }

    });
  });

    $('.btn.btn-default.btn-lg').click(function(concert) {
      $('.menu').toggle(1000);
      $('.menu-items').delay(500).toggle(1000);
    });

});

function formatDate(date) {
  var d = new Date(date);
  var hh = d.getHours();
  var m = d.getMinutes();
  var s = d.getSeconds();
  var dd = "AM";
  var h = hh;
  if (h >= 12) {
      h = hh-12;
      dd = "PM";
  }
  if (h == 0) {
      h = 12;
  }
  m = m<10?"0"+m:m;

  s = s<10?"0"+s:s;

  /* if you want 2 digit hours:
  h = h<10?"0"+h:h; */

  var pattern = new RegExp("0?"+hh+":"+m+":"+s);

  var replacement = h+":"+m;
  /* if you want to add seconds
  replacement += ":"+s;  */
  replacement += " "+dd;

  return date.replace(pattern,replacement);
}
<commit_msg>submit button change<commit_after>$( document ).ready(function() {
    console.log( "ready!" );

    $('.menu').hide();
    $('.menu-items').hide();

  $('#city-submit').click(function(evt) {
    $('.empty').slideUp(2000);
    $('#city-name-wrapper h1').empty();
    $('ul').empty();
    $('#map').toggle();

    var map = new GMaps({
          div: '#map',
          lat: 0,
          lng: 0,
          zoom: 12
        });
      var cityname = $('#address').val().toUpperCase();
      $('#city-name-wrapper h1').append(cityname);

    $.ajax({
      method: "GET",
      url: "http://ws.audioscrobbler.com/2.0/?method=geo.getEvents&location=" + cityname + "&api_key=2e8b4c0a324101689acd8d782097b1fc&format=json",
      dataType: "json",

      success: function(data) {
        console.log(data);

        for (var i = 0; i < 10; i++) {
          var concert = data.events.event[i];
          $("ul").append("

" + concert.title + "
 " + concert.venue.name + "
  " + formatDate(concert.startDate) + "
");
          $("ul").append("");

          var lat = concert.venue.location['geo:point']['geo:lat'];
          var long = concert.venue.location['geo:point']['geo:long'];

              map.setCenter(lat, long);
              map.addMarker({
                 lat: lat,
                 lng: long,
                 title: cityname,
                 click: function(e) {
                   alert('You clicked in this marker');
                 }
                });

        }

      }

    });
  });

    $('.btn.btn-default.btn-lg').click(function(concert) {
      $('.menu').toggle(1000);
      $('.menu-items').delay(500).toggle(1000);
    });

});

function formatDate(date) {
  var d = new Date(date);
  var hh = d.getHours();
  var m = d.getMinutes();
  var s = d.getSeconds();
  var dd = "AM";
  var h = hh;
  if (h >= 12) {
      h = hh-12;
      dd = "PM";
  }
  if (h == 0) {
      h = 12;
  }
  m = m<10?"0"+m:m;

  s = s<10?"0"+s:s;

  /* if you want 2 digit hours:
  h = h<10?"0"+h:h; */

  var pattern = new RegExp("0?"+hh+":"+m+":"+s);

  var replacement = h+":"+m;
  /* if you want to add seconds
  replacement += ":"+s;  */
  replacement += " "+dd;

  return date.replace(pattern,replacement);
}
<|endoftext|>


<commit_before>/**
 * DQL Queries
 */

var usageError = require('../utils/usageError'),
    utils = require('../utils/helpers'),
    normalize = require('../utils/normalize'),
    _ = require('underscore'),
    Deferred = require('./deferred'),
    async = require('async');

module.exports = {

  /**
   * Join
   *
   * Join with another collection
   * (use optimized join in adapter if one was provided)
   */

  join: function(collection, fk, pk, cb) {
    this._adapter.join(collection, fk, pk, cb);
  },

  /**
   * Create a new record
   *
   * @param {Object || Array} values for single model or array of multiple values
   * @param {Function} callback
   * @return Deferred object if no callback
   */

  create: function(values, cb) {
    var self = this;

    // Handle Deferred where it passes criteria first
    if(arguments.length === 3) {
      var args = Array.prototype.slice.call(arguments);
      cb = args.pop();
      values = args.pop();
    }

    // Return Deferred or pass to adapter
    if(typeof cb !== 'function') {
      return new Deferred(this, this.create, {}, values);
    }

    // Handle Array of values
    if(Array.isArray(values)) {
      return this.createEach(values, cb);
    }

    // Set Default Values if available
    for(var key in this.attributes) {
      if(!values[key] && this.attributes[key].defaultsTo) {
        values[key] = this.attributes[key].defaultsTo;
      }
    }

    // Cast values to proper types (handle numbers as strings)
    values = this._cast.run(values);

    async.series([

      // Run Before Validate Lifecycle Callbacks
      function(cb) {
        var runner = function(item, callback) {
          item(values, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.beforeValidation, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Run Validation
      function(cb) {
        self._validator.validate(values, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Run After Validate Lifecycle Callbacks
      function(cb) {
        var runner = function(item, callback) {
          item(values, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.afterValidation, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Before Create Lifecycle Callback
      function(cb) {
        var runner = function(item, callback) {
          item(values, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.beforeCreate, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      }

    ], function(err) {
      if(err) return cb(err);

      // Automatically add updatedAt and createdAt (if enabled)
      if(self.autoCreatedAt) values.createdAt = new Date();
      if(self.autoUpdatedAt) values.updatedAt = new Date();

      // Transform Values
      values = self._transformer.serialize(values);

      // Clean attributes
      values = self._schema.cleanValues(values);

      // Pass to adapter here
      self._adapter.create(values, function(err, values) {
        if(err) return cb(err);

        // Unserialize values
        values = self._transformer.unserialize(values);

        var runner = function(item, callback) {
          item(values, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        // Run afterCreate Lifecycle Callbacks
        async.eachSeries(self._callbacks.afterCreate, runner, function(err) {
          if(err) return cb(err);

          // Return an instance of Model
          var model = new self._model(values);
          cb(null, model);
        });
      });
    });
  },

  /**
   * Update all records matching criteria
   *
   * @param {Object} query keys
   * @param {Object} attributes to update
   * @param {Function} callback
   * @return Deferred object if no callback
   */

  update: function(options, newValues, cb) {
    var self = this;

    if(typeof options === 'function') {
      cb = options;
      options = null;
    }

    // Return Deferred or pass to adapter
    if(typeof cb !== 'function') {
      return new Deferred(this, this.update, options, newValues);
    }

    // Check if options is something other than an object
    // this allows you to pass in an id to update:
    // ex: model.update(id, cb);
    if(_.isString(options) || _.isNumber(options)) {
      options = { id: options };
    }

    var usage = utils.capitalize(this.identity) + '.update(criteria, newValues, callback)';

    if(!newValues) return usageError('No updated values specified!', usage, cb);
    if(typeof cb !== 'function') return usageError('Invalid callback specified!', usage, cb);

    // Cast values to proper types (handle numbers as strings)
    newValues = this._cast.run(newValues);

    async.series([

      // Run Before Validate Lifecycle Callbacks
      function(cb) {
        var runner = function(item, callback) {
          item(newValues, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.beforeValidation, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Run Validation
      function(cb) {
        self._validator.validate(newValues, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Run After Validate Lifecycle Callbacks
      function(cb) {
        var runner = function(item, callback) {
          item(newValues, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.afterValidation, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Before Save Lifecycle Callback
      function(cb) {
        var runner = function(item, callback) {
          item(newValues, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.beforeSave, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      }

    ], function(err) {
      if(err) return cb(err);

      // Automatically change updatedAt (if enabled)
      if(self.autoUpdatedAt) newValues.updatedAt = new Date();

      // Transform Values
      newValues = self._transformer.serialize(newValues);

      // Clean attributes
      newValues = self._schema.cleanValues(newValues);

      // Transform Search Criteria
      options = self._transformer.serialize(options);

      // Pass to adapter
      self._adapter.update(options, newValues, function(err, values) {
        if(err) return cb(err);

        // If values is not an array, return an array
        if(!Array.isArray(values)) values = [values];

        // Unserialize each value
        var transformedValues = [];

        values.forEach(function(value) {
          value = self._transformer.unserialize(value);
          transformedValues.push(value);
        });

        // Set values array to the transformed array
        values = transformedValues;

        async.each(values, function(record, callback) {

          var runner = function(item, callback) {
            item(record, function(err) {
              if(err) return callback(err);
              callback();
            });
          };

          // Run afterSave Lifecycle Callbacks on each record
          async.eachSeries(self._callbacks.afterSave, runner, function(err) {
            if(err) return callback(err);
            callback();
          });

        }, function(err) {
          if(err) return cb(err);

          var models = [];

          // Make each result an instance of model
          values.forEach(function(value) {
            models.push(new self._model(value));
          });

          cb(null, models);
        });
      });
    });
  },

  /**
   * Destroy a Record
   *
   * @param {Object} criteria to destroy
   * @param {Function} callback
   * @return Deferred object if no callback
   */

  destroy: function(criteria, cb) {
    var self = this;

    if(typeof criteria === 'function') {
      cb = criteria;
      criteria = {};
    }

    // Return Deferred or pass to adapter
    if(typeof cb !== 'function') {
      return new Deferred(this, this.destroy, criteria);
    }

    var usage = utils.capitalize(this.identity) + '.destroy([options], callback)';

    var runner = function(item, callback) {
      item(criteria, function(err) {
        if(err) return callback(err);
        callback();
      });
    };

    // Run beforeDestroy Lifecycle Callback
    async.eachSeries(this._callbacks.beforeDestroy, runner, function(err) {
      if(err) return cb(err);

      // Transform Search Criteria
      criteria = self._transformer.serialize(criteria);

      // Pass to adapter
      self._adapter.destroy(criteria, function(err, result) {
        var runner = function(item, callback) {
          item(function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        // Run afterDestroy Lifecycle Callback
        async.eachSeries(self._callbacks.afterDestroy, runner, function(err) {
          if(err) return cb(err);
          cb(null, result);
        });
      });
    });
  },

  /**
   * Count of Records
   *
   * @param {Object} criteria
   * @param {Object} options
   * @param {Function} callback
   * @return Deferred object if no callback
   */

  count: function(criteria, options, cb) {
    var usage = utils.capitalize(this.identity) + '.count([criteria],[options],callback)';

    if(typeof criteria === 'function') {
      cb = criteria;
      criteria = null;
      options = null;
    }

    if(typeof options === 'function') {
      cb = options;
      options = null;
    }

    // Normalize criteria and fold in options
    criteria = normalize.criteria(criteria);

    if(_.isObject(options) && _.isObject(criteria)) {
      criteria = _.extend({}, criteria, options);
    }

    if(_.isFunction(criteria) || _.isFunction(options)) {
      return usageError('Invalid options specified!', usage, cb);
    }

    // Transform Search Criteria
    criteria = this._transformer.serialize(criteria);

    this._adapter.count(criteria, cb);
  }

};
<commit_msg>fix for boolean defaults when set to false<commit_after>/**
 * DQL Queries
 */

var usageError = require('../utils/usageError'),
    utils = require('../utils/helpers'),
    normalize = require('../utils/normalize'),
    _ = require('underscore'),
    Deferred = require('./deferred'),
    async = require('async');

module.exports = {

  /**
   * Join
   *
   * Join with another collection
   * (use optimized join in adapter if one was provided)
   */

  join: function(collection, fk, pk, cb) {
    this._adapter.join(collection, fk, pk, cb);
  },

  /**
   * Create a new record
   *
   * @param {Object || Array} values for single model or array of multiple values
   * @param {Function} callback
   * @return Deferred object if no callback
   */

  create: function(values, cb) {
    var self = this;

    // Handle Deferred where it passes criteria first
    if(arguments.length === 3) {
      var args = Array.prototype.slice.call(arguments);
      cb = args.pop();
      values = args.pop();
    }

    // Return Deferred or pass to adapter
    if(typeof cb !== 'function') {
      return new Deferred(this, this.create, {}, values);
    }

    // Handle Array of values
    if(Array.isArray(values)) {
      return this.createEach(values, cb);
    }

    // Set Default Values if available
    for(var key in this.attributes) {
      if(!values[key] && this.attributes[key].hasOwnProperty('defaultsTo')) {
        values[key] = this.attributes[key].defaultsTo;
      }
    }

    // Cast values to proper types (handle numbers as strings)
    values = this._cast.run(values);

    async.series([

      // Run Before Validate Lifecycle Callbacks
      function(cb) {
        var runner = function(item, callback) {
          item(values, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.beforeValidation, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Run Validation
      function(cb) {
        self._validator.validate(values, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Run After Validate Lifecycle Callbacks
      function(cb) {
        var runner = function(item, callback) {
          item(values, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.afterValidation, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Before Create Lifecycle Callback
      function(cb) {
        var runner = function(item, callback) {
          item(values, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.beforeCreate, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      }

    ], function(err) {
      if(err) return cb(err);

      // Automatically add updatedAt and createdAt (if enabled)
      if(self.autoCreatedAt) values.createdAt = new Date();
      if(self.autoUpdatedAt) values.updatedAt = new Date();

      // Transform Values
      values = self._transformer.serialize(values);

      // Clean attributes
      values = self._schema.cleanValues(values);

      // Pass to adapter here
      self._adapter.create(values, function(err, values) {
        if(err) return cb(err);

        // Unserialize values
        values = self._transformer.unserialize(values);

        var runner = function(item, callback) {
          item(values, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        // Run afterCreate Lifecycle Callbacks
        async.eachSeries(self._callbacks.afterCreate, runner, function(err) {
          if(err) return cb(err);

          // Return an instance of Model
          var model = new self._model(values);
          cb(null, model);
        });
      });
    });
  },

  /**
   * Update all records matching criteria
   *
   * @param {Object} query keys
   * @param {Object} attributes to update
   * @param {Function} callback
   * @return Deferred object if no callback
   */

  update: function(options, newValues, cb) {
    var self = this;

    if(typeof options === 'function') {
      cb = options;
      options = null;
    }

    // Return Deferred or pass to adapter
    if(typeof cb !== 'function') {
      return new Deferred(this, this.update, options, newValues);
    }

    // Check if options is something other than an object
    // this allows you to pass in an id to update:
    // ex: model.update(id, cb);
    if(_.isString(options) || _.isNumber(options)) {
      options = { id: options };
    }

    var usage = utils.capitalize(this.identity) + '.update(criteria, newValues, callback)';

    if(!newValues) return usageError('No updated values specified!', usage, cb);
    if(typeof cb !== 'function') return usageError('Invalid callback specified!', usage, cb);

    // Cast values to proper types (handle numbers as strings)
    newValues = this._cast.run(newValues);

    async.series([

      // Run Before Validate Lifecycle Callbacks
      function(cb) {
        var runner = function(item, callback) {
          item(newValues, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.beforeValidation, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Run Validation
      function(cb) {
        self._validator.validate(newValues, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Run After Validate Lifecycle Callbacks
      function(cb) {
        var runner = function(item, callback) {
          item(newValues, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.afterValidation, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      },

      // Before Save Lifecycle Callback
      function(cb) {
        var runner = function(item, callback) {
          item(newValues, function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        async.eachSeries(self._callbacks.beforeSave, runner, function(err) {
          if(err) return cb(err);
          cb();
        });
      }

    ], function(err) {
      if(err) return cb(err);

      // Automatically change updatedAt (if enabled)
      if(self.autoUpdatedAt) newValues.updatedAt = new Date();

      // Transform Values
      newValues = self._transformer.serialize(newValues);

      // Clean attributes
      newValues = self._schema.cleanValues(newValues);

      // Transform Search Criteria
      options = self._transformer.serialize(options);

      // Pass to adapter
      self._adapter.update(options, newValues, function(err, values) {
        if(err) return cb(err);

        // If values is not an array, return an array
        if(!Array.isArray(values)) values = [values];

        // Unserialize each value
        var transformedValues = [];

        values.forEach(function(value) {
          value = self._transformer.unserialize(value);
          transformedValues.push(value);
        });

        // Set values array to the transformed array
        values = transformedValues;

        async.each(values, function(record, callback) {

          var runner = function(item, callback) {
            item(record, function(err) {
              if(err) return callback(err);
              callback();
            });
          };

          // Run afterSave Lifecycle Callbacks on each record
          async.eachSeries(self._callbacks.afterSave, runner, function(err) {
            if(err) return callback(err);
            callback();
          });

        }, function(err) {
          if(err) return cb(err);

          var models = [];

          // Make each result an instance of model
          values.forEach(function(value) {
            models.push(new self._model(value));
          });

          cb(null, models);
        });
      });
    });
  },

  /**
   * Destroy a Record
   *
   * @param {Object} criteria to destroy
   * @param {Function} callback
   * @return Deferred object if no callback
   */

  destroy: function(criteria, cb) {
    var self = this;

    if(typeof criteria === 'function') {
      cb = criteria;
      criteria = {};
    }

    // Return Deferred or pass to adapter
    if(typeof cb !== 'function') {
      return new Deferred(this, this.destroy, criteria);
    }

    var usage = utils.capitalize(this.identity) + '.destroy([options], callback)';

    var runner = function(item, callback) {
      item(criteria, function(err) {
        if(err) return callback(err);
        callback();
      });
    };

    // Run beforeDestroy Lifecycle Callback
    async.eachSeries(this._callbacks.beforeDestroy, runner, function(err) {
      if(err) return cb(err);

      // Transform Search Criteria
      criteria = self._transformer.serialize(criteria);

      // Pass to adapter
      self._adapter.destroy(criteria, function(err, result) {
        var runner = function(item, callback) {
          item(function(err) {
            if(err) return callback(err);
            callback();
          });
        };

        // Run afterDestroy Lifecycle Callback
        async.eachSeries(self._callbacks.afterDestroy, runner, function(err) {
          if(err) return cb(err);
          cb(null, result);
        });
      });
    });
  },

  /**
   * Count of Records
   *
   * @param {Object} criteria
   * @param {Object} options
   * @param {Function} callback
   * @return Deferred object if no callback
   */

  count: function(criteria, options, cb) {
    var usage = utils.capitalize(this.identity) + '.count([criteria],[options],callback)';

    if(typeof criteria === 'function') {
      cb = criteria;
      criteria = null;
      options = null;
    }

    if(typeof options === 'function') {
      cb = options;
      options = null;
    }

    // Normalize criteria and fold in options
    criteria = normalize.criteria(criteria);

    if(_.isObject(options) && _.isObject(criteria)) {
      criteria = _.extend({}, criteria, options);
    }

    if(_.isFunction(criteria) || _.isFunction(options)) {
      return usageError('Invalid options specified!', usage, cb);
    }

    // Transform Search Criteria
    criteria = this._transformer.serialize(criteria);

    this._adapter.count(criteria, cb);
  }

};
<|endoftext|>


<commit_before>/**
 * amWiki directory manager
 */

var fs = require('fs');

module.exports = {
    //读取文库文件夹
    readLibraryDir: function (path, callback) {
        if (!/library(\\|\/)$/.test(path)) {
            callback('The path is not a library.');
            return;
        }
        var tree = {};
        var folders = [];
        var files = [];
        try {
            var files1 = fs.readdirSync(path),
                files2, files3,
                path2, path3, path4;
            folders.push(path);
            //第一层，files1，library直接子级，仅允许为文件夹
            for (var i = 0; i < files1.length; i++) {
                path2 = path + files1[i];
                if (fs.statSync(path2).isDirectory(path2)) {
                    try {
                        files2 = fs.readdirSync(path2);
                        folders.push(path2);
                        tree[files1[i]] = {};
                        //第二层，files2，允许为文件夹和文件
                        for (var j = 0; j < files2.length; j++) {
                            path3 = path2 + '/' + files2[j];
                            if (fs.statSync(path3).isDirectory(path3)) {
                                try {
                                    files3 = fs.readdirSync(path3);
                                    folders.push(path3);
                                    tree[files1[i]][files2[j]] = {};
                                    //第三层，files3，仅允许为文件夹，不再深入
                                    for (var k = 0; k < files3.length; k++) {
                                        path4 = path3 + '/' + files3[k];
                                        if (!fs.statSync(path4).isDirectory(path4)) {
                                            tree[files1[i]][files2[j]][files3[k]] = false;
                                            files.push(path4);
                                        }
                                    }
                                } catch(err) {
                                    callback(err);
                                    return;
                                }
                            } else {
                                tree[files1[i]][files2[j]] = false;
                                files.push(path3);
                            }
                        }
                    } catch (err) {
                        callback(err);
                        return;
                    }
                }
            }
        } catch (err) {
            callback(err);
            return;
        }
        callback(null, tree, files, folders);
    },
    //循环检查每个库
    eachLibrary: function (list, stepCallback) {
        var list2 = [];
        var path = '';
        for (var i = 0; i < list.length; i++) {
            //路径缺乏library字段弃用
            if (list[i].indexOf('library') < 0) {
                continue;
            }
            path = list[i].replace(/\\/g, '/').split('library')[0] + 'library/';
            //路径不存在弃用
            if (!fs.existsSync(path)) {
                continue;
            }
            //路径重复弃用
            var hsPath = false;
            for (var j = 0; j < list2.length; j++) {
                if (list2[j] == list[i]) {
                    hsPath = true;
                }
            }
            if (hsPath) {
                continue;
            }
            //有用路径
            list2.push(path);
            stepCallback && stepCallback(list[i]);
        }
        return list2;
    }
};<commit_msg>允许library直接目录下存在以点号开头的额外文件夹，不做语法与文档检查，例如.git<commit_after>/**
 * amWiki directory manager
 */

var fs = require('fs');

module.exports = {
    //读取文库文件夹
    readLibraryDir: function (path, callback) {
        if (!/library(\\|\/)$/.test(path)) {
            callback('The path is not a library.');
            return;
        }
        var tree = {};
        var folders = [];
        var files = [];
        try {
            var files1 = fs.readdirSync(path),
                files2, files3,
                path2, path3, path4;
            folders.push(path);
            //第一层，files1，library直接子级，仅允许为文件夹
            for (var i = 0; i < files1.length; i++) {
                path2 = path + files1[i];
                if (/^\./.test(path2.split('library/')[1])) {
                    continue;
                }
                if (fs.statSync(path2).isDirectory(path2)) {
                    try {
                        files2 = fs.readdirSync(path2);
                        folders.push(path2);
                        tree[files1[i]] = {};
                        //第二层，files2，允许为文件夹和文件
                        for (var j = 0; j < files2.length; j++) {
                            path3 = path2 + '/' + files2[j];
                            if (fs.statSync(path3).isDirectory(path3)) {
                                try {
                                    files3 = fs.readdirSync(path3);
                                    folders.push(path3);
                                    tree[files1[i]][files2[j]] = {};
                                    //第三层，files3，仅允许为文件夹，不再深入
                                    for (var k = 0; k < files3.length; k++) {
                                        path4 = path3 + '/' + files3[k];
                                        if (!fs.statSync(path4).isDirectory(path4)) {
                                            tree[files1[i]][files2[j]][files3[k]] = false;
                                            files.push(path4);
                                        }
                                    }
                                } catch(err) {
                                    callback(err);
                                    return;
                                }
                            } else {
                                tree[files1[i]][files2[j]] = false;
                                files.push(path3);
                            }
                        }
                    } catch (err) {
                        callback(err);
                        return;
                    }
                }
            }
        } catch (err) {
            callback(err);
            return;
        }
        callback(null, tree, files, folders);
    },
    //循环检查每个库
    eachLibrary: function (list, stepCallback) {
        var list2 = [];
        var path = '';
        for (var i = 0; i < list.length; i++) {
            //路径缺乏library字段弃用
            if (list[i].indexOf('library') < 0) {
                continue;
            }
            path = list[i].replace(/\\/g, '/').split('library')[0] + 'library/';
            //路径不存在弃用
            if (!fs.existsSync(path)) {
                continue;
            }
            //路径重复弃用
            var hsPath = false;
            for (var j = 0; j < list2.length; j++) {
                if (list2[j] == list[i]) {
                    hsPath = true;
                }
            }
            if (hsPath) {
                continue;
            }
            //有用路径
            list2.push(path);
            stepCallback && stepCallback(list[i]);
        }
        return list2;
    }
};<|endoftext|>