<commit_before>"use strict";

class gsuiEnvelope extends HTMLElement {
	constructor() {
		const children = GSUI.getTemplate( "gsui-envelope" ),
			elWave = children[ 1 ].firstChild,
			beatlines = children[ 6 ].firstChild,
			graph = children[ 6 ].lastChild,
			sliders = Object.freeze( {
				attack: [ children[ 1 ].lastChild.firstChild, children[ 1 ].firstChild.lastChild ],
				hold: [ children[ 2 ].lastChild.firstChild, children[ 2 ].firstChild.lastChild ],
				decay: [ children[ 3 ].lastChild.firstChild, children[ 3 ].firstChild.lastChild ],
				substain: [ children[ 4 ].lastChild.firstChild, children[ 4 ].firstChild.lastChild ],
				release: [ children[ 5 ].lastChild.firstChild, children[ 5 ].firstChild.lastChild ],
			} );

		super();
		this._children = children;
		this._wave = elWave.firstChild;
		this._sliders = sliders;
		this._beatlines = beatlines;
		this._graph = graph;
		this._dur = 4;
		this._waveWidth = 300;
		this._dispatch = GSUI.dispatchEvent.bind( null, this, "gsuiEnvelope" );
		this._onresize = this._onresize.bind( this );
		Object.seal( this );

		this.onchange = this._onchangeForm.bind( this );
		this._initSlider( "attack" );
		this._initSlider( "hold" );
		this._initSlider( "decay" );
		this._initSlider( "substain" );
		this._initSlider( "release" );
	}

	// .........................................................................
	connectedCallback() {
		if ( this._children ) {
			this.classList.add( "gsuiEnvelope" );
			this.append( ...this._children );
			this._children = null;
			GSUI.recallAttributes( this, {
				toggle: false,
				timedivision: "4/4",
				attack: .1,
				hold: .1,
				decay: .1,
				substain: .8,
				release: 1,
			} );
			this.updateWave();
		}
		GSUI.observeSizeOf( this, this._onresize );
	}
	disconnectedCallback() {
		GSUI.unobserveSizeOf( this, this._onresize );
	}
	static get observedAttributes() {
		return [ "toggle", "attack", "hold", "decay", "substain", "release" ];
	}
	attributeChangedCallback( prop, prev, val ) {
		if ( prev !== val ) {
			switch ( prop ) {
				case "toggle": this._changeToggle( val !== null ); break;
				case "attack":
				case "hold":
				case "decay":
				case "substain":
				case "release":
					this._changeProp( prop, +val );
					break;
			}
		}
	}

	// .........................................................................
	timeDivision( a, b ) {
		this._beatlines.setAttribute( "timedivision", `${ a }/${ b }` );
		this.updateWave();
	}
	updateWave( prop, val ) {
		const g = this._graph,
			bPM = +this.getAttribute( "timedivision" ).split( "/" )[ 0 ];

		g.attack = prop === "attack" ? val : +this.getAttribute( "attack" );
		g.hold = prop === "hold" ? val : +this.getAttribute( "hold" );
		g.decay = prop === "decay" ? val : +this.getAttribute( "decay" );
		g.substain = prop === "substain" ? val : +this.getAttribute( "substain" );
		g.release = prop === "release" ? val : +this.getAttribute( "release" );
		g.duration =
		this._dur = Math.ceil( Math.max( g.attack + g.hold + g.decay + .5 + g.release, bPM ) );
		g.draw();
		this._updatePxPerBeat();
	}

	// .........................................................................
	_changeToggle( b ) {
		this.classList.toggle( "gsuiEnvelope-enable", b );
		this._sliders.attack[ 0 ].enable( b );
		this._sliders.hold[ 0 ].enable( b );
		this._sliders.decay[ 0 ].enable( b );
		this._sliders.substain[ 0 ].enable( b );
		this._sliders.release[ 0 ].enable( b );
	}
	_changeProp( prop, val ) {
		const [ sli, span ] = this._sliders[ prop ];

		sli.setValue( val );
		span.textContent = val.toFixed( 2 );
	}

	// .........................................................................
	_updatePxPerBeat() {
		this._beatlines.setAttribute( "pxperbeat", this._waveWidth / this._dur );
	}
	_initSlider( prop ) {
		const slider = this._sliders[ prop ][ 0 ];

		slider.oninput = this._oninputSlider.bind( this, prop );
		slider.onchange = this._onchangeSlider.bind( this, prop );
	}

	// events:
	// .........................................................................
	_onresize() {
		this._waveWidth = this._beatlines.getBoundingClientRect().width;
		this._updatePxPerBeat();
		this._graph.resized();
	}
	_onchangeForm( e ) {
		switch ( e.target.name ) {
			case "gsuiEnvelope-toggle":
				GSUI.setAttribute( this, "toggle", !this.classList.contains( "gsuiEnvelope-enable" ) );
				this._dispatch( "toggle" );
				break;
		}
	}
	_oninputSlider( prop, val ) {
		this._sliders[ prop ][ 1 ].textContent = val.toFixed( 2 );
		this.updateWave( prop, val );
		this._dispatch( "liveChange", prop, val );
	}
	_onchangeSlider( prop, val ) {
		GSUI.setAttribute( this, prop, val );
		this._dispatch( "change", prop, val );
	}
}

customElements.define( "gsui-envelope", gsuiEnvelope );

Object.freeze( gsuiEnvelope );
<commit_msg>gsuiEnvelope: duration fix<commit_after>"use strict";

class gsuiEnvelope extends HTMLElement {
	constructor() {
		const children = GSUI.getTemplate( "gsui-envelope" ),
			elWave = children[ 1 ].firstChild,
			beatlines = children[ 6 ].firstChild,
			graph = children[ 6 ].lastChild,
			sliders = Object.freeze( {
				attack: [ children[ 1 ].lastChild.firstChild, children[ 1 ].firstChild.lastChild ],
				hold: [ children[ 2 ].lastChild.firstChild, children[ 2 ].firstChild.lastChild ],
				decay: [ children[ 3 ].lastChild.firstChild, children[ 3 ].firstChild.lastChild ],
				substain: [ children[ 4 ].lastChild.firstChild, children[ 4 ].firstChild.lastChild ],
				release: [ children[ 5 ].lastChild.firstChild, children[ 5 ].firstChild.lastChild ],
			} );

		super();
		this._children = children;
		this._wave = elWave.firstChild;
		this._sliders = sliders;
		this._beatlines = beatlines;
		this._graph = graph;
		this._dur = 4;
		this._waveWidth = 300;
		this._dispatch = GSUI.dispatchEvent.bind( null, this, "gsuiEnvelope" );
		this._onresize = this._onresize.bind( this );
		Object.seal( this );

		this.onchange = this._onchangeForm.bind( this );
		this._initSlider( "attack" );
		this._initSlider( "hold" );
		this._initSlider( "decay" );
		this._initSlider( "substain" );
		this._initSlider( "release" );
	}

	// .........................................................................
	connectedCallback() {
		if ( this._children ) {
			this.classList.add( "gsuiEnvelope" );
			this.append( ...this._children );
			this._children = null;
			GSUI.recallAttributes( this, {
				toggle: false,
				timedivision: "4/4",
				attack: .1,
				hold: .1,
				decay: .1,
				substain: .8,
				release: 1,
			} );
			this.updateWave();
		}
		GSUI.observeSizeOf( this, this._onresize );
	}
	disconnectedCallback() {
		GSUI.unobserveSizeOf( this, this._onresize );
	}
	static get observedAttributes() {
		return [ "toggle", "attack", "hold", "decay", "substain", "release" ];
	}
	attributeChangedCallback( prop, prev, val ) {
		if ( prev !== val ) {
			switch ( prop ) {
				case "toggle": this._changeToggle( val !== null ); break;
				case "attack":
				case "hold":
				case "decay":
				case "substain":
				case "release":
					this._changeProp( prop, +val );
					break;
			}
		}
	}

	// .........................................................................
	timeDivision( a, b ) {
		this._beatlines.setAttribute( "timedivision", `${ a }/${ b }` );
		this.updateWave();
	}
	updateWave( prop, val ) {
		const g = this._graph,
			bPM = +this.getAttribute( "timedivision" ).split( "/" )[ 0 ];

		g.attack = prop === "attack" ? val : +this.getAttribute( "attack" );
		g.hold = prop === "hold" ? val : +this.getAttribute( "hold" );
		g.decay = prop === "decay" ? val : +this.getAttribute( "decay" );
		g.substain = prop === "substain" ? val : +this.getAttribute( "substain" );
		g.release = prop === "release" ? val : +this.getAttribute( "release" );
		g.duration =
		this._dur = Math.max( g.attack + g.hold + g.decay + 1 + g.release, bPM );
		g.draw();
		this._updatePxPerBeat();
	}

	// .........................................................................
	_changeToggle( b ) {
		this.classList.toggle( "gsuiEnvelope-enable", b );
		this._sliders.attack[ 0 ].enable( b );
		this._sliders.hold[ 0 ].enable( b );
		this._sliders.decay[ 0 ].enable( b );
		this._sliders.substain[ 0 ].enable( b );
		this._sliders.release[ 0 ].enable( b );
	}
	_changeProp( prop, val ) {
		const [ sli, span ] = this._sliders[ prop ];

		sli.setValue( val );
		span.textContent = val.toFixed( 2 );
	}

	// .........................................................................
	_updatePxPerBeat() {
		this._beatlines.setAttribute( "pxperbeat", this._waveWidth / this._dur );
	}
	_initSlider( prop ) {
		const slider = this._sliders[ prop ][ 0 ];

		slider.oninput = this._oninputSlider.bind( this, prop );
		slider.onchange = this._onchangeSlider.bind( this, prop );
	}

	// events:
	// .........................................................................
	_onresize() {
		this._waveWidth = this._beatlines.getBoundingClientRect().width;
		this._updatePxPerBeat();
		this._graph.resized();
	}
	_onchangeForm( e ) {
		switch ( e.target.name ) {
			case "gsuiEnvelope-toggle":
				GSUI.setAttribute( this, "toggle", !this.classList.contains( "gsuiEnvelope-enable" ) );
				this._dispatch( "toggle" );
				break;
		}
	}
	_oninputSlider( prop, val ) {
		this._sliders[ prop ][ 1 ].textContent = val.toFixed( 2 );
		this.updateWave( prop, val );
		this._dispatch( "liveChange", prop, val );
	}
	_onchangeSlider( prop, val ) {
		GSUI.setAttribute( this, prop, val );
		this._dispatch( "change", prop, val );
	}
}

customElements.define( "gsui-envelope", gsuiEnvelope );

Object.freeze( gsuiEnvelope );
<|endoftext|>


<commit_before>"use strict";

class gsuiWaveform {
	constructor( el ) {
		const svg = el || GSUI.$createElementSVG( "svg" );
		const poly = svg.querySelector( "polygon" );

		this.rootElement = svg;
		this.polygon = poly;
		this.width =
		this.height = 0;
		Object.seal( this );

		GSUI.$setAttribute( svg, "preserveAspectRatio", "none" );
		svg.classList.add( "gsuiWaveform" );
		if ( !poly ) {
			this.polygon = GSUI.$createElementSVG( "polygon" );
			svg.append( this.polygon );
		}
	}

	// .........................................................................
	remove() {
		this.empty();
		this.rootElement.remove();
	}
	empty() {
		this.polygon.removeAttribute( "points" );
	}
	setResolution( w, h ) {
		this.width = w;
		this.height = h;
		GSUI.$setAttribute( this.rootElement, "viewBox", `0 0 ${ w } ${ h }` );
	}
	drawBuffer( buf, offset, duration ) {
		gsuiWaveform.drawBuffer( this.polygon, this.width, this.height, buf, offset, duration );
	}

	// .........................................................................
	static drawBuffer( polygon, w, h, buf, offset, duration ) {
		const d0 = buf.getChannelData( 0 );
		const d1 = buf.numberOfChannels > 1 ? buf.getChannelData( 1 ) : d0;
		const off = offset || 0;
		const dur = duration || buf.duration - off;

		gsuiWaveform.draw( polygon, w, h, d0, d1, buf.duration, off, dur );
	}
	static draw( polygon, w, h, data0, data1, bufferDuration, offset, duration ) {
		const h2 = h / 2;
		const step = duration / bufferDuration * data0.length / w;
		const ind = ~~( offset / bufferDuration * data0.length );
		const iinc = ~~Math.max( 1, step / 100 );
		let dots0 = `0,${ gsuiWaveform.formatNb( h2 + data0[ ind ] * h2 ) }`;
		let dots1 = `0,${ gsuiWaveform.formatNb( h2 + data1[ ind ] * h2 ) }`;

		for ( let p = 1; p < w; ++p ) {
			let lmin = Infinity;
			let rmax = -Infinity;
			let i = ~~( ind + ( p - 1 ) * step );
			const iend = i + step;

			for ( ; i < iend; i += iinc ) {
				lmin = Math.min( lmin, data0[ i ], data1[ i ] );
				rmax = Math.max( rmax, data0[ i ], data1[ i ] );
			}
			if ( Math.abs( rmax - lmin ) * h2 < 1 ) {
				rmax += 1 / h;
				lmin -= 1 / h;
			}
			dots0 += ` ${ p },${ gsuiWaveform.formatNb( h2 + lmin * h2 ) }`;
			dots1  =  `${ p },${ gsuiWaveform.formatNb( h2 + rmax * h2 ) } ${ dots1 }`;
		}
		GSUI.$setAttribute( polygon, "points", `${ dots0 } ${ dots1 }` );
	}
	static formatNb( n ) {
		return n.toFixed( 2 );
	}
}
<commit_msg>gsuiWaveform: #formatNB, private<commit_after>"use strict";

class gsuiWaveform {
	constructor( el ) {
		const svg = el || GSUI.$createElementSVG( "svg" );
		const poly = svg.querySelector( "polygon" );

		this.rootElement = svg;
		this.polygon = poly;
		this.width =
		this.height = 0;
		Object.seal( this );

		GSUI.$setAttribute( svg, "preserveAspectRatio", "none" );
		svg.classList.add( "gsuiWaveform" );
		if ( !poly ) {
			this.polygon = GSUI.$createElementSVG( "polygon" );
			svg.append( this.polygon );
		}
	}

	// .........................................................................
	remove() {
		this.empty();
		this.rootElement.remove();
	}
	empty() {
		this.polygon.removeAttribute( "points" );
	}
	setResolution( w, h ) {
		this.width = w;
		this.height = h;
		GSUI.$setAttribute( this.rootElement, "viewBox", `0 0 ${ w } ${ h }` );
	}
	drawBuffer( buf, offset, duration ) {
		gsuiWaveform.drawBuffer( this.polygon, this.width, this.height, buf, offset, duration );
	}

	// .........................................................................
	static drawBuffer( polygon, w, h, buf, offset, duration ) {
		const d0 = buf.getChannelData( 0 );
		const d1 = buf.numberOfChannels > 1 ? buf.getChannelData( 1 ) : d0;
		const off = offset || 0;
		const dur = duration || buf.duration - off;

		gsuiWaveform.draw( polygon, w, h, d0, d1, buf.duration, off, dur );
	}
	static draw( polygon, w, h, data0, data1, bufferDuration, offset, duration ) {
		const h2 = h / 2;
		const step = duration / bufferDuration * data0.length / w;
		const ind = ~~( offset / bufferDuration * data0.length );
		const iinc = ~~Math.max( 1, step / 100 );
		let dots0 = `0,${ gsuiWaveform.#formatNb( h2 + data0[ ind ] * h2 ) }`;
		let dots1 = `0,${ gsuiWaveform.#formatNb( h2 + data1[ ind ] * h2 ) }`;

		for ( let p = 1; p < w; ++p ) {
			let lmin = Infinity;
			let rmax = -Infinity;
			let i = ~~( ind + ( p - 1 ) * step );
			const iend = i + step;

			for ( ; i < iend; i += iinc ) {
				lmin = Math.min( lmin, data0[ i ], data1[ i ] );
				rmax = Math.max( rmax, data0[ i ], data1[ i ] );
			}
			if ( Math.abs( rmax - lmin ) * h2 < 1 ) {
				rmax += 1 / h;
				lmin -= 1 / h;
			}
			dots0 += ` ${ p },${ gsuiWaveform.#formatNb( h2 + lmin * h2 ) }`;
			dots1  =  `${ p },${ gsuiWaveform.#formatNb( h2 + rmax * h2 ) } ${ dots1 }`;
		}
		GSUI.$setAttribute( polygon, "points", `${ dots0 } ${ dots1 }` );
	}
	static #formatNb( n ) {
		return n.toFixed( 2 );
	}
}
<|endoftext|>


<commit_before>Template.TreeView.onCreated(function() {
  let instance = this;

  instance.state = new ReactiveDict();
  instance.state.setDefault({
    errorMessage: null,
    ready: false
  });

  instance.autorun(() => {
    instance.state.set('ready', false);

    let dataContext = Template.currentData();

    if (dataContext && dataContext.collection) {
      if (dataContext.subscription) {
        //console.log('Calling subscribe');
        instance.subscribe(dataContext.subscription, {
          onReady: () => {
            //console.log("onReady called");
            //console.debug(this);
            instance.state.set('ready', true);
          }
        });
        Tracker.afterFlush(function() {
          instance.state.set('ready', instance.subscriptionsReady());
        });
      }
    } else if(! dataContext || ! dataContext.core || ! dataContext.core.data) {
      this.state.set('errorMessage', 'No collection set.');
    }
  });

});

Template.TreeView.helpers({
  showArgs() {
    const instance = Template.instance();
    return {
      errorMessage: instance.state.get('errorMessage'),
      ready: instance.state.get('ready'),
      options: Template.currentData()
    }
  }
});

Template.TreeView_content.onRendered(function() {
  let dataContext = Template.currentData();
  let collection = dataContext.collection;
  let mapping = dataContext.mapping || {};
  let events = dataContext.events || {};
  let instance = this;
  let select = dataContext.select;

  let parents = [];
  if (select && collection) {
    parents = getParents(select);
  }

  function getParents(id) {
    let parents = [];

    do {
      let item = collection.findOne(id);
      if (! item) break;
      id = item.parent;
      if(id) parents.push(id);
    } while (id);

    return parents;
  }

  let openId = null;
  let editId = null;

  function getItemId (item) {
      // Handle Mongos ObjectID instances
      if (item._id.valueOf) return item._id.valueOf();
      return item._id;
  }

  function getCount(listOrCursor) {
      if (typeof(listOrCursor.count) === 'function') return listOrCursor.count();
      return listOrCursor.length;
  }

  function getNodes(parent) {

    let f = dataContext.getNodes || function(parent) {
      let search = {};
      search[mapping['parent'] || 'parent'] = parent;
      return collection.find(search);
    }

    return f(parent).map( (item) => {
      node = {
        id: getItemId(item),
        text: getContent(item, 'text'),
        icon: getContent(item, 'icon'),
        // TODO: set state to show a selected node
        state: getState(item),
        li_attr: {class: getContent(item, 'liClass')},
        a_attr: getContent(item, 'aAttr'),
        data: item
      };

      // MMA: Allow node postprocessing for adding other plugins like "type"
      if (typeof dataContext.processNode == 'function') { dataContext.processNode(node, item); }

      node.children = getCount(f(getItemId(item))) > 0;
      return node;
    });
  }

  function getContent(item, field) {
    if (mapping && mapping[field]) {
      let f = mapping[field];
      if (typeof f === 'object') {
        return f;
      } else if (typeof f === 'string') {
        return item[f];
      } else if (typeof f === 'function') {
        return f(item, field);
      }
    } else {
      return item[field];
    }
  }

  function getState(item) {
    let content = getContent(item, 'state');
    if (content) return content;

    if (dataContext.select) {
      let state = {
        selected: (getItemId(item) == dataContext.select)
      }
      if (dataContext.openAll || parents.indexOf(getItemId(item)) > -1) {
        state.opened = true;
      }
      return state;
    } else if (dataContext.openAll) {
      return { opened: true };
    }
  }

  // function inspired from tracker.js
  function useComputation(c, f) {
    let savedComputation = Tracker.currentComputation;
    Tracker.currentComputation = c;
    Tracker.active = !! c;

    f();

    Tracker.currentComputation = savedComputation;
    Tracker.active = !! savedComputation;
  }

  instance.autorun((computation) => {
    if (computation.firstRun) {

      // Create tree on first run

      let jsTreeOptions = dataContext.jstree || {};

      jsTreeOptions.core = jsTreeOptions.core || {};
      jsTreeOptions.core.data = jsTreeOptions.core.data ||
        function(node, callback) {

          // The computation is reused to trigger only one refresh of the
          // complete tree.

          useComputation(computation, function() {
            if (node.id === '#') {
              callback(getNodes(dataContext.parent || null));
            } else {
              callback(getNodes(node.id));
            }
          });
        };

      jsTreeOptions.core.check_callback =
        jsTreeOptions.core.check_callback ||
        !! events.create ||
        !! events.rename ||
        !! events.delete ||
        !! events.copy ||
        !! events.move;

      jsTreeOptions.contextmenu = jsTreeOptions.contextmenu || {};
      jsTreeOptions.contextmenu.items = jsTreeOptions.contextmenu.items ||
        function() {
          let items = $.jstree.defaults.contextmenu.items();
          if (! events.create) delete items.create;
          if (! events.rename) delete items.rename;
          if (! events.delete) delete items.remove;
          if (! events.copy) delete items.ccp.submenu.copy;
          if (! events.move) delete items.ccp.submenu.move;
          if (! events.copy && ! events.move) delete items.ccp;

          return items;
        }();

      jsTreeOptions.dnd = jsTreeOptions.dnd || {};
      jsTreeOptions.dnd.always_copy = !! events.copy && ! events.move;
      jsTreeOptions.dnd.copy = !! events.copy;

      let tree = this.$('.js-treeview-content').jstree(jsTreeOptions);

      // Attach events
      function attachEventHandler(eventname, f) {
        if (typeof f == 'function') {
          tree.on(eventname, function(e, data) {
            //console.log(data);
            if (eventname === 'create_node.jstree') {
              tree.jstree().open_node(data.parent);
            }
            let newId = f(e, data.selected || (data.original && data.original.id) || data.node.id,
                          {text: data.text, parent: data.parent, position: data.position});
            if (newId === false) {
              ////console.log("Refreshing because of false as return value.")
              tree.jstree().refresh();
            } else if (newId) {
              data.instance.set_id(data.node, newId);
              if (eventname === 'create_node.jstree') {
                openId = data.parent;
                editId = newId;
              }
            }
          });
        }
      }

      attachEventHandler("changed.jstree", events.changed);
      attachEventHandler("create_node.jstree", events.create);
      attachEventHandler("rename_node.jstree", events.rename);
      attachEventHandler("delete_node.jstree", events.delete);
      attachEventHandler("copy_node.jstree", events.copy);
      attachEventHandler("move_node.jstree", events.move);

    } else {
      //console.log("refresh");

      let tree = this.$('.js-treeview-content').jstree();
      tree.refresh();
      if (editId) {
        //console.log('Calling edit on ' + editId);
        Meteor.setTimeout(function() {
          tree.edit(editId);
          editId = null;
        }, 1000);
      }
    }
  });
});
<commit_msg>Add data contexts to treeview<commit_after>Template.TreeView.onCreated(function() {
  let instance = this;

  instance.state = new ReactiveDict();
  instance.state.setDefault({
    errorMessage: null,
    ready: false
  });

  instance.autorun(() => {
    instance.state.set('ready', false);

    let dataContext = Template.currentData();

    if (dataContext && dataContext.collection) {
      if (dataContext.subscription) {
        //console.log('Calling subscribe');
        instance.subscribe(dataContext.subscription, {
          onReady: () => {
            //console.log("onReady called");
            //console.debug(this);
            instance.state.set('ready', true);
          }
        });
        Tracker.afterFlush(function() {
          instance.state.set('ready', instance.subscriptionsReady());
        });
      }
    } else if(! dataContext || ! dataContext.core || ! dataContext.core.data) {
      this.state.set('errorMessage', 'No collection set.');
    }
  });

});

Template.TreeView.helpers({
  showArgs() {
    const instance = Template.instance();
    return {
      errorMessage: instance.state.get('errorMessage'),
      ready: instance.state.get('ready'),
      options: Template.currentData()
    }
  }
});

Template.TreeView_content.onRendered(function() {
  let dataContext = Template.currentData();
  let collection = dataContext.collection;
  let mapping = dataContext.mapping || {};
  let events = dataContext.events || {};
  let instance = this;
  let select = dataContext.select;

  let parents = [];
  if (select && collection) {
    parents = getParents(select);
  }

  function getParents(id) {
    let parents = [];

    do {
      let item = collection.findOne(id);
      if (! item) break;
      id = item.parent;
      if(id) parents.push(id);
    } while (id);

    return parents;
  }

  let openId = null;
  let editId = null;

  function getItemId (item) {
      // Handle Mongos ObjectID instances
      if (item._id.valueOf) return item._id.valueOf();
      return item._id;
  }

  function getCount(listOrCursor) {
      if (typeof(listOrCursor.count) === 'function') return listOrCursor.count();
      return listOrCursor.length;
  }

  function getNodes(parent) {

    let f = dataContext.getNodes || function(parent) {
      let search = {};
      search[mapping['parent'] || 'parent'] = parent;
      return collection.find(search);
    }

    return f(parent).map( (item) => {
      node = {
        id: getItemId(item),
        text: getContent(item, 'text'),
        icon: getContent(item, 'icon'),
        // TODO: set state to show a selected node
        state: getState(item),
        li_attr: {class: getContent(item, 'liClass')},
        a_attr: getContent(item, 'aAttr'),
        data: item
      };

      // MMA: Allow node postprocessing for adding other plugins like "type"
      if (typeof dataContext.processNode == 'function') { dataContext.processNode(node, item); }

      node.children = getCount(f(getItemId(item))) > 0;
      return node;
    });
  }

  function getContent(item, field) {
    if (mapping && mapping[field]) {
      let f = mapping[field];
      if (typeof f === 'object') {
        return f;
      } else if (typeof f === 'string') {
        return item[f];
      } else if (typeof f === 'function') {
        return f(item, field);
      }
    } else {
      return item[field];
    }
  }

  function getState(item) {
    let content = getContent(item, 'state');
    if (content) return content;

    if (dataContext.select) {
      let state = {
        selected: (getItemId(item) == dataContext.select)
      }
      if (dataContext.openAll || parents.indexOf(getItemId(item)) > -1) {
        state.opened = true;
      }
      return state;
    } else if (dataContext.openAll) {
      return { opened: true };
    }
  }

  // function inspired from tracker.js
  function useComputation(c, f) {
    let savedComputation = Tracker.currentComputation;
    Tracker.currentComputation = c;
    Tracker.active = !! c;

    f();

    Tracker.currentComputation = savedComputation;
    Tracker.active = !! savedComputation;
  }

  instance.autorun((computation) => {
    if (computation.firstRun) {
      // Create tree on first run

      let jsTreeOptions = dataContext.jstree || {};

      jsTreeOptions.core = jsTreeOptions.core || {};
      jsTreeOptions.core.data = jsTreeOptions.core.data ||
        function(node, callback) {

          // The computation is reused to trigger only one refresh of the
          // complete tree.

          useComputation(computation, function() {
            if (node.id === '#') {
              callback(getNodes(dataContext.parent || null));
            } else {
              callback(getNodes(node.id));
            }
          });
        };

      jsTreeOptions.core.check_callback =
        jsTreeOptions.core.check_callback ||
        !! events.create ||
        !! events.rename ||
        !! events.delete ||
        !! events.copy ||
        !! events.move;

      jsTreeOptions.contextmenu = jsTreeOptions.contextmenu || {};
      jsTreeOptions.contextmenu.items = jsTreeOptions.contextmenu.items ||
        function() {
          let items = $.jstree.defaults.contextmenu.items();
          if (! events.create) delete items.create;
          if (! events.rename) delete items.rename;
          if (! events.delete) delete items.remove;
          if (! events.copy) delete items.ccp.submenu.copy;
          if (! events.move) delete items.ccp.submenu.move;
          if (! events.copy && ! events.move) delete items.ccp;

          return items;
        }();

      jsTreeOptions.dnd = jsTreeOptions.dnd || {};
      jsTreeOptions.dnd.always_copy = !! events.copy && ! events.move;
      jsTreeOptions.dnd.copy = !! events.copy;

      let tree = this.$('.js-treeview-content').jstree(jsTreeOptions);

      // Attach events
      function attachEventHandler(eventname, f) {
        if (typeof f == 'function') {
          tree.on(eventname, function(e, data) {
            //console.log(data);
            if (eventname === 'create_node.jstree') {
              tree.jstree().open_node(data.parent);
            }
            let nodeId     = data.selected || (data.original && data.original.id) || data.node.id;

            let parentNode = data.node && tree.jstree().get_node(data.parent);
            let itemNode   = data.node && tree.jstree().get_node(nodeId);

            let newId = f(e, nodeId,
                          {text: data.text,
                            parent: data.parent,
                            position: data.position,
                            item_data: (itemNode && itemNode.data) || {},
                            parent_data: (parentNode && parentNode.data) || {}
                           });

            if (newId === false) {
              ////console.log("Refreshing because of false as return value.")
              tree.jstree().refresh();
            } else if (newId) {
              data.instance.set_id(data.node, newId);
              if (eventname === 'create_node.jstree') {
                openId = data.parent;
                editId = newId;
              }
            }
          });
        }
      }

      attachEventHandler("changed.jstree", events.changed);
      attachEventHandler("create_node.jstree", events.create);
      attachEventHandler("rename_node.jstree", events.rename);
      attachEventHandler("delete_node.jstree", events.delete);
      attachEventHandler("copy_node.jstree", events.copy);
      attachEventHandler("move_node.jstree", events.move);

    } else {
      let tree = this.$('.js-treeview-content').jstree();
      tree.refresh();
      if (editId) {
        //console.log('Calling edit on ' + editId);
        Meteor.setTimeout(function() {
          tree.edit(editId);
          editId = null;
        }, 1000);
      }
    }
  });
});
<|endoftext|>


<commit_before>'use strict'

module.exports = (app) => {
  let slapp = app.slapp
  let kv = app.kv

    slapp.message('view (owners|reviewers|developers)', ['direct_mention', 'direct_message'], (msg, text, role) => {
        var roleList = kv.get(role, (err, role) => {
            if (err) return handleError(err, msg)
        })
        if(roleList == null)
            msg.say("Nothing Found!")
        else
            msg.say(role)
    })

    slapp.message('add myself (owner|reviewer|developer)', ['direct_mention', 'direct_message'], (msg, text, role) => {
        let userObj = GetUserName(msg);

        if(userObj.error)
            return msg.respond(`Sorry, something went wrong. Try again? (${err.message || err})`)

        var roleList = [];

        roleList.push(userObj.text);

        kv.set(role, roleList, (err, role) => {
            if (err) return handleError(err, msg)
        })

        var roleList = kv.get(role, (err, role) => {
            if (err) return handleError(err, msg)
        })

        msg.say("Added " + userObj.text + " to role " + role).say("Current " + role + " list: " + roleList)
    })

    function GetUserName(msg) {
        let userObj = null;

        slapp.client.users.info({ token: msg.meta.bot_token, user: msg.meta.user_id }, (err, data) => {
            if (err){
                userObj.error = true;
                userObj.text = `Sorry, something went wrong. Try again? (${err.message || err})`;
            }
            userObj.text = data.user.name;
        })

        return userObj;
    }

  return {}
}

function handleError (err, msg) {
  console.error(err)

  // Only show errors when we can respond with an ephemeral message
  // So this includes any button actions or slash commands
  if (!msg.body.response_url) return

  msg.respond({
    text: `:scream: Uh Oh: ${err.message || err}`,
    response_type: 'ephemeral',
    replace_original: false
  }, (err) => {
    if (err) console.error('Error handling error:', err)
  })
}<commit_msg>tesrt<commit_after>'use strict'

module.exports = (app) => {
  let slapp = app.slapp
  let kv = app.kv

    slapp.message('view (owners|reviewers|developers)', ['direct_mention', 'direct_message'], (msg, text, role) => {
        var roleList = kv.get(role, (err, role) => {
            if (err) return handleError(err, msg)
        })
        if(roleList == null)
            msg.say("Nothing Found!")
        else
            msg.say(role)
    })

    slapp.message('add myself (owner|reviewer|developer)', ['direct_mention', 'direct_message'], (msg, text, role) => {
        let userObj = GetUserName(msg);

        if(userObj.error)
            return msg.respond(`Sorry, something went wrong. Try again? (${err.message || err})`)

        var roleList = [];

        roleList.push(userObj.text);

        kv.set(role, roleList, (err, role) => {
            if (err) return handleError(err, msg)
        })

        var roleList = kv.get(role, (err, role) => {
            if (err) return handleError(err, msg)
        })

        msg.say("Added " + userObj.text + " to role " + role).say("Current " + role + " list: " + roleList)
    })

    function GetUserName(msg) {
        let userObj = null;

        slapp.client.users.info({ token: msg.meta.bot_token, user: msg.meta.user_id }, (err, data) => {
            if (err){
                userObj.error = true;
                userObj.text = `Sorry, something went wrong. Try again? (${err.message || err})`;
            }
            userObj.error = false;
            userObj.text = data.user.name;
        })

        return userObj;
    }

  return {}
}

function handleError (err, msg) {
  console.error(err)

  // Only show errors when we can respond with an ephemeral message
  // So this includes any button actions or slash commands
  if (!msg.body.response_url) return

  msg.respond({
    text: `:scream: Uh Oh: ${err.message || err}`,
    response_type: 'ephemeral',
    replace_original: false
  }, (err) => {
    if (err) console.error('Error handling error:', err)
  })
}<|endoftext|>


<commit_before>/* * * * * ** * * * * * POINT TEMPLATE UPDATES * * * * * * * * * * * * */

Template.point.p = function () {
    if (Session.get('current_point')) {
        var current_point = Points.find({"name":Session.get('current_point')}).fetch();
        return current_point[0];
    }
}

/* * * * * ** * * * * * MAP TEMPLATE UPDATES * * * * * * * * * * * * * */

Template.map.rendered = function() {
    if (! Session.get('google_maps_initialized'))
        gmaps.initialize();

    Deps.autorun(function() {
        var points = Points.find().fetch();

        _.each(points, function(point) {
            if (typeof point.location !== 'undefined' &&
                typeof point.location.latitude !== 'undefined' &&
                typeof point.location.longitude !== 'undefined') {

                var objMarker = {
                    id: point._id,
                    lat: point.location.latitude,
                    lng: point.location.longitude,
                    title: point.name
                };

                // check if marker already exists
                if (!gmaps.markerExists('id', objMarker.id))
                    gmaps.addMarker(objMarker);

            } else {
            	console.log("Point " + point._id + " has no location")
            }
        });

        gmaps.calcBounds();
    });
}

Template.map.destroyed = function() {
    Session.set('map', false);
}

// * * * * * * * * * * * * * GEO TRACKER * * * * * * * * * * * * * * *

// Used for debugging
geoSuccessManual = function(lat,long) {
    var position = { "coords" : {"latitude":lat,"longitude":long} }
    geoSuccess(position);
}

function geoSuccess(position) {
    if (Session.get('google_maps_initialized'))  {
        gmaps.updateGeoPosition(position.coords.latitude,position.coords.longitude);
        checkIfUserIsNearPoint();
    }
}

var geoOptions = {
  enableHighAccuracy: true,
  maximumAge        : 30000,
  timeout           : 27000
};

function geoError() {
  console.log("Sorry, no position available.");
}

// Initialize the geoTracker when google maps is initialized
var interval = setInterval(function() {
    if (Session.get('google_maps_initialized')) {
        var geoTracker = navigator.geolocation.watchPosition(geoSuccess, geoError, geoOptions);
        clearInterval(interval);
    }
}, 1000);

// * * * * * * * * * * * * SETUP THE LOCATIONS * * * * * * * * * * * * *

clearLocations = function() {
    var points = Points.find().fetch();

    _.each(points, function(point) {
        Points.remove(point._id);
    });
}

setupTest = function() {
    clearLocations();

    Points.insert({
        "name":"Speeltuintje Kuiper",
        "location":{
            "latitude": 51.412034,
            "longitude": 6.032487
        },
        "content" : [
            "Gefeliciteerd, je bent aangekomen op je eerste punt!",
            "CODE: Ik verstop mij graag achter een hoog bord"
        ],
        "img" : "https://lh6.googleusercontent.com/-0wMrAGGKcZo/UOG16lRu-UI/AAAAAAAATgM/2A51mFuPNz8/s912/IMG_4581.JPG"

    });
}

setupFinal = function() {
    clearLocations();

    Points.insert({
        "name":"The Final!",
        "location":{
            "latitude": 51.409491,
            "longitude": 6.041123
        },
        "content" : [
        "TODO: Bel aan op nummertje 19!"
        ],
        "img" : "http://www.allvectors.com/wp-content/uploads/2012/02/puzzle-vector.jpg"
    });
}

setupLocations = function() {
    clearLocations();

    Points.insert({
        "name":"Metieske",
        "location":{
            "latitude":51.412484,
            "longitude":6.035975
        },
        "content" : [
        "Foto: Maak een foto waarbij door de groep en eventueel door figuranten, uitgebeeld wordt dat het nederlands elftal in de 93e minuut van de titel 'Wereldkampioen' beroofd wordt.",
        "Foto: Maak een foto waarin uitgebeeld wordt dat Nederland in de 93e minuut van de finale wereldkampioen wordt.",
        "CODE: Ik ben binnen een pilsje aan het drinken",
        ],
        "img" : "https://lh3.googleusercontent.com/-JY9qJhQeLFc/AAAAAAAAAAI/AAAAAAAAAA0/QEUzphMhs8g/photo.jpg"

    });

    Points.insert({
        "name":"Bijen",
        "location":{
            "latitude":51.416472,
            "longitude":6.038467
        },
        "content" : [
        "TODO: In het begin van de vorige eeuw werd het haar van jonge dames vaak verfraaid met een bloemenkrans. Gebruik je fantasie en maak een prachtige haardecoratie met hetgeen de natuur in het blakterbeekpark je te bieden heeft. De decoratie dient tijdens de tocht door een van de groepsleden gedragen te worden. De decoratie wordt aansluitend aan de organisatie aangeboden.",
        "Foto: Maak een ludieke foto waarbij iemand deze mooie bloemenkrans draagt!",
        "Vraag: Achterhaal wat voor bijensoort vliegt op het Blakterbeekpark en welk schapensoort er rondloopt",
        "CODE: Ik ben aan het schuilen; hoog en droog"
        ],
        "img" : "http://www.depoortpijnacker.nl/wp-content/gallery/divers_1/bijen.jpg"
    });

    Points.insert({
        "name":"Molenberg",
        "location":{
            "latitude":51.415214,
            "longitude":6.031944
        },
        "content" : [
        "TODO: Rondje om de tafel: Welk team houdt het langste de bal in het spel?? Meeste aantal slagen heeft gewonnen.",
        "CODE: Ik vind het gezellig in mijn speelpaleisje!"
        ],
        "img" : "http://www.startpagina.nl/athene/dochters/tafeltennis/images/tafeltennis.jpg"
    });

    Points.insert({
        "name":"Luttel speeltuin",
        "location":{
            "latitude":51.40716,
            "longitude":6.035769
        },
        "content" : [
        "Raadsel: Het heeft een been, maar het kan niet lopen. Het heeft twee vleugels, maar het kan niet vliegen. Het draagt een bril, maar het kan niet zien. Het heeft haar, maar het kan niet gekamd worden?",
        "CODE: Onder een tafeltje zult u mij vinden!"
        ],
        "img" : "http://www.animaatjes.nl/plaatjes/d/dombo/dombo10.gif"
    });

    Points.insert({
        "name":"Vlaggenpunt",
        "location":{
            "latitude":51.408663,
            "longitude":6.02909
        },
        "content" : [
        "Foto: Maak een foto van een zo groot mogelijke menselijke piramide!",
        "CODE: Ik kijk graag op mensen neer"
        ],
        "img" : "http://img.geocaching.com/cache/4acdf6c4-df56-419e-86f8-fd6dcb215c7c.jpg?rnd=0.7269382"
    });

    Points.insert({
        "name":"Ooienvaar",
        "location":{
            "latitude":51.416756,
            "longitude":6.028275
        },
        "content" : [
        "TODO: Maak en schrijf op: De opsomming van geboortedata van opa, oma, kinderen en kleinkinderen Appeldoorn, op leeftijd van groot naar klein. (kalde kant laten we even buiten beschouwing)",
        "CODE: Slijmerig, maar smakelijk. Hakuna Matata!"
        ],
        "img" : "http://www.jandurkspolder.nl/ooievaar%20JDP.JPG"
    });

    Points.insert({
        "name":"Bejaarden",
        "location":{
            "latitude":51.409452,
            "longitude":6.036267
        },
        "content" : [
        "Vraag: Welk gebouw stond er vroeger op de plek waar nu 'ut Valdere' is. In welk jaar werd dit gebouw gesloopt en wie zat er boven op het dak om het gebouw voor sloop te behoeden.",
        "CODE: Het is geen Jan Wolkers"
        ],
        "img" : "http://1.nieuwsbladcdn.be/Assets/Images_Upload/2012/08/29/A2_GOJ3U1KBC010A2_bejaarden01.jpg.h380.jpg"
    });
}

// * * * * * * * * Application Behavior * * * * * ** * * **

DISTANCE_THRESHOLD = 15;

function checkIfUserIsNearPoint() {
    var lat = gmaps.geoPosition.position.k;
    var long = gmaps.geoPosition.position.A;

    // Get all Points
    var points = Points.find().fetch();

    // Loop over all points and check euclidean distance
    Session.set('current_point',false);
    points.forEach(function(point) {
        var d = getDistanceInMeter(point.location.latitude,point.location.longitude,lat,long);
        if (d < DISTANCE_THRESHOLD) {
            Session.set('current_point',point.name);
        }
    });
    if (Session.get('current_point'))
	   $("#point").show("modal");
    else
       $("#point").hide("modal");
}

// * * * * * * * * HELPER FUNCTIONS * * * * * ** * * **

function getDistanceInMeter(lat1,lon1,lat2,lon2) {
  var R = 6371000; // Radius of the earth in m
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}
<commit_msg>geboorte naar schoenmaten<commit_after>/* * * * * ** * * * * * POINT TEMPLATE UPDATES * * * * * * * * * * * * */

Template.point.p = function () {
    if (Session.get('current_point')) {
        var current_point = Points.find({"name":Session.get('current_point')}).fetch();
        return current_point[0];
    }
}

/* * * * * ** * * * * * MAP TEMPLATE UPDATES * * * * * * * * * * * * * */

Template.map.rendered = function() {
    if (! Session.get('google_maps_initialized'))
        gmaps.initialize();

    Deps.autorun(function() {
        var points = Points.find().fetch();

        _.each(points, function(point) {
            if (typeof point.location !== 'undefined' &&
                typeof point.location.latitude !== 'undefined' &&
                typeof point.location.longitude !== 'undefined') {

                var objMarker = {
                    id: point._id,
                    lat: point.location.latitude,
                    lng: point.location.longitude,
                    title: point.name
                };

                // check if marker already exists
                if (!gmaps.markerExists('id', objMarker.id))
                    gmaps.addMarker(objMarker);

            } else {
            	console.log("Point " + point._id + " has no location")
            }
        });

        gmaps.calcBounds();
    });
}

Template.map.destroyed = function() {
    Session.set('map', false);
}

// * * * * * * * * * * * * * GEO TRACKER * * * * * * * * * * * * * * *

// Used for debugging
geoSuccessManual = function(lat,long) {
    var position = { "coords" : {"latitude":lat,"longitude":long} }
    geoSuccess(position);
}

function geoSuccess(position) {
    if (Session.get('google_maps_initialized'))  {
        gmaps.updateGeoPosition(position.coords.latitude,position.coords.longitude);
        checkIfUserIsNearPoint();
    }
}

var geoOptions = {
  enableHighAccuracy: true,
  maximumAge        : 30000,
  timeout           : 27000
};

function geoError() {
  console.log("Sorry, no position available.");
}

// Initialize the geoTracker when google maps is initialized
var interval = setInterval(function() {
    if (Session.get('google_maps_initialized')) {
        var geoTracker = navigator.geolocation.watchPosition(geoSuccess, geoError, geoOptions);
        clearInterval(interval);
    }
}, 1000);

// * * * * * * * * * * * * SETUP THE LOCATIONS * * * * * * * * * * * * *

clearLocations = function() {
    var points = Points.find().fetch();

    _.each(points, function(point) {
        Points.remove(point._id);
    });
}

setupTest = function() {
    clearLocations();

    Points.insert({
        "name":"Speeltuintje Kuiper",
        "location":{
            "latitude": 51.412034,
            "longitude": 6.032487
        },
        "content" : [
            "Gefeliciteerd, je bent aangekomen op je eerste punt!",
            "CODE: Ik verstop mij graag achter een hoog bord"
        ],
        "img" : "https://lh6.googleusercontent.com/-0wMrAGGKcZo/UOG16lRu-UI/AAAAAAAATgM/2A51mFuPNz8/s912/IMG_4581.JPG"

    });
}

setupFinal = function() {
    clearLocations();

    Points.insert({
        "name":"The Final!",
        "location":{
            "latitude": 51.409491,
            "longitude": 6.041123
        },
        "content" : [
        "TODO: Bel aan op nummertje 19!"
        ],
        "img" : "http://www.allvectors.com/wp-content/uploads/2012/02/puzzle-vector.jpg"
    });
}

setupLocations = function() {
    clearLocations();

    Points.insert({
        "name":"Metieske",
        "location":{
            "latitude":51.412484,
            "longitude":6.035975
        },
        "content" : [
        "Foto: Maak een foto waarbij door de groep en eventueel door figuranten, uitgebeeld wordt dat het nederlands elftal in de 93e minuut van de titel 'Wereldkampioen' beroofd wordt.",
        "Foto: Maak een foto waarin uitgebeeld wordt dat Nederland in de 93e minuut van de finale wereldkampioen wordt.",
        "CODE: Ik ben binnen een pilsje aan het drinken",
        ],
        "img" : "https://lh3.googleusercontent.com/-JY9qJhQeLFc/AAAAAAAAAAI/AAAAAAAAAA0/QEUzphMhs8g/photo.jpg"

    });

    Points.insert({
        "name":"Bijen",
        "location":{
            "latitude":51.416472,
            "longitude":6.038467
        },
        "content" : [
        "TODO: In het begin van de vorige eeuw werd het haar van jonge dames vaak verfraaid met een bloemenkrans. Gebruik je fantasie en maak een prachtige haardecoratie met hetgeen de natuur in het blakterbeekpark je te bieden heeft. De decoratie dient tijdens de tocht door een van de groepsleden gedragen te worden. De decoratie wordt aansluitend aan de organisatie aangeboden.",
        "Foto: Maak een ludieke foto waarbij iemand deze mooie bloemenkrans draagt!",
        "Vraag: Achterhaal wat voor bijensoort vliegt op het Blakterbeekpark en welk schapensoort er rondloopt",
        "CODE: Ik ben aan het schuilen; hoog en droog"
        ],
        "img" : "http://www.depoortpijnacker.nl/wp-content/gallery/divers_1/bijen.jpg"
    });

    Points.insert({
        "name":"Molenberg",
        "location":{
            "latitude":51.415214,
            "longitude":6.031944
        },
        "content" : [
        "TODO: Rondje om de tafel: Welk team houdt het langste de bal in het spel?? Meeste aantal slagen heeft gewonnen.",
        "CODE: Ik vind het gezellig in mijn speelpaleisje!"
        ],
        "img" : "http://www.startpagina.nl/athene/dochters/tafeltennis/images/tafeltennis.jpg"
    });

    Points.insert({
        "name":"Luttel speeltuin",
        "location":{
            "latitude":51.40716,
            "longitude":6.035769
        },
        "content" : [
        "Raadsel: Het heeft een been, maar het kan niet lopen. Het heeft twee vleugels, maar het kan niet vliegen. Het draagt een bril, maar het kan niet zien. Het heeft haar, maar het kan niet gekamd worden?",
        "CODE: Onder een tafeltje zult u mij vinden!"
        ],
        "img" : "http://www.animaatjes.nl/plaatjes/d/dombo/dombo10.gif"
    });

    Points.insert({
        "name":"Vlaggenpunt",
        "location":{
            "latitude":51.408663,
            "longitude":6.02909
        },
        "content" : [
        "Foto: Maak een foto van een zo groot mogelijke menselijke piramide!",
        "CODE: Ik kijk graag op mensen neer"
        ],
        "img" : "http://img.geocaching.com/cache/4acdf6c4-df56-419e-86f8-fd6dcb215c7c.jpg?rnd=0.7269382"
    });

    Points.insert({
        "name":"Ooienvaar",
        "location":{
            "latitude":51.416756,
            "longitude":6.028275
        },
        "content" : [
        "TODO: Hoe groot zijn de voeten van de familie eigenlijk? Maak en schrijf op: De opsomming van de schoenmaten van opa, oma, kinderen en kleinkinderen Appeldoorn, op schoenmaat van groot naar klein. (kalde kant laten we even buiten beschouwing)",
        "CODE: Slijmerig, maar smakelijk. Hakuna Matata!"
        ],
        "img" : "http://www.jandurkspolder.nl/ooievaar%20JDP.JPG"
    });

    Points.insert({
        "name":"Bejaarden",
        "location":{
            "latitude":51.409452,
            "longitude":6.036267
        },
        "content" : [
        "Vraag: Welk gebouw stond er vroeger op de plek waar nu 'ut Valdere' is. In welk jaar werd dit gebouw gesloopt en wie zat er boven op het dak om het gebouw voor sloop te behoeden.",
        "CODE: Het is geen Jan Wolkers"
        ],
        "img" : "http://1.nieuwsbladcdn.be/Assets/Images_Upload/2012/08/29/A2_GOJ3U1KBC010A2_bejaarden01.jpg.h380.jpg"
    });
}

// * * * * * * * * Application Behavior * * * * * ** * * **

DISTANCE_THRESHOLD = 15;

function checkIfUserIsNearPoint() {
    var lat = gmaps.geoPosition.position.k;
    var long = gmaps.geoPosition.position.A;

    // Get all Points
    var points = Points.find().fetch();

    // Loop over all points and check euclidean distance
    Session.set('current_point',false);
    points.forEach(function(point) {
        var d = getDistanceInMeter(point.location.latitude,point.location.longitude,lat,long);
        if (d < DISTANCE_THRESHOLD) {
            Session.set('current_point',point.name);
        }
    });
    if (Session.get('current_point'))
	   $("#point").show("modal");
    else
       $("#point").hide("modal");
}

// * * * * * * * * HELPER FUNCTIONS * * * * * ** * * **

function getDistanceInMeter(lat1,lon1,lat2,lon2) {
  var R = 6371000; // Radius of the earth in m
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.dao',
  name: 'FileJournal',
  extends: 'foam.dao.AbstractJournal',
  flags: ['java'],

  javaImports: [
    'foam.core.FObject',
    'foam.core.PropertyInfo',
    'foam.core.ProxyX',
    'foam.lib.json.ExprParser',
    'foam.lib.json.JSONParser',
    'foam.lib.json.Outputter',
    'foam.lib.StoragePropertyPredicate',
    'foam.lib.parse.*',
    'foam.nanos.auth.LastModifiedByAware',
    'foam.nanos.auth.User',
    'foam.nanos.fs.Storage',
    'foam.nanos.logger.Logger',
    'foam.nanos.logger.PrefixLogger',
    'foam.nanos.logger.StdoutLogger',
    'foam.util.SafetyUtil',
    'java.io.BufferedReader',
    'java.io.BufferedWriter',
    'java.io.InputStreamReader',
    'java.io.File',
    'java.io.FileReader',
    'java.io.FileWriter',
    'java.text.SimpleDateFormat',
    'java.util.Calendar',
    'java.util.Iterator',
    'java.util.List',
    'java.util.TimeZone',
    'java.util.regex.Pattern'
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function (cls) {
        cls.extras.push(`
          protected static Pattern COMMENT = Pattern.compile("(/\\\\*([^*]|[\\\\r\\\\n]|(\\\\*+([^*/]|[\\\\r\\\\n])))*\\\\*+/)|(//.*)");

          protected static ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() {
            @Override
            protected StringBuilder initialValue() {
              return new StringBuilder();
            }
            @Override
            public StringBuilder get() {
              StringBuilder b = super.get();
              b.setLength(0);
              return b;
            }
          };

          protected static final ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
            @Override
            protected SimpleDateFormat initialValue() {
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
              sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
              return sdf;
            }
          };
        `);
      }
    }
  ],

  properties: [
    {
      class: 'Object',
      name: 'outputter',
      javaType: 'foam.lib.json.Outputter',
      javaFactory: `return new Outputter(getX()).setPropertyPredicate(new StoragePropertyPredicate());`
    },
    {
      class: 'Object',
      name: 'parser',
      javaType: 'foam.lib.json.JSONParser',
      javaFactory: `return getX().create(JSONParser.class);`
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'dao'
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.logger.Logger',
      name: 'logger',
      javaFactory: `
        Logger logger = (Logger) getX().get("logger");
        if ( logger == null ) {
          logger = new StdoutLogger();
        }
        return new PrefixLogger(new Object[] { "[JDAO]", getFilename() }, logger);
      `
    },
    {
      class: 'String',
      name: 'filename',
      required: true
    },
    {
      class: 'Boolean',
      name: 'multiLine'
    },
    {
      class: 'Boolean',
      name: 'createFile',
      documentation: 'Flag to create file if not present',
      value: true,
    },
    {
      class: 'Object',
      name: 'file',
      javaType: 'java.io.File',
      javaFactory: `
        try {
          getLogger().log("Loading file: " + getFilename());
          File file = getX().get(Storage.class).get(getFilename());
          if ( ! file.exists() ) {
            getLogger().warning("Journal not found:" + getFilename());

            if ( getCreateFile() ) {
              // if output journal does not exist, create one
              File dir = file.getAbsoluteFile().getParentFile();
              if ( ! dir.exists() ) {
                getLogger().log("Create dir: " + dir.getAbsolutePath());
                dir.mkdirs();
              }

              getLogger().log("Create file: " + getFilename());
              file.getAbsoluteFile().createNewFile();
            }
          }
          return file;
        } catch ( Throwable t ) {
          getLogger().error("Failed to read from journal", t);
          throw new RuntimeException(t);
        }
      `
    },
    // reader uses a getter because we want a new reader on file replay
    {
      class: 'Object',
      name: 'reader',
      javaType: 'java.io.BufferedReader',
      javaGetter: `
      try {
        Storage storage = (Storage) getX().get(Storage.class);
        if ( storage.isResource() ) {
          return new BufferedReader(new InputStreamReader(storage.getResourceAsStream(getFilename())));
        } else {
          return new BufferedReader(new FileReader(getFile()));
        }
      } catch ( Throwable t ) {
        getLogger().error("Failed to read from journal", t);
        throw new RuntimeException(t);
      }
      `
    },
    // writer uses a factory because we want to use one writer for the lifetime of this journal object
    {
      class: 'Object',
      name: 'writer',
      javaType: 'java.io.BufferedWriter',
      javaFactory: `
        try {
          BufferedWriter writer = new BufferedWriter(new FileWriter(getFile(), true), 16 * 1024);
          writer.newLine();
          return writer;
        } catch ( Throwable t ) {
          getLogger().error("Failed to create writer", t);
          throw new RuntimeException(t);
        }
      `
    }
  ],

  methods: [
    {
      name: 'put_',
      synchronized: true,
      javaCode: `
        try {
          String record = ( old != null ) ?
            getOutputter().stringifyDelta(old, nu) :
            getOutputter().stringify(nu);

          if ( ! foam.util.SafetyUtil.isEmpty(record) ) {
            writeComment_(x, nu);
            write_(sb.get()
              .append("p(")
              .append(record)
              .append(")")
              .toString());
          }
        } catch ( Throwable t ) {
          getLogger().error("Failed to write put entry to journal", t);
          throw new RuntimeException(t);
        }
      `
    },
    {
      name: 'remove',
      synchronized: true,
      javaCode: `
        try {
          // TODO: Would be more efficient to output the ID portion of the object.  But
          // if ID is an alias or multi part id we should only output the
          // true properties that ID/MultiPartID maps too.
          FObject toWrite = (FObject) obj.getClassInfo().newInstance();
          toWrite.setProperty("id", obj.getProperty("id"));
          String record = getOutputter().stringify(toWrite);

          if ( ! foam.util.SafetyUtil.isEmpty(record) ) {
            writeComment_(x, obj);
            write_(sb.get()
              .append("r(")
              .append(record)
              .append(")")
              .toString());
          }
        } catch ( Throwable t ) {
          getLogger().error("Failed to write remove entry to journal", t);
          throw new RuntimeException(t);
        }
      `
    },
    {
      name: 'write_',
      synchronized: true,
      javaThrows: [
        'java.io.IOException'
      ],
      args: [
        {
          class: 'String',
          name: 'data'
        }
      ],
      javaCode: `
        BufferedWriter writer = getWriter();
        writer.write(data);
        writer.newLine();
        writer.flush();
      `
    },
    {
      name: 'writeComment_',
      synchronized: true,
      javaThrows: [
        'java.io.IOException'
      ],
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'obj',
          type: 'foam.core.FObject'
        }
      ],
      javaCode: `
        if ( x.get("user") == null || ((User) x.get("user")).getId() <= 1 ) return;
        if ( obj instanceof LastModifiedByAware && ((LastModifiedByAware) obj).getLastModifiedBy() != 0L ) return;

        User user = (User) x.get("user");
        Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        write_(sb.get()
          .append("// Modified by ")
          .append(user.label())
          .append(" (")
          .append(user.getId())
          .append(") at ")
          .append(sdf.get().format(now.getTime()))
          .toString());
      `
    },
    {
      name: 'getUnit',
      documentation: 'Reads a syntatically meaningful unit from the journal',
      javacode: `

      `
    },
    {
      name: 'replay',
      documentation: 'Replays the journal file',
      javaCode: `
        // count number of lines successfully read
        int successReading = 0;
        JSONParser parser = getParser();

        try ( BufferedReader reader = getReader() ) {
          for ( String line ; ( line = reader.readLine() ) != null ; ) {
            if ( SafetyUtil.isEmpty(line)        ) continue;
            if ( COMMENT.matcher(line).matches() ) continue;

            try {
              char operation = line.charAt(0);
              int length = line.trim().length();
              line = line.trim().substring(2, length - 1);

              FObject obj = parser.parseString(line);
              if ( obj == null ) {
                getLogger().error("Parse error", getParsingErrorMessage(line), "line:", line);
                continue;
              }

              switch ( operation ) {
                case 'p':
                  foam.core.FObject old = dao.find(obj.getProperty("id"));
                  dao.put(old != null ? mergeFObject(old, obj) : obj);
                  break;

                case 'r':
                  dao.remove(obj);
                  break;
              }

              successReading++;
            } catch ( Throwable t ) {
              getLogger().error("Error replaying journal line:", line, t);
            }
          }
        } catch ( Throwable t) {
          getLogger().error("Failed to read from journal", t);
        }
        getLogger().log("Successfully read " + successReading + " entries from file: " + getFilename());
      `
    },
    {
      name: 'getParsingErrorMessage',
      documentation: 'Gets the result of a failed parsing of a journal line',
      type: 'String',
      args: [
        {
          class: 'String',
          name: 'line'
        }
      ],
      javaCode: `
        Parser        parser = new ExprParser();
        PStream       ps     = new StringPStream();
        ParserContext x      = new ParserContextImpl();

        ((StringPStream) ps).setString(line);
        x.set("X", ( getX() == null ) ? new ProxyX() : getX());

        ErrorReportingPStream eps = new ErrorReportingPStream(ps);
        ps = eps.apply(parser, x);
        return eps.getMessage();
      `
    },
    {
      name: 'mergeFObject',
      type: 'foam.core.FObject',
      documentation: 'Add diff property to old property',
      args: [
        {
          name: 'oldFObject',
          type: 'FObject'
        },
        {
          name: 'diffFObject',
          type: 'FObject'
        }
      ],
      javaCode: `
        //get PropertyInfos
        List list = oldFObject.getClassInfo().getAxiomsByClass(PropertyInfo.class);
        Iterator e = list.iterator();

        while( e.hasNext() ) {
          PropertyInfo prop = (PropertyInfo) e.next();
          mergeProperty(oldFObject, diffFObject, prop);
        }
        return oldFObject;
      `
    },
    {
      name: 'mergeProperty',
      args: [
        {
          name: 'oldFObject',
          type: 'FObject'
        },
        {
          name: 'diffFObject',
          type: 'FObject'
        },
        {
          name: 'prop',
          javaType: 'foam.core.PropertyInfo'
        }
      ],
      javaCode: `
        if ( prop.isSet(diffFObject) ) {
          prop.set(oldFObject, prop.get(diffFObject));
        }
      `
    }
  ]
});
<commit_msg>added try catch<commit_after>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.dao',
  name: 'FileJournal',
  extends: 'foam.dao.AbstractJournal',
  flags: ['java'],

  javaImports: [
    'foam.core.FObject',
    'foam.core.PropertyInfo',
    'foam.core.ProxyX',
    'foam.lib.json.ExprParser',
    'foam.lib.json.JSONParser',
    'foam.lib.json.Outputter',
    'foam.lib.StoragePropertyPredicate',
    'foam.lib.parse.*',
    'foam.nanos.auth.LastModifiedByAware',
    'foam.nanos.auth.User',
    'foam.nanos.fs.Storage',
    'foam.nanos.logger.Logger',
    'foam.nanos.logger.PrefixLogger',
    'foam.nanos.logger.StdoutLogger',
    'foam.util.SafetyUtil',
    'java.io.BufferedReader',
    'java.io.BufferedWriter',
    'java.io.InputStreamReader',
    'java.io.File',
    'java.io.FileReader',
    'java.io.FileWriter',
    'java.text.SimpleDateFormat',
    'java.util.Calendar',
    'java.util.Iterator',
    'java.util.List',
    'java.util.TimeZone',
    'java.util.regex.Pattern'
  ],

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function (cls) {
        cls.extras.push(`
          protected static Pattern COMMENT = Pattern.compile("(/\\\\*([^*]|[\\\\r\\\\n]|(\\\\*+([^*/]|[\\\\r\\\\n])))*\\\\*+/)|(//.*)");

          protected static ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() {
            @Override
            protected StringBuilder initialValue() {
              return new StringBuilder();
            }
            @Override
            public StringBuilder get() {
              StringBuilder b = super.get();
              b.setLength(0);
              return b;
            }
          };

          protected static final ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
            @Override
            protected SimpleDateFormat initialValue() {
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
              sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
              return sdf;
            }
          };
        `);
      }
    }
  ],

  properties: [
    {
      class: 'Object',
      name: 'outputter',
      javaType: 'foam.lib.json.Outputter',
      javaFactory: `return new Outputter(getX()).setPropertyPredicate(new StoragePropertyPredicate());`
    },
    {
      class: 'Object',
      name: 'parser',
      javaType: 'foam.lib.json.JSONParser',
      javaFactory: `return getX().create(JSONParser.class);`
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'dao'
    },
    {
      class: 'FObjectProperty',
      of: 'foam.nanos.logger.Logger',
      name: 'logger',
      javaFactory: `
        Logger logger = (Logger) getX().get("logger");
        if ( logger == null ) {
          logger = new StdoutLogger();
        }
        return new PrefixLogger(new Object[] { "[JDAO]", getFilename() }, logger);
      `
    },
    {
      class: 'String',
      name: 'filename',
      required: true
    },
    {
      class: 'Boolean',
      name: 'multiLine'
    },
    {
      class: 'Boolean',
      name: 'createFile',
      documentation: 'Flag to create file if not present',
      value: true,
    },
    {
      class: 'Object',
      name: 'file',
      javaType: 'java.io.File',
      javaFactory: `
        try {
          getLogger().log("Loading file: " + getFilename());
          File file = getX().get(Storage.class).get(getFilename());
          if ( ! file.exists() ) {
            getLogger().warning("Journal not found:" + getFilename());

            if ( getCreateFile() ) {
              // if output journal does not exist, create one
              File dir = file.getAbsoluteFile().getParentFile();
              if ( ! dir.exists() ) {
                getLogger().log("Create dir: " + dir.getAbsolutePath());
                dir.mkdirs();
              }

              getLogger().log("Create file: " + getFilename());
              file.getAbsoluteFile().createNewFile();
            }
          }
          return file;
        } catch ( Throwable t ) {
          getLogger().error("Failed to read from journal", t);
          throw new RuntimeException(t);
        }
      `
    },
    // reader uses a getter because we want a new reader on file replay
    {
      class: 'Object',
      name: 'reader',
      javaType: 'java.io.BufferedReader',
      javaGetter: `
      try {
        Storage storage = (Storage) getX().get(Storage.class);
        if ( storage.isResource() ) {
          return new BufferedReader(new InputStreamReader(storage.getResourceAsStream(getFilename())));
        } else {
          return new BufferedReader(new FileReader(getFile()));
        }
      } catch ( Throwable t ) {
        getLogger().error("Failed to read from journal", t);
        throw new RuntimeException(t);
      }
      `
    },
    // writer uses a factory because we want to use one writer for the lifetime of this journal object
    {
      class: 'Object',
      name: 'writer',
      javaType: 'java.io.BufferedWriter',
      javaFactory: `
        try {
          BufferedWriter writer = new BufferedWriter(new FileWriter(getFile(), true), 16 * 1024);
          writer.newLine();
          return writer;
        } catch ( Throwable t ) {
          getLogger().error("Failed to create writer", t);
          throw new RuntimeException(t);
        }
      `
    }
  ],

  methods: [
    {
      name: 'put_',
      synchronized: true,
      javaCode: `
        try {
          String record = ( old != null ) ?
            getOutputter().stringifyDelta(old, nu) :
            getOutputter().stringify(nu);

          if ( ! foam.util.SafetyUtil.isEmpty(record) ) {
            writeComment_(x, nu);
            write_(sb.get()
              .append("p(")
              .append(record)
              .append(")")
              .toString());
          }
        } catch ( Throwable t ) {
          getLogger().error("Failed to write put entry to journal", t);
          throw new RuntimeException(t);
        }
      `
    },
    {
      name: 'remove',
      synchronized: true,
      javaCode: `
        try {
          // TODO: Would be more efficient to output the ID portion of the object.  But
          // if ID is an alias or multi part id we should only output the
          // true properties that ID/MultiPartID maps too.
          FObject toWrite = (FObject) obj.getClassInfo().newInstance();
          toWrite.setProperty("id", obj.getProperty("id"));
          String record = getOutputter().stringify(toWrite);

          if ( ! foam.util.SafetyUtil.isEmpty(record) ) {
            writeComment_(x, obj);
            write_(sb.get()
              .append("r(")
              .append(record)
              .append(")")
              .toString());
          }
        } catch ( Throwable t ) {
          getLogger().error("Failed to write remove entry to journal", t);
          throw new RuntimeException(t);
        }
      `
    },
    {
      name: 'write_',
      synchronized: true,
      javaThrows: [
        'java.io.IOException'
      ],
      args: [
        {
          class: 'String',
          name: 'data'
        }
      ],
      javaCode: `
        BufferedWriter writer = getWriter();
        writer.write(data);
        writer.newLine();
        writer.flush();
      `
    },
    {
      name: 'writeComment_',
      synchronized: true,
      javaThrows: [
        'java.io.IOException'
      ],
      args: [
        {
          name: 'x',
          type: 'Context'
        },
        {
          name: 'obj',
          type: 'foam.core.FObject'
        }
      ],
      javaCode: `
        if ( x.get("user") == null || ((User) x.get("user")).getId() <= 1 ) return;
        if ( obj instanceof LastModifiedByAware && ((LastModifiedByAware) obj).getLastModifiedBy() != 0L ) return;

        User user = (User) x.get("user");
        Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        write_(sb.get()
          .append("// Modified by ")
          .append(user.label())
          .append(" (")
          .append(user.getId())
          .append(") at ")
          .append(sdf.get().format(now.getTime()))
          .toString());
      `
    },
    {
      name: 'getUnit',
      documentation: 'Reads a syntatically meaningful unit from the journal',
      type: 'String',
      args: [
        {
          name: 'reader',
          type: 'BufferedReader'
        }
      ],
      javaCode: `
        return reader.readLine();
      `
    },
    {
      name: 'replay',
      documentation: 'Replays the journal file',
      javaCode: `
        // count number of lines successfully read
        int successReading = 0;
        JSONParser parser = getParser();

        try ( BufferedReader reader = getReader() ) {
          for ( String line ; ( line = getUnit(reader) ) != null ; ) {
            if ( SafetyUtil.isEmpty(line)        ) continue;
            if ( COMMENT.matcher(line).matches() ) continue;

            try {
              char operation = line.charAt(0);
              int length = line.trim().length();
              line = line.trim().substring(2, length - 1);

              FObject obj = parser.parseString(line);
              if ( obj == null ) {
                getLogger().error("Parse error", getParsingErrorMessage(line), "line:", line);
                continue;
              }

              switch ( operation ) {
                case 'p':
                  foam.core.FObject old = dao.find(obj.getProperty("id"));
                  dao.put(old != null ? mergeFObject(old, obj) : obj);
                  break;

                case 'r':
                  dao.remove(obj);
                  break;
              }

              successReading++;
            } catch ( Throwable t ) {
              getLogger().error("Error replaying journal line:", line, t);
            }
          }
        } catch ( Throwable t) {
          getLogger().error("Failed to read from journal", t);
        } finally {
          getLogger().log("Successfully read " + successReading + " entries from file: " + getFilename());
        }
      `
    },
    {
      name: 'getParsingErrorMessage',
      documentation: 'Gets the result of a failed parsing of a journal line',
      type: 'String',
      args: [
        {
          class: 'String',
          name: 'line'
        }
      ],
      javaCode: `
        Parser        parser = new ExprParser();
        PStream       ps     = new StringPStream();
        ParserContext x      = new ParserContextImpl();

        ((StringPStream) ps).setString(line);
        x.set("X", ( getX() == null ) ? new ProxyX() : getX());

        ErrorReportingPStream eps = new ErrorReportingPStream(ps);
        ps = eps.apply(parser, x);
        return eps.getMessage();
      `
    },
    {
      name: 'mergeFObject',
      type: 'foam.core.FObject',
      documentation: 'Add diff property to old property',
      args: [
        {
          name: 'oldFObject',
          type: 'FObject'
        },
        {
          name: 'diffFObject',
          type: 'FObject'
        }
      ],
      javaCode: `
        //get PropertyInfos
        List list = oldFObject.getClassInfo().getAxiomsByClass(PropertyInfo.class);
        Iterator e = list.iterator();

        while( e.hasNext() ) {
          PropertyInfo prop = (PropertyInfo) e.next();
          mergeProperty(oldFObject, diffFObject, prop);
        }
        return oldFObject;
      `
    },
    {
      name: 'mergeProperty',
      args: [
        {
          name: 'oldFObject',
          type: 'FObject'
        },
        {
          name: 'diffFObject',
          type: 'FObject'
        },
        {
          name: 'prop',
          javaType: 'foam.core.PropertyInfo'
        }
      ],
      javaCode: `
        if ( prop.isSet(diffFObject) ) {
          prop.set(oldFObject, prop.get(diffFObject));
        }
      `
    }
  ]
});
<|endoftext|>


<commit_before>module.exports = {
  parser : 'babel-eslint',
  extends: 'airbnb',
  settings: {
    'import/resolver': 'webpack'
  },
  globals: {
    $        : false,
    _        : false,
    __dirname: false,
    Backbone : false,
    cui      : false,
    describe : false,
    expect   : false,
    exports  : false,
    it       : false,
    jQuery   : false,
    module   : false,
    require  : false
  },

  rules: {

    /*
     *
     * React-related rules
     *
     */

    // Forcing spacing with braces in jsx
    'react/jsx-curly-spacing': [2, 'always'],

    // we want to explicitly define boolean values within jsx
    'react/jsx-boolean-value': [2, 'always'],

    /*
     *
     * Extra ES6-related restrictions and misc AirBnB overrides
     *
     */
    // GUI team has decided against dangling commas
    'comma-dangle'   : [2, 'never'],
    'callback-return': 2,

    // The consistency checks do not match our early-returns + normal callback coding style
    'consistent-return': 0,

    // Relaxed but consistent usage of braces
    curly: [2, 'multi-line', 'consistent'],

    // Functions can be anonymous when used as an argument
    'func-names': 0,

    // Enforces how MDN writes their generators
    'generator-star-spacing': [2, { before: false, after: true }],
    'handle-callback-err'   : [2, '^(err|.*(e|E)rror)'],
    indent                  : [2, 2, {
      SwitchCase        : 1,
      VariableDeclarator: { var: 2, let: 2, const: 3 }
    }],

    // Align on colon to use auto-fix to prettify large objects
    'key-spacing': [
      2, {
        singleLine: { beforeColon: false, afterColon: true },
        multiLine : { beforeColon: false, afterColon: true, align: 'colon' }
      }
    ],
    'lines-around-comment': [2, {
      beforeBlockComment: true,
      beforeLineComment : true,
      allowBlockStart   : true,
      allowObjectStart  : true
    }],

    // Should not leak stuff to clientside
    'no-console': 2,

    // Allow multiple spaces only in certain situations involving aligned white spaces
    'no-multi-spaces': [2, {
      exceptions: {
        ImportDeclaration : true,
        Property          : true,
        LogicalExpression : true,
        VariableDeclarator: true
      }
    }],

    // Do not allow shadowed functions except in cases of extremely common parameter names
    'no-shadow': [2, { allow: ['callback', 'cb', 'done', 'err', 'error', 'next', 'req', 'res'] }],

    // We directly modify the `req` parameter in routing middleware
    'no-param-reassign': [2, { props: false }],

    // Currently a standard usage in GUI js
    'no-underscore-dangle': 0,

    // Only enforce shorthand on properties because doing so on methods produces weird behavior with anonymous fn
    'object-shorthand': [2, 'properties'],

    // Aggregate uninitialized declarations into one line. Otherwise, use multiple
    'one-var': [2, { uninitialized: 'always', initialized: 'never' }],

    // We allow developers to add padded blocks if they aid readability
    'padded-blocks': 0,

    // We do not gain anything from forcing multiline arrow functions
    'prefer-arrow-callback': 0,

    // Benefit of string templates is not worth all the white noise of current GUI infractions
    'prefer-template': 0,

    // We do not like space before the first parenthesis in function decl
    'space-before-function-paren': [2, 'never'],
    'spaced-comment'             : [2, 'always', {
      line: {
        markers: ['/', 'global']
      },
      block: {
        exceptions: ['*'],
        balanced  : true
      }
    }],

    // With modules, `use-strict` is superfluous but we have a mixed building system
    strict: 0,

    /*
     *
     * Taken & adapted from Cloudability GUI's eslint
     *
     */
    'brace-style'    : [2, '1tbs', { allowSingleLine: false }],
    'consistent-this': [2, 'self'],
    'func-style'     : [2, 'declaration', { allowArrowFunctions: true }],

    // 'new-cap': [2, {'capIsNew': false}],
    'operator-linebreak': [2, 'after'],

    // Stuff taken & adapted from Datahero's unfinished eslint
    'no-alert'             : 2,
    'no-bitwise'           : 2,
    'no-constant-condition': 2,
    'no-unused-vars'       : [2, {
      vars: 'all',
      args: 'after-used',

      argsIgnorePattern: 'callback|done|next',
      varsIgnorePattern: '_|colors'
    }],
    'no-use-before-define': [2, 'nofunc'],
    'max-len'             : [2, {
      code    : 120,
      tabWidth: 2,

      ignoreTrailingComments: true,
      ignoreUrls            : true
    }],
    'use-isnan': 2
  }
};
<commit_msg>update globals<commit_after>module.exports = {
  parser : 'babel-eslint',
  extends: 'airbnb',
  settings: {
    'import/resolver': 'webpack'
  },
  env: {
    browser: true,
    node   : true
  },
  globals: {
    $        : false,
    _        : false,
    Backbone : false,
    jQuery   : false,
    describe : false,
    expect   : false,
    it       : false,

    cui       : false,
    Highcharts: false
  },

  rules: {

    /*
     *
     * React-related rules
     *
     */

    // Forcing spacing with braces in jsx
    'react/jsx-curly-spacing': [2, 'always'],

    // we want to explicitly define boolean values within jsx
    'react/jsx-boolean-value': [2, 'always'],

    /*
     *
     * Extra ES6-related restrictions and misc AirBnB overrides
     *
     */
    // GUI team has decided against dangling commas
    'comma-dangle'   : [2, 'never'],
    'callback-return': 2,

    // The consistency checks do not match our early-returns + normal callback coding style
    'consistent-return': 0,

    // Relaxed but consistent usage of braces
    curly: [2, 'multi-line', 'consistent'],

    // Functions can be anonymous when used as an argument
    'func-names': 0,

    // Enforces how MDN writes their generators
    'generator-star-spacing': [2, { before: false, after: true }],
    'handle-callback-err'   : [2, '^(err|.*(e|E)rror)'],
    indent                  : [2, 2, {
      SwitchCase        : 1,
      VariableDeclarator: { var: 2, let: 2, const: 3 }
    }],

    // Align on colon to use auto-fix to prettify large objects
    'key-spacing': [
      2, {
        singleLine: { beforeColon: false, afterColon: true },
        multiLine : { beforeColon: false, afterColon: true, align: 'colon' }
      }
    ],
    'lines-around-comment': [2, {
      beforeBlockComment: true,
      beforeLineComment : true,
      allowBlockStart   : true,
      allowObjectStart  : true
    }],

    // Should not leak stuff to clientside
    'no-console': 2,

    // Allow multiple spaces only in certain situations involving aligned white spaces
    'no-multi-spaces': [2, {
      exceptions: {
        ImportDeclaration : true,
        Property          : true,
        LogicalExpression : true,
        VariableDeclarator: true
      }
    }],

    // Do not allow shadowed functions except in cases of extremely common parameter names
    'no-shadow': [2, { allow: ['callback', 'cb', 'done', 'err', 'error', 'next', 'req', 'res'] }],

    // We directly modify the `req` parameter in routing middleware
    'no-param-reassign': [2, { props: false }],

    // Currently a standard usage in GUI js
    'no-underscore-dangle': 0,

    // Only enforce shorthand on properties because doing so on methods produces weird behavior with anonymous fn
    'object-shorthand': [2, 'properties'],

    // Aggregate uninitialized declarations into one line. Otherwise, use multiple
    'one-var': [2, { uninitialized: 'always', initialized: 'never' }],

    // We allow developers to add padded blocks if they aid readability
    'padded-blocks': 0,

    // We do not gain anything from forcing multiline arrow functions
    'prefer-arrow-callback': 0,

    // Benefit of string templates is not worth all the white noise of current GUI infractions
    'prefer-template': 0,

    // We do not like space before the first parenthesis in function decl
    'space-before-function-paren': [2, 'never'],
    'spaced-comment'             : [2, 'always', {
      line: {
        markers: ['/', 'global']
      },
      block: {
        exceptions: ['*'],
        balanced  : true
      }
    }],

    // With modules, `use-strict` is superfluous but we have a mixed building system
    strict: 0,

    /*
     *
     * Taken & adapted from Cloudability GUI's eslint
     *
     */
    'brace-style'    : [2, '1tbs', { allowSingleLine: false }],
    'consistent-this': [2, 'self'],
    'func-style'     : [2, 'declaration', { allowArrowFunctions: true }],

    // 'new-cap': [2, {'capIsNew': false}],
    'operator-linebreak': [2, 'after'],

    // Stuff taken & adapted from Datahero's unfinished eslint
    'no-alert'             : 2,
    'no-bitwise'           : 2,
    'no-constant-condition': 2,
    'no-unused-vars'       : [2, {
      vars: 'all',
      args: 'after-used',

      argsIgnorePattern: 'callback|done|next',
      varsIgnorePattern: '_|colors'
    }],
    'no-use-before-define': [2, 'nofunc'],
    'max-len'             : [2, {
      code    : 120,
      tabWidth: 2,

      ignoreTrailingComments: true,
      ignoreUrls            : true
    }],
    'use-isnan': 2
  }
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 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.
 */

/**
  A Faceted Axiom, when added to a Class, makes it implement
  the Facet-Manager Pattern, meaning that calls to create() can
  be intercepted and return a special Facet class depending on the
  value of the 'of' create argument.

  Ex.:
  foam.CLASS({
    name: 'View',
    axioms: [ foam.pattern.Faceted.create() ],
    properties: [ 'of' ],
    methods: [ function view() { return 'default' } ]
  });

  foam.CLASS({name: 'A'});
  foam.CLASS({name: 'B'});
  foam.CLASS({name: 'C'});
  foam.CLASS({name: 'BView', extends: 'View', methods: [function view() { return 'BView'; }]});
  foam.CLASS({name: 'CView', extends: 'View', methods: [function view() { return 'CView'; }]});

  console.log(View.create({of: A}));
  console.log(View.create({of: B}));
  console.log(View.create({of: C}));
*/
// FUTURE: add createOriginal() (or similar) method.
foam.CLASS({
  package: 'foam.pattern',
  name: 'Faceted',

  methods: [
    function installInClass(cls) {
      var oldCreate = cls.create;

      cls.getFacetOf = function(of, X) {
        if ( ! of ) return this;
        X = X || foam.__context__;

        var name   = foam.String.isInstance(of) ? of : of.name;
        var facets = this.private_.facets || ( this.private_.facets = {} );

        if ( ! facets.hasOwnProperty(name) ) {
          var id = this.package ?
            this.package + '.' + name + this.name :
            name + this.name ;
          facets[name] = X.lookup(id, true) || this;
        }

        return facets[name];
      };

      // ignoreFacets is set to true when called to prevent a second-level
      // of facet checking
      cls.create = function(args, X, ignoreFacets) {
        if ( ! ignoreFacets ) {
          var facetCls = this.getFacetOf(args && args.of, X);

          if ( facetCls ) return facetCls.create(args, X, true);
        }

        return oldCreate.apply(this, arguments);
      }
    }
  ]
});
<commit_msg>Add name to faceted axiom so it doesn't conflict with any anonymous ones.<commit_after>/**
 * @license
 * Copyright 2017 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.
 */

/**
  A Faceted Axiom, when added to a Class, makes it implement
  the Facet-Manager Pattern, meaning that calls to create() can
  be intercepted and return a special Facet class depending on the
  value of the 'of' create argument.

  Ex.:
  foam.CLASS({
    name: 'View',
    axioms: [ foam.pattern.Faceted.create() ],
    properties: [ 'of' ],
    methods: [ function view() { return 'default' } ]
  });

  foam.CLASS({name: 'A'});
  foam.CLASS({name: 'B'});
  foam.CLASS({name: 'C'});
  foam.CLASS({name: 'BView', extends: 'View', methods: [function view() { return 'BView'; }]});
  foam.CLASS({name: 'CView', extends: 'View', methods: [function view() { return 'CView'; }]});

  console.log(View.create({of: A}));
  console.log(View.create({of: B}));
  console.log(View.create({of: C}));
*/
// FUTURE: add createOriginal() (or similar) method.
foam.CLASS({
  package: 'foam.pattern',
  name: 'Faceted',

  methods: [
    function installInClass(cls) {
      var oldCreate = cls.create;

      cls.getFacetOf = function(of, X) {
        if ( ! of ) return this;
        X = X || foam.__context__;

        var name   = foam.String.isInstance(of) ? of : of.name;
        var facets = this.private_.facets || ( this.private_.facets = {} );

        if ( ! facets.hasOwnProperty(name) ) {
          var id = this.package ?
            this.package + '.' + name + this.name :
            name + this.name ;
          facets[name] = X.lookup(id, true) || this;
        }

        return facets[name];
      };

      // ignoreFacets is set to true when called to prevent a second-level
      // of facet checking
      cls.create = function(args, X, ignoreFacets) {
        if ( ! ignoreFacets ) {
          var facetCls = this.getFacetOf(args && args.of, X);

          if ( facetCls ) return facetCls.create(args, X, true);
        }

        return oldCreate.apply(this, arguments);
      }
    }
  ],

  properties: [
    ['name', 'foam.pattern.Faceted']
  ]
});
<|endoftext|>


<commit_before>'use strict';

var _jshintConfig = require('../config/jshint');
var _scriptsFolder = 'scripts';
var _scriptsSrcPath = _paths.src + '/' + _scriptsFolder;
var _libsFilter = $.filter(['*', '!' + _scriptsSrcPath + '/libs/*.js']);

gulp.task('_scripts', function () {
	var _scriptsDistPath = _paths.tmp + '/' + _scriptsFolder;

	return gulp.src(_scriptsSrcPath + '/**/*.js')

		.pipe($.plumber({
			errorHandler: $.notify.onError({
				title: "Scripts task failed",
				message: "<%= error.message %>"
			})
		}))

		.pipe(_libsFilter)
		.pipe($.jshint(_jshintConfig))
		.pipe($.jshint.reporter('jshint-stylish'))
		.pipe($.jshint.reporter('fail'))
		.pipe(_libsFilter.restore())

		.pipe($.if(_paths.current === _paths.dist, $.uglify()))

		.pipe(gulp.dest(_scriptsDistPath))

		.pipe(reload({stream: true}));
});

// Scripts task
gulp.task('scripts', function (callback) {
	runSequence('_scripts', callback);

	// Watch all js files in scripts folder
	gulp.watch(_scriptsSrcPath + '/**/*.js', ['_scripts']);
});
<commit_msg>Fix _scriptsDistPath variable<commit_after>'use strict';

var _jshintConfig = require('../config/jshint');
var _scriptsFolder = 'scripts';
var _scriptsSrcPath = _paths.src + '/' + _scriptsFolder;
var _libsFilter = $.filter(['*', '!' + _scriptsSrcPath + '/libs/*.js']);

gulp.task('_scripts', function () {
	var _scriptsDistPath = _paths.current + '/' + _scriptsFolder;

	return gulp.src(_scriptsSrcPath + '/**/*.js')

		.pipe($.plumber({
			errorHandler: $.notify.onError({
				title: "Scripts task failed",
				message: "<%= error.message %>"
			})
		}))

		.pipe(_libsFilter)
		.pipe($.jshint(_jshintConfig))
		.pipe($.jshint.reporter('jshint-stylish'))
		.pipe($.jshint.reporter('fail'))
		.pipe(_libsFilter.restore())

		.pipe($.if(_paths.current === _paths.dist, $.uglify()))

		.pipe(gulp.dest(_scriptsDistPath))

		.pipe(reload({stream: true}));
});

// Scripts task
gulp.task('scripts', function (callback) {
	runSequence('_scripts', callback);

	// Watch all js files in scripts folder
	gulp.watch(_scriptsSrcPath + '/**/*.js', ['_scripts']);
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'CitationView',
  extends: 'foam.u2.View',

  axioms: [
    foam.pattern.Faceted.create()
  ],

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      class: 'String',
      name: 'summary'
    }
  ],

  reactions: [
    ['', 'propertyChange.data', 'updateSummary'],
    ['data', 'propertyChange', 'updateSummary']
  ],

  listeners: [
    {
      name: 'updateSummary',
      isFramed: true,
      code: function() {
        this.summary = this.data && this.data.toSummary ? this.data.toSummary() : undefined;
      }
    }
  ],

  methods: [
   function initE() {
      this.SUPER();
      this.updateSummary();
      this.add(this.summary$);
    }
  ]
});
<commit_msg>Fix indentation.<commit_after>/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'CitationView',
  extends: 'foam.u2.View',

  axioms: [
    foam.pattern.Faceted.create()
  ],

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      class: 'String',
      name: 'summary'
    }
  ],

  reactions: [
    ['', 'propertyChange.data', 'updateSummary'],
    ['data', 'propertyChange', 'updateSummary']
  ],

  listeners: [
    {
      name: 'updateSummary',
      isFramed: true,
      code: function() {
        this.summary = this.data && this.data.toSummary ? this.data.toSummary() : undefined;
      }
    }
  ],

  methods: [
    function initE() {
      this.SUPER();
      this.updateSummary();
      this.add(this.summary$);
    }
  ]
});
<|endoftext|>


<commit_before>const browserSync = require('browser-sync')
const gulp = require('gulp')
const gutil = require('gulp-util')
const webpack = require('webpack')

const webpackTask = function (callback) {
  var initialCompile = false
  return function (err, stats) {
    if (err) {
      throw new gutil.PluginError('webpack:build', err)
    }
    browserSync.reload()
    gutil.log('[webpack:build] Completed\n' + stats.toString({
      assets: true,
      chunks: false,
      chunkModules: false,
      colors: true,
      hash: false,
      timings: false,
      version: false
    }))
    if (!initialCompile) {
      initialCompile = true
      callback()
    }
  }
}

module.exports = function (webpackConfig, config) {
  gulp.task('webpack:build', function (callback) {
    config.webpack.production = true
    webpack(webpackConfig(config.webpack), webpackTask(callback))
  })

  gulp.task('webpack:watch', function (callback) {
    webpack(webpackConfig(config.webpack)).watch(null, webpackTask(callback))
  })
}
<commit_msg>build(webpack): trigger file deletion for files processed by webpack<commit_after>const path = require('path')
const fs = require('fs')
const browserSync = require('browser-sync')
const gulp = require('gulp')
const gutil = require('gulp-util')
const webpack = require('webpack')

let previousAssets = []

function removeUnusedAssets (stats) {
  const basePath = path.join(
    stats.compilation.options.context,
    stats.compilation.outputOptions.path
  )
  const currentAssets = Object.keys(stats.compilation.assets)
  const unusedAssets = previousAssets.filter(function (asset) {
    return currentAssets.indexOf(asset) === -1
  })
  unusedAssets.forEach(function (asset) {
    const assetPath = path.join(basePath, asset)
    if (fs.existsSync(assetPath)) {
      fs.unlinkSync(assetPath)
    }
  })
  previousAssets = currentAssets
}

const webpackTask = function (callback) {
  var initialCompile = false
  return function (err, stats) {
    if (err) {
      throw new gutil.PluginError('webpack:build', err)
    }
    removeUnusedAssets(stats)
    browserSync.reload()
    gutil.log('[webpack:build] Completed\n' + stats.toString({
      assets: true,
      chunks: false,
      chunkModules: false,
      colors: true,
      hash: false,
      timings: false,
      version: false
    }))
    if (!initialCompile) {
      initialCompile = true
      callback()
    }
  }
}

module.exports = function (webpackConfig, config) {
  gulp.task('webpack:build', function (callback) {
    config.webpack.production = true
    webpack(webpackConfig(config.webpack), webpackTask(callback))
  })

  gulp.task('webpack:watch', function (callback) {
    webpack(webpackConfig(config.webpack)).watch(null, webpackTask(callback))
  })
}
<|endoftext|>