<commit_before>'use strict';
import React, { PropTypes } from 'react';
import c from 'classnames';
import { clone, findIndex } from 'lodash';

import { Modal, ModalHeader, ModalBody, ModalFooter } from './modal';

import { environment } from '../config';

let idCounter = 0;
const uniqueId = key => `${key}-${++idCounter}`;

class AssetsEditModal extends React.Component {
  constructor (props) {
    super(props);

    this.addProperty = this.addProperty.bind(this);
    this.renderProperties = this.renderProperties.bind(this);
    this.onSave = this.onSave.bind(this);
    this.onCloseClick = this.onCloseClick.bind(this);

    this.state = this.prepareState(props);
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.revealed && nextProps.revealed) {
      this.setState(this.prepareState(nextProps));
    }
  }

  prepareState (props) {
    const roadProperties = props.roadProps.data.properties;
    const propertyNames = Object.keys(roadProperties);

    return {
      vpromm: props.vpromm,
      properties: propertyNames.map(p => ({
        id: uniqueId('property'),
        key: p,
        value: roadProperties[p],
        valueOriginal: roadProperties[p],
        existing: true
      })).concat(this.getBaseProperty()),
      propertiesToRemove: []
    };
  }

  getBaseProperty () {
    return {
      id: uniqueId('property'),
      key: '',
      value: '',
      existing: false
    };
  }

  addProperty () {
    const properties = this.state.properties.concat(this.getBaseProperty());
    this.setState({properties});
  }

  removeProperty (id) {
    const field = this.state.properties.find(o => o.id === id);
    const properties = this.state.properties.filter(o => o.id !== id);
    let propertiesToRemove = this.state.propertiesToRemove;
    // Only properties that already should be removed from the DB.
    if (field.existing) {
      propertiesToRemove = propertiesToRemove.concat(field);
    }
    this.setState({properties, propertiesToRemove});
  }

  onValueChange (what, event) {
    this.setState({ [what]: event.target.value });
  }

  onPropertyChange (id, what, event) {
    let properties = clone(this.state.properties);
    const idx = findIndex(properties, ['id', id]);

    const val = event.target.value;
    properties[idx][what] = val;

    this.setState({ properties });
  }

  onCloseClick (e) {
    // Block while processing.
    if (this.props.roadPropsOp.processing) return;
    this.props.onCloseClick();
  }

  onSave () {
    const propertiesToAdd = this.state.properties.filter(property => !property.existing && property.key !== '');
    const propertiesToUpdate = this.state.properties.filter(property => property.existing && property.value !== property.valueOriginal);
    const propertiesToRemove = this.state.propertiesToRemove;
    const originalVpromm = this.props.vpromm;
    const newVpromm = this.state.vpromm;
    const diffVpromm = newVpromm !== originalVpromm;

    console.log('propertiesToAdd', propertiesToAdd);
    console.log('propertiesToUpdate', propertiesToUpdate);
    console.log('propertiesToRemove', propertiesToRemove);
    console.log('diffVpromm', diffVpromm);

    if (!propertiesToAdd.length && !propertiesToUpdate.length && !propertiesToRemove.length && !diffVpromm) {
      // Nothing to do. Just close.
      return this.props.onCloseClick();
    }

    const handleError = () => alert('An error occurred while saving. Please try again.');
    const handleSuccess = (data) => this.props.onCloseClick(data);

    return this.props.opOnRoadProperty(this.props.vpromm, {
      add: propertiesToAdd,
      replace: propertiesToUpdate,
      remove: propertiesToRemove
    })
      .then(result => {
        if (result.error) return handleError();
        if (diffVpromm) {
          return this.props.editRoad(originalVpromm, newVpromm)
            .then(result => result.error ? handleError() : handleSuccess({action: 'redirect', vpromm: newVpromm}));
        }
        return handleSuccess({action: 'refresh'});
      });
  }

  renderProperties ({id, key, value, existing}) {
    const newProperties = this.state.properties.filter(o => !o.existing).length;

    return existing ? (

            {key}

            <button type='button' className='fia-trash' title={'Delete property'} onClick={this.removeProperty.bind(this, id)}>Delete</button>

        <input type='text' id={id} name={id} className='form__control' value={value} onChange={this.onPropertyChange.bind(this, id, 'value')} />

    ) : (
      <fieldset className='form__fieldset' key={id}>

            <legend className='form__legend'>New Property</legend>

            <button type='button' className={c('fia-trash', {disabled: newProperties <= 1})} title={'Delete property'} onClick={this.removeProperty.bind(this, id)}>Delete</button>

            <label className='form__label' htmlFor={`key-${id}`}>Name
            <input type='text' id={`key-${id}`} name={`key-${id}`} className='form__control' value={key} onChange={this.onPropertyChange.bind(this, id, 'key')} />

            <label className='form__label' htmlFor={`value-${id}`}>Value
            <input type='text' id={`value-${id}`} name={`value-${id}`} className='form__control' value={value} onChange={this.onPropertyChange.bind(this, id, 'value')} />

      </fieldset>
    );
  }

  render () {
    const { processing } = this.props.roadPropsOp;

    return (
      <Modal
        id='assets-edit-modal'
        className='modal--medium'
        onCloseClick={this.onCloseClick}
        revealed={this.props.revealed} >

        <ModalHeader>

Edit attributes of {this.props.vpromm}

        </ModalHeader>
        <ModalBody>
          <form className={c('form', {disabled: processing})} disabled={processing}>

                VPRoMMS
                <input type='text' id='vpromm' name='vpromm' className='form__control' value={this.state.vpromm} onChange={this.onValueChange.bind(this, 'vpromm')} />

              {this.state.properties.map(this.renderProperties)}

                <button type='button' className='fea-plus' title='Add new file' onClick={this.addProperty}>New property</button>

          </form>
        </ModalBody>
        <ModalFooter>
          <button className={c('button button--primary-raised-light', {disabled: processing})} disabled={processing} type='button' onClick={this.onCloseClick}>Cancel</button>
          <button className={c('button button--primary-raised-light', {disabled: processing})} disabled={processing} type='submit' onClick={this.onSave}>Save</button>
        </ModalFooter>
      </Modal>
    );
  }
}

if (environment !== 'production') {
  AssetsEditModal.propTypes = {
    vpromm: PropTypes.string,
    revealed: PropTypes.bool,
    roadProps: PropTypes.object,
    roadPropsOp: PropTypes.object,
    onCloseClick: PropTypes.func,
    opOnRoadProperty: PropTypes.func,
    editRoad: PropTypes.func
  };
}

export default AssetsEditModal;
<commit_msg>Use async await to save attributes<commit_after>'use strict';
import React, { PropTypes } from 'react';
import c from 'classnames';
import { clone, findIndex } from 'lodash';

import { Modal, ModalHeader, ModalBody, ModalFooter } from './modal';

import { environment } from '../config';

let idCounter = 0;
const uniqueId = key => `${key}-${++idCounter}`;

class AssetsEditModal extends React.Component {
  constructor (props) {
    super(props);

    this.addProperty = this.addProperty.bind(this);
    this.renderProperties = this.renderProperties.bind(this);
    this.onSave = this.onSave.bind(this);
    this.onCloseClick = this.onCloseClick.bind(this);

    this.state = this.prepareState(props);
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.revealed && nextProps.revealed) {
      this.setState(this.prepareState(nextProps));
    }
  }

  prepareState (props) {
    const roadProperties = props.roadProps.data.properties;
    const propertyNames = Object.keys(roadProperties);

    return {
      vpromm: props.vpromm,
      properties: propertyNames.map(p => ({
        id: uniqueId('property'),
        key: p,
        value: roadProperties[p],
        valueOriginal: roadProperties[p],
        existing: true
      })).concat(this.getBaseProperty()),
      propertiesToRemove: []
    };
  }

  getBaseProperty () {
    return {
      id: uniqueId('property'),
      key: '',
      value: '',
      existing: false
    };
  }

  addProperty () {
    const properties = this.state.properties.concat(this.getBaseProperty());
    this.setState({properties});
  }

  removeProperty (id) {
    const field = this.state.properties.find(o => o.id === id);
    const properties = this.state.properties.filter(o => o.id !== id);
    let propertiesToRemove = this.state.propertiesToRemove;
    // Only properties that already should be removed from the DB.
    if (field.existing) {
      propertiesToRemove = propertiesToRemove.concat(field);
    }
    this.setState({properties, propertiesToRemove});
  }

  onValueChange (what, event) {
    this.setState({ [what]: event.target.value });
  }

  onPropertyChange (id, what, event) {
    let properties = clone(this.state.properties);
    const idx = findIndex(properties, ['id', id]);

    const val = event.target.value;
    properties[idx][what] = val;

    this.setState({ properties });
  }

  onCloseClick (e) {
    // Block while processing.
    if (this.props.roadPropsOp.processing) return;
    this.props.onCloseClick();
  }

  async onSave () {
    const propertiesToAdd = this.state.properties.filter(property => !property.existing && property.key !== '');
    const propertiesToUpdate = this.state.properties.filter(property => property.existing && property.value !== property.valueOriginal);
    const propertiesToRemove = this.state.propertiesToRemove;
    const originalVpromm = this.props.vpromm;
    const newVpromm = this.state.vpromm;
    const diffVpromm = newVpromm !== originalVpromm;

    console.log('propertiesToAdd', propertiesToAdd);
    console.log('propertiesToUpdate', propertiesToUpdate);
    console.log('propertiesToRemove', propertiesToRemove);
    console.log('diffVpromm', diffVpromm);

    try {
      let successRes = {};

      if (propertiesToAdd.length || propertiesToUpdate.length || propertiesToRemove.length) {
        const res = await this.props.opOnRoadProperty(this.props.vpromm, {
          add: propertiesToAdd,
          replace: propertiesToUpdate,
          remove: propertiesToRemove
        });
        if (res.error) throw new Error(res.error);
        successRes = {action: 'refresh'};
      }

      if (diffVpromm) {
        const res = await this.props.editRoad(originalVpromm, newVpromm);
        if (res.error) throw new Error(res.error);
        successRes = {action: 'redirect', vpromm: newVpromm};
      }

      this.props.onCloseClick(successRes);
    } catch (error) {
      alert('An error occurred while saving. Please try again.');
    }
  }

  renderProperties ({id, key, value, existing}) {
    const newProperties = this.state.properties.filter(o => !o.existing).length;

    return existing ? (

            {key}

            <button type='button' className='fia-trash' title={'Delete property'} onClick={this.removeProperty.bind(this, id)}>Delete</button>

        <input type='text' id={id} name={id} className='form__control' value={value} onChange={this.onPropertyChange.bind(this, id, 'value')} />

    ) : (
      <fieldset className='form__fieldset' key={id}>

            <legend className='form__legend'>New Property</legend>

            <button type='button' className={c('fia-trash', {disabled: newProperties <= 1})} title={'Delete property'} onClick={this.removeProperty.bind(this, id)}>Delete</button>

            <label className='form__label' htmlFor={`key-${id}`}>Name
            <input type='text' id={`key-${id}`} name={`key-${id}`} className='form__control' value={key} onChange={this.onPropertyChange.bind(this, id, 'key')} />

            <label className='form__label' htmlFor={`value-${id}`}>Value
            <input type='text' id={`value-${id}`} name={`value-${id}`} className='form__control' value={value} onChange={this.onPropertyChange.bind(this, id, 'value')} />

      </fieldset>
    );
  }

  render () {
    const { processing } = this.props.roadPropsOp;

    return (
      <Modal
        id='assets-edit-modal'
        className='modal--medium'
        onCloseClick={this.onCloseClick}
        revealed={this.props.revealed} >

        <ModalHeader>

Edit attributes of {this.props.vpromm}

        </ModalHeader>
        <ModalBody>
          <form className={c('form', {disabled: processing})} disabled={processing}>

                VPRoMMS
                <input type='text' id='vpromm' name='vpromm' className='form__control' value={this.state.vpromm} onChange={this.onValueChange.bind(this, 'vpromm')} />

              {this.state.properties.map(this.renderProperties)}

                <button type='button' className='fea-plus' title='Add new file' onClick={this.addProperty}>New property</button>

          </form>
        </ModalBody>
        <ModalFooter>
          <button className={c('button button--primary-raised-light', {disabled: processing})} disabled={processing} type='button' onClick={this.onCloseClick}>Cancel</button>
          <button className={c('button button--primary-raised-light', {disabled: processing})} disabled={processing} type='submit' onClick={this.onSave}>Save</button>
        </ModalFooter>
      </Modal>
    );
  }
}

if (environment !== 'production') {
  AssetsEditModal.propTypes = {
    vpromm: PropTypes.string,
    revealed: PropTypes.bool,
    roadProps: PropTypes.object,
    roadPropsOp: PropTypes.object,
    onCloseClick: PropTypes.func,
    opOnRoadProperty: PropTypes.func,
    editRoad: PropTypes.func
  };
}

export default AssetsEditModal;
<|endoftext|>


<commit_before>const Promise = require("bluebird");

const { EXHAUSTED } = require("../sequence");
const INCOMPLETE = Symbol();

function next (renderer, iter, push) {
  const max = renderer.batchSize;
  let nextVal;

  if (iter >= max) {
    return Promise.resolve(INCOMPLETE);
  }

  try {
    nextVal = renderer._next();
  } catch (err) {
    return Promise.reject(err);
  }

  if (nextVal === EXHAUSTED) {
    return EXHAUSTED;
  } else if (nextVal instanceof Promise) {
    return nextVal
    .then(push)
    .then(() => next(renderer, iter + 1, push));
  } else {
    push(nextVal);
    return Promise.resolve(nextVal);
  }
}

/**
 * Given a batch size, request values from the source sequence and push them
 * onto the provided "pushable" (a Node stream or an array).  Once the number
 * of retrieved values reaches the specified batch size, return control back
 * to the caller.
 *
 * @param      {Renderer}     renderer   The Renderer from which to pull next-vals.
 * @param      {Array|Stream}            pushable   Destination for all segments.
 *
 * @return     {boolean|Promise}         Indicates whether there are more values to
 *                                       be retrieved, or if this the last batch.
 */
function pullBatch (renderer, pushable) {
  return next(renderer, 0, val => typeof val === "string" && pushable.push(val));
}

module.exports = { pullBatch, INCOMPLETE };
<commit_msg>Fix: check for exhaustion<commit_after>const Promise = require("bluebird");

const { EXHAUSTED } = require("../sequence");
const INCOMPLETE = Symbol();

function next (renderer, iter, push) {
  const max = renderer.batchSize;
  let nextVal;

  if (iter >= max) {
    return Promise.resolve(INCOMPLETE);
  }

  try {
    nextVal = renderer._next();
  } catch (err) {
    return Promise.reject(err);
  }

  if (nextVal === EXHAUSTED) {
    return Promise.resolve(EXHAUSTED);
  } else if (nextVal instanceof Promise) {
    return nextVal
    .then(push)
    .then(() => next(renderer, iter + 1, push));
  } else {
    push(nextVal);
    return Promise.resolve(nextVal);
  }
}

/**
 * Given a batch size, request values from the source sequence and push them
 * onto the provided "pushable" (a Node stream or an array).  Once the number
 * of retrieved values reaches the specified batch size, return control back
 * to the caller.
 *
 * @param      {Renderer}     renderer   The Renderer from which to pull next-vals.
 * @param      {Array|Stream}            pushable   Destination for all segments.
 *
 * @return     {boolean|Promise}         Indicates whether there are more values to
 *                                       be retrieved, or if this the last batch.
 */
function pullBatch (renderer, pushable) {
  return next(renderer, 0, val => typeof val === "string" && pushable.push(val));
}

module.exports = { pullBatch, INCOMPLETE };
<|endoftext|>


<commit_before>define(["dojo/_base/declare", "dojo/_base/lang", "ppwcode-util-oddsAndEnds/js"],
  function(declare, lang, js) {

    var _PreconditionViolationError = declare([Error], {
      instance: null,
      method: null,
      condition: null,
      arguments: null,
      caller: null,
      constructor: function(instance, method, caller, callArguments, condition) {
        this.instance = instance;
        this.method = (method && method.nom) || method;
        this.caller = (caller && caller.nom) || caller;
        this.arguments = callArguments;
        this.condition = condition;
        console.info(this.stack);
      },
      toString: function() {
        return "Precondition violation: " + this.condition +
          " (on " + this.instance.toString() + " in method " + this.method + ", called from " + this.caller + ")";
      }
    });

    var _ContractMixin = declare(null, {
      _c_invar: [],

      _c_pre: function(condition) {
        if (! condition.apply(this)) {
          throw new _PreconditionViolationError(this, this._c_pre.caller, this._c_pre.caller.caller, this._c_pre.caller.arguments, condition);
        }
      },

      _c_prop: function(subject, propName) {
        // summary:
        //   the property subject[propName] exists
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return js.getAllKeys(s).some(function(k) {return k === pName;});
      },

      _c_prop_mandatory: function(subject, propName) {
        // summary:
        //   the property subject[propName] is mandatory (exists and not-null)
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return this._c_prop(s, pName) && s[pName] !== null;
      },

      _c_prop_mandatory_string: function(subject, propName) {
        // summary:
        //   the property subject[propName] is a non-empty string
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop_mandatory(s, pName);
        if (exists) {
          var value = s[pName];
          return typeof value === "string" && value != "";
        }
        else {
          return false;
        }
      },

      _c_prop_number: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a number
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || typeof value === "number";
        }
        else {
          return false;
        }
      },

      _c_prop_int: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an integer
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return this._c_prop_number(s, pName) && js.isInt(s[pName]);
      },

      _c_prop_bool: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a bool
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || typeof value === "boolean";
        }
        else {
          return false;
        }
      },

      _c_prop_string: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a string
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isString(value);
        }
        else {
          return false;
        }
      },

        _c_prop_date: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a Date
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value == null || js.typeOf(value) === "date";
          }
          else {
            return false;
          }
        },

        _c_prop_array: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an Array
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isArray(value);
        }
        else {
          return false;
        }
      },

      _c_prop_function: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a Function
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isFunction(value);
        }
        else {
          return false;
        }
      },

      _c_prop_instance: function(subject, propName, Constructor) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an
        //   instance of the Dojo declared type Constructor (isInstanceOf) or an
        //   EnumerationValue (isValueOf).
        // description:
        //   if there is only 1 argument, subject is taken to be this

        var pName;
        var s;
        var Constr;
        if (arguments.length < 3) {
          pName = subject;
          s = this;
          Constr = propName;
        }
        else {
          pName = propName;
          s = subject;
          Constr = Constructor;
        }

        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          if (!value) {
            return true;
          }
          else if (js.typeOf(Constr) === "function") {
            return value.isInstanceOf ? value.isInstanceOf(Constr) : value instanceof Constr;
          }
          else if (js.typeOf(Constr) === "object") {
            // value must be an EnumerationValue, but we cannot test that here, because that would
            // create a dependency loop
            return value.isValueOf && value.isValueOf(Constr);
          }
          else {
            throw "ERROR: Constructor must be a Constructor function, or EnumerationValue definition";
          }
        }
        else {
          return false;
        }
      },

      _c_ABSTRACT: function() {
        // summary:
        //   use this to annotate a function as abstract
        // description:
        //   This method throws an exception "ABSTRACT".
        //
        //   An abstract method should be mentioned, to have a hook for documentation.
        //   Yet, an meaningful implementation is not possible.
        //   To detect errors early, and to avoid code inspection warnings, you
        //   can call this body in the abstract method. Because the method should
        //   be overwritten for every concrete subclass, this code should never be called.
        //
        //   Often, abstract methods also have parameters. These will not be used in the
        //   body of the abstract method declaration (the hook for the documentation),
        //   which will trigger code inspection warnings. To avoid these, you should
        //   add those parameters as arguments to this call.
        throw "ABSTRACT";
      },

      _c_NOP: function() {
        // summary:
        //   use this to annotate a function as having no body whatsoever
        // description:
        //   This method does NOP.
        //
        //   Methods like this must sometimes be mentioned, as a NOP implementation
        //   of an abstract method in some subclass, or in other circumstances.
        //   Using this method instead of a comment helps in avoiding unnecessary
        //   code inspection warnings.
        //
        //   Often, such NOP methods also have parameters. These will not be used in the
        //   empty body, which will trigger code inspection warnings. To avoid these, you
        //   should add those parameters as arguments to this call.
      }

    }
  );

  return _ContractMixin;
});
<commit_msg>Created a new has condition for ppwcode _Mixin pre-condition check: ppwcode-contracts-precondition<commit_after>define(["dojo/_base/declare", "dojo/_base/lang", "ppwcode-util-oddsAndEnds/js", "dojo/has"],
  function(declare, lang, js, has) {

    var _PreconditionViolationError = declare([Error], {
      instance: null,
      method: null,
      condition: null,
      arguments: null,
      caller: null,
      constructor: function(instance, method, caller, callArguments, condition) {
        this.instance = instance;
        this.method = (method && method.nom) || method;
        this.caller = (caller && caller.nom) || caller;
        this.arguments = callArguments;
        this.condition = condition;
        console.info(this.stack);
      },
      toString: function() {
        return "Precondition violation: " + this.condition +
          " (on " + this.instance.toString() + " in method " + this.method + ", called from " + this.caller + ")";
      }
    });

    var _ContractMixin = declare(null, {
      _c_invar: [],

      _c_pre: function(condition) {
        if (has("ppwcode-contracts-precondition")) {
          if (! condition.apply(this)) {
            throw new _PreconditionViolationError(this, this._c_pre.caller, this._c_pre.caller.caller, this._c_pre.caller.arguments, condition);
          }
        }
      },

      _c_prop: function(subject, propName) {
        // summary:
        //   the property subject[propName] exists
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return js.getAllKeys(s).some(function(k) {return k === pName;});
      },

      _c_prop_mandatory: function(subject, propName) {
        // summary:
        //   the property subject[propName] is mandatory (exists and not-null)
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return this._c_prop(s, pName) && s[pName] !== null;
      },

      _c_prop_mandatory_string: function(subject, propName) {
        // summary:
        //   the property subject[propName] is a non-empty string
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop_mandatory(s, pName);
        if (exists) {
          var value = s[pName];
          return typeof value === "string" && value != "";
        }
        else {
          return false;
        }
      },

      _c_prop_number: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a number
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || typeof value === "number";
        }
        else {
          return false;
        }
      },

      _c_prop_int: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an integer
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        return this._c_prop_number(s, pName) && js.isInt(s[pName]);
      },

      _c_prop_bool: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a bool
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || typeof value === "boolean";
        }
        else {
          return false;
        }
      },

      _c_prop_string: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a string
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isString(value);
        }
        else {
          return false;
        }
      },

        _c_prop_date: function(subject, propName) {
          // summary:
          //   the property subject[propName] is defined, and if it is not-null, it is a Date
          // description:
          //   if there is only 1 argument, subject is taken to be this
          var pName;
          var s;
          if (arguments.length < 2) {
            pName = subject;
            s = this;
          }
          else {
            pName = propName;
            s = subject;
          }
          var exists = this._c_prop(s, pName);
          if (exists) {
            var value = s[pName];
            return value == null || js.typeOf(value) === "date";
          }
          else {
            return false;
          }
        },

        _c_prop_array: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an Array
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isArray(value);
        }
        else {
          return false;
        }
      },

      _c_prop_function: function(subject, propName) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is a Function
        // description:
        //   if there is only 1 argument, subject is taken to be this
        var pName;
        var s;
        if (arguments.length < 2) {
          pName = subject;
          s = this;
        }
        else {
          pName = propName;
          s = subject;
        }
        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          return value == null || lang.isFunction(value);
        }
        else {
          return false;
        }
      },

      _c_prop_instance: function(subject, propName, Constructor) {
        // summary:
        //   the property subject[propName] is defined, and if it is not-null, it is an
        //   instance of the Dojo declared type Constructor (isInstanceOf) or an
        //   EnumerationValue (isValueOf).
        // description:
        //   if there is only 1 argument, subject is taken to be this

        var pName;
        var s;
        var Constr;
        if (arguments.length < 3) {
          pName = subject;
          s = this;
          Constr = propName;
        }
        else {
          pName = propName;
          s = subject;
          Constr = Constructor;
        }

        var exists = this._c_prop(s, pName);
        if (exists) {
          var value = s[pName];
          if (!value) {
            return true;
          }
          else if (js.typeOf(Constr) === "function") {
            return value.isInstanceOf ? value.isInstanceOf(Constr) : value instanceof Constr;
          }
          else if (js.typeOf(Constr) === "object") {
            // value must be an EnumerationValue, but we cannot test that here, because that would
            // create a dependency loop
            return value.isValueOf && value.isValueOf(Constr);
          }
          else {
            throw "ERROR: Constructor must be a Constructor function, or EnumerationValue definition";
          }
        }
        else {
          return false;
        }
      },

      _c_ABSTRACT: function() {
        // summary:
        //   use this to annotate a function as abstract
        // description:
        //   This method throws an exception "ABSTRACT".
        //
        //   An abstract method should be mentioned, to have a hook for documentation.
        //   Yet, an meaningful implementation is not possible.
        //   To detect errors early, and to avoid code inspection warnings, you
        //   can call this body in the abstract method. Because the method should
        //   be overwritten for every concrete subclass, this code should never be called.
        //
        //   Often, abstract methods also have parameters. These will not be used in the
        //   body of the abstract method declaration (the hook for the documentation),
        //   which will trigger code inspection warnings. To avoid these, you should
        //   add those parameters as arguments to this call.
        throw "ABSTRACT";
      },

      _c_NOP: function() {
        // summary:
        //   use this to annotate a function as having no body whatsoever
        // description:
        //   This method does NOP.
        //
        //   Methods like this must sometimes be mentioned, as a NOP implementation
        //   of an abstract method in some subclass, or in other circumstances.
        //   Using this method instead of a comment helps in avoiding unnecessary
        //   code inspection warnings.
        //
        //   Often, such NOP methods also have parameters. These will not be used in the
        //   empty body, which will trigger code inspection warnings. To avoid these, you
        //   should add those parameters as arguments to this call.
      }

    }
  );

  return _ContractMixin;
});
<|endoftext|>


<commit_before>import Component from '@ember/component'
import { computed } from '@ember/object'
import { run } from '@ember/runloop'
import ContributionValidations from '../../validations/contribution'

export default Component.extend({
  ContributionValidations,

  classNames: ['layout-column-flex'],

  contribution: null,
  validations: computed(() => []),

  onsave() {},
  oncancel() {},
  ondelete() {},

  actions: {
    async save(changeset) {
      await changeset.validate()

      if (changeset.get('isValid')) {
        return this.onsave(changeset)
      }
    },
    delete() {
      run.later(() => {
        this.ondelete(this.contribution)
      }, 400)
    },
    setDate(changeset, date) {
      changeset.set('date', date.format('YYYY-MM-DD'))
    },
  },
})
<commit_msg>Remove dead code<commit_after>import Component from '@ember/component'
import { run } from '@ember/runloop'
import ContributionValidations from '../../validations/contribution'

export default Component.extend({
  ContributionValidations,

  classNames: ['layout-column-flex'],

  contribution: null,

  onsave() {},
  oncancel() {},
  ondelete() {},

  actions: {
    async save(changeset) {
      await changeset.validate()

      if (changeset.get('isValid')) {
        return this.onsave(changeset)
      }
    },
    delete() {
      run.later(() => {
        this.ondelete(this.contribution)
      }, 400)
    },
    setDate(changeset, date) {
      changeset.set('date', date.format('YYYY-MM-DD'))
    },
  },
})
<|endoftext|>


<commit_before>////////////////////////////////////////
// ADFSUserMappingAPI
//
// Copyright (c) 2017 Jonathan Hardison
// /controllers/user.js
///////////////////////////////////////

import mongoose from 'mongoose';
import express from 'express';
import {Router} from 'express';
import User from '../models/user';
import Altid from '../models/altid';

export default({ config, db}) => {
    let api = Router();

    // general get from alternate email address input
    api.get('/altid/email/:altemail', (req, res) => {
        Altid.find({email: req.params.altemail}, (err, altid) =>{
            if(err){
                res.status(500).send(err);
            }

            User.findById(altid[0].user, (err, user) =>{
                if(err){
                    res.status(500).send(err);
                }
                res.status(200).send(user.realid);
            });

        })
    });

    // general get from alternate email by id
    api.get('/altid/:id', (req, res) => {
        Altid.findById(req.params.id, (err, altid) =>{
            if(err){
                res.status(500).send(err);
            }
            res.status(200).send(altid.realid);
        })
    });

    // general get from real email address input
    api.get('/email/:realemail', (req, res) => {
        User.find({realid: req.params.realemail}, (err, user) =>{
            if(err){
                res.status(500).send(err);
            }
            res.status(200).json(user);
        })
    });

    // general get from real email address input with ID
    api.get('/:id', (req, res) => {
        User.findById(req.params.realemail, (err, user) =>{
            if(err){
                res.status(500).send(err);
            }
            res.status(200).json(user);
        })
    });

    // general post to stage some users
    api.post('/', (req, res) => {
        let newUser = new User();
        newUser.realid = req.body.realid;

        newUser.save(err => {
            if(err){
                res.status(500).send(err);
            }
            res.status(200).json({message: "Real user created successfully"});
        });
    });

    // general post to stage some alt id's
    api.post('/altid/:realid', (req, res) => {
        User.findById(req.params.realid, (err, user) => {
            if(err){
                res.status(500).send(err);
            }
            let newAltID = new Altid();
            newAltID.email = req.body.email;
            newAltID.user = user.id;

            newAltID.save((err, altid) => {
            if(err){
                res.status(500).send(err);
            }
            user.altids.push(newAltID);
            user.save(err => {
                if(err){
                    res.status(500).send(err);
                }
                res.status(200).json({message: "Alt ID created successfully"});
                });
            });
        });
    });

    return api;
}<commit_msg>handle not found errors<commit_after>////////////////////////////////////////
// ADFSUserMappingAPI
//
// Copyright (c) 2017 Jonathan Hardison
// /controllers/user.js
///////////////////////////////////////

import mongoose from 'mongoose';
import express from 'express';
import {Router} from 'express';
import User from '../models/user';
import Altid from '../models/altid';

export default({ config, db}) => {
    let api = Router();

    // general get from alternate email address input
    api.get('/altid/email/:altemail', (req, res) => {
        Altid.find({email: req.params.altemail}, (err, altid) =>{
            if(err){
                res.status(500).send(err);
            }

            if((altid != null) && (typeof altid !== "undefined")){
                User.findById(altid[0].user, (err, user) =>{
                    if(err){
                        res.status(500).send(err);
                    }
                    res.status(200).send(user.realid);
                });
            }
            else{
                res.status(200).send(req.params.altemail);
            }

        })
    });

    // general get from alternate email by id
    api.get('/altid/:id', (req, res) => {
        Altid.findById(req.params.id, (err, altid) =>{
            if(err){
                res.status(500).send(err);
            }
            res.status(200).send(altid.realid);
        })
    });

    // general get from real email address input
    api.get('/email/:realemail', (req, res) => {
        User.find({realid: req.params.realemail}, (err, user) =>{
            if(err){
                res.status(500).send(err);
            }
            res.status(200).json(user);
        })
    });

    // general get from real email address input with ID
    api.get('/:id', (req, res) => {
        User.findById(req.params.realemail, (err, user) =>{
            if(err){
                res.status(500).send(err);
            }
            res.status(200).json(user);
        })
    });

    // general post to stage some users
    api.post('/', (req, res) => {
        let newUser = new User();
        newUser.realid = req.body.realid;

        newUser.save(err => {
            if(err){
                res.status(500).send(err);
            }
            res.status(200).json({message: "Real user created successfully"});
        });
    });

    // general post to stage some alt id's
    api.post('/altid/:realid', (req, res) => {
        User.findById(req.params.realid, (err, user) => {
            if(err){
                res.status(500).send(err);
            }
            let newAltID = new Altid();
            newAltID.email = req.body.email;
            newAltID.user = user.id;

            newAltID.save((err, altid) => {
            if(err){
                res.status(500).send(err);
            }
            user.altids.push(newAltID);
            user.save(err => {
                if(err){
                    res.status(500).send(err);
                }
                res.status(200).json({message: "Alt ID created successfully"});
                });
            });
        });
    });

    return api;
}<|endoftext|>


<commit_before>// defines the phase specific functions

// require design modules
const dgn = require('../design/design.js')

// require design-state Models
const dgnState = require('../design-state/dgnState.js')

// reguire implementation modules
const imp = require('../implementation/implementation.js')

// require implementation-state modules
const impState = require('../implementation-state/impState.js')

// phases model validation
const validateFunc = (cy, phase) => {
  if (phase === 'design') {
    dgn.validate(cy)
  } else if (phase === 'design-state') {
    dgnState.validate(cy)
  } else if (phase === 'implementation') {
    imp.validate(cy)
  } else if (phase === 'implementation-state') {
    impState.validate(cy)
  }
}

// phases model overview
const overviewFunc = (cy, phase) => {
  if (phase === 'design') {
    dgn.overview(cy)
  } else if (phase === 'design-state') {
    dgnState.overview(cy)
  } else if (phase === 'implementation') {
    imp.overview(cy)
  } else if (phase === 'implementation-state') {
    impState.overview(cy)
  }
}

module.exports = {
  validateFunc: validateFunc,
  overviewFunc: overviewFunc
}
<commit_msg>:hammer: refactor coreHelpers<commit_after>// defines the phase specific functions

// require design modules
const dgn = require('../design/design.js')

// require design-state Models
const dgnState = require('../design-state/dgnState.js')

// reguire implementation modules
const imp = require('../implementation/implementation.js')

// require implementation-state modules
const impState = require('../implementation-state/impState.js')

// phases model validation
const validateFunc = (cy, phase) => {
  if (phase === 'design') {
    dgn.validate(cy)
  } else if (phase === 'design-state') {
    dgnState.validate(cy)
  } else if (phase === 'implementation') {
    imp.validate(cy)
  } else if (phase === 'implementation-state') {
    impState.validate(cy)
  }
}

// phases model overview
const overviewFunc = (cy, phase) => {
  if (phase === 'design') {
    dgn.overview(cy)
  } else if (phase === 'design-state') {
    dgnState.overview(cy)
  } else if (phase === 'implementation') {
    imp.overview(cy)
  } else if (phase === 'implementation-state') {
    impState.overview(cy)
  }
}

module.exports = {
  corehelpers: validateFunc, overviewFunc
}
<|endoftext|>


<commit_before>/**
 * 对字符串对象的扩展
 * @class String
 */
_.extend(BI, {

    /**
     * 判断字符串是否已指定的字符串开始
     * @param str source字符串
     * @param {String} startTag   指定的开始字符串
     * @return {Boolean}  如果字符串以指定字符串开始则返回true，否则返回false
     */
    startWith: function (str, startTag) {
        str = str || "";
        if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) {
            return false;
        }
        return str.substr(0, startTag.length) == startTag;
    },
    /**
     * 判断字符串是否以指定的字符串结束
     * @param str source字符串
     * @param {String} endTag 指定的字符串
     * @return {Boolean}  如果字符串以指定字符串结束则返回true，否则返回false
     */
    endWith: function (str, endTag) {
        if (endTag == null || endTag == "" || str.length === 0 || endTag.length > str.length) {
            return false;
        }
        return str.substring(str.length - endTag.length) == endTag;
    },

    /**
     * 获取url中指定名字的参数
     * @param str source字符串
     * @param {String} name 参数的名字
     * @return {String} 参数的值
     */
    getQuery: function (str, name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = str.substr(str.indexOf("?") + 1).match(reg);
        if (r) {
            return unescape(r[2]);
        }
        return null;
    },

    /**
     * 给url加上给定的参数
     * @param str source字符串
     * @param {Object} paras 参数对象，是一个键值对对象
     * @return {String} 添加了给定参数的url
     */
    appendQuery: function (str, paras) {
        if (!paras) {
            return str;
        }
        var src = str;
        // 没有问号说明还没有参数
        if (src.indexOf("?") === -1) {
            src += "?";
        }
        // 如果以问号结尾，说明没有其他参数
        if (BI.endWith(src, "?") !== false) {
        } else {
            src += "&";
        }
        _.each(paras, function (value, name) {
            if (typeof(name) === "string") {
                src += name + "=" + value + "&";
            }
        });
        src = src.substr(0, src.length - 1);
        return src;
    },
    /**
     * 将所有符合第一个字符串所表示的字符串替换成为第二个字符串
     * @param str source字符串
     * @param {String} s1 要替换的字符串的正则表达式
     * @param {String} s2 替换的结果字符串
     * @returns {String} 替换后的字符串
     */
    replaceAll: function (str, s1, s2) {
        return BI.isNull(str) ? str : str.replace(new RegExp(s1, "gm"), s2);
    },
    /**
     * 总是让字符串以指定的字符开头
     * @param str source字符串
     * @param {String} start 指定的字符
     * @returns {String} 以指定字符开头的字符串
     */
    perfectStart: function (str, start) {
        if (BI.startWith(str, start)) {
            return str;
        }
        return start + str;

    },

    /**
     * 获取字符串中某字符串的所有项位置数组
     * @param str source字符串
     * @param {String} sub 子字符串
     * @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组
     */
    allIndexOf: function (str, sub) {
        if (typeof sub !== "string") {
            return [];
        }
        var location = [];
        var offset = 0;
        while (str.length > 0) {
            var loc = str.indexOf(sub);
            if (loc === -1) {
                break;
            }
            location.push(offset + loc);
            str = str.substring(loc + sub.length, str.length);
            offset += loc + sub.length;
        }
        return location;
    }
});<commit_msg>Pull request #1360: 无JIRA任务 replaceAll实现修改一下<commit_after>/**
 * 对字符串对象的扩展
 * @class String
 */
_.extend(BI, {

    /**
     * 判断字符串是否已指定的字符串开始
     * @param str source字符串
     * @param {String} startTag   指定的开始字符串
     * @return {Boolean}  如果字符串以指定字符串开始则返回true，否则返回false
     */
    startWith: function (str, startTag) {
        str = str || "";
        if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) {
            return false;
        }
        return str.substr(0, startTag.length) == startTag;
    },
    /**
     * 判断字符串是否以指定的字符串结束
     * @param str source字符串
     * @param {String} endTag 指定的字符串
     * @return {Boolean}  如果字符串以指定字符串结束则返回true，否则返回false
     */
    endWith: function (str, endTag) {
        if (endTag == null || endTag == "" || str.length === 0 || endTag.length > str.length) {
            return false;
        }
        return str.substring(str.length - endTag.length) == endTag;
    },

    /**
     * 获取url中指定名字的参数
     * @param str source字符串
     * @param {String} name 参数的名字
     * @return {String} 参数的值
     */
    getQuery: function (str, name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = str.substr(str.indexOf("?") + 1).match(reg);
        if (r) {
            return unescape(r[2]);
        }
        return null;
    },

    /**
     * 给url加上给定的参数
     * @param str source字符串
     * @param {Object} paras 参数对象，是一个键值对对象
     * @return {String} 添加了给定参数的url
     */
    appendQuery: function (str, paras) {
        if (!paras) {
            return str;
        }
        var src = str;
        // 没有问号说明还没有参数
        if (src.indexOf("?") === -1) {
            src += "?";
        }
        // 如果以问号结尾，说明没有其他参数
        if (BI.endWith(src, "?") !== false) {
        } else {
            src += "&";
        }
        _.each(paras, function (value, name) {
            if (typeof(name) === "string") {
                src += name + "=" + value + "&";
            }
        });
        src = src.substr(0, src.length - 1);
        return src;
    },
    /**
     * 将所有符合第一个字符串所表示的字符串替换成为第二个字符串
     * @param str source字符串
     * @param {String} s1 要替换的字符串的正则表达式
     * @param {String} s2 替换的结果字符串
     * @returns {String} 替换后的字符串
     */
    replaceAll: function (str, s1, s2) {
        return BI.isString(str) ? str.replace(new RegExp(s1, "gm"), s2) : str;
    },
    /**
     * 总是让字符串以指定的字符开头
     * @param str source字符串
     * @param {String} start 指定的字符
     * @returns {String} 以指定字符开头的字符串
     */
    perfectStart: function (str, start) {
        if (BI.startWith(str, start)) {
            return str;
        }
        return start + str;

    },

    /**
     * 获取字符串中某字符串的所有项位置数组
     * @param str source字符串
     * @param {String} sub 子字符串
     * @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组
     */
    allIndexOf: function (str, sub) {
        if (typeof sub !== "string") {
            return [];
        }
        var location = [];
        var offset = 0;
        while (str.length > 0) {
            var loc = str.indexOf(sub);
            if (loc === -1) {
                break;
            }
            location.push(offset + loc);
            str = str.substring(loc + sub.length, str.length);
            offset += loc + sub.length;
        }
        return location;
    }
});<|endoftext|>


<commit_before>//node >  rename file version outputpath
//demo > node rename src/app.js public/

var fs = require('fs');
var filePath = process.argv[2]; //SOURCE FILE PATH ex: Desktop/excel.xlsx;
var version = process.argv[3]; //OUTPUT PATH ex: 1.2.3 - could be anything'
var outputfolder = process.argv[4]; //OUTPUT PATH ex: Desktop/'

// fs.rename('./teste.js', './teste-renamed.js', (err) => {
//     if (err) throw err;
//     console.log('renamed complete');
// });
// fs.stat('./teste-renamed.js', (err, stats) => {
//     if (err) throw err;
//     console.log(`stats: ${JSON.stringify(stats)}`);
// });

var fileName = '',
    fileExtension = '',
    tempNameNoExtension = '',
    fileRenamed = '',
    finalOutputPath = '';

function setup() {
    fileName = removePathFromFileName(filePath);
    fileExtension = getFileExtension(fileName);
    tempNameNoExtension = getFileNameWithoutExtension(fileName);
    fileRenamed = concatNamedVersion({ name: tempNameNoExtension, version: version, extension: fileExtension });
    finalOutputPath = outputfolder + fileRenamed;
}

function rename() {
    fs.createReadStream(filePath).pipe(fs.createWriteStream(finalOutputPath));
};

function removePathFromFileName(input) {
    var output = input;

    //src/js/hello.js -> hello.js
    output = input.replace(/\w+\//g, '');

    return output;
};

function getFileExtension(input) {
    var output = input;

    //hello.js -> .js
    output = input.replace(/[0-9a-z-0-1]{1,}/, '');

    return output;
};

function getFileNameWithoutExtension(input) {
    var output = input;

    // hello.js -> hello.
    output = input.replace(/[0-9a-z]+$/, '');

    return output;
};

function concatNamedVersion(options) {
    var output = '';

    output = options.name + options.version + options.extension;

    return output;
};<commit_msg>formating<commit_after>//node >  rename file version outputpath
//demo > node rename src/app.js public/

var fs = require('fs');
var filePath = process.argv[2]; //SOURCE FILE PATH ex: Desktop/excel.xlsx;
var version = process.argv[3]; //OUTPUT PATH ex: 1.2.3 - could be anything'
var outputfolder = process.argv[4]; //OUTPUT PATH ex: Desktop/'

// fs.rename('./teste.js', './teste-renamed.js', (err) => {
//     if (err) throw err;
//     console.log('renamed complete');
// });
// fs.stat('./teste-renamed.js', (err, stats) => {
//     if (err) throw err;
//     console.log(`stats: ${JSON.stringify(stats)}`);
// });

var fileName = '',
    fileExtension = '',
    tempNameNoExtension = '',
    fileRenamed = '',
    finalOutputPath = '';

try {
    setup();
    rename();
    fs.stat(finalOutputPath, (err, stats) => {
        if (err) throw err;
        console.log('sucess:', `stats: ${JSON.stringify(stats)}`);
    });
} catch (ex) {
    console.log('ex:', ex.message());
}

function setup() {
    fileName = removePathFromFileName(filePath);
    fileExtension = getFileExtension(fileName);
    tempNameNoExtension = getFileNameWithoutExtension(fileName);
    fileRenamed = concatNamedVersion({
        name: tempNameNoExtension,
        version: version,
        extension: fileExtension
    });
    finalOutputPath = outputfolder + fileRenamed;
}

function rename() {
    fs.createReadStream(filePath).pipe(fs.createWriteStream(finalOutputPath));
};

function removePathFromFileName(input) {
    var output = input;

    //src/js/hello.js -> hello.js
    output = input.replace(/\w+\//g, '');

    return output;
};

function getFileExtension(input) {
    var output = input;

    //hello.js -> .js
    output = input.replace(/[0-9a-z-0-1]{1,}/, '');

    return output;
};

function getFileNameWithoutExtension(input) {
    var output = input;

    // hello.js -> hello.
    output = input.replace(/[0-9a-z]+$/, '');

    return output;
};

function concatNamedVersion(options) {
    var output = '';

    output = options.name + options.version + options.extension;

    return output;
};<|endoftext|>


<commit_before>// Source : https://leetcode.com/problems/palindrome-linked-list/discuss/
// Author : Dean Shi
// Date   : 2017-10-21

/***************************************************************************************
 *
 * Given a singly linked list, determine if it is a palindrome.
 *
 * Follow up:
 * Could you do it in O(n) time and O(1) space?
 *
 ***************************************************************************************/

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function(head) {
    const stack = []

    while (head) {
        stack.push(head.val)
        head = head.next
    }

    return stack.join('') === stack.reverse().join('')
};<commit_msg>Update PalindromeLinkedList<commit_after>// Source : https://leetcode.com/problems/palindrome-linked-list
// Author : Dean Shi
// Date   : 2017-10-21

/***************************************************************************************
 *
 * Given a singly linked list, determine if it is a palindrome.
 *
 * Follow up:
 * Could you do it in O(n) time and O(1) space?
 *
 ***************************************************************************************/

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function(head) {
    const stack = []

    while (head) {
        stack.push(head.val)
        head = head.next
    }

    return stack.join('') === stack.reverse().join('')
};<|endoftext|>


<commit_before>import { Comments } from 'meteor/example-forum';

Comments.addDefaultView(terms => {
  const validFields = _.pick(terms, 'userId');
  return ({
    selector: {
      $or: [{$and: [{deleted: true}, {deletedPublic: true}]}, {deleted: {$ne: true}}],
      ...validFields,
    }
  });
})

Comments.addView("postCommentsDeleted", function (terms) {
  return {
    selector: {
      $or: null,
      deleted: null,
      postId: terms.postId
    },
    options: {sort: {deletedDate: -1, baseScore: -1, postedAt: -1}}
  };
});

Comments.addView("postCommentsTop", function (terms) {
  return {
    selector: { postId: terms.postId },
    options: {sort: {deleted: 1, baseScore: -1, postedAt: -1}}
  };
});

Comments.addView("postCommentsNew", function (terms) {
  return {
    selector: { postId: terms.postId },
    options: {sort: {deleted: 1, postedAt: -1}}
  };
});

Comments.addView("postCommentsBest", function (terms) {
  console.log("ASDF", terms)
  return {
    selector: { postId: terms.postId },
    options: {sort: {deleted: 1, baseScore: -1}, postedAt: -1}
  };
});

Comments.addView("allRecentComments", function (terms) {
  return {
    selector: {deletedPublic: {$ne:true}},
    options: {sort: {postedAt: -1}, limit: terms.limit || 5},
  };
});

Comments.addView("recentComments", function (terms) {
  return {
    selector: { score:{$gt:0}, deletedPublic: {$ne: true}},
    options: {sort: {deletedPublic: -1}, limit: terms.limit || 5},
  };
});
Comments.addView("topRecentComments", function (terms) {
  return {
    selector: { score:{$gt:0}, postId:terms.postId},
    options: {sort: {baseScore: -1}, limit: terms.limit || 3},
  };
});

Comments.addView("postCommentsUnread", function (terms) {
  return {
    selector: {
      postId: terms.postId,
      deleted: {$ne: true }
    },
    options: {sort: {postedAt: -1}, limit: terms.limit || 5},
  };
});
<commit_msg>hotfix recentComment sorting<commit_after>import { Comments } from 'meteor/example-forum';

Comments.addDefaultView(terms => {
  const validFields = _.pick(terms, 'userId');
  return ({
    selector: {
      $or: [{$and: [{deleted: true}, {deletedPublic: true}]}, {deleted: {$ne: true}}],
      ...validFields,
    }
  });
})

Comments.addView("postCommentsDeleted", function (terms) {
  return {
    selector: {
      $or: null,
      deleted: null,
      postId: terms.postId
    },
    options: {sort: {deletedDate: -1, baseScore: -1, postedAt: -1}}
  };
});

Comments.addView("postCommentsTop", function (terms) {
  return {
    selector: { postId: terms.postId },
    options: {sort: {deleted: 1, baseScore: -1, postedAt: -1}}
  };
});

Comments.addView("postCommentsNew", function (terms) {
  return {
    selector: { postId: terms.postId },
    options: {sort: {deleted: 1, postedAt: -1}}
  };
});

Comments.addView("postCommentsBest", function (terms) {
  console.log("ASDF", terms)
  return {
    selector: { postId: terms.postId },
    options: {sort: {deleted: 1, baseScore: -1}, postedAt: -1}
  };
});

Comments.addView("allRecentComments", function (terms) {
  return {
    selector: {deletedPublic: {$ne:true}},
    options: {sort: {postedAt: -1}, limit: terms.limit || 5},
  };
});

Comments.addView("recentComments", function (terms) {
  return {
    selector: { score:{$gt:0}, deletedPublic: {$ne: true}},
    options: {sort: {postedAt: -1}, limit: terms.limit || 5},
  };
});
Comments.addView("topRecentComments", function (terms) {
  return {
    selector: { score:{$gt:0}, postId:terms.postId},
    options: {sort: {baseScore: -1}, limit: terms.limit || 3},
  };
});

Comments.addView("postCommentsUnread", function (terms) {
  return {
    selector: {
      postId: terms.postId,
      deleted: {$ne: true }
    },
    options: {sort: {postedAt: -1}, limit: terms.limit || 5},
  };
});
<|endoftext|>


<commit_before>/* This file contains templates for Blocks that control robots.  Each robot has its own BlockDefs file, but many
 * of the defined Blocks are just subclasses of the Blocks here.
 */

/**
 * A Block that polls a sensor
 * @param {number} x
 * @param {number} y
 * @param deviceClass - A subclass of Device indicating the type of robot
 * @param {string} sensorType - Needed for the http request
 * @param {string} displayName - Name present on Block
 * @param {number} numberOfPorts - Used to populate PortSlot
 * @constructor
 */
function B_DeviceWithPortsSensorBase(x, y, deviceClass, sensorType, displayName, numberOfPorts){
	ReporterBlock.call(this,x,y,deviceClass.getDeviceTypeId());
	this.deviceClass = deviceClass;
	this.sensorType = sensorType;
	this.displayName = displayName; //TODO: perhapse remove this
	this.numberOfPorts = numberOfPorts;
	this.addPart(new DeviceDropSlot(this,"DDS_1", deviceClass));
	this.addPart(new LabelText(this,displayName));
	this.addPart(new PortSlot(this,"PortS_1", numberOfPorts));
}
B_DeviceWithPortsSensorBase.prototype = Object.create(ReporterBlock.prototype);
B_DeviceWithPortsSensorBase.prototype.constructor = B_DeviceWithPortsSensorBase;
/* Sends the request for the sensor data. */
B_DeviceWithPortsSensorBase.prototype.startAction=function(){
	let deviceIndex = this.slots[0].getData().getValue();
	let device = this.deviceClass.getManager().getDevice(deviceIndex);
	if (device == null) {
		this.displayError(this.deviceClass.getNotConnectedMessage());
		return new ExecutionStatusError(); // Flutter was invalid, exit early
	}
	let mem = this.runMem;
	let port = this.slots[1].getData().getValue();
	if (port != null && port > 0 && port <= this.numberOfPorts) {
		mem.requestStatus = {};
		mem.requestStatus.finished = false;
		mem.requestStatus.error = false;
		mem.requestStatus.result = null;
		device.readSensor(mem.requestStatus, this.sensorType, port);
		return new ExecutionStatusRunning();
	} else {
		this.displayError("Invalid port number");
		return new ExecutionStatusError(); // Invalid port, exit early
	}
};
/* Returns the result of the request */
B_DeviceWithPortsSensorBase.prototype.updateAction=function(){
	const status = this.runMem.requestStatus;
	if (status.finished) {
		if(status.error){
			this.displayError(this.deviceClass.getNotConnectedMessage(status.code, status.result));
			return new ExecutionStatusError();
		} else {
			const result = new StringData(status.result);
			const num = result.asNum().getValue();
			const rounded = Math.round(num);
			return new ExecutionStatusResult(new NumData(rounded));
		}
	}
	return new ExecutionStatusRunning(); // Still running
};

/**
 * A Block that sets an output
 * @param {number} x
 * @param {number} y
 * @param deviceClass - A subclass of Device indicating the type of robot
 * @param {string} outputType - Needed for the http request
 * @param {string} displayName - Name present on Block
 * @param {number} numberOfPorts - Used to populate PortSlot
 * @param {string} valueKey - Needed for the http request. The key used to send the value in the slot
 * @param {number} minVal - The minimum value the output can take
 * @param {number} maxVal - The maximum value the output can take
 * @param {string} displayUnits - The units to display on the inputPad
 * @constructor
 */
function B_DeviceWithPortsOutputBase(x, y, deviceClass, outputType, displayName, numberOfPorts, valueKey,
									 minVal, maxVal, displayUnits){
	CommandBlock.call(this,x,y,deviceClass.getDeviceTypeId());
	this.deviceClass = deviceClass;
	this.outputType = outputType;
	this.displayName = displayName;
	this.numberOfPorts = numberOfPorts;
	this.minVal = minVal;
	this.maxVal = maxVal;
	this.positive = minVal >= 0;
	this.valueKey = valueKey;
	this.displayUnits = displayUnits;
	this.addPart(new DeviceDropSlot(this,"DDS_1", deviceClass));
	this.addPart(new LabelText(this,displayName));
	this.addPart(new PortSlot(this,"PortS_1", numberOfPorts)); //Four sensor ports.
	const numSlot = new NumSlot(this,"NumS_out", 0, this.positive, true);
	numSlot.addLimits(this.minVal, this.maxVal, displayUnits);
	this.addPart(numSlot);
}
B_DeviceWithPortsOutputBase.prototype = Object.create(CommandBlock.prototype);
B_DeviceWithPortsOutputBase.prototype.constructor = B_DeviceWithPortsOutputBase;
/* Sends the request */
B_DeviceWithPortsOutputBase.prototype.startAction = function() {
	let deviceIndex = this.slots[0].getData().getValue();
	let device = this.deviceClass.getManager().getDevice(deviceIndex);
	if (device == null) {
		this.displayError(this.deviceClass.getNotConnectedMessage());
		return new ExecutionStatusError(); // Flutter was invalid, exit early
	}
	let mem = this.runMem;
	let port = this.slots[1].getData().getValue();
	let value = this.slots[2].getData().getValueInR(this.minVal, this.maxVal, this.positive, true);
	if (port != null && port > 0 && port <= this.numberOfPorts) {
		mem.requestStatus = {};
		mem.requestStatus.finished = false;
		mem.requestStatus.error = false;
		mem.requestStatus.result = null;
		device.setOutput(mem.requestStatus, this.outputType, port, value, this.valueKey);
		return new ExecutionStatusRunning();
	} else {
		this.displayError("Invalid port number");
		return new ExecutionStatusError(); // Invalid port, exit early
	}
};
/* Waits until the request completes */
B_DeviceWithPortsOutputBase.prototype.updateAction = function() {
	if(this.runMem.requestStatus.finished){
		if(this.runMem.requestStatus.error){
			let status = this.runMem.requestStatus;
			this.displayError(this.deviceClass.getNotConnectedMessage(status.code, status.result));
			return new ExecutionStatusError();
		}
		return new ExecutionStatusDone();
	}
	else{
		return new ExecutionStatusRunning();
	}
};

/**
 * Block that sets a Tri-LED
 * @param {number} x
 * @param {number} y
 * @param deviceClass - A subclass of Device indicating the type of robot
 * @param {number} numberOfPorts - Number of Tri-LED ports on the device
 * @constructor
 */
function B_DeviceWithPortsTriLed(x, y, deviceClass, numberOfPorts) {
	CommandBlock.call(this, x, y, deviceClass.getDeviceTypeId());
	this.deviceClass = deviceClass;
	this.numberOfPorts = numberOfPorts;
	this.addPart(new DeviceDropSlot(this,"DDS_1", deviceClass, true));
	this.addPart(new LabelText(this, "TRI-LED"));
	this.addPart(new PortSlot(this,"PortS_1", numberOfPorts)); //Positive integer.
	this.addPart(new LabelText(this, "R"));
	const ledSlot1 = new NumSlot(this,"NumS_r", 0, true, true); //Positive integer.
	ledSlot1.addLimits(0, 100, "Intensity");
	this.addPart(ledSlot1);
	this.addPart(new LabelText(this, "G"));
	const ledSlot2 = new NumSlot(this,"NumS_g", 0, true, true); //Positive integer.
	ledSlot2.addLimits(0, 100, "Intensity");
	this.addPart(ledSlot2);
	this.addPart(new LabelText(this, "B"));
	const ledSlot3 = new NumSlot(this,"NumS_b", 0, true, true); //Positive integer.
	ledSlot3.addLimits(0, 100, "Intensity");
	this.addPart(ledSlot3);
}
B_DeviceWithPortsTriLed.prototype = Object.create(CommandBlock.prototype);
B_DeviceWithPortsTriLed.prototype.constructor = B_DeviceWithPortsTriLed;
/* Sends the request */
B_DeviceWithPortsTriLed.prototype.startAction = function() {
	let deviceIndex = this.slots[0].getData().getValue();
	let device = this.deviceClass.getManager().getDevice(deviceIndex);
	if (device == null) {
		this.displayError(this.deviceClass.getNotConnectedMessage());
		return new ExecutionStatusError(); // Flutter was invalid, exit early
	}
	let mem = this.runMem;
	mem.requestStatus = {};
	let port = this.slots[1].getData().getValue(); // Positive integer.
	let valueR = this.slots[2].getData().getValueInR(0, 100, true, true); //Positive integer.
	let valueG = this.slots[3].getData().getValueInR(0, 100, true, true); //Positive integer.
	let valueB = this.slots[4].getData().getValueInR(0, 100, true, true); //Positive integer.
	if (port != null && port > 0 && port <= this.numberOfPorts) {
		device.setTriLed(mem.requestStatus, port, valueR, valueG, valueB);
		return new ExecutionStatusRunning();
	} else {
		this.displayError("Invalid port number");
		return new ExecutionStatusError(); // Invalid port, exit early
	}
};
/* Waits for the request to finish. */
B_DeviceWithPortsTriLed.prototype.updateAction = function() {
	if(this.runMem.requestStatus.finished){
		if(this.runMem.requestStatus.error){
			let status = this.runMem.requestStatus;
			this.displayError(this.deviceClass.getNotConnectedMessage(status.code, status.result));
			return new ExecutionStatusError();
		}
		return new ExecutionStatusDone();
	}
	else{
		return new ExecutionStatusRunning();
	}
};
<commit_msg>triLed block<commit_after>/* This file contains templates for Blocks that control robots.  Each robot has its own BlockDefs file, but many
 * of the defined Blocks are just subclasses of the Blocks here.
 */

/**
 * A Block that polls a sensor
 * @param {number} x
 * @param {number} y
 * @param deviceClass - A subclass of Device indicating the type of robot
 * @param {string} sensorType - Needed for the http request
 * @param {string} displayName - Name present on Block
 * @param {number} numberOfPorts - Used to populate PortSlot
 * @constructor
 */
function B_DeviceWithPortsSensorBase(x, y, deviceClass, sensorType, displayName, numberOfPorts){
	ReporterBlock.call(this,x,y,deviceClass.getDeviceTypeId());
	this.deviceClass = deviceClass;
	this.sensorType = sensorType;
	this.displayName = displayName; //TODO: perhapse remove this
	this.numberOfPorts = numberOfPorts;
	this.addPart(new DeviceDropSlot(this,"DDS_1", deviceClass));
	this.addPart(new LabelText(this,displayName));
	this.addPart(new PortSlot(this,"PortS_1", numberOfPorts));
}
B_DeviceWithPortsSensorBase.prototype = Object.create(ReporterBlock.prototype);
B_DeviceWithPortsSensorBase.prototype.constructor = B_DeviceWithPortsSensorBase;
/* Sends the request for the sensor data. */
B_DeviceWithPortsSensorBase.prototype.startAction=function(){
	let deviceIndex = this.slots[0].getData().getValue();
	let device = this.deviceClass.getManager().getDevice(deviceIndex);
	if (device == null) {
		this.displayError(this.deviceClass.getNotConnectedMessage());
		return new ExecutionStatusError(); // Flutter was invalid, exit early
	}
	let mem = this.runMem;
	let port = this.slots[1].getData().getValue();
	if (port != null && port > 0 && port <= this.numberOfPorts) {
		mem.requestStatus = {};
		mem.requestStatus.finished = false;
		mem.requestStatus.error = false;
		mem.requestStatus.result = null;
		device.readSensor(mem.requestStatus, this.sensorType, port);
		return new ExecutionStatusRunning();
	} else {
		this.displayError("Invalid port number");
		return new ExecutionStatusError(); // Invalid port, exit early
	}
};
/* Returns the result of the request */
B_DeviceWithPortsSensorBase.prototype.updateAction=function(){
	const status = this.runMem.requestStatus;
	if (status.finished) {
		if(status.error){
			this.displayError(this.deviceClass.getNotConnectedMessage(status.code, status.result));
			return new ExecutionStatusError();
		} else {
			const result = new StringData(status.result);
			const num = result.asNum().getValue();
			const rounded = Math.round(num);
			return new ExecutionStatusResult(new NumData(rounded));
		}
	}
	return new ExecutionStatusRunning(); // Still running
};

/**
 * A Block that sets an output
 * @param {number} x
 * @param {number} y
 * @param deviceClass - A subclass of Device indicating the type of robot
 * @param {string} outputType - Needed for the http request
 * @param {string} displayName - Name present on Block
 * @param {number} numberOfPorts - Used to populate PortSlot
 * @param {string} valueKey - Needed for the http request. The key used to send the value in the slot
 * @param {number} minVal - The minimum value the output can take
 * @param {number} maxVal - The maximum value the output can take
 * @param {string} displayUnits - The units to display on the inputPad
 * @constructor
 */
function B_DeviceWithPortsOutputBase(x, y, deviceClass, outputType, displayName, numberOfPorts, valueKey,
									 minVal, maxVal, displayUnits){
	CommandBlock.call(this,x,y,deviceClass.getDeviceTypeId());
	this.deviceClass = deviceClass;
	this.outputType = outputType;
	this.displayName = displayName;
	this.numberOfPorts = numberOfPorts;
	this.minVal = minVal;
	this.maxVal = maxVal;
	this.positive = minVal >= 0;
	this.valueKey = valueKey;
	this.displayUnits = displayUnits;
	this.addPart(new DeviceDropSlot(this,"DDS_1", deviceClass));
	this.addPart(new LabelText(this,displayName));
	this.addPart(new PortSlot(this,"PortS_1", numberOfPorts)); //Four sensor ports.
	const numSlot = new NumSlot(this,"NumS_out", 0, this.positive, true);
	numSlot.addLimits(this.minVal, this.maxVal, displayUnits);
	this.addPart(numSlot);
}
B_DeviceWithPortsOutputBase.prototype = Object.create(CommandBlock.prototype);
B_DeviceWithPortsOutputBase.prototype.constructor = B_DeviceWithPortsOutputBase;
/* Sends the request */
B_DeviceWithPortsOutputBase.prototype.startAction = function() {
	let deviceIndex = this.slots[0].getData().getValue();
	let device = this.deviceClass.getManager().getDevice(deviceIndex);
	if (device == null) {
		this.displayError(this.deviceClass.getNotConnectedMessage());
		return new ExecutionStatusError(); // Flutter was invalid, exit early
	}
	let mem = this.runMem;
	let port = this.slots[1].getData().getValue();
	let value = this.slots[2].getData().getValueInR(this.minVal, this.maxVal, this.positive, true);
	if (port != null && port > 0 && port <= this.numberOfPorts) {
		mem.requestStatus = {};
		mem.requestStatus.finished = false;
		mem.requestStatus.error = false;
		mem.requestStatus.result = null;
		device.setOutput(mem.requestStatus, this.outputType, port, value, this.valueKey);
		return new ExecutionStatusRunning();
	} else {
		this.displayError("Invalid port number");
		return new ExecutionStatusError(); // Invalid port, exit early
	}
};
/* Waits until the request completes */
B_DeviceWithPortsOutputBase.prototype.updateAction = function() {
	if(this.runMem.requestStatus.finished){
		if(this.runMem.requestStatus.error){
			let status = this.runMem.requestStatus;
			this.displayError(this.deviceClass.getNotConnectedMessage(status.code, status.result));
			return new ExecutionStatusError();
		}
		return new ExecutionStatusDone();
	}
	else{
		return new ExecutionStatusRunning();
	}
};

/**
 * Block that sets a Tri-LED
 * @param {number} x
 * @param {number} y
 * @param deviceClass - A subclass of Device indicating the type of robot
 * @param {number} numberOfPorts - Number of Tri-LED ports on the device
 * @constructor
 */
function B_DeviceWithPortsTriLed(x, y, deviceClass, numberOfPorts) {
	CommandBlock.call(this, x, y, deviceClass.getDeviceTypeId());
	this.deviceClass = deviceClass;
	this.numberOfPorts = numberOfPorts;
	this.addPart(new DeviceDropSlot(this,"DDS_1", deviceClass, false)); //true for short text label
	this.addPart(new LabelText(this, "TRI-LED"));
	const portSlot = new PortSlot(this,"PortS_1", numberOfPorts); //Positive integer.
	portSlot.isEndOfLine = true;
	this.addPart(portSlot);
	this.addPart(new LabelText(this, "R"));
	const ledSlot1 = new NumSlot(this,"NumS_r", 0, true, true); //Positive integer.
	ledSlot1.addLimits(0, 100, "Intensity");
	this.addPart(ledSlot1);
	this.addPart(new LabelText(this, "G"));
	const ledSlot2 = new NumSlot(this,"NumS_g", 0, true, true); //Positive integer.
	ledSlot2.addLimits(0, 100, "Intensity");
	this.addPart(ledSlot2);
	this.addPart(new LabelText(this, "B"));
	const ledSlot3 = new NumSlot(this,"NumS_b", 0, true, true); //Positive integer.
	ledSlot3.addLimits(0, 100, "Intensity");
	this.addPart(ledSlot3);
}
B_DeviceWithPortsTriLed.prototype = Object.create(CommandBlock.prototype);
B_DeviceWithPortsTriLed.prototype.constructor = B_DeviceWithPortsTriLed;
/* Sends the request */
B_DeviceWithPortsTriLed.prototype.startAction = function() {
	let deviceIndex = this.slots[0].getData().getValue();
	let device = this.deviceClass.getManager().getDevice(deviceIndex);
	if (device == null) {
		this.displayError(this.deviceClass.getNotConnectedMessage());
		return new ExecutionStatusError(); // Flutter was invalid, exit early
	}
	let mem = this.runMem;
	mem.requestStatus = {};
	let port = this.slots[1].getData().getValue(); // Positive integer.
	let valueR = this.slots[2].getData().getValueInR(0, 100, true, true); //Positive integer.
	let valueG = this.slots[3].getData().getValueInR(0, 100, true, true); //Positive integer.
	let valueB = this.slots[4].getData().getValueInR(0, 100, true, true); //Positive integer.
	if (port != null && port > 0 && port <= this.numberOfPorts) {
		device.setTriLed(mem.requestStatus, port, valueR, valueG, valueB);
		return new ExecutionStatusRunning();
	} else {
		this.displayError("Invalid port number");
		return new ExecutionStatusError(); // Invalid port, exit early
	}
};
/* Waits for the request to finish. */
B_DeviceWithPortsTriLed.prototype.updateAction = function() {
	if(this.runMem.requestStatus.finished){
		if(this.runMem.requestStatus.error){
			let status = this.runMem.requestStatus;
			this.displayError(this.deviceClass.getNotConnectedMessage(status.code, status.result));
			return new ExecutionStatusError();
		}
		return new ExecutionStatusDone();
	}
	else{
		return new ExecutionStatusRunning();
	}
};
<|endoftext|>


<commit_before>

import Hapi from 'hapi';
import Inert from 'inert';
import fs from 'fs';
import path from 'path';

import dealScss from './precompile/scss';
import dealJs from './precompile/babel';

import initServer from '../mock/index';

{{#swig}}
import {swig} from './swig';
{{/swig}}

const server = new Hapi.Server({
    connections: {
        state: {
            ignoreErrors: true
        }
    }
});

// regist the static file and directory handlers
server.register(Inert);

server.connection({
    host: '0.0.0.0',
    port: {{localPort}}
});

// serve all static files
server.route({
    path: '/{param*}',
    method: 'GET',
    handler: {
        directory: {
            path: './',
            listing: true
        }
    }
});

// serve the static files need precompiled
server.route({
    path: '/app/{param*}',
    method: 'GET',
    handler: (request, reply) => {

        let filePath = 'app/' + request.params.param
        let length = filePath.length;

        if (filePath.slice(length - 4, length) === '.css') {
            filePath = filePath.replace('.css', 'scss');
        }

        try {
            let fileStat = fs.statSync(filePath);

            if (fileStat.isDirectory()) {
                reply.continue();
            }
            else {
                switch(path.extname(filePath)){
                    case 'js':
                        dealJs(filePath, false, (result) => {
                            reply(result)
                                .type('text/javascript');
                        });
                        break;
                    case 'scss':
                        dealScss(filePath, false, (result) => {
                            reply(result)
                                .type('text/css');
                        });
                        break;
                    default:
                        reply.continue();
                        break;
                }
            }

        }
        catch (e) {
            reply.continue();
        }
    }
});

// regist other request
initServer(server);

server.start(
    (err) => {
        if (err) {
            console.log(err);
        }
        console.log('server started at ', server.info.uri);
    }
);

<commit_msg>reply file<commit_after>

import Hapi from 'hapi';
import Inert from 'inert';
import fs from 'fs';
import path from 'path';

import dealScss from './precompile/scss';
import dealJs from './precompile/babel';

import initServer from '../mock/index';

{{#swig}}
import {swig} from './swig';
{{/swig}}

const server = new Hapi.Server({
    connections: {
        state: {
            ignoreErrors: true
        }
    }
});

// regist the static file and directory handlers
server.register(Inert);

server.connection({
    host: '0.0.0.0',
    port: {{localPort}}
});

// serve all static files
server.route({
    path: '/{param*}',
    method: 'GET',
    handler: {
        directory: {
            path: './',
            listing: true
        }
    }
});

// serve the static files need precompiled
server.route({
    path: '/app/{param*}',
    method: 'GET',
    handler: (request, reply) => {

        let filePath = 'app/' + request.params.param
        let length = filePath.length;

        if (filePath.slice(length - 4, length) === '.css') {
            filePath = filePath.replace('.css', '.scss');
        }

        try {
            let fileStat = fs.statSync(filePath);

            if (fileStat.isDirectory()) {
                reply.continue();
            }
            else {
                switch(path.extname(filePath)){
                    case '.js':
                        dealJs(filePath, false, (result) => {
                            reply(result)
                                .type('text/javascript');
                        });
                        break;
                    case '.scss':
                        dealScss(filePath, false, (result) => {
                            reply(result)
                                .type('text/css');
                        });
                        break;
                    default:
                        reply.file(filePath);
                        break;
                }
            }

        }
        catch (e) {
            reply.continue();
        }
    }
});

// regist other request
initServer(server);

server.start(
    (err) => {
        if (err) {
            console.log(err);
        }
        console.log('server started at ', server.info.uri);
    }
);

<|endoftext|>


<commit_before>/**
 * @class  	Animator
 * @author 	Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

var Matrix = require('T/matrix');

function noop() {}

function simpleFromTo(view, a, b, callback) {
	view.applyProperties(a);
	_.defer(function(){
		view.animate(b, _.isFunction(callback) ? callback : noop);
	});
}

/**
 * @method fadeIn
 */
exports.fadeIn = function(opt) {
	_.defaults(opt, {
		duration: 400
	});

	return simpleFromTo(opt.view,
	{ opacity: 0 },
	{ opacity: 1, duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeOut
 */
exports.fadeOut = function(opt) {
	_.defaults(opt, {
		duration: 400
	});

	return  simpleFromTo(opt.view,
	{ opacity: 1 },
	{ opacity: 0, duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeInUp
 */
exports.fadeInUp = function(opt) {
	_.defaults(opt, {
		duration: 5000,
		offset: 50
	});

	return simpleFromTo(opt.view,
	{ opacity: 0, transform: Ti.UI.create2DMatrix().translate(0, -opt.offset) },
	{ opacity: 1, transform: Ti.UI.create2DMatrix(), duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeInDown
 */
exports.fadeInLeft = function(opt) {
	_.defaults(opt, {
		duration: 400,
		offset: 50
	});

	return simpleFromTo(opt.view,
	{ opacity: 0, transform: Ti.UI.create2DMatrix().translate(-opt.offset, 0) },
	{ opacity: 1, transform: Ti.UI.create2DMatrix(), duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeInBottom
 */
exports.fadeInBottom = function(opt) {
	_.defaults(opt, {
		duration: 400,
		offset: 50
	});

	return simpleFromTo(opt.view,
	{ opacity: 0, transform: Ti.UI.create2DMatrix().translate(0, opt.offset) },
	{ opacity: 1, transform: Ti.UI.create2DMatrix(), duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeInRight
 */
exports.fadeInRight = function(opt) {
	_.defaults(opt, {
		duration: 400,
		offset: 50
	});

	return simpleFromTo(opt.view,
	{ opacity: 0, transform: Ti.UI.create2DMatrix().translate(opt.offset, 0) },
	{ opacity: 1, transform: Ti.UI.create2DMatrix(), duration: opt.duration },
	opt.callback);
};

/**
 * @method upAndDown
 * @return {Function}
 */
exports.upAndDown = function(opt) {
	var self = {};
	var run = true;

	self.stop = function() {
		run = false;
	};

	_.defaults(opt, {
		duration: 1000,
		y: 10
	});

	var index = 0;
	(function loop() {
		if (run === false) return;

		index = (index+1) % 2;
		_.defer(function(){
			opt.view.animate({
				transform: Ti.UI.create2DMatrix().translate(0, index ? opt.y : 0),
				duration: opt.duration
			}, loop);
		});
	})();

	return self;
};

/**
 * @method fallDownForGravity
 * @return {Function}
 */
exports.fallDownForGravity = function(opt) {
	var self = {};
	var run = true;
	var timeout = null;

	self.stop = function() {
		clearTimeout(timeout);
		run = false;
	};

	_.defaults(opt, {
		friction: 0.6,
		potentialEnergy: 10,
		y: 60,
		callback: function(){}
	});

	var U = Number(opt.potentialEnergy);
	var index = -1;
	var y = null;

	(function loop() {
		if (run === false) return;

		index++;
		if (U === 0 && index % 2 === 0) {
			opt.callback();
			return;
		}

		_.defer(function() {
			if (index % 2 === 1) {
				U =  Math.floor( U - (U * opt.friction) );
				y = opt.y - ((U / opt.potentialEnergy) * opt.y);
			} else {
				y = opt.y;
			}
			timeout = setTimeout(loop, 250);
			opt.view.animate({
				duration: 250,
				curve: Titanium.UI[ "ANIMATION_CURVE_EASE_" + (index % 2 === 0 ? "IN" : "OUT") ],
				transform: Matrix.i().t(0, y).matrix
			});
		});
	})();

	return self;
};
<commit_msg>animator now use matrix, really<commit_after>/**
 * @class  	Animator
 * @author 	Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

var Matrix = require('T/matrix');

function noop() {}

function simpleFromTo(view, a, b, callback) {
	view.applyProperties(a);
	_.defer(function(){
		view.animate(b, _.isFunction(callback) ? callback : noop);
	});
}

/**
 * @method fadeIn
 */
exports.fadeIn = function(opt) {
	_.defaults(opt, {
		duration: 400
	});

	return simpleFromTo(opt.view,
	{ opacity: 0 },
	{ opacity: 1, duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeOut
 */
exports.fadeOut = function(opt) {
	_.defaults(opt, {
		duration: 400
	});

	return  simpleFromTo(opt.view,
	{ opacity: 1 },
	{ opacity: 0, duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeInUp
 */
exports.fadeInUp = function(opt) {
	_.defaults(opt, {
		duration: 5000,
		offset: 50
	});

	return simpleFromTo(opt.view,
	{ opacity: 0, transform: Matrix.i().t(0, -opt.offset) },
	{ opacity: 1, transform: Matrix.i(), duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeInDown
 */
exports.fadeInLeft = function(opt) {
	_.defaults(opt, {
		duration: 400,
		offset: 50
	});

	return simpleFromTo(opt.view,
	{ opacity: 0, transform: Matrix.i().t(-opt.offset, 0) },
	{ opacity: 1, transform: Matrix.i(), duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeInBottom
 */
exports.fadeInBottom = function(opt) {
	_.defaults(opt, {
		duration: 400,
		offset: 50
	});

	return simpleFromTo(opt.view,
	{ opacity: 0, transform: Matrix.i().t(0, opt.offset) },
	{ opacity: 1, transform: Matrix.i(), duration: opt.duration },
	opt.callback);
};

/**
 * @method fadeInRight
 */
exports.fadeInRight = function(opt) {
	_.defaults(opt, {
		duration: 400,
		offset: 50
	});

	return simpleFromTo(opt.view,
	{ opacity: 0, transform: Matrix.i().t(opt.offset, 0) },
	{ opacity: 1, transform: Matrix.i(), duration: opt.duration },
	opt.callback);
};

/**
 * @method upAndDown
 * @return {Function}
 */
exports.upAndDown = function(opt) {
	var self = {};
	var run = true;

	self.stop = function() {
		run = false;
	};

	_.defaults(opt, {
		duration: 1000,
		y: 10
	});

	var index = 0;
	(function loop() {
		if (run === false) return;

		index = (index+1) % 2;
		_.defer(function(){
			opt.view.animate({
				transform: Matrix.i().t(0, index ? opt.y : 0),
				duration: opt.duration
			}, loop);
		});
	})();

	return self;
};

/**
 * @method fallDownForGravity
 * @return {Function}
 */
exports.fallDownForGravity = function(opt) {
	var self = {};
	var run = true;
	var timeout = null;

	self.stop = function() {
		clearTimeout(timeout);
		run = false;
	};

	_.defaults(opt, {
		friction: 0.6,
		potentialEnergy: 10,
		y: 60,
		callback: function(){}
	});

	var U = Number(opt.potentialEnergy);
	var index = -1;
	var y = null;

	(function loop() {
		if (run === false) return;

		index++;
		if (U === 0 && index % 2 === 0) {
			opt.callback();
			return;
		}

		_.defer(function() {
			if (index % 2 === 1) {
				U =  Math.floor( U - (U * opt.friction) );
				y = opt.y - ((U / opt.potentialEnergy) * opt.y);
			} else {
				y = opt.y;
			}
			timeout = setTimeout(loop, 250);
			opt.view.animate({
				duration: 250,
				curve: Titanium.UI[ "ANIMATION_CURVE_EASE_" + (index % 2 === 0 ? "IN" : "OUT") ],
				transform: Matrix.i().t(0, y).matrix
			});
		});
	})();

	return self;
};
<|endoftext|>