<commit_before>'use strict';

var extend = require('lodash/extend');

var Selectivity = require('../selectivity');
var stopPropagation = require('../util/stop-propagation');

/**
 * SingleInput Constructor.
 */
function SingleInput(options) {
    Selectivity.call(
        this,
        extend(
            {
                // dropdowns for single-value inputs should open below the select box,
                // unless there is not enough space below, in which case the dropdown should be moved up
                // just enough so it fits in the window, but never so much that it reaches above the top
                positionDropdown: function(el, selectEl) {
                    var rect = selectEl.getBoundingClientRect();
                    var dropdownTop = rect.bottom;

                    var deltaUp = Math.min(
                        Math.max(dropdownTop + el.clientHeight - window.innerHeight, 0),
                        rect.top + rect.height
                    );

                    extend(el.style, {
                        left: rect.left + 'px',
                        top: dropdownTop - deltaUp + 'px',
                        width: rect.width + 'px'
                    });
                }
            },
            options
        )
    );

    this.el.innerHTML = this.template('singleSelectInput', this.options);

    this.rerenderSelection();

    if (options.showSearchInputInDropdown === false) {
        this.initInput(this.$('.selectivity-single-select-input'), { search: false });
    }

    this.events.on({
        change: this.rerenderSelection,
        click: this._clicked,
        'click .selectivity-search-input': stopPropagation,
        'click .selectivity-single-selected-item-remove': this._itemRemoveClicked,
        'focus .selectivity-single-select-input': this._focused,
        'selectivity-selected': this._resultSelected
    });
}

/**
 * Methods.
 */
var callSuper = Selectivity.inherits(SingleInput, Selectivity, {
    /**
     * Clears the data and value.
     */
    clear: function() {
        this.setData(null);
    },

    /**
     * @inherit
     *
     * @param options Optional options object. May contain the following property:
     *                keepFocus - If true, the focus will remain on the input.
     */
    close: function(options) {
        this._closing = true;

        callSuper(this, 'close');

        if (options && options.keepFocus && this.input) {
            this.input.focus();
        }

        this._closing = false;
    },

    /**
     * Returns the correct data for a given value.
     *
     * @param value The value to get the data for. Should be an ID.
     *
     * @return The corresponding data. Will be an object with 'id' and 'text' properties. Note that
     *         if no items are defined, this method assumes the text label will be equal to the ID.
     */
    getDataForValue: function(value) {
        return this.getItemForId(value);
    },

    /**
     * Returns the correct value for the given data.
     *
     * @param data The data to get the value for. Should be an object with 'id' and 'text'
     *             properties or null.
     *
     * @return The corresponding value. Will be an ID or null.
     */
    getValueForData: function(data) {
        return data ? data.id : null;
    },

    /**
     * Re-renders the selection.
     *
     * Normally the UI is automatically updated whenever the selection changes, but you may want to
     * call this method explicitly if you've updated the selection with the triggerChange option set
     * to false.
     */
    rerenderSelection: function() {
        var template = this._data ? 'singleSelectedItem' : 'singleSelectPlaceholder';
        var options = this._data
            ? extend(
                  {
                      removable: this.options.allowClear && !this.options.readOnly
                  },
                  this._data
              )
            : { placeholder: this.options.placeholder };

        this.el.querySelector('input').value = this._value;
        this.$('.selectivity-single-result-container').innerHTML = this.template(template, options);
    },

    /**
     * Validates data to set. Throws an exception if the data is invalid.
     *
     * @param data The data to validate. Should be an object with 'id' and 'text' properties or null
     *             to indicate no item is selected.
     *
     * @return The validated data. This may differ from the input data.
     */
    validateData: function(data) {
        return data === null ? data : this.validateItem(data);
    },

    /**
     * Validates a value to set. Throws an exception if the value is invalid.
     *
     * @param value The value to validate. Should be null or a valid ID.
     *
     * @return The validated value. This may differ from the input value.
     */
    validateValue: function(value) {
        if (value === null || Selectivity.isValidId(value)) {
            return value;
        } else {
            throw new Error('Value for SingleSelectivity instance should be a valid ID or null');
        }
    },

    /**
     * @private
     */
    _clicked: function() {
        if (this.enabled) {
            if (this.dropdown) {
                this.close({ keepFocus: true });
            } else if (this.options.showDropdown !== false) {
                this.open();
            }
        }
    },

    /**
     * @private
     */
    _focused: function() {
        if (
            this.enabled &&
            !this._closing &&
            !this._opening &&
            this.options.showDropdown !== false
        ) {
            this.open();
        }
    },

    /**
     * @private
     */
    _itemRemoveClicked: function(event) {
        this.setData(null);

        stopPropagation(event);
    },

    /**
     * @private
     */
    _resultSelected: function(event) {
        this.setData(event.item);

        this.close({ keepFocus: true });
    }
});

module.exports = Selectivity.Inputs.Single = SingleInput;
<commit_msg>Forgot one occurence of lodash extend().<commit_after>'use strict';

var assign = require('lodash/assign');

var Selectivity = require('../selectivity');
var stopPropagation = require('../util/stop-propagation');

/**
 * SingleInput Constructor.
 */
function SingleInput(options) {
    Selectivity.call(
        this,
        assign(
            {
                // dropdowns for single-value inputs should open below the select box,
                // unless there is not enough space below, in which case the dropdown should be moved up
                // just enough so it fits in the window, but never so much that it reaches above the top
                positionDropdown: function(el, selectEl) {
                    var rect = selectEl.getBoundingClientRect();
                    var dropdownTop = rect.bottom;

                    var deltaUp = Math.min(
                        Math.max(dropdownTop + el.clientHeight - window.innerHeight, 0),
                        rect.top + rect.height
                    );

                    assign(el.style, {
                        left: rect.left + 'px',
                        top: dropdownTop - deltaUp + 'px',
                        width: rect.width + 'px'
                    });
                }
            },
            options
        )
    );

    this.el.innerHTML = this.template('singleSelectInput', this.options);

    this.rerenderSelection();

    if (options.showSearchInputInDropdown === false) {
        this.initInput(this.$('.selectivity-single-select-input'), { search: false });
    }

    this.events.on({
        change: this.rerenderSelection,
        click: this._clicked,
        'click .selectivity-search-input': stopPropagation,
        'click .selectivity-single-selected-item-remove': this._itemRemoveClicked,
        'focus .selectivity-single-select-input': this._focused,
        'selectivity-selected': this._resultSelected
    });
}

/**
 * Methods.
 */
var callSuper = Selectivity.inherits(SingleInput, Selectivity, {
    /**
     * Clears the data and value.
     */
    clear: function() {
        this.setData(null);
    },

    /**
     * @inherit
     *
     * @param options Optional options object. May contain the following property:
     *                keepFocus - If true, the focus will remain on the input.
     */
    close: function(options) {
        this._closing = true;

        callSuper(this, 'close');

        if (options && options.keepFocus && this.input) {
            this.input.focus();
        }

        this._closing = false;
    },

    /**
     * Returns the correct data for a given value.
     *
     * @param value The value to get the data for. Should be an ID.
     *
     * @return The corresponding data. Will be an object with 'id' and 'text' properties. Note that
     *         if no items are defined, this method assumes the text label will be equal to the ID.
     */
    getDataForValue: function(value) {
        return this.getItemForId(value);
    },

    /**
     * Returns the correct value for the given data.
     *
     * @param data The data to get the value for. Should be an object with 'id' and 'text'
     *             properties or null.
     *
     * @return The corresponding value. Will be an ID or null.
     */
    getValueForData: function(data) {
        return data ? data.id : null;
    },

    /**
     * Re-renders the selection.
     *
     * Normally the UI is automatically updated whenever the selection changes, but you may want to
     * call this method explicitly if you've updated the selection with the triggerChange option set
     * to false.
     */
    rerenderSelection: function() {
        var template = this._data ? 'singleSelectedItem' : 'singleSelectPlaceholder';
        var options = this._data
            ? assign(
                  {
                      removable: this.options.allowClear && !this.options.readOnly
                  },
                  this._data
              )
            : { placeholder: this.options.placeholder };

        this.el.querySelector('input').value = this._value;
        this.$('.selectivity-single-result-container').innerHTML = this.template(template, options);
    },

    /**
     * Validates data to set. Throws an exception if the data is invalid.
     *
     * @param data The data to validate. Should be an object with 'id' and 'text' properties or null
     *             to indicate no item is selected.
     *
     * @return The validated data. This may differ from the input data.
     */
    validateData: function(data) {
        return data === null ? data : this.validateItem(data);
    },

    /**
     * Validates a value to set. Throws an exception if the value is invalid.
     *
     * @param value The value to validate. Should be null or a valid ID.
     *
     * @return The validated value. This may differ from the input value.
     */
    validateValue: function(value) {
        if (value === null || Selectivity.isValidId(value)) {
            return value;
        } else {
            throw new Error('Value for SingleSelectivity instance should be a valid ID or null');
        }
    },

    /**
     * @private
     */
    _clicked: function() {
        if (this.enabled) {
            if (this.dropdown) {
                this.close({ keepFocus: true });
            } else if (this.options.showDropdown !== false) {
                this.open();
            }
        }
    },

    /**
     * @private
     */
    _focused: function() {
        if (
            this.enabled &&
            !this._closing &&
            !this._opening &&
            this.options.showDropdown !== false
        ) {
            this.open();
        }
    },

    /**
     * @private
     */
    _itemRemoveClicked: function(event) {
        this.setData(null);

        stopPropagation(event);
    },

    /**
     * @private
     */
    _resultSelected: function(event) {
        this.setData(event.item);

        this.close({ keepFocus: true });
    }
});

module.exports = Selectivity.Inputs.Single = SingleInput;
<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
(function(scope) {
  var preparingElements = 0;

  var base = {
    PolymerBase: true,
    job: Polymer.job,
    super: Polymer.super,
    // user entry point for element has had its createdCallback called
    created: function() {
    },
    // user entry point for element has shadowRoot and is ready for
    // api interaction
    ready: function() {
    },
    createdCallback: function() {
      this.created();
      if (this.ownerDocument.defaultView || this.alwaysPrepare ||
          preparingElements > 0) {
        this.prepareElement();
      }
    },
    // system entry point, do not override
    prepareElement: function() {
      this._elementPrepared = true;
      // install property observers
      this.observeProperties();
      // install boilerplate attributes
      this.copyInstanceAttributes();
      // process input attributes
      this.takeAttributes();
      // add event listeners
      this.addHostListeners();
      // guarantees that while preparing, any
      // sub-elements are also prepared
      preparingElements++;
      // process declarative resources
      this.parseDeclarations(this.__proto__);
      // decrement semaphore
      preparingElements--;
      // user entry point
      this.ready();
    },
    attachedCallback: function() {
      if (!this._elementPrepared) {
        this.prepareElement();
      }
      this.cancelUnbindAll(true);
      // invoke user action
      if (this.attached) {
        this.attached();
      }
      // TODO(sorvell): bc
      if (this.enteredView) {
        this.enteredView();
      }
    },
    detachedCallback: function() {
      if (!this.preventDispose) {
        this.asyncUnbindAll();
      }
      // invoke user action
      if (this.detached) {
        this.detached();
      }
      // TODO(sorvell): bc
      if (this.leftView) {
        this.leftView();
      }
    },
    // TODO(sorvell): bc
    enteredViewCallback: function() {
      this.attachedCallback();
    },
    // TODO(sorvell): bc
    leftViewCallback: function() {
      this.detachedCallback();
    },
    // TODO(sorvell): bc
    enteredDocumentCallback: function() {
      this.attachedCallback();
    },
    // TODO(sorvell): bc
    leftDocumentCallback: function() {
      this.detachedCallback();
    },
    // recursive ancestral <element> initialization, oldest first
    parseDeclarations: function(p) {
      if (p && p.element) {
        this.parseDeclarations(p.__proto__);
        p.parseDeclaration.call(this, p.element);
      }
    },
    // parse input <element> as needed, override for custom behavior
    parseDeclaration: function(elementElement) {
      var template = this.fetchTemplate(elementElement);
      if (template) {
        this.shadowFromTemplate(template);
      }
    },
    // return a shadow-root template (if desired), override for custom behavior
    fetchTemplate: function(elementElement) {
      return elementElement.querySelector('template');
    },
    // utility function that creates a shadow root from a <template>
    shadowFromTemplate: function(template) {
      if (template) {
        // cache elder shadow root (if any)
        var elderRoot = this.shadowRoot;
        // make a shadow root
        var root = this.createShadowRoot();
        // migrate flag(s)
        root.resetStyleInheritance = this.resetStyleInheritance;
        // stamp template
        // which includes parsing and applying MDV bindings before being
        // inserted (to avoid {{}} in attribute values)
        // e.g. to prevent  from generating a 404.
        var dom = this.instanceTemplate(template);
        // append to shadow dom
        root.appendChild(dom);
        // perform post-construction initialization tasks on shadow root
        this.shadowRootReady(root, template);
        // return the created shadow root
        return root;
      }
    },
    // utility function that stamps a <template> into light-dom
    lightFromTemplate: function(template) {
      if (template) {
        // stamp template
        // which includes parsing and applying MDV bindings before being
        // inserted (to avoid {{}} in attribute values)
        // e.g. to prevent  from generating a 404.
        var dom = this.instanceTemplate(template);
        // append to shadow dom
        this.appendChild(dom);
        // perform post-construction initialization tasks on ahem, light root
        this.shadowRootReady(this, template);
        // return the created shadow root
        return dom;
      }
    },
    shadowRootReady: function(root, template) {
      // locate nodes with id and store references to them in this.$ hash
      this.marshalNodeReferences(root);
      // set up pointer gestures
      PointerGestures.register(root);
    },
    // locate nodes with id and store references to them in this.$ hash
    marshalNodeReferences: function(root) {
      // establish $ instance variable
      var $ = this.$ = this.$ || {};
      // populate $ from nodes with ID from the LOCAL tree
      if (root) {
        var n$ = root.querySelectorAll("[id]");
        for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) {
          $[n.id] = n;
        };
      }
    },
    attributeChangedCallback: function(name, oldValue) {
      // TODO(sjmiles): adhoc filter
      if (name !== 'class' && name !== 'style') {
        this.attributeToProperty(name, this.getAttribute(name));
      }
      if (this.attributeChanged) {
        this.attributeChanged.apply(this, arguments);
      }
    },
    onMutation: function(node, listener) {
      var observer = new MutationObserver(function(mutations) {
        listener.call(this, observer, mutations);
        observer.disconnect();
      }.bind(this));
      observer.observe(node, {childList: true, subtree: true});
    }
  };

  // true if object has own PolymerBase api
  function isBase(object) {
    return object.hasOwnProperty('PolymerBase')
  }

  // name a base constructor for dev tools

  function PolymerBase() {};
  PolymerBase.prototype = base;
  base.constructor = PolymerBase;

  // exports

  scope.Base = PolymerBase;
  scope.isBase = isBase;
  scope.api.instance.base = base;

})(Polymer);
<commit_msg>ensure unresolved attribute is removed.<commit_after>/*
 * Copyright 2013 The Polymer Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
(function(scope) {
  var preparingElements = 0;

  var base = {
    PolymerBase: true,
    job: Polymer.job,
    super: Polymer.super,
    // user entry point for element has had its createdCallback called
    created: function() {
    },
    // user entry point for element has shadowRoot and is ready for
    // api interaction
    ready: function() {
    },
    createdCallback: function() {
      this.created();
      if (this.ownerDocument.defaultView || this.alwaysPrepare ||
          preparingElements > 0) {
        this.prepareElement();
      }
    },
    // system entry point, do not override
    prepareElement: function() {
      this._elementPrepared = true;
      // install property observers
      this.observeProperties();
      // install boilerplate attributes
      this.copyInstanceAttributes();
      // process input attributes
      this.takeAttributes();
      // add event listeners
      this.addHostListeners();
      // guarantees that while preparing, any
      // sub-elements are also prepared
      preparingElements++;
      // process declarative resources
      this.parseDeclarations(this.__proto__);
      // decrement semaphore
      preparingElements--;
      // TODO(sorvell): CE polyfill uses unresolved attribute to simulate
      // :unresolved; remove this attribute to be compatible with native
      // CE.
      this.removeAttribute('unresolved');
      // user entry point
      this.ready();
    },
    attachedCallback: function() {
      if (!this._elementPrepared) {
        this.prepareElement();
      }
      this.cancelUnbindAll(true);
      // invoke user action
      if (this.attached) {
        this.attached();
      }
      // TODO(sorvell): bc
      if (this.enteredView) {
        this.enteredView();
      }
    },
    detachedCallback: function() {
      if (!this.preventDispose) {
        this.asyncUnbindAll();
      }
      // invoke user action
      if (this.detached) {
        this.detached();
      }
      // TODO(sorvell): bc
      if (this.leftView) {
        this.leftView();
      }
    },
    // TODO(sorvell): bc
    enteredViewCallback: function() {
      this.attachedCallback();
    },
    // TODO(sorvell): bc
    leftViewCallback: function() {
      this.detachedCallback();
    },
    // TODO(sorvell): bc
    enteredDocumentCallback: function() {
      this.attachedCallback();
    },
    // TODO(sorvell): bc
    leftDocumentCallback: function() {
      this.detachedCallback();
    },
    // recursive ancestral <element> initialization, oldest first
    parseDeclarations: function(p) {
      if (p && p.element) {
        this.parseDeclarations(p.__proto__);
        p.parseDeclaration.call(this, p.element);
      }
    },
    // parse input <element> as needed, override for custom behavior
    parseDeclaration: function(elementElement) {
      var template = this.fetchTemplate(elementElement);
      if (template) {
        this.shadowFromTemplate(template);
      }
    },
    // return a shadow-root template (if desired), override for custom behavior
    fetchTemplate: function(elementElement) {
      return elementElement.querySelector('template');
    },
    // utility function that creates a shadow root from a <template>
    shadowFromTemplate: function(template) {
      if (template) {
        // cache elder shadow root (if any)
        var elderRoot = this.shadowRoot;
        // make a shadow root
        var root = this.createShadowRoot();
        // migrate flag(s)
        root.resetStyleInheritance = this.resetStyleInheritance;
        // stamp template
        // which includes parsing and applying MDV bindings before being
        // inserted (to avoid {{}} in attribute values)
        // e.g. to prevent  from generating a 404.
        var dom = this.instanceTemplate(template);
        // append to shadow dom
        root.appendChild(dom);
        // perform post-construction initialization tasks on shadow root
        this.shadowRootReady(root, template);
        // return the created shadow root
        return root;
      }
    },
    // utility function that stamps a <template> into light-dom
    lightFromTemplate: function(template) {
      if (template) {
        // stamp template
        // which includes parsing and applying MDV bindings before being
        // inserted (to avoid {{}} in attribute values)
        // e.g. to prevent  from generating a 404.
        var dom = this.instanceTemplate(template);
        // append to shadow dom
        this.appendChild(dom);
        // perform post-construction initialization tasks on ahem, light root
        this.shadowRootReady(this, template);
        // return the created shadow root
        return dom;
      }
    },
    shadowRootReady: function(root, template) {
      // locate nodes with id and store references to them in this.$ hash
      this.marshalNodeReferences(root);
      // set up pointer gestures
      PointerGestures.register(root);
    },
    // locate nodes with id and store references to them in this.$ hash
    marshalNodeReferences: function(root) {
      // establish $ instance variable
      var $ = this.$ = this.$ || {};
      // populate $ from nodes with ID from the LOCAL tree
      if (root) {
        var n$ = root.querySelectorAll("[id]");
        for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) {
          $[n.id] = n;
        };
      }
    },
    attributeChangedCallback: function(name, oldValue) {
      // TODO(sjmiles): adhoc filter
      if (name !== 'class' && name !== 'style') {
        this.attributeToProperty(name, this.getAttribute(name));
      }
      if (this.attributeChanged) {
        this.attributeChanged.apply(this, arguments);
      }
    },
    onMutation: function(node, listener) {
      var observer = new MutationObserver(function(mutations) {
        listener.call(this, observer, mutations);
        observer.disconnect();
      }.bind(this));
      observer.observe(node, {childList: true, subtree: true});
    }
  };

  // true if object has own PolymerBase api
  function isBase(object) {
    return object.hasOwnProperty('PolymerBase')
  }

  // name a base constructor for dev tools

  function PolymerBase() {};
  PolymerBase.prototype = base;
  base.constructor = PolymerBase;

  // exports

  scope.Base = PolymerBase;
  scope.isBase = isBase;
  scope.api.instance.base = base;

})(Polymer);
<|endoftext|>


<commit_before>const { DataEvents, DataProps, DataDefaultScopedSlotProps } = require('./v-data')
const { DataFooterPageTextScopedProps } = require('./v-data-footer')

const DataIteratorProps = DataProps.concat([
  { name: 'value', source: 'v-data-iterator' },
  { name: 'singleSelect', source: 'v-data-iterator' },
  { name: 'expanded', source: 'v-data-iterator' },
  { name: 'singleExpand', source: 'v-data-iterator' },
  { name: 'loading', source: 'v-data-iterator' },
  { name: 'loadingText', source: 'v-data-iterator' },
  { name: 'noResultsText', source: 'v-data-iterator' },
  { name: 'noDataText', source: 'v-data-iterator' },
  { name: 'hideDefaultFooter', source: 'v-data-iterator' },
  { name: 'footerProps', source: 'v-data-iterator' },
])

const DataIteratorEvents = DataEvents.concat([
  { name: 'input', source: 'v-data-iterator', value: 'any[]' },
  { name: 'update:expanded', source: 'v-data-iterator', value: 'any[]' },
  { name: 'item-selected', source: 'v-data-iterator', value: '{ item: any, value: boolean }' },
  { name: 'item-expanded', source: 'v-data-iterator', value: '{ item: any, value: boolean }' },
  { name: 'toggle-select-all', source: 'v-data-iterator', value: '{ items: any[], value: boolean }' },
])

const DataIteratorSlots = [
  { name: 'loading', source: 'data-iterator' },
  { name: 'no-data', source: 'data-iterator' },
  { name: 'no-results', source: 'data-iterator' },
]

const DataIteratorItemScopedProps = {
  item: 'any',
  select: '(v: boolean) => void',
  isSelected: 'boolean',
  expand: '(v: boolean) => void',
  isExpanded: 'boolean',
}

const DataIteratorScopedSlots = [
  {
    name: 'default',
    props: {
      ...DataDefaultScopedSlotProps,
      isSelected: '(item: any) => boolean',
      select: '(item: any, value: boolean) => void',
      isExpanded: '(item: any) => boolean',
      expand: '(item: any, value: boolean) => void',
    },
    source: 'data-iterator',
  },
  {
    name: 'footer',
    props: DataDefaultScopedSlotProps,
    source: 'data-iterator',
  },
  {
    name: 'footer.page-text',
    props: DataFooterPageTextScopedProps,
    source: 'data-iterator',
  },
  {
    name: 'header',
    props: DataDefaultScopedSlotProps,
    source: 'data-iterator',
  },
  {
    name: 'item',
    props: DataIteratorItemScopedProps,
    source: 'data-iterator',
  },
]

module.exports = {
  'v-data-iterator': {
    props: DataIteratorProps,
    slots: [
      ...DataIteratorSlots,
      ...DataIteratorScopedSlots,
    ],
    events: DataIteratorEvents,
  },
  DataIteratorProps,
  DataIteratorEvents,
  DataIteratorSlots,
  DataIteratorScopedSlots,
  DataIteratorItemScopedProps,
}
<commit_msg>docs(api): update data iterator item slot<commit_after>const { DataEvents, DataProps, DataDefaultScopedSlotProps } = require('./v-data')
const { DataFooterPageTextScopedProps } = require('./v-data-footer')

const DataIteratorProps = DataProps.concat([
  { name: 'value', source: 'v-data-iterator' },
  { name: 'singleSelect', source: 'v-data-iterator' },
  { name: 'expanded', source: 'v-data-iterator' },
  { name: 'singleExpand', source: 'v-data-iterator' },
  { name: 'loading', source: 'v-data-iterator' },
  { name: 'loadingText', source: 'v-data-iterator' },
  { name: 'noResultsText', source: 'v-data-iterator' },
  { name: 'noDataText', source: 'v-data-iterator' },
  { name: 'hideDefaultFooter', source: 'v-data-iterator' },
  { name: 'footerProps', source: 'v-data-iterator' },
])

const DataIteratorEvents = DataEvents.concat([
  { name: 'input', source: 'v-data-iterator', value: 'any[]' },
  { name: 'update:expanded', source: 'v-data-iterator', value: 'any[]' },
  { name: 'item-selected', source: 'v-data-iterator', value: '{ item: any, value: boolean }' },
  { name: 'item-expanded', source: 'v-data-iterator', value: '{ item: any, value: boolean }' },
  { name: 'toggle-select-all', source: 'v-data-iterator', value: '{ items: any[], value: boolean }' },
])

const DataIteratorSlots = [
  { name: 'loading', source: 'data-iterator' },
  { name: 'no-data', source: 'data-iterator' },
  { name: 'no-results', source: 'data-iterator' },
]

const DataIteratorItemScopedProps = {
  expand: '(v: boolean) => void',
  item: 'any',
  isExpanded: 'boolean',
  isMobile: 'boolean',
  isSelected: 'boolean',
  select: '(v: boolean) => void',
}

const DataIteratorScopedSlots = [
  {
    name: 'default',
    props: {
      ...DataDefaultScopedSlotProps,
      isSelected: '(item: any) => boolean',
      select: '(item: any, value: boolean) => void',
      isExpanded: '(item: any) => boolean',
      expand: '(item: any, value: boolean) => void',
    },
    source: 'data-iterator',
  },
  {
    name: 'footer',
    props: DataDefaultScopedSlotProps,
    source: 'data-iterator',
  },
  {
    name: 'footer.page-text',
    props: DataFooterPageTextScopedProps,
    source: 'data-iterator',
  },
  {
    name: 'header',
    props: DataDefaultScopedSlotProps,
    source: 'data-iterator',
  },
  {
    name: 'item',
    props: DataIteratorItemScopedProps,
    source: 'data-iterator',
  },
]

module.exports = {
  'v-data-iterator': {
    props: DataIteratorProps,
    slots: [
      ...DataIteratorSlots,
      ...DataIteratorScopedSlots,
    ],
    events: DataIteratorEvents,
  },
  DataIteratorProps,
  DataIteratorEvents,
  DataIteratorSlots,
  DataIteratorScopedSlots,
  DataIteratorItemScopedProps,
}
<|endoftext|>


<commit_before>import { get, set, lowerFirst } from 'lodash';
import { addFields } from 'olymp-graphql/server';
import adaptQuery from './adapt-query';
import shortId from 'shortid';

export default (ast, node, resolvers, typeName, isGeneric) => {
  const name = node.name.value;
  const table = lowerFirst(typeName || name);

  const Query = ast.definitions.find(x => get(x, 'name.value') === 'RootQuery');

  if (Query) {
    // Add one query
    addFields(
      ast,
      Query,
      `${table}(id: String, query: ${name}Query, sort: ${name}Sort): ${name}`,
      { replace: false }
    );
    if (!get(resolvers, `RootQuery.${table}`)) {
      set(resolvers, `RootQuery.${table}`, (source, { id, query }, { monk, app }) => {
        const x = id ? { id } : adaptQuery(query);
        const q = isGeneric ? { ...x, _appId: app.id } : { ...x, _type: table, _appId: app.id };
        // monk.collection(table).findOne(id ? { id } : adaptQuery(query))
        return monk.collection('item').findOne(q);
      });
    }

    // Add list query
    addFields(
      ast,
      Query,
      `${table}List(query: ${name}Query, sort: ${name}Sort, limit: Int, skip: Int): [${name}]`,
      { replace: false }
    );
    if (!get(resolvers, `RootQuery.${table}List`)) {
      set(
        resolvers,
        `RootQuery.${table}List`,
        (source, { query, sort }, { monk, app }) =>
          // monk.collection(table).find(adaptQuery(query))
          monk
            .collection('item')
            .find(
            isGeneric ? { ...adaptQuery(query), _appId: app.id } : { ...adaptQuery(query), _type: table, _appId: app.id },
            { rawCursor: true }
            )
            .then((cursor) => {
              const obj = sort || { name: 'ASC' };
              const sorting = Object.keys(obj).reduce((store, key) => {
                store[key] = obj[key] === 'DESC' ? -1 : 1;
                return store;
              }, {});
              return cursor.sort(sorting).toArray();
            })
      );
    }
  }

  const Mutation = ast.definitions.find(
    x => get(x, 'name.value') === 'RootMutation'
  );

  if (Mutation) {
    // Add mutation
    addFields(
      ast,
      Mutation,
      `${table}(id: String, type: MUTATION_TYPE, input: ${name}Input): ${name}`,
      { replace: false }
    );
    if (!get(resolvers, `RootMutation.${table}`)) {
      set(
        resolvers,
        `RootMutation.${table}`,
        /* (source, { id, input, type }, { monk }) => {
          if (!id) {
            monk.collection(table).insert(input);
          } else if (type === 'REPLACE') {
            monk.collection(table).update(input);
          } else {
            monk.collection(table).update({ $set: input });
          }
        }*/
        (source, { id, input, type }, { monk, app }) => {
          let promise;
          if (!id) {
            id = shortId.generate();
            promise = monk
              .collection('item')
              .insert({ ...input, _type: table, _appId: app.id, id });
          } else if (type === 'REMOVE') {
            promise = monk
              .collection('item')
              .update({ _type: table, id }, { ...input, state: 'REMOVED' });
          } else if (type === 'REPLACE') {
            promise = monk
              .collection('item')
              .update({ _type: table, id }, { ...input, _type: table, _appId: app.id, id });
          } else {
            promise = monk
              .collection('item')
              .update({ _type: table, id }, { $set: { ...input } });
          }
          return promise.then(() => monk.collection('item').findOne({ id, _type: table }));
        }
      );
    }
  }
};
<commit_msg>skip/limit<commit_after>import { get, set, lowerFirst } from 'lodash';
import { addFields } from 'olymp-graphql/server';
import adaptQuery from './adapt-query';
import shortId from 'shortid';

export default (ast, node, resolvers, typeName, isGeneric) => {
  const name = node.name.value;
  const table = lowerFirst(typeName || name);

  const Query = ast.definitions.find(x => get(x, 'name.value') === 'RootQuery');

  if (Query) {
    // Add one query
    addFields(ast, Query, `${table}(id: String, query: ${name}Query, sort: ${name}Sort): ${name}`, {
      replace: false,
    });
    if (!get(resolvers, `RootQuery.${table}`)) {
      set(resolvers, `RootQuery.${table}`, (source, { id, query }, { monk, app }) => {
        const x = id ? { id } : adaptQuery(query);
        const q = isGeneric ? { ...x, _appId: app.id } : { ...x, _type: table, _appId: app.id };
        // monk.collection(table).findOne(id ? { id } : adaptQuery(query))
        return monk.collection('item').findOne(q);
      });
    }

    // Add list query
    addFields(
      ast,
      Query,
      `${table}List(query: ${name}Query, sort: ${name}Sort, limit: Int, skip: Int): [${name}]`,
      { replace: false },
    );
    if (!get(resolvers, `RootQuery.${table}List`)) {
      set(
        resolvers,
        `RootQuery.${table}List`,
        (source, { query, sort, limit, skip }, { monk, app }) =>
          // monk.collection(table).find(adaptQuery(query))
          monk
            .collection('item')
            .find(
              isGeneric
                ? { ...adaptQuery(query), _appId: app.id }
                : { ...adaptQuery(query), _type: table, _appId: app.id },
              { rawCursor: true },
            )
            .then((cursor) => {
              const obj = sort || { name: 'ASC' };
              const sorting = Object.keys(obj).reduce((store, key) => {
                store[key] = obj[key] === 'DESC' ? -1 : 1;
                return store;
              }, {});
              return cursor
                .sort(sorting)
                .limit(limit || 100)
                .skip(skip || 0)
                .toArray();
            }),
      );
    }
  }

  const Mutation = ast.definitions.find(x => get(x, 'name.value') === 'RootMutation');

  if (Mutation) {
    // Add mutation
    addFields(
      ast,
      Mutation,
      `${table}(id: String, type: MUTATION_TYPE, input: ${name}Input): ${name}`,
      { replace: false },
    );
    if (!get(resolvers, `RootMutation.${table}`)) {
      set(
        resolvers,
        `RootMutation.${table}`,
        /* (source, { id, input, type }, { monk }) => {
          if (!id) {
            monk.collection(table).insert(input);
          } else if (type === 'REPLACE') {
            monk.collection(table).update(input);
          } else {
            monk.collection(table).update({ $set: input });
          }
        } */
        (source, { id, input, type }, { monk, app }) => {
          let promise;
          if (!id) {
            id = shortId.generate();
            promise = monk
              .collection('item')
              .insert({ ...input, _type: table, _appId: app.id, id });
          } else if (type === 'REMOVE') {
            promise = monk
              .collection('item')
              .update({ _type: table, id }, { ...input, state: 'REMOVED' });
          } else if (type === 'REPLACE') {
            promise = monk
              .collection('item')
              .update({ _type: table, id }, { ...input, _type: table, _appId: app.id, id });
          } else {
            promise = monk.collection('item').update({ _type: table, id }, { $set: { ...input } });
          }
          return promise.then(() => monk.collection('item').findOne({ id, _type: table }));
        },
      );
    }
  }
};
<|endoftext|>


<commit_before>
function dial_widgetlist()
{
  var widgets = {
    "dial":
    {
      "offsetx":-80,"offsety":-80,"width":160,"height":160,
      "menu":"Widgets",
      "options":["feed","max","scale","units","type"],
      "optionstype":["feed","value","value","value","value"]
    }
  }
  return widgets;
}

function dial_init()
{
  setup_widget_canvas('dial');
}

function dial_draw()
{
  $('.dial').each(function(index)
  {
    var feed = $(this).attr("feed");
    var val = curve_value(feed,dialrate);
    // ONLY UPDATE ON CHANGE
    if ((val * 1).toFixed(1) != (assoc[feed] * 1).toFixed(1) || redraw == 1)
    {
      var id = "can-"+$(this).attr("id");
      var scale = 1*$(this).attr("scale") || 1;
      draw_gauge(widgetcanvas[id],0,0,$(this).width(),$(this).height(),val*scale, $(this).attr("max"), $(this).attr("units"),$(this).attr("type"));
    }
  });
}

function dial_slowupdate()
{

}

function dial_fastupdate()
{
  dial_draw();
}

  function draw_gauge(ctx,x,y,width,height,position,maxvalue,units,type)
  {
    if (!ctx) return;
    maxvalue = 1 * maxvalue || 3000;
    units = units || "";
    var size = 0; if (width<height) size = width/2; else size = height/2;
    size = size - (size*0.058/2);
    x = width/2; y = height/2;

    ctx.clearRect(0,0,200,200);

    if (!position) position = 0;

    var offset = 0;
    var segment = ["#c0e392","#9dc965","#87c03f","#70ac21","#378d42","#046b34"];

    var type = type || 0;

    if (type == 0)
    {
      if (position<0) position = 0;
    }
    else if (type == 1)
    {
      offset = -0.75;
      segment = ["#e61703","#ff6254","#ffa29a","#70ac21","#378d42","#046b34"];
    }
    else if (type == 2)
    {
      segment = ["#046b34","#378d42","#87c03f","#f8a01b","#f46722","#bf2025"];
    }
    else if (type == 3)
    {
      offset = -0.75;
      segment = ["#046b34","#378d42","#87c03f","#f8a01b","#f46722","#bf2025"];
    }
    else if (type == 4)
    {
      segment = ["#bf2025","#f46722","#f8a01b","#87c03f","#378d42","#046b34"];
    }
    else if (type == 5)
    {
      offset = -0.75;
      segment = ["#bf2025","#f46722","#f8a01b","#87c03f","#378d42","#046b34"];
    }
    else if (type == 6)
    {
      offset = -0.75;
      segment = ["#f46722","#f8a01b","#87c03f","#87c03f","#f8a01b","#f46722"];
    }
    else if (type == 7)
    {
      offset = 0;
      segment = ["#a7cbe2","#68b7eb","#0d97f3","#0f81d0","#0c6dae","#08578e"];
    }
    else if (type == 8)  //temperature dial blue-red, first segment blue should mean below freezing C
    {
      offset = -0.25;
      segment = ["#b7beff","#ffd9d9","#ffbebe","#ff9c9c","#ff6e6e","#ff3d3d"];
    }
    else if (type == 9)  //temperature dial blue-red, first segment blue should mean below freezing C
    {
      offset = 0;
      segment = ["#e94937","#da4130","#c43626","#ad2b1c","#992113","#86170a"];
    }

    if (position>maxvalue) position = maxvalue;
    var a = 1.75 - ((position/maxvalue) * 1.5) + offset;

  var c=3*0.785;
  var width = 0.785;
  var pos = 0;
  var inner = size * 0.48;

  // Segments
  for (z in segment)
  {
    ctx.fillStyle = segment[z];
    ctx.beginPath();
    ctx.arc(x,y,size,c+pos,c+pos+width+0.01,false);
    ctx.lineTo(x,y);
    ctx.closePath();
    ctx.fill();
    pos += width;
  }
  pos -= width;
  ctx.lineWidth = (size*0.058).toFixed(0);
  pos += width;
  ctx.strokeStyle = "#fff";
  ctx.beginPath();
  ctx.arc(x,y,size,c,c+pos,false);
  ctx.lineTo(x,y);
  ctx.closePath();
  ctx.stroke();

  ctx.fillStyle = "#666867";
  ctx.beginPath();
  ctx.arc(x,y,inner,0,Math.PI*2,true);
  ctx.closePath();
  ctx.fill();

  ctx.lineWidth = (size*0.052).toFixed(0);
  //---------------------------------------------------------------
  ctx.beginPath();
  ctx.moveTo(x+Math.sin(Math.PI*a-0.2)*inner,y+Math.cos(Math.PI*a-0.2)*inner);
  ctx.lineTo(x+Math.sin(Math.PI*a)*size,y+Math.cos(Math.PI*a)*size);
  ctx.lineTo(x+Math.sin(Math.PI*a+0.2)*inner,y+Math.cos(Math.PI*a+0.2)*inner);
  ctx.arc(x,y,inner,1-(Math.PI*a-0.2),1-(Math.PI*a+5.4),true);
  ctx.closePath();
  ctx.fill();
  ctx.stroke();

  //---------------------------------------------------------------

  ctx.fillStyle = "#fff";
  ctx.textAlign    = "center";
  ctx.font = "bold "+(size*0.28)+"px arial";
  if (position>10) position = position.toFixed(0); else position = position.toFixed(1);
  ctx.fillText(position+units,x,y+(size*0.125));

  }

<commit_msg>Fix discrepancy in dial value<commit_after>
function dial_widgetlist()
{
  var widgets = {
    "dial":
    {
      "offsetx":-80,"offsety":-80,"width":160,"height":160,
      "menu":"Widgets",
      "options":["feed","max","scale","units","type"],
      "optionstype":["feed","value","value","value","value"]
    }
  }
  return widgets;
}

function dial_init()
{
  setup_widget_canvas('dial');
}

function dial_draw()
{
  $('.dial').each(function(index)
  {
    var feed = $(this).attr("feed");
    var val = curve_value(feed,dialrate);
    // ONLY UPDATE ON CHANGE
    if ((val * 1).toFixed(2) != (assoc[feed] * 1).toFixed(2) || redraw == 1)
    {
      var id = "can-"+$(this).attr("id");
      var scale = 1*$(this).attr("scale") || 1;
      draw_gauge(widgetcanvas[id],0,0,$(this).width(),$(this).height(),val*scale, $(this).attr("max"), $(this).attr("units"),$(this).attr("type"));
    }
  });
}

function dial_slowupdate()
{

}

function dial_fastupdate()
{
  dial_draw();
}

  function draw_gauge(ctx,x,y,width,height,position,maxvalue,units,type)
  {
    if (!ctx) return;
    maxvalue = 1 * maxvalue || 3000;
    units = units || "";
    var size = 0; if (width<height) size = width/2; else size = height/2;
    size = size - (size*0.058/2);
    x = width/2; y = height/2;

    ctx.clearRect(0,0,200,200);

    if (!position) position = 0;

    var offset = 0;
    var segment = ["#c0e392","#9dc965","#87c03f","#70ac21","#378d42","#046b34"];

    var type = type || 0;

    if (type == 0)
    {
      if (position<0) position = 0;
    }
    else if (type == 1)
    {
      offset = -0.75;
      segment = ["#e61703","#ff6254","#ffa29a","#70ac21","#378d42","#046b34"];
    }
    else if (type == 2)
    {
      segment = ["#046b34","#378d42","#87c03f","#f8a01b","#f46722","#bf2025"];
    }
    else if (type == 3)
    {
      offset = -0.75;
      segment = ["#046b34","#378d42","#87c03f","#f8a01b","#f46722","#bf2025"];
    }
    else if (type == 4)
    {
      segment = ["#bf2025","#f46722","#f8a01b","#87c03f","#378d42","#046b34"];
    }
    else if (type == 5)
    {
      offset = -0.75;
      segment = ["#bf2025","#f46722","#f8a01b","#87c03f","#378d42","#046b34"];
    }
    else if (type == 6)
    {
      offset = -0.75;
      segment = ["#f46722","#f8a01b","#87c03f","#87c03f","#f8a01b","#f46722"];
    }
    else if (type == 7)
    {
      offset = 0;
      segment = ["#a7cbe2","#68b7eb","#0d97f3","#0f81d0","#0c6dae","#08578e"];
    }
    else if (type == 8)  //temperature dial blue-red, first segment blue should mean below freezing C
    {
      offset = -0.25;
      segment = ["#b7beff","#ffd9d9","#ffbebe","#ff9c9c","#ff6e6e","#ff3d3d"];
    }
    else if (type == 9)  //temperature dial blue-red, first segment blue should mean below freezing C
    {
      offset = 0;
      segment = ["#e94937","#da4130","#c43626","#ad2b1c","#992113","#86170a"];
    }

    if (position>maxvalue) position = maxvalue;
    var a = 1.75 - ((position/maxvalue) * 1.5) + offset;

  var c=3*0.785;
  var width = 0.785;
  var pos = 0;
  var inner = size * 0.48;

  // Segments
  for (z in segment)
  {
    ctx.fillStyle = segment[z];
    ctx.beginPath();
    ctx.arc(x,y,size,c+pos,c+pos+width+0.01,false);
    ctx.lineTo(x,y);
    ctx.closePath();
    ctx.fill();
    pos += width;
  }
  pos -= width;
  ctx.lineWidth = (size*0.058).toFixed(0);
  pos += width;
  ctx.strokeStyle = "#fff";
  ctx.beginPath();
  ctx.arc(x,y,size,c,c+pos,false);
  ctx.lineTo(x,y);
  ctx.closePath();
  ctx.stroke();

  ctx.fillStyle = "#666867";
  ctx.beginPath();
  ctx.arc(x,y,inner,0,Math.PI*2,true);
  ctx.closePath();
  ctx.fill();

  ctx.lineWidth = (size*0.052).toFixed(0);
  //---------------------------------------------------------------
  ctx.beginPath();
  ctx.moveTo(x+Math.sin(Math.PI*a-0.2)*inner,y+Math.cos(Math.PI*a-0.2)*inner);
  ctx.lineTo(x+Math.sin(Math.PI*a)*size,y+Math.cos(Math.PI*a)*size);
  ctx.lineTo(x+Math.sin(Math.PI*a+0.2)*inner,y+Math.cos(Math.PI*a+0.2)*inner);
  ctx.arc(x,y,inner,1-(Math.PI*a-0.2),1-(Math.PI*a+5.4),true);
  ctx.closePath();
  ctx.fill();
  ctx.stroke();

  //---------------------------------------------------------------

  ctx.fillStyle = "#fff";
  ctx.textAlign    = "center";
  ctx.font = "bold "+(size*0.28)+"px arial";
  if (position>10) position = position.toFixed(0); else position = position.toFixed(1);
  ctx.fillText(position+units,x,y+(size*0.125));

  }

<|endoftext|>


<commit_before>(function( $ ) {
	$.fn.sequenceDiagram = function( options ) {

		var settings = $.extend( {
			'theme' : 'hand'
		}, options);

		return this.each(function() {
			var $this = $(this);
			var diagram = Diagram.parse($this.val());
			// Blank the HTML
			$this.html('');
			diagram.drawSVG(this, settings);
		});
	};
})( jQuery );<commit_msg>Fixed the jquery plugin.<commit_after>(function( $ ) {
	$.fn.sequenceDiagram = function( options ) {
		return this.each(function() {
			var $this = $(this);
			var diagram = Diagram.parse($this.text());
			$this.html('');
			diagram.drawSVG(this, options);
		});
	};
})( jQuery );<|endoftext|>


<commit_before>/**
 * ElevatorEngine
 * The core engine of the elevator
**/

'use strict'

var async = require('async');
var path = require('path');
var Errors = require('../errors/elevator-errors.js');
var FloorSelectionOptions = require('../floor-controllers/floor-controller.js').FloorSelectionOptions;
var FloorController = require('../floor-controllers/floor-controller.js').FloorController;
var FloorWorkerParameters = require('./floor-worker-parameters.js');
var BaseLevelController = require('../level-controllers/base-level-controller.js');
var Level = require('../level-controllers/level.js');

/**
 * Constructor
 */
var ElevatorEngine = function() {
}

/**
 * Get floors for selected destination
 * @param config
 * @param level
 * @param floor
 * @param callback(error, floors)
 */
var _getFloors = function(config, level, floor, callback) {
    var floors = [];
    var fromIdentifier = level ? level.identifier : null;
    var options = FloorSelectionOptions.createFromIdentifiers(fromIdentifier, floor);

    try{
        floors = FloorController.getFloors(config.floorsDir, options);
        return callback(null, floors, options);
    } catch(error) {
        return callback(error);
    }
}

/**
 * Migrate an array of migration files
 * @param config
 * @param floors
 * @param ascending
 * @param logger
 * @param levelController - Object derived from BaseLevelController to do custom level storage
 * @param callback(error)
 */
var _moveElevator = function(config, floors, ascending, logger, levelController, callback) {
    var self = this;

    //Itterate migrations files
    async.eachSeries(floors, function(floor, callback) {
        var parameters = new FloorWorkerParameters(config, logger, floor);
        var floorWorker = require(floor.filePath);
        var directionText = (ascending === true) ? 'Up' : 'Down';

        //Checkf if function is available in migration file
        if(floorWorker['on' + directionText]) {
            async.waterfall([
                function(callback) {
                    floorWorker['on' + directionText](parameters, function(error) {
                        if(error) {
                            logger.error('>>>> Stuck at floor ' + floor.getLongName());
                        } else {
                            logger.info('>>>> Migrating ' + directionText.toLowerCase() + ' floor: ' + floor.getLongName());
                        }
                        return callback(error);
                    });
                },
                function(callback) {
                    levelController.saveCurrentLevel(Level.create(floor.identifier), function(error) {
                        if(error) {
                            logger.error('>>>> Stuck at floor ' + floor.identifier + '. Failed to store the current level');
                        }
                        return callback(error);
                    });
                }
            ], function(error) {
                return callback(error);
            })
        } else {
            return callback(Errors.generalError('>>>> Invalid floor ' + floor.filePath));
        }
    }, function(error) {
        return callback(error);
    })
}

/**
 * Move elevator
 * @param config
 * @param floor
 * @param logger
 * @param LevelController - Class derived from BaseLevelController to do custom storage for current level
 * @param callback(error)
 */
ElevatorEngine.move = function(config, floor, logger, LevelController, callback) {
    var self = this;

    //Validate arguments
    if(!config) {
        return callback(Errors.invalidArgument('config', 'Object'));
    }

    if(floor === undefined || floor === null) {
        return callback(Errors.invalidArgument('floor', 'number'));
    }

    if(!LevelController) {
        return callback(Errors.generalError("Invalid argument 'LevelController' should be a class derived from 'BaseLevelController'"));
    }

    var levelController = null;

    try{
        levelController = new LevelController(config);
    } catch(error) {
       return callback(error);
    }

    if(levelController instanceof BaseLevelController) {
        async.waterfall([
            //Get the current migration status
            function(callback) {
                levelController.retrieveCurrentLevel(function(error, level) {
                    return callback(error, level);
                 })
            },
            //Get the migration files that need to be applied
            function(level, callback) {
                _getFloors(config, level, floor, function(error, floors, options) {
                    return callback(error, floors, options);
                })
            },
            //Migrate the files
            function(floors, options, callback) {
                if(floors != null && floors.length > 0) {
                   _moveElevator(config, floors, options.ascending, logger, levelController, function(error) {
                        return callback(error, floors, options);
                    });
                } else {
                    return callback(null, null, null);
                }
            },
             //Save the last level if going down, because the last level is not stored yet
            function(floors, options, callback) {
                if(floors && options && options.ascending === false) {
                    levelController.saveCurrentLevel(Level.create(options.identifierRange.min), function(error) {
                        if(error) {
                            logger.error('>>>> Stuck at floor ' + options.identifierRange.min + '. Failed to store the current level.');
                        }
                        return callback(error);
                    });
                } else {
                    return callback(null);
                }
            }
        ], function(error) {
            return callback(error);
        })
    } else {
        return callback(Errors.generalError("Invalid argument 'LevelController' should be a class derived from 'BaseLevelController'"));
    }
}

/**
 * Print the status of the elevator to the logger
 * @param config
 * @param logger
 * @param LevelController
 * @param callback(error)
 */
ElevatorEngine.printStatus = function(config, logger, LevelController, callback) {
    if(!LevelController) {
        return callback(Errors.generalError("Invalid argument 'LevelController' should be a class derived from 'BaseLevelController'"));
    }

    var levelController = new LevelController(config);

    levelController.retrieveCurrentLevel(function(error, level) {
        if(error) {
            logger.error('Failed to load elevator info.', error);
        } else if(level) {
            var date = new Date(level.timestamp);
            logger.info('Currently on floor: ' + level.identifier + '. Last movement: ' + date.toLocaleString() + ".");
        } else {
            logger.info('Elevator has not yet moved.');
        }
        return callback(error);
    })
}

/**
 * Print the status of the elevator to the logger
 * @param config
 * @param logger
 * @param LevelController
 * @param callback(error)
 */
ElevatorEngine.printList = function(config, logger, LevelController, callback) {
    if(!LevelController) {
        return callback(Errors.generalError("Invalid argument 'LevelController' should be a class derived from 'BaseLevelController'"));
    }

    var levelController = new LevelController(config);

    levelController.retrieveCurrentLevel(function(error, level) {
        if(!error) {
            if(!level || level.identifier == 0) {
                logger.info( ">> Floor: 0 - Ground floor");
            } else {
                logger.info( "   Floor: 0 - Ground floor");
            }

            _getFloors(config, null, null, function(error, floors, options) {
                if(!error) {
                    if(floors) {
                        floors.forEach(function(floor) {
                            if(level && level.identifier == floor.identifier) {
                                logger.info( ">> Floor: " + floor.getLongName());
                            } else {
                                logger.info( "   Floor: " + floor.getLongName());
                            }
                        });
                        return callback(null);
                    } else {
                        logger.info( "No floors available");
                        return callback(null);
                    }
                } else {
                    logger.error('Failed to load floors.', error);
                    return callback(error);
                }
            });
        } else {
             logger.error('Failed to load elevator info.', error);
             return callback(error);
        }
    });
}

module.exports = {
    ElevatorEngine: ElevatorEngine,
};<commit_msg>Prevent error:<commit_after>/**
 * ElevatorEngine
 * The core engine of the elevator
**/

'use strict'

var async = require('async');
var path = require('path');
var Errors = require('../errors/elevator-errors.js');
var FloorSelectionOptions = require('../floor-controllers/floor-controller.js').FloorSelectionOptions;
var FloorController = require('../floor-controllers/floor-controller.js').FloorController;
var FloorWorkerParameters = require('./floor-worker-parameters.js');
var BaseLevelController = require('../level-controllers/base-level-controller.js');
var Level = require('../level-controllers/level.js');

/**
 * Constructor
 */
var ElevatorEngine = function() {
}

/**
 * Get floors for selected destination
 * @param config
 * @param level
 * @param floor
 * @param callback(error, floors)
 */
var _getFloors = function(config, level, floor, callback) {
    var floors = [];
    var fromIdentifier = level ? level.identifier : null;
    var options = FloorSelectionOptions.createFromIdentifiers(fromIdentifier, floor);

    try{
        floors = FloorController.getFloors(config.floorsDir, options);
        return callback(null, floors, options);
    } catch(error) {
        return callback(error);
    }
}

/**
 * Migrate an array of migration files
 * @param config
 * @param floors
 * @param ascending
 * @param logger
 * @param levelController - Object derived from BaseLevelController to do custom level storage
 * @param callback(error)
 */
var _moveElevator = function(config, floors, ascending, logger, levelController, callback) {
    var self = this;

    //Itterate migrations files
    async.eachSeries(floors, function(floor, callback) {
        var parameters = new FloorWorkerParameters(config, logger, floor);
        var floorWorker = require(floor.filePath);
        var directionText = (ascending === true) ? 'Up' : 'Down';

        //Checkf if function is available in migration file
        if(floorWorker['on' + directionText]) {
            async.waterfall([
                function(callback) {
                    floorWorker['on' + directionText](parameters, function(error) {
                        if(error) {
                            logger.error('>>>> Stuck at floor ' + floor.getLongName());
                        } else {
                            logger.info('>>>> Migrating ' + directionText.toLowerCase() + ' floor: ' + floor.getLongName());
                        }
                        return callback(error);
                    });
                },
                function(callback) {
                    levelController.saveCurrentLevel(Level.create(floor.identifier), function(error) {
                        if(error) {
                            logger.error('>>>> Stuck at floor ' + floor.identifier + '. Failed to store the current level');
                        }
                        return callback(error);
                    });
                }
            ], function(error) {
                return callback(error);
            })
        } else {
            return callback(Errors.generalError('>>>> Invalid floor ' + floor.filePath));
        }
    }, function(error) {
        return callback(error);
    })
}

/**
 * Move elevator
 * @param config
 * @param floor
 * @param logger
 * @param LevelController - Class derived from BaseLevelController to do custom storage for current level
 * @param callback(error)
 */
ElevatorEngine.move = function(config, floor, logger, LevelController, callback) {
    var self = this;

    //Validate arguments
    if(!config) {
        return callback(Errors.invalidArgument('config', 'Object'));
    }

    if(floor === undefined || floor === null) {
        return callback(Errors.invalidArgument('floor', 'number'));
    }

    if(!LevelController) {
        return callback(Errors.generalError("Invalid argument 'LevelController' should be a class derived from 'BaseLevelController'"));
    }

    var levelController = null;

    try{
        levelController = new LevelController(config);
    } catch(error) {
       return callback(error);
    }

    if(levelController) {
        async.waterfall([
            //Get the current migration status
            function(callback) {
                levelController.retrieveCurrentLevel(function(error, level) {
                    return callback(error, level);
                 })
            },
            //Get the migration files that need to be applied
            function(level, callback) {
                _getFloors(config, level, floor, function(error, floors, options) {
                    return callback(error, floors, options);
                })
            },
            //Migrate the files
            function(floors, options, callback) {
                if(floors != null && floors.length > 0) {
                   _moveElevator(config, floors, options.ascending, logger, levelController, function(error) {
                        return callback(error, floors, options);
                    });
                } else {
                    return callback(null, null, null);
                }
            },
             //Save the last level if going down, because the last level is not stored yet
            function(floors, options, callback) {
                if(floors && options && options.ascending === false) {
                    levelController.saveCurrentLevel(Level.create(options.identifierRange.min), function(error) {
                        if(error) {
                            logger.error('>>>> Stuck at floor ' + options.identifierRange.min + '. Failed to store the current level.');
                        }
                        return callback(error);
                    });
                } else {
                    return callback(null);
                }
            }
        ], function(error) {
            return callback(error);
        })
    } else {
        return callback(Errors.generalError("Invalid argument 'LevelController' should be a class derived from 'BaseLevelController'"));
    }
}

/**
 * Print the status of the elevator to the logger
 * @param config
 * @param logger
 * @param LevelController
 * @param callback(error)
 */
ElevatorEngine.printStatus = function(config, logger, LevelController, callback) {
    if(!LevelController) {
        return callback(Errors.generalError("Invalid argument 'LevelController' should be a class derived from 'BaseLevelController'"));
    }

    var levelController = new LevelController(config);

    levelController.retrieveCurrentLevel(function(error, level) {
        if(error) {
            logger.error('Failed to load elevator info.', error);
        } else if(level) {
            var date = new Date(level.timestamp);
            logger.info('Currently on floor: ' + level.identifier + '. Last movement: ' + date.toLocaleString() + ".");
        } else {
            logger.info('Elevator has not yet moved.');
        }
        return callback(error);
    })
}

/**
 * Print the status of the elevator to the logger
 * @param config
 * @param logger
 * @param LevelController
 * @param callback(error)
 */
ElevatorEngine.printList = function(config, logger, LevelController, callback) {
    if(!LevelController) {
        return callback(Errors.generalError("Invalid argument 'LevelController' should be a class derived from 'BaseLevelController'"));
    }

    var levelController = new LevelController(config);

    levelController.retrieveCurrentLevel(function(error, level) {
        if(!error) {
            if(!level || level.identifier == 0) {
                logger.info( ">> Floor: 0 - Ground floor");
            } else {
                logger.info( "   Floor: 0 - Ground floor");
            }

            _getFloors(config, null, null, function(error, floors, options) {
                if(!error) {
                    if(floors) {
                        floors.forEach(function(floor) {
                            if(level && level.identifier == floor.identifier) {
                                logger.info( ">> Floor: " + floor.getLongName());
                            } else {
                                logger.info( "   Floor: " + floor.getLongName());
                            }
                        });
                        return callback(null);
                    } else {
                        logger.info( "No floors available");
                        return callback(null);
                    }
                } else {
                    logger.error('Failed to load floors.', error);
                    return callback(error);
                }
            });
        } else {
             logger.error('Failed to load elevator info.', error);
             return callback(error);
        }
    });
}

module.exports = {
    ElevatorEngine: ElevatorEngine,
};<|endoftext|>


<commit_before>module.exports = {
  name: '英語',
  key: 'ja',
  'Open in Debug Map': 'デバッグされた地図で開く',
  'Open in Mapillary': 'Mapilaryで開く',
  'GPX': 'ファイルを出力する',
  'Open in editor': '編集モードで開く',
  'Open in JOSM': 'JOSMで開く',
  'Select language': '言語を選択',
  'Start - press enter to drop marker': '出発地 – ピンを置くにはEnterを押して下さい',
  'End - press enter to drop marker': '目的地-ピンを置くにはEnterを押して下さい ',
  'Via point - press enter to drop marker': '経由地 -ピンを置くにはEnterを押して下さい'
};
<commit_msg>Fix the Japanese localization<commit_after>module.exports = {
  name: '日本語',
  key: 'ja',
  'Open in Debug Map': 'デバッグ地図で開く',
  'Open in Mapillary': 'Mapillaryで開く',
  'GPX': 'ファイルを出力する',
  'Open in editor': '編集モードで開く',
  'Open in JOSM': 'JOSMで開く',
  'Select language': '言語を選択',
  'Start - press enter to drop marker': '出発地 – ピンを置くにはEnterを押して下さい',
  'End - press enter to drop marker': '目的地 - ピンを置くにはEnterを押して下さい',
  'Via point - press enter to drop marker': '経由地 - ピンを置くにはEnterを押してください'
};
<|endoftext|>


<commit_before>mini.Module(
	"engine/rendering/animationsheet"
)
.requires(
	"engine/rendering/image"
)
.defines(function(Image) {
	var AnimationSheet = mini.Class.subclass({
		initialize: function(path, frameWidth, frameHeight) {
			this.image = Image.get(path);
			this.frameWidth = frameWidth;
			this.frameHeight = frameHeight;
		},

		draw: function(aabb, tileNumber) {
			var tilesPerRow = Math.floor(this.image.data.width / this.frameWidth);
			var sourceX = this.frameWidth * (tileNumber % tilesPerRow);
			var sourceY = this.frameHeight * Math.floor(tileNumber / tilesPerRow);
			this.image.draw(
				aabb,
				sourceX,
				sourceY,
				this.frameWidth,
				this.frameHeight
			);
		}
	});

	AnimationSheet.prototype.toJson = function() {
		var json = {
			imagePath: this.image.path,
			frameWidth: this.frameWidth,
			frameHeight: this.frameHeight
		};

		return json;
	};

	AnimationSheet.fromJson = function(json) {
		var animationSheet = new AnimationSheet(json.path, json.frameWidth, json.frameHeight);

		return animationSheet;
	};

	return AnimationSheet;
});
<commit_msg>changed parameter name when reading a json<commit_after>mini.Module(
	"engine/rendering/animationsheet"
)
.requires(
	"engine/rendering/image"
)
.defines(function(Image) {
	var AnimationSheet = mini.Class.subclass({
		initialize: function(path, frameWidth, frameHeight) {
			this.image = Image.get(path);
			this.frameWidth = frameWidth;
			this.frameHeight = frameHeight;
		},

		draw: function(aabb, tileNumber) {
			var tilesPerRow = Math.floor(this.image.data.width / this.frameWidth);
			var sourceX = this.frameWidth * (tileNumber % tilesPerRow);
			var sourceY = this.frameHeight * Math.floor(tileNumber / tilesPerRow);
			this.image.draw(
				aabb,
				sourceX,
				sourceY,
				this.frameWidth,
				this.frameHeight
			);
		}
	});

	AnimationSheet.prototype.toJson = function() {
		var json = {
			imagePath: this.image.path,
			frameWidth: this.frameWidth,
			frameHeight: this.frameHeight
		};

		return json;
	};

	AnimationSheet.fromJson = function(json) {
		var animationSheet = new AnimationSheet(json.imagePath, json.frameWidth, json.frameHeight);

		return animationSheet;
	};

	return AnimationSheet;
});
<|endoftext|>


<commit_before>/*!
 * @jQuery TimezZ: Plugin for countdown and count forward
 *
 * @Contribute: https://github.com/BrooonS/TimezZ
 *
 * @license: MIT license: http://opensource.org/licenses/MIT
 */

jQuery(function($) {

  $.fn.timezz = function( options ) {

    var settings = $.extend({
      'date' : 'January 1, 2040 00:00:00',
      'days' : 'd',
      'hours' : 'h',
      'minutes' : 'm',
      'seconds' : 's',
      'tagNumber' : 'span',
      'tagLetter' : 'i'
    }, options);

    return this.each(function() {

      var ths = $(this);

      var countDownDate = new Date(settings.date).getTime();

      setInterval(function() {

        var now = new Date().getTime(),
            distance = countDownDate - now;

        var days = "<" + settings.tagNumber + ">" + Math.floor(Math.abs(distance / (1000 * 60 * 60 * 24))) + "</" + settings.tagNumber + ">",
            hours = "<" + settings.tagNumber + ">" + Math.floor((Math.abs(distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))) + "</" + settings.tagNumber + ">",
            minutes = "<" + settings.tagNumber + ">" + Math.floor((Math.abs(distance % (1000 * 60 * 60)) / (1000 * 60))) + "</" + settings.tagNumber + ">",
            seconds = "<" + settings.tagNumber + ">" + Math.floor((Math.abs(distance % (1000 * 60)) / 1000)) + "</" + settings.tagNumber + ">";

        ths.html(
          days + "<" + settings.tagLetter + ">" + settings.days + "</" + settings.tagLetter + "> " +
          hours + "<" + settings.tagLetter + ">" + settings.hours + "</" + settings.tagLetter + "> " +
          minutes + "<" + settings.tagLetter + ">" + settings.minutes + "</" + settings.tagLetter + "> " +
          seconds + "<" + settings.tagLetter + ">" + settings.seconds + "</" + settings.tagLetter + "> "
        );

      }, 1000);

    });

  };
});<commit_msg>changed: tag in tag<commit_after>/*!
 * @jQuery TimezZ: Plugin for countdown and count forward
 *
 * @Contribute: https://github.com/BrooonS/TimezZ
 *
 * @license: MIT license: http://opensource.org/licenses/MIT
 */

jQuery(function($) {

  $.fn.timezz = function( options ) {

    var settings = $.extend({
      'date' : 'January 1, 2040 00:00:00',
      'days' : 'd',
      'hours' : 'h',
      'minutes' : 'm',
      'seconds' : 's',
      'tagNumber' : 'span',
      'tagLetter' : 'i'
    }, options);

    return this.each(function() {

      var ths = $(this);

      var countDownDate = new Date(settings.date).getTime();

      setInterval(function() {

        var now = new Date().getTime(),
            distance = countDownDate - now;

        var days = "<" + settings.tagNumber + ">" + Math.floor(Math.abs(distance / (1000 * 60 * 60 * 24))),
            hours = "<" + settings.tagNumber + ">" + Math.floor((Math.abs(distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))),
            minutes = "<" + settings.tagNumber + ">" + Math.floor((Math.abs(distance % (1000 * 60 * 60)) / (1000 * 60))),
            seconds = "<" + settings.tagNumber + ">" + Math.floor((Math.abs(distance % (1000 * 60)) / 1000));

        ths.html(
          days + "<" + settings.tagLetter + ">" + settings.days + "</" + settings.tagLetter + "> " + "</" + settings.tagNumber + ">" +
          hours + "<" + settings.tagLetter + ">" + settings.hours + "</" + settings.tagLetter + "> " + "</" + settings.tagNumber + ">" +
          minutes + "<" + settings.tagLetter + ">" + settings.minutes + "</" + settings.tagLetter + "> " + "</" + settings.tagNumber + ">" +
          seconds + "<" + settings.tagLetter + ">" + settings.seconds + "</" + settings.tagLetter + "> " + "</" + settings.tagNumber + ">"
        );

      }, 1000);

    });

  };
});<|endoftext|>


<commit_before>
import Component from 'can-component';
import CanEvent from 'can-event';
import DefineMap from 'can-define/map/map';
import assign from 'can-util/js/assign/assign';
import canViewModel from 'can-view-model';

import 'spectre-canjs/modal-dialog/';
import template from './olPopup.stache!';
import './olPopup.less!';

/**
 * @constructor ol-popup.ViewModel ViewModel
 * @parent ol-popup
 * @group ol-popup.ViewModel.props Properties
 *
 * @description A `<ol-popup />` component's ViewModel
 */
export const ViewModel = DefineMap.extend({
  /**
   * @prototype
   */
    /**
     * Whether or not the current state of this popup should be a modal dialog instead of a map overlay popup. This can be changed dynamically
     * @property {Boolean} ol-popup.ViewModel.props.modal
     * @parent ol-popup.ViewModel.props
     */
    modal: {
        type: 'htmlbool',
        value: false
    },
    x: {
        type: 'number',
        set (x) {
            this.showPopupAsync();
            return x;
        }
    },
    y: {
        type: 'number',
        set (y) {
            this.showPopupAsync();
            return y;
        }
    },
    active: {
        type: 'htmlbool',
        set (active) {
            if (!active) {
                this.hidePopup();
            }
            return active;
        }
    },
    overlay: {
        type: '*'
    },
    overlayElement: {
        type: '*',
        set (element) {
            this.overlay = new ol.Overlay({
                element: element,
                autoPan: true,
                autoPanAnimation: {
                    duration: 250
                }
            });
            return element;
        }
    },
    map: {
        type: '*',
        set (map) {
            if (!map) {
                return map;
            }
            map.addOverlay(this.overlay);
            map.on('click', (event) => {
                // this.showPopup(event.coordinate);
                this.set({
                    x: event.coordinate[0],
                    y: event.coordinate[1]
                });
            });
            return map;
        }
    },
    isSettingAsync: 'boolean',
  /**
   * @typedef {can.Event} ol-popup.events.popupShow show
   * An event dispatched when the popup is shown
   * @parent ol-popup.events
   * @option {Array<Number>} coordinate The coordinate in which the popup is shown
   */
  /**
   * Displays and centers this popup on a coordinate, and dispatches the `show` event
   * @param  {Array<Number>} coordinate The x,y pair to center the popup on
   */
    showPopup (coordinate) {
        if (!this.active || this.modal) {
            return;
        }
        if (!this.modal) {
            this.overlay.setPosition(coordinate);
        }
        this.dispatch('show', [coordinate]);
    },
    showPopupAsync () {
        return new Promise((resolve) => {
            if (!this.isSettingAsync) {
                this.isSettingAsync = true;
                setTimeout(() => {
                    this.showPopup([this.x, this.y]);
                    this.isSettingAsync = false;
                    resolve(true);
                }, 100);
            } else {
                resolve(false);
            }

        });
    },
    hidePopup () {
        this.overlay.setPosition(undefined);
    }
});

assign(ViewModel.prototype, CanEvent);

export default Component.extend({
    tag: 'ol-popup',
    view: template,
    viewModel: ViewModel,
    leakScope: true,
    events: {
        inserted () {
            var mapViewModel = canViewModel(this.element.parentNode);
            this.viewModel.set({
                overlayElement: this.element.querySelector('.ol-popup'),
                map: mapViewModel.mapObject
            });
        },
        removed () {
        }
    }
});
<commit_msg>allow showPopupAsync to accept a coordinate<commit_after>
import Component from 'can-component';
import CanEvent from 'can-event';
import DefineMap from 'can-define/map/map';
import assign from 'can-util/js/assign/assign';
import canViewModel from 'can-view-model';

import 'spectre-canjs/modal-dialog/';
import template from './olPopup.stache!';
import './olPopup.less!';

/**
 * @constructor ol-popup.ViewModel ViewModel
 * @parent ol-popup
 * @group ol-popup.ViewModel.props Properties
 *
 * @description A `<ol-popup />` component's ViewModel
 */
export const ViewModel = DefineMap.extend({
  /**
   * @prototype
   */
    /**
     * Whether or not the current state of this popup should be a modal dialog instead of a map overlay popup. This can be changed dynamically
     * @property {Boolean} ol-popup.ViewModel.props.modal
     * @parent ol-popup.ViewModel.props
     */
    modal: {
        type: 'htmlbool',
        value: false
    },
    x: {
        type: 'number',
        set (x) {
            this.showPopupAsync();
            return x;
        }
    },
    y: {
        type: 'number',
        set (y) {
            this.showPopupAsync();
            return y;
        }
    },
    active: {
        type: 'htmlbool',
        set (active) {
            if (!active) {
                this.hidePopup();
            }
            return active;
        }
    },
    overlay: {
        type: '*'
    },
    overlayElement: {
        type: '*',
        set (element) {
            this.overlay = new ol.Overlay({
                element: element,
                autoPan: true,
                autoPanAnimation: {
                    duration: 250
                }
            });
            return element;
        }
    },
    map: {
        type: '*',
        set (map) {
            if (!map) {
                return map;
            }
            map.addOverlay(this.overlay);
            map.on('click', (event) => {
                // this.showPopup(event.coordinate);
                this.set({
                    x: event.coordinate[0],
                    y: event.coordinate[1]
                });
            });
            return map;
        }
    },
    isSettingAsync: 'boolean',
  /**
   * @typedef {can.Event} ol-popup.events.popupShow show
   * An event dispatched when the popup is shown
   * @parent ol-popup.events
   * @option {Array<Number>} coordinate The coordinate in which the popup is shown
   */
  /**
   * Displays and centers this popup on a coordinate, and dispatches the `show` event
   * @param  {Array<Number>} coordinate The x,y pair to center the popup on
   */
    showPopup (coordinate) {
        if (!this.active || this.modal) {
            return;
        }
        if (!this.modal) {
            this.overlay.setPosition(coordinate);
        }
        this.dispatch('show', [coordinate]);
    },
    showPopupAsync (coordinate) {
        return new Promise((resolve) => {
            if (!this.isSettingAsync) {
                this.isSettingAsync = true;
                setTimeout(() => {
                    if (!coordinate) {
                        coordinate = [this.x, this.y];
                    }
                    this.showPopup(coordinate);
                    this.isSettingAsync = false;
                    resolve(true);
                });
            } else {
                resolve(false);
            }

        });
    },
    hidePopup () {
        this.overlay.setPosition(undefined);
    }
});

assign(ViewModel.prototype, CanEvent);

export default Component.extend({
    tag: 'ol-popup',
    view: template,
    viewModel: ViewModel,
    leakScope: true,
    events: {
        inserted () {
            var mapViewModel = canViewModel(this.element.parentNode);
            this.viewModel.set({
                overlayElement: this.element.querySelector('.ol-popup'),
                map: mapViewModel.mapObject
            });
        },
        removed () {
        }
    }
});
<|endoftext|>


<commit_before>( function( $ ){
	var methods = {
		settings: function ( options ) {
			//Fetch library's settings object.
			var settings = accounting.settings;

			//Merge in our new options
			settings = $.extend(settings, options);

			//Update library's settings object.
			accounting.settings = settings;

			//Keep the jQuery chain going.
			return this;
		},
		formatMoney: function( options ) {
			return this.each(function() {
				$this = $(this);

				//Get value for processing.
				var value = $this.html();

				//Format the value.
				var formatted = accounting.formatMoney(value, options);

				//Apply the formatted value to the element.
				$this.html(formatted);
			});
		},
		formatColumn: function( options ) {
			var column = new Array();

			//Collect our values into an array to pass to formatColumn().
			this.each(function() {
				var $this = $(this);
				column.push($this.html());
			});

			//Send it off for formatting.
			var formattedColumn = accounting.formatColumn(column, options);

			//Now set the element's values.
			return this.each(function(i) {
				var $this = $(this);
				var value = formattedColumn[i];
				$this.html(value);
			});
		},
		formatNumber: function( options ) {
			return this.each(function() {
				$this = $(this);

				//Get value for processing
				var value = $this.html();

				//Format the value
				var formatted = accounting.formatNumber(value, options);

				//Apply the formatted value to the element
				$this.html(formatted);
			});
		},
		toFixed: function( precision ) {
			return this.each(function() {
				$this = $(this);

				//Get value for processing.
				var value = $this.html();

				//Format the value.
				var formatted = accounting.toFixed(value, precision);

				//Apply the formatted value to the element.
				$this.html(formatted);
			});
		},
		unformat: function( decimal ) {
			return this.each(function() {
				$this = $(this);

				//Get value for processing.
				var value = $this.html();

				//Format the value.
				var formatted = accounting.unformat(value, decimal);

				//Apply the formatted value to the element.
				$this.html(formatted);
			});
		}
	};

	$.fn.accounting = function( method ) {
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.settings.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.accounting' );
		}
	};
})( jQuery );
<commit_msg>Setting the settings now no longer overwrites other settings.  This should set the jQuery wrapper to be ready to ship.<commit_after>( function( $ ){
	var methods = {
		settings: function ( options ) {
			//Fetch library's settings object.
			var settings = accounting.settings;

			//Merge in our new options
			settings = $.extend(true, settings, options);

			//Update library's settings object.
			accounting.settings = settings;

			//Keep the jQuery chain going.
			return this;
		},
		formatMoney: function( options ) {
			return this.each(function() {
				$this = $(this);

				//Get value for processing.
				var value = $this.html();

				//Format the value.
				var formatted = accounting.formatMoney(value, options);

				//Apply the formatted value to the element.
				$this.html(formatted);
			});
		},
		formatColumn: function( options ) {
			var column = new Array();

			//Collect our values into an array to pass to formatColumn().
			this.each(function() {
				var $this = $(this);
				column.push($this.html());
			});

			//Send it off for formatting.
			var formattedColumn = accounting.formatColumn(column, options);

			//Now set the element's values.
			return this.each(function(i) {
				var $this = $(this);
				var value = formattedColumn[i];
				$this.html(value);
			});
		},
		formatNumber: function( options ) {
			return this.each(function() {
				$this = $(this);

				//Get value for processing
				var value = $this.html();

				//Format the value
				var formatted = accounting.formatNumber(value, options);

				//Apply the formatted value to the element
				$this.html(formatted);
			});
		},
		toFixed: function( precision ) {
			return this.each(function() {
				$this = $(this);

				//Get value for processing.
				var value = $this.html();

				//Format the value.
				var formatted = accounting.toFixed(value, precision);

				//Apply the formatted value to the element.
				$this.html(formatted);
			});
		},
		unformat: function( decimal ) {
			return this.each(function() {
				$this = $(this);

				//Get value for processing.
				var value = $this.html();

				//Format the value.
				var formatted = accounting.unformat(value, decimal);

				//Apply the formatted value to the element.
				$this.html(formatted);
			});
		}
	};

	$.fn.accounting = function( method ) {
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.settings.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.accounting' );
		}
	};
})( jQuery );
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import {push} from 'react-router-redux'
import {connect} from 'react-redux'

import NotYetOpenPage from '../components/ready/NotYetOpenPage'
import ReviewList from '../components/review/ReviewList'
import TalkAbout from '../components/TalkAbout'
import ReadyUsers from '../components/ReadyUsers'
import ReadySwitch from '../components/ready/ReadySwitch'
import TimeToChoose from '../components/ready/TimeToChoose'
import NotYetInOperation from '../components/NotYetInOperation'
import NotSupportedBrowser from '../components/ready/NotSupportedBrowser'

class ReadyPageRaw extends React.Component {

  static propTypes = {
    push: PropTypes.func.isRequired,
    user: PropTypes.object,
    online: PropTypes.object
  }

  render () {
    const {user: {profile: {role} = {}} = {}} = this.props

    return (

        <TimeToChoose />
        <NotSupportedBrowser />
        <NotYetInOperation />

        {role === 'student' ? (
          <ReadySwitch />
        ) : undefined}

        {role === 'teacher' ? (
          <ReadyUsers />
        ) : undefined}

        <ReviewList />
        <TalkAbout />

    )
  }
}

const ReadyPage = connect((state, props) => {
  const {live: {online}, profile: {profile: user}} = state
  return {online, user}
}, {push})(ReadyPageRaw)

class ReadyOrNotYetOpen extends Component {
  static propTypes = {
    accepted: PropTypes.bool
  }

  render () {
    // if (this.props.accepted) return <ReadyPage />
    // return <NotYetOpenPage />
    return <ReadyPage />
  }
}

export default connect((state) => {
  const {notYetOpen: {accepted}} = state
  return {accepted}
})(ReadyOrNotYetOpen)
<commit_msg>Delete newsletter banner<commit_after>import React, {Component, PropTypes} from 'react'
import {push} from 'react-router-redux'
import {connect} from 'react-redux'

import NotYetOpenPage from '../components/ready/NotYetOpenPage'
import ReviewList from '../components/review/ReviewList'
import TalkAbout from '../components/TalkAbout'
import ReadyUsers from '../components/ReadyUsers'
import ReadySwitch from '../components/ready/ReadySwitch'
import TimeToChoose from '../components/ready/TimeToChoose'
// import NotYetInOperation from '../components/NotYetInOperation'
import NotSupportedBrowser from '../components/ready/NotSupportedBrowser'

class ReadyPageRaw extends React.Component {

  static propTypes = {
    push: PropTypes.func.isRequired,
    user: PropTypes.object,
    online: PropTypes.object
  }

  render () {
    const {user: {profile: {role} = {}} = {}} = this.props

    return (

        <TimeToChoose />
        <NotSupportedBrowser />

        {role === 'student' ? (
          <ReadySwitch />
        ) : undefined}

        {role === 'teacher' ? (
          <ReadyUsers />
        ) : undefined}

        <ReviewList />
        <TalkAbout />

    )
  }
}

const ReadyPage = connect((state, props) => {
  const {live: {online}, profile: {profile: user}} = state
  return {online, user}
}, {push})(ReadyPageRaw)

class ReadyOrNotYetOpen extends Component {
  static propTypes = {
    accepted: PropTypes.bool
  }

  render () {
    // if (this.props.accepted) return <ReadyPage />
    // return <NotYetOpenPage />
    return <ReadyPage />
  }
}

export default connect((state) => {
  const {notYetOpen: {accepted}} = state
  return {accepted}
})(ReadyOrNotYetOpen)
<|endoftext|>


<commit_before>'use strict'

window.Darwinator.GeneticAlgorithm = window.Darwinator.GeneticAlgorithm || {

  POPULATION_SIZE:          100,
  NUMBER_OF_GENES:          60,
  CROSSOVER_PROBABILITY:    0.8,
  MUTATION_PROBABILITY:     0.025,
  TOURNAMENT_PARAMETER:     0.75,
  VARIABLE_RANGE:           5.0,       // Might not need later?
  NUMBER_OF_GENERATIONS:    100,
  NUMBER_OF_VARIABLES:      2,
  TOURNAMENT_SIZE:          4,
  ELITISM_DEGREE:           1,

  generatePopulation: function(goalFunction, population, singleGeneration) {
    population = population || this.initPopulation();
    var fitnessLevels = new Array(this.POPULATION_SIZE);
    var totalMaxFit = 0.0;
    var n = 0;

    for (var i = 0; i < (singleGeneration ? 1 : this.NUMBER_OF_GENERATIONS); i++) {

      var maxFit = 0.0;
      var bestIndividual = population[0];

      for(var l = 0; l < population.length; l++) {
        var decodedInd = this.decodeIndividual(population[l]);
        fitnessLevels[l] = this.evaluateInd(decodedInd);
        if(fitnessLevels[l] > maxFit) {
          maxFit = fitnessLevels[l];
          bestIndividual = population[l];
          if (maxFit > totalMaxFit) {
            totalMaxFit = maxFit;
          }
        }
      }

      var tmpPopulation = new Array(population.length);
      for (l = 0; l < tmpPopulation.length; l++) {
        tmpPopulation[l] = new Array(population[l].length);
        for(var j = 0; j < population[l].length; j++) {
          tmpPopulation[l][j] = population[l][j];
        }
      }

      for(l = 0; l < population.length; l += 2) {
        var ind1 = this.selection(fitnessLevels);
        var ind2 = this.selection(fitnessLevels);
        if (Math.random() < this.CROSSOVER_PROBABILITY) {
          var chromePair = this.cross(population[ind1], population[ind2]);
          tmpPopulation[l] = chromePair[0];
          tmpPopulation[l + 1] = chromePair[1];
        } else {
          tmpPopulation[l] = population[ind1];
          tmpPopulation[l + 1] = population[ind2];
        }
      }

      for(l = 0; l < population.length; l++) {
        tmpPopulation[l] = this.mutate(tmpPopulation[l]);
        n++;
      }

      for(l = 0; l < this.ELITISM_DEGREE; l++) {
        tmpPopulation[l] = bestIndividual;
      }
      population = tmpPopulation;
    }

    console.log(1/maxFit);
    console.log(this.decodeIndividual(bestIndividual));
    //return tmpPopulation;
  },

  initPopulation: function() {
    var population = [];
    for(var i = 0; i < this.POPULATION_SIZE; i++) {
      population[i] = [];
      for(var l = 0; l < this.NUMBER_OF_GENES; l++) {
        population[i][l] = Math.round(Math.random());
      }
    }

    return population;
  },

  decodeIndividual: function(individual) {
    var bitsPerVar = this.NUMBER_OF_GENES / this.NUMBER_OF_VARIABLES;
    var decoded = [];

    for(var i = 1; i <= this.NUMBER_OF_VARIABLES; i++) {
      decoded[i - 1] = 0;
      for(var l = 1; l <= bitsPerVar; l++) {

        var startVar = (i-1) * bitsPerVar;
        decoded[i-1] = decoded[i-1] + individual[startVar + l - 1] * Math.pow(2, -l);
      }
      decoded[i-1] = -this.VARIABLE_RANGE + 2 * this.VARIABLE_RANGE * decoded[i-1]/(1 - Math.pow(2,-bitsPerVar));
    }

    return decoded;
  },

  cross: function(firstInd, secondInd) {
    var crossPoint = Math.round(Math.random()*this.NUMBER_OF_GENES - 1);
    var newInd1 = [];
    var newInd2 = [];

    for(var i = 0; i < this.NUMBER_OF_GENES; i++) {
      if (i < crossPoint) {
        newInd1[i] = firstInd[i];
        newInd2[i] = secondInd[i];
      } else {
        newInd2[i] = firstInd[i];
        newInd1[i] = secondInd[i];
      }
    }

    return [newInd1, newInd2];
  },

  selection: function(fitnessLevels) {
    var tournamentParticipants = new Array(this.TOURNAMENT_SIZE);

    for (var i = 0; i < this.TOURNAMENT_SIZE; i++) {
      tournamentParticipants[i] = new Array(2);
      tournamentParticipants[i][0] = Math.round(Math.random() * (this.POPULATION_SIZE - 1));
      tournamentParticipants[i][1] = fitnessLevels[tournamentParticipants[i][0]];
    }

    /* Sort by fitness levels */
    tournamentParticipants.sort(function(a,b){return b[1]-a[1]});

    for(i = 0; i < this.TOURNAMENT_SIZE; i++) {
      if (Math.random() < this.TOURNAMENT_PARAMETER) {
        return tournamentParticipants[i][0];
      }
    }

    return tournamentParticipants[i - 1][0];
  },

  mutate: function(individual) {
    for (var i = 0; i < this.NUMBER_OF_GENES; i++) {
      if (Math.random() < this.MUTATION_PROBABILITY) {
        individual[i] = 1 - individual[i];
      }
    }
    return individual;
  },

  evaluateInd: function(ind) {
    return (1 / this.exampleFunction(ind));
  },

  exampleFunction: function(ind) {
    var x = ind[0];
    var y = ind[1];
    return (1 + Math.pow((x + y + 1), 2) * (19 - 14 * x + 3 *
            Math.pow(x, 2) - 14 * y + 6 * x * y + 3 * Math.pow(y, 2))) *
    (30 + Math.pow((2*x - 3*y), 2) * (18 - 32 * x + 12 *
            Math.pow(x, 2) + 48 * y - 36 * x + 27 * Math.pow(y, 2)));
  }

};<commit_msg>Remove unused debugging-code and prints<commit_after>'use strict'

window.Darwinator.GeneticAlgorithm = window.Darwinator.GeneticAlgorithm || {

  POPULATION_SIZE:          100,
  NUMBER_OF_GENES:          60,
  CROSSOVER_PROBABILITY:    0.8,
  MUTATION_PROBABILITY:     0.025,
  TOURNAMENT_PARAMETER:     0.75,
  VARIABLE_RANGE:           5.0,       // Might not need later?
  NUMBER_OF_GENERATIONS:    100,
  NUMBER_OF_VARIABLES:      2,
  TOURNAMENT_SIZE:          4,
  ELITISM_DEGREE:           1,

  generatePopulation: function(goalFunction, population, singleGeneration) {
    population = population || this.initPopulation();
    var fitnessLevels = new Array(this.POPULATION_SIZE);
    var totalMaxFit = 0.0;

    for (var i = 0; i < (singleGeneration ? 1 : this.NUMBER_OF_GENERATIONS); i++) {

      var maxFit = 0.0;
      var bestIndividual = population[0];

      for(var l = 0; l < population.length; l++) {
        var decodedInd = this.decodeIndividual(population[l]);
        fitnessLevels[l] = this.evaluateInd(decodedInd);
        if(fitnessLevels[l] > maxFit) {
          maxFit = fitnessLevels[l];
          bestIndividual = population[l];
          if (maxFit > totalMaxFit) {
            totalMaxFit = maxFit;
          }
        }
      }

      var tmpPopulation = new Array(population.length);
      for (l = 0; l < tmpPopulation.length; l++) {
        tmpPopulation[l] = new Array(population[l].length);
        for(var j = 0; j < population[l].length; j++) {
          tmpPopulation[l][j] = population[l][j];
        }
      }

      for(l = 0; l < population.length; l += 2) {
        var ind1 = this.selection(fitnessLevels);
        var ind2 = this.selection(fitnessLevels);
        if (Math.random() < this.CROSSOVER_PROBABILITY) {
          var chromePair = this.cross(population[ind1], population[ind2]);
          tmpPopulation[l] = chromePair[0];
          tmpPopulation[l + 1] = chromePair[1];
        } else {
          tmpPopulation[l] = population[ind1];
          tmpPopulation[l + 1] = population[ind2];
        }
      }

      for(l = 0; l < population.length; l++) {
        tmpPopulation[l] = this.mutate(tmpPopulation[l]);
      }

      for(l = 0; l < this.ELITISM_DEGREE; l++) {
        tmpPopulation[l] = bestIndividual;
      }
      population = tmpPopulation;
    }

    console.log(1/maxFit);
    console.log(this.decodeIndividual(bestIndividual));
    return population;
  },

  initPopulation: function() {
    var population = [];
    for(var i = 0; i < this.POPULATION_SIZE; i++) {
      population[i] = [];
      for(var l = 0; l < this.NUMBER_OF_GENES; l++) {
        population[i][l] = Math.round(Math.random());
      }
    }

    return population;
  },

  decodeIndividual: function(individual) {
    var bitsPerVar = this.NUMBER_OF_GENES / this.NUMBER_OF_VARIABLES;
    var decoded = [];

    for(var i = 1; i <= this.NUMBER_OF_VARIABLES; i++) {
      decoded[i - 1] = 0;
      for(var l = 1; l <= bitsPerVar; l++) {

        var startVar = (i-1) * bitsPerVar;
        decoded[i-1] = decoded[i-1] + individual[startVar + l - 1] * Math.pow(2, -l);
      }
      decoded[i-1] = -this.VARIABLE_RANGE + 2 * this.VARIABLE_RANGE * decoded[i-1]/(1 - Math.pow(2,-bitsPerVar));
    }

    return decoded;
  },

  cross: function(firstInd, secondInd) {
    var crossPoint = Math.round(Math.random()*this.NUMBER_OF_GENES - 1);
    var newInd1 = [];
    var newInd2 = [];

    for(var i = 0; i < this.NUMBER_OF_GENES; i++) {
      if (i < crossPoint) {
        newInd1[i] = firstInd[i];
        newInd2[i] = secondInd[i];
      } else {
        newInd2[i] = firstInd[i];
        newInd1[i] = secondInd[i];
      }
    }

    return [newInd1, newInd2];
  },

  selection: function(fitnessLevels) {
    var tournamentParticipants = new Array(this.TOURNAMENT_SIZE);

    for (var i = 0; i < this.TOURNAMENT_SIZE; i++) {
      tournamentParticipants[i] = new Array(2);
      tournamentParticipants[i][0] = Math.round(Math.random() * (this.POPULATION_SIZE - 1));
      tournamentParticipants[i][1] = fitnessLevels[tournamentParticipants[i][0]];
    }

    /* Sort by fitness levels */
    tournamentParticipants.sort(function(a,b){return b[1]-a[1]});

    for(i = 0; i < this.TOURNAMENT_SIZE; i++) {
      if (Math.random() < this.TOURNAMENT_PARAMETER) {
        return tournamentParticipants[i][0];
      }
    }

    return tournamentParticipants[i - 1][0];
  },

  mutate: function(individual) {
    for (var i = 0; i < this.NUMBER_OF_GENES; i++) {
      if (Math.random() < this.MUTATION_PROBABILITY) {
        individual[i] = 1 - individual[i];
      }
    }
    return individual;
  },

  evaluateInd: function(ind) {
    return (1 / this.exampleFunction(ind));
  },

  exampleFunction: function(ind) {
    var x = ind[0];
    var y = ind[1];
    return (1 + Math.pow((x + y + 1), 2) * (19 - 14 * x + 3 *
            Math.pow(x, 2) - 14 * y + 6 * x * y + 3 * Math.pow(y, 2))) *
    (30 + Math.pow((2*x - 3*y), 2) * (18 - 32 * x + 12 *
            Math.pow(x, 2) + 48 * y - 36 * x + 27 * Math.pow(y, 2)));
  }

};<|endoftext|>