<commit_before>import React from 'react';
import {
  ListView,
  RefreshControl,
  View
} from 'react-native';

import Footer from './Footer';
import Story from './Story';

const renderSeparator = (sectionID, rowID, adjacentRowHighlighted) =>
  <View
    key={`${sectionID}-${rowID}`}
    style={{
      height: adjacentRowHighlighted ? 4 : 1,
      backgroundColor: adjacentRowHighlighted ? '#3B5998' : '#CCCCCC',
    }}
  />

export default StoriesListView = ({ dataSource, onStoryPress, refreshing, onRefresh, loadMore }) =>
  <ListView
    dataSource={dataSource}
    renderRow={(rowData, sectionID, rowID) => (
      <Story
        onPress={() => {
          console.log(rowData);
          onStoryPress(rowData);
        }}
        title={rowData.title}
        points={rowData.points}
        user={rowData.user}
        timeAgo={rowData.time_ago}
        commentsCount={rowData.comments_count}
        key={rowID} />
    )}
    refreshControl={
      <RefreshControl
        refreshing={refreshing}
        onRefresh={onRefresh}
      />
    }
    renderFooter={() => <Footer loadMore={loadMore} key="footer" />}
    renderSeparator={renderSeparator}
    enableEmptySections={true}
    pageSize={30}
  /><commit_msg>Hide load more button if no stories<commit_after>import React from 'react';
import {
  ListView,
  RefreshControl,
  View
} from 'react-native';

import Footer from './Footer';
import Story from './Story';

const renderSeparator = (sectionID, rowID, adjacentRowHighlighted) =>
  <View
    key={`${sectionID}-${rowID}`}
    style={{
      height: adjacentRowHighlighted ? 4 : 1,
      backgroundColor: adjacentRowHighlighted ? '#3B5998' : '#CCCCCC',
    }}
  />

export default StoriesListView = ({ dataSource, onStoryPress, refreshing, onRefresh, loadMore }) =>
  <ListView
    dataSource={dataSource}
    renderRow={(rowData, sectionID, rowID) => (
      <Story
        onPress={() => {
          console.log(rowData);
          onStoryPress(rowData);
        }}
        title={rowData.title}
        points={rowData.points}
        user={rowData.user}
        timeAgo={rowData.time_ago}
        commentsCount={rowData.comments_count}
        key={rowID} />
    )}
    refreshControl={
      <RefreshControl
        refreshing={refreshing}
        onRefresh={onRefresh}
      />
    }
    renderFooter={() => dataSource.getRowCount() > 0 ? <Footer loadMore={loadMore} key="footer" /> : null}
    renderSeparator={renderSeparator}
    enableEmptySections={true}
    pageSize={30}
  /><|endoftext|>


<commit_before>/**
 * @author qiao / https://github.com/qiao
 * @author mrdoob / http://mrdoob.com
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 */

THREE.EditorControls = function ( object, domElement ) {

	this.object = object;
	this.domElement = ( domElement !== undefined ) ? domElement : document;

	// API

	this.enabled = true;

	this.center = new THREE.Vector3();

	// internals

	var scope = this;
	var normalMatrix = new THREE.Matrix3();

	var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2 };
	var state = STATE.NONE;

	// events

	var changeEvent = { type: 'change' };

	this.pan = function ( distance ) {

		normalMatrix.getNormalMatrix( this.object.matrix );

		distance.applyMatrix3( normalMatrix );

		this.object.position.add( distance );
		this.center.add( distance );

		this.dispatchEvent( changeEvent );

	};

	this.rotate = function ( delta ) {

		var position = this.object.position;
		var offset = position.clone().sub( this.center );

		var theta = Math.atan2( offset.x, offset.z );
		var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );

		theta += delta.x;
		phi += delta.y;

		var EPS = 0.000001;

		phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );

		var radius = offset.length();

		offset.x = radius * Math.sin( phi ) * Math.sin( theta );
		offset.y = radius * Math.cos( phi );
		offset.z = radius * Math.sin( phi ) * Math.cos( theta );

		position.copy( this.center ).add( offset );

		this.object.lookAt( this.center );

		this.dispatchEvent( changeEvent );

	};

	function onMouseDown( event ) {

		if ( scope.enabled === false ) return;

		event.preventDefault();

		if ( event.button === 0 ) {

			state = STATE.ROTATE;

		} else if ( event.button === 1 ) {

			state = STATE.ZOOM;

		} else if ( event.button === 2 ) {

			state = STATE.PAN;

		}

		document.addEventListener( 'mousemove', onMouseMove, false );
		document.addEventListener( 'mouseup', onMouseUp, false );

	}

	function onMouseMove( event ) {

		if ( scope.enabled === false ) return;

		event.preventDefault();

		var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
		var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;

		if ( state === STATE.ROTATE ) {

			scope.rotate( new THREE.Vector3( - movementX * 0.005, - movementY * 0.005, 0 ) );

		} else if ( state === STATE.ZOOM ) {

			scope.pan( new THREE.Vector3( 0, 0, movementY ) );

		} else if ( state === STATE.PAN ) {

			scope.pan( new THREE.Vector3( - movementX * 0.5, movementY * 0.5, 0 ) );

		}

	}

	function onMouseUp( event ) {

		if ( scope.enabled === false ) return;

		document.removeEventListener( 'mousemove', onMouseMove, false );
		document.removeEventListener( 'mouseup', onMouseUp, false );

		state = STATE.NONE;

	}

	function onMouseWheel( event ) {

		if ( scope.enabled === false ) return;

		var delta = 0;

		if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9

			delta = - event.wheelDelta;

		} else if ( event.detail ) { // Firefox

			delta = event.detail;

		}

		scope.pan( new THREE.Vector3( 0, 0, delta * 0.1 ) );

	}

	this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
	this.domElement.addEventListener( 'mousedown', onMouseDown, false );
	this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
	this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox

};

THREE.EditorControls.prototype = Object.create( THREE.EventDispatcher.prototype );
<commit_msg>EditorControls: Tweaks for Firefox...<commit_after>/**
 * @author qiao / https://github.com/qiao
 * @author mrdoob / http://mrdoob.com
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 */

THREE.EditorControls = function ( object, domElement ) {

	this.object = object;
	this.domElement = ( domElement !== undefined ) ? domElement : document;

	// API

	this.enabled = true;

	this.center = new THREE.Vector3();

	// internals

	var scope = this;
	var normalMatrix = new THREE.Matrix3();

	var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2 };
	var state = STATE.NONE;

	// events

	var changeEvent = { type: 'change' };

	this.pan = function ( distance ) {

		normalMatrix.getNormalMatrix( this.object.matrix );

		distance.applyMatrix3( normalMatrix );

		this.object.position.add( distance );
		this.center.add( distance );

		this.dispatchEvent( changeEvent );

	};

	this.rotate = function ( delta ) {

		var position = this.object.position;
		var offset = position.clone().sub( this.center );

		var theta = Math.atan2( offset.x, offset.z );
		var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );

		theta += delta.x;
		phi += delta.y;

		var EPS = 0.000001;

		phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );

		var radius = offset.length();

		offset.x = radius * Math.sin( phi ) * Math.sin( theta );
		offset.y = radius * Math.cos( phi );
		offset.z = radius * Math.sin( phi ) * Math.cos( theta );

		position.copy( this.center ).add( offset );

		this.object.lookAt( this.center );

		this.dispatchEvent( changeEvent );

	};

	function onMouseDown( event ) {

		if ( scope.enabled === false ) return;

		event.preventDefault();

		if ( event.button === 0 ) {

			state = STATE.ROTATE;

		} else if ( event.button === 1 ) {

			state = STATE.ZOOM;

		} else if ( event.button === 2 ) {

			state = STATE.PAN;

		}

		document.addEventListener( 'mousemove', onMouseMove, false );
		document.addEventListener( 'mouseup', onMouseUp, false );

	}

	function onMouseMove( event ) {

		if ( scope.enabled === false ) return;

		event.preventDefault();

		var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
		var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;

		if ( state === STATE.ROTATE ) {

			scope.rotate( new THREE.Vector3( - movementX * 0.005, - movementY * 0.005, 0 ) );

		} else if ( state === STATE.ZOOM ) {

			scope.pan( new THREE.Vector3( 0, 0, movementY ) );

		} else if ( state === STATE.PAN ) {

			scope.pan( new THREE.Vector3( - movementX * 0.5, movementY * 0.5, 0 ) );

		}

	}

	function onMouseUp( event ) {

		if ( scope.enabled === false ) return;

		document.removeEventListener( 'mousemove', onMouseMove, false );
		document.removeEventListener( 'mouseup', onMouseUp, false );

		state = STATE.NONE;

	}

	function onMouseWheel( event ) {

		if ( scope.enabled === false ) return;

		var delta = 0;

		if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9

			delta = - event.wheelDelta * 0.1;

		} else if ( event.detail ) { // Firefox

			delta = event.detail * 5;

		}

		scope.pan( new THREE.Vector3( 0, 0, delta ) );

	}

	this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
	this.domElement.addEventListener( 'mousedown', onMouseDown, false );
	this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );
	this.domElement.addEventListener( 'DOMMouseScroll', onMouseWheel, false ); // firefox

};

THREE.EditorControls.prototype = Object.create( THREE.EventDispatcher.prototype );
<|endoftext|>


<commit_before>angular.module('scharwerk')
.factory('stages', ['$http', function($http){
  var s = {
    graphs: {}
  };

  s.getStats = function() {
    return $http.get('/stats/tasks.json').success(function(data){
      angular.forEach(data, function(stage, key) {
        // temporary fix
        // add 500 to markup and 100 to markup complex
        stage.total = stage.total + ((key == 'markup') ? 500 : 100);
        // check if undefined and summ
        finished = (stage.commited || 0) + (stage.unchanged || 0) + (stage.reproof || 0);
        console.log(finished);
        s.graphs[key] =
        [{
          label: 'Завершено',
          suffix: '%',
          value: Math.floor(100 * finished / stage.total),
          color: '#FFC107',
          colorComplement: '#FFFFFF',
          free: (!!stage.free),
          total: stage.total,
          finished: finished
        }];
      });
    });
  };

  s.getUsers = function(callback) {
    return $http.get('/stats/users.json').success(callback);
  }

  return s;
}])

<commit_msg>update counters<commit_after>angular.module('scharwerk')
.factory('stages', ['$http', function($http){
  var s = {
    graphs: {}
  };

  s.getStats = function() {
    return $http.get('/stats/tasks.json').success(function(data){
      angular.forEach(data, function(stage, key) {
        // temporary fix
        // add 254 to markup and 35 to markup complex
        stage.total = stage.total + ((key == 'markup') ? 254 : 35);
        // check if undefined and summ
        finished = (stage.commited || 0) + (stage.unchanged || 0) + (stage.reproof || 0);
        console.log(finished);
        s.graphs[key] =
        [{
          label: 'Завершено',
          suffix: '%',
          value: Math.floor(100 * finished / stage.total),
          color: '#FFC107',
          colorComplement: '#FFFFFF',
          free: (!!stage.free),
          total: stage.total,
          finished: finished
        }];
      });
    });
  };

  s.getUsers = function(callback) {
    return $http.get('/stats/users.json').success(callback);
  }

  return s;
}])

<|endoftext|>


<commit_before>'use strict'

const Readable = require('stream').Readable
const { clone, times, once } = require('lodash')
const debug = require('debug')('csw-client:harvester')

class Harvester extends Readable {

  constructor(client, options = {}) {
    const concurrency = options.concurrency || 2
    const step = options.step || 20
    super({ objectMode: true, highWaterMark: options.highWaterMark || step * concurrency })
    this.client = client
    this.options = options
    this.step = step
    this.concurrency = concurrency
    this.returned = 0
    this.progression = 0
    this.activityTimeout = options.activityTimeout || 20000
    debug('new harvester (concurrency=%d, step=%d)', concurrency, step)
  }

  renewActivityTimeout() {
    if (this.finished) return
    this.clearActivityTimeout()
    this._activityTimeout = setTimeout(() => {
      this.finish(new Error('Harvesting timeout'))
    }, this.activityTimeout)
  }

  clearActivityTimeout() {
    if (this._activityTimeout) {
      clearTimeout(this._activityTimeout)
    }
  }

  progress(count) {
    this.progression = this.progression + count
    this.emit('progress', count)
  }

  _read() {
    if (this.finished) return
    if (!this.started) return this.init()
    if (this.started) return this.fetchMoreRecords()
  }

  async init() {
    this.startDate = Date.now()

    try {
      const count = await this.client.count(clone(this.options))
      this.renewActivityTimeout()
      debug('found %d records', count)

      this.matched = count
      this.offset = 0
      this.pendingRequests = 0
      this.started = true
      this.emit('started')

      debug('ready to harvest')

      if (count === 0) {
        this.finish()
      } else {
        this.fetchMoreRecords()
      }
    } catch (err) {
      debug('error in count operation: %s', err)
      const newError =  new Error('Error in count operation')
      newError.err = err
      this.finish(newError)
    }
  }

  async fetchRecords() {
    if (!this.hasMoreRecords()) return

    const expected = Math.min(this.matched - this.offset + 1, this.step)

    const query = Object.assign({}, this.options, {
      maxRecords: this.step,
      startPosition: this.offset + 1,
    })

    this.offset = this.offset + this.step

    this.pendingRequests++
    debug('fetching records from %d', query.startPosition)
    debug('pending request: %d', this.pendingRequests)

    const decreasePendingRequests = once(() => this.pendingRequests--)

    try {
      const result = await this.client.records(query)
      decreasePendingRequests()

      const returned = result.records.length

      debug('returned %d records', returned)
      if (returned < expected) {
        debug('missed %d records (not returned by service)', expected - returned)
        this.fetchMoreRecords()
      }
      if (returned > expected) {
        this.finish(new Error('Fatal: more records returned than expected'))
      }
      result.records.forEach(record => {
        this.returned++
        this.emit('record', record)
        this.push(record)
      })
    } catch (err) {
      decreasePendingRequests()
      debug('error while fetching records from %d: %s', query.startPosition, err)
      debug('missed %d records (request failed)', expected)
      const newError = new Error('Error in fetch operation')
      newError.err = err
      this.emit('pageError', newError)
      this.fetchMoreRecords()
    }

    this.renewActivityTimeout()
    this.progress(expected)

    if (!this.hasMoreRecords() && this.pendingRequests === 0) {
      this.finish()
    }
  }

  fetchMoreRecords() {
    if (!this.hasMoreRecords()) return
    if (this.pendingRequests >= this.concurrency) return
    times(this.concurrency - this.pendingRequests, () => this.fetchRecords())
  }

  hasMoreRecords() {
    if (this._hasMoreRecords === false) return false
    if (this.offset < this.matched) return true
    this._hasMoreRecords = false
    debug('no more records: finishing %d pending requests', this.pendingRequests)
    return false
  }

  finish(err) {
    if (this.finished) return
    this.clearActivityTimeout()
    this.finished = true

    if (err) {
      debug('finished with following error: %s', err.message)
      this.failed = true
      this.emit('error', err)
      this.emit('failed')
    } else {
      debug('finished')
      debug('records returned: %d', this.returned)
      this.duration = Date.now() - this.startDate
      debug('duration: %s seconds', (this.duration / 1000).toFixed(1))
      this.push(null)
      this.on('end', () => this.removeAllListeners())
    }
  }

}

module.exports = Harvester
<commit_msg>Some code improvement<commit_after>'use strict'

const Readable = require('stream').Readable
const { clone, times, once } = require('lodash')
const debug = require('debug')('csw-client:harvester')

class Harvester extends Readable {

  constructor(client, options = {}) {
    const concurrency = options.concurrency || 2
    const step = options.step || 20
    super({ objectMode: true, highWaterMark: options.highWaterMark || step * concurrency })
    this.client = client
    this.options = options
    this.step = step
    this.concurrency = concurrency
    this.returned = 0
    this.progression = 0
    this.activityTimeout = options.activityTimeout || 20000
    debug('new harvester (concurrency=%d, step=%d)', concurrency, step)
  }

  renewActivityTimeout() {
    if (this.finished) return
    this.clearActivityTimeout()
    this._activityTimeout = setTimeout(() => {
      this.finish(new Error('Harvesting timeout'))
    }, this.activityTimeout)
  }

  clearActivityTimeout() {
    if (this._activityTimeout) {
      clearTimeout(this._activityTimeout)
    }
  }

  progress(count) {
    this.progression = this.progression + count
    this.emit('progress', count)
  }

  _read() {
    if (this.finished) return
    if (!this.started) return this.init()
    if (this.started) return this.fetchMoreRecords()
  }

  async init() {
    this.startDate = Date.now()

    try {
      const count = await this.client.count(clone(this.options))
      this.renewActivityTimeout()
      debug('found %d records', count)

      this.matched = count
      this.offset = 0
      this.pendingRequests = 0
      this.started = true
      this.emit('started')

      debug('ready to harvest')

      if (count === 0) {
        this.finish()
      } else {
        this.fetchMoreRecords()
      }
    } catch (err) {
      debug('error in count operation: %s', err)
      const newError =  new Error('Error in count operation')
      newError.err = err
      this.finish(newError)
    }
  }

  processRecord(record) {
    if (this.finished) return

    this.returned++
    this.emit('record', record)
    this.push(record)
  }

  async fetchRecords() {
    if (!this.hasMoreRecords()) return

    const expected = Math.min(this.matched - this.offset + 1, this.step)

    const query = Object.assign({}, this.options, {
      maxRecords: this.step,
      startPosition: this.offset + 1,
    })

    this.offset = this.offset + this.step

    this.pendingRequests++
    debug('fetching records from %d', query.startPosition)
    debug('pending request: %d', this.pendingRequests)

    const decreasePendingRequests = once(() => this.pendingRequests--)

    try {
      const result = await this.client.records(query)
      decreasePendingRequests()

      const returned = result.records.length

      debug('returned %d records', returned)
      if (returned < expected) {
        debug('missed %d records (not returned by service)', expected - returned)
        this.fetchMoreRecords()
      }
      if (returned > expected) {
        this.finish(new Error('Fatal: more records returned than expected'))
      }
      result.records.forEach(record => this.processRecord(record))
    } catch (err) {
      decreasePendingRequests()
      debug('error while fetching records from %d: %s', query.startPosition, err)
      debug('missed %d records (request failed)', expected)
      const newError = new Error('Error in fetch operation')
      newError.err = err
      this.emit('pageError', newError)
      this.fetchMoreRecords()
    }

    this.renewActivityTimeout()
    this.progress(expected)

    if (!this.hasMoreRecords() && this.pendingRequests === 0) {
      this.finish()
    }
  }

  fetchMoreRecords() {
    if (!this.hasMoreRecords()) return
    if (this.pendingRequests >= this.concurrency) return
    times(this.concurrency - this.pendingRequests, () => this.fetchRecords())
  }

  hasMoreRecords() {
    if (this._hasMoreRecords === false) return false
    if (this.offset < this.matched) return true
    this._hasMoreRecords = false
    debug('no more records: finishing %d pending requests', this.pendingRequests)
    return false
  }

  finish(err) {
    if (this.finished) return
    this.clearActivityTimeout()
    this.finished = true

    if (err) {
      debug('finished with following error: %s', err.message)
      this.failed = true
      this.emit('error', err)
      this.emit('failed')
    } else {
      debug('finished')
      debug('records returned: %d', this.returned)
      this.duration = Date.now() - this.startDate
      debug('duration: %s seconds', (this.duration / 1000).toFixed(1))
      this.push(null)
    }
  }

}

module.exports = Harvester
<|endoftext|>


<commit_before>function mouseOrbitUtility(scene) {

// Get handles to scene nodes

    var yawNode = scene.getNode("yaw");
    var pitchNode = scene.getNode("pitch");

// Rotate with mouse drags

    var lastX;
    var lastY;
    var dragging = false;

    var newInput = false;
    var yaw = 0;
    var pitch = 0;

    var canvas = scene.getCanvas();

    function mouseDown(event) {
        lastX = event.clientX;
        lastY = event.clientY;
        dragging = true;
    }

    function touchStart(event) {
        lastX = event.targetTouches[0].clientX;
        lastY = event.targetTouches[0].clientY;
        dragging = true;
    }

    function mouseUp() {
        dragging = false;
    }

    function touchEnd() {
        dragging = false;
    }

    function mouseMove(event) {
        var posX = event.clientX;
        var posY = event.clientY;
        actionMove(posX, posY);
    }

    function touchMove(event) {
        var posX = event.targetTouches[0].clientX;
        var posY = event.targetTouches[0].clientY;
        actionMove(posX, posY);
    }

    function actionMove(posX, posY) {
        if (dragging) {

            yaw += (posX - lastX) * 0.5;
            pitch += (posY - lastY) * 0.5;

            lastX = posX;
            lastY = posY;

            yawNode.set("angle", yaw);
            pitchNode.set("angle", pitch);
        }
    }

    canvas.addEventListener('mousedown', mouseDown, true);
    canvas.addEventListener('mousemove', mouseMove, true);
    canvas.addEventListener('mouseup', mouseUp, true);
    canvas.addEventListener('touchstart', touchStart, true);
    canvas.addEventListener('touchmove', touchMove, true);
    canvas.addEventListener('touchend', touchEnd, true);
}

function mousePanLookatUtility(scene) {

// Get handles to scene nodes

    var lookatNode = scene.getNode("lookat");

// Pan with mouse drags

    var lastX;
    var lastY;
    var dragging = false;

    var xeye = 0;
    var yeye = 0;

    var canvas = scene.getCanvas();

    function mouseDown(event) {
        lastX = event.clientX;
        lastY = event.clientY;
        dragging = true;
    }

    function touchStart(event) {
        lastX = event.targetTouches[0].clientX;
        lastY = event.targetTouches[0].clientY;
        dragging = true;
    }

    function mouseUp() {
        dragging = false;
    }

    function touchEnd() {
        dragging = false;
    }

    function mouseMove(event) {
        var posX = event.clientX;
        var posY = event.clientY;
        actionMove(posX, posY);
    }

    function touchMove(event) {
        var posX = event.targetTouches[0].clientX;
        var posY = event.targetTouches[0].clientY;
        actionMove(posX, posY);
    }

    function actionMove(posX, posY) {
        if (dragging) {

            xeye -= (posX - lastX) * 0.5;
            yeye -= (posY - lastY) * 0.5;

            lastX = posX;
            lastY = posY;

            lookatNode.set({
                eye: { x: xeye, y: yeye }
            });
        }
    }

    canvas.addEventListener('mousedown', mouseDown, true);
    canvas.addEventListener('mousemove', mouseMove, true);
    canvas.addEventListener('mouseup', mouseUp, true);
    canvas.addEventListener('touchstart', touchStart, true);
    canvas.addEventListener('touchmove', touchMove, true);
    canvas.addEventListener('touchend', touchEnd, true);
}<commit_msg>Example mouse listener on document body instead of canvas<commit_after>function mouseOrbitUtility(scene) {

// Get handles to scene nodes

    var yawNode = scene.getNode("yaw");
    var pitchNode = scene.getNode("pitch");

// Rotate with mouse drags

    var lastX;
    var lastY;
    var dragging = false;

    var newInput = false;
    var yaw = 0;
    var pitch = 0;

    function mouseDown(event) {
        lastX = event.clientX;
        lastY = event.clientY;
        dragging = true;
    }

    function touchStart(event) {
        lastX = event.targetTouches[0].clientX;
        lastY = event.targetTouches[0].clientY;
        dragging = true;
    }

    function mouseUp() {
        dragging = false;
    }

    function touchEnd() {
        dragging = false;
    }

    function mouseMove(event) {
        var posX = event.clientX;
        var posY = event.clientY;
        actionMove(posX, posY);
    }

    function touchMove(event) {
        var posX = event.targetTouches[0].clientX;
        var posY = event.targetTouches[0].clientY;
        actionMove(posX, posY);
    }

    function actionMove(posX, posY) {
        if (dragging) {

            yaw += (posX - lastX) * 0.5;
            pitch += (posY - lastY) * 0.5;

            lastX = posX;
            lastY = posY;

            yawNode.set("angle", yaw);
            pitchNode.set("angle", pitch);
        }
    }

    document.body.addEventListener('mousedown', mouseDown, true);
    document.body.addEventListener('mousemove', mouseMove, true);
    document.body.addEventListener('mouseup', mouseUp, true);
    document.body.addEventListener('touchstart', touchStart, true);
    document.body.addEventListener('touchmove', touchMove, true);
    document.body.addEventListener('touchend', touchEnd, true);
}

function mousePanLookatUtility(scene) {

// Get handles to scene nodes

    var lookatNode = scene.getNode("lookat");

// Pan with mouse drags

    var lastX;
    var lastY;
    var dragging = false;

    var xeye = 0;
    var yeye = 0;

    var canvas = scene.getCanvas();

    function mouseDown(event) {
        lastX = event.clientX;
        lastY = event.clientY;
        dragging = true;
    }

    function touchStart(event) {
        lastX = event.targetTouches[0].clientX;
        lastY = event.targetTouches[0].clientY;
        dragging = true;
    }

    function mouseUp() {
        dragging = false;
    }

    function touchEnd() {
        dragging = false;
    }

    function mouseMove(event) {
        var posX = event.clientX;
        var posY = event.clientY;
        actionMove(posX, posY);
    }

    function touchMove(event) {
        var posX = event.targetTouches[0].clientX;
        var posY = event.targetTouches[0].clientY;
        actionMove(posX, posY);
    }

    function actionMove(posX, posY) {
        if (dragging) {

            xeye -= (posX - lastX) * 0.5;
            yeye -= (posY - lastY) * 0.5;

            lastX = posX;
            lastY = posY;

            lookatNode.set({
                eye:{ x:xeye, y:yeye }
            });
        }
    }

    document.body.addEventListener('mousedown', mouseDown, true);
    document.body.addEventListener('mousemove', mouseMove, true);
    document.body.addEventListener('mouseup', mouseUp, true);
    document.body.addEventListener('touchstart', touchStart, true);
    document.body.addEventListener('touchmove', touchMove, true);
    document.body.addEventListener('touchend', touchEnd, true);
}<|endoftext|>


<commit_before>define(["sugar-web/activity/activity","sugar-web/env", "worldpalette", "viewPalette"], function (activity, env, worldpalette, viewpalette) {

	// Manipulate the DOM only when it is ready.
	requirejs(['domReady!'], function (doc) {

		// Initialize the activity.
		activity.setup();

		var datastoreObject = activity.getDatastoreObject();

        var worldButton = document.getElementById("world-button");

        var worldPalette = new worldpalette.ActivityPalette(
            worldButton, datastoreObject);

				var viewButton = document.getElementById("view-button");

        var viewPalette = new viewpalette.ActivityPalette(
            viewButton, datastoreObject);

		S(document).ready(function() {

			var planetarium = S.virtualsky({
							id: 'starmap', //Div tag id where you want to place star chart
							projection:'stereo', //Type of map projection used
							keyboard: false, //Disable/Enable keyboard
							showposition: false, //Show/Hide coordinates
							showstars: true, //Show/Hide stars
							constellations: true, //Show/Hide constellation lines
							constellationlabels: true, //Show/Hide Constellation names
							showplanets: true, //Show/Hide planets
							showplanetlabels: true, //Show/Hide planet names
							live: false, //Disabe/Enable real time clock
							clock: new Date(), //Set clock

			});

			//Necessary variables
			var chartJournal = [true,false,"55.3781,-3.4360","stereo"];
			var longlat = document.getElementById('worldConst').innerHTML;
			var customLatitude = planetarium.setLatitude(parseFloat(longlat.split(',')[0]));
			var customLongitude = planetarium.setLongitude(parseFloat(longlat.split(',')[1]));

			//Get Location of user and set the star chart to the position
			//when Location button is pressed
			function getUserLocation(){
				if (navigator.geolocation){
					navigator.geolocation.getCurrentPosition(userPosition);
				}
			}
			function userPosition(position) {
				S("button#location-button").on('click', function(){
					console.log(longlat);
					document.getElementById(longlat).style.backgroundColor = 'black';
					longlat = position.coords.latitude + "," + position.coords.longitude;
					customLatitude = planetarium.setLatitude(parseFloat(longlat.split(',')[0]));
					customLongitude = planetarium.setLongitude(parseFloat(longlat.split(',')[1]));
					planetarium.setGeo(S(customLatitude,customLongitude)).setClock(0).draw();
					chartJournal[2] = longlat;
					console.log(chartJournal);
				})
			}
			getUserLocation();

			//Add 1 day to date
			S("button#add-button").on('click', function (){
				planetarium.clock.setDate(planetarium.clock.getDate() + 1);
				planetarium.updateClock(planetarium.clock);
			})

			//Minus 1 day to date
			S("button#minus-button").on('click', function (){
				planetarium.clock.setDate(planetarium.clock.getDate() - 1);
				planetarium.updateClock(planetarium.clock);
			})

			//Toggle Constellation Lines and Name
			S("button#const-button").on('click', function (){

				planetarium.toggleConstellationLines();
				planetarium.toggleConstellationLabels();

				if (chartJournal[0] == true){
					chartJournal[0] = false;
				} else{
					chartJournal[0] = true;
				}

				console.log(chartJournal[0]);
			})

			//Toggle Star names
			S("button#star-button").on('click', function (){
				planetarium.toggleStarLabels();

				if (chartJournal[1] == true){
					chartJournal[1] = false;
				} else{
					chartJournal[1] = true;
				}
				console.log(chartJournal[1]);
			})

			//Set long and lat to specific country
			S("button.country").on('click', function (){
				longlat = document.getElementById('worldConst').innerHTML;
				customLatitude = planetarium.setLatitude(parseFloat(longlat.split(',')[0]));
				customLongitude = planetarium.setLongitude(parseFloat(longlat.split(',')[1]));
				planetarium.setGeo(S(customLatitude,customLongitude)).setClock(0).draw();
				chartJournal[2] = longlat;
				console.log(chartJournal);
			})

			//Change projection view
			S("button.view").on('click', function (){
				var pv = document.getElementById('projection-view').innerHTML;
				planetarium.selectProjection(pv);
				chartJournal[3] = pv;
				console.log(chartJournal);
			})

			//Save in Journal on stop
			document.getElementById("stop-button").addEventListener('click', function (event) {
				console.log("writing...");
				var jsonData = JSON.stringify(chartJournal);
				activity.getDatastoreObject().setDataAsText(jsonData);
				activity.getDatastoreObject().save(function (error) {
					if (error === null) {
						console.log("write done.");
						console.log(jsonData);
					} else {
						console.log("write failed.");
					}
				});
			});

			// Load from datastore
			env.getEnvironment(function(err, environment) {
			currentenv = environment;

			// Load from datastore
			if (!environment.objectId) {
				console.log("New instance");
				document.getElementById(chartJournal[2]).style.backgroundColor = 'grey';
				document.getElementById(chartJournal[3]).style.backgroundColor = 'grey';
			} else {
				activity.getDatastoreObject().loadAsText(function(error, metadata, data) {
					if (error==null && data!=null) {
						chartJournal = JSON.parse(data);
						customLatitude = planetarium.setLatitude(parseFloat(chartJournal[2].split(',')[0]));
					 	customLongitude = planetarium.setLongitude(parseFloat(chartJournal[2].split(',')[1]));
						planetarium.setGeo(S(customLatitude,customLongitude)).setClock(0).draw();
						try {
							document.getElementById(chartJournal[2]).style.backgroundColor = 'grey';
						}
						catch(e){
							console.log("User location used");
						}
						planetarium.selectProjection(chartJournal[3]);
						document.getElementById(chartJournal[3]).style.backgroundColor = 'grey';
						if (chartJournal[0] == false){
							planetarium.toggleConstellationLines();
							planetarium.toggleConstellationLabels();
						}
						if (chartJournal[1] == true){
							planetarium.toggleStarLabels();
						}
					}
				});
			}
		});

		});

	});

});
<commit_msg>Added localization<commit_after>define(["sugar-web/activity/activity","sugar-web/env", "worldpalette", "viewPalette", "webL10n"], function (activity, env, worldpalette, viewpalette, webL10n) {

	// Manipulate the DOM only when it is ready.
	requirejs(['domReady!'], function (doc) {

		// Initialize the activity.
		activity.setup();

		var datastoreObject = activity.getDatastoreObject();

        var worldButton = document.getElementById("world-button");

        var worldPalette = new worldpalette.ActivityPalette(
            worldButton, datastoreObject);

				var viewButton = document.getElementById("view-button");

        var viewPalette = new viewpalette.ActivityPalette(
            viewButton, datastoreObject);

		S(document).ready(function() {

			var planetarium = S.virtualsky({
							id: 'starmap', //Div tag id where you want to place star chart
							projection:'stereo', //Type of map projection used
							keyboard: false, //Disable/Enable keyboard
							showposition: false, //Show/Hide coordinates
							showstars: true, //Show/Hide stars
							constellations: true, //Show/Hide constellation lines
							constellationlabels: true, //Show/Hide Constellation names
							showplanets: true, //Show/Hide planets
							showplanetlabels: true, //Show/Hide planet names
							live: false, //Disabe/Enable real time clock
							clock: new Date(), //Set clock

			});

			//Necessary variables
			var chartJournal = [true,false,"55.3781,-3.4360","stereo"];
			var longlat = document.getElementById('worldConst').innerHTML;
			var customLatitude = planetarium.setLatitude(parseFloat(longlat.split(',')[0]));
			var customLongitude = planetarium.setLongitude(parseFloat(longlat.split(',')[1]));

			getUserLocation();

			//Add 1 day to date
			S("button#add-button").on('click', function (){
				planetarium.clock.setDate(planetarium.clock.getDate() + 1);
				planetarium.updateClock(planetarium.clock);
			})

			//Minus 1 day to date
			S("button#minus-button").on('click', function (){
				planetarium.clock.setDate(planetarium.clock.getDate() - 1);
				planetarium.updateClock(planetarium.clock);
			})

			//Toggle Constellation Lines and Name
			S("button#const-button").on('click', function (){

				planetarium.toggleConstellationLines();
				planetarium.toggleConstellationLabels();

				if (chartJournal[0] == true){
					chartJournal[0] = false;
				} else{
					chartJournal[0] = true;
				}

				console.log(chartJournal[0]);
			})

			//Toggle Star names
			S("button#star-button").on('click', function (){
				planetarium.toggleStarLabels();

				if (chartJournal[1] == true){
					chartJournal[1] = false;
				} else{
					chartJournal[1] = true;
				}
				console.log(chartJournal[1]);
			})

			//Set long and lat to specific country
			S("button.country").on('click', function (){
				longlat = document.getElementById('worldConst').innerHTML;
				customLatitude = planetarium.setLatitude(parseFloat(longlat.split(',')[0]));
				customLongitude = planetarium.setLongitude(parseFloat(longlat.split(',')[1]));
				planetarium.setGeo(S(customLatitude,customLongitude)).setClock(0).draw();
				chartJournal[2] = longlat;
				console.log(chartJournal);
			})

			//Change projection view
			S("button.view").on('click', function (){
				var pv = document.getElementById('projection-view').innerHTML;
				planetarium.selectProjection(pv);
				chartJournal[3] = pv;
				console.log(chartJournal);
			})

			//Save in Journal on stop
			document.getElementById("stop-button").addEventListener('click', function (event) {
				console.log("writing...");
				var jsonData = JSON.stringify(chartJournal);
				activity.getDatastoreObject().setDataAsText(jsonData);
				activity.getDatastoreObject().save(function (error) {
					if (error === null) {
						console.log("write done.");
						console.log(jsonData);
					} else {
						console.log("write failed.");
					}
				});
			});

			// Load from datastore
			env.getEnvironment(function(err, environment) {
				currentenv = environment;

				//Set current language
				var currentLang = (typeof chrome != 'undefined' && chrome.app && chrome.app.runtime) ? chrome.i18.getUILanguage() : navigator.language;
				var language = environment.user ? environment.user.language : currentLang;
				webL10n.language.code = language;

				//Set the star chart's language to Sugarizer's language
				planetarium.language = language;

				//Process localize event
				window.addEventListener("localized", function(){
					toLocalize();
				})

				// Load from datastore
				if (!environment.objectId) {
					console.log("New instance");
					document.getElementById(chartJournal[2]).style.backgroundColor = 'grey';
					document.getElementById(chartJournal[3]).style.backgroundColor = 'grey';
				} else {
					activity.getDatastoreObject().loadAsText(function(error, metadata, data) {
						if (error==null && data!=null) {
							chartJournal = JSON.parse(data);
							customLatitude = planetarium.setLatitude(parseFloat(chartJournal[2].split(',')[0]));
						 	customLongitude = planetarium.setLongitude(parseFloat(chartJournal[2].split(',')[1]));
							planetarium.setGeo(S(customLatitude,customLongitude)).setClock(0).draw();
							try {
								document.getElementById(chartJournal[2]).style.backgroundColor = 'grey';
							}
							catch(e){
								console.log("User location used");
							}
							planetarium.selectProjection(chartJournal[3]);
							document.getElementById(chartJournal[3]).style.backgroundColor = 'grey';
							if (chartJournal[0] == false){
								planetarium.toggleConstellationLines();
								planetarium.toggleConstellationLabels();
							}
							if (chartJournal[1] == true){
								planetarium.toggleStarLabels();
							}
						}
					});
				}
			});
		});

		//Things to localize
		function toLocalize() {
			document.getElementById("add-button").title = webL10n.get("AddDay");
			document.getElementById("minus-button").title = webL10n.get("MinusDay");
			document.getElementById("const-button").title = webL10n.get("ToggleConst");
			document.getElementById("star-button").title = webL10n.get("ToggleStar");
			document.getElementById("location-button").title = webL10n.get("Location");
			document.getElementById("world-button").title = webL10n.get("WorldList");
			document.getElementById("view-button").title = webL10n.get("View");
			document.getElementById("55.3781,-3.4360").innerHTML = webL10n.get("Britain");
			document.getElementById("23.6345,-102.5528").innerHTML = webL10n.get("Mexico");
			document.getElementById("40.4637,-3.7492").innerHTML = webL10n.get("Spain");
			document.getElementById("51.1657,10.4515").innerHTML = webL10n.get("Germany");
			document.getElementById("40.3399,127.5101").innerHTML = webL10n.get("NorthKorea");
			document.getElementById("23.8859,45.0792").innerHTML = webL10n.get("SaudiArabia");
			document.getElementById("35.9078,127.7669").innerHTML = webL10n.get("SouthKorea");
			document.getElementById("46.2276,2.2137").innerHTML = webL10n.get("France");
			document.getElementById("51.9194,19.1451").innerHTML = webL10n.get("Poland");
			document.getElementById("41.8719,12.5674").innerHTML = webL10n.get("Italy");
			document.getElementById("20.5937,78.9629").innerHTML = webL10n.get("India");
			document.getElementById("9.0820,8.6753").innerHTML = webL10n.get("Nigeria");
			document.getElementById("0.7893,113.9213").innerHTML = webL10n.get("Indonesia");
			document.getElementById("-14.2350,-51.9253").innerHTML = webL10n.get("Brazil");
			document.getElementById("54.5260,-105.2551").innerHTML = webL10n.get("NorthAmerica");
			document.getElementById("-8.7832,-55.4915").innerHTML = webL10n.get("SouthAmerica");
			document.getElementById("-8.7832,34.5085").innerHTML = webL10n.get("Africa");
			document.getElementById("-25.2744,133.7751").innerHTML = webL10n.get("Australia");
			document.getElementById("12.8797,121.7740").innerHTML = webL10n.get("Philippines");
			document.getElementById("4.2105,101.9758").innerHTML = webL10n.get("Malaysia");
			document.getElementById("36.2048,138.2529").innerHTML = webL10n.get("Japan");
			document.getElementById("39.9042,116.4074").innerHTML = webL10n.get("China");
		}

		//Get Location of user and set the star chart to the position
		//when Location button is pressed
		function getUserLocation(){
			if (navigator.geolocation){
				navigator.geolocation.getCurrentPosition(userPosition);
			}
		}
		function userPosition(position) {
			S("button#location-button").on('click', function(){
				console.log(longlat);
				document.getElementById(longlat).style.backgroundColor = 'black';
				longlat = position.coords.latitude + "," + position.coords.longitude;
				customLatitude = planetarium.setLatitude(parseFloat(longlat.split(',')[0]));
				customLongitude = planetarium.setLongitude(parseFloat(longlat.split(',')[1]));
				planetarium.setGeo(S(customLatitude,customLongitude)).setClock(0).draw();
				chartJournal[2] = longlat;
				console.log(chartJournal);
			})
		}

	});

});
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* HID Device module for conversation, IOET version */

/* global chrome */

var _ = require('lodash');
var async = require('async');
var localStore = require('./core/localStore');

// for tests
if (typeof localStore === 'function') {
  localStore = localStore({});
}

var DEVICEPORTS = 'hidPorts';

var debug = require('./bows')('HIDDevice');

var moduleCounter = 1;

module.exports = function(config) {
  config = config || {};
  var connection = null;
  var buffer = [];
  var packetBuffer = [];
  var packetHandler = null;
  var errorHandler = null;
  var moduleNumber = moduleCounter++;
  var log = '';
  var logcount = 0;
  var loglimit = 400;
  var doLogging = (config && config.doLogging) || false;
  var connectionId;

  function init() {
    connection = null;
    buffer = [];
    packetBuffer = [];
    packetHandler = null;
    log = '';
    connectionId = null,
    localStore.init(DEVICEPORTS, function() {});
  }

  init();

  // This is the object that is passed to the packetHandler
  // it lets us abstract away the details of the packetHandling
  var bufobj = {
    // get(x) -- returns char at x
    get : function(n) {return buffer[n]; },
    // len() -- returns length
    len : function() { return buffer.length; },
    // discard(n) -- deletes n chars at start of buffer
    discard : function(n) { discardBytes(n); },
    // bytes() -- returns entire buffer as a Uint8Array
    bytes : function() {
      return new Uint8Array(buffer);
    }
  };

  function addlog(s) {
    if (!doLogging) {
      return;
    }

    if (logcount < loglimit) {
      if (s.indexOf('\n') !== -1) {
        ++logcount;
      }
      log += s;
    }
  }

  var logdump = _.debounce(function() {
    if (doLogging) {
      debug(log);
    }
  }, 900);

  var emitLog = function(clearLog) {
    debug(log);
    if (clearLog) {
      log = '';
      logcount = 0;
    }
  };

  function _receiveSomeBytes(bufView) {
    for (var i=0; i<bufView.byteLength; i++) {
      buffer.push(bufView[i]);
    }

    addlog('  rcv ');
    for (i in bufView) {
      addlog(('00' + bufView[i].toString(16)).substr(-2) + ' ');
    }
    addlog('\n');
    logdump();

    // we got some bytes, let's see if they make one or more packets
    if (packetHandler) {
      var pkt = packetHandler(bufobj);
      while (pkt) {
        packetBuffer.push(pkt);
        pkt = packetHandler(bufobj);
      }
    }

  }

  function portListener(info) {
    if (connection && info.connectionId == connection.connectionId && info.data) {
      var bufView=new Uint8Array(info.data);
      _receiveSomeBytes(bufView);
    }
  }

  // if an errorHandler was specified, then we call it with every error.
  // If it returns anything, it should return either a string or an array
  // containing the bytes it wants to insert into the buffer.
  // According to chrome's docs, info will contain connectionId, and an
  // error member that can be any of "disconnected", "timeout", "device_lost", or "system_error"
  function errorListener(info) {
    if (info.error && errorHandler) {
      var bytes = errorHandler(info);
      var bufView = new Uint8Array(bytes.length);
      for (var i=0; i<bytes.length; i++) {
        if (_.isString(bytes)) {
          bufView[i] = bytes.charCodeAt(i);
        } else if (_.isArray(bytes)) {
          bufView[i] = bytes[i];
        }
      }
      _receiveSomeBytes(bufView);
    }
  }

  function connect(deviceInfo, probe, cb) {
    if (arguments.length != 3) {
      console.log('hid connect called with wrong number of arguments!');
    }

    debug('in HIDDevice.connect, info ', deviceInfo);

    //TODO: verificar si podemos en deviceInfo tener el deviceId
    //deviceInfo.deviceId se obtiene de device.detectHid en lib/core.device.js
    chrome.hid.connect(deviceInfo.deviceId, function(connectInfo){
      //TODO: arreglar esto para que tenga una validación
      if(!connectInfo){
          console.warn("Unable to connect to device");
       }
      connectionId = connectedInfo.connectionId;
      debug('connected to ' + connectInfo);
      //TODO: aqui hacer algo con el probe antes de llamar al callback final
        if (connectInfo && connectInfo.connectionId) {
            connection = connectInfo;
            probe(function(err) {
        if (!err) {
              return done(connectInfo);
            } else {
             chrome.hid.disconnect(deviceInfo.connectionId, function() {});
              return done();
              }
            });
          } else {
            done();
          }
      cb();
    });

  }

  //TODO verificar en donde se usa este recordPort
  //se utiliza en \lib\drivers\dexcomDriver
  //línea 732
  function recordPort(deviceId) {
    var ap = localStore.getItem(DEVICEPORTS);
    var allports = ap ? JSON.parse(ap) : {};
    var successfulPorts = [];
    if (allports && allports[deviceId]) {
      successfulPorts = allports[deviceId];
    } else {
      allports = {};
    }
    if (_.indexOf(successfulPorts, connection.name) == -1) {
      successfulPorts.unshift(connection.name);
    }
    allports[deviceId] = successfulPorts;
    var s = JSON.stringify(allports);
    localStore.setItem(DEVICEPORTS, s);
  }

  function disconnect(deviceInfo, cb) {
    if (connection === null){
      return;
    }else{
      chrome.hid.disconnect(deviceInfo.connectionId, function(){
        //TODO: decir algo aqui antes de llamar al cb
        console.log('disconnected from HIDDevice');
        addlog(' done\n');
      });
    }
  }

  function discardBytes(discardCount) {
    addlog('discard ' + discardCount + '\n');
    logdump();
    buffer = buffer.slice(discardCount);
  }

  var buildInput = function(bytes) {
    var dataInput = '';
    for (var i = 0; i < bytes.length; i += 16) {
      var sliceLength = Math.min(bytes.length - i, 16);
      var lineBytes = new Uint8Array(bytes.buffer, i, sliceLength);
      for (var j = 0; j < lineBytes.length; ++j) {
        dataInput += byteToHex(lineBytes[j]) + ' ';
      }
      for (var j = 0; j < lineBytes.length; ++j) {
        var ch = String.fromCharCode(lineBytes[j]);
        if (lineBytes[j] < 32 || lineBytes[j] > 126)
          ch = '.';
        dataInput += ch;
      }
      dataInput += '\n';
    }
    return dataInput;
  };

  function receive(bytes, timeout, cb){
    chrome.hid.receive(connection, function(reportId, data) {
      buildInput(new Uint8Array(data));
    });

    //TODO: tal vez ya no se necesita esto si lo de arriba funciona bien
    //      y si ese es el caso hay que eliminar timeout
    //var packet;
    //if (buffer.length >= bytes) {
    //  packet = buffer.slice(0,bytes);
    //  buffer = buffer.slice(0 - bytes);
    //  callback(packet);
    //} else if (timeout === 0) {
    //  packet = buffer;
    //  buffer = [];
    //  callback(packet);
    //} else {
    //  setTimeout(function() {
    //    receive(bytes, 0, callback);
    //  }, timeout);
    //}
  }

  function send(bytes, callback) {

    var bufView = new Uint8Array(bytes);
    //TODO: maybe not needed at all
    //var l = bufView.length;
    //var timerId = setTimeout(function() {
    //  sendcheck({ bytesSent: 0, error: 'timeout' });
    //}, 500);
    //var sendcheck = function(info) {
    //  clearTimeout(timerId);
    //  // debug('Sent ', info.bytesSent,' bytes');
    //  addlog(' xmit ');
    //  for (var i in bufView) {
    //    addlog(('00' + bufView[i].toString(16)).substr(-2) + ' ');
    //  }
    //  addlog('\n');
    //  logdump();

    //  if (l != info.bytesSent) {
    //    debug('Only ' + info.bytesSent + ' bytes sent out of ' + l);
    //  }
    //  if (info.error) {
    //    debug('Serial send returned ' + info.error);
    //  }
    //  callback(info.error, info);
    //};
    if (bytes == null) {
      debug('just tried to send nothing!');
    } else {
      //TODO: reportId seteado a 0 por probar
      var reportId = 0;
      chrome.hid.send(connectionId, reportId, data, function(){
          callback();
      });
    }
  }

  function hasAvailablePacket() {
    return packetBuffer.length > 0;
  }

  function peekPacket() {
    if (hasAvailablePacket()) {
      return packetBuffer[0];
    } else {
      return null;
    }
  }

  function nextPacket() {
    if (hasAvailablePacket()) {
      return packetBuffer.shift();
    } else {
      return null;
    }
  }

  function flush() {
    addlog('flush\n');
    logdump();
    packetBuffer = [];
  }

  return {
    connect: connect,
    recordPort: recordPort,
    disconnect: disconnect,
    discardBytes: discardBytes,
    receive: receive,
    send: send,
    clearPacketHandler: clearPacketHandler,
    hasAvailablePacket: hasAvailablePacket,
    peekPacket: peekPacket,
    nextPacket: nextPacket,
    flush: flush,
    emitLog: emitLog
  };

};
<commit_msg>fixed hid connect functions<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* HID Device module for conversation, IOET version */

/* global chrome */

var _ = require('lodash');
var async = require('async');
var localStore = require('./core/localStore');

// for tests
if (typeof localStore === 'function') {
  localStore = localStore({});
}

var DEVICEPORTS = 'hidPorts';

var debug = require('./bows')('HIDDevice');

var moduleCounter = 1;

module.exports = function(config) {
  config = config || {};
  var connection = null;
  var buffer = [];
  var packetBuffer = [];
  var packetHandler = null;
  var errorHandler = null;
  var moduleNumber = moduleCounter++;
  var log = '';
  var logcount = 0;
  var loglimit = 400;
  var doLogging = (config && config.doLogging) || false;
  var connectionId;

  function init() {
    connection = null;
    buffer = [];
    packetBuffer = [];
    packetHandler = null;
    log = '';
    connectionId = null,
    localStore.init(DEVICEPORTS, function() {});
  }

  init();

  // This is the object that is passed to the packetHandler
  // it lets us abstract away the details of the packetHandling
  var bufobj = {
    // get(x) -- returns char at x
    get : function(n) {return buffer[n]; },
    // len() -- returns length
    len : function() { return buffer.length; },
    // discard(n) -- deletes n chars at start of buffer
    discard : function(n) { discardBytes(n); },
    // bytes() -- returns entire buffer as a Uint8Array
    bytes : function() {
      return new Uint8Array(buffer);
    }
  };

  function addlog(s) {
    if (!doLogging) {
      return;
    }

    if (logcount < loglimit) {
      if (s.indexOf('\n') !== -1) {
        ++logcount;
      }
      log += s;
    }
  }

  var logdump = _.debounce(function() {
    if (doLogging) {
      debug(log);
    }
  }, 900);

  var emitLog = function(clearLog) {
    debug(log);
    if (clearLog) {
      log = '';
      logcount = 0;
    }
  };

  function _receiveSomeBytes(bufView) {
    for (var i=0; i<bufView.byteLength; i++) {
      buffer.push(bufView[i]);
    }

    addlog('  rcv ');
    for (i in bufView) {
      addlog(('00' + bufView[i].toString(16)).substr(-2) + ' ');
    }
    addlog('\n');
    logdump();

    // we got some bytes, let's see if they make one or more packets
    if (packetHandler) {
      var pkt = packetHandler(bufobj);
      while (pkt) {
        packetBuffer.push(pkt);
        pkt = packetHandler(bufobj);
      }
    }

  }

  function portListener(info) {
    if (connection && info.connectionId == connection.connectionId && info.data) {
      var bufView=new Uint8Array(info.data);
      _receiveSomeBytes(bufView);
    }
  }

  // if an errorHandler was specified, then we call it with every error.
  // If it returns anything, it should return either a string or an array
  // containing the bytes it wants to insert into the buffer.
  // According to chrome's docs, info will contain connectionId, and an
  // error member that can be any of "disconnected", "timeout", "device_lost", or "system_error"
  function errorListener(info) {
    if (info.error && errorHandler) {
      var bytes = errorHandler(info);
      var bufView = new Uint8Array(bytes.length);
      for (var i=0; i<bytes.length; i++) {
        if (_.isString(bytes)) {
          bufView[i] = bytes.charCodeAt(i);
        } else if (_.isArray(bytes)) {
          bufView[i] = bytes[i];
        }
      }
      _receiveSomeBytes(bufView);
    }
  }

  function connect(deviceInfo, probe, cb) {
    if (arguments.length != 3) {
      console.log('hid connect called with wrong number of arguments!');
    }

    debug('in HIDDevice.connect, info ', deviceInfo);

    //TODO: verificar si podemos en deviceInfo tener el deviceId
    //deviceInfo.deviceId se obtiene de device.detectHid en lib/core.device.js
    chrome.hid.connect(deviceInfo.deviceId, function(connectInfo){
      //TODO: arreglar esto para que tenga una validación
      if(!connectInfo){
          console.warn("Unable to connect to device");
        }
      connectionId = connectedInfo.connectionId;
      debug('connected to ' + connectInfo);
      //TODO: aqui hacer algo con el probe antes de llamar al callback final
        if (connectInfo && connectInfo.connectionId) {
            connection = connectInfo;
            probe(function(err) {
        if (!err) {
              return done(connectInfo);
            } else {
             chrome.hid.disconnect(deviceInfo.connectionId, function() {});
              return done();
              }
            });
          } else {
            done();
          }
      cb();
    });

  }

  function disconnect(deviceInfo, cb) {
    if (connection === null){
      return;
    }else{
      chrome.hid.disconnect(deviceInfo.connectionId, function(){
        //TODO: decir algo aqui antes de llamar al cb
        console.log('disconnected from HIDDevice');
        addlog(' done\n');
      });
    }
  }

  function discardBytes(discardCount) {
    addlog('discard ' + discardCount + '\n');
    logdump();
    buffer = buffer.slice(discardCount);
  }

  var buildInput = function(bytes) {
    var dataInput = '';
    for (var i = 0; i < bytes.length; i += 16) {
      var sliceLength = Math.min(bytes.length - i, 16);
      var lineBytes = new Uint8Array(bytes.buffer, i, sliceLength);
      for (var j = 0; j < lineBytes.length; ++j) {
        var ch = String.fromCharCode(lineBytes[j]);
        if (lineBytes[j] < 32 || lineBytes[j] > 126)
          ch = '.';
        dataInput += ch;
      }
      dataInput += '\n';
    }
    console.log('datos= 'dataInput);
    return dataInput;
  };

  function receive(bytes, timeout, cb){
    chrome.hid.receive(connection, function(reportId, data) {
      buildInput(new Uint8Array(data));
    });

    //TODO: tal vez ya no se necesita esto si lo de arriba funciona bien
    //      y si ese es el caso hay que eliminar timeout
    //var packet;
    //if (buffer.length >= bytes) {
    //  packet = buffer.slice(0,bytes);
    //  buffer = buffer.slice(0 - bytes);
    //  callback(packet);
    //} else if (timeout === 0) {
    //  packet = buffer;
    //  buffer = [];
    //  callback(packet);
    //} else {
    //  setTimeout(function() {
    //    receive(bytes, 0, callback);
    //  }, timeout);
    //}
  }

  function send(bytes, callback) {

    var bufView = new Uint8Array(bytes);
    //TODO: maybe not needed at all
    //var l = bufView.length;
    //var timerId = setTimeout(function() {
    //  sendcheck({ bytesSent: 0, error: 'timeout' });
    //}, 500);
    //var sendcheck = function(info) {
    //  clearTimeout(timerId);
    //  // debug('Sent ', info.bytesSent,' bytes');
    //  addlog(' xmit ');
    //  for (var i in bufView) {
    //    addlog(('00' + bufView[i].toString(16)).substr(-2) + ' ');
    //  }
    //  addlog('\n');
    //  logdump();

    //  if (l != info.bytesSent) {
    //    debug('Only ' + info.bytesSent + ' bytes sent out of ' + l);
    //  }
    //  if (info.error) {
    //    debug('Serial send returned ' + info.error);
    //  }
    //  callback(info.error, info);
    //};
    if (bytes == null) {
      debug('just tried to send nothing!');
    } else {
      //TODO: reportId seteado a 0 por probar
      var reportId = 0;
      chrome.hid.send(connectionId, reportId, data, function(){
          callback();
      });
    }
  }

  function hasAvailablePacket() {
    return packetBuffer.length > 0;
  }

  function peekPacket() {
    if (hasAvailablePacket()) {
      return packetBuffer[0];
    } else {
      return null;
    }
  }

  function nextPacket() {
    if (hasAvailablePacket()) {
      return packetBuffer.shift();
    } else {
      return null;
    }
  }

  function flush() {
    addlog('flush\n');
    logdump();
    packetBuffer = [];
  }

  return {
    connect: connect,
    recordPort: recordPort,
    disconnect: disconnect,
    discardBytes: discardBytes,
    receive: receive,
    send: send,
    clearPacketHandler: clearPacketHandler,
    hasAvailablePacket: hasAvailablePacket,
    peekPacket: peekPacket,
    nextPacket: nextPacket,
    flush: flush,
    emitLog: emitLog
  };

};
<|endoftext|>


<commit_before>var app = angular.module('app');

app.controller('UsersCtrl', function ($scope, $http) {
    $scope.users = [{
        name: 'Drew'
    }, {
        name: 'Chris'
    }, {
        name: 'Mike'
    }];
});

<commit_msg>Corrected structure for controller<commit_after>var app = angular.module('app');

app.controller('UsersCtrl', ['$scope', '$http', function ($scope, $http) {
    $scope.users = [{
        name: 'Drew'
    }, {
        name: 'Chris'
    }, {
        name: 'Mike'
    }];
}]);

<|endoftext|>


<commit_before>/**
 * @classdesc Base class for all the geometry classes besides [maptalks.Marker]{@link maptalks.Marker}.

 * @class
 * @category geometry
 * @abstract
 * @extends maptalks.Geometry
 */
Z.Vector = Z.Geometry.extend(/** @lends maptalks.Vector.prototype */{
    /**
     * @property {Object} options - Vector's options
     * @property {Object} options.symbol - Vector's default symbol
     */
    options:{
        'symbol':{
            'lineColor' : '#474cf8',
            'lineWidth' : 3,
            'lineOpacity' : 1,

            'polygonFill' : '#ffffff',
            'polygonOpacity' : 0
        }
    },

    _hitTestTolerance: function() {
        var symbol = this.getSymbol();
        var w;
        if (Z.Util.isArray(symbol)) {
            w = 0;
            for (var i = 0; i < symbol.length; i++) {
                if (Z.Util.isNumber(symbol[i]['lineWidth'])) {
                    if (symbol[i]['lineWidth'] > w) {
                        w = symbol[i]['lineWidth'];
                    }
                }
            }
        } else {
            w = symbol['lineWidth'];
        }
        return w ? w / 2 : 1.5;
    }
});
<commit_msg>change Vector's default style to #000000 1px<commit_after>/**
 * @classdesc Base class for all the geometry classes besides [maptalks.Marker]{@link maptalks.Marker}.

 * @class
 * @category geometry
 * @abstract
 * @extends maptalks.Geometry
 */
Z.Vector = Z.Geometry.extend(/** @lends maptalks.Vector.prototype */{
    /**
     * @property {Object} options - Vector's options
     * @property {Object} options.symbol - Vector's default symbol
     */
    options:{
        'symbol':{
            'lineColor' : '#000000',
            'lineWidth' : 1,
            'lineOpacity' : 1,

            'polygonFill' : '#ffffff',
            'polygonOpacity' : 0
        }
    },

    _hitTestTolerance: function() {
        var symbol = this.getSymbol();
        var w;
        if (Z.Util.isArray(symbol)) {
            w = 0;
            for (var i = 0; i < symbol.length; i++) {
                if (Z.Util.isNumber(symbol[i]['lineWidth'])) {
                    if (symbol[i]['lineWidth'] > w) {
                        w = symbol[i]['lineWidth'];
                    }
                }
            }
        } else {
            w = symbol['lineWidth'];
        }
        return w ? w / 2 : 1.5;
    }
});
<|endoftext|>


<commit_before>define([
    'require',
    'jquery',
    'base/js/namespace',
    'base/js/dialog',
    'notebook/js/celltoolbar',
    'base/js/events',
    './resources/diff.min'
], function (require,
             $,
             Jupyter,
             dialog,
             notebook_celltoolbar,
             events, JsDiff) {

    var preset_name = 'Cell Testing';

    var CellToolbar = notebook_celltoolbar.CellToolbar;

    var prepare_data = function(cell) {
        if (cell.nbcelltesting_data === undefined) {
            cell.nbcelltesting_data = {};
        }
        if (cell.nbcelltesting_data.pending === undefined) {
            cell.nbcelltesting_data.pending = false;
        }
    };

    events.on('delete.Cell', function(event, data) {
        update_global_result();
    });

    events.on('create.Cell', function(event, data) {
        update_global_result();
    });

    events.on('selected_cell_type_changed.Notebook', function(event, data) {
        update_global_result();
    });

    events.on('execute.CodeCell', function(event, data) {
        cell = data.cell;
        prepare_data(cell);
        cell.nbcelltesting_data.pending = true;
        delete cell.nbcelltesting_data.result_test;
        cell.celltoolbar.rebuild();
        update_global_result();
    });

    events.on('finished_execute.CodeCell', function(event, data) {
        cell = data.cell;
        prepare_data(cell);
        cell.nbcelltesting_data.pending = false;
        test_output(cell);
        cell.celltoolbar.rebuild();
        update_global_result();
    });

    var prepare_metadata = function(cell) {
        if (cell.metadata.nbcelltesting === undefined) {
            cell.metadata.nbcelltesting = {};
        }
    };

    var cleanup_metadata = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            Object.keys(cell.metadata.nbcelltesting).length === 0) {
            delete cell.metadata.nbcelltesting
        }
    };

    var cell_output = function(cell) {
        var pre = cell.output_area.element.find('div.output_subarea').last().find('pre');
        return pre.text();
    };

    var _save_desired_output_ = function(cell, output) {
        prepare_metadata(cell);
        cell.metadata.nbcelltesting.desired_output = output;
    };

    var save_current_output = function(cell) {
        return _save_desired_output_(cell, cell_output(cell));
    };

    var desired_output = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            cell.metadata.nbcelltesting.desired_output !== undefined) {
            return cell.metadata.nbcelltesting.desired_output;
        }
        return null;
    };

    var reset_desired_output = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            cell.metadata.nbcelltesting.hasOwnProperty("desired_output")) {
            delete cell.metadata.nbcelltesting.desired_output;
            cleanup_metadata(cell);
        }
    };

    var edit_nbcelltesting_metadata = function(cell, celltoolbar) {
        var metadata = {};
        if (cell.metadata.nbcelltesting !== undefined) {
            metadata = cell.metadata.nbcelltesting;
        }

        var notebook = Jupyter.notebook;
        dialog.edit_metadata({
            md: metadata,
            callback: function (md) {
                prepare_metadata(cell);
                cell.metadata.nbcelltesting = md;
                test_output(cell);
                if (celltoolbar !== null) {
                    celltoolbar.rebuild();
                }
            },
            name: 'Cell Testing',
            notebook: notebook,
            keyboard_manager: notebook.keyboard_manager});
    };

    var edit_desired_output = function(cell, celltoolbar=null) {
        var output = desired_output(cell);
        if (output === null) { output = ''; }
        var notebook = Jupyter.notebook
        var error_div = $('
').css('color', 'red');
        var message = 'Edit the desired output of the selected cell below.';

        var textarea = $('<textarea/>')
            .attr('rows', '13')
            .attr('cols', '80')
            .attr('name', 'desired-output')
            .text(output);

        var dialogform = $('
').attr('title', 'Edit Desired Output')
            .append(
                $('<form/>').append(
                    $('<fieldset/>').append(
                        $('')
                        .attr('for','desired-output')
                        .text(message)
                        )
                        .append(error_div)
                        .append($('
'))
                        .append(textarea)
                    )
            );

        var editor = CodeMirror.fromTextArea(textarea[0], {
            lineNumbers: true,
            matchBrackets: true,
            indentUnit: 2,
            autoIndent: true,
            mode: 'text/plain',
        });

        var modal_obj = dialog.modal({
            title: 'Edit Desired Output',
            body: dialogform,
            buttons: {
                OK: { class : "btn-primary",
                    click: function() {
                        var new_output = editor.getValue();
                        _save_desired_output_(cell, new_output);
                        test_output(cell);
                        celltoolbar.rebuild();
                        update_global_result();
                    }
                },
                Cancel: {}
            },
            notebook: notebook,
            keyboard_manager: notebook.keyboard_manager,
        });

        modal_obj.on('shown.bs.modal', function(){ editor.refresh(); });
    };

    var compare_output = function(cell) {
        var dout = desired_output(cell);
        if (dout === null) {
            return null;
        }
        var cout = cell_output(cell);
        return cout === dout;
    };

    var status = {'pending': {'text': '',
                              'style': 'info',
                              'cls': 'label-info ct-status-pending',
                              'count': 0,
                              'title': 'Number of pending tests'},
                  'not_available': {'text': 'no output saved',
                                    'style': 'info',
                                    'cls': 'label-info ct-status-not_available',
                                    'count': 0,
                                    'title': 'Number of cells without saved output'},
                  'failed': {'text': 'wrong output',
                             'style': 'danger',
                             'cls': 'label-danger ct-status-failed',
                             'count': 0,
                             'title': 'Number of cells with wrong output'},
                  'passed': {'text': 'correct output',
                             'style': 'success',
                             'cls': 'label-success ct-status-passed',
                             'count': 0,
                             'title': 'Number of cells with correct output'},
                 };

    var test_output = function(cell) {
        prepare_data(cell);
        var result;
        var cls;
        if (cell.nbcelltesting_data.pending === true) {
            result = 'pending';
        } else {
            comparison_result = compare_output(cell);
            if (comparison_result === null) {
                result = 'not_available';
            } else if (comparison_result === false) {
                result = 'failed';
            } else if (comparison_result === true) {
                result = 'passed';
            }
        }

        cell.nbcelltesting_data.result_test = result;
    };

    var result_test = function(cell) {
        if (cell.nbcelltesting_data === undefined ||
            cell.nbcelltesting_data.result_test === undefined) {
            test_output(cell);
        }
        return cell.nbcelltesting_data.result_test;
    };

    var diff_wrong_output = function(cell, celltoolbar=null) {
        var diff = JsDiff.diffChars(desired_output(cell), cell_output(cell));

        var modal_body = $('
').addClass('ct-diff-output');
        diff.forEach(function(part) {
            var colorstyle = part.added ? 'added' : (part.removed ? 'removed' : 'common');
            modal_body.append($('').addClass('ct-diff-output-' + colorstyle)
                              .html(part.value.replace(/\n/g, '
')));
        })

        var notebook = Jupyter.notebook;

        var modal_obj = dialog.modal({
            title: 'Comparison: Desired Output vs. Current Output',
            body: modal_body,
            buttons: {
                OK: {class: 'btn-primary'}
            },
            notebook: notebook,
            keyboard_manager: notebook.keyboard_manager,
        });
    };

    var create_result_test = function(div, cell, celltoolbar) {
        var cell_status = result_test(cell);

        var result = status[cell_status].text;
        var cls = status[cell_status].cls;

        var element = $('').addClass('label result-label').addClass(cls);
        element.append(result);
        element.on('click', function() { on_test_output(cell, celltoolbar); });

        $(div).addClass('ctb-thing result-test')
            .append(element);

        if (cell_status === 'failed') {
            var diffIcon = $('').addClass('fa fa-lg fa-question-circle ct-diff');
            diffIcon.on('click', function() {diff_wrong_output(cell, celltoolbar);});
            $(div).append(diffIcon)
        }
    };

    var create_button = function(name, value, callback) {
        return function(div, cell, celltoolbar) {
            var button = $('<button/>').addClass('btn btn-default btn-xs')
                .addClass('button-' + name)
                .prop('type', 'button')
                .html(value);
            button.name = name;
            button.on('click', function() { callback(cell, celltoolbar) });
            $(div).addClass('ctb-thing').append(button);
        };
    };

    var on_save_current_output = function(cell, celltoolbar) {
        save_current_output(cell);
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var create_button_save = create_button('save', 'Save Output',
                                           on_save_current_output);

    var on_reset_desired_output = function(cell, celltoolbar) {
        reset_desired_output(cell);
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var on_edit_nbcelltesting_metadata = edit_nbcelltesting_metadata;

    var on_edit_desired_output = edit_desired_output;

    var on_test_output = function(cell, celltoolbar) {
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var actions = [{name: 'Reset Output', callback: on_reset_desired_output},
                   {name: 'Edit Output', callback: on_edit_desired_output},
                   {name: 'Test Output', callback: on_test_output},
                   {name: 'break'},
                   {name: 'Edit Metadata', callback: on_edit_nbcelltesting_metadata}];

    var action_callback = function(action, cell, celltoolbar) {
        return function() { action.callback(cell, celltoolbar); }
    }

    var dropdown_factory = function(actions) {
        return function(div, cell, celltoolbar) {
        var dropdownButton = $('<button/>').addClass('btn btn-default btn-xs dropdown-toggle')
            .prop('type', 'button').attr('data-toggle', 'dropdown')
            .html('');

        var options = $('
').addClass('dropdown-menu');

        for (var action of actions) {
            if (action.name === 'break') {
                options.append($('
').attr('role', 'separator').addClass('divider'));
                continue;
            }
            var action_link = $('').prop('href', '#').html(action.name);
            action_link.on('click', action_callback(action, cell, celltoolbar));
            options.append($('
').append(action_link));
        }

        $(div).addClass('ctb-thing dropdown').append(dropdownButton).append(options);
        };
    };

    var create_dropdown_menu = dropdown_factory(actions);

    var global_status = ['passed', 'pending', 'failed', 'not_available'];

    var update_global_result = function() {
        var n = 0;
        for (var s of global_status) {
            status[s].count = $('.ct-status-' + s).length
            n += status[s].count;
        }
        for (var s of global_status) {
            $('#nbcelltesting-global-result-' + s)
                .attr('style', 'width: ' + status[s].count / n * 100 + '%')
                .html(status[s].count);
        }
    };

    events.on('preset_activated.CellToolbar', function(event, preset) {
        create_global_result(preset.name === preset_name);
    });

    var create_global_result = function(show) {
        if (typeof show === 'undefined') { show = true; }
        var element = $('#nbcelltesting-global-result');
        if (show) {
            if (element.length == 0) {
                var progress = $('
')
                    .attr('id', 'nbcelltesting-global-result')
                    .addClass('progress')
                for (var s of global_status) {
                    progress.append(
                        $('
')
                            .attr('id', 'nbcelltesting-global-result-' + s)
                            .addClass('progress-bar progress-bar-' + status[s].style)
                            .attr('role', 'progressbar')
                            .attr('title', status[s].title));
                }
                $("#maintoolbar-container").append(progress);
            }
            update_global_result();
            element = progress;
            element.show();
        } else {
            element.hide();
        }
    };

    var load_css = function () {
        var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = require.toUrl('./nbcelltesting.css');
        document.getElementsByTagName('head')[0].appendChild(link);
    };

    function load_extension(){
        load_css();

        CellToolbar.register_callback('nbcelltesting.result_test',
                                      create_result_test,
                                      ['code']);
        CellToolbar.register_callback('nbcelltesting.button_save',
                                      create_button_save,
                                      ['code']);
        CellToolbar.register_callback('nbcelltesting.dropdown_menu',
                                      create_dropdown_menu,
                                      ['code']);

         var preset = [
            'nbcelltesting.result_test',
            'nbcelltesting.button_save',
            'nbcelltesting.dropdown_menu',
        ];
        CellToolbar.register_preset(preset_name, preset, Jupyter.notebook);
        console.log('nbcelltesting extension loaded.');
    }

    return {
        load_ipython_extension: load_extension,
        load_css: load_css,
        create_button: create_button,
        create_global_result: create_global_result,
        dropdown_factory: dropdown_factory,
        on_reset_desired_output: on_reset_desired_output,
        on_edit_desired_output: on_edit_desired_output,
        on_test_output: on_test_output,
        on_edit_nbcelltesting_metadata: on_edit_nbcelltesting_metadata
    };
});
<commit_msg>toggle_ignore<commit_after>define([
    'require',
    'jquery',
    'base/js/namespace',
    'base/js/dialog',
    'notebook/js/celltoolbar',
    'base/js/events',
    './resources/diff.min'
], function (require,
             $,
             Jupyter,
             dialog,
             notebook_celltoolbar,
             events, JsDiff) {

    var preset_name = 'Cell Testing';

    var CellToolbar = notebook_celltoolbar.CellToolbar;

    var prepare_data = function(cell) {
        if (cell.nbcelltesting_data === undefined) {
            cell.nbcelltesting_data = {};
        }
        if (cell.nbcelltesting_data.pending === undefined) {
            cell.nbcelltesting_data.pending = false;
        }
    };

    events.on('delete.Cell', function(event, data) {
        update_global_result();
    });

    events.on('create.Cell', function(event, data) {
        update_global_result();
    });

    events.on('selected_cell_type_changed.Notebook', function(event, data) {
        update_global_result();
    });

    events.on('execute.CodeCell', function(event, data) {
        cell = data.cell;
        prepare_data(cell);
        cell.nbcelltesting_data.pending = true;
        delete cell.nbcelltesting_data.result_test;
        cell.celltoolbar.rebuild();
        update_global_result();
    });

    events.on('finished_execute.CodeCell', function(event, data) {
        cell = data.cell;
        prepare_data(cell);
        cell.nbcelltesting_data.pending = false;
        test_output(cell);
        cell.celltoolbar.rebuild();
        update_global_result();
    });

    var prepare_metadata = function(cell) {
        if (cell.metadata.nbcelltesting === undefined) {
            cell.metadata.nbcelltesting = {};
        }
    };

    var cleanup_metadata = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            Object.keys(cell.metadata.nbcelltesting).length === 0) {
            delete cell.metadata.nbcelltesting
        }
    };

    var cell_output = function(cell) {
        var pre = cell.output_area.element.find('div.output_subarea').last().find('pre');
        return pre.text();
    };

    var _save_desired_output_ = function(cell, output) {
        prepare_metadata(cell);
        cell.metadata.nbcelltesting.desired_output = output;
    };

    var save_current_output = function(cell) {
        return _save_desired_output_(cell, cell_output(cell));
    };

    var desired_output = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            cell.metadata.nbcelltesting.desired_output !== undefined) {
            return cell.metadata.nbcelltesting.desired_output;
        }
        return null;
    };

    var reset_desired_output = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            cell.metadata.nbcelltesting.hasOwnProperty("desired_output")) {
            delete cell.metadata.nbcelltesting.desired_output;
            cleanup_metadata(cell);
        }
    };

    var edit_nbcelltesting_metadata = function(cell, celltoolbar) {
        var metadata = {};
        if (cell.metadata.nbcelltesting !== undefined) {
            metadata = cell.metadata.nbcelltesting;
        }

        var notebook = Jupyter.notebook;
        dialog.edit_metadata({
            md: metadata,
            callback: function (md) {
                prepare_metadata(cell);
                cell.metadata.nbcelltesting = md;
                test_output(cell);
                if (celltoolbar !== null) {
                    celltoolbar.rebuild();
                }
            },
            name: 'Cell Testing',
            notebook: notebook,
            keyboard_manager: notebook.keyboard_manager});
    };

    var edit_desired_output = function(cell, celltoolbar=null) {
        var output = desired_output(cell);
        if (output === null) { output = ''; }
        var notebook = Jupyter.notebook
        var error_div = $('
').css('color', 'red');
        var message = 'Edit the desired output of the selected cell below.';

        var textarea = $('<textarea/>')
            .attr('rows', '13')
            .attr('cols', '80')
            .attr('name', 'desired-output')
            .text(output);

        var dialogform = $('
').attr('title', 'Edit Desired Output')
            .append(
                $('<form/>').append(
                    $('<fieldset/>').append(
                        $('')
                        .attr('for','desired-output')
                        .text(message)
                        )
                        .append(error_div)
                        .append($('
'))
                        .append(textarea)
                    )
            );

        var editor = CodeMirror.fromTextArea(textarea[0], {
            lineNumbers: true,
            matchBrackets: true,
            indentUnit: 2,
            autoIndent: true,
            mode: 'text/plain',
        });

        var modal_obj = dialog.modal({
            title: 'Edit Desired Output',
            body: dialogform,
            buttons: {
                OK: { class : "btn-primary",
                    click: function() {
                        var new_output = editor.getValue();
                        _save_desired_output_(cell, new_output);
                        test_output(cell);
                        celltoolbar.rebuild();
                        update_global_result();
                    }
                },
                Cancel: {}
            },
            notebook: notebook,
            keyboard_manager: notebook.keyboard_manager,
        });

        modal_obj.on('shown.bs.modal', function(){ editor.refresh(); });
    };

    var compare_output = function(cell) {
        var dout = desired_output(cell);
        if (dout === null) {
            return null;
        }
        var cout = cell_output(cell);
        return cout === dout;
    };

    var status = {'pending': {'text': '',
                              'style': 'info',
                              'cls': 'label-info ct-status-pending',
                              'count': 0,
                              'title': 'Number of pending tests'},
                  'not_available': {'text': 'no output saved',
                                    'style': 'info',
                                    'cls': 'label-info ct-status-not_available',
                                    'count': 0,
                                    'title': 'Number of cells without saved output'},
                  'failed': {'text': 'wrong output',
                             'style': 'danger',
                             'cls': 'label-danger ct-status-failed',
                             'count': 0,
                             'title': 'Number of cells with wrong output'},
                  'passed': {'text': 'correct output',
                             'style': 'success',
                             'cls': 'label-success ct-status-passed',
                             'count': 0,
                             'title': 'Number of cells with correct output'},
                  'ignore': {'text': 'ignored',
                             'style': 'default',
                             'cls': 'label-default ct-status-ignore',
                             'count': 0,
                             'title': 'Number of cells ignored'},
                 };

    var test_output = function(cell) {
        prepare_data(cell);
        var result;
        if (cell.nbcelltesting_data.ignore === true) {
            result = 'ignore';
        } else if (cell.nbcelltesting_data.pending === true) {
            result = 'pending';
        } else {
            comparison_result = compare_output(cell);
            if (comparison_result === null) {
                result = 'not_available';
            } else if (comparison_result === false) {
                result = 'failed';
            } else if (comparison_result === true) {
                result = 'passed';
            }
        }

        cell.nbcelltesting_data.result_test = result;
    };

    var result_test = function(cell) {
        if (cell.nbcelltesting_data === undefined ||
            cell.nbcelltesting_data.result_test === undefined) {
            test_output(cell);
        }
        return cell.nbcelltesting_data.result_test;
    };

    var diff_wrong_output = function(cell, celltoolbar=null) {
        var diff = JsDiff.diffChars(desired_output(cell), cell_output(cell));

        var modal_body = $('
').addClass('ct-diff-output');
        diff.forEach(function(part) {
            var colorstyle = part.added ? 'added' : (part.removed ? 'removed' : 'common');
            modal_body.append($('').addClass('ct-diff-output-' + colorstyle)
                              .html(part.value.replace(/\n/g, '
')));
        })

        var notebook = Jupyter.notebook;

        var modal_obj = dialog.modal({
            title: 'Comparison: Desired Output vs. Current Output',
            body: modal_body,
            buttons: {
                OK: {class: 'btn-primary'}
            },
            notebook: notebook,
            keyboard_manager: notebook.keyboard_manager,
        });
    };

    var create_result_test = function(div, cell, celltoolbar) {
        var cell_status = result_test(cell);

        var result = status[cell_status].text;
        var cls = status[cell_status].cls;

        var element = $('').addClass('label result-label').addClass(cls);
        element.append(result);
        element.on('click', function() { on_test_output(cell, celltoolbar); });

        $(div).addClass('ctb-thing result-test')
            .append(element);

        if (cell_status === 'failed') {
            var diffIcon = $('').addClass('fa fa-lg fa-question-circle ct-diff');
            diffIcon.on('click', function() {diff_wrong_output(cell, celltoolbar);});
            $(div).append(diffIcon)
        }
    };

    var toggle_ignore = function(cell) {
        prepare_data(cell);
        if (cell.nbcelltesting_data.ignore === undefined) {
            cell.nbcelltesting_data.ignore = true;
        } else {
            cell.nbcelltesting_data.ignore =
                !cell.nbcelltesting_data.ignore;
        }
    };

    var on_toggle_ignore = function(cell, celltoolbar) {
        toggle_ignore(cell);
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var create_button = function(name, value, callback) {
        return function(div, cell, celltoolbar) {
            var button = $('<button/>').addClass('btn btn-default btn-xs')
                .addClass('button-' + name)
                .prop('type', 'button')
                .html(value);
            button.name = name;
            button.on('click', function() { callback(cell, celltoolbar) });
            $(div).addClass('ctb-thing').append(button);
        };
    };

    var on_save_current_output = function(cell, celltoolbar) {
        save_current_output(cell);
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var create_button_save = create_button('save', 'Save Output',
                                           on_save_current_output);

    var on_reset_desired_output = function(cell, celltoolbar) {
        reset_desired_output(cell);
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var on_edit_nbcelltesting_metadata = edit_nbcelltesting_metadata;

    var on_edit_desired_output = edit_desired_output;

    var on_test_output = function(cell, celltoolbar) {
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var actions = [{name: 'Reset Output', callback: on_reset_desired_output},
                   {name: 'Edit Output', callback: on_edit_desired_output},
                   {name: 'Test Output', callback: on_test_output},
                   {name: 'break'},
                   {name: 'Toggle Ignore', callback: on_toggle_ignore},
                   {name: 'break'},
                   {name: 'Edit Metadata', callback: on_edit_nbcelltesting_metadata}];

    var action_callback = function(action, cell, celltoolbar) {
        return function() { action.callback(cell, celltoolbar); }
    }

    var dropdown_factory = function(actions) {
        return function(div, cell, celltoolbar) {
        var dropdownButton = $('<button/>').addClass('btn btn-default btn-xs dropdown-toggle')
            .prop('type', 'button').attr('data-toggle', 'dropdown')
            .html('');

        var options = $('
').addClass('dropdown-menu');

        for (var action of actions) {
            if (action.name === 'break') {
                options.append($('
').attr('role', 'separator').addClass('divider'));
                continue;
            }
            var action_link = $('').prop('href', '#').html(action.name);
            action_link.on('click', action_callback(action, cell, celltoolbar));
            options.append($('
').append(action_link));
        }

        $(div).addClass('ctb-thing dropdown').append(dropdownButton).append(options);
        };
    };

    var create_dropdown_menu = dropdown_factory(actions);

    var global_status = ['passed', 'pending', 'failed', 'not_available'];

    var update_global_result = function() {
        var n = 0;
        for (var s of global_status) {
            status[s].count = $('.ct-status-' + s).length
            n += status[s].count;
        }
        for (var s of global_status) {
            $('#nbcelltesting-global-result-' + s)
                .attr('style', 'width: ' + status[s].count / n * 100 + '%')
                .html(status[s].count);
        }
    };

    events.on('preset_activated.CellToolbar', function(event, preset) {
        create_global_result(preset.name === preset_name);
    });

    var create_global_result = function(show) {
        if (typeof show === 'undefined') { show = true; }
        var element = $('#nbcelltesting-global-result');
        if (show) {
            if (element.length == 0) {
                var progress = $('
')
                    .attr('id', 'nbcelltesting-global-result')
                    .addClass('progress')
                for (var s of global_status) {
                    progress.append(
                        $('
')
                            .attr('id', 'nbcelltesting-global-result-' + s)
                            .addClass('progress-bar progress-bar-' + status[s].style)
                            .attr('role', 'progressbar')
                            .attr('title', status[s].title));
                }
                $("#maintoolbar-container").append(progress);
            }
            update_global_result();
            element = progress;
            element.show();
        } else {
            element.hide();
        }
    };

    var load_css = function () {
        var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = require.toUrl('./nbcelltesting.css');
        document.getElementsByTagName('head')[0].appendChild(link);
    };

    function load_extension(){
        load_css();

        CellToolbar.register_callback('nbcelltesting.result_test',
                                      create_result_test,
                                      ['code']);
        CellToolbar.register_callback('nbcelltesting.button_save',
                                      create_button_save,
                                      ['code']);
        CellToolbar.register_callback('nbcelltesting.dropdown_menu',
                                      create_dropdown_menu,
                                      ['code']);

         var preset = [
            'nbcelltesting.result_test',
            'nbcelltesting.button_save',
            'nbcelltesting.dropdown_menu',
        ];
        CellToolbar.register_preset(preset_name, preset, Jupyter.notebook);
        console.log('nbcelltesting extension loaded.');
    }

    return {
        load_ipython_extension: load_extension,
        load_css: load_css,
        create_button: create_button,
        create_global_result: create_global_result,
        dropdown_factory: dropdown_factory,
        on_reset_desired_output: on_reset_desired_output,
        on_edit_desired_output: on_edit_desired_output,
        on_test_output: on_test_output,
        on_edit_nbcelltesting_metadata: on_edit_nbcelltesting_metadata
    };
});
<|endoftext|>


<commit_before>$(document).ready(function(){

  $('a.sidemenu-item#sidemenu-user').click(function() {
    if ($('li.dropdown#sidemenu-user').hasClass('open')) {
        $('li.dropdown#sidemenu-user').removeClass('open');
    } else {
        $('li.dropdown#sidemenu-user').addClass('open');
    }
  });
  $('i.pull-right.fa.fa-angle-left').click(function() {
    if ($('body').hasClass('sidemenu-open')) {
      $('body').removeClass('sidemenu-open');
      $('i.pull-right.fa.fa-angle-left').toggleClass('fa-angle-left fa-angle-right');
      $(".logo-icon").rotate({ angle:0,animateTo:270, duration: 2000, easing: $.easing.easeOutBounce })
    } else {
      $('body').addClass('sidemenu-open');
      $('i.pull-right.fa.fa-angle-right').toggleClass('fa-angle-right fa-angle-left');
      $(".logo-icon").rotate({ angle:270,animateTo:0, duration: 2000, easing: $.easing.easeOutBounce })
    }
  });
});
<commit_msg>[OWL-144] Clicking outside also closes the UIC dropdown menu.<commit_after>$(document).ready(function(){

  $('a.sidemenu-item#sidemenu-user').click(function() {
    if ($('li.dropdown#sidemenu-user').hasClass('open')) {
        $('li.dropdown#sidemenu-user').removeClass('open');
    } else {
        $('li.dropdown#sidemenu-user').addClass('open');
    }
  });
  $('i.pull-right.fa.fa-angle-left').click(function() {
    if ($('body').hasClass('sidemenu-open')) {
      $('body').removeClass('sidemenu-open');
      $('i.pull-right.fa.fa-angle-left').toggleClass('fa-angle-left fa-angle-right');
      $(".logo-icon").rotate({ angle:0,animateTo:270, duration: 2000, easing: $.easing.easeOutBounce })
    } else {
      $('body').addClass('sidemenu-open');
      $('i.pull-right.fa.fa-angle-right').toggleClass('fa-angle-right fa-angle-left');
      $(".logo-icon").rotate({ angle:270,animateTo:0, duration: 2000, easing: $.easing.easeOutBounce })
    }
  });
  $(document).click(function(){
      $('li.dropdown#sidemenu-user').removeClass('open');
  });
  $('li.dropdown#sidemenu-user').click(function(e){
      e.stopPropagation();
  });
});
<|endoftext|>


<commit_before>var mongoose = require('mongoose');

var types = Object.freeze({"up": 1, "down": 2});

var eventSchema = mongoose.Schema({
    monitor: {type: String, required: true},
    type: {type: Number, required: true},
    time: {type: Number, required: true},
    createdAt: Date

});

eventSchema.pre('save', function (next) {
    this.createdAt = Date.now();
    next();
});

var Event = mongoose.model('Response', eventSchema);

module.exports = Event;

<commit_msg>clone issue<commit_after>var mongoose = require('mongoose');

var types = Object.freeze({"up": 1, "down": 2});

var eventSchema = mongoose.Schema({
    monitor: {type: String, required: true},
    type: {type: Number, required: true},
    time: {type: Number, required: true},
    createdAt: Date

});

eventSchema.pre('save', function (next) {
    this.createdAt = Date.now();
    next();
});

var Event = mongoose.model('Event', eventSchema);

module.exports = Event;

<|endoftext|>


<commit_before>import createHistory from 'history/createBrowserHistory';
export default createHistory();<commit_msg>Added basename to route history for github pages<commit_after>import createHistory from 'history/createBrowserHistory';
export default createHistory({
  basename: "/HearthLounge"
});<|endoftext|>