<commit_before>'use strict';

import trimStart from 'lodash/trimStart'
import trimEnd from 'lodash/trimEnd'
import template from 'lodash/template'
import fromPairs from 'lodash/fromPairs'
import isObject from 'lodash/isObject'
import map from 'lodash/map'
import assign from 'lodash/assign'
import last from 'lodash/last'
import tail from 'lodash/tail'
import dropRight from 'lodash/dropRight'
import zipObject from 'lodash/zipObject'
import partial from 'lodash/partial'

const placeHolderRegex = /:([a-zA-Z_][a-zA-Z0-9_]*)/g;

const trimLeadingColon = s => trimStart(s, ':')

function assembleRoute(segment, routes = {}) {
    const renderPath = template(segment, {interpolate: placeHolderRegex});
    return assign(renderPath, assemble(routes, segment));
}

function assemble(routes, prefix = '') {
    return fromPairs(map(routes, (val, key) => {
        const name = isObject(val) ? val.name : val;
        return [name, assembleRoute(prefix + key, isObject(val) ? val.routes : null)];
    }));
}

function matchPath(path, segment) {
  const re = new RegExp('^' + segment.replace(placeHolderRegex, '([^/]+)') + '(/.+)?$');
  return path.match(re);
}

function findMatch(routes, path) {
  for (const segment in routes) {
    if (!routes.hasOwnProperty(segment)) continue
    const match = matchPath(path, segment)
    if (match) return [match, segment]
  }
  return []
}

function match(routes, path, parent = null) {
    const [matched, segment] = findMatch(routes, path)
    if (!matched) return null
    const spec = routes[segment];
    const name = isObject(spec) ? spec.name : spec;
    const props = isObject(spec) ? spec.props : {};
    const childRoutes = isObject(spec) ? spec.routes : null;
    const paramKeys = (segment.match(placeHolderRegex) || []).map(trimLeadingColon);
    const remainingPath = last(matched);
    const params = zipObject(paramKeys, dropRight(tail(matched)));
    if (childRoutes && remainingPath) {
        const childMatch = match(childRoutes, remainingPath, {name, props, params});
        if (childMatch) {
            const [childName, childParams, childRemaining, childProps, childParent] = childMatch
            return [
              [name].concat(childName),
              assign({}, params, childParams),
              childRemaining,
              childProps,
              childParent.concat(parent)
            ];
        }
    }
    return [[name], params, remainingPath, props, [parent]];
}

function resolve(routes, resolveRoute, path) {
    const matched = match(routes, trimEnd(path, '/'));
    if (matched) {
        const [keys, params, remaining, props, parents] = matched
        const parent = parents.reduceRight((parent, child) => assign({parent}, child), null)
        return {
            params,
            remaining,
            props,
            parent,
            route: resolveRoute(keys),
            name: keys.join('.')
        }
    }
    return null;
}

function myro(routes) {
    const routeFns = assemble(routes);
    const resolveRoute = path => path.reduce((obj, key) => obj[key], routeFns)
    return assign(partial(resolve, routes, resolveRoute), routeFns);
}

export default myro
<commit_msg>reduce lodash dependencies.<commit_after>'use strict';

import trimStart from 'lodash/trimStart'
import trimEnd from 'lodash/trimEnd'
import template from 'lodash/template'
import isObject from 'lodash/isObject'
import assign from 'lodash/assign'

const placeHolderRegex = /:([a-zA-Z_][a-zA-Z0-9_]*)/g;

const trimLeadingColon = s => trimStart(s, ':')

function zipObject(keys, vals) {
  const obj = {}
  keys.forEach((key, index) => obj[key] = vals[index])
  return obj
}

function map(obj, f) {
  const result = []
  for (const k in obj) {
    if (obj.hasOwnProperty(k)) result.push(f(obj[k], k))
  }
  return result
}

function fromPairs(pairs) {
  const obj = {}
  pairs.forEach(([key, val]) => obj[key] = val)
  return obj
}

function assembleRoute(segment, routes = {}) {
    const renderPath = template(segment, {interpolate: placeHolderRegex});
    return assign(renderPath, assemble(routes, segment));
}

function assemble(routes, prefix = '') {
    return fromPairs(map(routes, (val, key) => {
        const name = isObject(val) ? val.name : val;
        return [name, assembleRoute(prefix + key, isObject(val) ? val.routes : null)];
    }));
}

function matchPath(path, segment) {
  const re = new RegExp('^' + segment.replace(placeHolderRegex, '([^/]+)') + '(/.+)?$');
  return path.match(re);
}

function findMatch(routes, path) {
  for (const segment in routes) {
    if (!routes.hasOwnProperty(segment)) continue
    const match = matchPath(path, segment)
    if (match) return [match, segment]
  }
  return []
}

function match(routes, path, parent = null) {
    const [matched, segment] = findMatch(routes, path)
    if (!matched) return null
    const spec = routes[segment];
    const name = isObject(spec) ? spec.name : spec;
    const props = isObject(spec) ? spec.props : {};
    const childRoutes = isObject(spec) ? spec.routes : null;
    const paramKeys = (segment.match(placeHolderRegex) || []).map(trimLeadingColon);
    const remainingPath = matched[matched.length-1]
    const params = zipObject(paramKeys, matched.slice(1, -1))
    if (childRoutes && remainingPath) {
        const childMatch = match(childRoutes, remainingPath, {name, props, params});
        if (childMatch) {
            const [childName, childParams, childRemaining, childProps, childParent] = childMatch
            return [
              [name].concat(childName),
              assign({}, params, childParams),
              childRemaining,
              childProps,
              childParent.concat(parent)
            ];
        }
    }
    return [[name], params, remainingPath, props, [parent]];
}

function resolve(routes, resolveRoute, path) {
    const matched = match(routes, trimEnd(path, '/'))
    if (matched) {
        const [keys, params, remaining, props, parents] = matched
        return {
            params,
            remaining,
            props,
            parent: parents.reduceRight((parent, child) => assign({parent}, child), null),
            route: resolveRoute(keys),
            name: keys.join('.')
        }
    }
    return null
}

function myro(routes) {
    const routeFns = assemble(routes)
    const resolveRoute = path => path.reduce((obj, key) => obj[key], routeFns)
    return assign(path => resolve(routes, resolveRoute, path), routeFns)
}

export default myro
<|endoftext|>


<commit_before>/*Copyright (C) 2015 by Marijn Haverbeke <marijnh@gmail.com> and others

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.*/

function getAnnotationHints(cm, options) {
    var cur = cm.getCursor();
    var result = ['Plan:name(\'\')', 'Plan:description(\'\')', 'Plan:trace(\'\')', 'Plan:statistics(\'\')', 'Import(\'\')', 'Export(\'\')'];
    return {
        list: result,
        from: cur,
        to: cur
    };
}

function insertStr(cm, pos, str, option_str) {
    cm.replaceRange(str, pos, null, option_str);
    cm.setCursor({line: pos.line, ch: pos.ch + str.length});
}
<commit_msg>Adding same fix to Siddhi TryIt<commit_after>/*Copyright (C) 2015 by Marijn Haverbeke <marijnh@gmail.com> and others

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.*/

function getAnnotationHints(cm, options) {
    var cur = cm.getCursor();
    var result = [
        'Plan:name(\'\')',
        'Plan:description(\'\')',
        'Plan:trace(\'\')',
        'Plan:statistics(\'\')',
        'Import(\'\')',
        'Export(\'\')',
        'From(eventtable=\'\', )',
        'IndexBy(\'\')'
    ];
    return {
        list: result,
        from: cur,
        to: cur
    };
}

function insertStr(cm, pos, str, option_str) {
    cm.replaceRange(str, pos, null, option_str);
    cm.setCursor({line: pos.line, ch: pos.ch + str.length});
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import utils from '../utils/utils';

const factory = (Checkbox) => {
  class TableRow extends Component {
    static propTypes = {
      data: PropTypes.object,
      index: PropTypes.number,
      model: PropTypes.object,
      onChange: PropTypes.func,
      onSelect: PropTypes.func,
      selectable: PropTypes.bool,
      selected: PropTypes.bool,
      theme: PropTypes.shape({
        editable: PropTypes.string,
        row: PropTypes.string,
        selectable: PropTypes.string,
        selected: PropTypes.string
      })
    };

    handleInputChange = (index, key, type, event) => {
      const value = type === 'checkbox' ? event.target.checked : event.target.value;
      const onChange = this.props.model[key].onChange || this.props.onChange;
      onChange(index, key, value);
    };

    renderSelectCell () {
      if (this.props.selectable) {
        return (

            <Checkbox checked={this.props.selected} onChange={this.props.onSelect} />

        );
      }
    }

    renderCells () {
      return Object.keys(this.props.model).map((key) => {
        return {this.renderCell(key)}	;
      });
    }

    renderCell (key) {
      const value = this.props.data[key];

      // if the value is a valid React element return it directly, since it
      // cannot be edited and should not be converted to a string...
      if (React.isValidElement(value)) { return value; }

      const onChange = this.props.model[key].onChange || this.props.onChange;
      if (onChange) {
        return this.renderInput(key, value);
      } else if (value) {
        return value.toString();
      }
    }

    renderInput (key, value) {
      const index = this.props.index;
      const inputType = utils.inputTypeForPrototype(this.props.model[key].type);
      const inputValue = utils.prepareValueForInput(value, inputType);
      const checked = inputType === 'checkbox' && value ? true : null;
      return (
        <input
          checked={checked}
          onChange={this.handleInputChange.bind(null, index, key, inputType)}
          type={inputType}
          value={inputValue}
        />
      );
    }

    render () {
      const className = classnames(this.props.theme.row, {
        [this.props.theme.editable]: this.props.onChange,
        [this.props.theme.selected]: this.props.selected
      });

      return (

          {this.renderSelectCell()}
          {this.renderCells()}

      );
    }
  }

  return TableRow;
};

export default factory;
<commit_msg>Re-apply changes<commit_after>import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import utils from '../utils/utils';

const factory = (Checkbox) => {
  class TableRow extends Component {
    static propTypes = {
      data: PropTypes.object,
      index: PropTypes.number,
      model: PropTypes.object,
      onChange: PropTypes.func,
      onSelect: PropTypes.func,
      selectable: PropTypes.bool,
      selected: PropTypes.bool,
      theme: PropTypes.shape({
        editable: PropTypes.string,
        row: PropTypes.string,
        selectable: PropTypes.string,
        selected: PropTypes.string
      })
    };

    handleInputChange = (index, key, type, event) => {
      let value;
      switch (type) {
        case 'checkbox':
          value = event.target.checked;
          break;
        // Handle contentEditable
        case 'text':
          value = event.target.textContent;
          break;
        default:
          value = event.target.value;
          break;
      }

      const onChange = this.props.model[key].onChange || this.props.onChange;
      onChange(index, key, value);
    };

    renderSelectCell () {
      if (this.props.selectable) {
        return (

            <Checkbox checked={this.props.selected} onChange={this.props.onSelect} />

        );
      }
    }

    renderCells () {
      return Object.keys(this.props.model).map((key) => {
        return {this.renderCell(key)}	;
      });
    }

    renderCell (key) {
      const value = this.props.data[key];

      // if the value is a valid React element return it directly, since it
      // cannot be edited and should not be converted to a string...
      if (React.isValidElement(value)) { return value; }

      const onChange = this.props.model[key].onChange || this.props.onChange;
      if (onChange) {
        return this.renderInput(key, value);
      } else if (value) {
        return value.toString();
      }
    }

    renderInput (key, value) {
      const index = this.props.index;
      const inputType = utils.inputTypeForPrototype(this.props.model[key].type);
      const inputValue = utils.prepareValueForInput(value, inputType);
      const checked = inputType === 'checkbox' && value ? true : null;

      if (inputType === 'text') {
        return (

            {inputValue}

        );
      } else {
        return (
          <input
            checked={checked}
            onChange={this.handleInputChange.bind(null, index, key, inputType)}
            type={inputType}
            value={inputValue}
          />
        );
      }
    }

    render () {
      const className = classnames(this.props.theme.row, {
        [this.props.theme.editable]: this.props.onChange,
        [this.props.theme.selected]: this.props.selected
      });

      return (

          {this.renderSelectCell()}
          {this.renderCells()}

      );
    }
  }

  return TableRow;
};

export default factory;
<|endoftext|>


<commit_before>import Realm from 'realm';
import { complement } from 'set-manipulator';

import { addBatchToParent, createRecord, getTotal } from '../utilities';

export class Stocktake extends Realm.Object {
  destructor(database) {
    if (this.isFinalised) throw new Error('Cannot delete a finalised Stocktake');
    database.delete('StocktakeItem', this.items);
  }

  // Adds a StocktakeBatch, incorporating it into a matching StocktakeItem.
  addBatchIfUnique(database, stocktakeBatch) {
    addBatchToParent(stocktakeBatch, this, () =>
      createRecord(database, 'StocktakeItem', this, stocktakeBatch.itemBatch.item)
    );
  }

  /**
   * Sets the stocktake items attached to this stocktake, based on the array of
   * item ids passed in
   * @param   {Realm} database   App wide local database
   * @param   {array} itemIds    The ids of the items to include in this stocktake
   * @return  {none}
   */
  setItemsByID(database, itemIds) {
    if (this.isFinalised) throw new Error('Cannot add items to a finalised stocktake');

    // Delete any stocktake items that aren't in the new array of ids
    const itemsToRemove = complement(this.items,
                                     itemIds.map((itemId) => ({ itemId: itemId })),
                                     (stocktakeItem) => stocktakeItem.itemId);
    if (itemsToRemove && itemsToRemove.length > 0) database.delete('StocktakeItem', itemsToRemove);

    // Add a new StocktakeItem for each new item id not currently in the stocktake
    const itemIdsToAdd = complement(itemIds,
                                    this.items.map((stocktakeItem) => stocktakeItem.itemId));
    const items = database.objects('Item');
    itemIdsToAdd.forEach((itemId) => {
      // Find the matching database item and use it to create a stocktake item
      const item = items.filtered('id == $0', itemId)[0];
      const stocktakeItem = createRecord(database, 'StocktakeItem', this, item);

      // Add all item batches currently in stock to the stocktake item as stocktake batches
      item.batchesWithStock.forEach((itemBatch) =>
        createRecord(database, 'StocktakeBatch', stocktakeItem, itemBatch));
    });
  }

  get isConfirmed() {
    return this.status === 'confirmed';
  }

  get isFinalised() {
    return this.status === 'finalised';
  }

  /**
   * Check whether at least one stocktake item has a counted quantity set
   * @return {boolean} True if one or more counted items, otherwise false
   */
  get hasSomeCountedItems() {
    return this.items.filtered('countedTotalQuantity != null').length === 0;
  }

  /**
   * Get any stocktake items that would cause a reduction larger than the amount
   * of available stock in inventory if it were finalised.
   * @return {array} All stocktake items that have been reduced below minimum level
   */
  get itemsBelowMinimum() {
    const itemsBelowMinimum = [];
    this.items.forEach((stocktakeItem) => {
      if (stocktakeItem.isReducedBelowMinimum) itemsBelowMinimum.push(stocktakeItem);
    });
    return itemsBelowMinimum;
  }

  get numberOfBatches() {
    return getTotal(this.items, 'numberOfBatches');
  }

  /**
   * Finalises this stocktake, creating transactions to apply the stock changes to inventory
   * @param {Realm.Object}  user     The current user logged in
   * @param {Realm}         database App wide local database
   */
  finalise(database, user) {
    // Create the transactions for additions and reductions
    const date = new Date();

    // Create inventory adjustment transactions as required, and allocate batches
    this.adjustInventory(database, user, date);

    // Set the stocktake finalise details
    this.finalisedBy = user;
    this.stocktakeDate = date;
    this.status = 'finalised';
    database.save('Stocktake', this);
  }

  /**
   * Applies differences in snapshot and counted quantities to the appropriate inventory
   * adjustment transactions. Will create this.additions and this.reductions if needed.
   * @param  {Realm}  database   App wide local database
   * @param  {object} user       The user that finalised this stocktake
   * @param  {Date}   date       The current date
   * @return {none}
   */
  adjustInventory(database, user, date) {
    // Go through each item, add it to the appropriate transaction, then copy over the
    // batch quantities allocated by the transaction item
    const uncountedItems = [];
    this.items.forEach((stocktakeItem) => {
      // If no counted quantity was entered, remember the item to delete
      if (stocktakeItem.countedTotalQuantity === null) {
        uncountedItems.push(stocktakeItem);
        return; // This is a 'continue' in the context of the forEach loop
      }

      // Work out whether this should be in the additions or reductions transaction
      const difference = stocktakeItem.countedTotalQuantity - stocktakeItem.snapshotTotalQuantity;

      // Lazily create additions/reductions as and when they are required
      if (difference >= 0 && this.additions === null) {
        this.additions = createRecord(database, 'InventoryAdjustment', user, date, true);
      } else if (difference < 0 && this.reductions === null) {
        this.reductions = createRecord(database, 'InventoryAdjustment', user, date, false);
      }

      // Get the appropriate transaction to use for this item
      const transaction = difference >= 0 ? this.additions : this.reductions;

      // Create and add TransactionItem to the transaction
      const item = stocktakeItem.item;
      const transactionItem = createRecord(database, 'TransactionItem', transaction, item);

      // If this item has no batches with stock, add a new empty batch
      if (difference > 0 && item.batchesWithStock.length === 0) {
        const batchString = `stocktake_${this.serialNumber}`;
        const itemBatch = createRecord(database, 'ItemBatch', item, batchString);
        createRecord(database, 'StocktakeBatch', stocktakeItem, itemBatch);
        createRecord(database, 'TransactionBatch', transactionItem, itemBatch);
      }

      // Set the transaction item's quantity, causing it to handle batch logic
      // and apply adjustments to inventory
      transactionItem.setTotalQuantity(database, Math.abs(difference));

      // Copy batch quantities from transaction item to the stocktake item
      stocktakeItem.applyBatchAdjustments(database, transactionItem);

      // Prune off any batches with 0 quantity that were unchanged
      stocktakeItem.pruneBatches(database);

      // Save the stocktake item
      database.save('StocktakeItem', stocktakeItem);
    });
    // Prune off any items that did not get counted
    database.delete('StocktakeItem', uncountedItems);
  }
}

Stocktake.schema = {
  name: 'Stocktake',
  primaryKey: 'id',
  properties: {
    id: 'string',
    name: { type: 'string', default: 'placeholderName' },
    createdDate: { type: 'date', default: new Date() }, // Includes time
    stocktakeDate: { type: 'date', optional: true },
    status: { type: 'string', default: 'new' },
    createdBy: { type: 'User', optional: true },
    finalisedBy: { type: 'User', optional: true },
    comment: { type: 'string', optional: true },
    serialNumber: { type: 'string', default: 'placeholderSerialNumber' },
    items: { type: 'list', objectType: 'StocktakeItem' },
    additions: { type: 'Transaction', optional: true },
    reductions: { type: 'Transaction', optional: true },
  },
};
<commit_msg>Changes to stocktake datatype<commit_after>import Realm from 'realm';
import { complement } from 'set-manipulator';

import { addBatchToParent, createRecord, getTotal } from '../utilities';

export class Stocktake extends Realm.Object {
  destructor(database) {
    if (this.isFinalised) throw new Error('Cannot delete a finalised Stocktake');
    database.delete('StocktakeItem', this.items);
  }

  // Adds a StocktakeBatch, incorporating it into a matching StocktakeItem.
  addBatchIfUnique(database, stocktakeBatch) {
    addBatchToParent(stocktakeBatch, this, () =>
      createRecord(database, 'StocktakeItem', this, stocktakeBatch.itemBatch.item)
    );
  }

  /**
   * Sets the stocktake items attached to this stocktake, based on the array of
   * item ids passed in
   * @param   {Realm} database   App wide local database
   * @param   {array} itemIds    The ids of the items to include in this stocktake
   * @return  {none}
   */
  setItemsByID(database, itemIds) {
    if (this.isFinalised) throw new Error('Cannot add items to a finalised stocktake');

    // Delete any stocktake items that aren't in the new array of ids
    const itemsToRemove = complement(this.items,
                                     itemIds.map((itemId) => ({ itemId: itemId })),
                                     (stocktakeItem) => stocktakeItem.itemId);
    if (itemsToRemove && itemsToRemove.length > 0) database.delete('StocktakeItem', itemsToRemove);

    // Add a new StocktakeItem for each new item id not currently in the stocktake
    const itemIdsToAdd = complement(itemIds,
                                    this.items.map((stocktakeItem) => stocktakeItem.itemId));
    const items = database.objects('Item');
    itemIdsToAdd.forEach((itemId) => {
      // Find the matching database item and use it to create a stocktake item
      const item = items.filtered('id == $0', itemId)[0];
      const stocktakeItem = createRecord(database, 'StocktakeItem', this, item);

      // Add all item batches currently in stock to the stocktake item as stocktake batches
      item.batchesWithStock.forEach((itemBatch) =>
        createRecord(database, 'StocktakeBatch', stocktakeItem, itemBatch));
    });
  }

  get isConfirmed() {
    return this.status === 'confirmed';
  }

  get isFinalised() {
    return this.status === 'finalised';
  }

  /**
   * Check whether at least one stocktake item has a counted quantity set
   * @return {boolean} True if one or more counted items, otherwise false
   */
  get hasSomeCountedItems() {
    return this.items.some((stocktakeItem) => stocktakeItem.difference !== 0);
  }

  /**
   * Get any stocktake items that would cause a reduction larger than the amount
   * of available stock in inventory if it were finalised.
   * @return {array} All stocktake items that have been reduced below minimum level
   */
  get itemsBelowMinimum() {
    const itemsBelowMinimum = [];
    this.items.forEach((stocktakeItem) => {
      if (stocktakeItem.isReducedBelowMinimum) itemsBelowMinimum.push(stocktakeItem);
    });
    return itemsBelowMinimum;
  }

  get numberOfBatches() {
    return getTotal(this.items, 'numberOfBatches');
  }

  getReductions(database, user) {
    if (!this.reductions) {
      this.reductions = createRecord(database, 'InventoryAdjustment', user, new Date(), false);
    }
    return this.reductions;
  }

  getAdditions(database, user) {
    if (!this.additions) {
      this.additions = createRecord(database, 'InventoryAdjustment', user, new Date(), true);
    }
    return this.additions;
  }

  /**
   * Finalises this stocktake, creating transactions to apply the stock changes to inventory
   * @param {Realm.Object}  user     The current user logged in
   * @param {Realm}         database App wide local database
   */
  finalise(database, user) {
    this.adjustInventory(database, user);

    // Set the stocktake finalise details
    this.finalisedBy = user;
    this.stocktakeDate = new Date();
    this.status = 'finalised';
    database.save('Stocktake', this);
  }

  /**
   * Applies differences in snapshot and counted quantities to the appropriate inventory
   * adjustment transactions.
   * @param  {Realm}  database   App wide local database
   * @param  {object} user       The user that finalised this stocktake
   * @param  {Date}   date       The current date
   * @return {none}
   */
  adjustInventory(database, user) {
    // Delete all unchanged stocktake items
    database.delete('StocktakeItem', this.item.filter(stocktakeItem =>
                                            stocktakeItem.hasBatchWithQuantityChange));
    // Delete all unchanged stocktake batches
    const stocktakeBatches = database.objects('StocktakeBatch')
                             .filtered('stocktake.id = $0', this.id);
    database.delete('StocktakeBatch', stocktakeBatches.filter(stocktakeBatch =>
                                      stocktakeBatch.difference === 0));
    // Filtered stocktakeBatches selection should have been adjusted after delete
    stocktakeBatches.forEach((stocktakeBatch) => stocktakeBatch.finalise(database, user));
  }
}

Stocktake.schema = {
  name: 'Stocktake',
  primaryKey: 'id',
  properties: {
    id: 'string',
    name: { type: 'string', default: 'placeholderName' },
    createdDate: { type: 'date', default: new Date() }, // Includes time
    stocktakeDate: { type: 'date', optional: true },
    status: { type: 'string', default: 'new' },
    createdBy: { type: 'User', optional: true },
    finalisedBy: { type: 'User', optional: true },
    comment: { type: 'string', optional: true },
    serialNumber: { type: 'string', default: 'placeholderSerialNumber' },
    items: { type: 'list', objectType: 'StocktakeItem' },
    additions: { type: 'Transaction', optional: true },
    reductions: { type: 'Transaction', optional: true },
  },
};
<|endoftext|>


<commit_before>'use strict';

/*eslint global-require: 0 */

var utils = require('./utils');

module.exports = function(callback) {
  var spawn = require('child_process').spawn;
  var path = require('path');
  var installation = null;
  var bashBin = process.env.SHELL || 'bash';

  if (!/bash/i.test(bashBin)) {
    bashBin = 'bash';
  }

  try {
    installation = spawn(
      bashBin, [
        path.join(__dirname, 'framework.sh'),
      ]
    );
  } catch (error) {
    console.error(error);
    return;
  }

  installation.stdout.pipe(process.stdout);
  installation.stderr.pipe(process.stderr);

  installation.on('error', function(error) {
    console.error(error);
  });

  let installationPromise = new Promise((resolve) => {
    installation.on('close', function(code) {
      if (code !== 0) {
        console.error('Framework installation failed (exit with code ' + code + ')');
      }

      resolve();
    });
  });

  let directory = this.microservice.autoload.frontend.replace(/(\/_build)$/, '');

  utils.initializeApplication.call(this, directory)
    .then(callback)
    .catch((error) => {
      console.error(error);
      callback();
    });
};
<commit_msg># Fix node_modules instalation<commit_after>'use strict';

/*eslint global-require: 0 */

var utils = require('./utils');

module.exports = function(callback) {
  var spawn = require('child_process').spawn;
  var path = require('path');
  var installation = null;
  var bashBin = process.env.SHELL || 'bash';

  if (!/bash/i.test(bashBin)) {
    bashBin = 'bash';
  }

  try {
    installation = spawn(
      bashBin, [
        path.join(__dirname, 'framework.sh'),
      ]
    );
  } catch (error) {
    console.error(error);
    return;
  }

  installation.stdout.pipe(process.stdout);
  installation.stderr.pipe(process.stderr);

  installation.on('error', function(error) {
    console.error(error);
  });

  let installationPromise = new Promise((resolve) => {
    installation.on('close', function(code) {
      if (code !== 0) {
        console.error('Framework installation failed (exit with code ' + code + ')');
      }

      resolve();
    });
  });

  let directory = this.microservice.autoload.frontend.replace(/(\/_build)$/, '');

  installationPromise.then(() => utils.initializeApplication.call(this, directory))
    .then(callback)
    .catch((error) => {
      console.error(error);
      callback();
    });
};
<|endoftext|>


<commit_before>var express = require('express');
var http = require('http');
var app = express();
var fs = require("fs");

var locked = false;
var bypass = false;
var disabled = false;

app.get('/lock', function (req, res) {
    http.request({
        host: '192.168.0.254',
        path: '/lock',
        method: 'GET',
        port: '80'
    }).end();

    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ operation: 'lock', status: 'ok' }));
});

app.get('/free', function (req, res) {
    http.request({
        host: '192.168.0.254',
        path: '/free',
        method: 'GET',
        port: '80'
    }).end();

    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ operation: 'free', status: 'ok' }));
});

app.get('/check', function (req, res) {
    http.request({
        host: '192.168.0.254',
        path: '/free',
        method: 'GET',
        port: '80'
    }).end();

    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ operation: 'free', status: 'ok' }));
});

var server = app.listen(5000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log("Boss deployer server running at http://%s:%s", host, port);
});<commit_msg>More on raspAPI - Including base structure for cd methods.<commit_after>var express = require('express');
var http = require('http');
var app = express();
var fs = require("fs");

var locked = false;
var bypass = false;
var disabled = false;

app.get('/lock', function (req, res) {
    http.request({
        host: '192.168.0.254',
        path: '/lock',
        method: 'GET',
        port: '80'
    }).end();

    locked = true;

    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify({ operation: 'lock', status: 'ok' }));
});

app.get('/free', function (req, res) {
    locked = false;
});

app.get('/bypass', function (req, res) {
    bypass = true;
    disabled = false;
});

app.get('/disable', function (req, res) {
    bypass = false;
    disabled = true;
});

/*
 * Continuous delivery things
 */
app.get('/cd-check', function (req, res) {
    // Check versions
});

app.get('/cd-in', function (req, res) {
    // Check versions
});

app.get('/cd-out', function (req, res) {
    // Check versions
});

var server = app.listen(5000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log("Boss deployer server running at http://%s:%s", host, port);
});<|endoftext|>


<commit_before>/*!
 * # Semantic UI - Checkbox
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Copyright 2014 Contributors
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ( $, window, document, undefined ) {

"use strict";

$.fn.checkbox = function(parameters) {
  var
    $allModules    = $(this),
    moduleSelector = $allModules.selector || '',

    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),
    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings        = $.extend(true, {}, $.fn.checkbox.settings, parameters),

        className       = settings.className,
        namespace       = settings.namespace,
        selector        = settings.selector,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $module         = $(this),
        $label          = $(this).find(selector.label).first(),
        $input          = $(this).find(selector.input),

        instance        = $module.data(moduleNamespace),

        observer,
        element         = this,
        module
      ;

      module      = {

        initialize: function() {
          module.verbose('Initializing checkbox', settings);

          module.create.label();
          module.add.events();

          if( module.is.checked() ) {
            module.set.checked();
            if(settings.fireOnInit) {
              settings.onChecked.call($input.get());
            }
          }
          else {
            module.remove.checked();
            if(settings.fireOnInit) {
              settings.onUnchecked.call($input.get());
            }
          }
          module.observeChanges();

          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying module');
          module.remove.events();
          $module
            .removeData(moduleNamespace)
          ;
        },

        refresh: function() {
          $module = $(this);
          $label  = $(this).find(selector.label).first();
          $input  = $(this).find(selector.input);
        },

        observeChanges: function() {
          if('MutationObserver' in window) {
            observer = new MutationObserver(function(mutations) {
              module.debug('DOM tree modified, updating selector cache');
              module.refresh();
            });
            observer.observe(element, {
              childList : true,
              subtree   : true
            });
            module.debug('Setting up mutation observer', observer);
          }
        },

        attachEvents: function(selector, event) {
          var
            $element = $(selector)
          ;
          event = $.isFunction(module[event])
            ? module[event]
            : module.toggle
          ;
          if($element.length > 0) {
            module.debug('Attaching checkbox events to element', selector, event);
            $element
              .on('click' + eventNamespace, event)
            ;
          }
          else {
            module.error(error.notFound);
          }
        },

        event: {
          keydown: function(event) {
            var
              key     = event.which,
              keyCode = {
                enter  : 13,
                space  : 32,
                escape : 27
              }
            ;
            if( key == keyCode.escape) {
              module.verbose('Escape key pressed blurring field');
              $module
                .blur()
              ;
            }
            if(!event.ctrlKey && (key == keyCode.enter || key == keyCode.space)) {
              module.verbose('Enter key pressed, toggling checkbox');
              module.toggle.call(this);
              event.preventDefault();
            }
          }
        },

        is: {
          radio: function() {
            return $module.hasClass(className.radio);
          },
          checked: function() {
            return $input.prop('checked') !== undefined && $input.prop('checked');
          },
          unchecked: function() {
            return !module.is.checked();
          }
        },

        can: {
          change: function() {
            return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') );
          },
          uncheck: function() {
            return (typeof settings.uncheckable === 'boolean')
              ? settings.uncheckable
              : !module.is.radio()
            ;
          }
        },

        set: {
          checked: function() {
            $module.addClass(className.checked);
          },
          tab: function() {
            if( $input.attr('tabindex') === undefined) {
              $input
                .attr('tabindex', 0)
              ;
            }
          }
        },

        create: {
          label: function() {
            if($input.prevAll(selector.label).length > 0) {
              $input.prev(selector.label).detach().insertAfter($input);
              module.debug('Moving existing label', $label);
            }
            else if( !module.has.label() ) {
              $label = $('<label>').insertAfter($input);
              module.debug('Creating label', $label);
            }
          }
        },

        has: {
          label: function() {
            return ($label.length > 0);
          }
        },

        add: {
          events: function() {
            module.verbose('Attaching checkbox events');
            $module
              .on('click'   + eventNamespace, module.toggle)
              .on('keydown' + eventNamespace, selector.input, module.event.keydown)
            ;
          }
        },

        remove: {
          checked: function() {
            $module.removeClass(className.checked);
          },
          events: function() {
            module.debug('Removing events');
            $module
              .off(eventNamespace)
              .removeData(moduleNamespace)
            ;
            $input
              .off(eventNamespace, module.event.keydown)
            ;
            $label
              .off(eventNamespace)
            ;
          }
        },

        enable: function() {
          module.debug('Enabling checkbox functionality');
          $module.removeClass(className.disabled);
          $input.prop('disabled', false);
          settings.onEnabled.call($input.get());
        },

        disable: function() {
          module.debug('Disabling checkbox functionality');
          $module.addClass(className.disabled);
          $input.prop('disabled', 'disabled');
          settings.onDisabled.call($input.get());
        },

        check: function() {
          module.debug('Enabling checkbox', $input);
          $input
            .prop('checked', true)
            .trigger('change')
          ;
          module.set.checked();
          $input.trigger('blur');
          settings.onChange.call($input.get());
          settings.onChecked.call($input.get());
        },

        uncheck: function() {
          module.debug('Disabling checkbox');
          $input
            .prop('checked', false)
            .trigger('change')
          ;
          module.remove.checked();
          $input.trigger('blur');
          settings.onChange.call($input.get());
          settings.onUnchecked.call($input.get());
        },

        toggle: function(event) {
          if( !module.can.change() ) {
            console.log(module.can.change());
            module.debug('Checkbox is read-only or disabled, ignoring toggle');
            return;
          }
          module.verbose('Determining new checkbox state');
          if( module.is.unchecked() ) {
            module.check();
          }
          else if( module.is.checked() && module.can.uncheck() ) {
            module.uncheck();
          }
        },
        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
          module.error.apply(console, arguments);
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.checkbox.settings = {

  name        : 'Checkbox',
  namespace   : 'checkbox',

  debug       : false,
  verbose     : true,
  performance : true,

  // delegated event context
  uncheckable : 'auto',
  fireOnInit  : true,

  onChange    : function(){},
  onChecked   : function(){},
  onUnchecked : function(){},
  onEnabled   : function(){},
  onDisabled  : function(){},

  className   : {
    checked  : 'checked',
    disabled : 'disabled',
    radio    : 'radio',
    readOnly : 'read-only'
  },

  error     : {
    method   : 'The method you called is not defined'
  },

  selector : {
    input  : 'input[type="checkbox"], input[type="radio"]',
    label  : 'label'
  }

};

})( jQuery, window , document );
<commit_msg>Debug for radio<commit_after>/*!
 * # Semantic UI - Checkbox
 * http://github.com/semantic-org/semantic-ui/
 *
 *
 * Copyright 2014 Contributors
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 */

;(function ( $, window, document, undefined ) {

"use strict";

$.fn.checkbox = function(parameters) {
  var
    $allModules    = $(this),
    moduleSelector = $allModules.selector || '',

    time           = new Date().getTime(),
    performance    = [],

    query          = arguments[0],
    methodInvoked  = (typeof query == 'string'),
    queryArguments = [].slice.call(arguments, 1),
    returnedValue
  ;

  $allModules
    .each(function() {
      var
        settings        = $.extend(true, {}, $.fn.checkbox.settings, parameters),

        className       = settings.className,
        namespace       = settings.namespace,
        selector        = settings.selector,
        error           = settings.error,

        eventNamespace  = '.' + namespace,
        moduleNamespace = 'module-' + namespace,

        $module         = $(this),
        $label          = $(this).find(selector.label).first(),
        $input          = $(this).find(selector.input),

        instance        = $module.data(moduleNamespace),

        observer,
        element         = this,
        module
      ;

      module      = {

        initialize: function() {
          module.verbose('Initializing checkbox', settings);

          module.create.label();
          module.add.events();

          if( module.is.checked() ) {
            module.set.checked();
            if(settings.fireOnInit) {
              settings.onChecked.call($input.get());
            }
          }
          else {
            module.remove.checked();
            if(settings.fireOnInit) {
              settings.onUnchecked.call($input.get());
            }
          }
          module.observeChanges();

          module.instantiate();
        },

        instantiate: function() {
          module.verbose('Storing instance of module', module);
          instance = module;
          $module
            .data(moduleNamespace, module)
          ;
        },

        destroy: function() {
          module.verbose('Destroying module');
          module.remove.events();
          $module
            .removeData(moduleNamespace)
          ;
        },

        refresh: function() {
          $module = $(this);
          $label  = $(this).find(selector.label).first();
          $input  = $(this).find(selector.input);
        },

        observeChanges: function() {
          if('MutationObserver' in window) {
            observer = new MutationObserver(function(mutations) {
              module.debug('DOM tree modified, updating selector cache');
              module.refresh();
            });
            observer.observe(element, {
              childList : true,
              subtree   : true
            });
            module.debug('Setting up mutation observer', observer);
          }
        },

        attachEvents: function(selector, event) {
          var
            $element = $(selector)
          ;
          event = $.isFunction(module[event])
            ? module[event]
            : module.toggle
          ;
          if($element.length > 0) {
            module.debug('Attaching checkbox events to element', selector, event);
            $element
              .on('click' + eventNamespace, event)
            ;
          }
          else {
            module.error(error.notFound);
          }
        },

        event: {
          keydown: function(event) {
            var
              key     = event.which,
              keyCode = {
                enter  : 13,
                space  : 32,
                escape : 27
              }
            ;
            if( key == keyCode.escape) {
              module.verbose('Escape key pressed blurring field');
              $module
                .blur()
              ;
            }
            if(!event.ctrlKey && (key == keyCode.enter || key == keyCode.space)) {
              module.verbose('Enter key pressed, toggling checkbox');
              module.toggle.call(this);
              event.preventDefault();
            }
          }
        },

        is: {
          radio: function() {
            return $module.hasClass(className.radio);
          },
          checked: function() {
            return $input.prop('checked') !== undefined && $input.prop('checked');
          },
          unchecked: function() {
            return !module.is.checked();
          }
        },

        can: {
          change: function() {
            return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') );
          },
          uncheck: function() {
            return (typeof settings.uncheckable === 'boolean')
              ? settings.uncheckable
              : !module.is.radio()
            ;
          }
        },

        set: {
          checked: function() {
            $module.addClass(className.checked);
          },
          tab: function() {
            if( $input.attr('tabindex') === undefined) {
              $input
                .attr('tabindex', 0)
              ;
            }
          }
        },

        create: {
          label: function() {
            if($input.prevAll(selector.label).length > 0) {
              $input.prev(selector.label).detach().insertAfter($input);
              module.debug('Moving existing label', $label);
            }
            else if( !module.has.label() ) {
              $label = $('<label>').insertAfter($input);
              module.debug('Creating label', $label);
            }
          }
        },

        has: {
          label: function() {
            return ($label.length > 0);
          }
        },

        add: {
          events: function() {
            module.verbose('Attaching checkbox events');
            $module
              .on('click'   + eventNamespace, module.toggle)
              .on('keydown' + eventNamespace, selector.input, module.event.keydown)
            ;
          }
        },

        remove: {
          checked: function() {
            $module.removeClass(className.checked);
          },
          events: function() {
            module.debug('Removing events');
            $module
              .off(eventNamespace)
              .removeData(moduleNamespace)
            ;
            $input
              .off(eventNamespace, module.event.keydown)
            ;
            $label
              .off(eventNamespace)
            ;
          }
        },

        enable: function() {
          module.debug('Enabling checkbox functionality');
          $module.removeClass(className.disabled);
          $input.prop('disabled', false);
          settings.onEnabled.call($input.get());
        },

        disable: function() {
          module.debug('Disabling checkbox functionality');
          $module.addClass(className.disabled);
          $input.prop('disabled', 'disabled');
          settings.onDisabled.call($input.get());
        },

        check: function() {
          module.debug('Enabling checkbox', $input);
          $input
            .prop('checked', true)
            .trigger('change')
          ;
          module.set.checked();
          $input.trigger('blur');
          settings.onChange.call($input.get());
          settings.onChecked.call($input.get());
        },

        uncheck: function() {
          module.debug('Disabling checkbox');
          $input
            .prop('checked', false)
            .trigger('change')
          ;
          module.remove.checked();
          $input.trigger('blur');
          settings.onChange.call($input.get());
          settings.onUnchecked.call($input.get());
        },

        toggle: function(event) {
          if( !module.can.change() ) {
            console.log(module.can.change());
            if(!module.is.radio()) {
              module.debug('Checkbox is read-only or disabled, ignoring toggle');
            }
            return;
          }
          module.verbose('Determining new checkbox state');
          if( module.is.unchecked() ) {
            module.check();
          }
          else if( module.is.checked() && module.can.uncheck() ) {
            module.uncheck();
          }
        },
        setting: function(name, value) {
          module.debug('Changing setting', name, value);
          if( $.isPlainObject(name) ) {
            $.extend(true, settings, name);
          }
          else if(value !== undefined) {
            settings[name] = value;
          }
          else {
            return settings[name];
          }
        },
        internal: function(name, value) {
          if( $.isPlainObject(name) ) {
            $.extend(true, module, name);
          }
          else if(value !== undefined) {
            module[name] = value;
          }
          else {
            return module[name];
          }
        },
        debug: function() {
          if(settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.debug.apply(console, arguments);
            }
          }
        },
        verbose: function() {
          if(settings.verbose && settings.debug) {
            if(settings.performance) {
              module.performance.log(arguments);
            }
            else {
              module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
              module.verbose.apply(console, arguments);
            }
          }
        },
        error: function() {
          module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
          module.error.apply(console, arguments);
        },
        performance: {
          log: function(message) {
            var
              currentTime,
              executionTime,
              previousTime
            ;
            if(settings.performance) {
              currentTime   = new Date().getTime();
              previousTime  = time || currentTime;
              executionTime = currentTime - previousTime;
              time          = currentTime;
              performance.push({
                'Name'           : message[0],
                'Arguments'      : [].slice.call(message, 1) || '',
                'Element'        : element,
                'Execution Time' : executionTime
              });
            }
            clearTimeout(module.performance.timer);
            module.performance.timer = setTimeout(module.performance.display, 500);
          },
          display: function() {
            var
              title = settings.name + ':',
              totalTime = 0
            ;
            time = false;
            clearTimeout(module.performance.timer);
            $.each(performance, function(index, data) {
              totalTime += data['Execution Time'];
            });
            title += ' ' + totalTime + 'ms';
            if(moduleSelector) {
              title += ' \'' + moduleSelector + '\'';
            }
            if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
              console.groupCollapsed(title);
              if(console.table) {
                console.table(performance);
              }
              else {
                $.each(performance, function(index, data) {
                  console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
                });
              }
              console.groupEnd();
            }
            performance = [];
          }
        },
        invoke: function(query, passedArguments, context) {
          var
            object = instance,
            maxDepth,
            found,
            response
          ;
          passedArguments = passedArguments || queryArguments;
          context         = element         || context;
          if(typeof query == 'string' && object !== undefined) {
            query    = query.split(/[\. ]/);
            maxDepth = query.length - 1;
            $.each(query, function(depth, value) {
              var camelCaseValue = (depth != maxDepth)
                ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
                : query
              ;
              if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
                object = object[camelCaseValue];
              }
              else if( object[camelCaseValue] !== undefined ) {
                found = object[camelCaseValue];
                return false;
              }
              else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
                object = object[value];
              }
              else if( object[value] !== undefined ) {
                found = object[value];
                return false;
              }
              else {
                module.error(error.method, query);
                return false;
              }
            });
          }
          if ( $.isFunction( found ) ) {
            response = found.apply(context, passedArguments);
          }
          else if(found !== undefined) {
            response = found;
          }
          if($.isArray(returnedValue)) {
            returnedValue.push(response);
          }
          else if(returnedValue !== undefined) {
            returnedValue = [returnedValue, response];
          }
          else if(response !== undefined) {
            returnedValue = response;
          }
          return found;
        }
      };

      if(methodInvoked) {
        if(instance === undefined) {
          module.initialize();
        }
        module.invoke(query);
      }
      else {
        if(instance !== undefined) {
          instance.invoke('destroy');
        }
        module.initialize();
      }
    })
  ;

  return (returnedValue !== undefined)
    ? returnedValue
    : this
  ;
};

$.fn.checkbox.settings = {

  name        : 'Checkbox',
  namespace   : 'checkbox',

  debug       : false,
  verbose     : true,
  performance : true,

  // delegated event context
  uncheckable : 'auto',
  fireOnInit  : true,

  onChange    : function(){},
  onChecked   : function(){},
  onUnchecked : function(){},
  onEnabled   : function(){},
  onDisabled  : function(){},

  className   : {
    checked  : 'checked',
    disabled : 'disabled',
    radio    : 'radio',
    readOnly : 'read-only'
  },

  error     : {
    method   : 'The method you called is not defined'
  },

  selector : {
    input  : 'input[type="checkbox"], input[type="radio"]',
    label  : 'label'
  }

};

})( jQuery, window , document );
<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

var React = require('react');
var stringify = require("json-stringify-pretty-compact");
var DocsArticle = require('../../DocsArticle');
var Search = require('grommet/components/Search');

var SIMPLE_SUGGESTIONS = ['item 1', 'item 2', 'item 3'];
var RICH_SUGGESTIONS = [
  {label: 'item 1', data: '/item-1'},
  {label: 'item 2', data: '/item-2'},
  {label: 'item 3', data: '/item-3'}
];

var SearchDoc = React.createClass({

  getInitialState: function () {
    return {
      value: "",
      simpleSuggestions: [],
      richSuggestions: []
    };
  },

  _onDOMChange: function (event) {
    var regexp = new RegExp('^' + event.target.value);
    var simpleSuggestions = SIMPLE_SUGGESTIONS.filter(function (suggestion) {
      return regexp.test(suggestion);
    });
    var richSuggestions = RICH_SUGGESTIONS.filter(function (suggestion) {
      return regexp.test(suggestion.label);
    });

    this.setState({
      value: event.target.value,
      simpleSuggestions: simpleSuggestions,
      richSuggestions: richSuggestions
    });
  },

  _onSelect: function (pseudoEvent, selected) {
    var value;
    if (pseudoEvent.suggestion && pseudoEvent.suggestion.hasOwnProperty('label')) {
      value = pseudoEvent.suggestion.label;
    } else {
      value = pseudoEvent.suggestion;

    }
    this.setState({
      value: value,
      simpleSuggestions: [],
      richSuggestions: []
    });
  },

  render: function() {
    var inline =
    "<Search onDOMChange={...} onSelect={...} />";
    return (
      <DocsArticle title="Search" colorIndex="neutral-3">

A responsive search control.

{inline}

Options

defaultValue  {"{string}"}

What text to start with in the input.

dropAlign     {"{left: left|right, right: left|right, top: top|bottom, bottom: top|bottom}"}

Where to place the drop down.
              At most one of left or right and one of top or bottom should be specified.

inline        true|false

Indicates that the search input should always
              be visible.

onChange      {"function ({value: , label: }|{string}) {...}"}

Function that will be called when the user types some text
              into the input. This property is deprecated in favor of
              onDOMChange and onSelect.

onDOMChange   {"function (event) {...}"}

Function that will be called when the user types in the input.

onSelect      {"function ({target: , suggestion: }, selected) {...}"}

Function that will be called when the user selects a
              suggestion. The target corresponds to the embedded input element
              , allowing you to distinguish which component triggered the event
              . The suggestion contains the object chosen from the supplied
              suggestions. selected will be true when the user has chosen one
              of the suggestions, and false when the user presses enter after
              entering text (without selecting a suggestion).

placeHolder   {"{string}"}

Placeholder text to use when the input is empty.

responsive    true|false

Whether the search control is responsive (turns off inline
              search option for small screen sizes).
              Defaults to true.

size          medium|large

The size of the Header. Defaults to medium.

suggestions   [{"{string}|{label: {string}, ...}"}, ...]

Suggestions to show, typically based on what the user has
            typed so far. You can pass an array of strings or objects. Objects
            must have a label: property but can have any other properties you
            like. This object will be given to the onSelect() handler (or
            onChange() handler) if the suggestion is selected.

value         {"{string}"}

What text to show in the input.

Examples

Default

            <Search onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search />"}

Left

            <Search onDOMChange={this._onDOMChange} onSelect={this._onSelect}  dropAlign={{right: 'right'}} />

{"<Search dropAlign={{right: \"right\"}} />"}

Suggestions and Value

            <Search value={this.state.value}
              suggestions={this.state.simpleSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search defaultValue=\"" +
            this.state.value + "\" suggestions={" +
            stringify(this.state.simpleSuggestions) + "} />"}

Inline

            <Search inline={true}/>

{"<Search inline={true}/>"}

Inline, Placeholder

            <Search inline={true} placeHolder="Search" />

{"<Search inline={true} placeHolder=\"Search\" />"}

Inline, Value, and Suggestions

            <Search inline={true} value={this.state.value}
              suggestions={this.state.simpleSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search inline={true} value=\"" +
            this.state.value + "\" suggestions={" +
            stringify(this.state.simpleSuggestions) + "}/>"}

Inline, Value, Rich Suggestions

            <Search inline={true} value={this.state.value}
              suggestions={this.state.richSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search inline={true} value=\"" +
            this.state.value + "\" suggestions={" +
            stringify(this.state.simpleSuggestions) + "}/>"}

Large

            <Search inline={true} value={this.state.value} size="large"
              suggestions={this.state.simpleSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search size=\"large\"> ..."}

          {/*}

Small

Avoid using this size as it is too small for touch devices.

            <Search inline={true} value={this.state.value} size="small"
              suggestions={this.state.simpleSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search size=\"small\"> ..."}

          {*/}

      </DocsArticle>
    );
  }
});

module.exports = SearchDoc;
<commit_msg>updating search doc with options and examples for fill, iconAlign, and large/responsive.<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

var React = require('react');
var stringify = require("json-stringify-pretty-compact");
var DocsArticle = require('../../DocsArticle');
var Search = require('grommet/components/Search');

var SIMPLE_SUGGESTIONS = ['item 1', 'item 2', 'item 3'];
var RICH_SUGGESTIONS = [
  {label: 'item 1', data: '/item-1'},
  {label: 'item 2', data: '/item-2'},
  {label: 'item 3', data: '/item-3'}
];

var SearchDoc = React.createClass({

  getInitialState: function () {
    return {
      value: "",
      simpleSuggestions: [],
      richSuggestions: []
    };
  },

  _onDOMChange: function (event) {
    var regexp = new RegExp('^' + event.target.value);
    var simpleSuggestions = SIMPLE_SUGGESTIONS.filter(function (suggestion) {
      return regexp.test(suggestion);
    });
    var richSuggestions = RICH_SUGGESTIONS.filter(function (suggestion) {
      return regexp.test(suggestion.label);
    });

    this.setState({
      value: event.target.value,
      simpleSuggestions: simpleSuggestions,
      richSuggestions: richSuggestions
    });
  },

  _onSelect: function (pseudoEvent, selected) {
    var value;
    if (pseudoEvent.suggestion && pseudoEvent.suggestion.hasOwnProperty('label')) {
      value = pseudoEvent.suggestion.label;
    } else {
      value = pseudoEvent.suggestion;

    }
    this.setState({
      value: value,
      simpleSuggestions: [],
      richSuggestions: []
    });
  },

  render: function() {
    var inline =
    "<Search onDOMChange={...} onSelect={...} />";
    return (
      <DocsArticle title="Search" colorIndex="neutral-3">

A responsive search control.

{inline}

Options

defaultValue  {"{string}"}

What text to start with in the input.

dropAlign     {"{left: left|right, right: left|right, top: top|bottom, bottom: top|bottom}"}

Where to place the drop down.
              At most one of left or right and one of top or bottom should be specified.

fill          true|false

Indicates whether an inline search input should take up the full
              width of its parent container or not.

iconAlign     start|end

Whether the search icon should align with the start or end of
              the input field. Defaults to end.

inline        true|false

Indicates that the search input should always
              be visible.

onChange      {"function ({value: , label: }|{string}) {...}"}

Function that will be called when the user types some text
              into the input. This property is deprecated in favor of
              onDOMChange and onSelect.

onDOMChange   {"function (event) {...}"}

Function that will be called when the user types in the input.

onSelect      {"function ({target: , suggestion: }, selected) {...}"}

Function that will be called when the user selects a
              suggestion. The target corresponds to the embedded input element
              , allowing you to distinguish which component triggered the event
              . The suggestion contains the object chosen from the supplied
              suggestions. selected will be true when the user has chosen one
              of the suggestions, and false when the user presses enter after
              entering text (without selecting a suggestion).

placeHolder   {"{string}"}

Placeholder text to use when the input is empty.

responsive    true|false

Whether the search control is responsive (turns off inline
              search option for small screen sizes).
              If responsive is false, large inputs will shrink to
              the default inline size for smaller screens (instead of reverting
              to the search control button by default).
              Defaults to true.

size          medium|large

The size of the inline search input. Defaults to medium.

suggestions   [{"{string}|{label: {string}, ...}"}, ...]

Suggestions to show, typically based on what the user has
            typed so far. You can pass an array of strings or objects. Objects
            must have a label: property but can have any other properties you
            like. This object will be given to the onSelect() handler (or
            onChange() handler) if the suggestion is selected.

value         {"{string}"}

What text to show in the input.

Examples

Default

            <Search onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search />"}

Left

            <Search onDOMChange={this._onDOMChange} onSelect={this._onSelect}  dropAlign={{right: 'right'}} />

{"<Search dropAlign={{right: \"right\"}} />"}

Suggestions and Value

            <Search value={this.state.value}
              suggestions={this.state.simpleSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search defaultValue=\"" +
            this.state.value + "\" suggestions={" +
            stringify(this.state.simpleSuggestions) + "} />"}

Inline

            <Search inline={true}/>

{"<Search inline={true}/>"}

Inline, IconAlign Start

            <Search inline={true} iconAlign="start"/>

{"<Search inline={true} iconAlign=\"start\" />"}

Inline, Placeholder

            <Search inline={true} placeHolder="Search" />

{"<Search inline={true} placeHolder=\"Search\" />"}

Inline, Value, and Suggestions

            <Search inline={true} value={this.state.value}
              suggestions={this.state.simpleSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search inline={true} value=\"" +
            this.state.value + "\" suggestions={" +
            stringify(this.state.simpleSuggestions) + "}/>"}

Inline, Value, Rich Suggestions

            <Search inline={true} value={this.state.value}
              suggestions={this.state.richSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search inline={true} value=\"" +
            this.state.value + "\" suggestions={" +
            stringify(this.state.simpleSuggestions) + "}/>"}

Large

            <Search inline={true} value={this.state.value} size="large"
              suggestions={this.state.simpleSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search size=\"large\"> ..."}

Large, Fill, Responsive False

            <Search inline={true} value={this.state.value} size="large"
              fill={true} responsive={false}
              suggestions={this.state.simpleSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search size=\"large\" fill={true} responsive={false}> ..."}

          {/*}

Small

Avoid using this size as it is too small for touch devices.

            <Search inline={true} value={this.state.value} size="small"
              suggestions={this.state.simpleSuggestions}
              onDOMChange={this._onDOMChange} onSelect={this._onSelect} />

{"<Search size=\"small\"> ..."}

          {*/}

      </DocsArticle>
    );
  }
});

module.exports = SearchDoc;
<|endoftext|>


<commit_before>var ko = (function (ko) {
    ko.Node = function (args) {
        args = args || {};
        this.position = { x: 0, y: 0 };
        this.velocity = { x: 0, y: 0 };
        this.acceleration = { x: 0, y: 0 };
        this.color = 'rgb(255,255,255)';
        this.opacity = 1;
        this.rotation = 0;
        this.scale = 1;
        this.anchor = { x: 0, y: 0 };
        this.size = { width: 0, height: 0 };
        this.visible = true;
        this.children = [];
        this.actions = [];
        this._update = args.update || function (delta) {};
        this._handleInput = args.handleInput || function () {};
        this._render = args.render || function () {};
    };
    ko.Node.prototype.update = function (delta) {
        this.velocity.x += this.acceleration.x;
        this.velocity.y += this.acceleration.y;
        this.position.x += this.velocity.x;
        this.position.y += this.velocity.y;
        var i;
        for (i = 0; i < this.actions.length; i++) {
            this.actions[i].update(delta);
        }
        /*for (i = this.actions.length - 1; i > 0; i--) {
            if (this.actions[i].isComplete()) {
                this.actions.splice(i, 1);
            }
        }*/
        for (i = 0; i < this.children.length; i++) {
            this.children[i].update(delta);
        }
        this._update(delta);
    };
    ko.Node.prototype.render = function () {
        if (!this.visible) {
            return;
        }
        ko.renderer.beginTransform(this);
        this._render();
        for (var i = 0; i < this.children.length; i++) {
            this.children[i].render();
        }
        ko.renderer.endTransform();
    };
    ko.Node.prototype.handleInput = function () {
        this._handleInput();
        for (var i = 0; i < this.children.length; i++) {
            this.children[i].handleInput();
        }
    };
    ko.Node.prototype.addChild = function (child) {
        if (child === this) {
            throw new Error("Can't add a child to itself");
        }
        if (child.parent) {
            throw new Error("Child already has a parent");
        }
        this.children.push(child);
        child.parent = this;
    };
    ko.Node.prototype.perform = function (action) {
        if (action.target) {
            throw new Error("Action is already in use");
        }
        action.init(this);
        this.actions.push(action);
    };
    ko.Node.prototype.moveTo = function (x, y, duration, ease) {
        this.perform(new ko.MoveTo(x, y, duration, ease));
        return this;
    };
    ko.Node.prototype.scaleTo = function (scaleTo, duration, ease) {
        this.perform(new ko.ScaleTo(scaleTo, duration, ease));
        return this;
    };
    ko.Node.prototype.rotateTo = function (rotateTo, duration, ease) {
        this.perform(new ko.RotateTo(rotateTo, duration, ease));
        return this;
    };
    ko.Node.prototype.fadeTo = function (fadeTo, duration, ease) {
        this.perform(new ko.FadeTo(fadeTo, duration, ease));
        return this;
    };
    ko.Node.prototype.sequence = function (repeat) {
        var sequence = new ko.Sequence([], repeat);
        this.actions.push(sequence);
        return sequence;
    };
    ko.Node.prototype.isColliding = function (node, separate) {
        if (!this.boundingBox) {
            this.boundingBox = new ko.BoundingBox(this);
        }
        if (!node.boundingBox) {
            node.boundingBox = new ko.BoundingBox(node);
        }
        return this.boundingBox.isIntersecting(node.boundingBox, separate);
    };
    ko.Node.prototype.centerPosition = function () {
        var center = ko.renderer.center;
        this.position = { x: center.x, y: center.y };
    };
    ko.Node.prototype.centerAnchor = function () {
        this.anchor = { x: 0.5, y: 0.5 };
    };
    return ko;
})(ko || {});
<commit_msg>Actions are now removed from nodes when completed.<commit_after>var ko = (function (ko) {
    ko.Node = function (args) {
        args = args || {};
        this.position = { x: 0, y: 0 };
        this.velocity = { x: 0, y: 0 };
        this.acceleration = { x: 0, y: 0 };
        this.color = 'rgb(255,255,255)';
        this.opacity = 1;
        this.rotation = 0;
        this.scale = 1;
        this.anchor = { x: 0, y: 0 };
        this.size = { width: 0, height: 0 };
        this.visible = true;
        this.children = [];
        this.actions = [];
        this._update = args.update || function (delta) {};
        this._handleInput = args.handleInput || function () {};
        this._render = args.render || function () {};
    };
    ko.Node.prototype.update = function (delta) {
        this.velocity.x += this.acceleration.x;
        this.velocity.y += this.acceleration.y;
        this.position.x += this.velocity.x;
        this.position.y += this.velocity.y;
        var i;
        for (i = 0; i < this.actions.length; i++) {
            this.actions[i].update(delta);
        }
        for (i = this.actions.length - 1; i >= 0; i--) {
            if (this.actions[i].isComplete()) {
                this.actions.splice(i, 1);
            }
        }
        for (i = 0; i < this.children.length; i++) {
            this.children[i].update(delta);
        }
        this._update(delta);
    };
    ko.Node.prototype.render = function () {
        if (!this.visible) {
            return;
        }
        ko.renderer.beginTransform(this);
        this._render();
        for (var i = 0; i < this.children.length; i++) {
            this.children[i].render();
        }
        ko.renderer.endTransform();
    };
    ko.Node.prototype.handleInput = function () {
        this._handleInput();
        for (var i = 0; i < this.children.length; i++) {
            this.children[i].handleInput();
        }
    };
    ko.Node.prototype.addChild = function (child) {
        if (child === this) {
            throw new Error("Can't add a child to itself");
        }
        if (child.parent) {
            throw new Error("Child already has a parent");
        }
        this.children.push(child);
        child.parent = this;
    };
    ko.Node.prototype.perform = function (action) {
        if (action.target) {
            throw new Error("Action is already in use");
        }
        action.init(this);
        this.actions.push(action);
    };
    ko.Node.prototype.moveTo = function (x, y, duration, ease) {
        this.perform(new ko.MoveTo(x, y, duration, ease));
        return this;
    };
    ko.Node.prototype.scaleTo = function (scaleTo, duration, ease) {
        this.perform(new ko.ScaleTo(scaleTo, duration, ease));
        return this;
    };
    ko.Node.prototype.rotateTo = function (rotateTo, duration, ease) {
        this.perform(new ko.RotateTo(rotateTo, duration, ease));
        return this;
    };
    ko.Node.prototype.fadeTo = function (fadeTo, duration, ease) {
        this.perform(new ko.FadeTo(fadeTo, duration, ease));
        return this;
    };
    ko.Node.prototype.sequence = function (repeat) {
        var sequence = new ko.Sequence([], repeat);
        this.actions.push(sequence);
        return sequence;
    };
    ko.Node.prototype.isColliding = function (node, separate) {
        if (!this.boundingBox) {
            this.boundingBox = new ko.BoundingBox(this);
        }
        if (!node.boundingBox) {
            node.boundingBox = new ko.BoundingBox(node);
        }
        return this.boundingBox.isIntersecting(node.boundingBox, separate);
    };
    ko.Node.prototype.centerPosition = function () {
        var center = ko.renderer.center;
        this.position = { x: center.x, y: center.y };
    };
    ko.Node.prototype.centerAnchor = function () {
        this.anchor = { x: 0.5, y: 0.5 };
    };
    return ko;
})(ko || {});
<|endoftext|>