<commit_before>'use strict';

var Requested = require('./requested')
  , listeners = require('loads')
  , send = require('xhr-send')
  , hang = require('hang')
  , AXO = require('axo');

/**
 * RequestS(tream).
 *
 * Options:
 *
 * - streaming: Should the request be streaming.
 * - method: Which HTTP method should be used.
 * - headers: Additional request headers.
 * - mode: Enable CORS mode.
 * - body: The payload for the request.
 *
 * @constructor
 * @param {String} url The URL we want to request.
 * @param {Object} options Various of request options.
 * @api public
 */
var Requests = module.exports = Requested.extend({
  constructor: function bobthebuilder(url, options) {
    if (!(this instanceof Requests)) return new Requests(url, options);

    Requested.apply(this, arguments);
  },

  /**
   * The offset of data that we've already previously read
   *
   * @type {Number}
   * @private
   */
  offset: 0,

  /**
   * The requests instance has been fully initialized.
   *
   * @param {String} url The URL we need to connect to.
   * @api private
   */
  initialize: function initialize(url) {
    this.socket = Requests[Requests.method](this);

    //
    // Open the socket BEFORE adding any properties to the instance as this might
    // trigger a thrown `InvalidStateError: An attempt was made to use an object
    // that is not, or is no longer, usable` error in FireFox:
    //
    // @see https://bugzilla.mozilla.org/show_bug.cgi?id=707484
    //
    this.socket.open(this.method.toUpperCase(), url, true);

    //
    // Register this as an active HTTP request.
    //
    Requests.active[this.id] = this;
  },

  /**
   * Initialize and start requesting the supplied resource.
   *
   * @param {Object} options Passed in defaults.
   * @api private
   */
  open: function open() {
    var what
      , requests = this
      , socket = requests.socket;

    requests.on('stream', function stream(data) {
      if (socket.multipart || Requests.type.mozchunkedtext) {
        return requests.emit('data', data);
      }

      //
      // Please note that we need to use a method here that works on both string
      // as well as ArrayBuffer's as we have no certainty that we're receiving
      // text.
      //
      var chunk = data.slice(requests.offset);
      requests.offset = data.length;

      requests.emit('data', chunk);
    });

    requests.on('end', function cleanup() {
      delete Requests.active[requests.id];
    });

    if (this.timeout) {
      socket.timeout = +this.timeout;
    }

    if ('cors' === this.mode.toLowerCase() && 'withCredentials' in socket) {
      socket.withCredentials = true;
    }

    //
    // ActiveXObject will throw an `Type Mismatch` exception when setting the to
    // an null-value and to be consistent with all XHR implementations we're going
    // to cast the value to a string.
    //
    // While we don't technically support the XDomainRequest of IE, we do want to
    // double check that the setRequestHeader is available before adding headers.
    //
    // Chrome has a bug where it will actually append values to the header instead
    // of overriding it. So if you do a double setRequestHeader(Content-Type) with
    // text/plain and with text/plain again, it will end up as `text/plain,
    // text/plain` as header value. This is why use a headers object as it
    // already eliminates duplicate headers.
    //
    for (what in this.headers) {
      if (this.headers[what] !== undefined && this.socket.setRequestHeader) {
        this.socket.setRequestHeader(what, this.headers[what] +'');
      }
    }

    //
    // Set the correct responseType method.
    //
    if (requests.streaming) {
      if (!this.body || 'string' === typeof this.body) {
        if ('multipart' in socket) {
          socket.multipart = true;
        } else if (Requests.type.mozchunkedtext) {
          socket.responseType = 'moz-chunked-text';
        }
      } else {
        if (Requests.type.mozchunkedarraybuffer) {
          socket.responseType = 'moz-chunked-arraybuffer';
        } else if (Requests.type.msstream) {
          socket.responseType = 'ms-stream';
        }
      }
    }

    listeners(socket, requests, requests.streaming);
    requests.emit('before', socket);

    send(socket, this.body, hang(function send(err) {
      if (err) {
        requests.emit('error', err);
        requests.emit('end', err);
      }

      requests.emit('send');
    }));
  },

  /**
   * Completely destroy the running XHR and release of the internal references.
   *
   * @returns {Boolean} Successful destruction
   * @api public
   */
  destroy: function destroy() {
    if (!this.socket) return false;

    this.emit('destroy');

    this.socket.abort();
    this.removeAllListeners();

    this.headers = {};
    this.socket = null;
    this.body = null;

    delete Requests.active[this.id];

    return true;
  }
});

/**
 * Create a new XMLHttpRequest.
 *
 * @returns {XMLHttpRequest}
 * @api private
 */
Requests.XHR = function create() {
  try { return new XMLHttpRequest(); }
  catch (e) {}
};

/**
 * Create a new ActiveXObject which can be used for XHR.
 *
 * @returns {ActiveXObject}
 * @api private
 */
Requests.AXO = function create() {
  var ids = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']
    , id;

  while (ids.length) {
    id = ids.shift();

    try { return new AXO(id); }
    catch (e) {}
  }
};

/**
 * Requests that are currently running.
 *
 * @type {Object}
 * @private
 */
Requests.active = {};

/**
 * The type of technology we are using to establish a working Ajax connection.
 * This can either be:
 *
 * - XHR: XMLHttpRequest
 * - AXO: ActiveXObject
 *
 * This is also used as internal optimization so we can easily get the correct
 * constructor as we've already feature detected it.
 *
 * @type {String}
 * @public
 */
Requests.method = !!Requests.XHR() ? 'XHR' : (!!Requests.AXO() ? 'AXO' : '');

/**
 * Boolean indicating
 *
 * @type {Boolean}
 * @public
 */
Requests.supported = !!Requests.method;

/**
 * The different type of `responseType` parsers that are supported in this XHR
 * implementation.
 *
 * @type {Object}
 * @public
 */
Requests.type = 'XHR' === Requests.method ? (function detect() {
  var types = 'arraybuffer,blob,document,json,text,moz-blob,moz-chunked-text,moz-chunked-arraybuffer,ms-stream'.split(',')
    , supported = {}
    , type, xhr, prop;

  while (types.length) {
    type = types.pop();

    xhr = Requests.XHR();
    xhr.open('get', '/', true);
    prop = type.replace(/-/g, '');

    //
    // We can only set the `responseType` after we've opened the connection or
    // FireFox will throw an error and according to the spec only async requests
    // can use this, which is fine as we force that by default.
    //
    try {
      xhr.responseType = type;
      supported[prop] = 'response' in xhr && xhr.responseType === type;
    } catch (e) {
      supported[prop] = false;
    }

    xhr = null;
  }

  return supported;
}()) : {};

/**
 * Do we support streaming response parsing.
 *
 * @type {Boolean}
 * @private
 */
Requests.streaming = 'XHR' === Requests.method && (
     'multipart' in XMLHttpRequest.prototype
  || Requests.type.mozchunkedarraybuffer
  || Requests.type.mozchunkedtext
  || Requests.type.msstream
  || Requests.type.mozblob
);

//
// IE has a bug which causes IE10 to freeze when close WebPage during an XHR
// request: https://support.microsoft.com/kb/2856746
//
// The solution is to completely clean up all active running requests.
//
if (global.attachEvent) global.attachEvent('onunload', function reap() {
  for (var id in Requests.active) {
    Requests.active[id].destroy();
  }
});

//
// Expose the Requests library.
//
module.exports = Requests;
<commit_msg>[fix] Introduce slice boolean<commit_after>'use strict';

var Requested = require('./requested')
  , listeners = require('loads')
  , send = require('xhr-send')
  , hang = require('hang')
  , AXO = require('axo');

/**
 * RequestS(tream).
 *
 * Options:
 *
 * - streaming: Should the request be streaming.
 * - method: Which HTTP method should be used.
 * - headers: Additional request headers.
 * - mode: Enable CORS mode.
 * - body: The payload for the request.
 *
 * @constructor
 * @param {String} url The URL we want to request.
 * @param {Object} options Various of request options.
 * @api public
 */
var Requests = module.exports = Requested.extend({
  constructor: function bobthebuilder(url, options) {
    if (!(this instanceof Requests)) return new Requests(url, options);

    Requested.apply(this, arguments);
  },

  /**
   * The offset of data that we've already previously read
   *
   * @type {Number}
   * @private
   */
  offset: 0,

  /**
   * The requests instance has been fully initialized.
   *
   * @param {String} url The URL we need to connect to.
   * @api private
   */
  initialize: function initialize(url) {
    this.socket = Requests[Requests.method](this);

    //
    // Open the socket BEFORE adding any properties to the instance as this might
    // trigger a thrown `InvalidStateError: An attempt was made to use an object
    // that is not, or is no longer, usable` error in FireFox:
    //
    // @see https://bugzilla.mozilla.org/show_bug.cgi?id=707484
    //
    this.socket.open(this.method.toUpperCase(), url, true);

    //
    // Register this as an active HTTP request.
    //
    Requests.active[this.id] = this;
  },

  /**
   * Initialize and start requesting the supplied resource.
   *
   * @param {Object} options Passed in defaults.
   * @api private
   */
  open: function open() {
    var what
      , slice = true
      , requests = this
      , socket = requests.socket;

    requests.on('stream', function stream(data) {
      if (!slice) {
        return requests.emit('data', data);
      }

      //
      // Please note that we need to use a method here that works on both string
      // as well as ArrayBuffer's as we have no certainty that we're receiving
      // text.
      //
      var chunk = data.slice(requests.offset);
      requests.offset = data.length;

      requests.emit('data', chunk);
    });

    requests.on('end', function cleanup() {
      delete Requests.active[requests.id];
    });

    if (this.timeout) {
      socket.timeout = +this.timeout;
    }

    if ('cors' === this.mode.toLowerCase() && 'withCredentials' in socket) {
      socket.withCredentials = true;
    }

    //
    // ActiveXObject will throw an `Type Mismatch` exception when setting the to
    // an null-value and to be consistent with all XHR implementations we're going
    // to cast the value to a string.
    //
    // While we don't technically support the XDomainRequest of IE, we do want to
    // double check that the setRequestHeader is available before adding headers.
    //
    // Chrome has a bug where it will actually append values to the header instead
    // of overriding it. So if you do a double setRequestHeader(Content-Type) with
    // text/plain and with text/plain again, it will end up as `text/plain,
    // text/plain` as header value. This is why use a headers object as it
    // already eliminates duplicate headers.
    //
    for (what in this.headers) {
      if (this.headers[what] !== undefined && this.socket.setRequestHeader) {
        this.socket.setRequestHeader(what, this.headers[what] +'');
      }
    }

    //
    // Set the correct responseType method.
    //
    if (requests.streaming) {
      if (!this.body || 'string' === typeof this.body) {
        if ('multipart' in socket) {
          socket.multipart = true;
          slice = false;
        } else if (Requests.type.mozchunkedtext) {
          socket.responseType = 'moz-chunked-text';
          slice = false;
        }
      } else {
        if (Requests.type.mozchunkedarraybuffer) {
          socket.responseType = 'moz-chunked-arraybuffer';
        } else if (Requests.type.msstream) {
          socket.responseType = 'ms-stream';
        }
      }
    }

    listeners(socket, requests, requests.streaming);
    requests.emit('before', socket);

    send(socket, this.body, hang(function send(err) {
      if (err) {
        requests.emit('error', err);
        requests.emit('end', err);
      }

      requests.emit('send');
    }));
  },

  /**
   * Completely destroy the running XHR and release of the internal references.
   *
   * @returns {Boolean} Successful destruction
   * @api public
   */
  destroy: function destroy() {
    if (!this.socket) return false;

    this.emit('destroy');

    this.socket.abort();
    this.removeAllListeners();

    this.headers = {};
    this.socket = null;
    this.body = null;

    delete Requests.active[this.id];

    return true;
  }
});

/**
 * Create a new XMLHttpRequest.
 *
 * @returns {XMLHttpRequest}
 * @api private
 */
Requests.XHR = function create() {
  try { return new XMLHttpRequest(); }
  catch (e) {}
};

/**
 * Create a new ActiveXObject which can be used for XHR.
 *
 * @returns {ActiveXObject}
 * @api private
 */
Requests.AXO = function create() {
  var ids = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'Microsoft.XMLHTTP']
    , id;

  while (ids.length) {
    id = ids.shift();

    try { return new AXO(id); }
    catch (e) {}
  }
};

/**
 * Requests that are currently running.
 *
 * @type {Object}
 * @private
 */
Requests.active = {};

/**
 * The type of technology we are using to establish a working Ajax connection.
 * This can either be:
 *
 * - XHR: XMLHttpRequest
 * - AXO: ActiveXObject
 *
 * This is also used as internal optimization so we can easily get the correct
 * constructor as we've already feature detected it.
 *
 * @type {String}
 * @public
 */
Requests.method = !!Requests.XHR() ? 'XHR' : (!!Requests.AXO() ? 'AXO' : '');

/**
 * Boolean indicating
 *
 * @type {Boolean}
 * @public
 */
Requests.supported = !!Requests.method;

/**
 * The different type of `responseType` parsers that are supported in this XHR
 * implementation.
 *
 * @type {Object}
 * @public
 */
Requests.type = 'XHR' === Requests.method ? (function detect() {
  var types = 'arraybuffer,blob,document,json,text,moz-blob,moz-chunked-text,moz-chunked-arraybuffer,ms-stream'.split(',')
    , supported = {}
    , type, xhr, prop;

  while (types.length) {
    type = types.pop();

    xhr = Requests.XHR();
    xhr.open('get', '/', true);
    prop = type.replace(/-/g, '');

    //
    // We can only set the `responseType` after we've opened the connection or
    // FireFox will throw an error and according to the spec only async requests
    // can use this, which is fine as we force that by default.
    //
    try {
      xhr.responseType = type;
      supported[prop] = 'response' in xhr && xhr.responseType === type;
    } catch (e) {
      supported[prop] = false;
    }

    xhr = null;
  }

  return supported;
}()) : {};

/**
 * Do we support streaming response parsing.
 *
 * @type {Boolean}
 * @private
 */
Requests.streaming = 'XHR' === Requests.method && (
     'multipart' in XMLHttpRequest.prototype
  || Requests.type.mozchunkedarraybuffer
  || Requests.type.mozchunkedtext
  || Requests.type.msstream
  || Requests.type.mozblob
);

//
// IE has a bug which causes IE10 to freeze when close WebPage during an XHR
// request: https://support.microsoft.com/kb/2856746
//
// The solution is to completely clean up all active running requests.
//
if (global.attachEvent) global.attachEvent('onunload', function reap() {
  for (var id in Requests.active) {
    Requests.active[id].destroy();
  }
});

//
// Expose the Requests library.
//
module.exports = Requests;
<|endoftext|>


<commit_before>{% load vv_tags %}

isInStorage: function(resturl) {
	var url = store.get(resturl);
	if (url == undefined) {
		return false
	}
	return true
},
loadFromStorage: function(resturl) {
	var url = store.get(resturl);
	console.log("store: "+url);
},
loadHtml: function(resturl){
	if (this.isInStorage(resturl) === true) {
		loadFromStorage(resturl);
	}
	promise.get(resturl,{},{"Accept":"application/json"}).then(function(error, data, xhr) {
	    if (error) {console.log('Error ' + xhr.status);return;}
	    {% if isdebug is True %}console.log("Raw data: "+data);{% endif %}
	    app.flushContent();
	    var data = JSON.parse(data);
	    app.content = data.content;
	    app.title = data.title;
	    top.document.title = data.title;
	});
	return
},
loadChunk: function (resturl, title){
	promise.get(resturl).then(function(error, data, xhr) {
	    if (error) {console.log('Error ' + xhr.status);return;}
	    {% if isdebug is True %}console.log("Raw chunk: "+data);{% endif %}
	    app.flushContent();
	    app.content = data;
	    app.title = title;
	    top.document.title = title;
	});
	return
},<commit_msg>Using local storage for content<commit_after>{% load vv_tags %}

isInStorage: function(resturl) {
	var url = store.get(resturl);
	if (url == undefined) {
		return false
	}
	return true
},
loadFromStorage: function(resturl) {
	var data = store.get(resturl);
	return data
},
loadHtml: function(resturl){
	var fetch = true;
	var data = {};
	if (this.isInStorage(resturl) === true) {
		//console.log("Data in storage: "+resturl);
		data = this.loadFromStorage(resturl);
		now = new Date();
		var is_expired = false;
		if (data.expires < now) {
			var is_expired = true;
		}
		if (is_expired === false) {
			//console.log("Data not expired");
			fetch = false;
		} else {
			//console.log("Data expired");
			if (navigator.onLine === false) {
				fetch = false;
				//console.log("Navigator not online");
			} else {
				//console.log("Navigator online");
			}
		}
	}
	if (fetch === true){
		//console.log("Fetchind data from "+resturl+" //"+JSON.stringify(data));
		promise.get(resturl,{},{"Accept":"application/json"}).then(function(error, data, xhr) {
		    if (error) {
		    	console.log('Error ' + xhr.status);return;
		    }
		    {% if isdebug is True %}console.log("Raw data: "+data);{% endif %}
		    data = JSON.parse(data);
		});
		var now = new Date();
		var exp = new Date();
		var mins = 24*60;
		var duration = 1000*60*mins;
		exp.setTime(oldDateObj.getTime() + (duration));
		data.expires = exp;
		store.set(resturl, data);
	}
	app.flushContent();
	app.content = data.content;
    app.title = data.title;
    top.document.title = data.title;
	return
},
loadChunk: function (resturl, title){
	promise.get(resturl).then(function(error, data, xhr) {
	    if (error) {console.log('Error ' + xhr.status);return;}
	    {% if isdebug is True %}console.log("Raw chunk: "+data);{% endif %}
	    app.flushContent();
	    app.content = data;
	    app.title = title;
	    top.document.title = title;
	});
	return
},<|endoftext|>


<commit_before>import getElement from './-get-element';
import fireEvent from './fire-event';
import { __focus__ } from './focus';
import settled from '../settled';
import isFocusable from './-is-focusable';
import { nextTickPromise } from '../-utils';

/**
  @private
  @method __click__
  @param {Element} element
*/
export function __click__(element) {
  fireEvent(element, 'mousedown');

  if (isFocusable(element)) {
    __focus__(element);
  }

  fireEvent(element, 'mouseup');
  fireEvent(element, 'click');
}

/**
  @method click
  @param {String|Element} target
  @return {Promise<void>}
  @public
*/
export default function click(target) {
  return nextTickPromise().then(() => {
    if (!target) {
      throw new Error('Must pass an element or selector to `click`.');
    }

    let element = getElement(target);
    if (!element) {
      throw new Error(`Element not found when calling \`click('${target}')\`.`);
    }

    __click__(element);
    return settled();
  });
}
<commit_msg>Docs: flesh out click documentation<commit_after>import getElement from './-get-element';
import fireEvent from './fire-event';
import { __focus__ } from './focus';
import settled from '../settled';
import isFocusable from './-is-focusable';
import { nextTickPromise } from '../-utils';

export function __click__(element) {
  fireEvent(element, 'mousedown');

  if (isFocusable(element)) {
    __focus__(element);
  }

  fireEvent(element, 'mouseup');
  fireEvent(element, 'click');
}

/**
  Clicks on the specified selector.

  @public
  @method click
  @param {String|Element} target the element or selector to click on
  @return {Promise<void>} resolves when the application is settled
*/
export default function click(target) {
  return nextTickPromise().then(() => {
    if (!target) {
      throw new Error('Must pass an element or selector to `click`.');
    }

    let element = getElement(target);
    if (!element) {
      throw new Error(`Element not found when calling \`click('${target}')\`.`);
    }

    __click__(element);
    return settled();
  });
}
<|endoftext|>


<commit_before>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish;
	var valueOf;
	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
	}

	this.name = "activityIndicator";
	this.tests = [
		{name: "activityIndicator", timeout: 5000},
		{name: "focusWindow", timeout:50000},
	]

	//TIMOB-6092
	this.activityIndicator = function(testRun) {
		var win = Ti.UI.createWindow({
			backgroundColor : 'red'
		});
		var style1;
		if (Ti.Platform.name === 'iPhone OS') {
			style1 = Ti.UI.iPhone.ActivityIndicatorStyle.PLAIN;
		} else {
			style1 = Ti.UI.ActivityIndicatorStyle.PLAIN;
		}
		var activityIndicator = Ti.UI.createActivityIndicator({
			color : 'red',
			font : {
				fontFamily : 'Helvetica Neue',
				fontSize : 26,
				fontWeight : 'bold'
			},
			message : 'Loading...',
			style:style1,
			top : 0,
			left : 0,
			height: Ti.UI.SIZE,
			width: Ti.UI.SIZE
		});
		win.add(activityIndicator);
		win.addEventListener('focus', function(){
			valueOf(testRun, function(){
				activityIndicator.show();
			}).shouldNotThrowException();
			valueOf(testRun, activityIndicator.color).shouldBe('red');
				activityIndicator.color = 'green';
			valueOf(testRun, activityIndicator.color).shouldBe('green');
			valueOf(testRun, activityIndicator.getTop()).shouldBe(0);
			valueOf(testRun, activityIndicator.getLeft()).shouldBe(0);
				activityIndicator.color = 'blue';
			valueOf(testRun, activityIndicator.color).shouldBe('blue');
			valueOf(testRun, function(){
				activityIndicator.hide();
			}).shouldNotThrowException();

			finish(testRun);
		});
		win.open();
	}

	//TIMOB-7024
	this.focusWindow = function(testRun) {
		var suite_complete=false;
		var win1 = Ti.UI.createWindow({
			fullscreen : false,
			backgroundColor:'red'
		});
		win1.add(Ti.UI.createLabel({
			top : '0dp',
			text : 'Win1'
		}));
		setTimeout(function(){
			var win2 = Ti.UI.createWindow({
				fullscreen : false,
				backgroundColor:'green'
			});
			win2.add(Ti.UI.createLabel({
				top : '0dp',
				text : 'Win2'
			}));
			win2.open();
			setTimeout(function(){
				suite_complete=true;
				win2.close();
			},1000);
		},3000);
		win1.addEventListener('focus', function(){
			var actInd = Ti.UI.createActivityIndicator({
				bottom : 10,
				height : 50,
				width : 10,
				message : 'Loading...'
			});
			win.add(actInd);
			valueOf(testRun,function(){
				actInd.show();
			}).shouldNotThrowException();
			valueOf(testRun, actInd.getBottom()).shouldBe(10);
			valueOf(testRun, actInd.getHeight()).shouldBe(50);
			valueOf(testRun, actInd.getWidth()).shouldBe(10);
			setTimeout(function(){
				valueOf(testRun,function(){
					actInd.hide();
				}).shouldNotThrowException();
			}, 2000);
			if(suite_complete == true)
				finish(testRun);
		});
		win1.open();
	}
}<commit_msg>win changed to win1<commit_after>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish;
	var valueOf;
	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
	}

	this.name = "activityIndicator";
	this.tests = [
		{name: "activityIndicator", timeout: 5000},
		{name: "focusWindow", timeout:50000},
	]

	//TIMOB-6092
	this.activityIndicator = function(testRun) {
		var win = Ti.UI.createWindow({
			backgroundColor : 'red'
		});
		var style1;
		if (Ti.Platform.name === 'iPhone OS') {
			style1 = Ti.UI.iPhone.ActivityIndicatorStyle.PLAIN;
		} else {
			style1 = Ti.UI.ActivityIndicatorStyle.PLAIN;
		}
		var activityIndicator = Ti.UI.createActivityIndicator({
			color : 'red',
			font : {
				fontFamily : 'Helvetica Neue',
				fontSize : 26,
				fontWeight : 'bold'
			},
			message : 'Loading...',
			style:style1,
			top : 0,
			left : 0,
			height: Ti.UI.SIZE,
			width: Ti.UI.SIZE
		});
		win.add(activityIndicator);
		win.addEventListener('focus', function(){
			valueOf(testRun, function(){
				activityIndicator.show();
			}).shouldNotThrowException();
			valueOf(testRun, activityIndicator.color).shouldBe('red');
				activityIndicator.color = 'green';
			valueOf(testRun, activityIndicator.color).shouldBe('green');
			valueOf(testRun, activityIndicator.getTop()).shouldBe(0);
			valueOf(testRun, activityIndicator.getLeft()).shouldBe(0);
				activityIndicator.color = 'blue';
			valueOf(testRun, activityIndicator.color).shouldBe('blue');
			valueOf(testRun, function(){
				activityIndicator.hide();
			}).shouldNotThrowException();

			finish(testRun);
		});
		win.open();
	}

	//TIMOB-7024
	this.focusWindow = function(testRun) {
		var suite_complete=false;
		var win1 = Ti.UI.createWindow({
			fullscreen : false,
			backgroundColor:'red'
		});
		win1.add(Ti.UI.createLabel({
			top : '0dp',
			text : 'Win1'
		}));
		setTimeout(function(){
			var win2 = Ti.UI.createWindow({
				fullscreen : false,
				backgroundColor:'green'
			});
			win2.add(Ti.UI.createLabel({
				top : '0dp',
				text : 'Win2'
			}));
			win2.open();
			setTimeout(function(){
				suite_complete=true;
				win2.close();
			},1000);
		},3000);
		win1.addEventListener('focus', function(){
			var actInd = Ti.UI.createActivityIndicator({
				bottom : 10,
				height : 50,
				width : 10,
				message : 'Loading...'
			});
			win1.add(actInd);
			valueOf(testRun,function(){
				actInd.show();
			}).shouldNotThrowException();
			valueOf(testRun, actInd.getBottom()).shouldBe(10);
			valueOf(testRun, actInd.getHeight()).shouldBe(50);
			valueOf(testRun, actInd.getWidth()).shouldBe(10);
			setTimeout(function(){
				valueOf(testRun,function(){
					actInd.hide();
				}).shouldNotThrowException();
			}, 2000);
			if(suite_complete == true)
				finish(testRun);
		});
		win1.open();
	}
}<|endoftext|>


<commit_before>(function() {
  var global;

  if (!typeof module !== 'undefined') {
    global = window;
  }

  global.japanese = require('./');

}).call(this);
<commit_msg>jshint happy<commit_after>/* jslint browser: true */

(function() {
  var global;

  if (typeof module === 'undefined') {
    global = window;
  }

  global.japanese = require('./');

}).call(this);
<|endoftext|>


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

var fs = require("fs");
var path = require("path");
var UglifyJS = require("uglify-js");

namespace("_default", function () {
	task("typeScript", ["_typescript:getCompilerFactory"], function () {
		console.log("[" + this.fullName + "]");

		var Compiler = jake.Task["_typescript:getCompilerFactory"].value;

		var compiler = new Compiler();

		return compiler.compile(["libjass.ts"]);
	});

	task("fixup", ["_default:typeScript"], function () {
		console.log("[" + this.fullName + "]");

		var compiled = jake.Task["_default:typeScript"].value;

		UglifyJS.base54.reset();

		// Parse
		var root = UglifyJS.parse(compiled.code, {
			filename: "libjass.js",
			toplevel: null
		});

		root = root.wrap_enclose(['((typeof module !== "undefined") && module.exports) || (this.libjass = {}):libjass', '((typeof global !== "undefined") && global) || this:global']);

		root.figure_out_scope({ screw_ie8: true });

		// Remove some things from the AST
		var nodesToRemove;

		nodesToRemove = [];

		// 1. All the top-level "var libjass;"
		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "libjass") {
				nodesToRemove.push({ node: node, parent: this.parent().body });
			}
		}));

		// 2. All but the first top-level "var __extends = ..."
		var firstVarExtendsFound = false;
		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "__extends") {
				if (firstVarExtendsFound === false) {
					firstVarExtendsFound = true;
					// Remove the check for this.__extends
					node.definitions[0].value = node.definitions[0].value.right;
				}
				else {
					nodesToRemove.push({ node: node, parent: this.parent().body });
				}
			}
		}));

		// Repeat because removing some declarations may make others unreferenced
		for (;;) {
			// 3. Unreferenced variable and function declarations, and unreferenced terminal function arguments
			root.walk(new UglifyJS.TreeWalker(function (node, descend) {
				if (node instanceof UglifyJS.AST_SymbolDeclaration && node.unreferenced()) {
					if (node instanceof UglifyJS.AST_SymbolFunarg) {
						if (this.parent().argnames.indexOf(node) === this.parent().argnames.length - 1) {
							nodesToRemove.push({ node: node, parent: this.parent().argnames });
						}
					}
					else if (node instanceof UglifyJS.AST_SymbolVar) {
						nodesToRemove.push({ node: this.parent(), parent: this.parent(1).definitions });
						if (this.parent(1).definitions.length === 1) {
							nodesToRemove.push({ node: this.parent(1), parent: this.parent(2).body });
						}
					}
					else if (node instanceof UglifyJS.AST_SymbolDefun) {
						nodesToRemove.push({ node: this.parent(), parent: this.parent(1).body });
					}
				}
			}));

			if (nodesToRemove.length === 0) {
				break;
			}

			nodesToRemove.forEach(function (node) {
				node.parent.splice(node.parent.indexOf(node.node), 1);
			});

			nodesToRemove = [];

			root.figure_out_scope({ screw_ie8: true });
		}

		// 4. Rename all function arguments that begin with _ to not have the _.
		// This converts the TypeScript syntax of declaring private members in the constructor declaration `function Color(private _red: number, ...)` to `function Color(red, ...)`
		// so that it matches the JSDoc (and looks nicer).
		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (
				node instanceof UglifyJS.AST_SymbolFunarg &&
				node.thedef.name[0] === "_" &&
				node.thedef.name !== "_super" // Don't rename _super (used in TypeScript's inheritance shim) to super. super is a reserved word.
			) {
				node.thedef.name = node.thedef.name.slice(1);
			}
		}));

		// Output
		var firstLicenseHeaderFound = false; // To detect and preserve the first license header

		var output = {
			source_map: UglifyJS.SourceMap({
				file: "libjass.js.map",
				orig: compiled.sourceMap,
				root: ""
			}),
			beautify: true,
			comments: function (node, comment) {
				// If this is a license header
				if (comment.value.indexOf("Copyright") !== -1) {
					if (!firstLicenseHeaderFound) {
						firstLicenseHeaderFound = true;
					}
					else {
						// This isn't the first license header. Strip it.
						return false;
					}
				}

				// If this is a TypeScript reference comment, strip it.
				if (comment.value.substr(0, "/<reference path=".length) === "/<reference path=") {
					return false;
				}

				/* Align multi-line comments correctly.
				 * TypeScript shifts them one space left, and UJS shifts them four spaces left,
				 * so shift each line except the first five spaces right.
				 */
				if (comment.type === "comment2") {
					var lines = comment.value.split("\n");
					lines = [lines[0]].concat(lines.slice(1).map(function (line) { return '     ' + line; }));
					comment.value = lines.join('\n');
				}

				return true;
			}
		};

		var stream = UglifyJS.OutputStream(output);
		root.print(stream);

		return {
			code: stream.toString() + "\n//# sourceMappingURL=libjass.js.map",
			sourceMap: output.source_map.toString()
		};
	});

	task("writeCode", ["_default:fixup"], function () {
		console.log("[" + this.fullName + "]");

		var fixedUp = jake.Task["_default:fixup"].value;

		fs.writeFileSync("libjass.js", fixedUp.code);
	});

	task("writeSourceMap", ["_default:fixup"], function () {
		console.log("[" + this.fullName + "]");

		var fixedUp = jake.Task["_default:fixup"].value;

		fs.writeFileSync("libjass.js.map", fixedUp.sourceMap);
	});

	task("minify", ["_default:fixup"], function () {
		console.log("[" + this.fullName + "]");

		var fixedUp = jake.Task["_default:fixup"].value;

		UglifyJS.base54.reset();

		// Parse
		var root = null;
		root = UglifyJS.parse(fixedUp.code, {
			filename: "libjass.js",
			toplevel: root
		});

		root.figure_out_scope({ screw_ie8: true });

		// Suppress some warnings
		var originalWarn = UglifyJS.AST_Node.warn;
		UglifyJS.AST_Node.warn = function (text, properties) {
			if (
				(text === "Couldn't figure out mapping for {file}:{line},{col} \u2192 {cline},{ccol} [{name}]" && properties.file === "libjass.js" && properties.line === 1 && properties.col === 0 && properties.cline === 1 && properties.ccol === 1)
			) {
				return;
			}

			originalWarn.call(UglifyJS.AST_Node, text, properties);
		};

		// Warnings
		root.scope_warnings({
			func_arguments: false
		});

		// Compress
		var compressor = UglifyJS.Compressor({
			warnings: true,
			screw_ie8: true
		});
		root = root.transform(compressor);

		// Mangle
		root.figure_out_scope({ screw_ie8: true });
		root.compute_char_frequency();
		root.mangle_names({ screw_ie8: true });

		// Mangle private members
		var occurrences = Object.create(null);

		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (
				node instanceof UglifyJS.AST_PropAccess &&
				typeof node.property === "string" &&
				node.property[0] === "_" && node.property[1] !== "_"
			) {
				var occurrence = occurrences[node.property];
				if (occurrence === undefined) {
					occurrences[node.property] = 1;
				}
				else {
					occurrences[node.property]++;
				}
			}
		}));

		var identifiers = Object.keys(occurrences);
		identifiers.sort(function (first, second) { return occurrences[second] - occurrences[first]; });

		var generatedIdentifiers = occurrences;

		var validIdentifierCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
		var toIdentifier = function (index) {
			var result = validIdentifierCharacters[(index % validIdentifierCharacters.length)];
			index = (index / validIdentifierCharacters.length) | 0;

			while (index > 0) {
				index--;
				result = validIdentifierCharacters[index % validIdentifierCharacters.length] + result;
				index = (index / validIdentifierCharacters.length) | 0;
			}

			return "_" + result;
		};

		identifiers.forEach(function (identifier, index) {
			generatedIdentifiers[identifier] = toIdentifier(index);
		});

		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (
				node instanceof UglifyJS.AST_PropAccess &&
				typeof node.property === "string" &&
				node.property in generatedIdentifiers
			) {
				node.property = generatedIdentifiers[node.property];
			}
		}));

		// Output
		var firstLicenseHeaderFound = false; // To detect and preserve the first license header

		var output = {
			source_map: UglifyJS.SourceMap({
				file: "libjass.min.js.map",
				orig: fixedUp.sourceMap,
				root: ""
			}),
			comments: {
				test: function (comment) {
					if (!firstLicenseHeaderFound && comment.indexOf("Copyright") !== -1) {
						firstLicenseHeaderFound = true;
						return true;
					}

					return false;
				}
			},
			screw_ie8: true
		};

		var stream = UglifyJS.OutputStream(output);
		root.print(stream);

		return {
			code: stream.toString() + "\n//# sourceMappingURL=libjass.min.js.map",
			sourceMap: output.source_map.toString()
		};
	});

	task("writeMinifiedCode", ["_default:minify"], function () {
		console.log("[" + this.fullName + "]");

		var minified = jake.Task["_default:minify"].value;

		fs.writeFileSync("libjass.min.js", minified.code);
	});

	task("writeMinifiedSourceMap", ["_default:minify"], function () {
		console.log("[" + this.fullName + "]");

		var minified = jake.Task["_default:minify"].value;

		fs.writeFileSync("libjass.min.js.map", minified.sourceMap);
	});
});
<commit_msg>Embed the source in the source maps so that source debugging is available without needing to host the source.<commit_after>/**
 * libjass
 *
 * https://github.com/Arnavion/libjass
 *
 * Copyright 2013 Arnav Singh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var fs = require("fs");
var path = require("path");
var UglifyJS = require("uglify-js");

namespace("_default", function () {
	task("typeScript", ["_typescript:getCompilerFactory"], function () {
		console.log("[" + this.fullName + "]");

		var Compiler = jake.Task["_typescript:getCompilerFactory"].value;

		var compiler = new Compiler();

		return compiler.compile(["libjass.ts"]);
	});

	task("fixup", ["_default:typeScript"], function () {
		console.log("[" + this.fullName + "]");

		var compiled = jake.Task["_default:typeScript"].value;

		UglifyJS.base54.reset();

		// Parse
		var root = UglifyJS.parse(compiled.code, {
			filename: "libjass.js",
			toplevel: null
		});

		root = root.wrap_enclose(['((typeof module !== "undefined") && module.exports) || (this.libjass = {}):libjass', '((typeof global !== "undefined") && global) || this:global']);

		root.figure_out_scope({ screw_ie8: true });

		// Remove some things from the AST
		var nodesToRemove;

		nodesToRemove = [];

		// 1. All the top-level "var libjass;"
		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "libjass") {
				nodesToRemove.push({ node: node, parent: this.parent().body });
			}
		}));

		// 2. All but the first top-level "var __extends = ..."
		var firstVarExtendsFound = false;
		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "__extends") {
				if (firstVarExtendsFound === false) {
					firstVarExtendsFound = true;
					// Remove the check for this.__extends
					node.definitions[0].value = node.definitions[0].value.right;
				}
				else {
					nodesToRemove.push({ node: node, parent: this.parent().body });
				}
			}
		}));

		// Repeat because removing some declarations may make others unreferenced
		for (;;) {
			// 3. Unreferenced variable and function declarations, and unreferenced terminal function arguments
			root.walk(new UglifyJS.TreeWalker(function (node, descend) {
				if (node instanceof UglifyJS.AST_SymbolDeclaration && node.unreferenced()) {
					if (node instanceof UglifyJS.AST_SymbolFunarg) {
						if (this.parent().argnames.indexOf(node) === this.parent().argnames.length - 1) {
							nodesToRemove.push({ node: node, parent: this.parent().argnames });
						}
					}
					else if (node instanceof UglifyJS.AST_SymbolVar) {
						nodesToRemove.push({ node: this.parent(), parent: this.parent(1).definitions });
						if (this.parent(1).definitions.length === 1) {
							nodesToRemove.push({ node: this.parent(1), parent: this.parent(2).body });
						}
					}
					else if (node instanceof UglifyJS.AST_SymbolDefun) {
						nodesToRemove.push({ node: this.parent(), parent: this.parent(1).body });
					}
				}
			}));

			if (nodesToRemove.length === 0) {
				break;
			}

			nodesToRemove.forEach(function (node) {
				node.parent.splice(node.parent.indexOf(node.node), 1);
			});

			nodesToRemove = [];

			root.figure_out_scope({ screw_ie8: true });
		}

		// 4. Rename all function arguments that begin with _ to not have the _.
		// This converts the TypeScript syntax of declaring private members in the constructor declaration `function Color(private _red: number, ...)` to `function Color(red, ...)`
		// so that it matches the JSDoc (and looks nicer).
		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (
				node instanceof UglifyJS.AST_SymbolFunarg &&
				node.thedef.name[0] === "_" &&
				node.thedef.name !== "_super" // Don't rename _super (used in TypeScript's inheritance shim) to super. super is a reserved word.
			) {
				node.thedef.name = node.thedef.name.slice(1);
			}
		}));

		// Output
		var firstLicenseHeaderFound = false; // To detect and preserve the first license header

		var output = {
			source_map: UglifyJS.SourceMap({
				file: "libjass.js.map",
				orig: compiled.sourceMap,
				root: ""
			}),
			beautify: true,
			comments: function (node, comment) {
				// If this is a license header
				if (comment.value.indexOf("Copyright") !== -1) {
					if (!firstLicenseHeaderFound) {
						firstLicenseHeaderFound = true;
					}
					else {
						// This isn't the first license header. Strip it.
						return false;
					}
				}

				// If this is a TypeScript reference comment, strip it.
				if (comment.value.substr(0, "/<reference path=".length) === "/<reference path=") {
					return false;
				}

				/* Align multi-line comments correctly.
				 * TypeScript shifts them one space left, and UJS shifts them four spaces left,
				 * so shift each line except the first five spaces right.
				 */
				if (comment.type === "comment2") {
					var lines = comment.value.split("\n");
					lines = [lines[0]].concat(lines.slice(1).map(function (line) { return '     ' + line; }));
					comment.value = lines.join('\n');
				}

				return true;
			}
		};

		fs.readdirSync('.').filter(function (filename) { return path.extname(filename) === '.ts'; }).forEach(function (filename) {
			output.source_map.get().setSourceContent(filename, fs.readFileSync(filename, { encoding: 'utf-8'}));
		});

		var stream = UglifyJS.OutputStream(output);
		root.print(stream);

		return {
			code: stream.toString() + "\n//# sourceMappingURL=libjass.js.map",
			sourceMap: output.source_map.toString()
		};
	});

	task("writeCode", ["_default:fixup"], function () {
		console.log("[" + this.fullName + "]");

		var fixedUp = jake.Task["_default:fixup"].value;

		fs.writeFileSync("libjass.js", fixedUp.code);
	});

	task("writeSourceMap", ["_default:fixup"], function () {
		console.log("[" + this.fullName + "]");

		var fixedUp = jake.Task["_default:fixup"].value;

		fs.writeFileSync("libjass.js.map", fixedUp.sourceMap);
	});

	task("minify", ["_default:fixup"], function () {
		console.log("[" + this.fullName + "]");

		var fixedUp = jake.Task["_default:fixup"].value;

		UglifyJS.base54.reset();

		// Parse
		var root = null;
		root = UglifyJS.parse(fixedUp.code, {
			filename: "libjass.js",
			toplevel: root
		});

		root.figure_out_scope({ screw_ie8: true });

		// Suppress some warnings
		var originalWarn = UglifyJS.AST_Node.warn;
		UglifyJS.AST_Node.warn = function (text, properties) {
			if (
				(text === "Couldn't figure out mapping for {file}:{line},{col} \u2192 {cline},{ccol} [{name}]" && properties.file === "libjass.js" && properties.line === 1 && properties.col === 0 && properties.cline === 1 && properties.ccol === 1)
			) {
				return;
			}

			originalWarn.call(UglifyJS.AST_Node, text, properties);
		};

		// Warnings
		root.scope_warnings({
			func_arguments: false
		});

		// Compress
		var compressor = UglifyJS.Compressor({
			warnings: true,
			screw_ie8: true
		});
		root = root.transform(compressor);

		// Mangle
		root.figure_out_scope({ screw_ie8: true });
		root.compute_char_frequency();
		root.mangle_names({ screw_ie8: true });

		// Mangle private members
		var occurrences = Object.create(null);

		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (
				node instanceof UglifyJS.AST_PropAccess &&
				typeof node.property === "string" &&
				node.property[0] === "_" && node.property[1] !== "_"
			) {
				var occurrence = occurrences[node.property];
				if (occurrence === undefined) {
					occurrences[node.property] = 1;
				}
				else {
					occurrences[node.property]++;
				}
			}
		}));

		var identifiers = Object.keys(occurrences);
		identifiers.sort(function (first, second) { return occurrences[second] - occurrences[first]; });

		var generatedIdentifiers = occurrences;

		var validIdentifierCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
		var toIdentifier = function (index) {
			var result = validIdentifierCharacters[(index % validIdentifierCharacters.length)];
			index = (index / validIdentifierCharacters.length) | 0;

			while (index > 0) {
				index--;
				result = validIdentifierCharacters[index % validIdentifierCharacters.length] + result;
				index = (index / validIdentifierCharacters.length) | 0;
			}

			return "_" + result;
		};

		identifiers.forEach(function (identifier, index) {
			generatedIdentifiers[identifier] = toIdentifier(index);
		});

		root.walk(new UglifyJS.TreeWalker(function (node, descend) {
			if (
				node instanceof UglifyJS.AST_PropAccess &&
				typeof node.property === "string" &&
				node.property in generatedIdentifiers
			) {
				node.property = generatedIdentifiers[node.property];
			}
		}));

		// Output
		var firstLicenseHeaderFound = false; // To detect and preserve the first license header

		var output = {
			source_map: UglifyJS.SourceMap({
				file: "libjass.min.js.map",
				orig: fixedUp.sourceMap,
				root: ""
			}),
			comments: {
				test: function (comment) {
					if (!firstLicenseHeaderFound && comment.indexOf("Copyright") !== -1) {
						firstLicenseHeaderFound = true;
						return true;
					}

					return false;
				}
			},
			screw_ie8: true
		};

		fs.readdirSync('.').filter(function (filename) { return path.extname(filename) === '.ts'; }).forEach(function (filename) {
			output.source_map.get().setSourceContent(filename, fs.readFileSync(filename, { encoding: 'utf-8'}));
		});

		var stream = UglifyJS.OutputStream(output);
		root.print(stream);

		return {
			code: stream.toString() + "\n//# sourceMappingURL=libjass.min.js.map",
			sourceMap: output.source_map.toString()
		};
	});

	task("writeMinifiedCode", ["_default:minify"], function () {
		console.log("[" + this.fullName + "]");

		var minified = jake.Task["_default:minify"].value;

		fs.writeFileSync("libjass.min.js", minified.code);
	});

	task("writeMinifiedSourceMap", ["_default:minify"], function () {
		console.log("[" + this.fullName + "]");

		var minified = jake.Task["_default:minify"].value;

		fs.writeFileSync("libjass.min.js.map", minified.sourceMap);
	});
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Panel, Col, Row, Button } from 'react-bootstrap';
import { VictoryBar, VictoryChart, VictoryAxis } from 'victory';
var moment = require('moment');

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom';

const moment = require('moment');

export default class RoomPage extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.match.params.roomName;
		return (

				<Row>
					<StatusPanel roomName={roomName} />
					<ButtonGroup roomName={roomName} />
				</Row>
				<Row>
					<DailyPanel roomName={roomName} />
					<WeeklyPanel roomName={roomName} />
				</Row>

		)
	}
}

class ButtonGroup extends Component {
	render() {
		return (
			<Col md={4}>
				<Link to="/reportmatch"><Button block bsSize="large">Report Match</Button></Link>
				<Link to={`/matches/${this.props.roomName}`}><Button block bsSize="large">View Match History</Button></Link>
			</Col>
		)
	}
}

class WeeklyPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.roomName;
		return (
			<Col md={6}>
				<Panel header={
Weekly Use
} style={{textAlign:"center"}}>
					<WeeklyChart roomName={roomName} />
				</Panel>
			</Col>
		)
	}
}

class WeeklyChart extends Component {
	constructor() {
		super();
		this.state = {
			data: null,
			updatedAt:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName + '/currentWeekDataPoints';
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	          data: json,
	        })
	      }).catch(e => {
	        throw e;
	      });
	  }

	render() {
		if (!this.state.data) {
			return

		}

		const updatedAt = this.state.updatedAt;

		// console.log(updatedAt);
		// updatedAt.setDay(updatedAt.getDay() - 1);
		// console.log(updatedAt);

		const formattedData = this.state.data.map((dp, index) => {
			return {
				hour: index+1,
				value: dp
			}
		});

		// console.log(formattedData);

		const ticks = [...Array(7).keys()].map(dp => dp+1);

		return (

			    <VictoryChart
			        domainPadding={20} >
			        <VictoryAxis
			          tickValues={ticks}
			          label="Days"
			          // tickFormat={["Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4"]}
			        />
			        <VictoryAxis
			          dependentAxis
			          label="% Utilization"
			        />
			        <VictoryBar
			          data={formattedData}
			          style={{ data: { fill: "#005cb3" } }}
			          x="hour"
			          y="value"
			        />
			      </VictoryChart>

		)
	}
}

class DailyPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.roomName;
		return (
			<Col md={6}>
				<Panel header={
Daily Use
} style={{textAlign:"center"}}>
					<DailyChart roomName={roomName} />
				</Panel>
			</Col>
		)
	}
}

class DailyChart extends Component {
	constructor() {
		super();
		this.state = {
			data: null,
			updatedAt:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName + '/currentDayDataPoints';
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	          data: json.data,
	          updatedAt: json.updated_at
	        })
	      }).catch(e => {
	        throw e;
	      });
	  }

	render() {
		if (!this.state.data) {
			return

		}

		const updatedAt = this.state.updatedAt;

		// console.log(updatedAt);
		// updatedAt.setDay(updatedAt.getDay() - 1);
		// console.log(updatedAt);

		const formattedData = this.state.data.map((dp, index) => {
			return {
				hour: index,
				value: dp
			}
		});

		// console.log(formattedData);

		const ticks = [...Array(4).keys()].map(dp => (dp) * 6);

		const timeTicks = this.state.data.map((dp, index) => {
			const t = moment(this.state.updatedAt).subtract(index, 'hours');
			console.log(t.calendar());
			return t.calendar();
		}).filter((dp, index) => {
			return index % 6 == 0;
		});

		return (

			    <VictoryChart
			        domainPadding={20} >
			        <VictoryAxis
			          tickValues={timeTicks}
			          label="Hours"
			          // tickFormat={["Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4"]}
			        />
			        <VictoryAxis
			          dependentAxis
			          label="% Utilization"

			        />
			        <VictoryBar
			          data={formattedData}
			          style={{ data: { fill: "#005cb3" } }}
			          x="hour"
			          y="value"
			        />
			      </VictoryChart>

		)
	}
}

class StatusPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {
			occupied: null,
			lastOpen: null,
			averageUseTime:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName;
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	        	occupied: json.occupied,
	        	lastOpen: json.lastOpen,
	        	averageUseTime: json.averageUseTime
	        });
	      }).catch(e => {
	        throw e;
	      });
	}

	render() {
		const roomName = this.props.roomName;
		console.log("this.state.occupied");
		console.log(this.state.occupied);
		if (this.state.occupied === null) {
			return

;
		}

		return (
			<Col md={8}>
				<Panel header={
{roomName}
} style={{textAlign:"center"}}>
					<Col md={4}>

						<svg>
							<circle cx={75} cy={75} r={75} fill={this.state.occupied ? "red" : "green"} />
						</svg>

					</Col>
					<Col md={8}>
						{this.state.occupied ?

OCCUPIED

Last Open: {moment(this.state.lastOpen).calendar()}

Average Use: {this.state.averageUseTime}

 :

OPEN

Last Open: {moment(this.state.lastOpen).calendar()}

Average Use: {this.state.averageUseTime}

					}
					</Col>
				</Panel>
			</Col>
		)
	}
}

<commit_msg>Bug Fix<commit_after>import React, { Component } from 'react';
import { Panel, Col, Row, Button } from 'react-bootstrap';
import { VictoryBar, VictoryChart, VictoryAxis } from 'victory';
var moment = require('moment');

import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom';

const moment = require('moment');

export default class RoomPage extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.match.params.roomName;
		return (

				<Row>
					<StatusPanel roomName={roomName} />
					<ButtonGroup roomName={roomName} />
				</Row>
				<Row>
					<DailyPanel roomName={roomName} />
					<WeeklyPanel roomName={roomName} />
				</Row>

		)
	}
}

class ButtonGroup extends Component {
	render() {
		return (
			<Col md={4}>
				<Link to="/reportmatch"><Button block bsSize="large">Report Match</Button></Link>
				<Link to={`/matches/${this.props.roomName}`}><Button block bsSize="large">View Match History</Button></Link>
			</Col>
		)
	}
}

class WeeklyPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.roomName;
		return (
			<Col md={6}>
				<Panel header={
Weekly Use
} style={{textAlign:"center"}}>
					<WeeklyChart roomName={roomName} />
				</Panel>
			</Col>
		)
	}
}

class WeeklyChart extends Component {
	constructor() {
		super();
		this.state = {
			data: null,
			updatedAt:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName + '/currentWeekDataPoints';
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	          data: json,
	        })
	      }).catch(e => {
	        throw e;
	      });
	  }

	render() {
		if (!this.state.data) {
			return

		}

		const updatedAt = this.state.updatedAt;

		// console.log(updatedAt);
		// updatedAt.setDay(updatedAt.getDay() - 1);
		// console.log(updatedAt);

		const formattedData = this.state.data.map((dp, index) => {
			return {
				hour: index+1,
				value: dp
			}
		});

		// console.log(formattedData);

		const ticks = [...Array(7).keys()].map(dp => dp+1);

		return (

			    <VictoryChart
			        domainPadding={20} >
			        <VictoryAxis
			          tickValues={ticks}
			          label="Days"
			          // tickFormat={["Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4"]}
			        />
			        <VictoryAxis
			          dependentAxis
			          label="% Utilization"
			        />
			        <VictoryBar
			          data={formattedData}
			          style={{ data: { fill: "#005cb3" } }}
			          x="hour"
			          y="value"
			        />
			      </VictoryChart>

		)
	}
}

class DailyPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {

		}
	}

	render() {
		const roomName = this.props.roomName;
		return (
			<Col md={6}>
				<Panel header={
Daily Use
} style={{textAlign:"center"}}>
					<DailyChart roomName={roomName} />
				</Panel>
			</Col>
		)
	}
}

class DailyChart extends Component {
	constructor() {
		super();
		this.state = {
			data: null,
			updatedAt:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName + '/currentDayDataPoints';
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	          data: json.data,
	          updatedAt: json.updated_at
	        })
	      }).catch(e => {
	        throw e;
	      });
	  }

	render() {
		if (!this.state.data) {
			return

		}

		const updatedAt = this.state.updatedAt;

		// console.log(updatedAt);
		// updatedAt.setDay(updatedAt.getDay() - 1);
		// console.log(updatedAt);

		const formattedData = this.state.data.map((dp, index) => {
			return {
				hour: index,
				value: dp
			}
		});

		// console.log(formattedData);

		const ticks = [...Array(4).keys()].map(dp => (dp) * 6);

		const timeTicks = this.state.data.map((dp, index) => {
			const t = moment(this.state.updatedAt).subtract(index, 'hours');
			console.log(t.fromNow());
			return t.fromNow();
		}).filter((dp, index) => {
			return index % 6 == 0;
		});

		return (

			    <VictoryChart
			        domainPadding={20} >
			        <VictoryAxis
			          tickValues={timeTicks}
			          label="Hours"
			          // tickFormat={["Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4"]}
			        />
			        <VictoryAxis
			          dependentAxis
			          label="% Utilization"

			        />
			        <VictoryBar
			          data={formattedData}
			          style={{ data: { fill: "#005cb3" } }}
			          x="hour"
			          y="value"
			        />
			      </VictoryChart>

		)
	}
}

class StatusPanel extends Component {
	constructor(props) {
		super(props)
		this.state = {
			occupied: null,
			lastOpen: null,
			averageUseTime:null
		}
	}

	componentDidMount() {
		const query = '/api/rooms/' + this.props.roomName;
	    console.log(query);
	    fetch(query)
	      .then(response => {
	        if (!response.ok) {
	          console.log('response')
	          console.log(response.status)
	          throw new Error(`status ${response.status}`);
	        }
	        return response.json();
	      }).then(json => {
	        console.log(json);
	        this.setState({
	        	occupied: json.occupied,
	        	lastOpen: json.lastOpen,
	        	averageUseTime: json.averageUseTime
	        });
	      }).catch(e => {
	        throw e;
	      });
	}

	render() {
		const roomName = this.props.roomName;
		console.log("this.state.occupied");
		console.log(this.state.occupied);
		if (this.state.occupied === null) {
			return

;
		}

		return (
			<Col md={8}>
				<Panel header={
{roomName}
} style={{textAlign:"center"}}>
					<Col md={4}>

						<svg>
							<circle cx={75} cy={75} r={75} fill={this.state.occupied ? "red" : "green"} />
						</svg>

					</Col>
					<Col md={8}>
						{this.state.occupied ?

OCCUPIED

Last Open: {moment(this.state.lastOpen).calendar()}

Average Use: {this.state.averageUseTime}

 :

OPEN

Last Open: {moment(this.state.lastOpen).calendar()}

Average Use: {this.state.averageUseTime}

					}
					</Col>
				</Panel>
			</Col>
		)
	}
}

<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "Previewer", "preview", "vfs", "tabManager", "remote.PostMessage",
        "CSSDocument", "HTMLDocument"
    ];
    main.provides = ["preview.browser"];
    return main;

    function main(options, imports, register) {
        var Previewer    = imports.Previewer;
        var tabManager   = imports.tabManager;
        var preview      = imports.preview;
        var PostMessage  = imports["remote.PostMessage"];
        var CSSDocument  = imports.CSSDocument;
        var HTMLDocument = imports.HTMLDocument;
        // var JSDocument   = imports.JSDocument;

        // var join        = require("path").join;
        // var dirname     = require("path").dirname;

        /***** Initialization *****/

        var plugin = new Previewer("Ajax.org", main.consumes, {
            caption  : "Browser",
            index    : 10,
            divider  : true,
            selector : function(path){
                return path.match(/(?:\.html|\.htm|\.xhtml)$|^https?\:\/\//);
            }
        });

        var BASEPATH = preview.previewUrl;
        var counter  = 0;

        /***** Methods *****/

        function calcRootedPath(url){
            if (url.substr(0, BASEPATH.length) == BASEPATH)
                return url.substr(BASEPATH.length);
            return url;
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
        });
        plugin.on("documentLoad", function(e){
            var doc     = e.doc;
            var session = doc.getSession();
            var tab     = doc.tab;
            var editor  = e.editor;

            if (session.iframe) return;

            var iframe = document.createElement("iframe");
            // iframe.setAttribute("nwfaketop", true);
            iframe.setAttribute("nwdisable", true);

            iframe.style.width    = "100%";
            iframe.style.height   = "100%";
            iframe.style.border   = 0;
            iframe.style.backgroundColor = "rgba(255, 255, 255, 0.88)";

            iframe.addEventListener("load", function(){
                if (!iframe.src) return;

                var path = calcRootedPath(iframe.src
                    .replace(/_c9_id=\w+\&_c9_host=.*?(?:\&|$)/, "")
                    .replace(/[\?\&]$/, ""));

                tab.title   =
                tab.tooltip = "[B] " + path;
                session.lastSrc  = iframe.src;

                if (options.local)
                    plugin.activeSession.add(iframe.contentWindow.location.href);

                editor.setLocation(path);
                tab.className.remove("loading");
            });

            session.id        = "livepreview" + counter++;
            session.iframe    = iframe;
            session.editor    = editor;
            session.transport = new PostMessage(iframe, session.id);

            session.transport.on("ready", function(){
                session.transport.getSources(function(err, sources){
                    session.styleSheets = sources.styleSheets.map(function(path){
                        return new CSSDocument(path).addTransport(session.transport);
                    });
                    // session.scripts = sources.scripts.map(function(path){
                    //     return new JSDocument(path).addTransport(session.transport);
                    // });
                    session.html = new HTMLDocument(sources.html)
                        .addTransport(session.transport);
                });
            });
            session.transport.on("focus", function(){
                tabManager.focusTab(tab);
            });

            session.addOther(function(){ session.transport.unload(); });

            editor.container.appendChild(session.iframe);
        });
        plugin.on("documentUnload", function(e){
            var doc    = e.doc;
            var iframe = doc.getSession().iframe;
            iframe.parentNode.removeChild(iframe);

            doc.tab.className.remove("loading");
        });
        plugin.on("documentActivate", function(e){
            var session = e.doc.getSession();
            var path = calcRootedPath(session.iframe.src);

            session.iframe.style.display = "block";
            session.editor.setLocation(path);
            session.editor.setButtonStyle("Browser", "page_white.png");
        });
        plugin.on("documentDeactivate", function(e){
            var session = e.doc.getSession();
            session.iframe.style.display = "none";
        });
        plugin.on("navigate", function(e){
            var tab     = plugin.activeDocument.tab;
            var session = plugin.activeSession;
            var iframe  = session.iframe;
            var url = e.url.match(/^[a-z]\w{1,4}\:\/\//)
                ? e.url
                : BASEPATH + e.url;
            session.url = url;

            tab.className.add("loading");
            iframe.src = url + (~url.indexOf("?") ? "&" : "?")
                + "_c9_id=" + session.id
                + "&_c9_host=" + (options.local ? "local" : location.origin);

            var path = calcRootedPath(url);
            tab.title   =
            tab.tooltip = "[B] " + path;
            plugin.activeSession.editor.setLocation(path);
        });
        plugin.on("update", function(e){
            // var iframe = plugin.activeSession.iframe;
            // if (e.saved)
            //     iframe.src = iframe.src;
        });
        plugin.on("reload", function(){
            var iframe = plugin.activeSession.iframe;
            var tab    = plugin.activeDocument.tab;
            tab.className.add("loading");
            iframe.src = iframe.src;
        });
        plugin.on("popout", function(){
            var src = plugin.activeSession.iframe.src;
            window.open(src);
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
        });

        /***** Register and define API *****/

        /**
         * Previewer for content that the browser can display natively.
         **/
        plugin.freezePublicAPI({

        });

        register(null, {
            "preview.browser": plugin
        });
    }
});<commit_msg>Fix back/forward button<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "Previewer", "preview", "vfs", "tabManager", "remote.PostMessage",
        "CSSDocument", "HTMLDocument"
    ];
    main.provides = ["preview.browser"];
    return main;

    function main(options, imports, register) {
        var Previewer    = imports.Previewer;
        var tabManager   = imports.tabManager;
        var preview      = imports.preview;
        var PostMessage  = imports["remote.PostMessage"];
        var CSSDocument  = imports.CSSDocument;
        var HTMLDocument = imports.HTMLDocument;
        // var JSDocument   = imports.JSDocument;

        // var join        = require("path").join;
        // var dirname     = require("path").dirname;

        options.local = true;

        /***** Initialization *****/

        var plugin = new Previewer("Ajax.org", main.consumes, {
            caption  : "Browser",
            index    : 10,
            divider  : true,
            selector : function(path){
                return path.match(/(?:\.html|\.htm|\.xhtml)$|^https?\:\/\//);
            }
        });

        var BASEPATH = preview.previewUrl;
        var counter  = 0;

        /***** Methods *****/

        function calcRootedPath(url){
            if (url.substr(0, BASEPATH.length) == BASEPATH)
                return url.substr(BASEPATH.length);
            return url;
        }

        function cleanIframeSrc(src){
            return src
                .replace(/_c9_id=\w+\&_c9_host=.*?(?:\&|$)/, "")
                .replace(/[\?\&]$/, "");
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
        });
        plugin.on("documentLoad", function(e){
            var doc     = e.doc;
            var session = doc.getSession();
            var tab     = doc.tab;
            var editor  = e.editor;

            if (session.iframe) return;

            var iframe = document.createElement("iframe");
            // iframe.setAttribute("nwfaketop", true);
            iframe.setAttribute("nwdisable", true);

            iframe.style.width    = "100%";
            iframe.style.height   = "100%";
            iframe.style.border   = 0;
            iframe.style.backgroundColor = "rgba(255, 255, 255, 0.88)";

            iframe.addEventListener("load", function(){
                if (!iframe.src) return;

                var path = calcRootedPath(cleanIframeSrc(iframe.src));

                tab.title   =
                tab.tooltip = "[B] " + path;
                session.lastSrc  = iframe.src;

                if (options.local) {
                    var url = cleanIframeSrc(iframe.contentWindow.location.href);
                    editor.setLocation(url);
                    session.currentLocation = url;
                }
                else {
                    editor.setLocation(path);
                }

                tab.className.remove("loading");
            });

            session.id        = "livepreview" + counter++;
            session.iframe    = iframe;
            session.editor    = editor;
            session.transport = new PostMessage(iframe, session.id);

            session.transport.on("ready", function(){
                session.transport.getSources(function(err, sources){
                    session.styleSheets = sources.styleSheets.map(function(path){
                        return new CSSDocument(path).addTransport(session.transport);
                    });
                    // session.scripts = sources.scripts.map(function(path){
                    //     return new JSDocument(path).addTransport(session.transport);
                    // });
                    session.html = new HTMLDocument(sources.html)
                        .addTransport(session.transport);
                });
            });
            session.transport.on("focus", function(){
                tabManager.focusTab(tab);
            });

            session.addOther(function(){ session.transport.unload(); });

            editor.container.appendChild(session.iframe);
        });
        plugin.on("documentUnload", function(e){
            var doc    = e.doc;
            var iframe = doc.getSession().iframe;
            iframe.parentNode.removeChild(iframe);

            doc.tab.className.remove("loading");
        });
        plugin.on("documentActivate", function(e){
            var session = e.doc.getSession();
            var path = calcRootedPath(session.iframe.src);

            session.iframe.style.display = "block";
            session.editor.setLocation(path, true);
            session.editor.setButtonStyle("Browser", "page_white.png");
        });
        plugin.on("documentDeactivate", function(e){
            var session = e.doc.getSession();
            session.iframe.style.display = "none";
        });
        plugin.on("navigate", function(e){
            var tab     = plugin.activeDocument.tab;
            var session = plugin.activeSession;
            var iframe  = session.iframe;
            var url = e.url.match(/^[a-z]\w{1,4}\:\/\//)
                ? e.url
                : BASEPATH + e.url;
            session.url = url;

            tab.className.add("loading");
            iframe.src = url + (~url.indexOf("?") ? "&" : "?")
                + "_c9_id=" + session.id
                + "&_c9_host=" + (options.local ? "local" : location.origin);

            var path = calcRootedPath(url);
            tab.title   =
            tab.tooltip = "[B] " + path;

            plugin.activeSession.editor.setLocation(path, true);
        });
        plugin.on("update", function(e){
            // var iframe = plugin.activeSession.iframe;
            // if (e.saved)
            //     iframe.src = iframe.src;
        });
        plugin.on("reload", function(){
            var iframe = plugin.activeSession.iframe;
            var tab    = plugin.activeDocument.tab;
            tab.className.add("loading");
            iframe.src = iframe.src;
        });
        plugin.on("popout", function(){
            var src = plugin.activeSession.iframe.src;
            window.open(src);
        });
        plugin.on("getState", function(e){
            var session = e.doc.getSession();
            var state   = e.state;

            state.currentLocation = session.currentLocation;
        });
        plugin.on("setState", function(e){
            var session = e.doc.getSession();

            if (e.state.currentLocation) {
                if (session.initPath)
                    session.initPath = e.state.currentLocation;
                // else
                //     plugin.navigate({ url: e.state.currentLocation, doc: e.doc });
            }
        });
        plugin.on("unload", function(){
        });

        /***** Register and define API *****/

        /**
         * Previewer for content that the browser can display natively.
         **/
        plugin.freezePublicAPI({

        });

        register(null, {
            "preview.browser": plugin
        });
    }
});<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash')
  , iob = require('./iob')()
  , moment = require('moment');

function init() {

  var cob = {
    name: 'cob'
    , label: 'Carbs-on-Board'
    , pluginType: 'pill-minor'
  };

  cob.setProperties = function setProperties(sbx) {
    sbx.offerProperty('cob', function setCOB ( ) {
      return cob.cobTotal(sbx.data.treatments, sbx.data.profile, sbx.time);
    });
  };

  cob.cobTotal = function cobTotal(treatments, profile, time) {

    if (!profile || !profile.hasData()) {
      console.warn('For the COB plugin to function you need a treatment profile');
      return {};
    }

    if (!profile.getSensitivity(time) || !profile.getCarbRatio(time)) {
      console.warn('For the CPB plugin to function your treatment profile must have both sens and carbratio fields');
      return {};
    }

    // Adjusted from 1 to 8 to compensate for half of the effect (in adults; much less in kids) of fixing units on the delayedCarbs term
    var liverSensRatio = 8;
    var totalCOB = 0;
    var lastCarbs = null;

    if (!treatments) {
      return {};
    }

    if (typeof time === 'undefined') {
      time = Date.now();
    }

    var isDecaying = 0;
    var lastDecayedBy = 0;

    _.each(treatments, function eachTreatment(treatment) {
      if (treatment.carbs && treatment.mills < time) {
        lastCarbs = treatment;
        var cCalc = cob.cobCalc(treatment, profile, lastDecayedBy, time);
        var decaysin_hr = (cCalc.decayedBy - time) / 1000 / 60 / 60;
        if (decaysin_hr > -10) {
          // units: BG
          var actStart = iob.calcTotal(treatments, profile, lastDecayedBy).activity;
          var actEnd = iob.calcTotal(treatments, profile, cCalc.decayedBy).activity;
          var avgActivity = (actStart + actEnd) / 2;
          // These units were wrong:
          // units: BG^2/g (?) =   BG      *      scalar    *        BG / U                           /        g / U
          //var delayedCarbs = avgActivity * liverSensRatio * profile.getSensitivity(treatment.mills) / profile.getCarbRatio(treatment.mills);
          // This is correct:
          // units:  g     =       BG      *      scalar     /          BG / U                           *     g / U
          var delayedCarbs = ( avgActivity *  liverSensRatio / profile.getSensitivity(treatment.mills) ) * profile.getCarbRatio(treatment.mills);
          var delayMinutes = Math.round(delayedCarbs / profile.getCarbAbsorptionRate(treatment.mills) * 60);
          if (delayMinutes > 0) {
            cCalc.decayedBy.setMinutes(cCalc.decayedBy.getMinutes() + delayMinutes);
            decaysin_hr = (cCalc.decayedBy - time) / 1000 / 60 / 60;
          }
        }

        if (cCalc) {
          lastDecayedBy = cCalc.decayedBy;
        }

        if (decaysin_hr > 0) {
          //console.info('Adding ' + delayMinutes + ' minutes to decay of ' + treatment.carbs + 'g bolus at ' + treatment.mills);
          totalCOB += Math.min(Number(treatment.carbs), decaysin_hr * profile.getCarbAbsorptionRate(treatment.mills));
          //console.log("cob:", Math.min(cCalc.initialCarbs, decaysin_hr * profile.getCarbAbsorptionRate(treatment.mills)),cCalc.initialCarbs,decaysin_hr,profile.getCarbAbsorptionRate(treatment.mills));
          isDecaying = cCalc.isDecaying;
        } else {
          totalCOB = 0;
        }

      }
    });

    var rawCarbImpact = isDecaying * profile.getSensitivity(time) / profile.getCarbRatio(time) * profile.getCarbAbsorptionRate(time) / 60;
    var display = Math.round(totalCOB * 10) / 10;
    return {
      decayedBy: lastDecayedBy
      , isDecaying: isDecaying
      , carbs_hr: profile.getCarbAbsorptionRate(time)
      , rawCarbImpact: rawCarbImpact
      , cob: totalCOB
      , display: display
      , displayLine: 'COB: ' + display + 'g'
      , lastCarbs: lastCarbs
    };
  };

  cob.carbImpact = function carbImpact(rawCarbImpact, insulinImpact) {
    var liverSensRatio = 1.0;
    var liverCarbImpactMax = 0.7;
    var liverCarbImpact = Math.min(liverCarbImpactMax, liverSensRatio * insulinImpact);
    //var liverCarbImpact = liverSensRatio*insulinImpact;
    var netCarbImpact = Math.max(0, rawCarbImpact - liverCarbImpact);
    var totalImpact = netCarbImpact - insulinImpact;
    return {
      netCarbImpact: netCarbImpact,
      totalImpact: totalImpact
    };
  };

  cob.cobCalc = function cobCalc(treatment, profile, lastDecayedBy, time) {

    var delay = 20;
    var isDecaying = 0;
    var initialCarbs;

    if (treatment.carbs) {
      var carbTime = new Date(treatment.mills);

      var carbs_hr = profile.getCarbAbsorptionRate(treatment.mills);
      var carbs_min = carbs_hr / 60;

      var decayedBy = new Date(carbTime);
      var minutesleft = (lastDecayedBy - carbTime) / 1000 / 60;
      decayedBy.setMinutes(decayedBy.getMinutes() + Math.max(delay, minutesleft) + treatment.carbs / carbs_min);
      if (delay > minutesleft) {
        initialCarbs = parseInt(treatment.carbs);
      }
      else {
        initialCarbs = parseInt(treatment.carbs) + minutesleft * carbs_min;
      }
      var startDecay = new Date(carbTime);
      startDecay.setMinutes(carbTime.getMinutes() + delay);
      if (time < lastDecayedBy || time > startDecay) {
        isDecaying = 1;
      }
      else {
        isDecaying = 0;
      }
      return {
        initialCarbs: initialCarbs,
        decayedBy: decayedBy,
        isDecaying: isDecaying,
        carbTime: carbTime
      };
    }
    else {
      return '';
    }
  };

  cob.updateVisualisation = function updateVisualisation(sbx) {

    var prop = sbx.properties.cob;

    if (prop === undefined || prop.cob === undefined) { return; }

    var displayCob = Math.round(prop.cob * 10) / 10;

    var info = null;
    if (prop.lastCarbs) {
      var when = moment(prop.lastCarbs.mills).format('lll');
      var amount = prop.lastCarbs.carbs + 'g';
      info = [{label: 'Last Carbs', value: amount + ' @ ' + when }];
    }

    sbx.pluginBase.updatePillText(sbx, {
      value: displayCob + 'g'
      , label: 'COB'
      , info: info
    });
  };

  return cob;

}

module.exports = init;
<commit_msg>remove commented old incorrect-units code<commit_after>'use strict';

var _ = require('lodash')
  , iob = require('./iob')()
  , moment = require('moment');

function init() {

  var cob = {
    name: 'cob'
    , label: 'Carbs-on-Board'
    , pluginType: 'pill-minor'
  };

  cob.setProperties = function setProperties(sbx) {
    sbx.offerProperty('cob', function setCOB ( ) {
      return cob.cobTotal(sbx.data.treatments, sbx.data.profile, sbx.time);
    });
  };

  cob.cobTotal = function cobTotal(treatments, profile, time) {

    if (!profile || !profile.hasData()) {
      console.warn('For the COB plugin to function you need a treatment profile');
      return {};
    }

    if (!profile.getSensitivity(time) || !profile.getCarbRatio(time)) {
      console.warn('For the CPB plugin to function your treatment profile must have both sens and carbratio fields');
      return {};
    }

    // TODO: figure out the liverSensRatio that gives the most accurate purple line predictions
    var liverSensRatio = 8;
    var totalCOB = 0;
    var lastCarbs = null;

    if (!treatments) {
      return {};
    }

    if (typeof time === 'undefined') {
      time = Date.now();
    }

    var isDecaying = 0;
    var lastDecayedBy = 0;

    _.each(treatments, function eachTreatment(treatment) {
      if (treatment.carbs && treatment.mills < time) {
        lastCarbs = treatment;
        var cCalc = cob.cobCalc(treatment, profile, lastDecayedBy, time);
        var decaysin_hr = (cCalc.decayedBy - time) / 1000 / 60 / 60;
        if (decaysin_hr > -10) {
          // units: BG
          var actStart = iob.calcTotal(treatments, profile, lastDecayedBy).activity;
          var actEnd = iob.calcTotal(treatments, profile, cCalc.decayedBy).activity;
          var avgActivity = (actStart + actEnd) / 2;
          // units:  g     =       BG      *      scalar     /          BG / U                           *     g / U
          var delayedCarbs = ( avgActivity *  liverSensRatio / profile.getSensitivity(treatment.mills) ) * profile.getCarbRatio(treatment.mills);
          var delayMinutes = Math.round(delayedCarbs / profile.getCarbAbsorptionRate(treatment.mills) * 60);
          if (delayMinutes > 0) {
            cCalc.decayedBy.setMinutes(cCalc.decayedBy.getMinutes() + delayMinutes);
            decaysin_hr = (cCalc.decayedBy - time) / 1000 / 60 / 60;
          }
        }

        if (cCalc) {
          lastDecayedBy = cCalc.decayedBy;
        }

        if (decaysin_hr > 0) {
          //console.info('Adding ' + delayMinutes + ' minutes to decay of ' + treatment.carbs + 'g bolus at ' + treatment.mills);
          totalCOB += Math.min(Number(treatment.carbs), decaysin_hr * profile.getCarbAbsorptionRate(treatment.mills));
          //console.log("cob:", Math.min(cCalc.initialCarbs, decaysin_hr * profile.getCarbAbsorptionRate(treatment.mills)),cCalc.initialCarbs,decaysin_hr,profile.getCarbAbsorptionRate(treatment.mills));
          isDecaying = cCalc.isDecaying;
        } else {
          totalCOB = 0;
        }

      }
    });

    var rawCarbImpact = isDecaying * profile.getSensitivity(time) / profile.getCarbRatio(time) * profile.getCarbAbsorptionRate(time) / 60;
    var display = Math.round(totalCOB * 10) / 10;
    return {
      decayedBy: lastDecayedBy
      , isDecaying: isDecaying
      , carbs_hr: profile.getCarbAbsorptionRate(time)
      , rawCarbImpact: rawCarbImpact
      , cob: totalCOB
      , display: display
      , displayLine: 'COB: ' + display + 'g'
      , lastCarbs: lastCarbs
    };
  };

  cob.carbImpact = function carbImpact(rawCarbImpact, insulinImpact) {
    var liverSensRatio = 1.0;
    var liverCarbImpactMax = 0.7;
    var liverCarbImpact = Math.min(liverCarbImpactMax, liverSensRatio * insulinImpact);
    //var liverCarbImpact = liverSensRatio*insulinImpact;
    var netCarbImpact = Math.max(0, rawCarbImpact - liverCarbImpact);
    var totalImpact = netCarbImpact - insulinImpact;
    return {
      netCarbImpact: netCarbImpact,
      totalImpact: totalImpact
    };
  };

  cob.cobCalc = function cobCalc(treatment, profile, lastDecayedBy, time) {

    var delay = 20;
    var isDecaying = 0;
    var initialCarbs;

    if (treatment.carbs) {
      var carbTime = new Date(treatment.mills);

      var carbs_hr = profile.getCarbAbsorptionRate(treatment.mills);
      var carbs_min = carbs_hr / 60;

      var decayedBy = new Date(carbTime);
      var minutesleft = (lastDecayedBy - carbTime) / 1000 / 60;
      decayedBy.setMinutes(decayedBy.getMinutes() + Math.max(delay, minutesleft) + treatment.carbs / carbs_min);
      if (delay > minutesleft) {
        initialCarbs = parseInt(treatment.carbs);
      }
      else {
        initialCarbs = parseInt(treatment.carbs) + minutesleft * carbs_min;
      }
      var startDecay = new Date(carbTime);
      startDecay.setMinutes(carbTime.getMinutes() + delay);
      if (time < lastDecayedBy || time > startDecay) {
        isDecaying = 1;
      }
      else {
        isDecaying = 0;
      }
      return {
        initialCarbs: initialCarbs,
        decayedBy: decayedBy,
        isDecaying: isDecaying,
        carbTime: carbTime
      };
    }
    else {
      return '';
    }
  };

  cob.updateVisualisation = function updateVisualisation(sbx) {

    var prop = sbx.properties.cob;

    if (prop === undefined || prop.cob === undefined) { return; }

    var displayCob = Math.round(prop.cob * 10) / 10;

    var info = null;
    if (prop.lastCarbs) {
      var when = moment(prop.lastCarbs.mills).format('lll');
      var amount = prop.lastCarbs.carbs + 'g';
      info = [{label: 'Last Carbs', value: amount + ' @ ' + when }];
    }

    sbx.pluginBase.updatePillText(sbx, {
      value: displayCob + 'g'
      , label: 'COB'
      , info: info
    });
  };

  return cob;

}

module.exports = init;
<|endoftext|>


<commit_before>var OSS = require('.');
OSS.co = require('co');

module.exports = OSS;
<commit_msg>add comments to browser.js<commit_after>/*
 * Export `OSS` as standalone lib which can be used in browser
 *
 * Use browserify:
 *  browserify browser.js --standalone OSS > ali-oss-sdk.js
 *
 * @example
 * <script type="text/javascript" src="ali-oss-sdk.js"></script>
 * <script type="text/javascript">
 *   var oss = new OSS(options);
 *   OSS.co(function* () {
 *     var result = oss.list({
 *       'max-keys': 10
 *     });
 *     console.log(result);
 *   }).then(function () {
 *     // pass
 *   }).catch(function (err) {
 *     console.log(err);
 *   });
 * </script>
 */

var OSS = require('.');
OSS.co = require('co');
OSS.urllib = require('urllib');

module.exports = OSS;
<|endoftext|>