<commit_before>/**
 * Util method to get effect
 */
import {checkStatus} from './customEvent'

export default function (target) {
  target.prototype.isBodyMode = function () {
    return this.props.bodyMode
  }

  const makeProxy = (e) => {
    const proxy = {}
    for (const key in e) {
      if (typeof e[key] === 'function') {
        proxy[key] = e[key].bind(e)
      } else {
        proxy[key] = e[key]
      }
    }
    return proxy
  }

  const bodyListener = function (callback, options, e) {
    const {respectEffect = false, customEvent = false} = options
    const {id} = this.props

    const tip = e.target.dataset.tip
    const _for = e.target.dataset.for

    const target = e.target
    if (!!target.getAttribute('data-event') && !customEvent) {
      return
    }

    if (tip != null &&
      (!respectEffect || this.getEffect(target) === 'float') &&
      ((id == null && _for == null) || (id != null && _for === id))
    ) {
      const proxy = makeProxy(e)
      proxy.currentTarget = target
      callback(proxy)
    }
  }

  const findCustomEvents = (targetArray, dataAttribute) => {
    const events = {}
    targetArray.forEach(target => {
      const event = target.getAttribute(dataAttribute)
      if (event) event.split(' ').forEach(event => events[event] = true)
    })

    return events
  }

  target.prototype.bindBodyListener = function () {
    const { id } = this.props
    const { event, eventOff } = this.state
    const body = document.getElementsByTagName('body')[0]

    const targetArray = this.getTargetArray(id)

    const customEvents = findCustomEvents(targetArray, 'data-event')
    const customEventsOff = findCustomEvents(targetArray, 'data-event-off')

    if (event != null) customEvents[event] = true
    if (eventOff != null) customEventsOff[eventOff] = true
    for (const event of this.state.possibleCustomEvents) customEvents[event] = true
    for (const event of this.state.possibleCustomEventsOff) customEventsOff[event] = true

    this.unbindBodyListener(body)

    const listeners = this.bodyModeListeners = {
      'mouseover': bodyListener.bind(this, this.showTooltip, {}),
      'mousemove': bodyListener.bind(this, this.updateTooltip, { respectEffect: true }),
      'mouseout': bodyListener.bind(this, this.hideTooltip, {})
    }

    for (const event in customEvents) {
      listeners[event] = bodyListener.bind(this, (e) => {
        checkStatus.call(this, e.currentTarget.getAttribute('data-event-off') || eventOff, e)
      }, { customEvent: true })
    }
    for (const event in customEventsOff) {
      listeners[event] = bodyListener.bind(this, this.hideTooltip, { customEvent: true })
    }
    for (const event in listeners) {
      body.addEventListener(event, listeners[event])
    }
  }

  target.prototype.unbindBodyListener = function (body) {
    body = body || document.getElementsByTagName('body')[0]

    const listeners = this.bodyModeListeners
    for (const event in listeners) {
      body.removeEventListener(event, listeners(event))
    }
  }
}
<commit_msg>Refactor<commit_after>/**
 * Util method to get effect
 */
import {checkStatus} from './customEvent'

const makeProxy = (e) => {
  const proxy = {}
  for (const key in e) {
    if (typeof e[key] === 'function') {
      proxy[key] = e[key].bind(e)
    } else {
      proxy[key] = e[key]
    }
  }
  return proxy
}

const bodyListener = function (callback, options, e) {
  const {respectEffect = false, customEvent = false} = options
  const {id} = this.props

  const tip = e.target.dataset.tip
  const _for = e.target.dataset.for

  const target = e.target
  if (this.isCustomEvent(target) && !customEvent) {
    return
  }

  const isTargetBelongsToTooltip =
    (id == null && _for == null) || (id != null && _for === id)

  if (tip != null &&
    (!respectEffect || this.getEffect(target) === 'float') &&
    isTargetBelongsToTooltip
  ) {
    const proxy = makeProxy(e)
    proxy.currentTarget = target
    callback(proxy)
  }
}

const findCustomEvents = (targetArray, dataAttribute) => {
  const events = {}
  targetArray.forEach(target => {
    const event = target.getAttribute(dataAttribute)
    if (event) event.split(' ').forEach(event => events[event] = true)
  })

  return events
}

const getBody = () => document.getElementsByTagName('body')[0]

export default function (target) {
  target.prototype.isBodyMode = function () {
    return this.props.bodyMode
  }

  target.prototype.bindBodyListener = function () {
    const { id } = this.props
    const { event, eventOff } = this.state
    const targetArray = this.getTargetArray(id)
    const body = getBody()

    const customEvents = findCustomEvents(targetArray, 'data-event')
    const customEventsOff = findCustomEvents(targetArray, 'data-event-off')

    if (event != null) customEvents[event] = true
    if (eventOff != null) customEventsOff[eventOff] = true
    for (const event of this.state.possibleCustomEvents) customEvents[event] = true
    for (const event of this.state.possibleCustomEventsOff) customEventsOff[event] = true

    this.unbindBodyListener(body)

    const listeners = this.bodyModeListeners = {
      'mouseover': bodyListener.bind(this, this.showTooltip, {}),
      'mousemove': bodyListener.bind(this, this.updateTooltip, { respectEffect: true }),
      'mouseout': bodyListener.bind(this, this.hideTooltip, {})
    }

    for (const event in customEvents) {
      listeners[event] = bodyListener.bind(this, (e) => {
        const targetEventOff = e.currentTarget.getAttribute('data-event-off') || eventOff
        checkStatus.call(this, targetEventOff, e)
      }, { customEvent: true })
    }
    for (const event in customEventsOff) {
      listeners[event] = bodyListener.bind(this, this.hideTooltip, { customEvent: true })
    }
    for (const event in listeners) {
      body.addEventListener(event, listeners[event])
    }
  }

  target.prototype.unbindBodyListener = function (body) {
    body = body || getBody()

    const listeners = this.bodyModeListeners
    for (const event in listeners) {
      body.removeEventListener(event, listeners(event))
    }
  }
}
<|endoftext|>


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

(function() {
  // Copy X.AbstractDAO methods in Array prototype

  var pmap = {};
  for ( var key in AbstractDAO.methods ) {
    pmap[AbstractDAO.methods[key].name] = AbstractDAO.methods[key].code;
  }

  defineProperties(Array.prototype, pmap);
})();

defineLazyProperty(Array.prototype, 'daoListeners_', function() {
  return {
    value: [],
    configurable: true
  };
});

var ArraySink = {
  __proto__: Array.prototype,
  put: function(obj, sink) {
    this.push(obj);
    this.notify_('put', arguments);
    sink && sink.put && sink.put(obj);
  },
  clone: function() {
    return this.slice(0).sink;
  },
  deepClone: function() {
    var a = this.slice(0);
    for ( var i = 0 ; i < a.length ; i++ ) {
      a[i] = a[i].deepClone();
    }
    return a.sink;
  }
};

Object.defineProperty(Array.prototype, 'dao', {
  get: function() { this.__proto__ = Array.prototype; return this; },
  writeable: true
});

Object.defineProperty(Array.prototype, 'sink', {
  get: function() { this.__proto__ = ArraySink; return this; },
  writeable: true
});

defineProperties(Array.prototype, {
  listen:   AbstractDAO.getPrototype().listen,
  unlisten: AbstractDAO.getPrototype().unlisten,
  notify_:  AbstractDAO.getPrototype().notify_,
/*
  listen:   function() { },
  unlisten: function() { },
  notify_:  function() { },
*/
  // Clone this Array and remove 'v' (only 1 instance)
  // TODO: make faster by copying in one pass, without splicing
  deleteF: function(v) {
    var a = this.clone();
    for ( var i = 0 ; i < a.length ; i++ ) {
      if ( a[i] === v ) { a.splice(i, 1); break; }
    }
    return a;
  },
  // Remove 'v' from this array (only 1 instance removed)
  // return true iff the value was removed
  deleteI: function(v) {
    for ( var i = 0 ; i < this.length ; i++ ) {
      if ( this[i] === v ) { this.splice(i, 1); return true; }
    }
    return false;
  },
  // Clone this Array and remove first object where predicate 'p' returns true
  // TODO: make faster by copying in one pass, without splicing
  removeF: function(p) {
    var a = this.clone();
    for ( var i = 0 ; i < a.length ; i++ ) {
      if ( p.f(a[i]) ) { a.splice(i, 1); break; }
    }
    return a;
  },
  // Remove first object in this array where predicate 'p' returns true
  removeI: function(p) {
    for ( var i = 0 ; i < this.length ; i++ ) {
      if ( p.f(this[i]) ) { this.splice(i, 1); breeak; }
    }
    return this;
  },
  pushF: function(obj) {
    var a = this.clone();
    a.push(obj);
    return a;
  },
  clone: function() {
    return this.slice(0);
  },
  deepClone: function() {
    var a = this.slice(0);
    for ( var i = 0 ; i < a.length ; i++ ) {
      a[i] = a[i].deepClone();
    }
    return a;
  },
  id: function(obj) {
    return obj.id || obj.$UID;
  },
  put: function(obj, sink) {
    for ( var idx = 0; idx < this.length; idx++ ) {
      if ( this[idx].id === obj.id ) {
        this[idx] = obj;
        sink && sink.put && sink.put(obj);
        this.notify_('put', arguments);
        //        sink && sink.error && sink.error('put', obj, duplicate);
        return;
      }
    }

    this.push(obj);
    this.notify_('put', arguments);
    sink && sink.put && sink.put(obj);
  },
  find: function(query, sink) {
    if ( query.f ) {
      for ( var idx = 0 ; idx < this.length; idx++ ) {
        if ( query.f(this[idx]) ) {
          sink && sink.put && sink.put(this[idx]);
          return;
        }
      }
    } else {
      for ( var idx = 0 ; idx < this.length; idx++ ) {
        if ( this[idx].id === query ) {
          sink && sink.put && sink.put(this[idx]);
          return;
        }
      }
    }
    sink && sink.error && sink.error('find', query);
  },
  // TODO: make this faster, should stop after finding first item.
  remove: function(obj, sink) {
    if ( ! obj ) {
      sink && sink.error && sink.error('missing key');
      return;
    }
    var objId = obj.id;
    var id = (objId !== undefined && objId !== '') ? objId : obj;
    for ( var idx = 0 ; idx < this.length; idx++ ) {
      if ( this[idx].id === id ) {
        var rem = this.splice(idx,1)[0];
//        this.notify_('remove', rem);
        sink && sink.remove && sink.remove(rem[0]);
        return;
      }
    }
    sink && sink.error && sink.error('remove', obj);
  },
  removeAll: function(sink, options) {
    if ( ! options ) options = {};
    if ( !options.query ) options.query = { f: function() { return true; } };

    for (var i = 0; i < this.length; i++) {
      var obj = this[i];
      if ( options.query.f(obj) ) {
        var rem = this.splice(i,1)[0];
//        this.notify_('remove', [rem]);
        sink && sink.remove && sink.remove(rem);
        i--;
      }
    }
    sink && sink.eof && sink.eof();
    return anop();
  },
  select: function(sink, options) {
    sink = sink || [].sink;
    var hasQuery = options && ( options.query || options.order );
    var originalsink = sink;
    sink = this.decorateSink_(sink, options, false, ! hasQuery);

    // Short-circuit COUNT.
    if ( ! hasQuery && GLOBAL.CountExpr && CountExpr.isInstance(sink) ) {
      sink.count = this.length;
      return aconstant(originalsink);
    }

    var fc = this.createFlowControl_();
    var start = Math.max(0, hasQuery ? 0 : ( options && options.skip ) || 0);
    var end = hasQuery ?
      this.length :
      Math.min(this.length, start + ( ( options && options.limit ) || this.length));
    for ( var i = start ; i < end ; i++ ) {
      sink.put(this[i], null, fc);
      if ( fc.stopped ) break;
      if ( fc.errorEvt ) {
        sink.error && sink.error(fc.errorEvt);
        return aconstant(originalsink, fc.errorEvt);
      }
    }

    sink.eof && sink.eof();

    return aconstant(originalsink);
  }
});
<commit_msg>ArrayDAO: find() and select():  Clone entities before putting them to sink<commit_after>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function() {
  // Copy X.AbstractDAO methods in Array prototype

  var pmap = {};
  for ( var key in AbstractDAO.methods ) {
    pmap[AbstractDAO.methods[key].name] = AbstractDAO.methods[key].code;
  }

  defineProperties(Array.prototype, pmap);
})();

defineLazyProperty(Array.prototype, 'daoListeners_', function() {
  return {
    value: [],
    configurable: true
  };
});

var ArraySink = {
  __proto__: Array.prototype,
  put: function(obj, sink) {
    this.push(obj);
    this.notify_('put', arguments);
    sink && sink.put && sink.put(obj);
  },
  clone: function() {
    return this.slice(0).sink;
  },
  deepClone: function() {
    var a = this.slice(0);
    for ( var i = 0 ; i < a.length ; i++ ) {
      a[i] = a[i].deepClone();
    }
    return a.sink;
  }
};

Object.defineProperty(Array.prototype, 'dao', {
  get: function() { this.__proto__ = Array.prototype; return this; },
  writeable: true
});

Object.defineProperty(Array.prototype, 'sink', {
  get: function() { this.__proto__ = ArraySink; return this; },
  writeable: true
});

defineProperties(Array.prototype, {
  listen:   AbstractDAO.getPrototype().listen,
  unlisten: AbstractDAO.getPrototype().unlisten,
  notify_:  AbstractDAO.getPrototype().notify_,
/*
  listen:   function() { },
  unlisten: function() { },
  notify_:  function() { },
*/
  // Clone this Array and remove 'v' (only 1 instance)
  // TODO: make faster by copying in one pass, without splicing
  deleteF: function(v) {
    var a = this.clone();
    for ( var i = 0 ; i < a.length ; i++ ) {
      if ( a[i] === v ) { a.splice(i, 1); break; }
    }
    return a;
  },
  // Remove 'v' from this array (only 1 instance removed)
  // return true iff the value was removed
  deleteI: function(v) {
    for ( var i = 0 ; i < this.length ; i++ ) {
      if ( this[i] === v ) { this.splice(i, 1); return true; }
    }
    return false;
  },
  // Clone this Array and remove first object where predicate 'p' returns true
  // TODO: make faster by copying in one pass, without splicing
  removeF: function(p) {
    var a = this.clone();
    for ( var i = 0 ; i < a.length ; i++ ) {
      if ( p.f(a[i]) ) { a.splice(i, 1); break; }
    }
    return a;
  },
  // Remove first object in this array where predicate 'p' returns true
  removeI: function(p) {
    for ( var i = 0 ; i < this.length ; i++ ) {
      if ( p.f(this[i]) ) { this.splice(i, 1); breeak; }
    }
    return this;
  },
  pushF: function(obj) {
    var a = this.clone();
    a.push(obj);
    return a;
  },
  clone: function() {
    return this.slice(0);
  },
  deepClone: function() {
    var a = this.slice(0);
    for ( var i = 0 ; i < a.length ; i++ ) {
      a[i] = a[i].deepClone();
    }
    return a;
  },
  id: function(obj) {
    return obj.id || obj.$UID;
  },
  put: function(obj, sink) {
    for ( var idx = 0; idx < this.length; idx++ ) {
      if ( this[idx].id === obj.id ) {
        this[idx] = obj;
        sink && sink.put && sink.put(obj);
        this.notify_('put', arguments);
        //        sink && sink.error && sink.error('put', obj, duplicate);
        return;
      }
    }

    this.push(obj);
    this.notify_('put', arguments);
    sink && sink.put && sink.put(obj);
  },
  find: function(query, sink) {
    if ( query.f ) {
      for ( var idx = 0 ; idx < this.length; idx++ ) {
        if ( query.f(this[idx]) ) {
          sink && sink.put && sink.put(this[idx].clone());
          return;
        }
      }
    } else {
      for ( var idx = 0 ; idx < this.length; idx++ ) {
        if ( this[idx].id === query ) {
          sink && sink.put && sink.put(this[idx].clone());
          return;
        }
      }
    }
    sink && sink.error && sink.error('find', query);
  },
  // TODO: make this faster, should stop after finding first item.
  remove: function(obj, sink) {
    if ( ! obj ) {
      sink && sink.error && sink.error('missing key');
      return;
    }
    var objId = obj.id;
    var id = (objId !== undefined && objId !== '') ? objId : obj;
    for ( var idx = 0 ; idx < this.length; idx++ ) {
      if ( this[idx].id === id ) {
        var rem = this.splice(idx,1)[0];
//        this.notify_('remove', rem);
        sink && sink.remove && sink.remove(rem[0]);
        return;
      }
    }
    sink && sink.error && sink.error('remove', obj);
  },
  removeAll: function(sink, options) {
    if ( ! options ) options = {};
    if ( !options.query ) options.query = { f: function() { return true; } };

    for (var i = 0; i < this.length; i++) {
      var obj = this[i];
      if ( options.query.f(obj) ) {
        var rem = this.splice(i,1)[0];
//        this.notify_('remove', [rem]);
        sink && sink.remove && sink.remove(rem);
        i--;
      }
    }
    sink && sink.eof && sink.eof();
    return anop();
  },
  select: function(sink, options) {
    sink = sink || [].sink;
    var hasQuery = options && ( options.query || options.order );
    var originalsink = sink;
    sink = this.decorateSink_(sink, options, false, ! hasQuery);

    // Short-circuit COUNT.
    if ( ! hasQuery && GLOBAL.CountExpr && CountExpr.isInstance(sink) ) {
      sink.count = this.length;
      return aconstant(originalsink);
    }

    var fc = this.createFlowControl_();
    var start = Math.max(0, hasQuery ? 0 : ( options && options.skip ) || 0);
    var end = hasQuery ?
      this.length :
      Math.min(this.length, start + ( ( options && options.limit ) || this.length));
    for ( var i = start ; i < end ; i++ ) {
      sink.put(this[i].clone(), null, fc);
      if ( fc.stopped ) break;
      if ( fc.errorEvt ) {
        sink.error && sink.error(fc.errorEvt);
        return aconstant(originalsink, fc.errorEvt);
      }
    }

    sink.eof && sink.eof();

    return aconstant(originalsink);
  }
});
<|endoftext|>


<commit_before>define([ "util/assert", "core/core", "core/tasync", "util/jjv" ], function(ASSERT, Core, TASYNC, JsonValidator) {
    "use strict";

    // ----------------- CoreType -----------------

    var MetaCore = function(oldcore) {
        // copy all operations
        var core = {};
        for ( var key in oldcore) {
            core[key] = oldcore[key];
        }

        var sameNode = function(nodeA,nodeB){
            if(core.getPath(nodeA) === core.getPath(nodeB)){
                return true;
            }
            return false;
        };

        var realNode = function(node){ //TODO we have to make some more sophisticated distinction
            if(core.getPath(node).indexOf('_') !== -1){
                return false;
            }
            return true;
        };

        var MetaNode = function(node){
            return core.getChild(node,"_meta");
        };
        var MetaChildrenNode = function(node){
            return core.getChild(MetaNode(node),"children");
        };
        var MetaPointerNode = function(node,name){
            var meta = MetaNode(node),
                pointerNames = core.getPointerNames(meta) || [];
            if(pointerNames.indexOf(name) !== -1){
                return core.getChild(meta,"_p_"+name);
            }
            return null;
        };

        //now the additional functions
        core.isTypeOf = function(node, typeNode){
            if(!realNode(node)){
                return false;
            }
            while(node){
                if(sameNode(node,typeNode)){
                    return true;
                }
                node = core.getBase(node);
            }
            return false;
        };

        core.isValidChildOf = function(node,parentNode){
            if(!realNode(node)){
                return true;
            }
            var validChildTypePaths = core.getMemberPaths(MetaChildrenNode(parentNode),"items") || [];
            while(node){
                if(validChildTypePaths.indexOf(core.getPath(node)) !== -1){
                    return true;
                }
                node = core.getBase(node);
            }
            return false;
        };

        core.getValidPointerNames = function(node){
            var validNames = core.getPointerNames(MetaNode(node)) || [],
                i,
                validPointerNames = [],
                metaPointerNode;

            for(i=0;i<validNames.length;i++){
                metaPointerNode = MetaPointerNode(node,validNames[i]);
                if(metaPointerNode.max === 1){ //TODO specify what makes something a pointer and what a set??? - can you extend a pointer to a set????
                    validPointerNames.push(validNames[i]);
                }
            }

            return validPointerNames;
        };

        core.getValidSetNames = function(node){
            var validNames = core.getPointerNames(MetaNode(node)) || [],
                i,
                validSetNames = [],
                metaPointerNode;

            for(i=0;i<validNames.length;i++){
                metaPointerNode = MetaPointerNode(node,validNames[i]);
                if(metaPointerNode.max === undefined || metaPointerNode.max === -1 || metaPointerNode > 1){ //TODO specify what makes something a pointer and what a set??? - can you extend a pointer to a set????
                    validSetNames.push(validNames[i]);
                }
            }

            return validSetNames;
        };

        core.isValidTargetOf = function(node,source,name){
            if(!realNode(source) || node === null){ //we position ourselves over the null-pointer layer
                return true;
            }
            var pointerMetaNode = MetaPointerNode(source,name);
            if(pointerMetaNode){
                var validTargetTypePaths = core.getMemberPaths(pointerMetaNode,"items") || [];
                while(node){
                    if(validTargetTypePaths.indexOf(core.getPath(node)) !== -1){
                        return true;
                    }
                    node = core.getBase(node);
                }
            }
            return false;
        };

        core.getValidAttributeNames = function(node){
            var names = [];
            if(realNode(node)){
                names = core.getAttributeNames(MetaNode(node)) || [];
            }
            return names;
        };

        core.isValidAttributeValueOf = function(node,name,value){
            //currently it only checks the name and the type
            if(!realNode(node)){
                return true;
            }
            if(core.getValidAttributeNames(node).indexOf(name) === -1){
                return false;
            }
            var meta = core.getAttribute(MetaNode(node),name);
            switch(meta.type){
                case "boolean":
                    if(value === true || value === false){
                        return true;
                    }
                    break;
                case "string":
                case "asset":
                    if(typeof value === 'string'){
                        return true;
                    }
                    break;
                case "integer":
                    if(!isNaN(parseInt(value)) && parseFloat(value) === parseInt(value)) {
                        return true;
                    }
                    break;
                case "float":
                    if(!isNaN(parseFloat(value))) {
                        return true;
                    }
                    break;
            }
            return false;
        };

        var MetaAspectNode = function(node,name){
            var aspectNode = core.getChild(MetaNode(node),'aspects'),
                names = core.getPointerNames(aspectNode) ||[];
            if(names.indexOf(name) !== -1){
                return core.getChild(aspectNode,"_a_"+name);
            }
            return null;
        };

        core.getValidAspectNames = function(node){
            return core.getPointerNames(core.getChild(MetaNode(node),'aspects')) ||[];
        };

        //additional meta functions for getting meta definitions
        core.getJsonMeta = function(node){
            var meta = {children:{},attributes:{},pointers:{},aspects:{}},
                tempNode,
                names,
                pointer,
                i,j;

            //fill children part
            tempNode = MetaChildrenNode(node);

            meta.children.minItems = [];
            meta.children.maxItems = [];
            meta.children.items = core.getMemberPaths(tempNode,"items");
            for(i=0;i<meta.children.items.length;i++){
                meta.children.minItems.push(core.getMemberAttribute(tempNode,"items",meta.children.items[i],"min") || -1);
                meta.children.maxItems.push(core.getMemberAttribute(tempNode,"items",meta.children.items[i],"max") || -1);
            }
            meta.children.min = core.getAttribute(tempNode,"min");
            meta.children.max = core.getAttribute(tempNode,"max");

            //attributes
            names = core.getValidAttributeNames(node);
            for(i=0;i<names.length;i++){
                meta.attributes[names[i]] = core.getAttribute(MetaNode(node),names[i]);
            }

            //pointers
            names = core.getPointerNames(MetaNode(node));
            for(i=0;i<names.length;i++){
                tempNode = MetaPointerNode(node,names[i]);
                pointer = {};

                pointer.items = core.getMemberPaths(tempNode,"items");
                pointer.min = core.getAttribute(tempNode,"min");
                pointer.max = core.getAttribute(tempNode,"max");
                pointer.minItems = [];
                pointer.maxItems = [];

                for(var j=0;j<pointer.items.length;j++){
                    pointer.minItems.push(core.getMemberAttribute(tempNode,"items",pointer.items[j],"min") || -1);
                    pointer.maxItems.push(core.getMemberAttribute(tempNode,"items",pointer.items[j],"max") || -1);

                }

                meta.pointers[names[i]] = pointer;
            }

            //aspects
            names = core.getValidAspectNames(node);

            for(i=0;i<names.length;i++){
                tempNode = MetaAspectNode(node,names[i]);
                meta.aspects[names[i]] = core.getMemberPaths(tempNode,'items') || [];
            }

            return meta;
        };

        var isEmptyObject = function(object){
            if(Object.keys(object).length === 0){
                return true;
            }
            return false;
        };
        var getObjectDiff = function(bigger,smaller){
            var diff = {},
                names, i,temp;
            if(smaller === null || smaller === undefined || isEmptyObject(smaller)){
                if(bigger === null || bigger === undefined){
                    return {};
                }
                return bigger;
            }

            names = Object.keys(bigger);
            for(i=0;i<names.length;i++){
                if(smaller[names[i]] === undefined){
                    //extra attribute of the bigger object
                    if(bigger[names[i]] !== undefined){
                        diff[names[i]] = bigger[names[i]];
                    } //if both are undefined, then they are equal :)
                } else {
                    //they share the attribute
                    if(typeof smaller[names[i]] === 'object'){
                        if(typeof bigger[names[i]] === 'object'){
                            temp = getObjectDiff(bigger[names[i]],smaller[names[i]]);
                            if(!isEmptyObject(temp)){
                                diff[names[i]] = temp;
                            }
                        } else {
                            diff[names[i]] = bigger[names[i]];
                        }
                    } else {
                        if(JSON.stringify(smaller[names[i]]) !== JSON.stringify(bigger[names[i]])){
                            diff[names[i]] = bigger[names[i]];
                        }
                    }
                }
            }

            return diff;

        };

        core.getOwnJsonMeta = function(node){
            var base = core.getBase(node),
                baseMeta = base ? core.getJsonMeta(base) : {},
                meta = core.getJsonMeta(node);

            return getObjectDiff(meta,baseMeta);
        };

        //now the overridden functions to check as many meta rules as possible before making the actual modification
        core.setAttribute = function(node,name,value){
            if(core.isValidAttributeValueOf(node,name,value)){
                return oldcore.setAttribute(node,name,value);
            } else {
                return new Error('meta validation failed');
            }
        };

        core.createNode = function(parameters){
            //TODO currently we allow the creation of baseless child for every node - because we use this functionality and it cannot be used by a simple user
            parameters = parameters || {};

            if(!parameters.base || !parameters.parent || core.isValidChildOf(parameters.base,parameters.parent)){
                return oldcore.createNode(parameters);
            } else {
                return null; //TODO how to give back an error in this case??
            }
        };

        core.setPointer = function(node,name,target){
            if(core.isValidTargetOf(target,node,name)){
                return oldcore.setPointer(node,name,target);
            } else {
                return new Error('meta validation failed');
            }
        };

        return core;

    };

    return MetaCore;
});
<commit_msg>any kind of check have been removed from core...<commit_after>define([ "util/assert", "core/core", "core/tasync", "util/jjv" ], function(ASSERT, Core, TASYNC, JsonValidator) {
    "use strict";

    // ----------------- CoreType -----------------

    var MetaCore = function(oldcore) {
        // copy all operations
        var core = {};
        for ( var key in oldcore) {
            core[key] = oldcore[key];
        }

        var sameNode = function(nodeA,nodeB){
            if(core.getPath(nodeA) === core.getPath(nodeB)){
                return true;
            }
            return false;
        };

        var realNode = function(node){ //TODO we have to make some more sophisticated distinction
            if(core.getPath(node).indexOf('_') !== -1){
                return false;
            }
            return true;
        };

        var MetaNode = function(node){
            return core.getChild(node,"_meta");
        };
        var MetaChildrenNode = function(node){
            return core.getChild(MetaNode(node),"children");
        };
        var MetaPointerNode = function(node,name){
            var meta = MetaNode(node),
                pointerNames = core.getPointerNames(meta) || [];
            if(pointerNames.indexOf(name) !== -1){
                return core.getChild(meta,"_p_"+name);
            }
            return null;
        };

        //now the additional functions
        core.isTypeOf = function(node, typeNode){
            if(!realNode(node)){
                return false;
            }
            while(node){
                if(sameNode(node,typeNode)){
                    return true;
                }
                node = core.getBase(node);
            }
            return false;
        };

        core.isValidChildOf = function(node,parentNode){
            if(!realNode(node)){
                return true;
            }
            var validChildTypePaths = core.getMemberPaths(MetaChildrenNode(parentNode),"items") || [];
            while(node){
                if(validChildTypePaths.indexOf(core.getPath(node)) !== -1){
                    return true;
                }
                node = core.getBase(node);
            }
            return false;
        };

        core.getValidPointerNames = function(node){
            var validNames = core.getPointerNames(MetaNode(node)) || [],
                i,
                validPointerNames = [],
                metaPointerNode;

            for(i=0;i<validNames.length;i++){
                metaPointerNode = MetaPointerNode(node,validNames[i]);
                if(metaPointerNode.max === 1){ //TODO specify what makes something a pointer and what a set??? - can you extend a pointer to a set????
                    validPointerNames.push(validNames[i]);
                }
            }

            return validPointerNames;
        };

        core.getValidSetNames = function(node){
            var validNames = core.getPointerNames(MetaNode(node)) || [],
                i,
                validSetNames = [],
                metaPointerNode;

            for(i=0;i<validNames.length;i++){
                metaPointerNode = MetaPointerNode(node,validNames[i]);
                if(metaPointerNode.max === undefined || metaPointerNode.max === -1 || metaPointerNode > 1){ //TODO specify what makes something a pointer and what a set??? - can you extend a pointer to a set????
                    validSetNames.push(validNames[i]);
                }
            }

            return validSetNames;
        };

        core.isValidTargetOf = function(node,source,name){
            if(!realNode(source) || node === null){ //we position ourselves over the null-pointer layer
                return true;
            }
            var pointerMetaNode = MetaPointerNode(source,name);
            if(pointerMetaNode){
                var validTargetTypePaths = core.getMemberPaths(pointerMetaNode,"items") || [];
                while(node){
                    if(validTargetTypePaths.indexOf(core.getPath(node)) !== -1){
                        return true;
                    }
                    node = core.getBase(node);
                }
            }
            return false;
        };

        core.getValidAttributeNames = function(node){
            var names = [];
            if(realNode(node)){
                names = core.getAttributeNames(MetaNode(node)) || [];
            }
            return names;
        };

        core.isValidAttributeValueOf = function(node,name,value){
            //currently it only checks the name and the type
            if(!realNode(node)){
                return true;
            }
            if(core.getValidAttributeNames(node).indexOf(name) === -1){
                return false;
            }
            var meta = core.getAttribute(MetaNode(node),name);
            switch(meta.type){
                case "boolean":
                    if(value === true || value === false){
                        return true;
                    }
                    break;
                case "string":
                case "asset":
                    if(typeof value === 'string'){
                        return true;
                    }
                    break;
                case "integer":
                    if(!isNaN(parseInt(value)) && parseFloat(value) === parseInt(value)) {
                        return true;
                    }
                    break;
                case "float":
                    if(!isNaN(parseFloat(value))) {
                        return true;
                    }
                    break;
            }
            return false;
        };

        var MetaAspectNode = function(node,name){
            var aspectNode = core.getChild(MetaNode(node),'aspects'),
                names = core.getPointerNames(aspectNode) ||[];
            if(names.indexOf(name) !== -1){
                return core.getChild(aspectNode,"_a_"+name);
            }
            return null;
        };

        core.getValidAspectNames = function(node){
            return core.getPointerNames(core.getChild(MetaNode(node),'aspects')) ||[];
        };

        //additional meta functions for getting meta definitions
        core.getJsonMeta = function(node){
            var meta = {children:{},attributes:{},pointers:{},aspects:{}},
                tempNode,
                names,
                pointer,
                i,j;

            //fill children part
            tempNode = MetaChildrenNode(node);

            meta.children.minItems = [];
            meta.children.maxItems = [];
            meta.children.items = core.getMemberPaths(tempNode,"items");
            for(i=0;i<meta.children.items.length;i++){
                meta.children.minItems.push(core.getMemberAttribute(tempNode,"items",meta.children.items[i],"min") || -1);
                meta.children.maxItems.push(core.getMemberAttribute(tempNode,"items",meta.children.items[i],"max") || -1);
            }
            meta.children.min = core.getAttribute(tempNode,"min");
            meta.children.max = core.getAttribute(tempNode,"max");

            //attributes
            names = core.getValidAttributeNames(node);
            for(i=0;i<names.length;i++){
                meta.attributes[names[i]] = core.getAttribute(MetaNode(node),names[i]);
            }

            //pointers
            names = core.getPointerNames(MetaNode(node));
            for(i=0;i<names.length;i++){
                tempNode = MetaPointerNode(node,names[i]);
                pointer = {};

                pointer.items = core.getMemberPaths(tempNode,"items");
                pointer.min = core.getAttribute(tempNode,"min");
                pointer.max = core.getAttribute(tempNode,"max");
                pointer.minItems = [];
                pointer.maxItems = [];

                for(var j=0;j<pointer.items.length;j++){
                    pointer.minItems.push(core.getMemberAttribute(tempNode,"items",pointer.items[j],"min") || -1);
                    pointer.maxItems.push(core.getMemberAttribute(tempNode,"items",pointer.items[j],"max") || -1);

                }

                meta.pointers[names[i]] = pointer;
            }

            //aspects
            names = core.getValidAspectNames(node);

            for(i=0;i<names.length;i++){
                tempNode = MetaAspectNode(node,names[i]);
                meta.aspects[names[i]] = core.getMemberPaths(tempNode,'items') || [];
            }

            return meta;
        };

        var isEmptyObject = function(object){
            if(Object.keys(object).length === 0){
                return true;
            }
            return false;
        };
        var getObjectDiff = function(bigger,smaller){
            var diff = {},
                names, i,temp;
            if(smaller === null || smaller === undefined || isEmptyObject(smaller)){
                if(bigger === null || bigger === undefined){
                    return {};
                }
                return bigger;
            }

            names = Object.keys(bigger);
            for(i=0;i<names.length;i++){
                if(smaller[names[i]] === undefined){
                    //extra attribute of the bigger object
                    if(bigger[names[i]] !== undefined){
                        diff[names[i]] = bigger[names[i]];
                    } //if both are undefined, then they are equal :)
                } else {
                    //they share the attribute
                    if(typeof smaller[names[i]] === 'object'){
                        if(typeof bigger[names[i]] === 'object'){
                            temp = getObjectDiff(bigger[names[i]],smaller[names[i]]);
                            if(!isEmptyObject(temp)){
                                diff[names[i]] = temp;
                            }
                        } else {
                            diff[names[i]] = bigger[names[i]];
                        }
                    } else {
                        if(JSON.stringify(smaller[names[i]]) !== JSON.stringify(bigger[names[i]])){
                            diff[names[i]] = bigger[names[i]];
                        }
                    }
                }
            }

            return diff;

        };

        core.getOwnJsonMeta = function(node){
            var base = core.getBase(node),
                baseMeta = base ? core.getJsonMeta(base) : {},
                meta = core.getJsonMeta(node);

            return getObjectDiff(meta,baseMeta);
        };

        return core;

    };

    return MetaCore;
});
<|endoftext|>


<commit_before>var tc = tc || {};
tc.gam = tc.gam || {};
tc.gam.project_widgets = tc.gam.project_widgets || {};

tc.gam.project_widgets.inkind_form = function(options) {
  tc.util.log('project.inkind_form');
  var dom = options.dom,
      $window = tc.jQ(window),
      cached_events = [],
      self = {};

  /**
   * Function: initMerlin
   * Initialize the merlin object for validation of the modal dialog.
   */
  var initMerlin = function(need) {
      var merlin;
      need = need || {}; //So we don't have to check for null all the time

      //We are using merlin only for the built-in validation in this case.
      merlin =  new tc.merlin(options.app, {
          name:'inkind_form',
          dom:tc.jQ('.add-need.merlin'),
          next_button:tc.jQ('a.need-submit'),
          first_step:'inkind_form',
          use_hashchange:false,
          data: {
            type:null,
            request:null,
            quantity:null,
            description:null,
            project_id:null,
            event_id:null
          },
          steps: {
              'inkind_form': {
                  selector: '.step.add-need-step',
                  next_step:'need-submit',
                  inputs: {
                      'subtype': {
                        selector: 'input[name="inkind-type-radio"]:checked'
                      },
                      'quantity': {
                          selector: '#inkind-quantity',
                          validators: ['required', 'numeric'],
                          hint:'Qty'
                      },
                      'request': {
                          selector: '#inkind-request',
                          validators: ['required', 'max-100'],
                          hint:'What you need - rakes, truck, etc'
                      },
                      'description': {
                        selector: '#inkind-desc',
                        validators: ['required', 'max-200'],
                        hint:'Write a brief description of why you need this',
                        counter:{
                          selector:'.charlimit.title',
                          limit:200
                        }
                      },
                      'event_link': {
                        selector: '#inkind-event-list',
                        validators: function(merlinInput, $element, step, onSubmit) {
                          //Always valid, but change the style to show selected vs default
                          var $ddSelectContainer = $element.next('.ddSelectContainer'),
                              $ddSelect = $ddSelectContainer.find('.ddSelect');

                          $ddSelect.removeClass('valid');

                          if ($ddSelectContainer.hasClass('ddNoDefault')
                            || ($element.val() !== '' && $element.val() !== $element.data('default'))) {
                            $ddSelect.addClass('has-been-focused valid');
                          }
                          return { valid: true };
                        }
                      }
                  },
                  init:function(merlin, dom) {
                    if (need.id) {
                      tc.jQ.each(merlin.current_step.inputs, function(key, input) {
                        if (input.default_val) {
                          input.dom.val(input.default_val);
                        }
                      });

                      //Special case for the radio button
                      if (need.subtype) {
                        tc.jQ('input[for="inkind-'+ need.subtype + '-check"]').click();
                      }

                      merlin.validate(true);
                    }
                  },
                  finish:function(merlin, dom) {
                    merlin.options.data = tc.jQ.extend(merlin.options.data,{
                      type:'inkind',
                      subtype:merlin.current_step.inputs.subtype.dom.val(),
                      request:merlin.current_step.inputs.request.dom.val(),
                      quantity:merlin.current_step.inputs.quantity.dom.val(),
                      description:merlin.current_step.inputs.description.dom.val(),
                      project_id:merlin.app.app_page.data.project.project_id,
                      event_id:merlin.current_step.inputs.event_link.dom.val()
                    });
                  }
              },
              'need-submit':{
                selector:'.step.submit-need-step',
                init:function(merlin,dom){
                  var need_data = merlin.options.data;

                  var success = function(data,tx,xhr){
                    if(data == 'False'){
                      return false;
                    }

                    tc.reloadProjectHash('show,needs');
                  };

                  if (need.id === undefined) {
                    tc.gam.project_data.createNeed(need_data, success);
                  } else {
                    tc.gam.project_data.updateNeed(need.id, need_data, success);
                  }
                }
              }
          }
      });

      merlin.show_step('inkind_form');
  };

  var mergeTemplate = function(need_details) {
    var new_details = tc.jQ.extend(true, {
      eventOpts: function() {
        var options = '';

        for (var i = 0; i < cached_events.length; i++) {
          if (need_details && cached_events[i].id === need_details.event_id) {
            options += '<option value="'+cached_events[i].id+'" selected>'+cached_events[i].name+'</option>';
          } else {
            options += '<option value="'+cached_events[i].id+'">'+cached_events[i].name+'</option>';
          }
        }
        return options;
      }
    }, need_details),
    $html = ich.inkind_form_tmpl(new_details);

    dom.find('.add-need-step').html($html);
  };

  var initForm = function(need_id, callback) {
    var project_id = options.app.app_page.data.project.project_id;

    tc.gam.project_data.getProjectEvents(project_id, function(events) {
      cached_events = events;

      if (need_id) {
      //We are editing an existing need
          tc.gam.project_data.getNeedDetails(need_id, function(need){
            mergeTemplate(need);
            if (callback) {
              callback();
            }
            initMerlin(need);
          });
      } else {
        mergeTemplate();
        if (callback) {
          callback();
        }
        initMerlin();
      }

    });
  };

  tc.jQ(tc).bind('show-project-widget', function(event, widgetName) {
    if (options.name === widgetName) {
      tc.util.log('&&& showing ' + options.name);

      initForm(id, function(){
          dom.show();

          dom.find('input[type=radio]').prettyCheckboxes();
          tc.initDropDown('inkind-event-list', 'Link to an event');
      });

      if((dom.offset().top - $window.scrollTop()) < 0){
        $window.scrollTop(0);
      }
    } else {
      tc.util.log('&&& hiding ' + options.name);
      dom.hide();
    }
  });

  return self;
};<commit_msg>Update the subtype widget before sending the in-kind need merlin<commit_after>var tc = tc || {};
tc.gam = tc.gam || {};
tc.gam.project_widgets = tc.gam.project_widgets || {};

tc.gam.project_widgets.inkind_form = function(options) {
  tc.util.log('project.inkind_form');
  var dom = options.dom,
      $window = tc.jQ(window),
      cached_events = [],
      self = {};

  /**
   * Function: initMerlin
   * Initialize the merlin object for validation of the modal dialog.
   */
  var initMerlin = function(need) {
      var merlin;
      need = need || {}; //So we don't have to check for null all the time

      //We are using merlin only for the built-in validation in this case.
      merlin =  new tc.merlin(options.app, {
          name:'inkind_form',
          dom:tc.jQ('.add-need.merlin'),
          next_button:tc.jQ('a.need-submit'),
          first_step:'inkind_form',
          use_hashchange:false,
          data: {
            type:null,
            request:null,
            quantity:null,
            description:null,
            project_id:null,
            event_id:null
          },
          steps: {
              'inkind_form': {
                  selector: '.step.add-need-step',
                  next_step:'need-submit',
                  inputs: {
                      'subtype': {
                        selector: 'input[name="inkind-type-radio"]:checked'
                      },
                      'quantity': {
                          selector: '#inkind-quantity',
                          validators: ['required', 'numeric'],
                          hint:'Qty'
                      },
                      'request': {
                          selector: '#inkind-request',
                          validators: ['required', 'max-100'],
                          hint:'What you need - rakes, truck, etc'
                      },
                      'description': {
                        selector: '#inkind-desc',
                        validators: ['required', 'max-200'],
                        hint:'Write a brief description of why you need this',
                        counter:{
                          selector:'.charlimit.title',
                          limit:200
                        }
                      },
                      'event_link': {
                        selector: '#inkind-event-list',
                        validators: function(merlinInput, $element, step, onSubmit) {
                          //Always valid, but change the style to show selected vs default
                          var $ddSelectContainer = $element.next('.ddSelectContainer'),
                              $ddSelect = $ddSelectContainer.find('.ddSelect');

                          $ddSelect.removeClass('valid');

                          if ($ddSelectContainer.hasClass('ddNoDefault')
                            || ($element.val() !== '' && $element.val() !== $element.data('default'))) {
                            $ddSelect.addClass('has-been-focused valid');
                          }
                          return { valid: true };
                        }
                      }
                  },
                  init:function(merlin, dom) {
                    if (need.id) {
                      tc.jQ.each(merlin.current_step.inputs, function(key, input) {
                        if (input.default_val) {
                          input.dom.val(input.default_val);
                        }
                      });

                      //Special case for the radio button
                      if (need.subtype) {
                        tc.jQ('input[for="inkind-'+ need.subtype + '-check"]').click();
                      }

                      merlin.validate(true);
                    }
                  },
                  finish:function(merlin, dom) {
                    merlin.current_step.inputs.subtype.dom = $('input[name="inkind-type-radio"]:checked');
                    merlin.options.data = tc.jQ.extend(merlin.options.data,{
                      type:'inkind',
                      subtype:merlin.current_step.inputs.subtype.dom.val(),
                      request:merlin.current_step.inputs.request.dom.val(),
                      quantity:merlin.current_step.inputs.quantity.dom.val(),
                      description:merlin.current_step.inputs.description.dom.val(),
                      project_id:merlin.app.app_page.data.project.project_id,
                      event_id:merlin.current_step.inputs.event_link.dom.val()
                    });
                  }
              },
              'need-submit':{
                selector:'.step.submit-need-step',
                init:function(merlin,dom){
                  var need_data = merlin.options.data;

                  var success = function(data,tx,xhr){
                    if(data == 'False'){
                      return false;
                    }

                    tc.reloadProjectHash('show,needs');
                  };

                  if (need.id === undefined) {
                    tc.gam.project_data.createNeed(need_data, success);
                  } else {
                    tc.gam.project_data.updateNeed(need.id, need_data, success);
                  }
                }
              }
          }
      });

      merlin.show_step('inkind_form');
  };

  var mergeTemplate = function(need_details) {
    var new_details = tc.jQ.extend(true, {
      eventOpts: function() {
        var options = '';

        for (var i = 0; i < cached_events.length; i++) {
          if (need_details && cached_events[i].id === need_details.event_id) {
            options += '<option value="'+cached_events[i].id+'" selected>'+cached_events[i].name+'</option>';
          } else {
            options += '<option value="'+cached_events[i].id+'">'+cached_events[i].name+'</option>';
          }
        }
        return options;
      }
    }, need_details),
    $html = ich.inkind_form_tmpl(new_details);

    dom.find('.add-need-step').html($html);
  };

  var initForm = function(need_id, callback) {
    var project_id = options.app.app_page.data.project.project_id;

    tc.gam.project_data.getProjectEvents(project_id, function(events) {
      cached_events = events;

      if (need_id) {
      //We are editing an existing need
          tc.gam.project_data.getNeedDetails(need_id, function(need){
            mergeTemplate(need);
            if (callback) {
              callback();
            }
            initMerlin(need);
          });
      } else {
        mergeTemplate();
        if (callback) {
          callback();
        }
        initMerlin();
      }

    });
  };

  tc.jQ(tc).bind('show-project-widget', function(event, widgetName) {
    if (options.name === widgetName) {
      tc.util.log('&&& showing ' + options.name);

      initForm(id, function(){
          dom.show();

          dom.find('input[type=radio]').prettyCheckboxes();
          tc.initDropDown('inkind-event-list', 'Link to an event');
      });

      if((dom.offset().top - $window.scrollTop()) < 0){
        $window.scrollTop(0);
      }
    } else {
      tc.util.log('&&& hiding ' + options.name);
      dom.hide();
    }
  });

  return self;
};
<|endoftext|>


<commit_before>var URLS = {
    'lm_exp': '/api/lungmapexperiments/',
    'exp': '/api/experiments/',
    'images': '/api/images/'
};

var service = angular.module('IHCApp');

service.factory(
    'LungMapExperiment',
    function ($resource) {
        return $resource(
            URLS.lm_exp + ':id',
            {},
            {}
        );
    }
).factory(
    'Experiment',
    function ($resource) {
        return $resource(
            URLS.exp + ':experiment_id',
            {},
            {}
        );
    }
).factory('Image', function ($resource) {
        return  $resource(
            URLS.images + ':id',
            {},
            {}
        );
});
<commit_msg>ng service for Probe API<commit_after>var URLS = {
    'lm_exp': '/api/lungmapexperiments/',
    'exp': '/api/experiments/',
    'probes': '/api/probes/',
    'images': '/api/images/'
};

var service = angular.module('IHCApp');

service.factory(
    'LungMapExperiment',
    function ($resource) {
        return $resource(
            URLS.lm_exp + ':id',
            {},
            {}
        );
    }
).factory(
    'Experiment',
    function ($resource) {
        return $resource(
            URLS.exp + ':experiment_id',
            {},
            {}
        );
    }
).factory(
    'Probe',
    function ($resource) {
        return $resource(
            URLS.probes + ':probe_id',
            {},
            {}
        );
    }
).factory('Image', function ($resource) {
        return  $resource(
            URLS.images + ':id',
            {},
            {}
        );
});
<|endoftext|>


<commit_before>var fs = require("q-io/fs"),
    q = require("q"),
    git = require("gift-wrapper"),
    generate = require("./generate.js"),
    exec = require('child_process').exec;

var repoDir = __dirname + "/../"
var credentialFilePath = repoDir + ".git/credentials";
var repo = git(repoDir);

function setAuthConfig(){
  var deferred = q.defer();
  exec('git config credential.helper "store --file=' + credentialFilePath + '"',
    {
        cwd: repoDir,
        encoding: "utf8",
        maxBuffer: 5000 * 1024
    },
    function(err){
      if(err){
        return deferred.reject(err);
      }

      return deferred.resolve();
    }
  );

  return deferred.promise;
};

function publishChanges(github_personal_access_token){
  return setAuthConfig()
  .then(function(){
    var content = "https://" + github_personal_access_token + ":@github.com"
    return fs.write(credentialFilePath, content);
  })
  .then(function(){
    return repo.identify({name: "zpbappi", email: "zpbappi@gmail.com"});
  })
  .then(function(){
    console.log("Adding all files...");
    return repo.add("-A");
  })
  .then(function(){
    console.log("Committing changes...");
    return repo.commit("[ci skip] automated tag and archive page generation");
  }).
  then(function(){
    console.log("Pushing changes...");
    return repo.remote_push("origin", "master");
  });
};

// the main entry point
generate()
.then(function(){
  return repo.status();
})
.then(function(status){
  console.log(status);
  if(!status.clean){
    return publishChanges(process.env.GH_TOKEN);
  }
})
.fail(console.error);
<commit_msg>added post push status logging<commit_after>var fs = require("q-io/fs"),
    q = require("q"),
    git = require("gift-wrapper"),
    generate = require("./generate.js"),
    exec = require('child_process').exec;

var repoDir = __dirname + "/../"
var credentialFilePath = repoDir + ".git/credentials";
var repo = git(repoDir);

function setAuthConfig(){
  var deferred = q.defer();
  exec('git config credential.helper "store --file=' + credentialFilePath + '"',
    {
        cwd: repoDir,
        encoding: "utf8",
        maxBuffer: 5000 * 1024
    },
    function(err){
      if(err){
        return deferred.reject(err);
      }

      return deferred.resolve();
    }
  );

  return deferred.promise;
};

function publishChanges(github_personal_access_token){
  return setAuthConfig()
  .then(function(){
    var content = "https://" + github_personal_access_token + ":@github.com"
    return fs.write(credentialFilePath, content);
  })
  .then(function(){
    return repo.identify({name: "zpbappi", email: "zpbappi@gmail.com"});
  })
  .then(function(){
    console.log("Adding all files...");
    return repo.add("-A");
  })
  .then(function(){
    console.log("Committing changes...");
    return repo.commit("[ci skip] automated tag and archive page generation");
  })
  .then(function(){
    console.log("Pushing changes...");
    return repo.remote_push("origin", "master");
  })
  .then(function(){
    console.log("Printing post push status...");
    return repo.status().then(console.log);
  })
};

// the main entry point
generate()
.then(function(){
  return repo.status();
})
.then(function(status){
  console.log(status);
  if(!status.clean){
    return publishChanges(process.env.GH_TOKEN);
  }
})
.fail(console.error);
<|endoftext|>


<commit_before>/* gloabl suggestions object */
suggestions = {};

/* months in string format */
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";

/* list of providers */
var providers = ['facebook','linkedin','github'];

var single_fields = ['name','email','website','location'];

/* array of fields attached with each suggestion */
var complex_fields = {};
complex_fields['workex'] = ['job-description','company-name','job-title','end-date','start-date'];
complex_fields['education'] = ['education-type','institution-name','education-period' ,'education-description'];
complex_fields['projects'] = ['project-title','project-url','project-start-date','project-end-date','project-description'];

/* fields for which popovers will be defined */
var popoverFields = {};
popoverFields['workex'] = ['job-title','company-name'];
popoverFields['education'] = ['education-type','institution-name'];
popoverFields['projects'] = ['project-title','project-url'];

/* adding event listeners */

$(document).ready(function(){

/* attaching click event listerners for single suggestion fields */
single_fields.forEach(function(field){

	$("body").on("click", '.'+field+'Suggestion', function(){
	     $('#'+field).val($(this).children('span:first').text()); // setting value of name input
	     $('#'+field).keyup(); // for calling validation
	});

});

var categories = ['workex','education','projects'];

/* attaching event listeners for categories */
categories.forEach(function(category){

	popoverFields[category].forEach(function(field){

	$("body").on("click", '.'+field+'Suggestion', function(event){

		var provider = $(this).data('provider');
		var key = $(this).data('ref-no');

		var target = $(event.target).parents().eq(3).children('.'+field); // target input box

		container = target.parents().eq(3); // getting 4th level parent of target element

    	complex_fields[category].forEach(function(sibling){

    		container.find('.'+sibling+':first').val(suggestions[provider+'_'+category][key][sibling]).keyup(); // seting text of sibbling fields in div; keyup called for triggering validation

		});

		var numWysiEditor = $('.html5-editor-toggle');
		for(var i=0;i<numWysiEditor.length;i++) {
			numWysiEditor[i].click();
		}

	});

});

});

});

/* popover settings for complex segment */

function popoverSettings(category,field)
{
	return {
 	placement : 'bottom',
 	title :field+' suggestions',
 	html : true,
 	trigger : 'focus',
 	content : function(){

 			var list = '';
 			providers.forEach(function(provider)
 			{

 				// if suggestion is availbale from social provider
 				if (suggestions[provider+'_'+category] && (suggestions[provider+'_'+category] != ''))
 				{
 					//console.log(suggestions[provider+'_workex']);

 					for(key in suggestions[provider+'_'+category])
 					{
 						var suggestion = suggestions[provider+'_'+category][key];

 						if(suggestion[field]!='')
 						{
 							if((field =='company-name') || category !='workex')
 						 		list+='
'+suggestion[field]+' -'+provider+'
';
 						 	else
 						 		list+='
'+suggestion[field]+' ('+suggestion['company-name']+')'+' -'+provider+'
';
 						 }

 					}

 				}

 			});

	 		if(list != '')
	 		{
	 			list='
'+list+'
';
	 			return list;
	 		}
	 		else
	 			return 'No sugestions available';
 	}

 }

};

function attachPopOvers()
{

	/* checking if social data exists */
	if(typeof social_data === 'undefined'){
	   social_data = {};
	 };

	 /* declaring suggestions for each fiels */

	 var suggestions = {};

	 suggestions['facebook_name'] = '';
	 suggestions['linkedin_name'] = '';
	 suggestions['github_name'] = '';

	 suggestions['facebook_email'] = '';
	 suggestions['linkedin_email'] = '';
	 suggestions['github_email'] = '';

	 suggestions['github_website'] = '';

	 suggestions['facebook_workex'] = [];
	 suggestions['linkedin_workex'] = [];

	 suggestions['facebook_location'] = '';
	 suggestions['github_location'] = '';

	 suggestions['facebook_education'] = [];
	 suggestions['linkedin_education'] = [];

	 suggestions['linkedin_projects'] =[];
	 suggestions['github_projects'] = [];

	 if(social_data['facebook'])
	 {
	 	if(social_data['facebook']['first_name'] && social_data['facebook']['last_name'])
		 	suggestions['facebook_name']= social_data['facebook']['first_name'] + ' ' + social_data['facebook']['last_name'];

	 	if(social_data['facebook']['email'])
	 		suggestions['facebook_email']= social_data['facebook']['email'];

	 	if(social_data['facebook']['location']) {
		 	if(social_data['facebook']['location']['name'])
		 		suggestions['facebook_location']= social_data['facebook']['location']['name'];
	 	}

		if(social_data['facebook']['work'])
		{
				var d = '';
		 		for (var key in social_data['facebook']['work']) {

			 		var workex = social_data['facebook']['work'][key];
			 		var work_info = {};

			 		work_info['job-description'] = workex['description'] || '';
			 		work_info['company-name'] = workex['employer']['name'] || '';
			 		work_info['job-title'] = workex['position']['name'] || '';
			 		d = new Date(workex['start_date']);
			 		work_info['start-date'] = month[d.getMonth()]+', '+d.getFullYear();

			 		if(typeof workex['end_date'] === 'undefined')
			 			work_info['end-date'] = 'present';
			 		else
			 		{
			 			d = new Date(workex['end_date']);
				 		work_info['end-date'] = month[d.getMonth()]+', '+d.getFullYear();
			 		}
			 		suggestions['facebook_workex'].push(work_info);
				}
	 	}

	 	if(social_data['facebook']['education'])
		{
				var d = '';
		 		for (var key in social_data['facebook']['education']) {

			 		var education = social_data['facebook']['education'][key];
			 		var education_info = {};

			 		education_info['education-type'] = education['type'] || '';
			 		education_info['institution-name'] = education['school']['name'] || '';
			 		if('year' in education)
			 			education_info['education-period'] = ' -'+(education['year']['name'] || '');
			 		else
			 			education_info['education-period'] = '';

			 		education_info['education-description'] = '';

				 	suggestions['facebook_education'].push(education_info);

				}
				console.log(suggestions['facebook_education']);
	 	}

	 }

	if(social_data['linkedin'])
	{
		if(social_data['linkedin']['skills'] && (social_data['linkedin']['skills']['_total']>0)) {
			var skillSetArray = [];
			for(var i=0; i<social_data['linkedin']['skills']['_total']; i++) {
				skillSetArray.push(social_data['linkedin']['skills']['values'][i]['skill']['name']);
			}
			suggestions['linkedin_skills'] = skillSetArray;

        skillsName = skillsName.concat(skillSetArray);
        $('[class^="form-control tagInputs"]').tagsinput('destroy');
	    $('[class^="form-control tagInputs"]').tagsinput('input');
        $('[class^="form-control tagInputs"]').tagsinput('input').typeahead({
		  local: skillsName
		}).bind('typeahead:selected', $.proxy(function (obj, datum) {
		  this.tagsinput('add', datum.value);
		  this.tagsinput('input').typeahead('setQuery', '');
		}, $('[class^="form-control tagInputs"]')));

		}
		else {
	        skillsName = defaultSkills;
	    }

		if(social_data['linkedin']['firstName'] && social_data['linkedin']['lastName'])
			suggestions['linkedin_name'] = social_data['linkedin']['firstName']+' '+social_data['linkedin']['lastName'];

		if(social_data['linkedin']['emailAddress'])
	 		suggestions['linkedin_email'] = social_data['linkedin']['emailAddress'];

	 	if(social_data['linkedin']['positions'] && (social_data['linkedin']['positions']['_total']>0))
		{

		 		for (var key in social_data['linkedin']['positions']['values']) {

			 		var workex = social_data['linkedin']['positions']['values'][key];
			 		var work_info = {};

			 		work_info['job-description'] = workex['summary'] || '';
			 		work_info['company-name'] = workex['company']['name'] || '';
			 		work_info['job-title'] = workex['title'] || '';
			 		work_info['start-date'] = month[parseInt(workex['startDate']['month'])-1]+', '+workex['startDate']['year'];

			 		if(workex['isCurrent']==true)
			 			work_info['end-date'] = 'present';

			 		else
			 			work_info['end-date'] = month[parseInt(workex['endDate']['month'])-1]+', '+workex['endDate']['year'];

			 		suggestions['linkedin_workex'].push(work_info);
				}
	 	}

	 	if(social_data['linkedin']['educations'] && (social_data['linkedin']['educations']['_total']>0))
		{

		 		for (var key in social_data['linkedin']['educations']['values']) {

			 		var education = social_data['linkedin']['educations']['values'][key];
			 		var education_info = {};

			 		education_info['education-type'] = education['degree'] || '';
			 		education_info['institution-name'] = education['schoolName'] || '';

			 		if(('startDate' in education) && ('endDate' in education))
			 			education_info['education-period'] = (education['startDate']['year'] || '') +'-'+(education['endDate']['year'] || '');

			 		else
			 			education_info['education-period'] = '';

			 		education_info['education-description'] = education['activities'] || '';

			 		suggestions['linkedin_education'].push(education_info);
				}

				console.log(suggestions['linkedin_education']);
	 	}

	 	if(social_data['linkedin']['projects'] && (social_data['linkedin']['projects']['_total']>0))
	 	{

	 		for (var key in social_data['linkedin']['projects']['values'])
	 		{

			 		var projects = social_data['linkedin']['projects']['values'][key];
			 		var projects_info = {};

			 		projects_info['project-title'] = projects['name'] || '';
			 		projects_info['project-url'] = projects['url'] || '';

			 		projects_info['project-start-date'] = '';
			 		projects_info['project-end-date'] = '';
			 		projects_info['project-description'] = projects['description'] || '';

			 		suggestions['linkedin_projects'].push(projects_info);
			}

	 	}
	}

	if(social_data['github'])
	{

		if(social_data['github']['name'])
			suggestions['github_name'] = social_data['github']['name'];

		if(social_data['github']['email'])
			suggestions['github_email'] = social_data['github']['email'];

		if(social_data['github']['blog'])
			suggestions['github_website'] = social_data['github']['blog'];

		if(social_data['github']['location'])
			suggestions['github_location'] = social_data['github']['location'];

		if(social_data['github']['repos'])
		{

			for (var key in social_data['github']['repos'])
	 		{

			 		var projects = social_data['github']['repos'][key];

			 		if( projects['fork'] == false)
			 		{
			 			var projects_info = {};

				 		projects_info['project-title'] = projects['name'] || '';
				 		projects_info['project-url'] = projects['url'] || '';
				 		projects_info['project-description'] = projects['description'] || '';

				 		var start_d = new Date(projects['created_at']);
				 		var end_d = new Date(projects['pushed_at']);

				 		projects_info['project-start-date'] = month[start_d.getMonth()]+', '+start_d.getFullYear();
				 		projects_info['project-end-date'] = month[end_d.getMonth()]+', '+end_d.getFullYear();

				 		suggestions['github_projects'].push(projects_info);

			 		}

			}

		}
	}

	window.suggestions = suggestions ; // assigning local data to global variable

	/* attaching popovers to single fields */
	single_fields.forEach(function(field){

		$('#'+field).popover('destroy');
		$('#'+field).popover({
	 	placement : 'bottom',
	 	title :field+' suggestions',
	 	html : true,
	 	trigger : 'focus',
	 	content : function(){

	 			var list = '';
	 			providers.forEach(function(provider)
	 			{

	 				// if suggestion is availbale from social provider
	 				if (suggestions[provider+'_'+field] && (suggestions[provider+'_'+field] != ''))
	 				{
	 					list+='
'+suggestions[provider+'_'+field]+' -'+provider+'
';

	 				}

	 			});
	 		if(list != '')
	 		{
	 			list='
'+list+'
';
	 			return list;
	 		}
	 		else
	 			return 'No sugestions available';
	 	}

	 });

	});

	dynamicWorkexPopoverBinder();
	dynamicEducationPopoverBinder();
	dynamicProjectsPopoverBinder();

}

function dynamicWorkexPopoverBinder()
{
	/* suggestion for job experience */

	popoverFields['workex'].forEach(function(field){

		$('.'+field).popover('destroy');
		$('.'+field).popover(popoverSettings('workex',field));

	});

}

function dynamicEducationPopoverBinder()
{

	/* suggestion for education */

	popoverFields['education'].forEach(function(field){
		$('.'+field).popover('destroy');
		$('.'+field).popover(popoverSettings('education',field));

	});

}

function dynamicProjectsPopoverBinder()
{

	/* suggestion for projects */

	popoverFields['projects'].forEach(function(field){
		$('.'+field).popover('destroy');
		$('.'+field).popover(popoverSettings('projects',field));

	});

}

<commit_msg>fixed : tagsinput error<commit_after>/* gloabl suggestions object */
suggestions = {};

/* months in string format */
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";

/* list of providers */
var providers = ['facebook','linkedin','github'];

var single_fields = ['name','email','website','location'];

/* array of fields attached with each suggestion */
var complex_fields = {};
complex_fields['workex'] = ['job-description','company-name','job-title','end-date','start-date'];
complex_fields['education'] = ['education-type','institution-name','education-period' ,'education-description'];
complex_fields['projects'] = ['project-title','project-url','project-start-date','project-end-date','project-description'];

/* fields for which popovers will be defined */
var popoverFields = {};
popoverFields['workex'] = ['job-title','company-name'];
popoverFields['education'] = ['education-type','institution-name'];
popoverFields['projects'] = ['project-title','project-url'];

/* adding event listeners */

$(document).ready(function(){

/* attaching click event listerners for single suggestion fields */
single_fields.forEach(function(field){

	$("body").on("click", '.'+field+'Suggestion', function(){
	     $('#'+field).val($(this).children('span:first').text()); // setting value of name input
	     $('#'+field).keyup(); // for calling validation
	});

});

var categories = ['workex','education','projects'];

/* attaching event listeners for categories */
categories.forEach(function(category){

	popoverFields[category].forEach(function(field){

	$("body").on("click", '.'+field+'Suggestion', function(event){

		var provider = $(this).data('provider');
		var key = $(this).data('ref-no');

		var target = $(event.target).parents().eq(3).children('.'+field); // target input box

		container = target.parents().eq(3); // getting 4th level parent of target element

    	complex_fields[category].forEach(function(sibling){

    		container.find('.'+sibling+':first').val(suggestions[provider+'_'+category][key][sibling]).keyup(); // seting text of sibbling fields in div; keyup called for triggering validation

		});

		var numWysiEditor = $('.html5-editor-toggle');
		for(var i=0;i<numWysiEditor.length;i++) {
			numWysiEditor[i].click();
		}

	});

});

});

});

/* popover settings for complex segment */

function popoverSettings(category,field)
{
	return {
 	placement : 'bottom',
 	title :field+' suggestions',
 	html : true,
 	trigger : 'focus',
 	content : function(){

 			var list = '';
 			providers.forEach(function(provider)
 			{

 				// if suggestion is availbale from social provider
 				if (suggestions[provider+'_'+category] && (suggestions[provider+'_'+category] != ''))
 				{
 					//console.log(suggestions[provider+'_workex']);

 					for(key in suggestions[provider+'_'+category])
 					{
 						var suggestion = suggestions[provider+'_'+category][key];

 						if(suggestion[field]!='')
 						{
 							if((field =='company-name') || category !='workex')
 						 		list+='
'+suggestion[field]+' -'+provider+'
';
 						 	else
 						 		list+='
'+suggestion[field]+' ('+suggestion['company-name']+')'+' -'+provider+'
';
 						 }

 					}

 				}

 			});

	 		if(list != '')
	 		{
	 			list='
'+list+'
';
	 			return list;
	 		}
	 		else
	 			return 'No sugestions available';
 	}

 }

};

function attachPopOvers()
{

	/* checking if social data exists */
	if(typeof social_data === 'undefined'){
	   social_data = {};
	 };

	 /* declaring suggestions for each fiels */

	 var suggestions = {};

	 suggestions['facebook_name'] = '';
	 suggestions['linkedin_name'] = '';
	 suggestions['github_name'] = '';

	 suggestions['facebook_email'] = '';
	 suggestions['linkedin_email'] = '';
	 suggestions['github_email'] = '';

	 suggestions['github_website'] = '';

	 suggestions['facebook_workex'] = [];
	 suggestions['linkedin_workex'] = [];

	 suggestions['facebook_location'] = '';
	 suggestions['github_location'] = '';

	 suggestions['facebook_education'] = [];
	 suggestions['linkedin_education'] = [];

	 suggestions['linkedin_projects'] =[];
	 suggestions['github_projects'] = [];

	 if(social_data['facebook'])
	 {
	 	if(social_data['facebook']['first_name'] && social_data['facebook']['last_name'])
		 	suggestions['facebook_name']= social_data['facebook']['first_name'] + ' ' + social_data['facebook']['last_name'];

	 	if(social_data['facebook']['email'])
	 		suggestions['facebook_email']= social_data['facebook']['email'];

	 	if(social_data['facebook']['location']) {
		 	if(social_data['facebook']['location']['name'])
		 		suggestions['facebook_location']= social_data['facebook']['location']['name'];
	 	}

		if(social_data['facebook']['work'])
		{
				var d = '';
		 		for (var key in social_data['facebook']['work']) {

			 		var workex = social_data['facebook']['work'][key];
			 		var work_info = {};

			 		work_info['job-description'] = workex['description'] || '';
			 		work_info['company-name'] = workex['employer']['name'] || '';
			 		work_info['job-title'] = workex['position']['name'] || '';
			 		d = new Date(workex['start_date']);
			 		work_info['start-date'] = month[d.getMonth()]+', '+d.getFullYear();

			 		if(typeof workex['end_date'] === 'undefined')
			 			work_info['end-date'] = 'present';
			 		else
			 		{
			 			d = new Date(workex['end_date']);
				 		work_info['end-date'] = month[d.getMonth()]+', '+d.getFullYear();
			 		}
			 		suggestions['facebook_workex'].push(work_info);
				}
	 	}

	 	if(social_data['facebook']['education'])
		{
				var d = '';
		 		for (var key in social_data['facebook']['education']) {

			 		var education = social_data['facebook']['education'][key];
			 		var education_info = {};

			 		education_info['education-type'] = education['type'] || '';
			 		education_info['institution-name'] = education['school']['name'] || '';
			 		if('year' in education)
			 			education_info['education-period'] = ' -'+(education['year']['name'] || '');
			 		else
			 			education_info['education-period'] = '';

			 		education_info['education-description'] = '';

				 	suggestions['facebook_education'].push(education_info);

				}
				console.log(suggestions['facebook_education']);
	 	}

	 }

	if(social_data['linkedin'])
	{
		if(social_data['linkedin']['skills'] && (social_data['linkedin']['skills']['_total']>0)) {
			var skillSetArray = [];
			for(var i=0; i<social_data['linkedin']['skills']['_total']; i++) {
				skillSetArray.push(social_data['linkedin']['skills']['values'][i]['skill']['name']);
			}
			suggestions['linkedin_skills'] = skillSetArray;

        skillsName = skillsName.concat(skillSetArray);
        $('[class^="form-control skill-tags tagInputs"]').tagsinput('destroy');
	    $('[class^="form-control skill-tags tagInputs"]').tagsinput('input');
        $('[class^="form-control skill-tags tagInputs"]').tagsinput('input').typeahead({
		  local: skillsName
		}).bind('typeahead:selected', $.proxy(function (obj, datum) {
		  this.tagsinput('add', datum.value);
		  this.tagsinput('input').typeahead('setQuery', '');
		}, $('[class^="form-control tagInputs"]')));

		}
		else {
	        skillsName = defaultSkills;
	    }

		if(social_data['linkedin']['firstName'] && social_data['linkedin']['lastName'])
			suggestions['linkedin_name'] = social_data['linkedin']['firstName']+' '+social_data['linkedin']['lastName'];

		if(social_data['linkedin']['emailAddress'])
	 		suggestions['linkedin_email'] = social_data['linkedin']['emailAddress'];

	 	if(social_data['linkedin']['positions'] && (social_data['linkedin']['positions']['_total']>0))
		{

		 		for (var key in social_data['linkedin']['positions']['values']) {

			 		var workex = social_data['linkedin']['positions']['values'][key];
			 		var work_info = {};

			 		work_info['job-description'] = workex['summary'] || '';
			 		work_info['company-name'] = workex['company']['name'] || '';
			 		work_info['job-title'] = workex['title'] || '';
			 		work_info['start-date'] = month[parseInt(workex['startDate']['month'])-1]+', '+workex['startDate']['year'];

			 		if(workex['isCurrent']==true)
			 			work_info['end-date'] = 'present';

			 		else
			 			work_info['end-date'] = month[parseInt(workex['endDate']['month'])-1]+', '+workex['endDate']['year'];

			 		suggestions['linkedin_workex'].push(work_info);
				}
	 	}

	 	if(social_data['linkedin']['educations'] && (social_data['linkedin']['educations']['_total']>0))
		{

		 		for (var key in social_data['linkedin']['educations']['values']) {

			 		var education = social_data['linkedin']['educations']['values'][key];
			 		var education_info = {};

			 		education_info['education-type'] = education['degree'] || '';
			 		education_info['institution-name'] = education['schoolName'] || '';

			 		if(('startDate' in education) && ('endDate' in education))
			 			education_info['education-period'] = (education['startDate']['year'] || '') +'-'+(education['endDate']['year'] || '');

			 		else
			 			education_info['education-period'] = '';

			 		education_info['education-description'] = education['activities'] || '';

			 		suggestions['linkedin_education'].push(education_info);
				}

				console.log(suggestions['linkedin_education']);
	 	}

	 	if(social_data['linkedin']['projects'] && (social_data['linkedin']['projects']['_total']>0))
	 	{

	 		for (var key in social_data['linkedin']['projects']['values'])
	 		{

			 		var projects = social_data['linkedin']['projects']['values'][key];
			 		var projects_info = {};

			 		projects_info['project-title'] = projects['name'] || '';
			 		projects_info['project-url'] = projects['url'] || '';

			 		projects_info['project-start-date'] = '';
			 		projects_info['project-end-date'] = '';
			 		projects_info['project-description'] = projects['description'] || '';

			 		suggestions['linkedin_projects'].push(projects_info);
			}

	 	}
	}

	if(social_data['github'])
	{

		if(social_data['github']['name'])
			suggestions['github_name'] = social_data['github']['name'];

		if(social_data['github']['email'])
			suggestions['github_email'] = social_data['github']['email'];

		if(social_data['github']['blog'])
			suggestions['github_website'] = social_data['github']['blog'];

		if(social_data['github']['location'])
			suggestions['github_location'] = social_data['github']['location'];

		if(social_data['github']['repos'])
		{

			for (var key in social_data['github']['repos'])
	 		{

			 		var projects = social_data['github']['repos'][key];

			 		if( projects['fork'] == false)
			 		{
			 			var projects_info = {};

				 		projects_info['project-title'] = projects['name'] || '';
				 		projects_info['project-url'] = projects['url'] || '';
				 		projects_info['project-description'] = projects['description'] || '';

				 		var start_d = new Date(projects['created_at']);
				 		var end_d = new Date(projects['pushed_at']);

				 		projects_info['project-start-date'] = month[start_d.getMonth()]+', '+start_d.getFullYear();
				 		projects_info['project-end-date'] = month[end_d.getMonth()]+', '+end_d.getFullYear();

				 		suggestions['github_projects'].push(projects_info);

			 		}

			}

		}
	}

	window.suggestions = suggestions ; // assigning local data to global variable

	/* attaching popovers to single fields */
	single_fields.forEach(function(field){

		$('#'+field).popover('destroy');
		$('#'+field).popover({
	 	placement : 'bottom',
	 	title :field+' suggestions',
	 	html : true,
	 	trigger : 'focus',
	 	content : function(){

	 			var list = '';
	 			providers.forEach(function(provider)
	 			{

	 				// if suggestion is availbale from social provider
	 				if (suggestions[provider+'_'+field] && (suggestions[provider+'_'+field] != ''))
	 				{
	 					list+='
'+suggestions[provider+'_'+field]+' -'+provider+'
';

	 				}

	 			});
	 		if(list != '')
	 		{
	 			list='
'+list+'
';
	 			return list;
	 		}
	 		else
	 			return 'No sugestions available';
	 	}

	 });

	});

	dynamicWorkexPopoverBinder();
	dynamicEducationPopoverBinder();
	dynamicProjectsPopoverBinder();

}

function dynamicWorkexPopoverBinder()
{
	/* suggestion for job experience */

	popoverFields['workex'].forEach(function(field){

		$('.'+field).popover('destroy');
		$('.'+field).popover(popoverSettings('workex',field));

	});

}

function dynamicEducationPopoverBinder()
{

	/* suggestion for education */

	popoverFields['education'].forEach(function(field){
		$('.'+field).popover('destroy');
		$('.'+field).popover(popoverSettings('education',field));

	});

}

function dynamicProjectsPopoverBinder()
{

	/* suggestion for projects */

	popoverFields['projects'].forEach(function(field){
		$('.'+field).popover('destroy');
		$('.'+field).popover(popoverSettings('projects',field));

	});

}

<|endoftext|>


<commit_before>import Ember from 'ember';

const {
  Route,
  RSVP
} = Ember;

export default Route.extend({

  deactivate() {
    this.store.peekAll('team-member').forEach((team) => {
      if (team.get('isNew')) {
        this.store.deleteRecord(team);
      }
    });
  },

  actions: {
    assignMember(member) {
      const flashMessages = Ember.get(this, 'flashMessages');

      return member.save().then(() => {
        this.currentModel.get('teamMembers').addObject(member);

        flashMessages.success(member.get('name')+' has been assigned to the team');
      }).catch(() => {
        member.rollback();

        flashMessages.danger('Unable to assign member to the team');
      });
    },

    removeMember(member) {
      const flashMessages = Ember.get(this, 'flashMessages');

      return member.destroyRecord().then(() => {
        flashMessages.success(member.get('name')+' has been removed from the team');
      }).catch(() => {
        member.rollback();

        flashMessages.danger('Unable to remove member from the team');
      });
    }
  },

  model: function (params) {
    const store = this.store;
    const teamId = params.id;
    const tournament = this.modelFor('tournament');

    return RSVP.hash({
      team: store.find('team', teamId),
      matches: store.query('match', {tournamentId: tournament.get('id'), teamId}),
      teamMembers: store.query('team-member', {teamId})
    }).then((hash) => {
      hash.team.set('teamMembers', hash.teamMembers);

      return hash;
    });
  }
});
<commit_msg>Fix assign member to the team<commit_after>import Ember from 'ember';

const {
  Route,
  RSVP
} = Ember;

export default Route.extend({

  deactivate() {
    this.store.peekAll('team-member').forEach((team) => {
      if (team.get('isNew')) {
        this.store.deleteRecord(team);
      }
    });
  },

  actions: {
    assignMember(member) {
      const flashMessages = Ember.get(this, 'flashMessages');

      return member.save().then(() => {
        flashMessages.success(member.get('name')+' has been assigned to the team');
      }).catch(() => {
        member.rollback();

        flashMessages.danger('Unable to assign member to the team');
      });
    },

    removeMember(member) {
      const flashMessages = Ember.get(this, 'flashMessages');

      return member.destroyRecord().then(() => {
        flashMessages.success(member.get('name')+' has been removed from the team');
      }).catch(() => {
        member.rollback();

        flashMessages.danger('Unable to remove member from the team');
      });
    }
  },

  model: function (params) {
    const store = this.store;
    const teamId = params.id;
    const tournament = this.modelFor('tournament');

    return RSVP.hash({
      team: store.find('team', teamId),
      matches: store.query('match', {tournamentId: tournament.get('id'), teamId}),
      teamMembers: store.query('team-member', {teamId})
    }).then((hash) => {
      hash.team.set('teamMembers', hash.teamMembers);

      return hash;
    });
  }
});
<|endoftext|>


<commit_before>require('colors');
var fs = require('fs');
var net = require('net');
var childProcess = require('child_process');

var terminal = module.exports = exports = {
	operations: {
		start: function(params) {
			var exists = fs.existsSync('/tmp/nodeserver.sock');

			console.log('-= Nodeserver =-\n'.blue);

			if(exists) {
				console.log('Nodeserver are running'.yellow);
			} else {
				console.log('start nodeserver'.yellow);

				var child = childProcess.spawn(__dirname + "/../bin/nodeserver", ["start-loop"], { detached: true, stdio: 'ignore' });
				child.unref();
			}
		},
		'start-loop': function(params) {
			var exists = fs.existsSync('/tmp/nodeserver.sock');

			console.log('-= Nodeserver =-\n'.blue);

			if(exists) {
				console.log('Nodeserver are running'.yellow);
			} else {
				console.log('start nodeserver'.yellow);

				terminal.nodeserver.readConfigFile(params[3] || '/etc/nodeserver/nodeserver.config')
				terminal.nodeserver.start();
			}
		},
		stop: function(params) {
			console.log('-= Nodeserver =-\n'.blue);
			var exists = fs.existsSync('/tmp/nodeserver.sock');

			if(exists) {
				console.log('stopping server...'.grey);

				var socket = new net.Socket();
				socket.connect('/tmp/nodeserver.sock', function() {
					socket.write('stop', function() {});

					socket.on('data', function(data) {
						console.log('server stopped'.grey);
						socket.end();
					});
				});
			} else {
				console.log('No server running'.yellow)
			}
		},
		reload: function(params) {
			console.log('reload')
		},
		status: function(params) {
			console.log('-= Nodeserver =-\n'.blue);
			var exists = fs.existsSync('/tmp/nodeserver.sock');

			if(exists) {
				console.log('Server running'.yellow);

				var socket = new net.Socket();
				socket.connect('/tmp/nodeserver.sock', function() {
					socket.write('status', function() {});

					socket.on('data', function(data) {
						var json = JSON.parse(data);
						socket.end();

						if(json.websites.length > 0) {
							for (var i = 0; i < json.websites.length; i++) {
								var website = json.websites[i];
								var status = (website.status == 'started') ? ' * '.green : ' * '.red;
								console.log(status + website.name + '\t\t'.gray);
								console.log('   ' + website.type + '\t\t'.gray);
								console.log('\n');
							};
						} else {
							console.log('No websites configured'.gray);
						}
					});
				});
			} else {
				console.log('No server running'.yellow)
			}
		},
		help: function(params) {
			console.log('-= Nodeserver Help =-'.blue);
			console.log('use: nodeserver [command] [parameters]\n'.green);
			console.log('* start\t\tStart server service in background'.gray);
			console.log('* start-loop\t\tStart server service in loop'.gray);
			console.log('* stop\t\tStop server service'.gray);
			console.log('* reload\tReload server configuration. Stop all child process and restart its'.gray);
			console.log('* status\tShow status of all child websites'.gray);
		},
	},
	process: function(params) {
		if(params.length < 3) {
			params[2] = 'help';
		}

		var operation = params[2];

		if(terminal.operations[operation]) {
			terminal.operations[operation](params);
		} else {
			console.log('invalid operation'.red);
			terminal.operations.help(params);
		}
	}
};<commit_msg>start server with server script parameter for config<commit_after>require('colors');
var fs = require('fs');
var net = require('net');
var childProcess = require('child_process');

var terminal = module.exports = exports = {
	operations: {
		start: function(params) {
			var exists = fs.existsSync('/tmp/nodeserver.sock');

			console.log('-= Nodeserver =-\n'.blue);

			if(exists) {
				console.log('Nodeserver are running'.yellow);
			} else {
				console.log('start nodeserver'.yellow);

				var child = childProcess.spawn(__dirname + "/../bin/nodeserver", ["start-loop", params[3] || '/etc/nodeserver/nodeserver.config'], { detached: true, stdio: 'ignore' });
				child.unref();
			}
		},
		'start-loop': function(params) {
			var exists = fs.existsSync('/tmp/nodeserver.sock');

			console.log('-= Nodeserver =-\n'.blue);

			if(exists) {
				console.log('Nodeserver are running'.yellow);
			} else {
				console.log('start nodeserver'.yellow);

				terminal.nodeserver.readConfigFile(params[3] || '/etc/nodeserver/nodeserver.config')
				terminal.nodeserver.start();
			}
		},
		stop: function(params) {
			console.log('-= Nodeserver =-\n'.blue);
			var exists = fs.existsSync('/tmp/nodeserver.sock');

			if(exists) {
				console.log('stopping server...'.grey);

				var socket = new net.Socket();
				socket.connect('/tmp/nodeserver.sock', function() {
					socket.write('stop', function() {});

					socket.on('data', function(data) {
						console.log('server stopped'.grey);
						socket.end();
					});
				});
			} else {
				console.log('No server running'.yellow)
			}
		},
		reload: function(params) {
			console.log('reload')
		},
		status: function(params) {
			console.log('-= Nodeserver =-\n'.blue);
			var exists = fs.existsSync('/tmp/nodeserver.sock');

			if(exists) {
				console.log('Server running'.yellow);

				var socket = new net.Socket();
				socket.connect('/tmp/nodeserver.sock', function() {
					socket.write('status', function() {});

					socket.on('data', function(data) {
						var json = JSON.parse(data);
						socket.end();

						if(json.websites.length > 0) {
							for (var i = 0; i < json.websites.length; i++) {
								var website = json.websites[i];
								var status = (website.status == 'started') ? ' * '.green : ' * '.red;
								console.log(status + website.name + '\t\t'.gray);
								console.log('   ' + website.type + '\t\t'.gray);
								console.log('\n');
							};
						} else {
							console.log('No websites configured'.gray);
						}
					});
				});
			} else {
				console.log('No server running'.yellow)
			}
		},
		help: function(params) {
			console.log('-= Nodeserver Help =-'.blue);
			console.log('use: nodeserver [command] [parameters]\n'.green);
			console.log('* start\t\tStart server service in background'.gray);
			console.log('* start-loop\t\tStart server service in loop'.gray);
			console.log('* stop\t\tStop server service'.gray);
			console.log('* reload\tReload server configuration. Stop all child process and restart its'.gray);
			console.log('* status\tShow status of all child websites'.gray);
		},
	},
	process: function(params) {
		if(params.length < 3) {
			params[2] = 'help';
		}

		var operation = params[2];

		if(terminal.operations[operation]) {
			terminal.operations[operation](params);
		} else {
			console.log('invalid operation'.red);
			terminal.operations.help(params);
		}
	}
};<|endoftext|>