<commit_before>
angular.module('ASysMonApp').controller('CtrlEnvVar', function($scope, $log, Rest) {
    $('.btn').tooltip({
        container: 'body',
        html: true
    });

    var rootLevel = 0;
    var nodesByFqn = {};

    function initFromResponse(data) {
        $scope.envTree = data.envTree;
        nodesByFqn = {};
        initTreeNodes($scope.envTree, 0, '');

        $('#theTree').html(htmlForAllTrees());
        $('#theTree .data-row')
            .click(function() {
                var fqn = $(this).children('.fqn-holder').text();
                var childrenDiv = $(this).next();
                childrenDiv.slideToggle(50, function() {
                    $scope.$apply(function() {
//                        var nodeIconDiv = dataRow.children('.node-icon');
                        //TODO
//                        if($scope.expansionModel[node.fqn]) {
//                            nodeIconDiv.removeClass('node-icon-collapsed').addClass('node-icon-expanded');
//                        }
//                        else {
//                            nodeIconDiv.addClass('node-icon-collapsed').removeClass('node-icon-expanded');
//                        }
                    });
                });
            })
    }
    function initTreeNodes(nodes, level, prefix) {
        if(nodes) {
            for(var i=0; i<nodes.length; i++) {
                nodes[i].level = level;
                var fqn = prefix + '\n' + (nodes[i].id || nodes[i].name);
                nodes[i].fqn = fqn;
                nodesByFqn[fqn] = nodes[i];
                initTreeNodes(nodes[i].children, level+1, fqn);
            }
        }
    }

    Rest.call('getData', initFromResponse);

    function htmlForAllTrees() {
        var result = '';
        angular.forEach($scope.envTree, function(rootNode) {
            result +=
                '
' +
                    htmlForTreeNode(rootNode) +
                '
';
        });

        return result;
    }

    function htmlForTreeNode(curNode) {
        var result =
            '
' +
                '
' + curNode.fqn + '
' +
                '

' +
                (curNode.value ? ('
' + escapeHtml(curNode.value) + '
') : '') +
                '
' + escapeHtml(curNode.name) + '
' +
                '
';

        if(curNode.children && curNode.children.length) {
            result += '
';
            angular.forEach(curNode.children, function(child) {
                result += htmlForTreeNode(child);
            });
            result += '
';
        }
        return result;
    }

    function nodeIconClass(node) {
        if(! node.fqn) {
            //TODO remove this heuristic
            node = nodesByFqn[node];
        }

        if(node.children && node.children.length) {
            return 'node-icon-collapsed';
//            return expansionModel[node.fqn] ? 'node-icon-expanded' : 'node-icon-collapsed';
        }
        return 'node-icon-empty';
    }

    var entityMap = {
        "&": "&",
        "<": "<",
        ">": ">",
        '"': '"',
        "'": ''',
        "/": '/'
    };
    function escapeHtml(string) { //TODO extract to module
        return String(string).replace(/[&<>"'\/]/g, function (s) {
            return entityMap[s];
        });
    }
});

<commit_msg>bugfix: tree icon toggling in 'environment' view<commit_after>
angular.module('ASysMonApp').controller('CtrlEnvVar', function($scope, $log, Rest) {
    $('.btn').tooltip({
        container: 'body',
        html: true
    });

    var rootLevel = 0;
    var nodesByFqn = {};

    function initFromResponse(data) {
        $scope.envTree = data.envTree;
        nodesByFqn = {};
        initTreeNodes($scope.envTree, 0, '');

        $('#theTree').html(htmlForAllTrees());
        $('#theTree .data-row')
            .click(function() {
                var fqn = $(this).children('.fqn-holder').text();
                var childrenDiv = $(this).next();
                var nodeIconDiv = $(this).children('.node-icon');
                var isExpanded = nodeIconDiv.hasClass('node-icon-expanded');

                childrenDiv.slideToggle(50, function() {
                    if(isExpanded) {
                        nodeIconDiv.addClass('node-icon-collapsed').removeClass('node-icon-expanded');
                    }
                    else {
                        nodeIconDiv.removeClass('node-icon-collapsed').addClass('node-icon-expanded');
                    }
                });
            })
    }
    function initTreeNodes(nodes, level, prefix) {
        if(nodes) {
            for(var i=0; i<nodes.length; i++) {
                nodes[i].level = level;
                var fqn = prefix + '\n' + (nodes[i].id || nodes[i].name);
                nodes[i].fqn = fqn;
                nodesByFqn[fqn] = nodes[i];
                initTreeNodes(nodes[i].children, level+1, fqn);
            }
        }
    }

    Rest.call('getData', initFromResponse);

    function htmlForAllTrees() {
        var result = '';
        angular.forEach($scope.envTree, function(rootNode) {
            result +=
                '
' +
                    htmlForTreeNode(rootNode) +
                '
';
        });

        return result;
    }

    function htmlForTreeNode(curNode) {
        var result =
            '
' +
                '
' + curNode.fqn + '
' +
                '

' +
                (curNode.value ? ('
' + escapeHtml(curNode.value) + '
') : '') +
                '
' + escapeHtml(curNode.name) + '
' +
                '
';

        if(curNode.children && curNode.children.length) {
            result += '
';
            angular.forEach(curNode.children, function(child) {
                result += htmlForTreeNode(child);
            });
            result += '
';
        }
        return result;
    }

    function nodeIconClass(node) {
        if(! node.fqn) {
            //TODO remove this heuristic
            node = nodesByFqn[node];
        }

        if(node.children && node.children.length) {
            return 'node-icon-collapsed';
//            return expansionModel[node.fqn] ? 'node-icon-expanded' : 'node-icon-collapsed';
        }
        return 'node-icon-empty';
    }

    var entityMap = {
        "&": "&",
        "<": "<",
        ">": ">",
        '"': '"',
        "'": ''',
        "/": '/'
    };
    function escapeHtml(string) { //TODO extract to module
        return String(string).replace(/[&<>"'\/]/g, function (s) {
            return entityMap[s];
        });
    }
});

<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');

const outputPath = path.join(__dirname, '../next.config.js');

const fileTemplate = (routes) => `
module.exports = {
  exportPathMap: function () {
    return ${routes};
  }
};
`;

const generateRouteDefinitions = (data) => {
  let routes = `
    '/': { page: '/' },
    '/api': { page: '/api' }
  `;

  Object.keys(data).forEach((rootId) => {
    const rootObject = data[rootId];
    const pageIds = Object.keys(rootObject);

    pageIds.forEach((pageId) => {
      routes += `
        '${rootId}/${pageId}': {
          page: '${rootId}/${pageId}'
        },
      `;
    });
  });

  return `{${routes}}`;
};

module.exports = function (data) {
  const routes = generateRouteDefinitions(data);
  fs.writeFile(outputPath, fileTemplate(routes));
};
<commit_msg>adding forward slash to output dir<commit_after>const fs = require('fs');
const path = require('path');

const outputPath = path.join(__dirname, '../next.config.js');

const fileTemplate = (routes) => `
module.exports = {
  exportPathMap: function () {
    return ${routes};
  }
};
`;

const generateRouteDefinitions = (data) => {
  let routes = `
    '/': { page: '/' },
    '/api': { page: '/api' }
  `;

  Object.keys(data).forEach((rootId) => {
    const rootObject = data[rootId];
    const pageIds = Object.keys(rootObject);

    pageIds.forEach((pageId) => {
      routes += `
        '${rootId}/${pageId}': {
          page: '/${rootId}/${pageId}'
        },
      `;
    });
  });

  return `{${routes}}`;
};

module.exports = function (data) {
  const routes = generateRouteDefinitions(data);
  fs.writeFile(outputPath, fileTemplate(routes));
};
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

'use strict';
/* jshint -W015 */

var _ = window._;
var util = require('util');
var Rx = window.Rx;

// Require it so that it gets registered
var selfJoin = require('../rx/selfjoin.js');

/**
 * A map of "builders".  Builders factories for handlers, which know how to handle joining a specific type of event.
 *
 * A builder is a `function()`.  It returns a handler, which is an object of two methods:
 *
 * 1. `canHandle(event)` -- returns boolean if the handler can handle the message
 * 2. `handle(event)` -- "handles" the event and returns either `null` for "not done joining" or an array of events
 * that should be emitted.  Returning an array is an indication that this handler is done handling things and should
 * be thrown away.
 */
function dualNormalBuilder() {
  var eventBuffer = [];
  var normal = null;
  var square = null;
  return {
    completed: function () {
      var retVal = [];

      function addIfNotNull(e) {
        if (e != null) {
          retVal.push(_.assign({}, e, { _unmatched: true }));
        }
      }

      addIfNotNull(normal);
      addIfNotNull(square);
      return retVal.concat(eventBuffer);
    },
    handle: function (event) {
      if (event.type !== 'bolus') {
        eventBuffer.push(event);
        return null;
      }

      switch (event.subType) {
        case 'dual/normal':
          normal = event;
          break;
        case 'dual/square':
          square = event;
          break;
        default:
          eventBuffer.push(event);
          return null;
      }

      if (normal == null || square == null) {
        return null;
      }

      if (normal.groupId !== square.groupId) {
        throw new Error(
          util.format('Mismatched joinKeys[%s][%s] at ts[%s]', normal.groupId, square.groupId, normal.deviceTime)
        );
      }

      return [
        {
          _id: normal._id,
          initialDelivery: normal.value,
          extendedDelivery: square.value,
          value: normal.value + square.value,
          deviceTime: normal.deviceTime,
          duration: square.duration,
          extended: true,
          type: 'bolus'
        }
      ].concat(eventBuffer);
    }
  };
}

if (Rx.Observable.prototype.tidepoolConvertBolus == null) {
  /**
   * A function that does a self-join on the provided eventStream (an Observable) in order to join together
   * bolus records.
   *
   * The idea is basically to intercept a bolus record and if it is of a subType that needs to be joined with
   * other records, we set it aside and start buffering up all other events while we wait for the joined event
   * to be completed.  Once completed, the joined event is emitted and all buffered events are also emitted.

   * @param eventStream an Observable to have its bolus events self-joined.
   */
  Rx.Observable.prototype.tidepoolConvertBolus = function () {
    return this.tidepoolSelfJoin(
      [
        function (e) {
          if (! (e.type === 'bolus' && e.subType === 'dual/normal')) {
            return null;
          }

          if (e._unmatched) {
            return null;
          }

          return dualNormalBuilder();
        }
      ]
    ).map(function(e) {
            // Doing source-specific processing here is pretty broken, but it's the "simplest" way to
            // get it working given a lack of standard for the data type.  When we go back and
            // standardize the tidepool data format, this will probably need adjustment.
            if (e.type === 'bolus' && e.subType === 'square' && e.source === 'diasend') {
              return {
                _id: e._id,
                initialDelivery: e.immediate,
                extendedDelivery: e.extended,
                value: e.value,
                deviceTime: e.deviceTime,
                duration: e.duration,
                extended: true,
                type: 'bolus'
              };
            }
            return e;
          });
  };
}

module.exports = function (eventStream) {
  return eventStream.tidepoolConvertBolus();
};<commit_msg>Use joinKey instead of groupId for joining Bolus objects.<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

'use strict';
/* jshint -W015 */

var _ = window._;
var util = require('util');
var Rx = window.Rx;

// Require it so that it gets registered
var selfJoin = require('../rx/selfjoin.js');

/**
 * A map of "builders".  Builders factories for handlers, which know how to handle joining a specific type of event.
 *
 * A builder is a `function()`.  It returns a handler, which is an object of two methods:
 *
 * 1. `canHandle(event)` -- returns boolean if the handler can handle the message
 * 2. `handle(event)` -- "handles" the event and returns either `null` for "not done joining" or an array of events
 * that should be emitted.  Returning an array is an indication that this handler is done handling things and should
 * be thrown away.
 */
function dualNormalBuilder() {
  var eventBuffer = [];
  var normal = null;
  var square = null;
  var myDeviceId = null;
  return {
    completed: function () {
      var retVal = [];

      function addIfNotNull(e) {
        if (e != null) {
          retVal.push(_.assign({}, e, { _unmatched: true }));
        }
      }

      addIfNotNull(normal);
      addIfNotNull(square);
      return retVal.concat(eventBuffer);
    },
    handle: function (event) {
      if (event.type !== 'bolus') {
        eventBuffer.push(event);
        return null;
      }

      if (myDeviceId != null && event.deviceId !== myDeviceId) {
        eventBuffer.push(event);
        return null;
      }

      switch (event.subType) {
        case 'dual/normal':
          normal = event;
          myDeviceId = event.deviceId;
          break;
        case 'dual/square':
          square = event;
          myDeviceId = event.deviceId;
          break;
        default:
          eventBuffer.push(event);
          return null;
      }

      if (normal == null || square == null) {
        return null;
      }

      if (normal.joinKey !== square.joinKey) {
        throw new Error(
          util.format('Mismatched joinKeys[%s][%s] at ts[%s]', normal.joinKey, square.joinKey, normal.deviceTime)
        );
      }

      return [
        {
          _id: normal._id,
          initialDelivery: normal.value,
          extendedDelivery: square.value,
          value: normal.value + square.value,
          deviceTime: normal.deviceTime,
          duration: square.duration,
          extended: true,
          type: 'bolus'
        }
      ].concat(eventBuffer);
    }
  };
}

if (Rx.Observable.prototype.tidepoolConvertBolus == null) {
  /**
   * A function that does a self-join on the provided eventStream (an Observable) in order to join together
   * bolus records.
   *
   * The idea is basically to intercept a bolus record and if it is of a subType that needs to be joined with
   * other records, we set it aside and start buffering up all other events while we wait for the joined event
   * to be completed.  Once completed, the joined event is emitted and all buffered events are also emitted.

   * @param eventStream an Observable to have its bolus events self-joined.
   */
  Rx.Observable.prototype.tidepoolConvertBolus = function () {
    return this.tidepoolSelfJoin(
      [
        function (e) {
          if (! (e.type === 'bolus' && e.subType === 'dual/normal')) {
            return null;
          }

          if (e._unmatched) {
            return null;
          }

          return dualNormalBuilder();
        }
      ]
    ).map(function(e) {
            // Doing source-specific processing here is pretty broken, but it's the "simplest" way to
            // get it working given a lack of standard for the data type.  When we go back and
            // standardize the tidepool data format, this will probably need adjustment.
            if (e.type === 'bolus' && e.subType === 'square' && e.source === 'diasend') {
              return {
                _id: e._id,
                initialDelivery: e.immediate,
                extendedDelivery: e.extended,
                value: e.value,
                deviceTime: e.deviceTime,
                duration: e.duration,
                extended: true,
                type: 'bolus'
              };
            }
            return e;
          });
  };
}

module.exports = function (eventStream) {
  return eventStream.tidepoolConvertBolus();
};<|endoftext|>


<commit_before>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.core.ViewBase');

goog.require('org.apache.flex.core.UIBase');
goog.require('org.apache.flex.core.ValuesManager');
goog.require('org.apache.flex.events.Event');
goog.require('org.apache.flex.events.ValueChangeEvent');
goog.require('org.apache.flex.utils.MXMLDataInterpreter');

/**
 * @constructor
 * @extends {org.apache.flex.core.UIBase}
 */
org.apache.flex.core.ViewBase = function() {
  goog.base(this);

  /**
   * @private
   * @type {Array}
   */
  this.states_ = null;

  /**
   * @private
   * @type {Array}
   */
  this.transitions_ = null;

  /**
   * @private
   * @type {string}
   */
  this.currentState_ = null;

};
goog.inherits(org.apache.flex.core.ViewBase, org.apache.flex.core.UIBase);

/**
 * @expose
 * @type {Object}
 */
org.apache.flex.core.ViewBase.prototype.applicationModel = null;

/**
 * @expose
 * @type {Array}
 */
org.apache.flex.core.ViewBase.prototype.MXMLProperties = null;

/**
 * @expose
 * @type {Array}
 */
org.apache.flex.core.ViewBase.prototype.MXMLDescriptor = null;

/**
 */
org.apache.flex.core.ViewBase.prototype.addedToParent = function() {

  //goog.base(this,'addedToParent');

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLProperties(this,
      this.get_MXMLProperties());

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLInstances(this,
      this, this.get_MXMLDescriptor());

  this.dispatchEvent(new org.apache.flex.events.Event('initComplete'));
};

/**
 * @expose
 * @return {Object} The application model.
 */
org.apache.flex.core.ViewBase.prototype.get_applicationModel = function() {
  return this.applicationModel;
};

/**
 * @expose
 * @return {Array} The array of State objects.
 */
org.apache.flex.core.ViewBase.prototype.get_states = function() {
  return this.states_;
};

/**
 * @expose
 * @param {Array} value The array of State objects.
 */
org.apache.flex.core.ViewBase.prototype.set_states = function(value) {
  this.states_ = value;

  var impl = org.apache.flex.core.ValuesManager.valuesImpl.
      getValue(this, 'iStatesImpl');
  // TODO: (aharui) check if bead already exists
  this.addBead(new impl());
};

/**
 * @expose
 * @param {string} state The name of the state.
 * @return {boolean} True if state in states array.
 */
org.apache.flex.core.ViewBase.prototype.hasState = function(state) {
  for (var p in this.states_)
  {
    var s = this.states_[p];
    if (s.name == state)
      return true;
  }
  return false;
};

/**
 * @expose
 * @return {string} The name of the current state.
 */
org.apache.flex.core.ViewBase.prototype.get_currentState = function() {
  return this.currentState_;
};

/**
 * @expose
 * @param {string} value The name of the current state.
 */
org.apache.flex.core.ViewBase.prototype.set_currentState = function(value) {
  var event = new org.apache.flex.events.ValueChangeEvent(
      'currentStateChanged', this.currentState_, value);
  this.currentState_ = value;
  this.dispatchEvent(event);
};

/**
 * @expose
 * @return {Array} The array of transitions.
 */
org.apache.flex.core.ViewBase.prototype.get_transitions = function() {
  return this.transitions_;
};

/**
 * @expose
 * @param {Array} value The array of transitions.
 */
org.apache.flex.core.ViewBase.prototype.set_transitions = function(value) {
  this.transitions_ = value;
};

<commit_msg>Support custom styles in fx:Style blocks<commit_after>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.core.ViewBase');

goog.require('org.apache.flex.core.UIBase');
goog.require('org.apache.flex.core.ValuesManager');
goog.require('org.apache.flex.events.Event');
goog.require('org.apache.flex.events.ValueChangeEvent');
goog.require('org.apache.flex.utils.MXMLDataInterpreter');

/**
 * @constructor
 * @extends {org.apache.flex.core.UIBase}
 */
org.apache.flex.core.ViewBase = function() {
  goog.base(this);

  /**
   * @private
   * @type {Array}
   */
  this.states_ = null;

  /**
   * @private
   * @type {Array}
   */
  this.transitions_ = null;

  /**
   * @private
   * @type {string}
   */
  this.currentState_ = null;

};
goog.inherits(org.apache.flex.core.ViewBase, org.apache.flex.core.UIBase);

/**
 * @expose
 * @type {Object}
 */
org.apache.flex.core.ViewBase.prototype.applicationModel = null;

/**
 * @expose
 * @type {Array}
 */
org.apache.flex.core.ViewBase.prototype.MXMLProperties = null;

/**
 * @expose
 * @type {Array}
 */
org.apache.flex.core.ViewBase.prototype.MXMLDescriptor = null;

/**
 */
org.apache.flex.core.ViewBase.prototype.addedToParent = function() {

  //goog.base(this,'addedToParent');
  org.apache.flex.core.ValuesManager.valuesImpl.init(this);

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLProperties(this,
      this.get_MXMLProperties());

  org.apache.flex.utils.MXMLDataInterpreter.generateMXMLInstances(this,
      this, this.get_MXMLDescriptor());

  this.dispatchEvent(new org.apache.flex.events.Event('initComplete'));
};

/**
 * @expose
 * @return {Object} The application model.
 */
org.apache.flex.core.ViewBase.prototype.get_applicationModel = function() {
  return this.applicationModel;
};

/**
 * @expose
 * @return {Array} The array of State objects.
 */
org.apache.flex.core.ViewBase.prototype.get_states = function() {
  return this.states_;
};

/**
 * @expose
 * @param {Array} value The array of State objects.
 */
org.apache.flex.core.ViewBase.prototype.set_states = function(value) {
  this.states_ = value;

  var impl = org.apache.flex.core.ValuesManager.valuesImpl.
      getValue(this, 'iStatesImpl');
  // TODO: (aharui) check if bead already exists
  this.addBead(new impl());
};

/**
 * @expose
 * @param {string} state The name of the state.
 * @return {boolean} True if state in states array.
 */
org.apache.flex.core.ViewBase.prototype.hasState = function(state) {
  for (var p in this.states_)
  {
    var s = this.states_[p];
    if (s.name == state)
      return true;
  }
  return false;
};

/**
 * @expose
 * @return {string} The name of the current state.
 */
org.apache.flex.core.ViewBase.prototype.get_currentState = function() {
  return this.currentState_;
};

/**
 * @expose
 * @param {string} value The name of the current state.
 */
org.apache.flex.core.ViewBase.prototype.set_currentState = function(value) {
  var event = new org.apache.flex.events.ValueChangeEvent(
      'currentStateChanged', this.currentState_, value);
  this.currentState_ = value;
  this.dispatchEvent(event);
};

/**
 * @expose
 * @return {Array} The array of transitions.
 */
org.apache.flex.core.ViewBase.prototype.get_transitions = function() {
  return this.transitions_;
};

/**
 * @expose
 * @param {Array} value The array of transitions.
 */
org.apache.flex.core.ViewBase.prototype.set_transitions = function(value) {
  this.transitions_ = value;
};

<|endoftext|>


<commit_before>import Ember from 'ember';
import BaseValidator from 'ember-cp-validations/validators/base';

const { isEmpty, RSVP } = Ember;
const { Promise } = RSVP;

export default BaseValidator.extend({
  validate(value, options) {
    let promise = options['in'];
    if (isEmpty(promise)) {
      return true;
    }

    return new Promise(resolve => {
      promise.then(excluded => {
        if (excluded.contains(value)) {
          resolve(this.createErrorMessage('exclusion', value, options));
        }
      });
    });
  }
});
<commit_msg>Fix async-exclusion validator<commit_after>import Ember from 'ember';
import BaseValidator from 'ember-cp-validations/validators/base';

const { isEmpty, RSVP } = Ember;
const { Promise } = RSVP;

export default BaseValidator.extend({
  validate(value, options) {
    let promise = options['in'];
    if (isEmpty(promise)) {
      return true;
    }

    return new Promise(resolve => {
      promise.then(excluded => {
        if (excluded.contains(value)) {
          resolve(this.createErrorMessage('exclusion', value, options));
        } else {
          resolve(true);
        }
      });
    });
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import AmountPicker from '../../components/public_group/AmountPicker';

export default class PublicGroupJoinUs extends React.Component {
  _showTier(tier, index) {
    const { donateToGroup } = this.props;

    return (
      <div className='md-col-6 col-12 px3 pb4 mb4 border-box flex' key={`${tier.name}_${index}`}>

            Become a {tier.title}

            {tier.description}

          <AmountPicker tier={tier} onToken={donateToGroup.bind(this)} {...this.props}/>

    );
  }

  render() {
    const { group } = this.props;

    return (

Join us and help fulfill our mission!

With your membership plan, you’ll help us cover all the expenses the collective needs to keep going!

            {group.tiers.map(::this._showTier)}

    );
  }
};
<commit_msg>reverting back to tier.name (#149)<commit_after>import React from 'react';
import AmountPicker from '../../components/public_group/AmountPicker';

export default class PublicGroupJoinUs extends React.Component {
  _showTier(tier, index) {
    const { donateToGroup } = this.props;

    return (
      <div className='md-col-6 col-12 px3 pb4 mb4 border-box flex' key={`${tier.name}_${index}`}>

            Become a {tier.name}

            {tier.description}

          <AmountPicker tier={tier} onToken={donateToGroup.bind(this)} {...this.props}/>

    );
  }

  render() {
    const { group } = this.props;

    return (

Join us and help fulfill our mission!

With your membership plan, you’ll help us cover all the expenses the collective needs to keep going!

            {group.tiers.map(::this._showTier)}

    );
  }
};
<|endoftext|>


<commit_before>"use strict";

var Stroke = function(brush) {
    this.brush = brush;
    this.traces = [];
};

var Trace = function(x, y, p, t) {
    this.x = x;
    this.y = y;
    this.p = p;
    this.t = t;
};

var Brush = function(radius, globalAlpha, spacing, fillStyle, globalCompositeOperation) {
    var distance;
    var prevX;
    var prevY;
    var prevP;
    var lastX;
    var lastY;
    var direction;
    this.name = 'arc';
    this.radius = radius;
    this.globalAlpha = globalAlpha;
    this.spacing = spacing;
    this.fillStyle = fillStyle;
    this.globalCompositeOperation = globalCompositeOperation;
    this.draw = function(canvas, trace) {
        var ctx = canvas[0].getContext('2d');
        ctx.globalAlpha = this.globalAlpha;
        ctx.fillStyle = this.fillStyle;
        ctx.globalCompositeOperation = this.globalCompositeOperation;
        ctx.beginPath();
        ctx.arc(trace.x, trace.y, trace.p * this.radius, 0, Math.PI * 2);
        ctx.fill();
        ctx.closePath();
    };
    this.down = function(canvas, trace) {
        lastX = prevX = trace.x;
        lastY = prevY = trace.y;
        prevP = trace.p;
        distance = 0;
        this.draw(canvas, trace);
    };
    this.move = function(canvas, trace) {
        var dx = trace.x - prevX;
        var dy = trace.y - prevY;
        var dp = trace.p - prevP;
        distance += Math.sqrt(dx * dx + dy * dy);
        prevX = trace.x;
        prevY = trace.y;
        var ldx = trace.x - lastX;
        var ldy = trace.y - lastY;
        var ld = Math.sqrt(ldx * ldx + ldy * ldy);
        direction = Math.atan2(ldy, ldx);
        var midScale = (prevP + trace.p) / 2;
        var drawSpacing = this.radius * this.spacing * midScale;
        if (drawSpacing === 0) {
            return
        }
        if (distance < drawSpacing) {
            prevP = trace.p;
            return
        }
        var scaleSpacing = dp * (drawSpacing / distance);
        if (ld < drawSpacing) {
            lastX = trace.x;
            lastY = trace.y;
            distance -= drawSpacing;
            this.draw(canvas, new Trace(lastX, lastY, trace.p, new Date().getTime()));
        } else {
            while (distance >= drawSpacing) {
                var tx = Math.cos(direction);
                var ty = Math.sin(direction);
                lastX += tx * drawSpacing;
                lastY += ty * drawSpacing;
                prevP += scaleSpacing;
                distance -= drawSpacing;
                this.draw(canvas, new Trace(lastX, lastY, prevP, new Date().getTime()));
            }
        }
    };
};

var brush;
var stroke;
var isLocked;
var isDrawing;
var replayStrokes;

function getPressure(wacom) {
    var defaultPressure = 0.5;
    if ($('#tablet').is(':checked')) {
        if (wacom === undefined) {
            return defaultPressure
        } else {
            return wacom.pressure
        }
    } else {
        return defaultPressure
    }
}

function getGlobalCompositeOperation(wacom) {
    var destinationOut = 'destination-out';
    var sourceOver = 'source-over';
    var defaultOperation;
    if ($('#eraser').is(':checked')) {
        defaultOperation = destinationOut
    } else {
        defaultOperation = sourceOver
    }
    if ($('#tablet').is(':checked')) {
        if (wacom === undefined) {
            return defaultOperation
        } else {
            if (wacom.isEraser) {
                return destinationOut
            } else {
                return sourceOver
            }
        }
    } else {
        return defaultOperation
    }
}

function replayCanvas() {
    var canvas = $('#replay_canvas');
    var width = canvas.width();
    var height = canvas.height();
    var playerCanvas = $('<canvas></canvas>')
        .attr('id', 'replay_canvas')
        .attr('width', width)
        .attr('height', height);
    canvas.replaceWith(playerCanvas);
    $.get('strokes', function(data) {
        replayStrokes = data.strokes;
        setInterval(replayStroke, 10);
    });
}

function replayStroke() {
    if (replayStrokes.length) {
        var playerCanvas = $('#replay_canvas');
        var stroke = replayStrokes.shift();
        var brush = new Brush(
            stroke.brush.radius,
            stroke.brush.globalAlpha,
            stroke.brush.spacing,
            stroke.brush.fillStyle,
            stroke.brush.globalCompositeOperation
        );
        brush.down(playerCanvas, stroke.traces.shift());
        while (stroke.traces.length) {
            brush.move(playerCanvas, stroke.traces.shift());
        }
    }
}

$(document).ready(function() {
    var strokes = [];
    var save = $('#save');
    var canvas = $('#canvas');
    $('#replay').on('click', replayCanvas);
    canvas.on('mousedown', function(e) {
        var pressure = getPressure(wacom);
        if (pressure !== 0) {
            if (!isLocked) {
                isLocked = true;
                $('#width').prop('disabled', true);
                $('#height').prop('disabled', true);
            }
            isDrawing = true;
            brush = new Brush(
                $('#radius').val(),
                $('#flow').val(),
                $('#spacing').val(),
                $('#color').val(),
                getGlobalCompositeOperation(wacom)
            );
            stroke = new Stroke(brush);
            var trace = new Trace(e.offsetX, e.offsetY, pressure, new Date().getTime());
            stroke.traces.push(trace);
            brush.down(canvas, trace);
        }
    });
    canvas.on('mousemove', function(e) {
        if (isDrawing) {
            var trace = new Trace(e.offsetX, e.offsetY, getPressure(wacom), new Date().getTime());
            stroke.traces.push(trace);
            brush.move(canvas, trace);
        }
    });
    canvas.on('mouseup mouseleave', function() {
        if (stroke) {
            strokes.push(stroke);
        }
        isDrawing = false;
        brush = undefined;
        stroke = undefined;
    });
    save.submit(function(e) {
        $('#submit').prop('disabled', true);
        $.ajax({
            url: save[0].action,
            type: save[0].method,
            dataType: 'json',
            data: {
                title: $('#title').val(),
                description: $('#description').val(),
                canvas: canvas[0].toDataURL(),
                strokes: JSON.stringify(strokes)
            },
            success: function(data) {
                window.location.replace(data.location);
            },
            error: function() {
                $('#submit').prop('disabled', false);
            }
        });
        e.preventDefault();
    });
    var width = $('#width');
    width.on('change', function() {
        canvas[0].width = width.val();
    });
    var height = $('#height');
    height.on('change', function() {
        canvas[0].height = height.val();
    })
});
<commit_msg>Bring back wacom<commit_after>"use strict";

var Stroke = function(brush) {
    this.brush = brush;
    this.traces = [];
};

var Trace = function(x, y, p, t) {
    this.x = x;
    this.y = y;
    this.p = p;
    this.t = t;
};

var Brush = function(radius, globalAlpha, spacing, fillStyle, globalCompositeOperation) {
    var distance;
    var prevX;
    var prevY;
    var prevP;
    var lastX;
    var lastY;
    var direction;
    this.name = 'arc';
    this.radius = radius;
    this.globalAlpha = globalAlpha;
    this.spacing = spacing;
    this.fillStyle = fillStyle;
    this.globalCompositeOperation = globalCompositeOperation;
    this.draw = function(canvas, trace) {
        var ctx = canvas[0].getContext('2d');
        ctx.globalAlpha = this.globalAlpha;
        ctx.fillStyle = this.fillStyle;
        ctx.globalCompositeOperation = this.globalCompositeOperation;
        ctx.beginPath();
        ctx.arc(trace.x, trace.y, trace.p * this.radius, 0, Math.PI * 2);
        ctx.fill();
        ctx.closePath();
    };
    this.down = function(canvas, trace) {
        lastX = prevX = trace.x;
        lastY = prevY = trace.y;
        prevP = trace.p;
        distance = 0;
        this.draw(canvas, trace);
    };
    this.move = function(canvas, trace) {
        var dx = trace.x - prevX;
        var dy = trace.y - prevY;
        var dp = trace.p - prevP;
        distance += Math.sqrt(dx * dx + dy * dy);
        prevX = trace.x;
        prevY = trace.y;
        var ldx = trace.x - lastX;
        var ldy = trace.y - lastY;
        var ld = Math.sqrt(ldx * ldx + ldy * ldy);
        direction = Math.atan2(ldy, ldx);
        var midScale = (prevP + trace.p) / 2;
        var drawSpacing = this.radius * this.spacing * midScale;
        if (drawSpacing === 0) {
            return
        }
        if (distance < drawSpacing) {
            prevP = trace.p;
            return
        }
        var scaleSpacing = dp * (drawSpacing / distance);
        if (ld < drawSpacing) {
            lastX = trace.x;
            lastY = trace.y;
            distance -= drawSpacing;
            this.draw(canvas, new Trace(lastX, lastY, trace.p, new Date().getTime()));
        } else {
            while (distance >= drawSpacing) {
                var tx = Math.cos(direction);
                var ty = Math.sin(direction);
                lastX += tx * drawSpacing;
                lastY += ty * drawSpacing;
                prevP += scaleSpacing;
                distance -= drawSpacing;
                this.draw(canvas, new Trace(lastX, lastY, prevP, new Date().getTime()));
            }
        }
    };
};

var brush;
var stroke;
var isLocked;
var isDrawing;
var replayStrokes;

function getPressure(wacom) {
    var defaultPressure = 0.5;
    if ($('#tablet').is(':checked')) {
        if (wacom === undefined) {
            return defaultPressure
        } else {
            return wacom.pressure
        }
    } else {
        return defaultPressure
    }
}

function getGlobalCompositeOperation(wacom) {
    var destinationOut = 'destination-out';
    var sourceOver = 'source-over';
    var defaultOperation;
    if ($('#eraser').is(':checked')) {
        defaultOperation = destinationOut
    } else {
        defaultOperation = sourceOver
    }
    if ($('#tablet').is(':checked')) {
        if (wacom === undefined) {
            return defaultOperation
        } else {
            if (wacom.isEraser) {
                return destinationOut
            } else {
                return sourceOver
            }
        }
    } else {
        return defaultOperation
    }
}

function replayCanvas() {
    var canvas = $('#replay_canvas');
    var width = canvas.width();
    var height = canvas.height();
    var playerCanvas = $('<canvas></canvas>')
        .attr('id', 'replay_canvas')
        .attr('width', width)
        .attr('height', height);
    canvas.replaceWith(playerCanvas);
    $.get('strokes', function(data) {
        replayStrokes = data.strokes;
        setInterval(replayStroke, 10);
    });
}

function replayStroke() {
    if (replayStrokes.length) {
        var playerCanvas = $('#replay_canvas');
        var stroke = replayStrokes.shift();
        var brush = new Brush(
            stroke.brush.radius,
            stroke.brush.globalAlpha,
            stroke.brush.spacing,
            stroke.brush.fillStyle,
            stroke.brush.globalCompositeOperation
        );
        brush.down(playerCanvas, stroke.traces.shift());
        while (stroke.traces.length) {
            brush.move(playerCanvas, stroke.traces.shift());
        }
    }
}

$(document).ready(function() {
    var wacom = document.getElementById('wacom').penAPI;
    var strokes = [];
    var save = $('#save');
    var canvas = $('#canvas');
    $('#replay').on('click', replayCanvas);
    canvas.on('mousedown', function(e) {
        var pressure = getPressure(wacom);
        if (pressure !== 0) {
            if (!isLocked) {
                isLocked = true;
                $('#width').prop('disabled', true);
                $('#height').prop('disabled', true);
            }
            isDrawing = true;
            brush = new Brush(
                $('#radius').val(),
                $('#flow').val(),
                $('#spacing').val(),
                $('#color').val(),
                getGlobalCompositeOperation(wacom)
            );
            stroke = new Stroke(brush);
            var trace = new Trace(e.offsetX, e.offsetY, pressure, new Date().getTime());
            stroke.traces.push(trace);
            brush.down(canvas, trace);
        }
    });
    canvas.on('mousemove', function(e) {
        if (isDrawing) {
            var trace = new Trace(e.offsetX, e.offsetY, getPressure(wacom), new Date().getTime());
            stroke.traces.push(trace);
            brush.move(canvas, trace);
        }
    });
    canvas.on('mouseup mouseleave', function() {
        if (stroke) {
            strokes.push(stroke);
        }
        isDrawing = false;
        brush = undefined;
        stroke = undefined;
    });
    save.submit(function(e) {
        $('#submit').prop('disabled', true);
        $.ajax({
            url: save[0].action,
            type: save[0].method,
            dataType: 'json',
            data: {
                title: $('#title').val(),
                description: $('#description').val(),
                canvas: canvas[0].toDataURL(),
                strokes: JSON.stringify(strokes)
            },
            success: function(data) {
                window.location.replace(data.location);
            },
            error: function() {
                $('#submit').prop('disabled', false);
            }
        });
        e.preventDefault();
    });
    var width = $('#width');
    width.on('change', function() {
        canvas[0].width = width.val();
    });
    var height = $('#height');
    height.on('change', function() {
        canvas[0].height = height.val();
    })
});
<|endoftext|>


<commit_before>/*
 * gencurrency.js - ilib tool to generate the json data about currency
 *
 * Copyright © 2016, 2018 LGE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This code is intended to be run under node.js
 */
var fs = require('fs');
var util = require('util');
var unifile = require('./unifile.js');
var common = require('./common.js');
var UnicodeFile = unifile.UnicodeFile;
var coelesce = common.coelesce;
var mkdirs = common.makeDirs;
var path = require("path");

function usage() {
    console.log("Usage: gencurrency [-h] [toDir]\n" +
        "Generate the currency.jf files for each country.\n\n" +
        "-h or --help\n" +
        "  this help\n" +
        "toDir\n" +
    "  directory to output the currency.jf json files. Default: current dir.\n");
    process.exit(1);
}

function getUsingCurrency(object) {
    var i, curObj, cur, ret = [];
    for (i = 0; i < object.length; i++) {
        for (curObj in object[i]) {
            if(object[i][curObj]._to === undefined && object[i][curObj]._from !== undefined) {
                ret.push(curObj);
            }
        }
    }
    return ret;
}

function getDecimals(currency, fractions) {
    var cur;
    for(cur in fractions) {
        if(cur === currency) {
            return Number(fractions[cur]._digits);
        }
    }
    /*
     * in CLDR, default _digits value is 2
     * "DEFAULT": {
     *       "_rounding": "0",
     *       "_digits": "2"
     * }
     */
    return 2;
}

function getNameAndSign(currency, cldrData, ilibData) {
    var cur, arr = [];

    for(cur in cldrData) {
        if(cur === currency) {
            if(cldrData[cur]['symbol-alt-narrow'] !== undefined) {
                arr['sign'] = cldrData[cur]['symbol-alt-narrow'];
            } else if(cldrData[cur]['symbol-alt-variant'] !== undefined && cldrData[cur]['symbol-alt-narrow'] === undefined) {
                arr['sign'] = cldrData[cur]['symbol-alt-variant'];
            } else if(cldrData[cur]['symbol-alt-variant'] === undefined && cldrData[cur]['symbol-alt-narrow'] === undefined && ilibData && ilibData[cur] && ilibData[cur]['sign'] !== undefined) {
                arr['sign'] = ilibData[cur]['sign'];
            } else {
                arr['sign'] = cldrData[cur]['symbol'];
            }

            if(arr['sign'] === undefined) {
                arr['sign'] = currency;
            }

            arr['name'] = cldrData[cur].displayName;
            return arr;
        }
    }
    return undefined;
}

var currencyDataFileName;
var toDir = "tmp";

process.argv.forEach(function (val, index, array) {
    if (val === "-h" || val === "--help") {
        usage();
    }
});

if (process.argv.length < 2) {
    console.error('Error: not enough arguments');
    usage();
}

if (process.argv.length > 2) {
    toDir = process.argv[2];
}

console.log("gencurrency - generate currency information files.\n" + "Copyright (c) 2016 LGE\n");
console.log("output dir: " + toDir + "\n");

var ilibDataFileName = path.join(toDir, "currency.json");

if (!fs.existsSync(toDir)) {
    common.makeDirs(toDir);
}

var ilibData = {};
if (fs.existsSync(ilibDataFileName)) {
    var ilibDataString = fs.readFileSync(ilibDataFileName, "utf-8");
    ilibData = JSON.parse(ilibDataString);
}
var supplementalData = require("cldr-data/supplemental/currencyData.json");
var mainData = require("cldr-data/main/en/currencies.json");
var currencyData = supplementalData.supplemental.currencyData;
var currencyDispData = mainData.main['en'].numbers.currencies;
var currencyObj = {}; // for saving currency.jf in each directory
var currencyInfoObj = {}; // currency information object for currency.json
var filename, nameAndSign = [], cur = [];

for (var region in currencyData.region) {
    if (region && currencyData.region[region]) {
        if (region == "150") { // 150 code: europe
            continue;
        } else {
            filename = path.join(toDir, 'und', region);
        }
        if (!fs.existsSync(filename)) {
            mkdirs(filename);
        }

        cur = getUsingCurrency(currencyData.region[region]);

        if(cur.length === 0) {
            continue;
        }
        for (var i = 0; i < cur.length; i++) {
            nameAndSign = getNameAndSign(cur[i], currencyDispData, ilibData);
            currencyObj.currency = cur[i];
            currencyInfoObj[cur[i]] = {};
            console.log(region + '/' + cur[i]);
            currencyInfoObj[cur[i]].name = nameAndSign['name'];
            currencyInfoObj[cur[i]].decimals = getDecimals(cur[i], currencyData.fractions);
            currencyInfoObj[cur[i]].sign = nameAndSign['sign'];
            fn = path.join(filename, "currency.jf");
            fs.writeFileSync(fn, JSON.stringify(currencyObj, true, 4), "utf-8");
        }
    }
}

var keys = Object.keys(currencyInfoObj);
var fnJson = path.join(toDir, "currency.json");
var sortedInfoObj = {};
var key;
var primaryCur = [];

keys.sort();
//for currency that has large circulation
for(var i = keys.length-1; i >= 0; i--) {
    if(keys[i] === "USD") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "CHF") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "RON") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "RUB") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "SEK") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "GBP") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "PKR") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "KES") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "KRW") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
}
for(var i = primaryCur.length-1; i >= 0; i--) {
    keys.unshift(primaryCur[i]);
}
for(var i = 0; i < keys.length; i++) {
    key = keys[i];
    sortedInfoObj[key] = {};
    sortedInfoObj[key].name = currencyInfoObj[key].name
    sortedInfoObj[key].decimals = currencyInfoObj[key].decimals
    sortedInfoObj[key].sign = currencyInfoObj[key].sign
}
fs.writeFileSync(fnJson, JSON.stringify(sortedInfoObj, true, 4), "utf-8");<commit_msg>Add more condition to creat currency.js annd update copyright<commit_after>/*
 * gencurrencies.js - ilib tool to generate the json data about currency
 * the CLDR data files
 *
 * Copyright © 2016, 2018-2019, JEDLSoft
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This code is intended to be run under node.js
 */
var fs = require('fs');
var util = require('util');
var unifile = require('./unifile.js');
var common = require('./common.js');
var UnicodeFile = unifile.UnicodeFile;
var coelesce = common.coelesce;
var mkdirs = common.makeDirs;
var path = require("path");

function usage() {
    console.log("Usage: gencurrency [-h] [toDir]\n" +
        "Generate the currency.jf files for each country.\n\n" +
        "-h or --help\n" +
        "  this help\n" +
        "toDir\n" +
    "  directory to output the currency.jf json files. Default: current dir.\n");
    process.exit(1);
}

function getUsingCurrency(object) {
    var i, curObj, cur, ret = [];
    for (i = 0; i < object.length; i++) {
        for (curObj in object[i]) {
            if(object[i][curObj]._to === undefined && object[i][curObj]._from !== undefined && object[i][curObj]._tender === undefined) {
                ret.push(curObj);
            }
        }
    }
    return ret;
}

function getDecimals(currency, fractions) {
    var cur;
    for(cur in fractions) {
        if(cur === currency) {
            return Number(fractions[cur]._digits);
        }
    }
    /*
     * in CLDR, default _digits value is 2
     * "DEFAULT": {
     *       "_rounding": "0",
     *       "_digits": "2"
     * }
     */
    return 2;
}

function getNameAndSign(currency, cldrData, ilibData) {
    var cur, arr = [];

    for(cur in cldrData) {
        if(cur === currency) {
            if(cldrData[cur]['symbol-alt-narrow'] !== undefined) {
                arr['sign'] = cldrData[cur]['symbol-alt-narrow'];
            } else if(cldrData[cur]['symbol-alt-variant'] !== undefined && cldrData[cur]['symbol-alt-narrow'] === undefined) {
                arr['sign'] = cldrData[cur]['symbol-alt-variant'];
            } else if(cldrData[cur]['symbol-alt-variant'] === undefined && cldrData[cur]['symbol-alt-narrow'] === undefined && ilibData && ilibData[cur] && ilibData[cur]['sign'] !== undefined) {
                arr['sign'] = ilibData[cur]['sign'];
            } else {
                arr['sign'] = cldrData[cur]['symbol'];
            }

            if(arr['sign'] === undefined) {
                arr['sign'] = currency;
            }

            arr['name'] = cldrData[cur].displayName;
            return arr;
        }
    }
    return undefined;
}

var currencyDataFileName;
var toDir = "tmp";

process.argv.forEach(function (val, index, array) {
    if (val === "-h" || val === "--help") {
        usage();
    }
});

if (process.argv.length < 2) {
    console.error('Error: not enough arguments');
    usage();
}

if (process.argv.length > 2) {
    toDir = process.argv[2];
}

console.log("gencurrency - generate currency information files.\n" + "Copyright (c) 2016 LGE\n");
console.log("output dir: " + toDir + "\n");

var ilibDataFileName = path.join(toDir, "currency.json");

if (!fs.existsSync(toDir)) {
    common.makeDirs(toDir);
}

var ilibData = {};
if (fs.existsSync(ilibDataFileName)) {
    var ilibDataString = fs.readFileSync(ilibDataFileName, "utf-8");
    ilibData = JSON.parse(ilibDataString);
}
var supplementalData = require("cldr-data/supplemental/currencyData.json");
var mainData = require("cldr-data/main/en/currencies.json");
var currencyData = supplementalData.supplemental.currencyData;
var currencyDispData = mainData.main['en'].numbers.currencies;
var currencyObj = {}; // for saving currency.jf in each directory
var currencyInfoObj = {}; // currency information object for currency.json
var filename, nameAndSign = [], cur = [];

for (var region in currencyData.region) {
    if (region && currencyData.region[region]) {
        if (region == "150") { // 150 code: europe
            continue;
        } else {
            filename = path.join(toDir, 'und', region);
        }
        if (!fs.existsSync(filename)) {
            mkdirs(filename);
        }

        cur = getUsingCurrency(currencyData.region[region]);

        if(cur.length === 0) {
            continue;
        }
        for (var i = 0; i < cur.length; i++) {
            nameAndSign = getNameAndSign(cur[i], currencyDispData, ilibData);
            currencyObj.currency = cur[i];
            currencyInfoObj[cur[i]] = {};
            console.log(region + '/' + cur[i]);
            currencyInfoObj[cur[i]].name = nameAndSign['name'];
            currencyInfoObj[cur[i]].decimals = getDecimals(cur[i], currencyData.fractions);
            currencyInfoObj[cur[i]].sign = nameAndSign['sign'];
            fn = path.join(filename, "currency.jf");
            fs.writeFileSync(fn, JSON.stringify(currencyObj, true, 4), "utf-8");
        }
    }
}

var keys = Object.keys(currencyInfoObj);
var fnJson = path.join(toDir, "currency.json");
var sortedInfoObj = {};
var key;
var primaryCur = [];

keys.sort();
//for currency that has large circulation
for(var i = keys.length-1; i >= 0; i--) {
    if(keys[i] === "USD") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "CHF") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "RON") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "RUB") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "SEK") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "GBP") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "PKR") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "KES") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
    if(keys[i] === "KRW") {
        primaryCur.push(keys[i]);
        keys.splice(i, 1);
    }
}
for(var i = primaryCur.length-1; i >= 0; i--) {
    keys.unshift(primaryCur[i]);
}
for(var i = 0; i < keys.length; i++) {
    key = keys[i];
    sortedInfoObj[key] = {};
    sortedInfoObj[key].name = currencyInfoObj[key].name
    sortedInfoObj[key].decimals = currencyInfoObj[key].decimals
    sortedInfoObj[key].sign = currencyInfoObj[key].sign
}
fs.writeFileSync(fnJson, JSON.stringify(sortedInfoObj, true, 4), "utf-8");
<|endoftext|>


<commit_before>define(
        [ "DamageCardV2", "DamageCardTrait" ],
        function(DamageCardV2, DamageCardTrait)
        {
            "use strict";
            QUnit.module("DamageCardV2");

            QUnit
                    .test(
                            "DamageCardV2 properties Blinded Pilot",
                            function(assert)
                            {
                                var damage = DamageCardV2.BLINDED_PILOT;
                                var properties = DamageCardV2.properties[damage];
                                assert.equal(properties.name, "Blinded Pilot");
                                assert.equal(properties.trait, DamageCardTrait.PILOT);
                                assert
                                        .equal(
                                                properties.description,
                                                "You cannot perform attacks. After your next opportunity to attack (even if there was no target for an attack), flip this card facedown.");
                                assert.ok(!properties.hasAction);
                                assert.ok(!properties.actionDescription);
                                assert.equal(properties.value, damage);
                            });

            QUnit
                    .test(
                            "DamageCardV2 properties Console Fire",
                            function(assert)
                            {
                                var damage = DamageCardV2.CONSOLE_FIRE;
                                var properties = DamageCardV2.properties[damage];
                                assert.equal(properties.name, "Console Fire");
                                assert.equal(properties.trait, DamageCardTrait.SHIP);
                                assert
                                        .equal(
                                                properties.description,
                                                "At the start of each Combat phase, roll 1 attack die. On a Hit result, suffer 1 damage. Action: Flip this card facedown.");
                                assert.ok(properties.hasAction);
                                assert.equal(properties.value, damage);
                            });

            QUnit.test("keys and values", function(assert)
            {
                // Setup.

                // Run.
                var result = DamageCardV2.values();
                var ownPropertyNames = Object.getOwnPropertyNames(DamageCardV2);

                // Verify.
                ownPropertyNames.forEach(function(key)
                {
                    var key2 = DamageCardV2[key];

                    if (key !== "properties" && typeof key2 === "string")
                    {
                        assert.ok(DamageCardV2.properties[key2], "Missing value for key = " + key);
                    }
                });

                result.forEach(function(value)
                {
                    var p = ownPropertyNames.filter(function(key)
                    {
                        return DamageCardV2[key] === value;
                    });

                    assert.equal(p.length, 1, "Missing key for value = " + value);
                });
            });

            QUnit.test("DamageCardV2.values()", function(assert)
            {
                var values = DamageCardV2.values();
                assert.equal(values.length, 14);
                assert.ok(!values[-1]);
                assert.equal(values[0], DamageCardV2.BLINDED_PILOT);
                assert.equal(values[13], DamageCardV2.WEAPONS_FAILURE);
                assert.ok(!values[14]);
            });

            QUnit.test("DamageCardV2.createDeck()", function(assert)
            {
                var deck = DamageCardV2.createDeck();
                assert.equal(deck.length, 33);
                assert.ok(!deck[-1]);
                assert.ok(deck[0]);
                assert.ok(deck[32]);
                assert.ok(!deck[33]);

                // Count each damage card type.
                var damageToCount = {};
                var damage;
                for (var i = 0; i < deck.length; i++)
                {
                    damage = deck[i];

                    if (damageToCount[damage])
                    {
                        damageToCount[damage] += 1;
                    }
                    else
                    {
                        damageToCount[damage] = 1;
                    }
                }

                // Verify.
                for (damage in damageToCount)
                {
                    if (damage === DamageCardV2.DIRECT_HIT)
                    {
                        assert.equal(damageToCount[damage], 7);
                    }
                    else
                    {
                        assert.equal(damageToCount[damage], 2);
                    }
                }
            });
        });
<commit_msg>Updated data.<commit_after>define(["DamageCardV2", "DamageCardTrait"],
    function(DamageCardV2, DamageCardTrait)
    {
        "use strict";
        QUnit.module("DamageCardV2");

        QUnit
            .test(
                "DamageCardV2 properties Blinded Pilot",
                function(assert)
                {
                    var damage = DamageCardV2.BLINDED_PILOT;
                    var properties = DamageCardV2.properties[damage];
                    assert.equal(properties.name, "Blinded Pilot");
                    assert.equal(properties.trait, DamageCardTrait.PILOT);
                    assert
                        .equal(
                            properties.description,
                            "You cannot perform attacks. After your next opportunity to attack (even if there was no target for an attack), flip this card facedown.");
                    assert.ok(!properties.hasAction);
                    assert.ok(!properties.actionDescription);
                    assert.equal(properties.value, damage);
                });

        QUnit
            .test(
                "DamageCardV2 properties Console Fire",
                function(assert)
                {
                    var damage = DamageCardV2.CONSOLE_FIRE;
                    var properties = DamageCardV2.properties[damage];
                    assert.equal(properties.name, "Console Fire");
                    assert.equal(properties.trait, DamageCardTrait.SHIP);
                    assert
                        .equal(
                            properties.description,
                            "At the start of each Combat phase, roll 1 attack die. On a Hit result, suffer 1 damage.");
                    assert.ok(properties.hasAction);
                    assert.equal(properties.value, damage);
                });

        QUnit.test("keys and values", function(assert)
        {
            // Setup.

            // Run.
            var result = DamageCardV2.values();
            var ownPropertyNames = Object.getOwnPropertyNames(DamageCardV2);

            // Verify.
            ownPropertyNames.forEach(function(key)
            {
                var key2 = DamageCardV2[key];

                if (key !== "properties" && typeof key2 === "string")
                {
                    assert.ok(DamageCardV2.properties[key2], "Missing value for key = " + key);
                }
            });

            result.forEach(function(value)
            {
                var p = ownPropertyNames.filter(function(key)
                {
                    return DamageCardV2[key] === value;
                });

                assert.equal(p.length, 1, "Missing key for value = " + value);
            });
        });

        QUnit.test("DamageCardV2.values()", function(assert)
        {
            var values = DamageCardV2.values();
            assert.equal(values.length, 14);
            assert.ok(!values[-1]);
            assert.equal(values[0], DamageCardV2.BLINDED_PILOT);
            assert.equal(values[13], DamageCardV2.WEAPONS_FAILURE);
            assert.ok(!values[14]);
        });

        QUnit.test("DamageCardV2.createDeck()", function(assert)
        {
            var deck = DamageCardV2.createDeck();
            assert.equal(deck.length, 33);
            assert.ok(!deck[-1]);
            assert.ok(deck[0]);
            assert.ok(deck[32]);
            assert.ok(!deck[33]);

            // Count each damage card type.
            var damageToCount = {};
            var damage;
            for (var i = 0; i < deck.length; i++)
            {
                damage = deck[i];

                if (damageToCount[damage])
                {
                    damageToCount[damage] += 1;
                }
                else
                {
                    damageToCount[damage] = 1;
                }
            }

            // Verify.
            for (damage in damageToCount)
            {
                if (damage === DamageCardV2.DIRECT_HIT)
                {
                    assert.equal(damageToCount[damage], 7);
                }
                else
                {
                    assert.equal(damageToCount[damage], 2);
                }
            }
        });
    });
<|endoftext|>


<commit_before>'use strict';
var _ = require('lodash');

var links = {},
    tagId = 0;

function Tag(name, linkedItem, cloud) {
  this.id = tagId++;
  this.cloud = cloud;
  this.name = name;
  this.count = 0;
  this.links = [];
  this.link(linkedItem);
}

Tag.prototype.link = function(linkedItem) {
  links[linkedItem.id + '-' + this.name] = true;
  this.links.push(linkedItem);
  this.count++;
};

Tag.prototype.select = function() {
  var tag=this;
  this.isSelected = true;
  this.links.forEach(function(linkedItem){
    links[linkedItem.id + '-' + tag.name] = true;
  });
};

Tag.prototype.unselect = function() {
  var tag=this;
  this.isSelected = false;
  this.links.forEach(function(linkedItem){
    links[linkedItem.id + '-' + tag.name] = false;
  });
};

// Cloud multiton

function TagCloud(name) {
  this.name = name;
  this.tagsByName = {};
  this.tags = [];
  this.selected = [];
  _.bindAll(this, 'filterSelected', 'filterUnselected');
}

TagCloud.prototype.get = function(tag) {
  if ( typeof tag === 'string' )  {
    return this.tagsByName[tag];
  } else {
    return tag;
  }
};

TagCloud.prototype.add = function(name, linkedItem){
  if ( !this.tagsByName[name] ) {
    this.tagsByName[name] = new Tag(name, linkedItem, this);
    this.tags.push(this.tagsByName[name]);
  } else {
    this.tagsByName[name].link(linkedItem);
  }
};

TagCloud.prototype.clearSelected = function(){
  _.each(this.selected, function(tag){
    TagCloud.selectedTagNames = _.without(TagCloud.selectedTagNames, tag.name);
    tag.unselect();
  });
  this.selected = [];
};

TagCloud.prototype.toggle = function(tag){
  tag = this.get(tag);
  this[tag.isSelected ? 'unselect' : 'select'](tag);
};

TagCloud.prototype.select = function(tag){
  tag = this.get(tag);
  if ( this.forceSingleSelectedValue ) {
    this.clearSelected();
  }
  tag.select();
  this.selected = _.union(this.selected, [tag]);
  TagCloud.selectedTagNames = _.union(TagCloud.selectedTagNames, [tag.name]);
};

TagCloud.prototype.unselect = function(tag){
  tag = this.get(tag);
  tag.unselect();
  this.selected = _.without(this.selected, tag);
  TagCloud.selectedTagNames = _.without(TagCloud.selectedTagNames, tag.name);
};

TagCloud.prototype.filterUnselected = function(tag){
  tag = this.get(tag);
  return !tag.isSelected;
};

TagCloud.prototype.filterSelected = function(tag){
  tag = this.get(tag);
  return tag.isSelected;
};

TagCloud.prototype.isLinkSelected = function(linkedItem){
  return _.every(this.selected, function(tag) {
    return links[linkedItem.id + '-' + tag.name];
  });
};

// Static API

TagCloud.instances = [];
TagCloud.selectedTagNames = [];
TagCloud.getInstance = function(name) {
  if ( !TagCloud.instances[name] ) {
    TagCloud.instances[name] = new TagCloud(name);
  }
  return TagCloud.instances[name];
};

module.exports = TagCloud;<commit_msg>Do not break TagCloud functionality when directly accessing Tag methods<commit_after>'use strict';
var _ = require('lodash');

var links = {},
    tagId = 0;

function Tag(name, linkedItem, cloud) {
  this.id = tagId++;
  this.cloud = cloud;
  this.name = name;
  this.count = 0;
  this.links = [];
  this.link(linkedItem);
}

Tag.prototype.link = function(linkedItem) {
  links[linkedItem.id + '-' + this.name] = true;
  this.links.push(linkedItem);
  this.count++;
};

Tag.prototype.toggle = function(){
  var tag = this;
  this[tag.isSelected ? 'unselect' : 'select']();
};

Tag.prototype.select = function() {
  var tag=this;
  if ( this.cloud.forceSingleSelectedValue ) {
    this.cloud.clearSelected();
  }
  this.isSelected = true;
  this.links.forEach(function(linkedItem){
    links[linkedItem.id + '-' + tag.name] = true;
  });
  this.cloud.selected = _.union(this.cloud.selected, [tag]);
  TagCloud.selectedTags = _.union(TagCloud.selectedTags, [tag]);
};

Tag.prototype.unselect = function() {
  var tag=this;
  this.isSelected = false;
  this.links.forEach(function(linkedItem){
    links[linkedItem.id + '-' + tag.name] = false;
  });
  this.cloud.selected = _.without(this.cloud.selected, tag);
  TagCloud.selectedTags = _.without(TagCloud.selectedTags, tag);
};

// Cloud multiton

function TagCloud(name) {
  this.name = name;
  this.tagsByName = {};
  this.tags = [];
  this.selected = [];
  _.bindAll(this, 'filterSelected', 'filterUnselected');
}

TagCloud.prototype.get = function(tag) {
  if ( typeof tag === 'string' )  {
    return this.tagsByName[tag];
  } else {
    return tag;
  }
};

TagCloud.prototype.add = function(name, linkedItem){
  if ( !this.tagsByName[name] ) {
    this.tagsByName[name] = new Tag(name, linkedItem, this);
    this.tags.push(this.tagsByName[name]);
  } else {
    this.tagsByName[name].link(linkedItem);
  }
};

TagCloud.prototype.clearSelected = function(){
  _.each(this.selected, function(tag){
    TagCloud.selectedTags = _.without(TagCloud.selectedTags, tag);
    tag.unselect();
  });
  this.selected = [];
};

TagCloud.prototype.toggle = function(tag){
  tag = this.get(tag);
  tag.toggle();
};

TagCloud.prototype.select = function(tag){
  tag = this.get(tag);
  tag.select();
};

TagCloud.prototype.unselect = function(tag){
  tag = this.get(tag);
  tag.unselect();
};

TagCloud.prototype.filterUnselected = function(tag){
  tag = this.get(tag);
  return !tag.isSelected;
};

TagCloud.prototype.filterSelected = function(tag){
  tag = this.get(tag);
  return tag.isSelected;
};

TagCloud.prototype.isLinkSelected = function(linkedItem){
  return _.every(this.selected, function(tag) {
    return links[linkedItem.id + '-' + tag.name];
  });
};

// Static API

TagCloud.instances = [];
TagCloud.selectedTags = [];
TagCloud.getInstance = function(name) {
  if ( !TagCloud.instances[name] ) {
    TagCloud.instances[name] = new TagCloud(name);
  }
  return TagCloud.instances[name];
};

module.exports = TagCloud;<|endoftext|>


<commit_before>
// limbus-buildgen - A "build anywhere" C/C++ makefile/project generator.
// Written in 2014-2016 by Jesper Oskarsson jesosk@gmail.com
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

var should = require('should');
var util = require('./util.js');
var shell = require('./shell.js');

describe('Linking', function () {
    beforeEach(function () {
        return util.beforeEach().then(function () {
            return shell.mkdir('temp/include');
        }).then(function () {
            return shell.copyFiles([
                'linked.c',
                'linked_dynamic.c',
                'source/mylibrary.c',
                'include/mylibrary.h',
                'source/mydynamiclibrary.c',
                'include/mydynamiclibrary.h',
                'math.c',
            ], 'features/linking/', 'temp/');
        });
    });

    afterEach(function () {
        return util.afterEach();
    });

    it('should compile and link correctly given several source files and includes', function () {
        return util.generateCompileAndRun({
            config: {
                type: 'application',
                host: util.host,
                files: [
                    'linked.c',
                    'source/mylibrary.c'
                ],
                includePaths: [
                    'include'
                ],
                outputName: 'linked'
            },
            command: 'linked',
            expectOutputToMatch: /42/
        });
    });

    it('should pass linker flags as is', function () {
        var failFlags = {
            'application': {
                'cl': '/link /NODEFAULTLIB',
                'clang': '-nostdlib',
                'gcc': '-nostdlib'
            },
            'static-library': {
                'cl': '/SUBSYSTEM:BOOT_APPLICATIO',
                'clang': 'q',
                'gcc': 'q'
            },
            'dynamic-library': {
                'cl': '/NODEFAULTLIB',
                'clang': '-fuse-ld=invalid',
                'gcc': '-fuse-ld=invalid'
            }
        };
        var succeedFlags = {
            'application': {
                'cl': '/link /VERSION:1.0',
                'clang': '-s',
                'gcc': '-s'
            },
            'static-library': {
                'cl': '/WX:NO',
                'clang': 'v',
                'gcc': 'v'
            },
            'dynamic-library': {
                'cl': '/VERSION:1.0',
                'clang': '-s',
                'gcc': '-s'
            }
        };

        var linkerFlagsShouldFailForType = function(type, flags) {
            return util.buildSimple({
                type: type,
                host: util.host,
                files: ['simple.c'],
                outputName: 'app',
                linkerFlags: failFlags[type][util.hostCompiler]
            }).then(function () {
                return Promise.reject(new Error(type + ' did not fail'));
            }, function () {
                return Promise.resolve();
            });
        };
        var linkerFlagsShouldSucceedForType = function(type, flags) {
            return util.buildSimple({
                type: type,
                host: util.host,
                files: ['simple.c'],
                outputName: 'app',
                linkerFlags: succeedFlags[type][util.hostCompiler]
            });
        };

        return Promise.resolve().then(function () {
            return linkerFlagsShouldSucceedForType('application');
        }).then(function () {
            return linkerFlagsShouldSucceedForType('static-library');
        }).then(function () {
            return linkerFlagsShouldSucceedForType('dynamic-library');
        }).then(function () {
            return linkerFlagsShouldFailForType('application');
        }).then(function () {
            return linkerFlagsShouldFailForType('static-library');
        }).then(function () {
            return linkerFlagsShouldFailForType('dynamic-library');
        });
    });

    it('should link with libm by default', function () {
        return util.generateCompileAndRun({
            config: {
                type: 'application',
                host: util.host,
                files: [
                    'math.c'
                ],
                outputName: 'math'
            },
            command: 'math',
            expectOutputToMatch: /42/
        });
    });

    it('should compile to an executable with outputName', function () {
        return util.generateCompileAndRun({
            config: {
                type: 'application',
                host: util.host,
                files: [
                    'simple.c'
                ],
                outputName: 'my_executable'
            },
            command: 'my_executable',
            expectOutputToMatch: /42/
        });
    });

    it('should compile a static library and then be able to link to it', function () {
        return util.generateCompileAndRun({
            config: [
                {
                    type: 'static-library',
                    host: util.host,
                    files: [
                        'source/mylibrary.c'
                    ],
                    outputName: 'my_lib_name'
                },
                {
                    type: 'application',
                    host: util.host,
                    files: [
                        'linked.c'
                    ],
                    libraries: [
                        'my_lib_name'
                    ],
                    includePaths: [
                        'include'
                    ],
                    outputName: 'linked_with_library'
                }
            ],
            command: 'linked_with_library',
            expectOutputToMatch: /42/
        });
    });

    it('should compile a dynamic library and then be able to link to it', function () {
        return util.generateCompileAndRun({
            config: [
                {
                    type: 'static-library',
                    host: util.host,
                    files: [
                        'source/mylibrary.c'
                    ],
                    outputName: 'my_lib_name'
                },
                {
                    type: 'dynamic-library',
                    host: util.host,
                    files: [
                        'source/mydynamiclibrary.c'
                    ],
                    libraries: [
                        'my_lib_name'
                    ],
                    outputName: 'my_dyn_lib_name'
                },
                {
                    type: 'application',
                    host: util.host,
                    files: [
                        'linked_dynamic.c'
                    ],
                    libraries: [
                        'my_dyn_lib_name'
                    ],
                    includePaths: [
                        'include'
                    ],
                    // On linux systems the shared object won't be looked for in
                    // the current working directory by default. We just add a
                    // flag so that it is.
                    linkerFlags: (process.platform === 'linux') ? '-Wl,-rpath=.' : '',
                    outputName: 'linked_with_library'
                }
            ],
            command: 'linked_with_library',
            expectOutputToMatch: /42/
        });
    });
});
<commit_msg>Tried to fix dynamically linking integration test on gcc/clang<commit_after>
// limbus-buildgen - A "build anywhere" C/C++ makefile/project generator.
// Written in 2014-2016 by Jesper Oskarsson jesosk@gmail.com
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

var should = require('should');
var util = require('./util.js');
var shell = require('./shell.js');

describe('Linking', function () {
    beforeEach(function () {
        return util.beforeEach().then(function () {
            return shell.mkdir('temp/include');
        }).then(function () {
            return shell.copyFiles([
                'linked.c',
                'linked_dynamic.c',
                'source/mylibrary.c',
                'include/mylibrary.h',
                'source/mydynamiclibrary.c',
                'include/mydynamiclibrary.h',
                'math.c',
            ], 'features/linking/', 'temp/');
        });
    });

    afterEach(function () {
        return util.afterEach();
    });

    it('should compile and link correctly given several source files and includes', function () {
        return util.generateCompileAndRun({
            config: {
                type: 'application',
                host: util.host,
                files: [
                    'linked.c',
                    'source/mylibrary.c'
                ],
                includePaths: [
                    'include'
                ],
                outputName: 'linked'
            },
            command: 'linked',
            expectOutputToMatch: /42/
        });
    });

    it('should pass linker flags as is', function () {
        var failFlags = {
            'application': {
                'cl': '/link /NODEFAULTLIB',
                'clang': '-nostdlib',
                'gcc': '-nostdlib'
            },
            'static-library': {
                'cl': '/SUBSYSTEM:BOOT_APPLICATIO',
                'clang': 'q',
                'gcc': 'q'
            },
            'dynamic-library': {
                'cl': '/NODEFAULTLIB',
                'clang': '-invalid-flag',
                'gcc': '-invalid-flag'
            }
        };
        var succeedFlags = {
            'application': {
                'cl': '/link /VERSION:1.0',
                'clang': '-s',
                'gcc': '-s'
            },
            'static-library': {
                'cl': '/WX:NO',
                'clang': 'v',
                'gcc': 'v'
            },
            'dynamic-library': {
                'cl': '/VERSION:1.0',
                'clang': '-s',
                'gcc': '-s'
            }
        };

        var linkerFlagsShouldFailForType = function(type, flags) {
            return util.buildSimple({
                type: type,
                host: util.host,
                files: ['simple.c'],
                outputName: 'app',
                linkerFlags: failFlags[type][util.hostCompiler]
            }).then(function () {
                return Promise.reject(new Error(type + ' did not fail'));
            }, function () {
                return Promise.resolve();
            });
        };
        var linkerFlagsShouldSucceedForType = function(type, flags) {
            return util.buildSimple({
                type: type,
                host: util.host,
                files: ['simple.c'],
                outputName: 'app',
                linkerFlags: succeedFlags[type][util.hostCompiler]
            });
        };

        return Promise.resolve().then(function () {
            return linkerFlagsShouldSucceedForType('application');
        }).then(function () {
            return linkerFlagsShouldSucceedForType('static-library');
        }).then(function () {
            return linkerFlagsShouldSucceedForType('dynamic-library');
        }).then(function () {
            return linkerFlagsShouldFailForType('application');
        }).then(function () {
            return linkerFlagsShouldFailForType('static-library');
        }).then(function () {
            return linkerFlagsShouldFailForType('dynamic-library');
        });
    });

    it('should link with libm by default', function () {
        return util.generateCompileAndRun({
            config: {
                type: 'application',
                host: util.host,
                files: [
                    'math.c'
                ],
                outputName: 'math'
            },
            command: 'math',
            expectOutputToMatch: /42/
        });
    });

    it('should compile to an executable with outputName', function () {
        return util.generateCompileAndRun({
            config: {
                type: 'application',
                host: util.host,
                files: [
                    'simple.c'
                ],
                outputName: 'my_executable'
            },
            command: 'my_executable',
            expectOutputToMatch: /42/
        });
    });

    it('should compile a static library and then be able to link to it', function () {
        return util.generateCompileAndRun({
            config: [
                {
                    type: 'static-library',
                    host: util.host,
                    files: [
                        'source/mylibrary.c'
                    ],
                    outputName: 'my_lib_name'
                },
                {
                    type: 'application',
                    host: util.host,
                    files: [
                        'linked.c'
                    ],
                    libraries: [
                        'my_lib_name'
                    ],
                    includePaths: [
                        'include'
                    ],
                    outputName: 'linked_with_library'
                }
            ],
            command: 'linked_with_library',
            expectOutputToMatch: /42/
        });
    });

    it('should compile a dynamic library and then be able to link to it', function () {
        return util.generateCompileAndRun({
            config: [
                {
                    type: 'static-library',
                    host: util.host,
                    files: [
                        'source/mylibrary.c'
                    ],
                    outputName: 'my_lib_name'
                },
                {
                    type: 'dynamic-library',
                    host: util.host,
                    files: [
                        'source/mydynamiclibrary.c'
                    ],
                    libraries: [
                        'my_lib_name'
                    ],
                    outputName: 'my_dyn_lib_name'
                },
                {
                    type: 'application',
                    host: util.host,
                    files: [
                        'linked_dynamic.c'
                    ],
                    libraries: [
                        'my_dyn_lib_name'
                    ],
                    includePaths: [
                        'include'
                    ],
                    // On linux systems the shared object won't be looked for in
                    // the current working directory by default. We just add a
                    // flag so that it is.
                    linkerFlags: (process.platform === 'linux') ? '-Wl,-rpath=.' : '',
                    outputName: 'linked_with_library'
                }
            ],
            command: 'linked_with_library',
            expectOutputToMatch: /42/
        });
    });
});
<|endoftext|>


<commit_before>
// limbus-buildgen - A "build anywhere" C/C++ makefile/project generator.
// Written in 2014 by Jesper Oskarsson jesosk@gmail.com
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

var should = require('should');
var fs = require('fs');
var util = require('./util.js');

var setup = function () {
    /* Includes and linking */
    fs.writeFileSync(
        "temp/linked.c",
        fs.readFileSync("features/linking/linked.c"));

    fs.writeFileSync(
        "temp/linked_dynamic.c",
        fs.readFileSync("features/linking/linked_dynamic.c"));

    fs.writeFileSync(
        "temp/source/mylibrary.c",
        fs.readFileSync("features/linking/source/mylibrary.c"));

    fs.writeFileSync(
        "temp/include/mylibrary.h",
        fs.readFileSync("features/linking/include/mylibrary.h"));

    fs.writeFileSync(
        "temp/source/mydynamiclibrary.c",
        fs.readFileSync("features/linking/source/mydynamiclibrary.c"));

    fs.writeFileSync(
        "temp/include/mydynamiclibrary.h",
        fs.readFileSync("features/linking/include/mydynamiclibrary.h"));

    /* Check for libm */
    fs.writeFileSync(
        "temp/math.c",
        fs.readFileSync("features/linking/math.c"));

    fs.writeFileSync(
        "temp/simple.c",
        fs.readFileSync("features/linking/simple.c"));
};

describe('Linking', function () {
    it('should compile and link correctly given several source files and includes', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: {
                type: 'application',
                host: process.platform,
                files: [
                    'linked.c',
                    'source/mylibrary.c'
                ],
                includePaths: [
                    'include'
                ],
                outputName: 'linked'
            },
            command: 'linked',
            expectOutputToMatch: /42/
        }, done);
    });

    it('should link with libm by default', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: {
                type: 'application',
                host: process.platform,
                files: [
                    'math.c'
                ],
                outputName: 'math'
            },
            command: 'math',
            expectOutputToMatch: /42/
        }, done);
    });

    it('should compile to an executable with outputName', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: {
                type: 'application',
                host: process.platform,
                files: [
                    'simple.c'
                ],
                outputName: 'my_executable'
            },
            command: 'my_executable',
            expectOutputToMatch: /42/
        }, done);
    });

    it('should compile a static library and then be able to link to it', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: [
                {
                    type: 'static-library',
                    host: process.platform,
                    files: [
                        'source/mylibrary.c'
                    ],
                    outputName: 'my_lib_name'
                },
                {
                    type: 'application',
                    host: process.platform,
                    files: [
                        'linked.c'
                    ],
                    libraries: [
                        'my_lib_name'
                    ],
                    includePaths: [
                        'include'
                    ],
                    outputName: 'linked_with_library'
                }
            ],
            command: 'linked_with_library',
            expectOutputToMatch: /42/
        }, done);
    });

    it('should compile a dynamic library and then be able to link to it', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: [
                {
                    type: 'static-library',
                    host: process.platform,
                    files: [
                        'source/mylibrary.c'
                    ],
                    outputName: 'my_lib_name'
                },
                {
                    type: 'dynamic-library',
                    host: process.platform,
                    files: [
                        'source/mydynamiclibrary.c'
                    ],
                    libraries: [
                        'my_lib_name'
                    ],
                    outputName: 'my_dyn_lib_name'
                },
                {
                    type: 'application',
                    host: process.platform,
                    files: [
                        'linked_dynamic.c'
                    ],
                    libraries: [
                        'my_dyn_lib_name'
                    ],
                    includePaths: [
                        'include'
                    ],
                    outputName: 'linked_with_library'
                }
            ],
            command: 'linked_with_library',
            expectOutputToMatch: /42/
        }, done);
    });
});
<commit_msg>Fixed linking feature on linux systems<commit_after>
// limbus-buildgen - A "build anywhere" C/C++ makefile/project generator.
// Written in 2014 by Jesper Oskarsson jesosk@gmail.com
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

var should = require('should');
var fs = require('fs');
var util = require('./util.js');

var setup = function () {
    /* Includes and linking */
    fs.writeFileSync(
        "temp/linked.c",
        fs.readFileSync("features/linking/linked.c"));

    fs.writeFileSync(
        "temp/linked_dynamic.c",
        fs.readFileSync("features/linking/linked_dynamic.c"));

    fs.writeFileSync(
        "temp/source/mylibrary.c",
        fs.readFileSync("features/linking/source/mylibrary.c"));

    fs.writeFileSync(
        "temp/include/mylibrary.h",
        fs.readFileSync("features/linking/include/mylibrary.h"));

    fs.writeFileSync(
        "temp/source/mydynamiclibrary.c",
        fs.readFileSync("features/linking/source/mydynamiclibrary.c"));

    fs.writeFileSync(
        "temp/include/mydynamiclibrary.h",
        fs.readFileSync("features/linking/include/mydynamiclibrary.h"));

    /* Check for libm */
    fs.writeFileSync(
        "temp/math.c",
        fs.readFileSync("features/linking/math.c"));

    fs.writeFileSync(
        "temp/simple.c",
        fs.readFileSync("features/linking/simple.c"));
};

describe('Linking', function () {
    it('should compile and link correctly given several source files and includes', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: {
                type: 'application',
                host: process.platform,
                files: [
                    'linked.c',
                    'source/mylibrary.c'
                ],
                includePaths: [
                    'include'
                ],
                outputName: 'linked'
            },
            command: 'linked',
            expectOutputToMatch: /42/
        }, done);
    });

    it('should link with libm by default', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: {
                type: 'application',
                host: process.platform,
                files: [
                    'math.c'
                ],
                outputName: 'math'
            },
            command: 'math',
            expectOutputToMatch: /42/
        }, done);
    });

    it('should compile to an executable with outputName', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: {
                type: 'application',
                host: process.platform,
                files: [
                    'simple.c'
                ],
                outputName: 'my_executable'
            },
            command: 'my_executable',
            expectOutputToMatch: /42/
        }, done);
    });

    it('should compile a static library and then be able to link to it', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: [
                {
                    type: 'static-library',
                    host: process.platform,
                    files: [
                        'source/mylibrary.c'
                    ],
                    outputName: 'my_lib_name'
                },
                {
                    type: 'application',
                    host: process.platform,
                    files: [
                        'linked.c'
                    ],
                    libraries: [
                        'my_lib_name'
                    ],
                    includePaths: [
                        'include'
                    ],
                    outputName: 'linked_with_library'
                }
            ],
            command: 'linked_with_library',
            expectOutputToMatch: /42/
        }, done);
    });

    it('should compile a dynamic library and then be able to link to it', function (done) {
        util.generateCompileAndRun({
            setup: setup,
            config: [
                {
                    type: 'static-library',
                    host: process.platform,
                    files: [
                        'source/mylibrary.c'
                    ],
                    outputName: 'my_lib_name'
                },
                {
                    type: 'dynamic-library',
                    host: process.platform,
                    files: [
                        'source/mydynamiclibrary.c'
                    ],
                    libraries: [
                        'my_lib_name'
                    ],
                    outputName: 'my_dyn_lib_name'
                },
                {
                    type: 'application',
                    host: process.platform,
                    files: [
                        'linked_dynamic.c'
                    ],
                    libraries: [
                        'my_dyn_lib_name'
                    ],
                    includePaths: [
                        'include'
                    ],
                    // On linux systems the shared object won't be looked for in
                    // the current working directory by default. We just add a
                    // flag so that it is.
                    linkerFlags: (process.platform === 'linux') ? '-Wl,-rpath=.' : '',
                    outputName: 'linked_with_library'
                }
            ],
            command: 'linked_with_library',
            expectOutputToMatch: /42/
        }, done);
    });
});
<|endoftext|>