<commit_before>const BinarySocket       = require('../socket');
const BinaryPjax         = require('../../base/binary_pjax');
const Client             = require('../../base/client');
const getPropertyValue   = require('../../base/utility').getPropertyValue;
const elementTextContent = require('../../common_functions/common_functions').elementTextContent;
const isCryptocurrency   = require('../../common_functions/currency').isCryptocurrency;
const FormManager        = require('../../common_functions/form_manager');

const AccountTransfer = (() => {
    const form_id       = 'frm_transfer_funds';
    const form_id_hash  = `#${form_id}`;

    const messages = {
        parent : 'client_message',
        error  : 'no_account',
        deposit: 'no_balance',
    };

    let el_transfer_from,
        el_transfer_to,
        client_loginid,
        client_currency,
        client_balance;

    const populateAccounts = (accounts) => {
        client_loginid  = Client.get('loginid');
        client_currency = Client.get('currency');

        el_transfer_from = document.getElementById('lbl_transfer_from');
        el_transfer_to   = document.getElementById('transfer_to');

        elementTextContent(el_transfer_from, `${client_loginid} (${client_currency})`);

        const fragment_transfer_to   = document.createElement('div');

        accounts.forEach((account, idx) => {
            if (accounts[idx].loginid !== client_loginid) {
                const option  = document.createElement('option');
                option.appendChild(document.createTextNode(accounts[idx].loginid));
                fragment_transfer_to.appendChild(option);
            }
        });

        if (!fragment_transfer_to.childElementCount) {
            showError();
            return;
        }
        if (fragment_transfer_to.childElementCount > 1) {
            el_transfer_to.innerHTML = `${fragment_transfer_to.innerHTML} (${client_currency})`;
        } else {
            const label = document.createElement('label');
            label.appendChild(document.createTextNode(`${fragment_transfer_to.innerText} (${client_currency})`));
            label.setAttribute('data-value', fragment_transfer_to.innerText);
            label.id = 'transfer_to';

            el_transfer_to.parentNode.replaceChild(label, el_transfer_to);
            el_transfer_to = document.getElementById('transfer_to');
        }

        showForm();

        if (Client.hasCurrencyType('crypto') && Client.hasCurrencyType('fiat')) {
            document.getElementById('transfer_fee').setVisibility(1);
        }
    };

    const hasError = (response) => {
        const error = response.error;
        if (error) {
            const el_error = document.getElementById('error_message').getElementsByTagName('p')[0];
            elementTextContent(el_error, error.message);
            el_error.parentNode.setVisibility(1);
            return true;
        }
        return false;
    };

    const showError = () => {
        document.getElementById(messages.parent).setVisibility(1);
        document.getElementById(messages.error).setVisibility(1);
    };

    // TODO: change values when back-end updates logic
    const getMinAmount = () => (isCryptocurrency(client_currency) ? 0.002 : 1);

    const getDecimals = () => (isCryptocurrency(client_currency) ? '1, 8' : '1, 2');

    const showForm = () => {
        elementTextContent(document.querySelector(`${form_id_hash} #currency`), client_currency);

        document.getElementById(form_id).setVisibility(1);

        FormManager.init(form_id_hash, [
            { selector: '#amount', validations: [['req', { hide_asterisk: true }], ['number', { type: 'float', decimals: getDecimals(), min: getMinAmount(), max: client_balance, custom_message: 'This amount exceeds your withdrawal limit.' }]] },

            { request_field: 'transfer_between_accounts', value: 1 },
            { request_field: 'account_from',              value: client_loginid },
            { request_field: 'account_to',                value: () => el_transfer_to.value || el_transfer_to.getAttribute('data-value') },
            { request_field: 'currency',                  value: client_currency },
        ]);

        FormManager.handleSubmit({
            form_selector       : form_id_hash,
            fnc_response_handler: responseHandler,
        });
    };

    const responseHandler = (response) => {
        if (response.error) {
            const el_error = document.getElementById('form_error');
            elementTextContent(el_error, response.error.message);
            el_error.setVisibility(1);
        } else {
            BinarySocket.send({ transfer_between_accounts: 1 }).then(data => populateReceipt(response, data));
        }
    };

    const populateReceipt = (response_submit_success, response) => {
        document.getElementById(form_id).setVisibility(0);

        elementTextContent(document.getElementById('from_loginid'), client_loginid);
        elementTextContent(document.getElementById('to_loginid'), response_submit_success.client_to_loginid);

        response.accounts.forEach((account) => {
            if (account.loginid === client_loginid) {
                elementTextContent(document.getElementById('from_balance'), account.balance);
            } else if (account.loginid === response_submit_success.client_to_loginid) {
                elementTextContent(document.getElementById('to_balance'), account.balance);
            }
        });

        document.getElementById('transfer_fee').setVisibility(0);
        document.getElementById('success_form').setVisibility(1);
    };

    const onLoad = () => {
        if (!Client.canTransferFunds()) {
            BinaryPjax.loadPreviousUrl();
        }
        BinarySocket.wait('balance').then((response) => {
            client_balance = getPropertyValue(response, ['balance', 'balance']);
            if (!client_balance || +client_balance === 0) {
                document.getElementById(messages.parent).setVisibility(1);
                document.getElementById(messages.deposit).setVisibility(1);
            } else {
                BinarySocket.send({ transfer_between_accounts: 1 }).then((response_transfer) => {
                    if (hasError(response_transfer)) {
                        return;
                    }
                    const accounts = response_transfer.accounts;
                    if (!accounts || !accounts.length) {
                        showError();
                        return;
                    }
                    BinarySocket.send({ get_limits: 1 }).then((response_limits) => {
                        if (hasError(response_limits)) {
                            return;
                        }
                        populateAccounts(accounts);
                    });
                });
            }
        });
    };

    return {
        onLoad,
    };
})();

module.exports = AccountTransfer;
<commit_msg>fix currency for transfer to<commit_after>const BinarySocket       = require('../socket');
const BinaryPjax         = require('../../base/binary_pjax');
const Client             = require('../../base/client');
const getPropertyValue   = require('../../base/utility').getPropertyValue;
const elementTextContent = require('../../common_functions/common_functions').elementTextContent;
const isCryptocurrency   = require('../../common_functions/currency').isCryptocurrency;
const FormManager        = require('../../common_functions/form_manager');

const AccountTransfer = (() => {
    const form_id       = 'frm_transfer_funds';
    const form_id_hash  = `#${form_id}`;

    const messages = {
        parent : 'client_message',
        error  : 'no_account',
        deposit: 'no_balance',
    };

    let el_transfer_from,
        el_transfer_to,
        client_loginid,
        client_currency,
        client_balance;

    const populateAccounts = (accounts) => {
        client_loginid  = Client.get('loginid');
        client_currency = Client.get('currency');

        el_transfer_from = document.getElementById('lbl_transfer_from');
        el_transfer_to   = document.getElementById('transfer_to');

        elementTextContent(el_transfer_from, `${client_loginid} (${client_currency})`);

        const fragment_transfer_to   = document.createElement('div');

        accounts.forEach((account, idx) => {
            if (accounts[idx].loginid !== client_loginid) {
                const option  = document.createElement('option');
                option.appendChild(document.createTextNode(`${accounts[idx].loginid} (${accounts[idx].currency})`));
                fragment_transfer_to.appendChild(option);
            }
        });

        if (!fragment_transfer_to.childElementCount) {
            showError();
            return;
        }
        if (fragment_transfer_to.childElementCount > 1) {
            el_transfer_to.innerHTML = fragment_transfer_to.innerHTML;
        } else {
            const label = document.createElement('label');
            label.appendChild(document.createTextNode(fragment_transfer_to.innerText));
            label.setAttribute('data-value', fragment_transfer_to.innerText);
            label.id = 'transfer_to';

            el_transfer_to.parentNode.replaceChild(label, el_transfer_to);
            el_transfer_to = document.getElementById('transfer_to');
        }

        showForm();

        if (Client.hasCurrencyType('crypto') && Client.hasCurrencyType('fiat')) {
            document.getElementById('transfer_fee').setVisibility(1);
        }
    };

    const hasError = (response) => {
        const error = response.error;
        if (error) {
            const el_error = document.getElementById('error_message').getElementsByTagName('p')[0];
            elementTextContent(el_error, error.message);
            el_error.parentNode.setVisibility(1);
            return true;
        }
        return false;
    };

    const showError = () => {
        document.getElementById(messages.parent).setVisibility(1);
        document.getElementById(messages.error).setVisibility(1);
    };

    // TODO: change values when back-end updates logic
    const getMinAmount = () => (isCryptocurrency(client_currency) ? 0.002 : 1);

    const getDecimals = () => (isCryptocurrency(client_currency) ? '1, 8' : '1, 2');

    const showForm = () => {
        elementTextContent(document.querySelector(`${form_id_hash} #currency`), client_currency);

        document.getElementById(form_id).setVisibility(1);

        FormManager.init(form_id_hash, [
            { selector: '#amount', validations: [['req', { hide_asterisk: true }], ['number', { type: 'float', decimals: getDecimals(), min: getMinAmount(), max: client_balance, custom_message: 'This amount exceeds your withdrawal limit.' }]] },

            { request_field: 'transfer_between_accounts', value: 1 },
            { request_field: 'account_from',              value: client_loginid },
            { request_field: 'account_to',                value: () => el_transfer_to.value || el_transfer_to.getAttribute('data-value') },
            { request_field: 'currency',                  value: client_currency },
        ]);

        FormManager.handleSubmit({
            form_selector       : form_id_hash,
            fnc_response_handler: responseHandler,
        });
    };

    const responseHandler = (response) => {
        if (response.error) {
            const el_error = document.getElementById('form_error');
            elementTextContent(el_error, response.error.message);
            el_error.setVisibility(1);
        } else {
            BinarySocket.send({ transfer_between_accounts: 1 }).then(data => populateReceipt(response, data));
        }
    };

    const populateReceipt = (response_submit_success, response) => {
        document.getElementById(form_id).setVisibility(0);

        elementTextContent(document.getElementById('from_loginid'), client_loginid);
        elementTextContent(document.getElementById('to_loginid'), response_submit_success.client_to_loginid);

        response.accounts.forEach((account) => {
            if (account.loginid === client_loginid) {
                elementTextContent(document.getElementById('from_balance'), account.balance);
            } else if (account.loginid === response_submit_success.client_to_loginid) {
                elementTextContent(document.getElementById('to_balance'), account.balance);
            }
        });

        document.getElementById('transfer_fee').setVisibility(0);
        document.getElementById('success_form').setVisibility(1);
    };

    const onLoad = () => {
        if (!Client.canTransferFunds()) {
            BinaryPjax.loadPreviousUrl();
        }
        BinarySocket.wait('balance').then((response) => {
            client_balance = getPropertyValue(response, ['balance', 'balance']);
            if (!client_balance || +client_balance === 0) {
                document.getElementById(messages.parent).setVisibility(1);
                document.getElementById(messages.deposit).setVisibility(1);
            } else {
                BinarySocket.send({ transfer_between_accounts: 1 }).then((response_transfer) => {
                    if (hasError(response_transfer)) {
                        return;
                    }
                    const accounts = response_transfer.accounts;
                    if (!accounts || !accounts.length) {
                        showError();
                        return;
                    }
                    BinarySocket.send({ get_limits: 1 }).then((response_limits) => {
                        if (hasError(response_limits)) {
                            return;
                        }
                        populateAccounts(accounts);
                    });
                });
            }
        });
    };

    return {
        onLoad,
    };
})();

module.exports = AccountTransfer;
<|endoftext|>


<commit_before>import { DeviceEventEmitter } from "react-native";
import { Observable } from "rxjs";
import { publish, refCount } from "rxjs/operators";
import RNSensors from "./rnsensors";

function createSensorObservable(sensorType) {
  return Observable.create(function subscribe(observer) {
    this.unsubscribeCallback = () => {};

    RNSensors.isAvailable(sensorType).then(
      () => {
        DeviceEventEmitter.addListener(sensorType, data => {
          observer.next(data);
        });

        // Register the unsubscribe handler
        this.unsubscribeCallback = () => {
          RNSensors.stop(sensorType);
        };

        // Start the sensor manager
        RNSensors.start(sensorType);
      },
      () => {
        observer.error(`Sensor ${sensorType} is not available`);
      }
    );

    return this.unsubscribeCallback;
  }).pipe(makeSingleton());
}

// As we only have one sensor we need to share it between the different consumers
function makeSingleton() {
  return source => source.pipe(publish(), refCount());
}

const accelerometer = createSensorObservable("accelerometer");
const gyroscope = createSensorObservable("gyroscope");
const magnetometer = createSensorObservable("magnetometer");

export default {
  gyroscope,
  accelerometer,
  magnetometer
};
<commit_msg>fix: sensor type is wrongly cased for listeners<commit_after>import { DeviceEventEmitter } from "react-native";
import { Observable } from "rxjs";
import { publish, refCount } from "rxjs/operators";
import RNSensors from "./rnsensors";

const listenerKeys = new Map([
  ["accelerometer", "Accelerometer"],
  ["gyroscope", "Gyroscope"],
  ["magnetometer", "Magnetometer"]
]);

function createSensorObservable(sensorType) {
  return Observable.create(function subscribe(observer) {
    this.unsubscribeCallback = () => {};

    RNSensors.isAvailable(sensorType).then(
      () => {
        DeviceEventEmitter.addListener(listenerKeys.get(sensorType), data => {
          observer.next(data);
        });

        // Register the unsubscribe handler
        this.unsubscribeCallback = () => {
          RNSensors.stop(sensorType);
        };

        // Start the sensor manager
        RNSensors.start(sensorType);
      },
      () => {
        observer.error(`Sensor ${sensorType} is not available`);
      }
    );

    return this.unsubscribeCallback;
  }).pipe(makeSingleton());
}

// As we only have one sensor we need to share it between the different consumers
function makeSingleton() {
  return source => source.pipe(publish(), refCount());
}

const accelerometer = createSensorObservable("accelerometer");
const gyroscope = createSensorObservable("gyroscope");
const magnetometer = createSensorObservable("magnetometer");

export default {
  gyroscope,
  accelerometer,
  magnetometer
};
<|endoftext|>


<commit_before>/*global define*/

define(function (require) {
    'use strict';

    var angular = require('angular'),
        Configurable = require('ng-admin/Main/component/service/config/Configurable'),
        utils = require('ng-admin/lib/utils'),
        availableTypes = ['number', 'string', 'text', 'wysiwyg', 'email', 'date', 'boolean', 'choice', 'choices', 'password', 'template'];

    function defaultValueTemplate(entry) {
        return '';
    }

    var config = {
        name: 'myField',
        type: 'string',
        label: 'My field',
        editable : true,
        displayed: true,
        order: null,
        identifier : false,
        format : 'yyyy-MM-dd',
        template: defaultValueTemplate,
        isEditLink: false,
        list: true,
        dashboard: true,
        validation: {
            required: false,
            minlength: 0,
            maxlength: 99999 // We can't remove ng-maxlength directive
        },
        choices: [],
        defaultValue: null,
        cssClasses: []
    };

    /**
     * @constructor
     *
     * @param {String } fieldName
     *
     */
    function Field(fieldName) {
        this.config = angular.copy(config);
        this.config.name = fieldName || Math.random().toString(36).substring(7);
        this.config.label = utils.camelCase(this.config.name);
        this.config.isEditLink = fieldName === 'id';
        this.entity = null; // Used when this field is an identifier
        this.view = null;
        this.maps = [];
    }

    Configurable(Field.prototype, config);

    /**
     * Set or get the type
     *
     * @param {String} type
     * @returns string|Field
     */
    Field.prototype.type = function (type) {
        if (arguments.length === 0) {
            return this.config.type;
        }

        if (availableTypes.indexOf(type) === -1) {
            throw new Error('Type should be one of : "' + availableTypes.join('", "') + '" but "' + type + '" was given.');
        }

        this.config.type = type;

        return this;
    };

    /**
     * Add a map function
     *
     * @param {Function} fn
     *
     * @returns {Field}
     */
    Field.prototype.map = function (fn) {
        this.maps.push(fn);

        return this;
    };

    /**
     * Truncate the value based after applying all maps
     *
     * @param {*} value
     *
     * @returns {*}
     */
    Field.prototype.getMappedValue = function (value) {
        for (var i in this.maps) {
            value = this.maps[i](value);
        }

        return value;
    };

    /**
     * Get CSS classes list based on the `cssClasses` configuration
     *
     * @returns {string}
     */
    Field.prototype.getCssClasses = function () {
        var classes = 'form-control';

        if (this.config.cssClasses) {
            classes += ' ' + this.config.cssClasses.join(' ');
        }

        return classes;
    }

    /**
     * @param {View} view
     */
    Field.prototype.setView = function (view) {
        this.view = view;

        return this;
    };

    /**
     * @return {View}
     */
    Field.prototype.getView = function () {
        return this.view;
    };

    /**
     * @return {string}
     */
    Field.prototype.getSortName = function () {
        return this.view.name() + '.' + this.name();
    };

    /**
      * Return field value
      *
      * @returns mixed
      */
    Field.prototype.getTemplateValue = function (data) {
        return typeof (this.config.template) === 'function' ? this.config.template(data) : this.config.template;
    };

    /**
     * Return the entity attached to the Field
     * this.entity is set first when this Field is used as an identifier
     *
     * @return {Entity}
     */
    Field.prototype.getEntity = function () {
        if (this.entity === null) {
            this.entity = this.view.getEntity();
        }

        return this.entity;
    };

    /**
     * Return a modifiable clone of the field
     *
     * @return {Field}
     */
    Field.prototype.clone = function () {
        return {
            prototype: Field.prototype,
            __proto__: this.__proto__,
            config: angular.copy(this.config),
            entity: null,
            view: null
        };
    };

    return Field;
});
<commit_msg>Remove useless clone method<commit_after>/*global define*/

define(function (require) {
    'use strict';

    var angular = require('angular'),
        Configurable = require('ng-admin/Main/component/service/config/Configurable'),
        utils = require('ng-admin/lib/utils'),
        availableTypes = ['number', 'string', 'text', 'wysiwyg', 'email', 'date', 'boolean', 'choice', 'choices', 'password', 'template'];

    function defaultValueTemplate(entry) {
        return '';
    }

    var config = {
        name: 'myField',
        type: 'string',
        label: 'My field',
        editable : true,
        displayed: true,
        order: null,
        identifier : false,
        format : 'yyyy-MM-dd',
        template: defaultValueTemplate,
        isEditLink: false,
        list: true,
        dashboard: true,
        validation: {
            required: false,
            minlength: 0,
            maxlength: 99999 // We can't remove ng-maxlength directive
        },
        choices: [],
        defaultValue: null,
        cssClasses: []
    };

    /**
     * @constructor
     *
     * @param {String } fieldName
     *
     */
    function Field(fieldName) {
        this.config = angular.copy(config);
        this.config.name = fieldName || Math.random().toString(36).substring(7);
        this.config.label = utils.camelCase(this.config.name);
        this.config.isEditLink = fieldName === 'id';
        this.entity = null; // Used when this field is an identifier
        this.view = null;
        this.maps = [];
    }

    Configurable(Field.prototype, config);

    /**
     * Set or get the type
     *
     * @param {String} type
     * @returns string|Field
     */
    Field.prototype.type = function (type) {
        if (arguments.length === 0) {
            return this.config.type;
        }

        if (availableTypes.indexOf(type) === -1) {
            throw new Error('Type should be one of : "' + availableTypes.join('", "') + '" but "' + type + '" was given.');
        }

        this.config.type = type;

        return this;
    };

    /**
     * Add a map function
     *
     * @param {Function} fn
     *
     * @returns {Field}
     */
    Field.prototype.map = function (fn) {
        this.maps.push(fn);

        return this;
    };

    /**
     * Truncate the value based after applying all maps
     *
     * @param {*} value
     *
     * @returns {*}
     */
    Field.prototype.getMappedValue = function (value) {
        for (var i in this.maps) {
            value = this.maps[i](value);
        }

        return value;
    };

    /**
     * Get CSS classes list based on the `cssClasses` configuration
     *
     * @returns {string}
     */
    Field.prototype.getCssClasses = function () {
        var classes = 'form-control';

        if (this.config.cssClasses) {
            classes += ' ' + this.config.cssClasses.join(' ');
        }

        return classes;
    }

    /**
     * @param {View} view
     */
    Field.prototype.setView = function (view) {
        this.view = view;

        return this;
    };

    /**
     * @return {View}
     */
    Field.prototype.getView = function () {
        return this.view;
    };

    /**
     * @return {string}
     */
    Field.prototype.getSortName = function () {
        return this.view.name() + '.' + this.name();
    };

    /**
      * Return field value
      *
      * @returns mixed
      */
    Field.prototype.getTemplateValue = function (data) {
        return typeof (this.config.template) === 'function' ? this.config.template(data) : this.config.template;
    };

    /**
     * Return the entity attached to the Field
     * this.entity is set first when this Field is used as an identifier
     *
     * @return {Entity}
     */
    Field.prototype.getEntity = function () {
        if (this.entity === null) {
            this.entity = this.view.getEntity();
        }

        return this.entity;
    };

    return Field;
});
<|endoftext|>


<commit_before>var quicktest = function(svg, data, Plottable){

        var dataseries = data[0].slice(0, 20);
        var dataseries_top = data[1].slice(0, 20);
        for (var i = 0; i < 20; ++i) {
          dataseries_top[i].x = dataseries[i].x;
          dataseries_top[i].y += dataseries[i].y;
        }

        var xScale = new Plottable.Scale.Linear();
        var xAxis = new Plottable.Axis.XAxis(xScale, "bottom");

        var yScale = new Plottable.Scale.Linear();
        var yAxis = new Plottable.Axis.YAxis(yScale, "left");

        var y0Accessor = function(d, i) { return dataseries[i].y; }

        var renderAreaD1 = new Plottable.Plot.Area(dataseries, xScale, yScale);
        var renderAreaD2 = new Plottable.Plot.Area(dataseries_top, xScale, yScale, "x", "y", y0Accessor);

        var fillAccessor = function() { return "steelblue"; }
        var fillAccessorTop = function() { return "pink"; }
        renderAreaD1.project("fill", fillAccessor)
        renderAreaD2.project("fill", fillAccessorTop)

        var gridlines = new Plottable.Component.Gridlines(xScale, yScale);
        var renderGroup = new Plottable.Component.Group([gridlines, renderAreaD1, renderAreaD2]);

        var chart = new Plottable.Template.StandardChart()
                        .center(renderGroup).xAxis(xAxis).yAxis(yAxis)
                        .renderTo(svg);

        window.x = new Plottable.Interaction.XDragBox(renderGroup).setupZoomCallback(xScale, null).registerWithComponent();

}
quicktest.quicktestName = "dragzoom_x";
quicktest.categories = ["area", "interaction"];
quicktests.push(quicktest)
<commit_msg>Update interaction_dragzoomx.js<commit_after>var quicktest = function(svg, data, Plottable){

        var dataseries = data[0].slice(0, 20);
        var dataseries_top = data[1].slice(0, 20);
        for (var i = 0; i < 20; ++i) {
          dataseries_top[i].x = dataseries[i].x;
          dataseries_top[i].y += dataseries[i].y;
        }

        var xScale = new Plottable.Scale.Linear();
        var xAxis = new Plottable.Axis.XAxis(xScale, "bottom");

        var yScale = new Plottable.Scale.Linear();
        var yAxis = new Plottable.Axis.YAxis(yScale, "left");

        var y0Accessor = function(d, i) { return dataseries[i].y; }

        var renderAreaD1 = new Plottable.Plot.Area(dataseries, xScale, yScale);
        var renderAreaD2 = new Plottable.Plot.Area(dataseries_top, xScale, yScale, "x", "y", y0Accessor);

        var fillAccessor = function() { return "steelblue"; }
        var fillAccessorTop = function() { return "pink"; }
        renderAreaD1.project("fill", fillAccessor)
        renderAreaD2.project("fill", fillAccessorTop)

        var gridlines = new Plottable.Component.Gridlines(xScale, yScale);
        var renderGroup = new Plottable.Component.Group([gridlines, renderAreaD1, renderAreaD2]);

        var chart = new Plottable.Template.StandardChart()
                        .center(renderGroup).xAxis(xAxis).yAxis(yAxis)
                        .renderTo(svg);

        window.x = new Plottable.Interaction.XDragBox(renderGroup).setupZoomCallback(xScale, null).registerWithComponent();

}
quicktest.quicktestName = "dragzoom_x";
quicktests.push(quicktest)
<|endoftext|>


<commit_before>Runner.Preloader = function (game) {
    this.preloadBar = null;
    this.title.text = null;
    this.ready  = false

}

Runner.Preloader.prototype = {

    preload: function (){
        // add images loaded in boot preload as sprite
        // load add sprites
    },

    create: function(){
        // disable crop of image since it will be 100%
        this.preloadBar.setCropEnabled = false;
    },

    update: function(){
        this.ready = true;
    }
}<commit_msg>load images for splash<commit_after>Runner.Preloader = function (game) {
    this.ready  = false
}

Runner.Preloader.prototype = {

    preload: function (){
        // add images loaded in boot preload
        this.load.image('characterimg','assets/splash/gb_0009_Layer-5.png');

        this.load.spritesheet('map', 'assets/splash/gb_0007_map.png');
        this.load.image('logo', 'assets/splash/gb_0008_logo.png');
        this.load.image('spikes', 'assets/splash/gb_0010_spikes.png');
        this.load.image('tree', 'assets/splash/gb_0011_trees-copy.png')
        // load add sprites
        this.load.spritesheet('startbtn', 'assets/splash/gb_0003_button-start.png',138,38);

    },

    create: function(){

    },

    update: function(){
        this.ready = true;
        this.state.start('StartMenu');
    }
}<|endoftext|>


<commit_before>// check if document is loaded and properly connected
$(document).ready(function(){
	console.log("DOM Ready")
})

// create a function using jquery that reacts with every key entered into the form #inputUser
$('#inputUser').keyup(function() {

	console.log('jquery function works')

// create a variable that takes the input entered into the form as a value
	var searchUser = {
		name: $('#inputUser').val()
	}

	console.log(searchUser)

// post request to pass on the user input to the backend app.js,
// use response of the backend function to append matching names to the dropdown of the searchbar
	$.post("/searchBar", searchUser, function (data, stat) {

		$('#users').empty()

		console.log("this is " + data)

		for (var i = 0; i < data.length; i++) {
			$('#users').append("<option>" + data[i] + "</option>")
		}

	})
})<commit_msg>added a timeout function<commit_after>// check if document is loaded and properly connected
$(document).ready(function(){
	console.log("DOM Ready")
})

function timeout () {
	var startTime = Date.now()

	setTimeout(autocompSearch (startTime), 3000)
}

timeout ()

function autocompSearch (startTime) {

// create a function using jquery that reacts with every key entered into the form #inputUser
$('#inputUser').keyup(function() {

	console.log('jquery function works')

// create a variable that takes the input entered into the form as a value
	var searchUser = {
		name: $('#inputUser').val()
	}

	console.log(searchUser)

// post request to pass on the user input to the backend app.js,
// use response of the backend function to append matching names to the dropdown of the searchbar
	$.post("/searchBar", searchUser, function (data, stat) {

		$('#users').empty()

		console.log("this is " + data)

		for (var i = 0; i < data.length; i++) {
			$('#users').append("<option>" + data[i] + "</option>")
		}

	if ((Date.now() - startTime) > 300) {
	clearTimeout(timeout)
	timeout()
	}

	})
 })
}<|endoftext|>


<commit_before>// Copyright (c) 2012-2018, Najjar Chedy
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

'use strict';

var $ = require('jquery');
var vis = require('vis');
var _ = require('underscore');

require('selectize');
require("vis/dist/vis.css");

function Cfg(hub, container, state) {
    this.container = container;
    this.eventHub = hub.createEventHub();
    this.domRoot = container.getElement();
    this.domRoot.html($('#cfg').html());
    this.defaultCfgOutput = {nodes: [{id: 0, shape: 'box', label: 'No Output'}], edges: []};
    this.binaryModeSupport = {
        nodes: [{
            id: 0,
            shape: 'box',
            label: 'Cfg mode cannot be used when the binary filter is set'
        }], edges: []
    };
    // Note that this might be outdated if no functions were present when creating the link, but that's handled
    // by selectize
    this.currentFunc = state.selectedFn || '';
    this.functions = [];
    this.networkOpts = {
        autoResize: true,
        locale: 'en',
        edges: {
            arrows: {to: {enabled: true}},
            smooth: {enabled: true},
            physics: false
        },
        nodes: {
            font: {face: 'monospace', align: 'left'}
        },
        layout: {
            improvedLayout: true,
            hierarchical: {
                enabled: true,
                sortMethod: 'directed',
                direction: 'UD',
                nodeSpacing: 100,
                levelSeparation: 150
            }
        },
        physics: {
            hierarchicalRepulsion: {
                nodeDistance: 125
            }
        },
        interaction: {
            navigationButtons: false,
            keyboard: {
                enabled: true,
                speed: {x: 10, y: 10, zoom: 0.03},
                bindToWindow: false
            }
        }
    };

    this.cfgVisualiser = new vis.Network(this.domRoot.find('.graph-placeholder')[0],
        this.defaultCfgOutput, this.networkOpts);
    this.domRoot.find('.show-hide-btn').on('click', _.bind(function () {
        this.networkOpts.interaction.navigationButtons = !this.networkOpts.interaction.navigationButtons;
        this.cfgVisualiser.setOptions(this.networkOpts);
    }, this));

    this.compilerId = state.id;
    this._editorid = state.editorid;
    this._binaryFilter = false;

    this.functionPicker = $(this.domRoot).find('.function-picker').selectize({
        sortField: 'name',
        valueField: 'name',
        labelField: 'name',
        searchField: ['name']
    }).on('change', _.bind(function (e) {
        var selectedFn = this.functions[e.target.value];
        if (selectedFn) {
            this.currentFunc = e.target.value;
            this.showCfgResults({
                nodes: selectedFn.nodes,
                edges: selectedFn.edges
            });
            this.cfgVisualiser.selectNodes([selectedFn.nodes[0].id]);
            this.saveState();
        }
    }, this));

    this.eventHub.on('compilerClose', this.onCompilerClose, this);
    this.eventHub.on('compileResult', this.onCompileResult, this);
    this.eventHub.on('compiler', this.onCompiler, this);
    this.eventHub.on('filtersChange', this.onFiltersChange, this);

    this.container.on('destroy', this.close, this);
    this.container.on('resize', this.resize, this);
    this.container.on('shown', this.resize, this);
    this.eventHub.emit('cfgViewOpened', this.compilerId);
    this.eventHub.emit('requestFilters', this.compilerId);
    this.eventHub.emit('requestCompiler', this.compilerId);

    this.adaptStructure = function (names) {
        return _.map(names, function (name) {
            return {name: name};
        });
    };

    this.setTitle();
}

Cfg.prototype.onCompileResult = function (id, compiler, result) {
    if (this._compilerid === id) {
        var functionNames = [];
        if (result.supportsCfg && !$.isEmptyObject(result.cfg)) {
            this.functions = result.cfg;
            functionNames = Object.keys(this.functions);
            if (functionNames.indexOf(this.currentFunc) === -1) {
                this.currentFunc = functionNames[0];
            }
            this.showCfgResults({
                nodes: this.functions[this.currentFunc].nodes,
                edges: this.functions[this.currentFunc].edges
            });
            this.cfgVisualiser.selectNodes([this.functions[this.currentFunc].nodes[0].id]);
        } else {
            // We don't reset the current function here as we would lose the saved one if this happened at the begining
            // (Hint: It *does* happen)
            this.showCfgResults(this._binaryFilter ? this.binaryModeSupport : this.defaultCfgOutput);
        }

        this.functionPicker[0].selectize.clearOptions();
        this.functionPicker[0].selectize.addOption(functionNames.length ? this.adaptStructure(functionNames) : {name: 'The input does not contain functions'});
        this.functionPicker[0].selectize.refreshOptions(false);

        this.functionPicker[0].selectize.clear();
        this.functionPicker[0].selectize.addItem(functionNames.length ? this.currentFunc : 'The input does not contain any function', true);
        this.saveState();
    }
};
Cfg.prototype.onCompiler = function (id, compiler) {
    if (id === this.compilerId) {
        this._compilerName = compiler ? compiler.name : '';
        this.supportsCfg = compiler.supportsCfg;
        this.setTitle();
    }
};

Cfg.prototype.onFiltersChange = function (id, filters) {
    if (this.compilerId === id) {
        this._binaryFilter = filters.binary;
    }
};

Cfg.prototype.resize = function () {
    if (this.cfgVisualiser.canvas) {
        var height = this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true);
        this.cfgVisualiser.setSize('100%', height.toString());
        this.cfgVisualiser.redraw();
    }
};

Cfg.prototype.setTitle = function () {
    this.container.setTitle(this._compilerName + ' Graph Viewer (Editor #' + this._editorid + ', Compiler #' + this._compilerid + ')');
};

Cfg.prototype.showCfgResults = function (data) {
    this.cfgVisualiser.setData(data);
};

Cfg.prototype.onCompilerClose = function (compilerId) {
    if (this.compilerId === compilerId) {
        // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
        // the hierarchy. We can't modify while it's being iterated over.
        this.close();
        _.defer(function (self) {
            self.container.close();
        }, this);
    }
};

Cfg.prototype.close = function () {
    this.eventHub.unsubscribe();
    this.eventHub.emit('cfgViewClosed', this.compilerId);
    this.cfgVisualiser.destroy();
};

Cfg.prototype.saveState = function () {
    this.container.setState(this.currentState());
};

Cfg.prototype.currentState = function () {
    return {
        id: this.compilerId,
        editorid: this._editorid,
        selectedFn: this.currentFunc
    };
};

module.exports = {
    Cfg: Cfg
};

<commit_msg>Fix #819<commit_after>// Copyright (c) 2012-2018, Najjar Chedy
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

'use strict';

var $ = require('jquery');
var vis = require('vis');
var _ = require('underscore');

require('selectize');
require("vis/dist/vis.css");

function Cfg(hub, container, state) {
    this.container = container;
    this.eventHub = hub.createEventHub();
    this.domRoot = container.getElement();
    this.domRoot.html($('#cfg').html());
    this.defaultCfgOutput = {nodes: [{id: 0, shape: 'box', label: 'No Output'}], edges: []};
    this.binaryModeSupport = {
        nodes: [{
            id: 0,
            shape: 'box',
            label: 'Cfg mode cannot be used when the binary filter is set'
        }], edges: []
    };
    // Note that this might be outdated if no functions were present when creating the link, but that's handled
    // by selectize
    this.currentFunc = state.selectedFn || '';
    this.functions = [];
    this.networkOpts = {
        autoResize: true,
        locale: 'en',
        edges: {
            arrows: {to: {enabled: true}},
            smooth: {enabled: true},
            physics: false
        },
        nodes: {
            font: {face: 'monospace', align: 'left'}
        },
        layout: {
            improvedLayout: true,
            hierarchical: {
                enabled: true,
                sortMethod: 'directed',
                direction: 'UD',
                nodeSpacing: 100,
                levelSeparation: 150
            }
        },
        physics: {
            hierarchicalRepulsion: {
                nodeDistance: 125
            }
        },
        interaction: {
            navigationButtons: false,
            keyboard: {
                enabled: true,
                speed: {x: 10, y: 10, zoom: 0.03},
                bindToWindow: false
            }
        }
    };

    this.cfgVisualiser = new vis.Network(this.domRoot.find('.graph-placeholder')[0],
        this.defaultCfgOutput, this.networkOpts);
    this.domRoot.find('.show-hide-btn').on('click', _.bind(function () {
        this.networkOpts.interaction.navigationButtons = !this.networkOpts.interaction.navigationButtons;
        this.cfgVisualiser.setOptions(this.networkOpts);
    }, this));

    this.compilerId = state.id;
    this._editorid = state.editorid;
    this._binaryFilter = false;

    this.functionPicker = $(this.domRoot).find('.function-picker').selectize({
        sortField: 'name',
        valueField: 'name',
        labelField: 'name',
        searchField: ['name']
    }).on('change', _.bind(function (e) {
        var selectedFn = this.functions[e.target.value];
        if (selectedFn) {
            this.currentFunc = e.target.value;
            this.showCfgResults({
                nodes: selectedFn.nodes,
                edges: selectedFn.edges
            });
            this.cfgVisualiser.selectNodes([selectedFn.nodes[0].id]);
            this.saveState();
        }
    }, this));

    this.eventHub.on('compilerClose', this.onCompilerClose, this);
    this.eventHub.on('compileResult', this.onCompileResult, this);
    this.eventHub.on('compiler', this.onCompiler, this);
    this.eventHub.on('filtersChange', this.onFiltersChange, this);

    this.container.on('destroy', this.close, this);
    this.container.on('resize', this.resize, this);
    this.container.on('shown', this.resize, this);
    this.eventHub.emit('cfgViewOpened', this.compilerId);
    this.eventHub.emit('requestFilters', this.compilerId);
    this.eventHub.emit('requestCompiler', this.compilerId);

    this.adaptStructure = function (names) {
        return _.map(names, function (name) {
            return {name: name};
        });
    };

    this.setTitle();
}

Cfg.prototype.onCompileResult = function (id, compiler, result) {
    if (this.compilerId === id) {
        var functionNames = [];
        if (this.supportsCfg && !$.isEmptyObject(result.cfg)) {
            this.functions = result.cfg;
            functionNames = Object.keys(this.functions);
            if (functionNames.indexOf(this.currentFunc) === -1) {
                this.currentFunc = functionNames[0];
            }
            this.showCfgResults({
                nodes: this.functions[this.currentFunc].nodes,
                edges: this.functions[this.currentFunc].edges
            });
            this.cfgVisualiser.selectNodes([this.functions[this.currentFunc].nodes[0].id]);
        } else {
            // We don't reset the current function here as we would lose the saved one if this happened at the begining
            // (Hint: It *does* happen)
            this.showCfgResults(this._binaryFilter ? this.binaryModeSupport : this.defaultCfgOutput);
        }

        this.functionPicker[0].selectize.clearOptions();
        this.functionPicker[0].selectize.addOption(functionNames.length ? this.adaptStructure(functionNames) : {name: 'The input does not contain functions'});
        this.functionPicker[0].selectize.refreshOptions(false);

        this.functionPicker[0].selectize.clear();
        this.functionPicker[0].selectize.addItem(functionNames.length ? this.currentFunc : 'The input does not contain any function', true);
        this.saveState();
    }
};
Cfg.prototype.onCompiler = function (id, compiler) {
    if (id === this.compilerId) {
        this._compilerName = compiler ? compiler.name : '';
        this.supportsCfg = compiler.supportsCfg;
        this.setTitle();
    }
};

Cfg.prototype.onFiltersChange = function (id, filters) {
    if (this.compilerId === id) {
        this._binaryFilter = filters.binary;
    }
};

Cfg.prototype.resize = function () {
    if (this.cfgVisualiser.canvas) {
        var height = this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true);
        this.cfgVisualiser.setSize('100%', height.toString());
        this.cfgVisualiser.redraw();
    }
};

Cfg.prototype.setTitle = function () {
    this.container.setTitle(this._compilerName + ' Graph Viewer (Editor #' + this._editorid + ', Compiler #' + this.compilerId + ')');
};

Cfg.prototype.showCfgResults = function (data) {
    this.cfgVisualiser.setData(data);
};

Cfg.prototype.onCompilerClose = function (compilerId) {
    if (this.compilerId === compilerId) {
        // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
        // the hierarchy. We can't modify while it's being iterated over.
        this.close();
        _.defer(function (self) {
            self.container.close();
        }, this);
    }
};

Cfg.prototype.close = function () {
    this.eventHub.unsubscribe();
    this.eventHub.emit('cfgViewClosed', this.compilerId);
    this.cfgVisualiser.destroy();
};

Cfg.prototype.saveState = function () {
    this.container.setState(this.currentState());
};

Cfg.prototype.currentState = function () {
    return {
        id: this.compilerId,
        editorid: this._editorid,
        selectedFn: this.currentFunc
    };
};

module.exports = {
    Cfg: Cfg
};

<|endoftext|>


<commit_before>
/**
 * Exports the current runtime environment, by processing
 * the query-params of the URL (window.location.search
 *
 *  currently supported settings are
 *

 *
browser

 *
cordova

 *
android

 *
ios

 *

 *
 *  @exports {Object} a singleton object with information about the runtime setting:
 *
{
 *  			isBrowserEnv: [true|false],
 *  			isCordovaEnv: [true|false],
 *  			platform: ["browser" | "android" | "ios" | "default"],
 *  		}

 */
define(['mmirf/paramsParseFunc'], function(paramsParseFunc) {

	var ctx = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : typeof global !== 'undefined' ? global : this;
	var paramsStr = ctx && ctx.location? ctx.location.search : '?env=node';
	var params = paramsParseFunc( paramsStr );

	var isBrowserEnv;
	var isCordovaEnv;
	var isNodeEnv;
	var envSetting = '';
	var envParamSetting = '';

	if(typeof cordova !== 'undefined'){
		envSetting = cordova.platformId? cordova.platformId : envSetting;
		isCordovaEnv = true;
	}

	if(params.has('env')){

		envParamSetting = params['env'];
		envSetting = !envSetting? envParamSetting : envSetting;
	}

	if(envSetting){

		if(envSetting === 'browser'){
			isBrowserEnv = true;
		}
		else {
			isBrowserEnv = false;
		}

		if(envSetting === 'cordova' || envSetting === 'android' || envSetting === 'ios'){
			isCordovaEnv = true;
//			isBrowserEnv = false;
		}
		else {
			isCordovaEnv = false;
		}

		if(envSetting === 'node'){
			isNodeEnv = true;
		}
		else {
			isNodeEnv = false;
		}
	}
	else {
		isBrowserEnv = true;
		isCordovaEnv = false;
		isNodeEnv = false;
	}

	var env;
	if(isBrowserEnv){
		env = 'browser';
	} else {

		//if available, use plugin cordova-plugin-device for detecting specific env
		if(typeof device !== 'undefined' && device.platform){

			var platform = device.platform;
			if(/\bios\b/i.test(platform)){
				env = 'ios';
			} else if(/\bandroid\b/i.test(platform)){
				env = 'android';
			} else {//TODO handle other platforms
				console.warn('Unknown platform "'+platform+'"');
				env = 'default';
			}

		} else if(typeof navigator !== 'undefined') {

			//fallback: use UserAgent for detecting env
			var userAgent = navigator.userAgent;
			if(/(iPad|iPhone|iPod)/ig.test(userAgent)){
				env = 'ios';
			} else if(/android/i.test(userAgent)){
				env = 'android';
			} else {//TODO handle other platforms
				console.warn('Unknown platform for userAgent "'+userAgent+'"');
				env = 'default';
			}

		} else if(isNodeEnv) {
			env = 'node';
		} else {//TODO handle other platforms
			console.warn('Unknown platform');
			env = 'default';
		}

	}

	return {
		  isBrowserEnv: isBrowserEnv,
		  isCordovaEnv: isCordovaEnv,
		  isNodeEnv: isNodeEnv,
		  envSetting: envSetting,
		  platform: env
//		, params : params
	};
});
<commit_msg>added missing env value in js-doc<commit_after>
/**
 * Exports the current runtime environment, by processing
 * the query-params of the URL (window.location.search
 *
 *  currently supported settings are
 *

 *
browser

 *
cordova

 *
android

 *
ios

 *

 *
 *  @exports {Object} a singleton object with information about the runtime setting:
 *
{
 *  			isBrowserEnv: [true|false],
 *  			isCordovaEnv: [true|false],
 *  			platform: ["browser" | "android" | "ios" | "node" | "default"],
 *  		}

 */
define(['mmirf/paramsParseFunc'], function(paramsParseFunc) {

	var ctx = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : typeof global !== 'undefined' ? global : this;
	var paramsStr = ctx && ctx.location? ctx.location.search : '?env=node';
	var params = paramsParseFunc( paramsStr );

	var isBrowserEnv;
	var isCordovaEnv;
	var isNodeEnv;
	var envSetting = '';
	var envParamSetting = '';

	if(typeof cordova !== 'undefined'){
		envSetting = cordova.platformId? cordova.platformId : envSetting;
		isCordovaEnv = true;
	}

	if(params.has('env')){

		envParamSetting = params['env'];
		envSetting = !envSetting? envParamSetting : envSetting;
	}

	if(envSetting){

		if(envSetting === 'browser'){
			isBrowserEnv = true;
		}
		else {
			isBrowserEnv = false;
		}

		if(envSetting === 'cordova' || envSetting === 'android' || envSetting === 'ios'){
			isCordovaEnv = true;
//			isBrowserEnv = false;
		}
		else {
			isCordovaEnv = false;
		}

		if(envSetting === 'node'){
			isNodeEnv = true;
		}
		else {
			isNodeEnv = false;
		}
	}
	else {
		isBrowserEnv = true;
		isCordovaEnv = false;
		isNodeEnv = false;
	}

	var env;
	if(isBrowserEnv){
		env = 'browser';
	} else {

		//if available, use plugin cordova-plugin-device for detecting specific env
		if(typeof device !== 'undefined' && device.platform){

			var platform = device.platform;
			if(/\bios\b/i.test(platform)){
				env = 'ios';
			} else if(/\bandroid\b/i.test(platform)){
				env = 'android';
			} else {//TODO handle other platforms
				console.warn('Unknown platform "'+platform+'"');
				env = 'default';
			}

		} else if(typeof navigator !== 'undefined') {

			//fallback: use UserAgent for detecting env
			var userAgent = navigator.userAgent;
			if(/(iPad|iPhone|iPod)/ig.test(userAgent)){
				env = 'ios';
			} else if(/android/i.test(userAgent)){
				env = 'android';
			} else {//TODO handle other platforms
				console.warn('Unknown platform for userAgent "'+userAgent+'"');
				env = 'default';
			}

		} else if(isNodeEnv) {
			env = 'node';
		} else {//TODO handle other platforms
			console.warn('Unknown platform');
			env = 'default';
		}

	}

	return {
		  isBrowserEnv: isBrowserEnv,
		  isCordovaEnv: isCordovaEnv,
		  isNodeEnv: isNodeEnv,
		  envSetting: envSetting,
		  platform: env
//		, params : params
	};
});
<|endoftext|>


<commit_before>$(document).ready(function() {
    //Swap classes on nav tabs
    $('.tab').click(function () {
        $(this).siblings().removeClass('active')
        $(this).addClass('active')
    })

    //Swap graph time period
    $(".tab a").on("click", function() {
        var $anchor = $(this);
        if ($anchor.data('html-target') != undefined) {
            $('#' + $anchor.data('html-target') + ' img').show()
            if ($anchor.data('net-block-time') == undefined) {
                generate_worker_data($anchor.data('html-target'), $anchor.data('target'), $anchor.data('format'), $anchor.data('user'),
                    $anchor.data('worker'), $anchor.data('stat-type'));
            } else {
                generate_network_data($anchor.data('html-target'), $anchor.data('target'), $anchor.data('format'), $anchor.data('graph-type'),
                    $anchor.data('net-block-time'));
            }

        } else {
            $('#chart img').show()
            generate_data($anchor.data('target'), $anchor.data('format'), $anchor.data('user'));
        }
    });

    find_seconds = function(request_url) {
      var seconds;
      if (request_url == 'hour') {
        seconds = 60;
      } else if (request_url == 'day') {
        seconds = 300;
      } else if (request_url == 'month') {
        seconds = 3600;
      }
      return seconds
    }
});

generate_graph = function(request_url, date_format, user) {
  //Calculate the hash rate based on the number of diff-1 shares generated in a minute
    var calculate_hash = function(sharesPerMin, seconds) {
      var khashes = ((Math.pow(2, 16) * sharesPerMin)/seconds)/1000;
      return khashes
    }
  //Calculate a value to return for the y-scale, in khash or mhash
    var y_scale = function(max_hash, seconds) {
        return (calculate_hash(max_hash, seconds))/1000
    }
  //Calculate a value to return for the y-axis text, khash or mhash
    var generate_y_text = function(max_hash) {
        return "MHashes/sec"
    }

  var clean_data = [];
  var last_10min = 0;
  generate_data = function(request_url, date_format, user) {
    clean_data = [];
    d3.json('/' + user + '/stats/' + request_url, function(data) {
      start = data.start;
      end = data.end;
      step = data.step;
      for (var key in data.workers) {
        var worker = data.workers[key];
        var values = []
        for (var i = start; i <= end; i += step) {

          if (i in worker) {
            values.push([i * 1000, worker[i]]);
            //If this is an hour loop build a total value for last 10min
            if (i > (end - (10 * step)) &&  request_url == 'hour') {
              last_10min += worker[i];
            }
          } else {
            values.push([i * 1000, 0]);
          }
        }

        if (key == "")
          key = "[unnamed]";
          clean_data.push({key: key, seriesIndex: 0, values: values});
      }

      //set seconds to determine hashrate by
      var seconds = find_seconds(request_url);

      //Actually generate/regenerate the graph here
      nv.addGraph(window.generate_graph = function() {
        var chart = nv.models.stackedAreaChart()
                      .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                      .y(function(d) { return +y_scale(d[1], seconds) })   //...in case your data is formatted differently.
                      .useInteractiveGuideline(true)    //Tooltips which show all data points. Very nice!
                      .transitionDuration(500)
                      .showControls(true)       //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode.
                      .clipEdge(true);

        // Format x-axis labels with custom function.
        chart.xAxis
            .tickFormat(function(d) { return d3.time.format(date_format)(new Date(d)) })
            .scale(d3.time.scale())
            .axisLabel('Time')
            .axisLabelDistance(30);;

        chart.yAxis
            .tickFormat(d3.format(',.2f'))
            .axisLabel('MHash/sec')
            .axisLabelDistance(30);

        d3.select('#chart svg')
          .datum(clean_data)
          .call(chart);

        $('#chart img').hide()

        //Hack to update chart when click event occurs
        $(".nv-stackedAreaChart").on("click", function() {
            chart.update();
        });

        nv.utils.windowResize(chart.update);
      });
    });
  }

  // Initial graph generation
  generate_data(request_url, date_format, user);
}

generate_worker_graph = function(target, request_url, date_format, user, worker, stat_type) {

  var clean_data = [];
  generate_worker_data = function(target, request_url, date_format, user, worker, stat_type) {
    clean_data = [];
    d3.json('/' + user + '/' + worker + '/' + stat_type + '/' + request_url, function(data) {

      start = data.start;
      end = data.end;
      step = data.step;
      var values_no_stamp = []
      for (var key in data.workers) {
        var worker = data.workers[key];
        var values = [];

        for (var i = start; i <= end; i += step) {
          if (i in worker) {
            if (worker[i] < 0){ worker[i] = 0; }
            values.push([i * 1000, worker[i]]);
            values_no_stamp.push(worker[i]);
          } else {
            values.push([i * 1000, 0]);
          }
        }

        if (key == "")
          key = "[unnamed]";
          clean_data.push({key: key, seriesIndex: 0, values: values});
      }

      //set seconds to determine hashrate by
      var seconds = find_seconds(request_url);

      //Actually generate/regenerate the graph here
      nv.addGraph(window.generate_graph = function() {
      if (stat_type == 'temp') {
        var chart = nv.models.lineChart()
                      .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                      .y(function(d) { return d[1] })   //...in case your data is formatted differently.
                    .useInteractiveGuideline(true)  //We want nice looking tooltips and a guideline!
                    .transitionDuration(350)  //how fast do you want the lines to transition?
                    .clipEdge(true);

        var axis_label = 'Temperature';

      } else {
        var chart = nv.models.stackedAreaChart()
                      .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                      .y(function(d) { return d[1]/1000 })   //...in case your data is formatted differently.
                      .useInteractiveGuideline(true)    //Tooltips which show all data points. Very nice!
                      .transitionDuration(500)
                      .showControls(true)       //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode.
                      .clipEdge(true);
        var axis_label = 'KHash/sec';
      }

        // Format x-axis labels with custom function.
        chart.xAxis
            .tickFormat(function(d) { return d3.time.format(date_format)(new Date(d)) })
            .scale(d3.time.scale())
            .axisLabel('Time')
            .axisLabelDistance(30);

        chart.yAxis
            .tickFormat(d3.format(',.2f'))
            .axisLabel(axis_label)
            .axisLabelDistance(25);

        chart.forceY([0, d3.max(values_no_stamp)*1.1 ]);

        d3.select('#' + target + ' svg')
          .datum(clean_data)
          .call(chart);

        $('#' + target + ' img').hide()

        //Hack to update chart when click event occurs
        $(".nv-stackedAreaChart").on("click", function() {
            chart.update();
        });

        nv.utils.windowResize(chart.update);
      });
    });
  }

  // Initial graph generation
  generate_worker_data(target, request_url, date_format, user, worker, stat_type);

}

generate_network_graph = function(target, request_url, date_format, graph_type, network_block_time) {

  var clean_data = [];
  generate_network_data = function(target, request_url, date_format, graph_type, network_block_time) {
    clean_data = [];
    d3.json('/network_stats/' + graph_type + '/' + request_url, function(data) {

      start = data.start;
      end = data.end;
      step = data.step;
      var values_no_stamp = []
      for (var key in data.workers) {
        var worker = data.workers[key];
        var values = [];

        var x;
        for (x in worker) {
          values.push([x * 1000, worker[x]/1000]);
        }

        if (key == "")
          key = "[unnamed]";
        if (network_block_time > 0)
          key = 'nethash';
          clean_data.push({key: key, seriesIndex: 0, values: values});
      }

      //set seconds to determine hashrate by
      var seconds = find_seconds(request_url);

      //Actually generate/regenerate the graph here
      nv.addGraph(window.generate_graph = function() {

      // if a block time is passed in, lets get ready to return a calculated hashrate
      // rather than a difficulty
      var multiplier = 1;

      if (network_block_time > 0) {
        multiplier = Math.pow(2, 32) / network_block_time
        var chart = nv.models.stackedAreaChart()
                      .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                      .y(function(d) { return (d[1] * multiplier)/1000000 })   //...in case your data is formatted differently.
                      .useInteractiveGuideline(true)    //Tooltips which show all data points. Very nice!
                      .transitionDuration(500)
                      .showControls(true)       //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode.
                      .clipEdge(true);
        var axis_label = 'MHash/sec';
      } else {
          var chart = nv.models.lineChart()
                        .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                        .y(function(d) { return d[1] })   //...in case your data is formatted differently.
                        .useInteractiveGuideline(true)  //We want nice looking tooltips and a guideline!
                        .transitionDuration(350)  //how fast do you want the lines to transition?
                        .clipEdge(true);

          var axis_label = 'Network Difficulty';
      }

        // Format x-axis labels with custom function.
        chart.xAxis
            .tickFormat(function(d) { return d3.time.format(date_format)(new Date(d)) })
            .scale(d3.time.scale())
            .axisLabel('Time')
            .axisLabelDistance(30);

        chart.yAxis
            .tickFormat(d3.format(',.2f'))
            .axisLabel(axis_label)
            .axisLabelDistance(25);

        chart.forceY([0, d3.max(values_no_stamp)*1.1 ]);

        d3.select('#' + target + ' svg')
          .datum(clean_data)
          .call(chart);

        $('#' + target + ' img').hide()

        nv.utils.windowResize(chart.update);
      });
    });
  }

  // Initial graph generation
  generate_network_data(target, request_url, date_format, graph_type, network_block_time);

}
<commit_msg>Y Axis to be calculated by min-max with padding<commit_after>$(document).ready(function() {
    //Swap classes on nav tabs
    $('.tab').click(function () {
        $(this).siblings().removeClass('active')
        $(this).addClass('active')
    })

    //Swap graph time period
    $(".tab a").on("click", function() {
        var $anchor = $(this);
        if ($anchor.data('html-target') != undefined) {
            $('#' + $anchor.data('html-target') + ' img').show()
            if ($anchor.data('net-block-time') == undefined) {
                generate_worker_data($anchor.data('html-target'), $anchor.data('target'), $anchor.data('format'), $anchor.data('user'),
                    $anchor.data('worker'), $anchor.data('stat-type'));
            } else {
                generate_network_data($anchor.data('html-target'), $anchor.data('target'), $anchor.data('format'), $anchor.data('graph-type'),
                    $anchor.data('net-block-time'));
            }

        } else {
            $('#chart img').show()
            generate_data($anchor.data('target'), $anchor.data('format'), $anchor.data('user'));
        }
    });

    find_seconds = function(request_url) {
      var seconds;
      if (request_url == 'hour') {
        seconds = 60;
      } else if (request_url == 'day') {
        seconds = 300;
      } else if (request_url == 'month') {
        seconds = 3600;
      }
      return seconds
    }
});

generate_graph = function(request_url, date_format, user) {
  //Calculate the hash rate based on the number of diff-1 shares generated in a minute
    var calculate_hash = function(sharesPerMin, seconds) {
      var khashes = ((Math.pow(2, 16) * sharesPerMin)/seconds)/1000;
      return khashes
    }
  //Calculate a value to return for the y-scale, in khash or mhash
    var y_scale = function(max_hash, seconds) {
        return (calculate_hash(max_hash, seconds))/1000
    }
  //Calculate a value to return for the y-axis text, khash or mhash
    var generate_y_text = function(max_hash) {
        return "MHashes/sec"
    }

  var clean_data = [];
  var last_10min = 0;
  generate_data = function(request_url, date_format, user) {
    clean_data = [];
    d3.json('/' + user + '/stats/' + request_url, function(data) {
      start = data.start;
      end = data.end;
      step = data.step;
      for (var key in data.workers) {
        var worker = data.workers[key];
        var values = []
        for (var i = start; i <= end; i += step) {

          if (i in worker) {
            values.push([i * 1000, worker[i]]);
            //If this is an hour loop build a total value for last 10min
            if (i > (end - (10 * step)) &&  request_url == 'hour') {
              last_10min += worker[i];
            }
          } else {
            values.push([i * 1000, 0]);
          }
        }

        if (key == "")
          key = "[unnamed]";
          clean_data.push({key: key, seriesIndex: 0, values: values});
      }

      //set seconds to determine hashrate by
      var seconds = find_seconds(request_url);

      //Actually generate/regenerate the graph here
      nv.addGraph(window.generate_graph = function() {
        var chart = nv.models.stackedAreaChart()
                      .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                      .y(function(d) { return +y_scale(d[1], seconds) })   //...in case your data is formatted differently.
                      .useInteractiveGuideline(true)    //Tooltips which show all data points. Very nice!
                      .transitionDuration(500)
                      .showControls(true)       //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode.
                      .clipEdge(true);

        // Format x-axis labels with custom function.
        chart.xAxis
            .tickFormat(function(d) { return d3.time.format(date_format)(new Date(d)) })
            .scale(d3.time.scale())
            .axisLabel('Time')
            .axisLabelDistance(30);;

        chart.yAxis
            .tickFormat(d3.format(',.2f'))
            .axisLabel('MHash/sec')
            .axisLabelDistance(30);

        d3.select('#chart svg')
          .datum(clean_data)
          .call(chart);

        $('#chart img').hide()

        //Hack to update chart when click event occurs
        $(".nv-stackedAreaChart").on("click", function() {
            chart.update();
        });

        nv.utils.windowResize(chart.update);
      });
    });
  }

  // Initial graph generation
  generate_data(request_url, date_format, user);
}

generate_worker_graph = function(target, request_url, date_format, user, worker, stat_type) {

  var clean_data = [];
  generate_worker_data = function(target, request_url, date_format, user, worker, stat_type) {
    clean_data = [];
    d3.json('/' + user + '/' + worker + '/' + stat_type + '/' + request_url, function(data) {

      start = data.start;
      end = data.end;
      step = data.step;
      var values_no_stamp = []
      for (var key in data.workers) {
        var worker = data.workers[key];
        var values = [];

        for (var i = start; i <= end; i += step) {
          if (i in worker) {
            if (worker[i] < 0){ worker[i] = 0; }
            values.push([i * 1000, worker[i]]);
            values_no_stamp.push(worker[i]);
          } else {
            values.push([i * 1000, 0]);
          }
        }

        if (key == "")
          key = "[unnamed]";
          clean_data.push({key: key, seriesIndex: 0, values: values});
      }

      //set seconds to determine hashrate by
      var seconds = find_seconds(request_url);

      //Actually generate/regenerate the graph here
      nv.addGraph(window.generate_graph = function() {
      if (stat_type == 'temp') {
        var chart = nv.models.lineChart()
                      .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                      .y(function(d) { return d[1] })   //...in case your data is formatted differently.
                    .useInteractiveGuideline(true)  //We want nice looking tooltips and a guideline!
                    .transitionDuration(350)  //how fast do you want the lines to transition?
                    .clipEdge(true);

        var axis_label = 'Temperature';

      } else {
        var chart = nv.models.stackedAreaChart()
                      .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                      .y(function(d) { return d[1]/1000 })   //...in case your data is formatted differently.
                      .useInteractiveGuideline(true)    //Tooltips which show all data points. Very nice!
                      .transitionDuration(500)
                      .showControls(true)       //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode.
                      .clipEdge(true);
        var axis_label = 'KHash/sec';
      }

        // Format x-axis labels with custom function.
        chart.xAxis
            .tickFormat(function(d) { return d3.time.format(date_format)(new Date(d)) })
            .scale(d3.time.scale())
            .axisLabel('Time')
            .axisLabelDistance(30);

        chart.yAxis
            .tickFormat(d3.format(',.2f'))
            .axisLabel(axis_label)
            .axisLabelDistance(25);

        chart.forceY([0, d3.max(values_no_stamp)*1.1 ]);

        d3.select('#' + target + ' svg')
          .datum(clean_data)
          .call(chart);

        $('#' + target + ' img').hide()

        //Hack to update chart when click event occurs
        $(".nv-stackedAreaChart").on("click", function() {
            chart.update();
        });

        nv.utils.windowResize(chart.update);
      });
    });
  }

  // Initial graph generation
  generate_worker_data(target, request_url, date_format, user, worker, stat_type);

}

generate_network_graph = function(target, request_url, date_format, graph_type, network_block_time) {

  var clean_data = [];
  generate_network_data = function(target, request_url, date_format, graph_type, network_block_time) {
    clean_data = [];
    d3.json('/network_stats/' + graph_type + '/' + request_url, function(data) {

      start = data.start;
      end = data.end;
      step = data.step;
      var values_no_stamp = []
      for (var key in data.workers) {
        var worker = data.workers[key];
        var values = [];

        var x;
        for (x in worker) {
          values.push([x * 1000, worker[x]/1000]);
        }

        if (key == "")
          key = "[unnamed]";
        if (network_block_time > 0)
          key = 'nethash';
          clean_data.push({key: key, seriesIndex: 0, values: values});
      }

      //set seconds to determine hashrate by
      var seconds = find_seconds(request_url);

      //Actually generate/regenerate the graph here
      nv.addGraph(window.generate_graph = function() {

      // if a block time is passed in, lets get ready to return a calculated hashrate
      // rather than a difficulty
      var multiplier = 1;

      if (network_block_time > 0) {
        multiplier = Math.pow(2, 32) / network_block_time
        var chart = nv.models.stackedAreaChart()
                      .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                      .y(function(d) { return (d[1] * multiplier)/1000000 })   //...in case your data is formatted differently.
                      .useInteractiveGuideline(true)    //Tooltips which show all data points. Very nice!
                      .transitionDuration(500)
                      .showControls(true)       //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode.
                      .clipEdge(true);
        var axis_label = 'MHash/sec';
      } else {
          var chart = nv.models.lineChart()
                        .x(function(d) { return d[0] })   //We can modify the data accessor functions...
                        .y(function(d) { return d[1] })   //...in case your data is formatted differently.
                        .useInteractiveGuideline(true)  //We want nice looking tooltips and a guideline!
                        .transitionDuration(350)  //how fast do you want the lines to transition?
                        .clipEdge(true);

          var axis_label = 'Network Difficulty';
      }

        // Format x-axis labels with custom function.
        chart.xAxis
            .tickFormat(function(d) { return d3.time.format(date_format)(new Date(d)) })
            .scale(d3.time.scale())
            .axisLabel('Time')
            .axisLabelDistance(30);

        chart.yAxis
            .tickFormat(d3.format(',.2f'))
            .axisLabel(axis_label)
            .axisLabelDistance(25);

        chart.forceY([d3.min(clean_data[0].values, function(d) { return d[1]; })*0.95,
                d3.max(clean_data[0].values, function(d) { return d[1]; })*1.05]);

        d3.select('#' + target + ' svg')
          .datum(clean_data)
          .call(chart);

        $('#' + target + ' img').hide()

        nv.utils.windowResize(chart.update);
      });
    });
  }

  // Initial graph generation
  generate_network_data(target, request_url, date_format, graph_type, network_block_time);

}
<|endoftext|>


<commit_before>(function () {

var jqueryNoConflict = jQuery;
var currentTheme = 'default';
var templateDir = './static/templates/'+currentTheme+'/';

jqueryNoConflict(document).ready(function () {
  registerHelpers();
  retriveData();
  registerEvents();
});

function hbsDebug (optionalValue) {
  console.log('Current Context');
  console.log('====================');
  console.log(this);
}

function hbsJoin (array, sep, options) {
  if (array)
    return array.map(function(item) {
      return options.fn(item);
    }).join(sep);
}

function hbsBuildDateRange (_meta, enc) {
  var s = '';

  if (!(typeof(enc) == 'string' && enc.length == 2)) {
    enc = null;
  }

  if (_meta.dateEnded != null) {
    s = _meta.dateStarted + '–' + _meta.dateEnded;
  } else {
    s = _meta.dateStarted;
  }

  if (s) {
    if (enc != null)
      return enc[0] + '' + s + '' + enc[1];
    else
      return '' + s + '';
  } else {
    return '';
  }
}

function hbsBuildPosition (_meta) {
  if (_meta.position && _meta.department)
    return _meta.position + ', ' + _meta.department;
  else
    return _meta.position;
}

function hbsBuildSubtitle (_meta, ignore) {
  if (!(typeof(ignore) == 'object' && ignore.length > 0)) {
    ignore = [];
  }

  var array = [];
  if (_meta.position && ignore.indexOf('position') != 0)
    array.push(hbsBuildPosition(_meta));
  if (_meta.dateStarted && ignore.indexOf('date') != 0)
    array.push(hbsBuildDateRange(_meta));
  if (_meta.address && ignore.indexOf('address') != 0)
    array.push(_meta.address);
  if (_meta.technologies && ignore.indexOf('technologies') != 0)
    array.push('Technologies used: ' + _meta.technologies.join(", "));

  return array.join(" | ");
}

function retriveData () {
  var dataSource = './static/data.json';
  jqueryNoConflict.getJSON(dataSource, renderThemeTemplate);
}

function renderThemeTemplate (data) {
  includeThemeStyles();
  renderHandlebarsTemplate(templateDir + 'content.hbs', '#content', data);
}

function getTemplateAjax (path, callback) {
  var source, template;
  jqueryNoConflict.ajax({
    url: path,
    success: function (data) {
        source = data;
        template = Handlebars.compile(source);
        if (callback) callback(template);
    }
  });
}

function renderHandlebarsTemplate (withTemplate, inElement, withData) {
  document.title = 'Curriculum Vitae – ' + withData.personalDetails.title || 'Curriculum Vitae';
  getTemplateAjax(withTemplate, function(template) {
    jqueryNoConflict(inElement).html(template(withData));
  });
}

function registerEvents () {
  // NOTE: removed for now
  // jqueryNoConflict(document).on('click', '.section-title', function (e) {
  //   var sectionTitle, content;
  //   sectionTitle = $(this);
  //   content = sectionTitle.next();
  //   content.slideToggle(750, function () {});
  // });
}

function registerHelpers () {
  Handlebars.registerHelper('join', hbsJoin);
  Handlebars.registerHelper('debug', hbsDebug);
  Handlebars.registerHelper('buildDateRange', hbsBuildDateRange);
  Handlebars.registerHelper('buildPosition', hbsBuildPosition);
  Handlebars.registerHelper('buildSubtitle', hbsBuildSubtitle);
}

function includeThemeStyles () {
  jqueryNoConflict('head').append('<link rel="stylesheet" type="text/css" media="screen" href="' + templateDir + 'screen.css">');
  jqueryNoConflict('head').append('<link rel="stylesheet" type="text/css" media="print" href="' + templateDir + 'print.css">');
}

function downloadFile () {
  var element = document.getElementById('content');

  html2pdf(element, {
    margin: 0,
    filename: 'njncalub - cv.pdf',
    enableLinks: false,
    image: {type: 'jpeg', quality: 1},
    html2canvas: {
      dpi: 300,
      width: 1000,
      letterRendering: true
    },
    jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
  });
}

window.downloadFile = downloadFile;

}());
<commit_msg>Updated index file.<commit_after>(function() {
  var jqueryNoConflict = jQuery;
  var currentTheme = "default";
  var templateDir = "./static/templates/" + currentTheme + "/";

  jqueryNoConflict(document).ready(function() {
    registerHelpers();
    retriveData();
    registerEvents();
  });

  function hbsDebug(optionalValue) {
    console.log("Current Context");
    console.log("====================");
    console.log(this);
  }

  function hbsJoin(array, sep, options) {
    if (array)
      return array
        .map(function(item) {
          return options.fn(item);
        })
        .join(sep);
  }

  function hbsBuildDateRange(_meta, enc) {
    var s = "";

    if (!(typeof enc == "string" && enc.length == 2)) {
      enc = null;
    }

    if (_meta.dateEnded != null) {
      s = _meta.dateStarted + "–" + _meta.dateEnded;
    } else {
      s = _meta.dateStarted;
    }

    if (s) {
      if (enc != null)
        return enc[0] + '' + s + "" + enc[1];
      else return '' + s + "";
    } else {
      return "";
    }
  }

  function hbsBuildPosition(_meta) {
    if (_meta.position && _meta.department)
      return _meta.position + ", " + _meta.department;
    else return _meta.position;
  }

  function hbsBuildSubtitle(_meta, ignore) {
    if (!(typeof ignore == "object" && ignore.length > 0)) {
      ignore = [];
    }

    var array = [];
    if (_meta.position && ignore.indexOf("position") != 0)
      array.push(hbsBuildPosition(_meta));
    if (_meta.dateStarted && ignore.indexOf("date") != 0)
      array.push(hbsBuildDateRange(_meta));
    if (_meta.address && ignore.indexOf("address") != 0)
      array.push(_meta.address);
    if (_meta.technologies && ignore.indexOf("technologies") != 0)
      array.push("Technologies used: " + _meta.technologies.join(", "));

    return array.join(" | ");
  }

  function retriveData() {
    var dataSource = "./static/data.json";
    jqueryNoConflict.getJSON(dataSource, renderThemeTemplate);
  }

  function renderThemeTemplate(data) {
    includeThemeStyles();
    renderHandlebarsTemplate(templateDir + "content.hbs", "#content", data);
  }

  function getTemplateAjax(path, callback) {
    var source, template;
    jqueryNoConflict.ajax({
      url: path,
      success: function(data) {
        source = data;
        template = Handlebars.compile(source);
        if (callback) callback(template);
      }
    });
  }

  function renderHandlebarsTemplate(withTemplate, inElement, withData) {
    document.title =
      "Curriculum Vitae – " + withData.personalDetails.title ||
      "Curriculum Vitae";
    getTemplateAjax(withTemplate, function(template) {
      jqueryNoConflict(inElement).html(template(withData));
    });
  }

  function registerEvents() {
    jqueryNoConflict(document).on("click", ".section-title", function(e) {
      var sectionTitle, content;
      sectionTitle = $(this);
      content = sectionTitle.next();
      content.slideToggle(750, function() {});
    });
  }

  function registerHelpers() {
    Handlebars.registerHelper("join", hbsJoin);
    Handlebars.registerHelper("debug", hbsDebug);
    Handlebars.registerHelper("buildDateRange", hbsBuildDateRange);
    Handlebars.registerHelper("buildPosition", hbsBuildPosition);
    Handlebars.registerHelper("buildSubtitle", hbsBuildSubtitle);
  }

  function includeThemeStyles() {
    jqueryNoConflict("head").append(
      '<link rel="stylesheet" type="text/css" media="screen" href="' +
        templateDir +
        'screen.css">'
    );
    jqueryNoConflict("head").append(
      '<link rel="stylesheet" type="text/css" media="print" href="' +
        templateDir +
        'print.css">'
    );
  }

  function downloadFile() {
    var element = document.getElementById("content");

    html2pdf(element, {
      margin: 0,
      filename: "njncalub - cv.pdf",
      enableLinks: false,
      image: { type: "jpeg", quality: 1 },
      html2canvas: {
        dpi: 300,
        width: 1000,
        letterRendering: true
      },
      jsPDF: { unit: "in", format: "letter", orientation: "portrait" }
    });
  }

  window.downloadFile = downloadFile;
})();
<|endoftext|>


<commit_before>var selected_classifier = "";

function showSnackbar(message) {
	// Get the snackbar DIV
	var snackbar = document.getElementById("snackbar")

	// Add the "show" class to DIV
	snackbar.className = "show";
	snackbar.textContent = message

	// After 3 seconds, remove the show class from DIV
	setTimeout(function () { snackbar.className = snackbar.className.replace("show", ""); }, 5000);
}

var query = function (queryText, category) {
	var package = {}
	package['queryText'] = queryText;
	package['category'] = category;

	var url = "/api/query";

	$.ajax({
		type: "POST",
		url: url,
		data: JSON.stringify(package),
		dataType: 'json',
		contentType: 'application/json; charset=utf-8',
		success: function (result) {

			var wrapper_object = JSON.parse(result.result);

			// If the Watson NLC was able to correctly classify the request, then it will just return html
			if (wrapper_object['error'].length > 0) {
				showSnackbar(wrapper_object['error']);
			} else {
				if (wrapper_object['html'].length > 0) {
					for (var i = 1; i < wrapper_object['html'].length + 1; i++) {
						var resulttag = '#result' + i;
						var collapsetag = '#collapseheader' + i;
						var rawHTML = wrapper_object['html'][i - 1];
						rawHTML = rawHTML.substring(4);
						var end = rawHTML.indexOf('<');
						if (end > 50){
							end = 50;
							rawHTML = rawHTML.substring(0, end);
							rawHTML = rawHTML+ "..."
						}else{
							rawHTML = rawHTML.substring(0, end);
						}
						$(collapsetag).html(rawHTML+"
");
						$(resulttag).html(wrapper_object['html'][i - 1]);

					}
					$("#response").hide();
					$(" #accordion").show();
				}
				//Otherwise we need to some logic to populate and show the dropdown box
				//to let the user choose a category for their query
				else {
					$("#category-dropdown-button").show();
					$("#response").show();
					$("#accordion").hide();

					var outstring = "
To clarify your results, please pick a category from the box on the right.
"
					$("#category-dropdown").empty()
					for (var i = 0; i < wrapper_object['categories'].length; i++) {
						category = wrapper_object['categories'][i]
						$("#category-dropdown").append('' + category + '');
					}
					$("#result0").html(outstring);
				}
			}

			$("#result-container").show();
			$("#query-text").removeAttr("disabled");

		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			$("#query-text").removeAttr("disabled");
			showSnackbar('Error while searching for request');
		}
	});
}

$(document).ready(function () {

	$("#category-dropdown-button").hide();
	$("#response").hide();
	$("#submit-search").click(function () {
		console.log('Search Sent with classifier ' + selected_classifier);

		var queryText = $('#query-text').val();
		var category = selected_classifier;

		$("#query-text").attr("disabled", "disabled");

		query(queryText, category);

	});

	$('#query-text').keypress(function (e) {
		if (e.which == 13) {//Enter key pressed
			$('#submit-search').click();//Trigger search button click event
		}
	});

	//Need to set this super basic function to track which value of the dropdown was last selected
	//this will let the parent of the list objects (really  elements) delegate the function
	//which we need since the 's are dynamically generated.
	$("#category-dropdown").on('click', 'a', function (event) {
		selected_classifier = $(this).text();
		var queryText = $("#query-text").val();
		query(queryText, selected_classifier);
		selected_classifier = "";
	});

});
<commit_msg>Trying<commit_after>var selected_classifier = "";

function showSnackbar(message) {
	// Get the snackbar DIV
	var snackbar = document.getElementById("snackbar")

	// Add the "show" class to DIV
	snackbar.className = "show";
	snackbar.textContent = message

	// After 3 seconds, remove the show class from DIV
	setTimeout(function () { snackbar.className = snackbar.className.replace("show", ""); }, 5000);
}

var query = function (queryText, category) {
	var package = {}
	package['queryText'] = queryText;
	package['category'] = category;

	var url = "/api/query";

	$.ajax({
		type: "POST",
		url: url,
		data: JSON.stringify(package),
		dataType: 'json',
		contentType: 'application/json; charset=utf-8',
		success: function (result) {

			var wrapper_object = JSON.parse(result.result);

			// If the Watson NLC was able to correctly classify the request, then it will just return html
			if (wrapper_object['error'].length > 0) {
				showSnackbar(wrapper_object['error']);
			} else {
				if (wrapper_object['html'].length > 0) {
					$('#result1').html("");
					$('#result2').html("");
					$('#result3').html("");
					$('#collapseheader1').html("");
					$('#collapseheader2').html("");
					$('#collapseheader3').html("");
					for (var i = 1; i < wrapper_object['html'].length + 1; i++) {
						var resulttag = '#result' + i;
						var collapsetag = '#collapseheader' + i;
						var rawHTML = wrapper_object['html'][i - 1];
						rawHTML = rawHTML.substring(4);
						var end = rawHTML.indexOf('<');
						if (end > 50){
							end = 50;
							rawHTML = rawHTML.substring(0, end);
							rawHTML = rawHTML+ "..."
						}else{
							rawHTML = rawHTML.substring(0, end);
						}
						$(collapsetag).html(rawHTML+"
");
						$(resulttag).html(wrapper_object['html'][i - 1]);

					}
					$("#response").hide();
					$("#accordion").show();
				}
				//Otherwise we need to some logic to populate and show the dropdown box
				//to let the user choose a category for their query
				else {
					$("#category-dropdown-button").show();
					$("#response").show();
					$("#accordion").hide();

					var outstring = "
To clarify your results, please pick a category from the box on the right.
"
					$("#category-dropdown").empty()
					for (var i = 0; i < wrapper_object['categories'].length; i++) {
						category = wrapper_object['categories'][i]
						$("#category-dropdown").append('' + category + '');
					}
					$("#result0").html(outstring);
				}
			}

			$("#result-container").show();
			$("#query-text").removeAttr("disabled");

		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			$("#query-text").removeAttr("disabled");
			showSnackbar('Error while searching for request');
		}
	});
}

$(document).ready(function () {

	$("#category-dropdown-button").hide();
	$("#response").hide();
	$("#submit-search").click(function () {
		console.log('Search Sent with classifier ' + selected_classifier);

		var queryText = $('#query-text').val();
		var category = selected_classifier;

		$("#query-text").attr("disabled", "disabled");

		query(queryText, category);

	});

	$('#query-text').keypress(function (e) {
		if (e.which == 13) {//Enter key pressed
			$('#submit-search').click();//Trigger search button click event
		}
	});

	//Need to set this super basic function to track which value of the dropdown was last selected
	//this will let the parent of the list objects (really  elements) delegate the function
	//which we need since the 's are dynamically generated.
	$("#category-dropdown").on('click', 'a', function (event) {
		selected_classifier = $(this).text();
		var queryText = $("#query-text").val();
		query(queryText, selected_classifier);
		selected_classifier = "";
	});

});
<|endoftext|>