<commit_before>/**
*
*	OPENTSDB: Datum
*
*
*	DESCRIPTION:
*		- Factory for individual OpenTSDB data points.
*
*
*	NOTES:
*		[1]
*
*
*	TODO:
*		[1]
*
*
*	LICENSE:
*		MIT
*
*	Copyright (c) 2014. Athan Reines.
*
*
*	AUTHOR:
*		Athan Reines. kgryte@gmail.com.
*
*/

(function() {
	'use strict';

	// MODULES //

	var // Time format validation:
		validate = require( 'opentsdb-validate-time' );

	// DATUM //

	/**
	* FUNCTION: Datum()
	*	OpenTSDB datum contructor.
	*
	* @constructor
	* @returns {Datum} Datum instance
	*/
	function Datum() {
		// Metric (required):
		this._metric = null;

		// Timestamp (required):
		this._timestamp = null;

		// Value (required):
		this._value = null;

		// Tags (optional):
		this._tags = {};

		return this;
	} // end FUNCTION Datum()

	/**
	* METHOD: metric( metric )
	*	Metric name setter and getter. If a metric is supplied, sets the metric name. If no metric is supplied, returns the metric name.
	*
	* @param {String} [metric] - metric name; e.g., 'cpu.utilization'
	* @returns {Datum|String} Datum instance or metric name
	*/
	Datum.prototype.metric = function( metric ) {
		if ( !arguments.length ) {
			return this._metric;
		}
		if ( typeof metric !== 'string' ) {
			throw new Error( 'metric()::invalid input argument. Metric name must be a string.' );
		}
		this._metric = metric;
		return this;
	}; // end METHOD metric()

	/**
	* METHOD: timestamp( value )
	*	Timestamp setter and getter. If a value is provided, sets the timestamp. If no value is provided, returns the timestamp.
	*
	* @param {String|Number} [value] - timestamp; may be either an absolute time string or a UNIX timestamp
	* @returns {Datum|Number} Datum instance or timestamp
	*/
	Datum.prototype.timestamp = function( value ) {
		if ( !arguments.length ) {
			return this._timestamp;
		}
		if ( typeof value !== 'string' && ( typeof value !== 'number' || value !== value ) ) {
			throw new Error( 'timestamp()::invalid input argument. Timestamp must be either a string or numeric.' );
		}
		if ( !validate.format( value ) ) {
			throw new Error( 'timestamp()::invalid input argument. Timestamp must be a valid time.' );
		}
		this._timestamp = value;
		return this;
	}; // end METHOD timestamp()

	/**
	* METHOD: value( value )
	*	Value setter and getter. If a value is supplied, sets the datum value. If no value is supplied, returns the datum value.
	*
	* @param {Number} [value] - datum value
	* @returns {Datum|Number} Datum instance or value
	*/
	Datum.prototype.value = function( value ) {
		if ( !arguments.length ) {
			return this._value;
		}
		if ( typeof value !== 'number' || value !== value ) {
			throw new Error( 'value()::invalid input argument. Value must be numeric.' );
		}
		this._value = value;
		return this;
	}; // end METHOD value()

	/**
	* METHOD: tags( tag, value )
	*	Tag value setter and getter. If a value is supplied, sets the tag value. If no value is supplied, gets the tag value. If the tag name has not been set, getting the tag value returns undefined. If no tag name-value pair is provided, returns all tags. NOTE: the returned object for all tags does not correspond to the internal object. Accordingly, the internal object should not be treated as mutable.
	*
	* @param {String} [tag] - tag name
	* @param {String} [value] - tag value
	* @returns {Datum|Object|String|undefined} Datum instance, all tags, or tag value
	*/
	Datum.prototype.tags = function( tag, value ) {
		var numArgs = arguments.length,
			keys = Object.keys( this._tags ),
			key,
			tags = {};
		if ( !numArgs ) {
			for ( var i = 0; i < keys.length; i++ ) {
				key = keys[ i ];
				tags[ key ] = this._tags[ key ];
			}
			return tags;
		}
		if ( typeof tag !== 'string' ) {
			throw new Error( 'tag()::invalid input argument. Tag name must be a string.' );
		}
		if ( numArgs === 1 ) {
			return this._tags[ tag ];
		}
		if ( typeof value !== 'string' ) {
			throw new Error( 'tag()::invalid input argument. Tag value must be a string.' );
		}
		this._tags[ tag ] = value;
		return this;
	}; // end METHOD tags()

	/**
	* METHOD: dtag( tag )
	*	Removes a tag.
	*
	* @param {String} tag - tag name
	* @returns {Datum} Datum instance
	*/
	Datum.prototype.dtag = function( tag ) {
		if ( !arguments.length ) {
			throw new Error( 'dtag()::insufficient input arguments. Must provide a tag name' );
		}
		if ( typeof tag !== 'string' ) {
			throw new Error( 'dtag()::invalid input argument. Tag name must be a string.' );
		}
		delete this._tags[ tag ];
		return this;
	}; // end METHOD tag()

	/**
	* METHOD: toString()
	*	Custom `toString()` method which serializes a datum. Format:
	*	"metric timestamp value tagk1=tagv1 tagk2=tagkN ... tagkN=tagvN"
	*
	* @returns {String} serialized datum
	*/
	Datum.prototype.toString = function() {
		var tags = this._tags,
			keys,
			numTags,
			key,
			buffer;

		if ( !this._metric ) {
			throw new Error( 'toString()::invalid datum. Datum must be assigned a `metric` name.' );
		}
		if ( !this._timestamp ) {
			throw new Error( 'toString()::invalid datum. Datum must be assigned a `timestamp`.' );
		}
		if ( !this._value && this._value !== 0 ) {
			throw new Error( 'toString()::invalid datum. Datum must be assigned a `value`.' );
		}
		// Count the tags:
		keys = Object.keys( tags );
		numTags = keys.length;

		if ( numTags < 1 ) {
			throw new Error( 'toString()::invalid datum. Datum must have at least one `tag`.' );
		}

		// Create a new array buffer:
		buffer = new Array( 3+numTags );
		buffer[ 0 ] = this._metric;
		buffer[ 1 ] = this._timestamp;
		buffer[ 2 ] = this._value;

		// If we have tags, process them...
		for ( var i = 0; i < numTags; i++ ) {
			key = keys[ i ];
			buffer[ i+3 ] = key + '=' + tags[ key ];
		}
		return buffer.join( ' ' );
	}; // end METHOD toString()

	// EXPORTS //

	module.exports = function newDatum(){
		return new Datum();
	};

})();<commit_msg>accept 0 unix time so that user can query from 0<commit_after>/**
*
*	OPENTSDB: Datum
*
*
*	DESCRIPTION:
*		- Factory for individual OpenTSDB data points.
*
*
*	NOTES:
*		[1]
*
*
*	TODO:
*		[1]
*
*
*	LICENSE:
*		MIT
*
*	Copyright (c) 2014. Athan Reines.
*
*
*	AUTHOR:
*		Athan Reines. kgryte@gmail.com.
*
*/

(function() {
	'use strict';

	// MODULES //

	var // Time format validation:
		validate = require( 'opentsdb-validate-time' );

	// DATUM //

	/**
	* FUNCTION: Datum()
	*	OpenTSDB datum contructor.
	*
	* @constructor
	* @returns {Datum} Datum instance
	*/
	function Datum() {
		// Metric (required):
		this._metric = null;

		// Timestamp (required):
		this._timestamp = null;

		// Value (required):
		this._value = null;

		// Tags (optional):
		this._tags = {};

		return this;
	} // end FUNCTION Datum()

	/**
	* METHOD: metric( metric )
	*	Metric name setter and getter. If a metric is supplied, sets the metric name. If no metric is supplied, returns the metric name.
	*
	* @param {String} [metric] - metric name; e.g., 'cpu.utilization'
	* @returns {Datum|String} Datum instance or metric name
	*/
	Datum.prototype.metric = function( metric ) {
		if ( !arguments.length ) {
			return this._metric;
		}
		if ( typeof metric !== 'string' ) {
			throw new Error( 'metric()::invalid input argument. Metric name must be a string.' );
		}
		this._metric = metric;
		return this;
	}; // end METHOD metric()

	/**
	* METHOD: timestamp( value )
	*	Timestamp setter and getter. If a value is provided, sets the timestamp. If no value is provided, returns the timestamp.
	*
	* @param {String|Number} [value] - timestamp; may be either an absolute time string or a UNIX timestamp
	* @returns {Datum|Number} Datum instance or timestamp
	*/
	Datum.prototype.timestamp = function( value ) {
		if ( !arguments.length ) {
			return this._timestamp;
		}
		if ( typeof value !== 'string' && ( typeof value !== 'number' || value !== value ) ) {
			throw new Error( 'timestamp()::invalid input argument. Timestamp must be either a string or numeric.' );
		}
		if ( !validate.format( value ) ) {
			throw new Error( 'timestamp()::invalid input argument. Timestamp must be a valid time.' );
		}
		this._timestamp = value;
		return this;
	}; // end METHOD timestamp()

	/**
	* METHOD: value( value )
	*	Value setter and getter. If a value is supplied, sets the datum value. If no value is supplied, returns the datum value.
	*
	* @param {Number} [value] - datum value
	* @returns {Datum|Number} Datum instance or value
	*/
	Datum.prototype.value = function( value ) {
		if ( !arguments.length ) {
			return this._value;
		}
		if ( typeof value !== 'number' || value !== value ) {
			throw new Error( 'value()::invalid input argument. Value must be numeric.' );
		}
		this._value = value;
		return this;
	}; // end METHOD value()

	/**
	* METHOD: tags( tag, value )
	*	Tag value setter and getter. If a value is supplied, sets the tag value. If no value is supplied, gets the tag value. If the tag name has not been set, getting the tag value returns undefined. If no tag name-value pair is provided, returns all tags. NOTE: the returned object for all tags does not correspond to the internal object. Accordingly, the internal object should not be treated as mutable.
	*
	* @param {String} [tag] - tag name
	* @param {String} [value] - tag value
	* @returns {Datum|Object|String|undefined} Datum instance, all tags, or tag value
	*/
	Datum.prototype.tags = function( tag, value ) {
		var numArgs = arguments.length,
			keys = Object.keys( this._tags ),
			key,
			tags = {};
		if ( !numArgs ) {
			for ( var i = 0; i < keys.length; i++ ) {
				key = keys[ i ];
				tags[ key ] = this._tags[ key ];
			}
			return tags;
		}
		if ( typeof tag !== 'string' ) {
			throw new Error( 'tag()::invalid input argument. Tag name must be a string.' );
		}
		if ( numArgs === 1 ) {
			return this._tags[ tag ];
		}
		if ( typeof value !== 'string' ) {
			throw new Error( 'tag()::invalid input argument. Tag value must be a string.' );
		}
		this._tags[ tag ] = value;
		return this;
	}; // end METHOD tags()

	/**
	* METHOD: dtag( tag )
	*	Removes a tag.
	*
	* @param {String} tag - tag name
	* @returns {Datum} Datum instance
	*/
	Datum.prototype.dtag = function( tag ) {
		if ( !arguments.length ) {
			throw new Error( 'dtag()::insufficient input arguments. Must provide a tag name' );
		}
		if ( typeof tag !== 'string' ) {
			throw new Error( 'dtag()::invalid input argument. Tag name must be a string.' );
		}
		delete this._tags[ tag ];
		return this;
	}; // end METHOD tag()

	/**
	* METHOD: toString()
	*	Custom `toString()` method which serializes a datum. Format:
	*	"metric timestamp value tagk1=tagv1 tagk2=tagkN ... tagkN=tagvN"
	*
	* @returns {String} serialized datum
	*/
	Datum.prototype.toString = function() {
		var tags = this._tags,
			keys,
			numTags,
			key,
			buffer;

		if ( !this._metric ) {
			throw new Error( 'toString()::invalid datum. Datum must be assigned a `metric` name.' );
		}
		if ( !this._timestamp && this._timestamp !== 0) {
			throw new Error( 'toString()::invalid datum. Datum must be assigned a `timestamp`.' );
		}
		if ( !this._value && this._value !== 0 ) {
			throw new Error( 'toString()::invalid datum. Datum must be assigned a `value`.' );
		}
		// Count the tags:
		keys = Object.keys( tags );
		numTags = keys.length;

		if ( numTags < 1 ) {
			throw new Error( 'toString()::invalid datum. Datum must have at least one `tag`.' );
		}

		// Create a new array buffer:
		buffer = new Array( 3+numTags );
		buffer[ 0 ] = this._metric;
		buffer[ 1 ] = this._timestamp;
		buffer[ 2 ] = this._value;

		// If we have tags, process them...
		for ( var i = 0; i < numTags; i++ ) {
			key = keys[ i ];
			buffer[ i+3 ] = key + '=' + tags[ key ];
		}
		return buffer.join( ' ' );
	}; // end METHOD toString()

	// EXPORTS //

	module.exports = function newDatum(){
		return new Datum();
	};

})();<|endoftext|>


<commit_before>/***/

process.on('message', onMessage);
process.ny = true;

function onMessage(m) {
  var cp = process;
  if(cp.ny === false)
    return onDupError();
  cp.ny = false, sender.wrap = wrap;
  wrap(function() {
    var fn = null, cached = null;
    try {
      fn = eval('(' + m.action + ')');
    } catch(e) {
      cached = e;
    }
    if(typeof fn != 'function')
      fn = require(m.action);
    if(typeof fn != 'function' && cached)
      throw cached;
    var rt = fn.apply(process, m.args.concat(sender));
    if(typeof rt != 'undefined')
      sender(rt);
  })();
  function wrap(fn) {
    return function() {
      try {
        fn();
      } catch(e) {
        sender(e);
      }
    };
  }
  function onDupError() {
    sender(new Error('Duplicated execute is not allowed.'));
  }
  function sender(args, alive, type) {
    if(args instanceof Error)
      args = args.message, alive = false, type = 'error';
    cp.send({
      type: type,
      args: args
    });
    if(alive !== true)
      cp.exit();
  }
}
<commit_msg>format<commit_after>/***/

process.on('message', onMessage);
process.ny = true;

function onMessage(m) {

  var cp = process;
  if(cp.ny === false)
    return onDupError();

  cp.ny = false, sender.wrap = wrap;
  wrap(function() {
    var fn = null, cached = null;
    try {
      fn = eval('(' + m.action + ')');
    } catch(e) {
      cached = e;
    }
    if(typeof fn != 'function')
      fn = require(m.action);
    if(typeof fn != 'function' && cached)
      throw cached;
    var rt = fn.apply(process, m.args.concat(sender));
    if(typeof rt != 'undefined')
      sender(rt);
  })();
  function wrap(fn) {
    return function() {
      try {
        fn();
      } catch(e) {
        sender(e);
      }
    };
  }
  function onDupError() {
    sender(new Error('Duplicated execute is not allowed.'));
  }

  function sender(args, alive, type) {
    if(args instanceof Error)
      args = args.message, alive = false, type = 'error';
    cp.send({
      type: type,
      args: args
    });
    if(alive !== true)
      cp.exit();
  }

}
<|endoftext|>


<commit_before>/*
 * Handles duration processing display
 *
 * It process `Contract.durations()` and display them according to
 * the current `Contract.form()` and `Contract.barriers()`
 *
 * It also populate expiry type select box i.e Durations and Endtime select
 *
 */

var Durations = (function(){
    'use strict';

    var trading_times = {};
    var selected_duration = {};
    var expiry_time = '';
    var has_end_date = 0;

    var displayDurations = function(startType) {
        var durations = Contract.durations();
        if (durations === false) {
            document.getElementById('expiry_row').style.display = 'none';
            return false;
        }

        var target = document.getElementById('duration_units'),
            formName = Contract.form(),
            barrierCategory = Contract.barrier(),
            fragment = document.createDocumentFragment(), durationContainer = {};

        while (target && target.firstChild) {
            target.removeChild(target.firstChild);
        }

        for (var key in durations) {
            if (durations.hasOwnProperty(key)) {
                for (var form in durations[key][formName]) {
                    if (durations[key][formName].hasOwnProperty(form)) {
                        var obj = {};
                        if (barrierCategory) {
                            obj = durations[key][formName][barrierCategory];
                        } else {
                            obj = durations[key][formName][form];
                        }
                        for (var type in obj) {
                            if (obj.hasOwnProperty(type)) {
                                if (startType) {
                                    if (startType === type) {
                                        if(!durationContainer.hasOwnProperty(startType)) {
                                            durationContainer[key] = obj[startType];
                                        }
                                    }
                                } else {
                                    if(!durationContainer.hasOwnProperty(type)) {
                                        durationContainer[key] = obj[type];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        var duration_list = {};
        for (var duration in durationContainer) {
            if(durationContainer.hasOwnProperty(duration)) {
                var min = durationContainer[duration]['min_contract_duration'],
                    textMapping = durationTextValueMappings(min);

                var option, content;
                if (duration === 'intraday') {
                    switch (textMapping['value']) {
                        case 's':
                            option = document.createElement('option');
                            content = document.createTextNode(textMapping['text']);
                            option.setAttribute('value', textMapping['value']);
                            option.setAttribute('data-minimum', textMapping['min']);
                            option.appendChild(content);
                            duration_list[textMapping['value']]=option;
                            option = document.createElement('option');
                            content = document.createTextNode(Content.localize().textDurationMinutes);
                            option.setAttribute('value', 'm');
                            option.setAttribute('data-minimum', 1);
                            option.setAttribute('selected', 'selected');
                            option.appendChild(content);
                            duration_list['m']=option;
                            option = document.createElement('option');
                            content = document.createTextNode(Content.localize().textDurationHours);
                            option.setAttribute('value', 'h');
                            option.setAttribute('data-minimum', 1);
                            option.appendChild(content);
                            duration_list['h']=option;
                            break;
                        case 'm':
                            option = document.createElement('option');
                            content = document.createTextNode(textMapping['text']);
                            option.setAttribute('value', textMapping['value']);
                            option.setAttribute('data-minimum', textMapping['min']);
                            option.setAttribute('selected', 'selected');
                            option.appendChild(content);
                            duration_list[textMapping['value']]=option;
                            option = document.createElement('option');
                            content = document.createTextNode(Content.localize().textDurationHours);
                            option.setAttribute('value', 'h');
                            option.setAttribute('data-minimum', 1);
                            option.appendChild(content);
                            duration_list['h']=option;
                            break;
                        case 'h':
                            option = document.createElement('option');
                            content = document.createTextNode(textMapping['text']);
                            option.setAttribute('value', textMapping['value']);
                            option.setAttribute('data-minimum', textMapping['min']);
                            option.appendChild(content);
                            duration_list[textMapping['value']]=option;
                            break;
                        default :
                            option = document.createElement('option');
                            content = document.createTextNode(textMapping['text']);
                            option.setAttribute('value', textMapping['value']);
                            option.setAttribute('data-minimum', textMapping['min']);
                            option.appendChild(content);
                            duration_list[textMapping['value']]=option;
                            break;
                    }
                } else if (duration === 'daily') {
                    option = document.createElement('option');
                    content = document.createTextNode(textMapping['text']);
                    option.setAttribute('value', textMapping['value']);
                    option.setAttribute('data-minimum', textMapping['min']);
                    option.appendChild(content);
                    duration_list[textMapping['value']]=option;
                } else if (duration === 'tick') {
                    option = document.createElement('option');
                    content = document.createTextNode(textMapping['text']);
                    option.setAttribute('value', textMapping['value']);
                    option.setAttribute('data-minimum', textMapping['min']);
                    option.appendChild(content);
                    duration_list[textMapping['value']]=option;
                }
            }
        }
        var list = Object.keys(duration_list).sort(function(a,b){
            if(durationOrder(a)>durationOrder(b)){
                return 1;
            }
            else{
                return -1;
            }
        });
        has_end_date = 0;
        for(var k=0; k<list.length; k++){
            var d = list[k];
            if(d!=='t'){
                has_end_date = 1;
            }
            if(duration_list.hasOwnProperty(d)){
                target.appendChild(duration_list[d]);
            }
        }

        if(selected_duration.unit){
            if(!selectOption(selected_duration.unit,target)){
                selected_duration = {};
            }
        }

        durationPopulate();
    };

    var displayEndTime = function(){
        var current_moment = moment().add(5, 'minutes').utc();
        document.getElementById('expiry_date').value = current_moment.format('YYYY-MM-DD');
        document.getElementById('expiry_time').value = current_moment.format('HH:mm');
        Durations.setTime(current_moment.format('HH:mm'));

        durationPopulate();
    }

    var durationTextValueMappings = function(str) {
        var mapping = {
            s : Content.localize().textDurationSeconds,
            m : Content.localize().textDurationMinutes,
            h : Content.localize().textDurationHours,
            d : Content.localize().textDurationDays,
            t : Content.localize().textDurationTicks
        };

        var arry = str ? str.toString().match(/[a-zA-Z]+|[0-9]+/g) : [],
            obj = {};

        if (arry.length > 1) {
            obj['value'] = arry[1];
            obj['text'] = mapping[arry[1]];
            obj['min'] = arry[0];
        } else {
            obj['value'] = 't';
            obj['text'] = mapping['t'];
            obj['min'] = arry[0];
        }

        return obj;
    };

    var durationPopulate = function() {
        var unit = document.getElementById('duration_units');
        if (isVisible(unit)) {
            var unitValue = unit.options[unit.selectedIndex].getAttribute('data-minimum');
            document.getElementById('duration_minimum').textContent = unitValue;
            if(selected_duration.amount && selected_duration.unit > unitValue){
                unitValue = selected_duration.amount;
            }
            document.getElementById('duration_amount').value = unitValue;
            displayExpiryType(unit.value);
        } else {
            displayExpiryType();
        }

        // jquery for datepicker
        var amountElement = $('#duration_amount');
        if (unit.value === 'd') {
            var tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);

            amountElement.datepicker({
                minDate: tomorrow,
                onSelect: function() {
                    var date = $(this).datepicker('getDate');
                    var today = new Date();
                    var dayDiff = Math.ceil((date - today) / (1000 * 60 * 60 * 24));
                    amountElement.val(dayDiff);
                    amountElement.trigger('change');
                }
            });
        } else {
            amountElement.datepicker("destroy");
        }

        // we need to call it here as for days we need to show absolute barriers
        Barriers.display();
    };

    var displayExpiryType = function(unit) {
        var target = document.getElementById('expiry_type'),
            fragment = document.createDocumentFragment();

        var current_selected = target.value || 'duration',
            id = current_selected,
            hideId = (current_selected === 'duration') ? 'endtime' : 'duration';

        id = document.getElementById('expiry_type_' + id);
        if (id) {
            id.style.display = 'flex';
        }
        // need to hide the non selected one
        hideId = document.getElementById('expiry_type_' + hideId);
        if (hideId) {
            hideId.style.display = 'none';
        }

        while (target && target.firstChild) {
            target.removeChild(target.firstChild);
        }

        var option = document.createElement('option'),
            content = document.createTextNode(Content.localize().textDuration);

        option.setAttribute('value', 'duration');
        if (current_selected === 'duration') {
            option.setAttribute('selected', 'selected');
        }
        option.appendChild(content);
        fragment.appendChild(option);

        if (has_end_date) {
            option = document.createElement('option');
            content = document.createTextNode(Content.localize().textEndTime);
            option.setAttribute('value', 'endtime');
            if (current_selected === 'endtime') {
                option.setAttribute('selected', 'selected');
            }
            option.appendChild(content);
            fragment.appendChild(option);
        }
        target.appendChild(fragment);
    };

    var processTradingTimesAnswer = function(response){
        if(!trading_times.hasOwnProperty(response.echo_req.trading_times) && response.hasOwnProperty('trading_times') && response.trading_times.hasOwnProperty('markets')){
            for(var i=0; i<response.trading_times.markets.length; i++){
                var submarkets = response.trading_times.markets[i].submarkets;
                if(submarkets){
                    for(var j=0; j<submarkets.length; j++){
                        var symbols = submarkets[j].symbols;
                        if(symbols){
                            for(var k=0; k<symbols.length; k++){
                                var symbol = symbols[k];
                                if(!trading_times[response.echo_req.trading_times]){
                                    trading_times[response.echo_req.trading_times] = {};
                                }
                                trading_times[response.echo_req.trading_times][symbol.symbol] = symbol.times.close;
                            }
                        }
                    }
                }
            }
        }
    };

    return {
        display: displayDurations,
        displayEndTime: displayEndTime,
        populate: durationPopulate,
        setTime: function(time){ expiry_time = time; },
        getTime: function(){ return expiry_time; },
        processTradingTimesAnswer: processTradingTimesAnswer,
        trading_times: function(){ return trading_times; },
        select_amount: function(a){ selected_duration.amount = a; },
        select_unit: function(u){ selected_duration.unit = u; }
    };
})();

<commit_msg>fix tests<commit_after>/*
 * Handles duration processing display
 *
 * It process `Contract.durations()` and display them according to
 * the current `Contract.form()` and `Contract.barriers()`
 *
 * It also populate expiry type select box i.e Durations and Endtime select
 *
 */

var Durations = (function(){
    'use strict';

    var trading_times = {};
    var selected_duration = {};
    var expiry_time = '';
    var has_end_date = 0;

    var displayDurations = function(startType) {
        var durations = Contract.durations();
        if (durations === false) {
            document.getElementById('expiry_row').style.display = 'none';
            return false;
        }

        var target = document.getElementById('duration_units'),
            formName = Contract.form(),
            barrierCategory = Contract.barrier(),
            fragment = document.createDocumentFragment(), durationContainer = {};

        while (target && target.firstChild) {
            target.removeChild(target.firstChild);
        }

        for (var key in durations) {
            if (durations.hasOwnProperty(key)) {
                for (var form in durations[key][formName]) {
                    if (durations[key][formName].hasOwnProperty(form)) {
                        var obj = {};
                        if (barrierCategory) {
                            obj = durations[key][formName][barrierCategory];
                        } else {
                            obj = durations[key][formName][form];
                        }
                        for (var type in obj) {
                            if (obj.hasOwnProperty(type)) {
                                if (startType) {
                                    if (startType === type) {
                                        if(!durationContainer.hasOwnProperty(startType)) {
                                            durationContainer[key] = obj[startType];
                                        }
                                    }
                                } else {
                                    if(!durationContainer.hasOwnProperty(type)) {
                                        durationContainer[key] = obj[type];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        var duration_list = {};
        for (var duration in durationContainer) {
            if(durationContainer.hasOwnProperty(duration)) {
                var min = durationContainer[duration]['min_contract_duration'],
                    textMapping = durationTextValueMappings(min);

                var option, content;
                if (duration === 'intraday') {
                    switch (textMapping['value']) {
                        case 's':
                            option = document.createElement('option');
                            content = document.createTextNode(textMapping['text']);
                            option.setAttribute('value', textMapping['value']);
                            option.setAttribute('data-minimum', textMapping['min']);
                            option.appendChild(content);
                            duration_list[textMapping['value']]=option;
                            option = document.createElement('option');
                            content = document.createTextNode(Content.localize().textDurationMinutes);
                            option.setAttribute('value', 'm');
                            option.setAttribute('data-minimum', 1);
                            option.setAttribute('selected', 'selected');
                            option.appendChild(content);
                            duration_list['m']=option;
                            option = document.createElement('option');
                            content = document.createTextNode(Content.localize().textDurationHours);
                            option.setAttribute('value', 'h');
                            option.setAttribute('data-minimum', 1);
                            option.appendChild(content);
                            duration_list['h']=option;
                            break;
                        case 'm':
                            option = document.createElement('option');
                            content = document.createTextNode(textMapping['text']);
                            option.setAttribute('value', textMapping['value']);
                            option.setAttribute('data-minimum', textMapping['min']);
                            option.setAttribute('selected', 'selected');
                            option.appendChild(content);
                            duration_list[textMapping['value']]=option;
                            option = document.createElement('option');
                            content = document.createTextNode(Content.localize().textDurationHours);
                            option.setAttribute('value', 'h');
                            option.setAttribute('data-minimum', 1);
                            option.appendChild(content);
                            duration_list['h']=option;
                            break;
                        case 'h':
                            option = document.createElement('option');
                            content = document.createTextNode(textMapping['text']);
                            option.setAttribute('value', textMapping['value']);
                            option.setAttribute('data-minimum', textMapping['min']);
                            option.appendChild(content);
                            duration_list[textMapping['value']]=option;
                            break;
                        default :
                            option = document.createElement('option');
                            content = document.createTextNode(textMapping['text']);
                            option.setAttribute('value', textMapping['value']);
                            option.setAttribute('data-minimum', textMapping['min']);
                            option.appendChild(content);
                            duration_list[textMapping['value']]=option;
                            break;
                    }
                } else if (duration === 'daily') {
                    option = document.createElement('option');
                    content = document.createTextNode(textMapping['text']);
                    option.setAttribute('value', textMapping['value']);
                    option.setAttribute('data-minimum', textMapping['min']);
                    option.appendChild(content);
                    duration_list[textMapping['value']]=option;
                } else if (duration === 'tick') {
                    option = document.createElement('option');
                    content = document.createTextNode(textMapping['text']);
                    option.setAttribute('value', textMapping['value']);
                    option.setAttribute('data-minimum', textMapping['min']);
                    option.appendChild(content);
                    duration_list[textMapping['value']]=option;
                }
            }
        }
        var list = Object.keys(duration_list).sort(function(a,b){
            if(durationOrder(a)>durationOrder(b)){
                return 1;
            }
            else{
                return -1;
            }
        });
        has_end_date = 0;
        for(var k=0; k<list.length; k++){
            var d = list[k];
            if(d!=='t'){
                has_end_date = 1;
            }
            if(duration_list.hasOwnProperty(d)){
                target.appendChild(duration_list[d]);
            }
        }

        if(selected_duration.unit){
            if(!selectOption(selected_duration.unit,target)){
                selected_duration = {};
            }
        }

        durationPopulate();
    };

    var displayEndTime = function(){
        var current_moment = moment().add(5, 'minutes').utc();
        document.getElementById('expiry_date').value = current_moment.format('YYYY-MM-DD');
        document.getElementById('expiry_time').value = current_moment.format('HH:mm');
        Durations.setTime(current_moment.format('HH:mm'));

        durationPopulate();
    };

    var durationTextValueMappings = function(str) {
        var mapping = {
            s : Content.localize().textDurationSeconds,
            m : Content.localize().textDurationMinutes,
            h : Content.localize().textDurationHours,
            d : Content.localize().textDurationDays,
            t : Content.localize().textDurationTicks
        };

        var arry = str ? str.toString().match(/[a-zA-Z]+|[0-9]+/g) : [],
            obj = {};

        if (arry.length > 1) {
            obj['value'] = arry[1];
            obj['text'] = mapping[arry[1]];
            obj['min'] = arry[0];
        } else {
            obj['value'] = 't';
            obj['text'] = mapping['t'];
            obj['min'] = arry[0];
        }

        return obj;
    };

    var durationPopulate = function() {
        var unit = document.getElementById('duration_units');
        if (isVisible(unit)) {
            var unitValue = unit.options[unit.selectedIndex].getAttribute('data-minimum');
            document.getElementById('duration_minimum').textContent = unitValue;
            if(selected_duration.amount && selected_duration.unit > unitValue){
                unitValue = selected_duration.amount;
            }
            document.getElementById('duration_amount').value = unitValue;
            displayExpiryType(unit.value);
        } else {
            displayExpiryType();
        }

        // jquery for datepicker
        var amountElement = $('#duration_amount');
        if (unit.value === 'd') {
            var tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);

            amountElement.datepicker({
                minDate: tomorrow,
                onSelect: function() {
                    var date = $(this).datepicker('getDate');
                    var today = new Date();
                    var dayDiff = Math.ceil((date - today) / (1000 * 60 * 60 * 24));
                    amountElement.val(dayDiff);
                    amountElement.trigger('change');
                }
            });
        } else {
            amountElement.datepicker("destroy");
        }

        // we need to call it here as for days we need to show absolute barriers
        Barriers.display();
    };

    var displayExpiryType = function(unit) {
        var target = document.getElementById('expiry_type'),
            fragment = document.createDocumentFragment();

        var current_selected = target.value || 'duration',
            id = current_selected,
            hideId = (current_selected === 'duration') ? 'endtime' : 'duration';

        id = document.getElementById('expiry_type_' + id);
        if (id) {
            id.style.display = 'flex';
        }
        // need to hide the non selected one
        hideId = document.getElementById('expiry_type_' + hideId);
        if (hideId) {
            hideId.style.display = 'none';
        }

        while (target && target.firstChild) {
            target.removeChild(target.firstChild);
        }

        var option = document.createElement('option'),
            content = document.createTextNode(Content.localize().textDuration);

        option.setAttribute('value', 'duration');
        if (current_selected === 'duration') {
            option.setAttribute('selected', 'selected');
        }
        option.appendChild(content);
        fragment.appendChild(option);

        if (has_end_date) {
            option = document.createElement('option');
            content = document.createTextNode(Content.localize().textEndTime);
            option.setAttribute('value', 'endtime');
            if (current_selected === 'endtime') {
                option.setAttribute('selected', 'selected');
            }
            option.appendChild(content);
            fragment.appendChild(option);
        }
        target.appendChild(fragment);
    };

    var processTradingTimesAnswer = function(response){
        if(!trading_times.hasOwnProperty(response.echo_req.trading_times) && response.hasOwnProperty('trading_times') && response.trading_times.hasOwnProperty('markets')){
            for(var i=0; i<response.trading_times.markets.length; i++){
                var submarkets = response.trading_times.markets[i].submarkets;
                if(submarkets){
                    for(var j=0; j<submarkets.length; j++){
                        var symbols = submarkets[j].symbols;
                        if(symbols){
                            for(var k=0; k<symbols.length; k++){
                                var symbol = symbols[k];
                                if(!trading_times[response.echo_req.trading_times]){
                                    trading_times[response.echo_req.trading_times] = {};
                                }
                                trading_times[response.echo_req.trading_times][symbol.symbol] = symbol.times.close;
                            }
                        }
                    }
                }
            }
        }
    };

    return {
        display: displayDurations,
        displayEndTime: displayEndTime,
        populate: durationPopulate,
        setTime: function(time){ expiry_time = time; },
        getTime: function(){ return expiry_time; },
        processTradingTimesAnswer: processTradingTimesAnswer,
        trading_times: function(){ return trading_times; },
        select_amount: function(a){ selected_duration.amount = a; },
        select_unit: function(u){ selected_duration.unit = u; }
    };
})();

<|endoftext|>


<commit_before>/*jslint node: true*/
require('string.prototype.codepointat');
var toArray = require('lodash.toarray');

"use strict";

/**
 * regex to parse emoji in a string - finds emoji, e.g. :coffee:
 */
var parser = /:([a-zA-Z0-9_\-\+]+):/g;

/**
 * Removes colons on either side
 * of the string if present
 * @param  {string} str
 * @return {string}
 */
var trim = function(str) {
  var colonIndex = str.indexOf(':');
  if (colonIndex > -1) {
    // :emoji: (http://www.emoji-cheat-sheet.com/)
    if (colonIndex === str.length - 1) {
      str = str.substring(0, colonIndex);
      return trim(str);
    } else {
      str = str.substr(colonIndex + 1);
      return trim(str);
    }
  }
  return str;
}

/**
 * Adds colons to either side
 * of the string
 * @param {string} str
 * @return {string}
 */
var wrapColons = function(str) {
  return (str && str.length > 0) ? ':' + str + ':' : '';
}

var NON_SPACING_MARK = String.fromCharCode(65039); // 65039 - '' - 0xFE0F;

/**
 * Emoji namespace
 */
var Emoji = module.exports = {
  emoji: require('./emoji.json')
};

/**
 * get emoji code from name
 * @param  {string} emoji
 * @return {string}
 */
Emoji._get = function _get(emoji) {
  if (Emoji.emoji.hasOwnProperty(emoji)) {
    return Emoji.emoji[emoji];
  }
  return ':' + emoji + ':';
};

/**
 * get emoji code from :emoji: string or name
 * @param  {string} emoji
 * @return {string}
 */
Emoji.get = function get(emoji) {
  emoji = trim(emoji);

  return Emoji._get(emoji);
};

/**
 * get emoji name from code
 * @param  {string} emoji
 * @param  {boolean} includeColons should the result include the ::
 * @return {string}
 */
Emoji.which = function which(emoji_code, includeColons) {
  var word = emojiToCode[emoji_code];
  if (word) {
    return includeColons ? wrapColons(word) : word;
  }

  // Most of the times, the word is already returned by now. Sometimes
  // we need to handle the non-spacing-mark. If we haven't returned yet,
  // we're going to try the oposite version, with or without the mark.
  var endsWithMark = emoji_code[emoji_code.length - 1] === NON_SPACING_MARK;
  var alias = endsWithMark
    ? emoji_code.substr(0, emoji_code.length - 1)
    : emoji_code + NON_SPACING_MARK;

  word = emojiToCode[alias];

  return includeColons ? wrapColons(word) : word;
};

/**
 * emojify a string (replace :emoji: with an emoji)
 * @param  {string} str
 * @param  {function} on_missing (gets emoji name without :: and returns a proper emoji if no emoji was found)
 * @param  {function} format (wrap the returned emoji in a custom element)
 * @return {string}
 */
Emoji.emojify = function emojify(str, on_missing, format) {
  if (!str) return '';

  return str.split(parser) // parse emoji via regex
            .map(function parseEmoji(s, i) {
              // every second element is an emoji, e.g. "test :fast_forward:" -> [ "test ", "fast_forward" ]
              if (i % 2 === 0) return s;
              var emoji = Emoji._get(s);

              if (emoji.indexOf(':') > -1 && typeof on_missing === 'function') {
                return on_missing(emoji.substr(1, emoji.length-2));
              }

              if (typeof format === 'function') {
                return format(emoji, s);
              }

              return emoji;
            })
            .join('') // convert back to string
  ;
};

/**
 * return a random emoji
 * @return {string}
 */
Emoji.random = function random() {
  var emojiKeys = Object.keys(Emoji.emoji);
  var randomIndex = Math.floor(Math.random() * emojiKeys.length);
  var key = emojiKeys[randomIndex];
  var emoji = Emoji._get(key);
  return {key: key, emoji: emoji};
}

/**
 *  return an collection of potential emoji matches
 *  @param {string} str
 *  @return {Array.<Object>}
 */
Emoji.search = function search(str) {
  var emojiKeys = Object.keys(Emoji.emoji);
  var matcher = trim(str)
  var matchingKeys = emojiKeys.filter(function(key) {
    return key.toString().indexOf(matcher) === 0;
  });
  return matchingKeys.map(function(key) {
    return {
      key: key,
      emoji: Emoji._get(key),
    };
  });
}

var emojiToCode = Object.keys(Emoji.emoji).reduce(function(h,k) {
  return h[Emoji.emoji[k]] = k, h;
}, {});

/**
 * unemojify a string (replace emoji with :emoji:)
 * @param  {string} str
 * @return {string}
 */
Emoji.unemojify = function unemojify(str) {
  if (!str) return '';
  var words = toArray(str);

  return words.map(function(word) {
    var emoji_text = emojiToCode[word];
    if (emoji_text) {
      return ':'+emoji_text+':';
    }
    return word;
  }).join('');
};
<commit_msg>Use Emoji.which to dedupe code, and fix the flag bug<commit_after>/*jslint node: true*/
require('string.prototype.codepointat');
var toArray = require('lodash.toarray');

"use strict";

/**
 * regex to parse emoji in a string - finds emoji, e.g. :coffee:
 */
var parser = /:([a-zA-Z0-9_\-\+]+):/g;

/**
 * Removes colons on either side
 * of the string if present
 * @param  {string} str
 * @return {string}
 */
var trim = function(str) {
  var colonIndex = str.indexOf(':');
  if (colonIndex > -1) {
    // :emoji: (http://www.emoji-cheat-sheet.com/)
    if (colonIndex === str.length - 1) {
      str = str.substring(0, colonIndex);
      return trim(str);
    } else {
      str = str.substr(colonIndex + 1);
      return trim(str);
    }
  }
  return str;
}

/**
 * Adds colons to either side
 * of the string
 * @param {string} str
 * @return {string}
 */
var wrapColons = function(str) {
  return (str && str.length > 0) ? ':' + str + ':' : '';
}

var NON_SPACING_MARK = String.fromCharCode(65039); // 65039 - '' - 0xFE0F;

/**
 * Emoji namespace
 */
var Emoji = module.exports = {
  emoji: require('./emoji.json')
};

/**
 * get emoji code from name
 * @param  {string} emoji
 * @return {string}
 */
Emoji._get = function _get(emoji) {
  if (Emoji.emoji.hasOwnProperty(emoji)) {
    return Emoji.emoji[emoji];
  }
  return ':' + emoji + ':';
};

/**
 * get emoji code from :emoji: string or name
 * @param  {string} emoji
 * @return {string}
 */
Emoji.get = function get(emoji) {
  emoji = trim(emoji);

  return Emoji._get(emoji);
};

/**
 * get emoji name from code
 * @param  {string} emoji
 * @param  {boolean} includeColons should the result include the ::
 * @return {string}
 */
Emoji.which = function which(emoji_code, includeColons) {
  var word = emojiToCode[emoji_code];
  if (word) {
    return includeColons ? wrapColons(word) : word;
  }

  // Most of the times, the word is already returned by now. Sometimes
  // we need to handle the non-spacing-mark. If we haven't returned yet,
  // we're going to try the oposite version, with or without the mark.
  var endsWithMark = emoji_code[emoji_code.length - 1] === NON_SPACING_MARK;
  var alias = endsWithMark
    ? emoji_code.substr(0, emoji_code.length - 1)
    : emoji_code + NON_SPACING_MARK;

  word = emojiToCode[alias];

  return includeColons ? wrapColons(word) : word;
};

/**
 * emojify a string (replace :emoji: with an emoji)
 * @param  {string} str
 * @param  {function} on_missing (gets emoji name without :: and returns a proper emoji if no emoji was found)
 * @param  {function} format (wrap the returned emoji in a custom element)
 * @return {string}
 */
Emoji.emojify = function emojify(str, on_missing, format) {
  if (!str) return '';

  return str.split(parser) // parse emoji via regex
            .map(function parseEmoji(s, i) {
              // every second element is an emoji, e.g. "test :fast_forward:" -> [ "test ", "fast_forward" ]
              if (i % 2 === 0) return s;
              var emoji = Emoji._get(s);

              if (emoji.indexOf(':') > -1 && typeof on_missing === 'function') {
                return on_missing(emoji.substr(1, emoji.length-2));
              }

              if (typeof format === 'function') {
                return format(emoji, s);
              }

              return emoji;
            })
            .join('') // convert back to string
  ;
};

/**
 * return a random emoji
 * @return {string}
 */
Emoji.random = function random() {
  var emojiKeys = Object.keys(Emoji.emoji);
  var randomIndex = Math.floor(Math.random() * emojiKeys.length);
  var key = emojiKeys[randomIndex];
  var emoji = Emoji._get(key);
  return {key: key, emoji: emoji};
}

/**
 *  return an collection of potential emoji matches
 *  @param {string} str
 *  @return {Array.<Object>}
 */
Emoji.search = function search(str) {
  var emojiKeys = Object.keys(Emoji.emoji);
  var matcher = trim(str)
  var matchingKeys = emojiKeys.filter(function(key) {
    return key.toString().indexOf(matcher) === 0;
  });
  return matchingKeys.map(function(key) {
    return {
      key: key,
      emoji: Emoji._get(key),
    };
  });
}

var emojiToCode = Object.keys(Emoji.emoji).reduce(function(h,k) {
  return h[Emoji.emoji[k]] = k, h;
}, {});

/**
 * unemojify a string (replace emoji with :emoji:)
 * @param  {string} str
 * @return {string}
 */
Emoji.unemojify = function unemojify(str) {
  if (!str) return '';
  var words = toArray(str);

  return words.map(function(word) {
    return Emoji.which(word, true) || word;
  }).join('');
};
<|endoftext|>


<commit_before>const auth = require('@feathersjs/authentication');
const hooks = require('feathers-hooks-common');
const globalHooks = require('../../../hooks');
const lookupSchool = require('./lookupSchool');

module.exports = {
	before: {
		all: [
			globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')),
			globalHooks.ifNotLocal(globalHooks.restrictToCurrentSchool),
			lookupSchool,
		],
		find: [],
		create: [
			globalHooks.ifNotLocal(globalHooks.hasPermission('SCHOOL_EDIT')),
		],
		update: [hooks.disable()],
		get: [hooks.disallow()],
		patch: [hooks.disallow()],
		remove: [hooks.disallow()],
	},
};
<commit_msg>Use disallow instead of disable<commit_after>const auth = require('@feathersjs/authentication');
const hooks = require('feathers-hooks-common');
const globalHooks = require('../../../hooks');
const lookupSchool = require('./lookupSchool');

module.exports = {
	before: {
		all: [
			globalHooks.ifNotLocal(auth.hooks.authenticate('jwt')),
			globalHooks.ifNotLocal(globalHooks.restrictToCurrentSchool),
			lookupSchool,
		],
		find: [],
		create: [
			globalHooks.ifNotLocal(globalHooks.hasPermission('SCHOOL_EDIT')),
		],
		update: [hooks.disallow()],
		get: [hooks.disallow()],
		patch: [hooks.disallow()],
		remove: [hooks.disallow()],
	},
};
<|endoftext|>


<commit_before>const path = require("path");
const express = require("express");
const morgan = require("morgan");
const expressStaticGzip = require("express-static-gzip");

const staticDir = path.join(__dirname, "dist");

const ENVs = [
  "IRENE_API_HOST",
  "IRENE_DEVICEFARM_HOST",
  "IRENE_API_SOCKET_PATH",
  "IRENE_ENABLE_REGISTRATION",
  "IRENE_REGISTRATION_LINK",
  "IRENE_SHOW_LICENSE",
  "IRENE_CRISP_WEBSITE_ID",
  "IRENE_ENABLE_HOTJAR",
  "IRENE_ENABLE_PENDO",
  "IRENE_ENABLE_CSB",
  "IRENE_ENABLE_MARKETPLACE",
  "IRENE_ENABLE_ROLLBAR",
  "ENTERPRISE",
  "WHITELABEL_ENABLED",
  "WHITELABEL_NAME",
  "WHITELABEL_LOGO",
  "WHITELABEL_THEME",
];

const app = express();
function getRuntimeConfig() {
  const content = {};
  for (const env of ENVs) {
    const value = process.env[env];
    if (value) {
      content[env] = value;
    }
  }
  return JSON.stringify(content);
}
app.use(morgan("tiny"));
app.get("/runtimeconfig.js", function (req, res) {
  const config = `var runtimeGlobalConfig=${getRuntimeConfig()};`;
  res.send(config);
});
app.use(
  expressStaticGzip(staticDir, {
    serveStatic: {
      index: ["index.html"],
    },
  })
);
app.use(function (req, res) { // lgtm [js/missing-rate-limiting]
  res.sendFile(path.join(staticDir, "index.html"));
});
app.listen(4200, function () {
  console.log("server listening on port " + 4200);
});
<commit_msg>Added FAVICON env in static server<commit_after>const path = require("path");
const express = require("express");
const morgan = require("morgan");
const expressStaticGzip = require("express-static-gzip");

const staticDir = path.join(__dirname, "dist");

const ENVs = [
  "IRENE_API_HOST",
  "IRENE_DEVICEFARM_HOST",
  "IRENE_API_SOCKET_PATH",
  "IRENE_ENABLE_REGISTRATION",
  "IRENE_REGISTRATION_LINK",
  "IRENE_SHOW_LICENSE",
  "IRENE_CRISP_WEBSITE_ID",
  "IRENE_ENABLE_HOTJAR",
  "IRENE_ENABLE_PENDO",
  "IRENE_ENABLE_CSB",
  "IRENE_ENABLE_MARKETPLACE",
  "IRENE_ENABLE_ROLLBAR",
  "ENTERPRISE",
  "WHITELABEL_ENABLED",
  "WHITELABEL_NAME",
  "WHITELABEL_LOGO",
  "WHITELABEL_THEME",
  "WHITELABEL_FAVICON",
];

const app = express();
function getRuntimeConfig() {
  const content = {};
  for (const env of ENVs) {
    const value = process.env[env];
    if (value) {
      content[env] = value;
    }
  }
  return JSON.stringify(content);
}
app.use(morgan("tiny"));
app.get("/runtimeconfig.js", function (req, res) {
  const config = `var runtimeGlobalConfig=${getRuntimeConfig()};`;
  res.send(config);
});
app.use(
  expressStaticGzip(staticDir, {
    serveStatic: {
      index: ["index.html"],
    },
  })
);
app.use(function (req, res) { // lgtm [js/missing-rate-limiting]
  res.sendFile(path.join(staticDir, "index.html"));
});
app.listen(4200, function () {
  console.log("server listening on port " + 4200);
});
<|endoftext|>


<commit_before>/*
* jQuery Mobile Framework : resolution and CSS media query related helpers and behavior
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function($, undefined ) {

var $window = $(window),
	$html = $( "html" ),

	//media-query-like width breakpoints, which are translated to classes on the html element
	resolutionBreakpoints = [320,480,768,1024];

/* $.mobile.media method: pass a CSS media type or query and get a bool return
	note: this feature relies on actual media query support for media queries, though types will work most anywhere
	examples:
		$.mobile.media('screen') //>> tests for screen media type
		$.mobile.media('screen and (min-width: 480px)') //>> tests for screen media type with window width > 480px
		$.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') //>> tests for webkit 2x pixel ratio (iPhone 4)
*/
$.mobile.media = (function() {
	// TODO: use window.matchMedia once at least one UA implements it
	var cache = {},
		testDiv = $( "
" ),
		fakeBody = $( "" ).append( testDiv );

	return function( query ) {
		if ( !( query in cache ) ) {
			var styleBlock = $( "" );
			$html.prepend( fakeBody ).prepend( styleBlock );
			cache[ query ] = testDiv.css( "position" ) === "absolute";
			fakeBody.add( styleBlock ).remove();
		}
		return cache[ query ];
	};
})();

/*
	private function for adding/removing breakpoint classes to HTML element for faux media-query support
	It does not require media query support, instead using JS to detect screen width > cross-browser support
	This function is called on orientationchange, resize, and mobileinit, and is bound via the 'htmlclass' event namespace
*/
function detectResolutionBreakpoints(){
	var currWidth = $window.width(),
		minPrefix = "min-width-",
		maxPrefix = "max-width-",
		minBreakpoints = [],
		maxBreakpoints = [],
		unit = "px",
		breakpointClasses;

	$html.removeClass( minPrefix + resolutionBreakpoints.join(unit + " " + minPrefix) + unit + " " +
		maxPrefix + resolutionBreakpoints.join( unit + " " + maxPrefix) + unit );

	$.each(resolutionBreakpoints,function( i, breakPoint ){
		if( currWidth >= breakPoint ){
			minBreakpoints.push( minPrefix + breakPoint + unit );
		}
		if( currWidth <= breakPoint ){
			maxBreakpoints.push( maxPrefix + breakPoint + unit );
		}
	});

	if( minBreakpoints.length ){ breakpointClasses = minBreakpoints.join(" "); }
	if( maxBreakpoints.length ){ breakpointClasses += " " +  maxBreakpoints.join(" "); }

	$html.addClass( breakpointClasses );
};

/* $.mobile.addResolutionBreakpoints method:
	pass either a number or an array of numbers and they'll be added to the min/max breakpoint classes
	Examples:
		$.mobile.addResolutionBreakpoints( 500 );
		$.mobile.addResolutionBreakpoints( [500, 1200] );
*/
$.mobile.addResolutionBreakpoints = function( newbps ){
	if( $.type( newbps ) === "array" ){
		resolutionBreakpoints = resolutionBreakpoints.concat( newbps );
	}
	else {
		resolutionBreakpoints.push( newbps );
	}
	resolutionBreakpoints.sort(function(a,b){ return a-b; });
	detectResolutionBreakpoints();
};

/* 	on mobileinit, add classes to HTML element
	and set handlers to update those on orientationchange and resize*/
$(document).bind("mobileinit.htmlclass", function(){
	/* bind to orientationchange and resize
	to add classes to HTML element for min/max breakpoints and orientation */
	$window.bind("orientationchange.htmlclass resize.htmlclass", function(event){
		//add orientation class to HTML element on flip/resize.
		if(event.orientation){
			$html.removeClass( "portrait landscape" ).addClass( event.orientation );
		}
		//add classes to HTML element for min/max breakpoints
		detectResolutionBreakpoints();
	});
});

/* Manually trigger an orientationchange event when the dom ready event fires.
   This will ensure that any viewport meta tag that may have been injected
   has taken effect already, allowing us to properly calculate the width of the
   document.
*/
$(function(){
	//trigger event manually
	$window.trigger( "orientationchange.htmlclass" );
});

})(jQuery);<commit_msg>small workaround to get media query function to work on Nokia<commit_after>/*
* jQuery Mobile Framework : resolution and CSS media query related helpers and behavior
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function($, undefined ) {

var $window = $(window),
	$html = $( "html" ),

	//media-query-like width breakpoints, which are translated to classes on the html element
	resolutionBreakpoints = [320,480,768,1024];

/* $.mobile.media method: pass a CSS media type or query and get a bool return
	note: this feature relies on actual media query support for media queries, though types will work most anywhere
	examples:
		$.mobile.media('screen') //>> tests for screen media type
		$.mobile.media('screen and (min-width: 480px)') //>> tests for screen media type with window width > 480px
		$.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') //>> tests for webkit 2x pixel ratio (iPhone 4)
*/
$.mobile.media = (function() {
	// TODO: use window.matchMedia once at least one UA implements it
	var cache = {},
		testDiv = $( "
" ),
		fakeBody = $( "" ).append( testDiv );

	return function( query ) {
		if ( !( query in cache ) ) {
			var styleBlock = document.createElement('style'),
        		cssrule = "@media " + query + " { #jquery-mediatest { position:absolute; } }";
	        //must set type for IE!
	        styleBlock.type = "text/css";
	        if (styleBlock.styleSheet){
	          styleBlock.styleSheet.cssText = cssrule;
	        }
	        else {
	          styleBlock.appendChild(document.createTextNode(cssrule));
	        }

			$html.prepend( fakeBody ).prepend( styleBlock );
			cache[ query ] = testDiv.css( "position" ) === "absolute";
			fakeBody.add( styleBlock ).remove();
		}
		return cache[ query ];
	};
})();

/*
	private function for adding/removing breakpoint classes to HTML element for faux media-query support
	It does not require media query support, instead using JS to detect screen width > cross-browser support
	This function is called on orientationchange, resize, and mobileinit, and is bound via the 'htmlclass' event namespace
*/
function detectResolutionBreakpoints(){
	var currWidth = $window.width(),
		minPrefix = "min-width-",
		maxPrefix = "max-width-",
		minBreakpoints = [],
		maxBreakpoints = [],
		unit = "px",
		breakpointClasses;

	$html.removeClass( minPrefix + resolutionBreakpoints.join(unit + " " + minPrefix) + unit + " " +
		maxPrefix + resolutionBreakpoints.join( unit + " " + maxPrefix) + unit );

	$.each(resolutionBreakpoints,function( i, breakPoint ){
		if( currWidth >= breakPoint ){
			minBreakpoints.push( minPrefix + breakPoint + unit );
		}
		if( currWidth <= breakPoint ){
			maxBreakpoints.push( maxPrefix + breakPoint + unit );
		}
	});

	if( minBreakpoints.length ){ breakpointClasses = minBreakpoints.join(" "); }
	if( maxBreakpoints.length ){ breakpointClasses += " " +  maxBreakpoints.join(" "); }

	$html.addClass( breakpointClasses );
};

/* $.mobile.addResolutionBreakpoints method:
	pass either a number or an array of numbers and they'll be added to the min/max breakpoint classes
	Examples:
		$.mobile.addResolutionBreakpoints( 500 );
		$.mobile.addResolutionBreakpoints( [500, 1200] );
*/
$.mobile.addResolutionBreakpoints = function( newbps ){
	if( $.type( newbps ) === "array" ){
		resolutionBreakpoints = resolutionBreakpoints.concat( newbps );
	}
	else {
		resolutionBreakpoints.push( newbps );
	}
	resolutionBreakpoints.sort(function(a,b){ return a-b; });
	detectResolutionBreakpoints();
};

/* 	on mobileinit, add classes to HTML element
	and set handlers to update those on orientationchange and resize*/
$(document).bind("mobileinit.htmlclass", function(){
	/* bind to orientationchange and resize
	to add classes to HTML element for min/max breakpoints and orientation */
	$window.bind("orientationchange.htmlclass resize.htmlclass", function(event){
		//add orientation class to HTML element on flip/resize.
		if(event.orientation){
			$html.removeClass( "portrait landscape" ).addClass( event.orientation );
		}
		//add classes to HTML element for min/max breakpoints
		detectResolutionBreakpoints();
	});
});

/* Manually trigger an orientationchange event when the dom ready event fires.
   This will ensure that any viewport meta tag that may have been injected
   has taken effect already, allowing us to properly calculate the width of the
   document.
*/
$(function(){
	//trigger event manually
	$window.trigger( "orientationchange.htmlclass" );
});

})(jQuery);<|endoftext|>


<commit_before>var path = require('path');
var gulp = require('gulp');
var del = require('del');
var less = require('gulp-less');
var connect = require('gulp-connect');
var runSequence = require('gulp-run-sequence');
var rename = require('gulp-rename');
var exec = require('child_process').exec;
var ghPages = require('gulp-gh-pages');

var srcDocs = path.join(__dirname, 'docs');
var destDocs = path.join(srcDocs, '_site')

gulp.task('jekyll', function (cb) {
    exec('jekyll build', {
        cwd: srcDocs
    }, function(err) {
        console.log(err, arguments);
        if (err) return cb(err);
        cb();
    });
});

gulp.task('styles', function() {
    return gulp.src('./docs/less/main.less')
    .pipe(less())
    .pipe(rename('docs.css'))
    .pipe(gulp.dest(destDocs));
});

gulp.task('clean', function(cb) {
    del([
        path.join(destDocs, '**')
    ], cb);
});

gulp.task('connect', function() {
    connect.server({
        root: destDocs
    });
});

gulp.task('assets', function() {
    return gulp.src([
            'assets/**/*.*'
        ], {
            base: 'assets'
        })
        .pipe(gulp.dest(path.join(destDocs, 'static')));
});

gulp.task('build', function(cb) {
    runSequence('jekyll', 'styles', 'assets', cb);
});

gulp.task('deploy', function() {
    return gulp.src('./docs/_site/**/*')
    .pipe(ghPages());
});

gulp.task('default', function(cb) {
    gulp.watch([
        'less/**/*.less',
        'docs/less/**/*.less'
    ], ['styles']);
    gulp.watch([
        'docs/**/*.md',
        'docs/_layouts/*.html',
        'docs/_includes/*.html'
    ], ['build']);
    runSequence('build', 'connect', cb);
});
<commit_msg>Build before deployment<commit_after>var path = require('path');
var gulp = require('gulp');
var del = require('del');
var less = require('gulp-less');
var connect = require('gulp-connect');
var runSequence = require('gulp-run-sequence');
var rename = require('gulp-rename');
var exec = require('child_process').exec;
var ghPages = require('gulp-gh-pages');

var srcDocs = path.join(__dirname, 'docs');
var destDocs = path.join(srcDocs, '_site')

gulp.task('jekyll', function (cb) {
    exec('jekyll build', {
        cwd: srcDocs
    }, function(err) {
        console.log(err, arguments);
        if (err) return cb(err);
        cb();
    });
});

gulp.task('styles', function() {
    return gulp.src('./docs/less/main.less')
    .pipe(less())
    .pipe(rename('docs.css'))
    .pipe(gulp.dest(destDocs));
});

gulp.task('clean', function(cb) {
    del([
        path.join(destDocs, '**')
    ], cb);
});

gulp.task('connect', function() {
    connect.server({
        root: destDocs
    });
});

gulp.task('assets', function() {
    return gulp.src([
            'assets/**/*.*'
        ], {
            base: 'assets'
        })
        .pipe(gulp.dest(path.join(destDocs, 'static')));
});

gulp.task('build', function(cb) {
    runSequence('jekyll', 'styles', 'assets', cb);
});

gulp.task('deploy', ['build'], function() {
    return gulp.src('./docs/_site/**/*')
    .pipe(ghPages());
});

gulp.task('default', function(cb) {
    gulp.watch([
        'less/**/*.less',
        'docs/less/**/*.less'
    ], ['styles']);
    gulp.watch([
        'docs/**/*.md',
        'docs/_layouts/*.html',
        'docs/_includes/*.html'
    ], ['build']);
    runSequence('build', 'connect', cb);
});
<|endoftext|>


<commit_before>'use strict';

var http = require('http');
var https = require('https');

function RpcClient(opts) {
  opts = opts || {};
  this.host = opts.host || '127.0.0.1';
  this.port = opts.port || 8332;
  this.user = opts.user || 'user';
  this.pass = opts.pass || 'pass';
  this.protocol = opts.protocol === 'http' ? http : https;
  this.batchedCalls = null;
  this.disableAgent  = opts.disableAgent || false;

  if(RpcClient.config.log) {
    this.log = RpcClient.config.log;
  } else {
    this.log = RpcClient.loggers[RpcClient.config.logger || 'normal'];
  }

}

var cl = function() {
    console.log(arguments);
};

var noop = function() {};

RpcClient.loggers = {
  none: {info: noop, warn: noop, err: noop, debug: noop},
  normal: {info: cl, warn: cl, err: cl, debug: noop},
  debug: {info: cl, warn: cl, err: cl, debug: cl}
};

RpcClient.config = {
  logger: 'normal' // none, normal, debug
};

function rpc(request, callback) {

  var self = this;
  request = JSON.stringify(request);
  var auth = new Buffer(self.user + ':' + self.pass).toString('base64');

  var options = {
    host: self.host,
    path: '/',
    method: 'POST',
    port: self.port,
    agent: self.disableAgent ? false : undefined,
  };

  if (self.httpOptions) {
    for (var k in self.httpOptions) {
      options[k] = self.httpOptions[k];
    }
  }

  var called = false;

  var errorMessage = 'Bitcoin Core JSON-RPC: host=' + self.host + ' port=' + self.port + ': ';

  var req = this.protocol.request(options, function(res) {

    var buf = '';
    res.on('data', function(data) {
      buf += data;
    });

    res.on('end', function() {

      if (called) {
        return;
      }
      called = true;

      if (res.statusCode === 401) {
        callback(new Error(errorMessage + 'Connection Rejected: 401 Unnauthorized'));
        return;
      }
      if (res.statusCode === 403) {
        callback(new Error(errorMessage + 'Connection Rejected: 403 Forbidden'));
        return;
      }

      var parsedBuf;
      try {
        parsedBuf = JSON.parse(buf);
      } catch(e) {
        self.log.err(e.stack);
        self.log.err(buf);
        self.log.err('HTTP Status code:' + res.statusCode);
        var err = new Error(errorMessage + 'Error Parsing JSON: ' + e.message);
        callback(err);
        return;
      }

      callback(parsedBuf.error, parsedBuf);

    });
  });

  req.on('error', function(e) {
    var err = new Error(errorMessage + 'Request Error: ' + e.message);
    self.log.err(err);
    if (!called) {
      called = true;
      callback(err);
    }
  });

  req.setHeader('Content-Length', request.length);
  req.setHeader('Content-Type', 'application/json');
  req.setHeader('Authorization', 'Basic ' + auth);
  req.write(request);
  req.end();
}

RpcClient.prototype.batch = function(batchCallback, resultCallback) {
  this.batchedCalls = [];
  batchCallback();
  rpc.call(this, this.batchedCalls, resultCallback);
  this.batchedCalls = null;
};

var callspec = {
  addMultiSigAddress: '',
  addNode: '',
  backupWallet: '',
  createMultiSig: '',
  createRawTransaction: '',
  decodeRawTransaction: '',
  dumpPrivKey: '',
  encryptWallet: '',
  estimateFee: 'int',
  estimatePriority: 'int',
  getAccount: '',
  getAccountAddress: 'str',
  getAddedNodeInfo: '',
  getAddressesByAccount: '',
  getBalance: 'str int',
  getBestBlockHash: '',
  getBlock: '',
  getBlockCount: '',
  getBlockHash: 'int',
  getBlockNumber: '',
  getBlockTemplate: '',
  getConnectionCount: '',
  getChainTips: '',
  getDifficulty: '',
  getGenerate: '',
  getHashesPerSec: '',
  getInfo: '',
  getMemoryPool: '',
  getMemPoolInfo: '',
  getMiningInfo: '',
  getNewAddress: '',
  getPeerInfo: '',
  getRawMemPool: '',
  getRawTransaction: 'str int',
  getReceivedByAccount: 'str int',
  getReceivedByAddress: 'str int',
  getTransaction: '',
  getTxOut: 'str int bool',
  getTxOutSetInfo: '',
  getWork: '',
  help: '',
  importAddress: 'str str bool',
  importPrivKey: 'str str bool',
  keyPoolRefill: '',
  listAccounts: 'int',
  listAddressGroupings: '',
  listReceivedByAccount: 'int bool',
  listReceivedByAddress: 'int bool',
  listSinceBlock: 'str int',
  listTransactions: 'str int int',
  listUnspent: 'int int',
  listLockUnspent: 'bool',
  lockUnspent: '',
  move: 'str str float int str',
  prioritiseTransaction: 'str float int',
  sendFrom: 'str str float int str str',
  sendMany: 'str str int str',  //not sure this is will work
  sendRawTransaction: '',
  sendToAddress: 'str float str str',
  setAccount: '',
  setGenerate: 'bool int',
  setTxFee: 'float',
  signMessage: '',
  signRawTransaction: '',
  stop: '',
  submitBlock: '',
  validateAddress: '',
  verifyMessage: '',
  walletLock: '',
  walletPassPhrase: 'string int',
  walletPassphraseChange: '',
};

var slice = function(arr, start, end) {
  return Array.prototype.slice.call(arr, start, end);
};

function generateRPCMethods(constructor, apiCalls, rpc) {

  function createRPCMethod(methodName, argMap) {
    return function() {

      var limit = arguments.length - 1;

      if (this.batchedCalls) {
        limit = arguments.length;
      }

      for (var i = 0; i < limit; i++) {
        if(argMap[i]) {
          arguments[i] = argMap[i](arguments[i]);
        }
      }

      if (this.batchedCalls) {
        this.batchedCalls.push({
          jsonrpc: '2.0',
          method: methodName,
          params: slice(arguments)
        });
      } else {
        rpc.call(this, {
          method: methodName,
          params: slice(arguments, 0, arguments.length - 1)
        }, arguments[arguments.length - 1]);
      }

    };
  };

  var types = {
    str: function(arg) {
      return arg.toString();
    },
    int: function(arg) {
      return parseFloat(arg);
    },
    float: function(arg) {
      return parseFloat(arg);
    },
    bool: function(arg) {
      return (arg === true || arg == '1' || arg == 'true' || arg.toString().toLowerCase() == 'true');
    }
  };

  for(var k in apiCalls) {
    var spec = apiCalls[k].split(' ');
    for (var i = 0; i < spec.length; i++) {
      if(types[spec[i]]) {
        spec[i] = types[spec[i]];
      } else {
        spec[i] = types.string;
      }
    }
    var methodName = k.toLowerCase();
    constructor.prototype[k] = createRPCMethod(methodName, spec);
    constructor.prototype[methodName] = constructor.prototype[k];
  }

}

generateRPCMethods(RpcClient, callspec, rpc);

module.exports = RpcClient;
<commit_msg>var cl = console.log.bind(console);<commit_after>'use strict';

var http = require('http');
var https = require('https');

function RpcClient(opts) {
  opts = opts || {};
  this.host = opts.host || '127.0.0.1';
  this.port = opts.port || 8332;
  this.user = opts.user || 'user';
  this.pass = opts.pass || 'pass';
  this.protocol = opts.protocol === 'http' ? http : https;
  this.batchedCalls = null;
  this.disableAgent  = opts.disableAgent || false;

  if(RpcClient.config.log) {
    this.log = RpcClient.config.log;
  } else {
    this.log = RpcClient.loggers[RpcClient.config.logger || 'normal'];
  }

}

var cl = console.log.bind(console);

var noop = function() {};

RpcClient.loggers = {
  none: {info: noop, warn: noop, err: noop, debug: noop},
  normal: {info: cl, warn: cl, err: cl, debug: noop},
  debug: {info: cl, warn: cl, err: cl, debug: cl}
};

RpcClient.config = {
  logger: 'normal' // none, normal, debug
};

function rpc(request, callback) {

  var self = this;
  request = JSON.stringify(request);
  var auth = new Buffer(self.user + ':' + self.pass).toString('base64');

  var options = {
    host: self.host,
    path: '/',
    method: 'POST',
    port: self.port,
    agent: self.disableAgent ? false : undefined,
  };

  if (self.httpOptions) {
    for (var k in self.httpOptions) {
      options[k] = self.httpOptions[k];
    }
  }

  var called = false;

  var errorMessage = 'Bitcoin Core JSON-RPC: host=' + self.host + ' port=' + self.port + ': ';

  var req = this.protocol.request(options, function(res) {

    var buf = '';
    res.on('data', function(data) {
      buf += data;
    });

    res.on('end', function() {

      if (called) {
        return;
      }
      called = true;

      if (res.statusCode === 401) {
        callback(new Error(errorMessage + 'Connection Rejected: 401 Unnauthorized'));
        return;
      }
      if (res.statusCode === 403) {
        callback(new Error(errorMessage + 'Connection Rejected: 403 Forbidden'));
        return;
      }

      var parsedBuf;
      try {
        parsedBuf = JSON.parse(buf);
      } catch(e) {
        self.log.err(e.stack);
        self.log.err(buf);
        self.log.err('HTTP Status code:' + res.statusCode);
        var err = new Error(errorMessage + 'Error Parsing JSON: ' + e.message);
        callback(err);
        return;
      }

      callback(parsedBuf.error, parsedBuf);

    });
  });

  req.on('error', function(e) {
    var err = new Error(errorMessage + 'Request Error: ' + e.message);
    self.log.err(err);
    if (!called) {
      called = true;
      callback(err);
    }
  });

  req.setHeader('Content-Length', request.length);
  req.setHeader('Content-Type', 'application/json');
  req.setHeader('Authorization', 'Basic ' + auth);
  req.write(request);
  req.end();
}

RpcClient.prototype.batch = function(batchCallback, resultCallback) {
  this.batchedCalls = [];
  batchCallback();
  rpc.call(this, this.batchedCalls, resultCallback);
  this.batchedCalls = null;
};

var callspec = {
  addMultiSigAddress: '',
  addNode: '',
  backupWallet: '',
  createMultiSig: '',
  createRawTransaction: '',
  decodeRawTransaction: '',
  dumpPrivKey: '',
  encryptWallet: '',
  estimateFee: 'int',
  estimatePriority: 'int',
  getAccount: '',
  getAccountAddress: 'str',
  getAddedNodeInfo: '',
  getAddressesByAccount: '',
  getBalance: 'str int',
  getBestBlockHash: '',
  getBlock: '',
  getBlockCount: '',
  getBlockHash: 'int',
  getBlockNumber: '',
  getBlockTemplate: '',
  getConnectionCount: '',
  getChainTips: '',
  getDifficulty: '',
  getGenerate: '',
  getHashesPerSec: '',
  getInfo: '',
  getMemoryPool: '',
  getMemPoolInfo: '',
  getMiningInfo: '',
  getNewAddress: '',
  getPeerInfo: '',
  getRawMemPool: '',
  getRawTransaction: 'str int',
  getReceivedByAccount: 'str int',
  getReceivedByAddress: 'str int',
  getTransaction: '',
  getTxOut: 'str int bool',
  getTxOutSetInfo: '',
  getWork: '',
  help: '',
  importAddress: 'str str bool',
  importPrivKey: 'str str bool',
  keyPoolRefill: '',
  listAccounts: 'int',
  listAddressGroupings: '',
  listReceivedByAccount: 'int bool',
  listReceivedByAddress: 'int bool',
  listSinceBlock: 'str int',
  listTransactions: 'str int int',
  listUnspent: 'int int',
  listLockUnspent: 'bool',
  lockUnspent: '',
  move: 'str str float int str',
  prioritiseTransaction: 'str float int',
  sendFrom: 'str str float int str str',
  sendMany: 'str str int str',  //not sure this is will work
  sendRawTransaction: '',
  sendToAddress: 'str float str str',
  setAccount: '',
  setGenerate: 'bool int',
  setTxFee: 'float',
  signMessage: '',
  signRawTransaction: '',
  stop: '',
  submitBlock: '',
  validateAddress: '',
  verifyMessage: '',
  walletLock: '',
  walletPassPhrase: 'string int',
  walletPassphraseChange: '',
};

var slice = function(arr, start, end) {
  return Array.prototype.slice.call(arr, start, end);
};

function generateRPCMethods(constructor, apiCalls, rpc) {

  function createRPCMethod(methodName, argMap) {
    return function() {

      var limit = arguments.length - 1;

      if (this.batchedCalls) {
        limit = arguments.length;
      }

      for (var i = 0; i < limit; i++) {
        if(argMap[i]) {
          arguments[i] = argMap[i](arguments[i]);
        }
      }

      if (this.batchedCalls) {
        this.batchedCalls.push({
          jsonrpc: '2.0',
          method: methodName,
          params: slice(arguments)
        });
      } else {
        rpc.call(this, {
          method: methodName,
          params: slice(arguments, 0, arguments.length - 1)
        }, arguments[arguments.length - 1]);
      }

    };
  };

  var types = {
    str: function(arg) {
      return arg.toString();
    },
    int: function(arg) {
      return parseFloat(arg);
    },
    float: function(arg) {
      return parseFloat(arg);
    },
    bool: function(arg) {
      return (arg === true || arg == '1' || arg == 'true' || arg.toString().toLowerCase() == 'true');
    }
  };

  for(var k in apiCalls) {
    var spec = apiCalls[k].split(' ');
    for (var i = 0; i < spec.length; i++) {
      if(types[spec[i]]) {
        spec[i] = types[spec[i]];
      } else {
        spec[i] = types.string;
      }
    }
    var methodName = k.toLowerCase();
    constructor.prototype[k] = createRPCMethod(methodName, spec);
    constructor.prototype[methodName] = constructor.prototype[k];
  }

}

generateRPCMethods(RpcClient, callspec, rpc);

module.exports = RpcClient;
<|endoftext|>


<commit_before>/*
 * Plantalytics
 *     Copyright (c) 2016 Sapphire Becker, Katy Brimm, Scott Ewing,
 *       Matt Fraser, Kelly Ledford, Michael Limb, Steven Ngo, Eric Turley.
 *     This project is licensed under the MIT License.
 *     Please see the file LICENSE in this distribution for license terms.
 * Contact: plantalytics.capstone@gmail.com
 */

$(function() {
    /*
     * Listener for 'enter' keypress on #login* field.
     */
    $("#loginUsername, #loginPassword").keypress(function(evt) {
        if (evt.which == 13 && !evt.shiftKey) {
            $("#loginButton").trigger("click");
        }
    });

    $("#loginButton").click(function() {
        /* This function handles user login */
        $.ajax({
            "url": backendIpAddress + "login",
            "data": JSON.stringify({
                "username": $("#loginUsername").val(),
                "password": $("#loginPassword").val()
            }),
            "type": "POST"
        }).done(function(json) {
            if (json.auth_token) {
                localStorage.accessToken = json.auth_token;
                window.location.href = "dashboard.html";
            } else {
                // Show error message.
                $("#loginError").text("Error logging in.");
            }
        }).fail(function() {
            // Show error message
            $("#loginError").text("Error logging in.");
        });
    });

    $('#forgotPassword').click(function() {
        /* If the username is already entered we can just submit. */
        if ($("#loginUsername").val()) {
            $("#resetButton").click();
        } else {
            /* Hide loginItems and show resetItems. */
            $("#loginError").text("");
            $(".loginItem").hide();
            $(".resetItem").show();
        }
    });

    $('#resetButton').click(function() {
        /* Submit password reset request. */
        $(this).prop("disabled", true);
        $.ajax({
            "url": backendIpAddress + "password/reset",
            "data": JSON.stringify({
                "username": $('#loginUsername').val(),
            }),
            "type": "POST",
        }).done(function(json) {
            json = json || {};
            if ("errors" in json && json.errors.length) {
                // TODO: Integrate with error system.
                $("#loginError").text("Error requesting password.");
            } else {
                $("<span>").addClass("success")
                .text("Password reset request successful, check your email!")
                .appendTo("#loginError");
                revertToLogin();
            }
        }).fail(function() {
            // Show error message
            revertToLogin();
            $("#loginError").text("Error requesting password.");
        });
    });
});

function revertToLogin() {
    $(".resetItem").hide();
    $(".loginItem").show();
    $("#resetButton").prop("disabled", false);
}
<commit_msg>FE#53: Add storing of vineyard ids on login.<commit_after>/*
 * Plantalytics
 *     Copyright (c) 2016 Sapphire Becker, Katy Brimm, Scott Ewing,
 *       Matt Fraser, Kelly Ledford, Michael Limb, Steven Ngo, Eric Turley.
 *     This project is licensed under the MIT License.
 *     Please see the file LICENSE in this distribution for license terms.
 * Contact: plantalytics.capstone@gmail.com
 */

$(function() {
    /*
     * Listener for 'enter' keypress on #login* field.
     */
    $("#loginUsername, #loginPassword").keypress(function(evt) {
        if (evt.which == 13 && !evt.shiftKey) {
            $("#loginButton").trigger("click");
        }
    });

    $("#loginButton").click(function() {
        /* This function handles user login */
        $.ajax({
            "url": backendIpAddress + "login",
            "data": JSON.stringify({
                "username": $("#loginUsername").val(),
                "password": $("#loginPassword").val()
            }),
            "type": "POST"
        }).done(function(json) {
            if (json.auth_token &&
                    json.vineyard_ids) {
                localStorage.accessToken = json.auth_token;
                localStorage.vineyardIds = JSON.stringify(json.vineyard_ids);
                window.location.href = "dashboard.html";
            } else {
                // Show error message.
                $("#loginError").text("Error logging in.");
            }
        }).fail(function() {
            // Show error message
            $("#loginError").text("Error logging in.");
        });
    });

    $('#forgotPassword').click(function() {
        /* If the username is already entered we can just submit. */
        if ($("#loginUsername").val()) {
            $("#resetButton").click();
        } else {
            /* Hide loginItems and show resetItems. */
            $("#loginError").text("");
            $(".loginItem").hide();
            $(".resetItem").show();
        }
    });

    $('#resetButton').click(function() {
        /* Submit password reset request. */
        $(this).prop("disabled", true);
        $.ajax({
            "url": backendIpAddress + "password/reset",
            "data": JSON.stringify({
                "username": $('#loginUsername').val(),
            }),
            "type": "POST",
        }).done(function(json) {
            json = json || {};
            if ("errors" in json && json.errors.length) {
                // TODO: Integrate with error system.
                $("#loginError").text("Error requesting password.");
            } else {
                $("<span>").addClass("success")
                .text("Password reset request successful, check your email!")
                .appendTo("#loginError");
                revertToLogin();
            }
        }).fail(function() {
            // Show error message
            revertToLogin();
            $("#loginError").text("Error requesting password.");
        });
    });
});

function revertToLogin() {
    $(".resetItem").hide();
    $(".loginItem").show();
    $("#resetButton").prop("disabled", false);
}
<|endoftext|>


<commit_before>/* global chrome, fetch, chrome, Worker, localStorage */

const MENU_ID_COPY_PATH = "copy-path";
const MENU_ID_COPY_VALUE = "copy-value";
const MENU_ID_COPY_JSON_VALUE = "copy-json-value";

let extensionReady, copiedPath, copiedValue;
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
	onmessage(message, sender, sendResponse);
	return true;
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
	let message;
	if (info.menuItemId == MENU_ID_COPY_PATH) {
		message = { copy: true, value: copiedPath };
	}
	if (info.menuItemId == MENU_ID_COPY_VALUE) {
		message = { copy: true, value: copiedValue };
	}
	if (info.menuItemId == MENU_ID_COPY_JSON_VALUE) {
		message = { copy: true, value: JSON.stringify(copiedValue) };
	}
	if (message) {
		chrome.tabs.sendMessage(tab.id, message);
	}
});
init();

async function init() {
	extensionReady = migrateSettings();
	const settings = await getSettings();
	if (!settings.options) {
		settings.options = {};
	}
	if (settings.options && typeof settings.options.addContextMenu == "undefined") {
		settings.options.addContextMenu = true;
		await setSetting("options", settings.options);
	}
	if (!settings.theme) {
		const theme = await getDefaultTheme();
		await setSetting("theme", theme);
	}
	await refreshMenuEntry();
}

async function migrateSettings() {
	const promises = [];
	if (typeof localStorage != "undefined") {
		if (localStorage.options) {
			promises.push(new Promise(resolve => {
				chrome.storage.local.set({ options: JSON.parse(localStorage.options) }, () => resolve());
				delete localStorage.options;
			}));
		}
		if (localStorage.theme) {
			promises.push(new Promise(resolve => {
				chrome.storage.local.set({ theme: localStorage.theme }, () => resolve());
				delete localStorage.theme;
			}));
		}
	}
	await Promise.all(promises);
}

async function onmessage(message, sender, sendResponse) {
	const json = message.json;
	let workerFormatter, workerJSONLint;
	if (message.setSetting) {
		await setSetting(message.name, message.value);
	}
	if (message.getSettings) {
		const settings = await getSettings();
		sendResponse(settings);
	}
	if (message.refreshMenuEntry) {
		await refreshMenuEntry();
	}
	if (message.init) {
		sendResponse({ options: (await getSettings()).options || {} });
	}
	if (message.copyPropertyPath) {
		copiedPath = message.path;
		copiedValue = message.value;
	}
	if (message.jsonToHTML) {
		workerFormatter = new Worker("js/worker-formatter.js");
		workerFormatter.addEventListener("message", onWorkerFormatterMessage, false);
		workerFormatter.postMessage({ json: json, fnName: message.fnName });
	}

	function onWorkerJSONLintMessage(event) {
		const message = JSON.parse(event.data);
		workerJSONLint.removeEventListener("message", onWorkerJSONLintMessage, false);
		workerJSONLint.terminate();
		sendResponse({ error: message.error, loc: message.loc, offset: message.offset || 0 });
	}

	async function onWorkerFormatterMessage(event) {
		const message = event.data;
		workerFormatter.removeEventListener("message", onWorkerFormatterMessage, false);
		workerFormatter.terminate();
		if (message.html) {
			sendResponse({ html: message.html, theme: (await getSettings()).theme });
		}
		if (message.error) {
			workerJSONLint = new Worker("js/worker-JSONLint.js");
			workerJSONLint.addEventListener("message", onWorkerJSONLintMessage, false);
			workerJSONLint.postMessage(json);
		}
	}
}

async function refreshMenuEntry() {
	const settings = await getSettings();
	const options = (settings).options;
	chrome.contextMenus.removeAll();
	if (options.addContextMenu) {
		chrome.contextMenus.create({
			id: MENU_ID_COPY_PATH,
			title: "Copy path",
			contexts: ["page", "link"]
		});
		chrome.contextMenus.create({
			id: MENU_ID_COPY_VALUE,
			title: "Copy value",
			contexts: ["page", "link"]
		});
		chrome.contextMenus.create({
			id: MENU_ID_COPY_JSON_VALUE,
			title: "Copy JSON value",
			contexts: ["page", "link"]
		});
	}
}

async function getDefaultTheme() {
	return (await fetch("css/jsonvue.css")).text();
}

async function getSettings() {
	await extensionReady;
	return new Promise(resolve => chrome.storage.local.get(["options", "theme"], result => resolve(result)));
}

async function setSetting(name, value) {
	await extensionReady;
	return new Promise(resolve => chrome.storage.local.set({ [name]: value }, result => resolve(result)));
}<commit_msg>fix CSP issue when copying text (e.g. on https://raw.githubusercontent.com/)<commit_after>/* global chrome, fetch, chrome, document, Worker, localStorage */

const MENU_ID_COPY_PATH = "copy-path";
const MENU_ID_COPY_VALUE = "copy-value";
const MENU_ID_COPY_JSON_VALUE = "copy-json-value";

let extensionReady, copiedPath, copiedValue;
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
	onmessage(message, sender, sendResponse);
	return true;
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
	if (info.menuItemId == MENU_ID_COPY_PATH) {
		copyText(tab, copiedPath);
	}
	if (info.menuItemId == MENU_ID_COPY_VALUE) {
		copyText(tab, copiedValue);
	}
	if (info.menuItemId == MENU_ID_COPY_JSON_VALUE) {
		copyText(tab, JSON.stringify(copiedValue));
	}
});
init();

async function init() {
	extensionReady = migrateSettings();
	const settings = await getSettings();
	if (!settings.options) {
		settings.options = {};
	}
	if (settings.options && typeof settings.options.addContextMenu == "undefined") {
		settings.options.addContextMenu = true;
		await setSetting("options", settings.options);
	}
	if (!settings.theme) {
		const theme = await getDefaultTheme();
		await setSetting("theme", theme);
	}
	await refreshMenuEntry();
}

function copyText(tab, value) {
	if (typeof document != "undefined") {
		const command = "copy";
		document.addEventListener(command, listener);
		document.execCommand(command);
		document.removeEventListener(command, listener);
	} else {
		let message = { copy: true, value: copiedPath };
		chrome.tabs.sendMessage(tab.id, message);
	}

	function listener(event) {
		event.clipboardData.setData("text/plain", value);
		event.preventDefault();
	}
}

async function migrateSettings() {
	const promises = [];
	if (typeof localStorage != "undefined") {
		if (localStorage.options) {
			promises.push(new Promise(resolve => {
				chrome.storage.local.set({ options: JSON.parse(localStorage.options) }, () => resolve());
				delete localStorage.options;
			}));
		}
		if (localStorage.theme) {
			promises.push(new Promise(resolve => {
				chrome.storage.local.set({ theme: localStorage.theme }, () => resolve());
				delete localStorage.theme;
			}));
		}
	}
	await Promise.all(promises);
}

async function onmessage(message, sender, sendResponse) {
	const json = message.json;
	let workerFormatter, workerJSONLint;
	if (message.setSetting) {
		await setSetting(message.name, message.value);
	}
	if (message.getSettings) {
		const settings = await getSettings();
		sendResponse(settings);
	}
	if (message.refreshMenuEntry) {
		await refreshMenuEntry();
	}
	if (message.init) {
		sendResponse({ options: (await getSettings()).options || {} });
	}
	if (message.copyPropertyPath) {
		copiedPath = message.path;
		copiedValue = message.value;
	}
	if (message.jsonToHTML) {
		workerFormatter = new Worker("js/worker-formatter.js");
		workerFormatter.addEventListener("message", onWorkerFormatterMessage, false);
		workerFormatter.postMessage({ json: json, fnName: message.fnName });
	}

	function onWorkerJSONLintMessage(event) {
		const message = JSON.parse(event.data);
		workerJSONLint.removeEventListener("message", onWorkerJSONLintMessage, false);
		workerJSONLint.terminate();
		sendResponse({ error: message.error, loc: message.loc, offset: message.offset || 0 });
	}

	async function onWorkerFormatterMessage(event) {
		const message = event.data;
		workerFormatter.removeEventListener("message", onWorkerFormatterMessage, false);
		workerFormatter.terminate();
		if (message.html) {
			sendResponse({ html: message.html, theme: (await getSettings()).theme });
		}
		if (message.error) {
			workerJSONLint = new Worker("js/worker-JSONLint.js");
			workerJSONLint.addEventListener("message", onWorkerJSONLintMessage, false);
			workerJSONLint.postMessage(json);
		}
	}
}

async function refreshMenuEntry() {
	const settings = await getSettings();
	const options = (settings).options;
	chrome.contextMenus.removeAll();
	if (options.addContextMenu) {
		chrome.contextMenus.create({
			id: MENU_ID_COPY_PATH,
			title: "Copy path",
			contexts: ["page", "link"]
		});
		chrome.contextMenus.create({
			id: MENU_ID_COPY_VALUE,
			title: "Copy value",
			contexts: ["page", "link"]
		});
		chrome.contextMenus.create({
			id: MENU_ID_COPY_JSON_VALUE,
			title: "Copy JSON value",
			contexts: ["page", "link"]
		});
	}
}

async function getDefaultTheme() {
	return (await fetch("css/jsonvue.css")).text();
}

async function getSettings() {
	await extensionReady;
	return new Promise(resolve => chrome.storage.local.get(["options", "theme"], result => resolve(result)));
}

async function setSetting(name, value) {
	await extensionReady;
	return new Promise(resolve => chrome.storage.local.set({ [name]: value }, result => resolve(result)));
}<|endoftext|>