<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import {validator as v} from 'redux-router-querystring';

export const queryString = {
    recurrence: {
        validator: v.isIn(['single', 'daily', 'every']),
        stateField: 'filters.recurrence.type'
    },
    number: {
        validator: v.isInt({min: 1, max: 99}),
        sanitizer: v.toInt(),
        stateField: 'filters.recurrence.number'
    },
    interval: {
        validator: v.isIn(['day', 'week', 'month']),
        stateField: 'filters.recurrence.interval'
    },
    startDate: {
        validator: v.isDate(),
        stateField: 'filters.dates.startDate'
    },
    endDate: {
        validator: v.isDate(),
        stateField: 'filters.dates.endDate'
    },
    startTime: {
        validator: v.isTime(),
        stateField: 'filters.timeSlot.startTime'
    },
    endTime: {
        validator: v.isTime(),
        stateField: 'filters.timeSlot.endTime'
    },
    favorite: {
        validator: v.isBoolean(),
        sanitizer: v.toBoolean(),
        stateField: 'filters.onlyFavorites'
    },
    capacity: {
        validator: v.isInt({min: 1}),
        sanitizer: v.toInt(),
        stateField: 'filters.capacity'
    },
    building: {
        validator: v.isInt(),
        sanitizer: v.toInt(),
        stateField: 'filters.building'
    },
    floor: {
        stateField: 'filters.floor'
    },
    text: {
        stateField: 'filters.text'
    },
    SWLat: {
        validator: v.isFloat({min: -90, max: 90}),
        sanitizer: v.toFloat(),
        stateField: 'filters.bounds.SW[0]'
    },
    SWLng: {
        validator: v.isFloat({min: -180, max: 180}),
        sanitizer: v.toFloat(),
        stateField: 'filters.bounds.SW[1]'
    },
    NELat: {
        validator: v.isFloat({min: -90, max: 90}),
        sanitizer: v.toFloat(),
        stateField: 'filters.bounds.NE[0]'
    },
    NELng: {
        validator: v.isFloat({min: -180, max: 180}),
        sanitizer: v.toFloat(),
        stateField: 'filters.bounds.NE[1]'
    }
};

const _dtHandler = (prefix) => {
    return function({dates, timeSlot}) {
        const timePart = timeSlot[`${prefix}Time`];
        let datePart = dates[`${prefix}Date`];

        // single bookings have a 'null' endDate
        if (datePart === null && prefix === 'end') {
            datePart = dates['startDate'];
        }

        return moment(`${datePart} ${timePart}`, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm');
    };
};

export const ajax = {
    repeat_frequency: {
        onlyIf: (data) => 'recurrence' in data,
        serializer: ({recurrence: {type, interval}}) => {
            if (type === 'single') {
                return 'NEVER';
            } else if (type === 'daily') {
                return 'DAY';
            } else {
                return {
                    daily: 'DAY',
                    week: 'WEEK',
                    month: 'MONTH'
                }[interval];
            }
        }
    },
    repeat_interval: {
        onlyIf: (data) => 'recurrence' in data,
        serializer: ({recurrence: {type, number}}) => {
            if (type === 'single') {
                return 0;
            } else if (type === 'daily') {
                return 1;
            } else {
                return number;
            }
        }
    },
    capacity: ({capacity}) => capacity,
    favorite: {
        onlyIf: ({onlyFavorites}) => onlyFavorites,
        serializer: ({onlyFavorites}) => onlyFavorites,
    },
    building: ({building}) => building,
    floor: ({floor}) => floor,
    text: ({text}) => text,
    start_dt: {
        onlyIf: (data) => data.dates && data.dates.startDate,
        serializer: _dtHandler('start')
    },
    end_dt: {
        onlyIf: (data) => data.dates && data.dates.endDate,
        serializer: _dtHandler('end')
    },
    sw_lat: {
        onlyIf: (data) => data.bounds && 'SW' in data.bounds,
        serializer: ({bounds: {SW}}) => SW[0]
    },
    sw_lng: {
        onlyIf: (data) => data.bounds && 'SW' in data.bounds,
        serializer: ({bounds: {SW}}) => SW[1]
    },
    ne_lat: {
        onlyIf: (data) => data.bounds && 'NE' in data.bounds,
        serializer: ({bounds: {NE}}) => NE[0]
    },
    ne_lng: {
        onlyIf: (data) => data.bounds && 'NE' in data.bounds,
        serializer: ({bounds: {NE}}) => NE[1]
    }
};
<commit_msg>Use more compact query string param names<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import {validator as v} from 'redux-router-querystring';

export const queryString = {
    recurrence: {
        validator: v.isIn(['single', 'daily', 'every']),
        stateField: 'filters.recurrence.type'
    },
    number: {
        validator: v.isInt({min: 1, max: 99}),
        sanitizer: v.toInt(),
        stateField: 'filters.recurrence.number'
    },
    interval: {
        validator: v.isIn(['day', 'week', 'month']),
        stateField: 'filters.recurrence.interval'
    },
    sd: {
        validator: v.isDate(),
        stateField: 'filters.dates.startDate'
    },
    ed: {
        validator: v.isDate(),
        stateField: 'filters.dates.endDate'
    },
    st: {
        validator: v.isTime(),
        stateField: 'filters.timeSlot.startTime'
    },
    et: {
        validator: v.isTime(),
        stateField: 'filters.timeSlot.endTime'
    },
    favorite: {
        validator: v.isBoolean(),
        sanitizer: v.toBoolean(),
        stateField: 'filters.onlyFavorites'
    },
    capacity: {
        validator: v.isInt({min: 1}),
        sanitizer: v.toInt(),
        stateField: 'filters.capacity'
    },
    building: {
        validator: v.isInt(),
        sanitizer: v.toInt(),
        stateField: 'filters.building'
    },
    floor: {
        stateField: 'filters.floor'
    },
    text: {
        stateField: 'filters.text'
    },
    SWLat: {
        validator: v.isFloat({min: -90, max: 90}),
        sanitizer: v.toFloat(),
        stateField: 'filters.bounds.SW[0]'
    },
    SWLng: {
        validator: v.isFloat({min: -180, max: 180}),
        sanitizer: v.toFloat(),
        stateField: 'filters.bounds.SW[1]'
    },
    NELat: {
        validator: v.isFloat({min: -90, max: 90}),
        sanitizer: v.toFloat(),
        stateField: 'filters.bounds.NE[0]'
    },
    NELng: {
        validator: v.isFloat({min: -180, max: 180}),
        sanitizer: v.toFloat(),
        stateField: 'filters.bounds.NE[1]'
    }
};

const _dtHandler = (prefix) => {
    return function({dates, timeSlot}) {
        const timePart = timeSlot[`${prefix}Time`];
        let datePart = dates[`${prefix}Date`];

        // single bookings have a 'null' endDate
        if (datePart === null && prefix === 'end') {
            datePart = dates['startDate'];
        }

        return moment(`${datePart} ${timePart}`, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DD HH:mm');
    };
};

export const ajax = {
    repeat_frequency: {
        onlyIf: (data) => 'recurrence' in data,
        serializer: ({recurrence: {type, interval}}) => {
            if (type === 'single') {
                return 'NEVER';
            } else if (type === 'daily') {
                return 'DAY';
            } else {
                return {
                    daily: 'DAY',
                    week: 'WEEK',
                    month: 'MONTH'
                }[interval];
            }
        }
    },
    repeat_interval: {
        onlyIf: (data) => 'recurrence' in data,
        serializer: ({recurrence: {type, number}}) => {
            if (type === 'single') {
                return 0;
            } else if (type === 'daily') {
                return 1;
            } else {
                return number;
            }
        }
    },
    capacity: ({capacity}) => capacity,
    favorite: {
        onlyIf: ({onlyFavorites}) => onlyFavorites,
        serializer: ({onlyFavorites}) => onlyFavorites,
    },
    building: ({building}) => building,
    floor: ({floor}) => floor,
    text: ({text}) => text,
    start_dt: {
        onlyIf: (data) => data.dates && data.dates.startDate,
        serializer: _dtHandler('start')
    },
    end_dt: {
        onlyIf: (data) => data.dates && data.dates.endDate,
        serializer: _dtHandler('end')
    },
    sw_lat: {
        onlyIf: (data) => data.bounds && 'SW' in data.bounds,
        serializer: ({bounds: {SW}}) => SW[0]
    },
    sw_lng: {
        onlyIf: (data) => data.bounds && 'SW' in data.bounds,
        serializer: ({bounds: {SW}}) => SW[1]
    },
    ne_lat: {
        onlyIf: (data) => data.bounds && 'NE' in data.bounds,
        serializer: ({bounds: {NE}}) => NE[0]
    },
    ne_lng: {
        onlyIf: (data) => data.bounds && 'NE' in data.bounds,
        serializer: ({bounds: {NE}}) => NE[1]
    }
};
<|endoftext|>


<commit_before><commit_msg>Company.<commit_after><|endoftext|>


<commit_before>// [START containeranalysis_get_occurrence]
// Retrieves and prints a specified Occurrence from the server
const getOccurrence = async(
    projectId = 'your-project-id', // Your GCP Project ID
    occurrenceId = 'my-occurrence' // Your Occurrence name
) => {
    // Import the library and create a client
    const grafeas = require('@google-cloud/grafeas');
    const client = new grafeas.v1.GrafeasClient();

    // Get full path to occurrence
    const formattedName = client.occurrencePath(projectId, occurrenceId)

    // Get occurrence
    const [occurrence] = await client.getOccurrence({
        name: formattedName
    });

    console.log(`Occurrence name: ${occurrence.name}`)

};
// [END containeranalysis_get_occurrence]

const args = process.argv.slice(2);
getOccurrence(...args).catch(console.error)<commit_msg>updated description of occurrenceId<commit_after>// [START containeranalysis_get_occurrence]
// Retrieves and prints a specified Occurrence from the server
const getOccurrence = async(
    projectId = 'your-project-id', // Your GCP Project ID
    occurrenceId = 'my-occurrence' // The API-generated identifier associated with the occurrence
) => {
    // Import the library and create a client
    const grafeas = require('@google-cloud/grafeas');
    const client = new grafeas.v1.GrafeasClient();

    // Get full path to occurrence
    const formattedName = client.occurrencePath(projectId, occurrenceId)

    // Get occurrence
    const [occurrence] = await client.getOccurrence({
        name: formattedName
    });

    console.log(`Occurrence name: ${occurrence.name}`)

};
// [END containeranalysis_get_occurrence]

const args = process.argv.slice(2);
getOccurrence(...args).catch(console.error)<|endoftext|>


<commit_before>
  function ExplanationWindow() {
    this.create();
  }

  ExplanationWindow.prototype = {};

  ExplanationWindow.prototype.create = function() {
    var me = this;
    this.div = document.createElement('div');
    this.div.setAttribute('id','appInfo');
    this.div.innerHTML =
      ''+
      '
'+
        ''+
        '
¿DE DÓNDE SALEN LOS DATOS?
'+
        '
Datos demográficos
'+
        '
'+
          '
Inmigración
'+
          '
Sexo
'+
          '
Paro
'+
          '
Saldo Vegetativo
'+
        '
'+
      '
'+
      '
'+
        '
Edad Media de la Población
'+
        '
La edad  media de la población española se ha calculado en base a los datos de población inlcuidos en el censo nacional y publicados en la página web del INE.
'+
        '
Para calcular la edad media hemos multiplicado el valor medio de cada quinquenio por el número de personas situadas en ese rango, para después, volver a dividir entre el total.
'+
      '
';

    $('body').append(this.div);
    $(this.div).children('a.close_info').click(function(ev){ev.stopPropagation();ev.preventDefault();me.hide();});

    $(this.div).find('li').children('a').click(function(ev){
      ev.stopPropagation(); ev.preventDefault();
      if (!$(this).parent().hasClass('selected')) {
        $('div#appInfo ul li').each(function(i,ele){$(ele).removeClass('selected')});
        $(this).parent().addClass('selected');
        var offset = $(this).position().top;
        $('div#appInfo span.arrow').animate({top:offset+'px'},300);
        //TODO - change div to show in the right main window

      }
    });
    $(this.div).draggable({containment: 'parent'});
  }

  ExplanationWindow.prototype.show = function() {
    $(this.div).css({margin:'-257px 0 0 -385px',top:'65%',left:'50%'});
    $(this.div).fadeIn();
  }

  ExplanationWindow.prototype.hide = function() {
    $(this.div).fadeOut();
  }
<commit_msg>Moved down a bit the Explanation Window<commit_after>
  function ExplanationWindow() {
    this.create();
  }

  ExplanationWindow.prototype = {};

  ExplanationWindow.prototype.create = function() {
    var me = this;
    this.div = document.createElement('div');
    this.div.setAttribute('id','appInfo');
    this.div.innerHTML =
      ''+
      '
'+
        ''+
        '
¿DE DÓNDE SALEN LOS DATOS?
'+
        '
Datos demográficos
'+
        '
'+
          '
Inmigración
'+
          '
Sexo
'+
          '
Paro
'+
          '
Saldo Vegetativo
'+
        '
'+
      '
'+
      '
'+
        '
Edad Media de la Población
'+
        '
La edad  media de la población española se ha calculado en base a los datos de población inlcuidos en el censo nacional y publicados en la página web del INE.
'+
        '
Para calcular la edad media hemos multiplicado el valor medio de cada quinquenio por el número de personas situadas en ese rango, para después, volver a dividir entre el total.
'+
      '
';

    $('body').append(this.div);
    $(this.div).children('a.close_info').click(function(ev){ev.stopPropagation();ev.preventDefault();me.hide();});

    $(this.div).find('li').children('a').click(function(ev){
      ev.stopPropagation(); ev.preventDefault();
      if (!$(this).parent().hasClass('selected')) {
        $('div#appInfo ul li').each(function(i,ele){$(ele).removeClass('selected')});
        $(this).parent().addClass('selected');
        var offset = $(this).position().top;
        $('div#appInfo span.arrow').animate({top:offset+'px'},300);
        //TODO - change div to show in the right main window

      }
    });
    $(this.div).draggable({containment: 'parent'});
  }

  ExplanationWindow.prototype.show = function() {
    $(this.div).css({margin:'-237px 0 0 -385px',top:'50%',left:'50%'});
    $(this.div).fadeIn();
  }

  ExplanationWindow.prototype.hide = function() {
    $(this.div).fadeOut();
  }
<|endoftext|>


<commit_before>const test = rrequire('test')

test.todo('All tests')
<commit_msg>publish wrapper tests<commit_after>const test = rrequire('test')
const sinon = require('sinon')

const publish = require('./publish')

test('should publish route with correct arguments', async t => {
    const spy = sinon.spy()
    const wampMock = { publish: spy }

    const publishRoute = publish(wampMock)

    publishRoute('test', { test: true })

    t.notThrows(() => sinon.assert.calledWith(spy, 'test', { test: true }))
})
<|endoftext|>


<commit_before>angular.module('foundation.common', [])
  .service('FoundationApi', function() {
    var listeners = [];

    return {
      subscribe: function(type, name, callback) {
        if (!listeners[type]) {
          listeners[type] = [];
        }

        listeners[type][name] = callback;
        return true;
      },
      publish: function(type, name, msg) {
        if (!listeners[type]) {
          listeners[type] = [];
        }

        var cb = listeners[type][name] || function() {};
        cb(msg);
        return;
      }
    }
  }
);
<commit_msg>True pub/sub system<commit_after>angular.module('foundation.common', [])
  .service('FoundationApi', function() {
    var listeners = [];

    return {
      subscribe: function(type, name, callback) {
        if (!listeners[type]) {
          listeners[type] = [];
        }

        if (!listeners[type][name]) {
          listeners[type][name] = [];
        }

        listeners[type][name].push(callback);
        return true;
      },
      publish: function(type, name, msg) {
        if (!listeners[type]) {
          listeners[type] = [];
        }

        if (!listeners[type][name]) {
          listeners[type][name] = [];
        }

        angular.forEach(listeners[type][name], function(cb) {
          cb(msg)
        });

        return;
      }
    }
  }
);
<|endoftext|>


<commit_before>Ext.define('Mba.ux.Searchbar.Search', {
    override: 'Ext.field.Search',

    requires: [
        'Mba.ux.Searchbar.SearchInput'
    ],

    config: {
        component: {
            xtype: 'searchinput',
            type: 'search'
        }
    }

});
<commit_msg>implementando mecanismo de replace de acentos<commit_after>Ext.define('Mba.ux.Searchbar.Search', {
    override: 'Ext.field.Search',

    requires: [
        'Mba.ux.Searchbar.SearchInput'
    ],

    config: {
        component: {
            xtype: 'searchinput',
            type: 'search'
        }
    },

    getValue: function() {
        var value = this.callOverridden();
        value = value.replace(/[âáã]/g, 'a');
        value = value.replace(/[êé]/g, 'e');
        value = value.replace(/[îí]/g, 'i');
        value = value.replace(/[ôóõ]/g, 'o');
        value = value.replace(/ú/g, 'u');
        value = value.replace(/ç/g, 'c');
        return value;
    }

});
<|endoftext|>


<commit_before>module.exports = function(gulp){

  'use strict';

  var config = require('./config')();

  gulp.task('watch', ['browsersync'], function(){

    gulp.watch('bower.json', ['bower']);
    gulp.watch('views/**/*.html').on('change', config.browsersync.reload);
    gulp.watch('src/css/**/*.scss', ['css']);
    gulp.watch('src/js/**/*.js', ['js']);

  });

};<commit_msg>start server task before watch task start<commit_after>module.exports = function(gulp){

  'use strict';

  var config = require('./config')();

  gulp.task('watch', ['server', 'browsersync'], function(){

    gulp.watch('bower.json', ['bower']);
    gulp.watch('index.html').on('change', config.browsersync.reload);
    gulp.watch('src/css/**/*.scss', ['css']);
    gulp.watch('src/js/**/*.js', ['js']);

  });

};<|endoftext|>


<commit_before>/** $Id$
 *
 * To facilitate use of ajax services, including providing providing modal popup forms and feedback
 */

/**
 * To trigger ajax services modal with a form submission
 *
 *  - clicked submit element must have a class of confirm-submit
 *  - the formaction attribute of the submit element must be set using the bootstrap_modal smarty function
 *  - the form attribute of the submit element must be set with the form id
 *  - for a submit button related to a select element:
 *      - the name attribute of the select element must be set to action (name=action)
 *      - the select option value being submitted should be the action value only (e.g., remove_users)
 *      - the submit element's formaction attribute value will be used for the first part of the services url,
 *          ie without the action specified - eg {bootstrap_modal controller=user}
 *      - the above requirements for a submitted select value (ie, name=action, value contains only the action, rest of
 *          url in formaction) is necessary for ajax services to work when javascript is not enabled
 */

$('[type=submit].confirm-submit').click(function() {
	var target = $('.modal.fade:not(.in)').first();
	$.post($(this).attr('formaction'), $(this.form).serialize(), function (data) {
		$('.modal-content', target).html(data);
		target.modal();
	});
	return false;
});

/**
 * To trigger ajax services when there are no modals involved
 *
 *  - clicked submit element must have a class of service-submit
 *  - the formaction attribute of the submit element must be set using the service smarty function
 *  - the form attribute of the submit element must be set with the form id
 */
$('[type=submit].service-submit').click(function() {
	$.post($(this).attr('formaction'), $(this.form).serialize(), function (data) {});
	return false;
});

// Triggers the form submission in ajax confirmation modals.
// This is needed for IE 10/11 since it does not support the form attribute on buttons.
$(document).on('click', 'button[form="confirm-action"]' ,function(ev) {
	ev.preventDefault();
	$('#confirm-action').submit();
});

/**
 * Use data posted from a popup modal as input for the ajax service action
 *
 * @param form
 */
function confirmAction(form) {
	//this is the ajax action once the confirm submit button is clicked
	$.ajax({
		dataType: 'json',
		url: $(form).attr('action'),
		type: 'POST',
		data: $(form).serialize(),
		success: function (data) {
			if (!data) {
				$.closeModal();
				return;
			}
			var extra = data.extra || false, dataurl = data.url || false, dataError = data.error || false;
			if (extra) {
				/* Simply close modal. Feedback is added to the page without refreshing in the ajax service using the
				the sandard Feedback class function send_headers(). Used when there is an error in submitting modal
				form*/
				if (extra === 'close') {
					$.closeModal();
				//Close modal and refresh page. Feedback can be added to the refreshed page in the ajax service using
				//the Feedback class
				} else if (extra === 'refresh') {
					$.closeModal();
					document.location.href = document.location.href.replace(/#.*$/, "");
				}
			}
			//send to another page
			if (dataurl) {
				$.closeModal();
				//reload if the same base url, otherwise page won't refresh if only adding a hash anchor to the same page
				var $href = document.location.href.replace(/#.*$/, "");
				if (dataurl.indexOf($href) > -1 || dataurl === $href) {
					document.location.href = dataurl;
					location.reload();
				//different url prior to any anchor tags
				} else {
					document.location.assign(dataurl);
				}
			}
			//send error
			if (dataError) {
				if (dataError === 'CSRF') {
					dataError = tr('Potential cross-site request forgery (CSRF) detected. Operation blocked. The security ticket may have expired - reloading the page may help.');
				}
				$.closeModal();
				feedback (
					dataError,
					'error'
				);
			}
			return false;
		}
	});
}<commit_msg>[FIX] ajax: Submit event wasn't getting to the form in IE (when creating or modifying a group for instance) so pass the message on...<commit_after>/** $Id$
 *
 * To facilitate use of ajax services, including providing providing modal popup forms and feedback
 */

/**
 * To trigger ajax services modal with a form submission
 *
 *  - clicked submit element must have a class of confirm-submit
 *  - the formaction attribute of the submit element must be set using the bootstrap_modal smarty function
 *  - the form attribute of the submit element must be set with the form id
 *  - for a submit button related to a select element:
 *      - the name attribute of the select element must be set to action (name=action)
 *      - the select option value being submitted should be the action value only (e.g., remove_users)
 *      - the submit element's formaction attribute value will be used for the first part of the services url,
 *          ie without the action specified - eg {bootstrap_modal controller=user}
 *      - the above requirements for a submitted select value (ie, name=action, value contains only the action, rest of
 *          url in formaction) is necessary for ajax services to work when javascript is not enabled
 */

$('[type=submit].confirm-submit').click(function() {
	var target = $('.modal.fade:not(.in)').first();
	$.post($(this).attr('formaction'), $(this.form).serialize(), function (data) {
		$('.modal-content', target).html(data);

		// IE seems to need some help submitting the form here?
		$('.confirm-action-btn', target).click(function () {
			$(this).parents(".modal-content").find("form").submit();
		});

		target.modal();
	});
	return false;
});

/**
 * To trigger ajax services when there are no modals involved
 *
 *  - clicked submit element must have a class of service-submit
 *  - the formaction attribute of the submit element must be set using the service smarty function
 *  - the form attribute of the submit element must be set with the form id
 */
$('[type=submit].service-submit').click(function() {
	$.post($(this).attr('formaction'), $(this.form).serialize(), function (data) {});
	return false;
});

// Triggers the form submission in ajax confirmation modals.
// This is needed for IE 10/11 since it does not support the form attribute on buttons.
$(document).on('click', 'button[form="confirm-action"]' ,function(ev) {
	ev.preventDefault();
	$('#confirm-action').submit();
});

/**
 * Use data posted from a popup modal as input for the ajax service action
 *
 * @param form
 */
function confirmAction(form) {
	//this is the ajax action once the confirm submit button is clicked
	$.ajax({
		dataType: 'json',
		url: $(form).attr('action'),
		type: 'POST',
		data: $(form).serialize(),
		success: function (data) {
			if (!data) {
				$.closeModal();
				return;
			}
			var extra = data.extra || false, dataurl = data.url || false, dataError = data.error || false;
			if (extra) {
				/* Simply close modal. Feedback is added to the page without refreshing in the ajax service using the
				the sandard Feedback class function send_headers(). Used when there is an error in submitting modal
				form*/
				if (extra === 'close') {
					$.closeModal();
				//Close modal and refresh page. Feedback can be added to the refreshed page in the ajax service using
				//the Feedback class
				} else if (extra === 'refresh') {
					$.closeModal();
					document.location.href = document.location.href.replace(/#.*$/, "");
				}
			}
			//send to another page
			if (dataurl) {
				$.closeModal();
				//reload if the same base url, otherwise page won't refresh if only adding a hash anchor to the same page
				var $href = document.location.href.replace(/#.*$/, "");
				if (dataurl.indexOf($href) > -1 || dataurl === $href) {
					document.location.href = dataurl;
					location.reload();
				//different url prior to any anchor tags
				} else {
					document.location.assign(dataurl);
				}
			}
			//send error
			if (dataError) {
				if (dataError === 'CSRF') {
					dataError = tr('Potential cross-site request forgery (CSRF) detected. Operation blocked. The security ticket may have expired - reloading the page may help.');
				}
				$.closeModal();
				feedback (
					dataError,
					'error'
				);
			}
			return false;
		}
	});
}<|endoftext|>


<commit_before>define('spec/audiomanager', ['lyria/audio/manager'], function(AudioManager) {

  describe('lyria/audio/manager', function() {

    it('is an object', function() {
      expect(AudioManager).to.be.a('function');
    });

    describe('constructor', function() {
      it('can be instantiated', function() {
        var audioManager = new AudioManager({});

        expect(audioManager).to.be.a('object');
        expect(audioManager).to.be.an.instanceOf(AudioManager);
      });
    });
  });

});
<commit_msg>added some unit tests for audiomanager<commit_after>define('spec/audiomanager', ['lyria/audio/manager'], function(AudioManager) {

  describe('lyria/audio/manager', function() {

    var audioManager = new AudioManager();

    it('is a function', function() {
      expect(AudioManager).to.be.a('function');
    });

    describe('constructor', function() {
      it('can be instantiated', function() {
        expect(audioManager).to.be.a('object');
        expect(audioManager).to.be.an.instanceOf(AudioManager);
      });
    });

    describe('Methods and functionality', function() {
      describe('#add', function() {
        it('exists', function() {
          expect(audioManager).to.have.property('add');
          expect(AudioManager.prototype.add).to.be.a('function');
          expect(audioManager.add).to.equal(AudioManager.prototype.add);
        });
      });

      describe('#play', function() {
        it('exists', function() {
          expect(audioManager).to.have.property('play');
          expect(AudioManager.prototype.play).to.be.a('function');
          expect(audioManager.play).to.equal(AudioManager.prototype.play);
        });
      });

      describe('#stop', function() {
        it('exists', function() {
          expect(audioManager).to.have.property('stop');
          expect(AudioManager.prototype.stop).to.be.a('function');
          expect(audioManager.stop).to.equal(AudioManager.prototype.stop);
        });
      });
    });
  });

});
<|endoftext|>


<commit_before><commit_msg>make test not immediately fail<commit_after><|endoftext|>


<commit_before>'use strict';

var accumulator = require('../lib/accumulator.js'),
    nock = require('nock');

describe('accumulator', function() {
    afterEach(function() {
        nock.cleanAll();
    });

    it('resolves successfully when all urls are successful', function(done) {
        var url = "http://localhost:32768/",
            statusCode = 200,
            thirty_seconds_in_ms = 30 * 1000;

        nock(url)
            .head('/')
            .reply(statusCode);

        var url_b = "http://localhost:32769/";
        nock(url_b)
            .head('/')
            .reply(statusCode);

        var pending = accumulator([url, url_b], thirty_seconds_in_ms);

        pending.done(function() {
            done();
        });
    });
});
<commit_msg>Add test for failure case to accumulator<commit_after>'use strict';

var accumulator = require('../lib/accumulator.js'),
    nock = require('nock'),
    successCode = 200;

describe('accumulator', function() {
    afterEach(function() {
        nock.cleanAll();
    });

    it('resolves successfully when all URLs are successful', function(done) {
        var urls = ['http://localhost:32001/', 'http://localhost:32002'],
            thirty_seconds_in_ms = 30 * 1000;

        urls.forEach(function(url) {
            nock(url)
                .head('/')
                .reply(successCode);
        });

        var pending = accumulator(urls, thirty_seconds_in_ms);

        pending.done(function() {
            done();
        });
    });

    it('errors out if one of the URLs is not successful', function(done) {
        var urls = ['http://localhost:32001/', 'http://localhost:32002'],
            one_second_in_ms = 1 * 1000;

        urls.forEach(function(url) {
            nock(url)
                .head('/')
                .reply(successCode);
        });

        urls.push('http://not.going.to.respond.localhost:32003/');

        var pending = accumulator(urls, one_second_in_ms);

        pending.done(
            function() {},
            function() {
                done();
            });
    });
});
<|endoftext|>


<commit_before>/*jslint browser: true, devel: true */
/**

=head1 Accessions.js

Dialogs for managing accessions

=head1 AUTHOR

Jeremy D. Edwards <jde22@cornell.edu>

=cut

*/

var $j = jQuery.noConflict();

jQuery(document).ready(function ($) {

    var list = new CXGN.List();

    $("#review_absent_dialog").dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Add: function() {
		alert("Warning: use caution adding accessions.  Slight differences in spelling can cause undesired duplication.  Please send your list of accessions to add to a curator if you are unsure.");
		$(this).dialog( "close" );
	    },
	    Close: function() {
		$(this).dialog( "close" );
	    },
	}
    });

    $("#review_found_matches_dialog").dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Ok: function() {
		$(this).dialog( "close" );
	    },
	}
    });

    $("#review_fuzzy_matches_dialog").dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Ok: function() {
		$(this).dialog( "close" );
	    },
	}
    });

    function review_verification_results(verifyResponse){
	var i;
	var j;

	if (verifyResponse.found) {
	var found_html = '';
	for( i=0; i < verifyResponse.found.length; i++){
	    found_html = found_html
		+'
'+verifyResponse.found[i].matched_string
		+'
';
	    if (verifyResponse.found[i].matched_string != verifyResponse.found[i].unique_name){
		found_html = found_html
		    +'
'
		    +verifyResponse.found[i].unique_name
		    +'
';
	    }
	}
	    $('#view_found_matches').html(found_html);

	    if (verifyResponse.fuzzy) {
		$('#review_found_matches_dialog').bind('dialogclose', function() {
		    $('#review_fuzzy_matches_dialog').dialog('open');
		});
	    } else {
		$('#review_found_matches_dialog').bind('dialogclose', function() {
		    $('#review_absent_dialog').dialog('open');
		});
	    }

	    $('#review_found_matches_dialog').dialog('open');
	}

	if (verifyResponse.fuzzy) {
	    var fuzzy_html = '';
	    for( i=0; i < verifyResponse.fuzzy.length; i++) {
		fuzzy_html = fuzzy_html + '
'+ verifyResponse.fuzzy[i].name + '
';
		fuzzy_html = fuzzy_html + '
<select id ="fuzzyselect'+i+'">';
		for(j=0; j < verifyResponse.fuzzy[i].matches.length; j++){
		    fuzzy_html = fuzzy_html + '<option value="">' + verifyResponse.fuzzy[i].matches[j].name + '</option>';
		}
		fuzzy_html = fuzzy_html + '</select>';
	    }
	    fuzzy_html = fuzzy_html + '
';
	    $('#view_fuzzy_matches').html(fuzzy_html);
	    //$('#review_fuzzy_matches_dialog').dialog('open');
	}

	if (verifyResponse.absent) {
	    var absent_html = '';
	    for( i=0; i < verifyResponse.absent.length; i++){
		absent_html = absent_html
		    +'
'+verifyResponse.absent[i]
		    +'
'
		    +'
'
		    +verifyResponse.absent[i]
		    +'
';
	    }
	    $('#view_absent').html(absent_html);
	    //$('#review_absent_dialog').dialog('open');
	}
    }

    function verify_accession_list() {
	var accession_list_id = $('#accessions_list_select').val();
	var accession_list = JSON.stringify(list.getList(accession_list_id));
	var doFuzzySearch = $('#fuzzy_check').val();
	alert(accession_list);

	$.ajax({
	    type: 'POST',
	    url: '/ajax/accession_list/verify',
	    async: false,
	    dataType: "json",
	    data: {
                'accession_list': accession_list,
		'do_fuzzy_search': doFuzzySearch,
	    },
	    success: function (response) {
                if (response.error) {
		    alert(response.error);
                } else {
		    //var text = JSON.stringify(response, null, '\t');
		    //alert(text);
		    review_verification_results(response);
                }
	    },
	    error: function () {
                alert('An error occurred in processing. sorry');
	    }
        });
    }

    $( "#add_accessions_dialog" ).dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Ok: function() {
		verify_accession_list();
		//$(this).dialog( "close" );
		//location.reload();
	    }
	}
    });

    $('#add_accessions_link').click(function () {
        $('#add_accessions_dialog').dialog("open");
	$("#list_div").append(list.listSelect("accessions"));
	//$( "#fuzzy_check" ).button();
    });

});
<commit_msg>end dialogs with add accessions<commit_after>/*jslint browser: true, devel: true */
/**

=head1 Accessions.js

Dialogs for managing accessions

=head1 AUTHOR

Jeremy D. Edwards <jde22@cornell.edu>

=cut

*/

var $j = jQuery.noConflict();

jQuery(document).ready(function ($) {

    var list = new CXGN.List();

    $("#review_absent_dialog").dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Add: function() {
		alert("Warning: use caution adding accessions.  Slight differences in spelling can cause undesired duplication.  Please send your list of accessions to add to a curator if you are unsure.");
		$(this).dialog( "close" );
	    },
	    Close: function() {
		$(this).dialog( "close" );
	    },
	}
    });

    $("#review_found_matches_dialog").dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Ok: function() {
		$(this).dialog( "close" );
	    },
	}
    });

    $("#review_fuzzy_matches_dialog").dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Ok: function() {
		$(this).dialog( "close" );
	    },
	}
    });

    function review_verification_results(verifyResponse){
	var i;
	var j;

	if (verifyResponse.found) {
	var found_html = '';
	for( i=0; i < verifyResponse.found.length; i++){
	    found_html = found_html
		+'
'+verifyResponse.found[i].matched_string
		+'
';
	    if (verifyResponse.found[i].matched_string != verifyResponse.found[i].unique_name){
		found_html = found_html
		    +'
'
		    +verifyResponse.found[i].unique_name
		    +'
';
	    }
	}
	    $('#view_found_matches').html(found_html);

	    if (verifyResponse.fuzzy) {
		$('#review_found_matches_dialog').bind('dialogclose', function() {
		    $('#review_fuzzy_matches_dialog').dialog('open');
		});
	    } else {
		$('#review_found_matches_dialog').bind('dialogclose', function() {
		    $('#review_absent_dialog').dialog('open');
		});
	    }

	    $('#review_found_matches_dialog').dialog('open');
	}

	if (verifyResponse.fuzzy) {
	    var fuzzy_html = '';
	    for( i=0; i < verifyResponse.fuzzy.length; i++) {
		fuzzy_html = fuzzy_html + '
'+ verifyResponse.fuzzy[i].name + '
';
		fuzzy_html = fuzzy_html + '
<select id ="fuzzyselect'+i+'">';
		for(j=0; j < verifyResponse.fuzzy[i].matches.length; j++){
		    fuzzy_html = fuzzy_html + '<option value="">' + verifyResponse.fuzzy[i].matches[j].name + '</option>';
		}
		fuzzy_html = fuzzy_html + '</select>';
	    }
	    fuzzy_html = fuzzy_html + '
';
	    $('#view_fuzzy_matches').html(fuzzy_html);
	    //$('#review_fuzzy_matches_dialog').dialog('open');

	    $('#review_fuzzy_matches_dialog').bind('dialogclose', function() {
		$('#review_absent_dialog').dialog('open');
	    });

	}

	if (verifyResponse.absent) {
	    var absent_html = '';
	    for( i=0; i < verifyResponse.absent.length; i++){
		absent_html = absent_html
		    +'
'+verifyResponse.absent[i]
		    +'
'
		    +'
'
		    +verifyResponse.absent[i]
		    +'
';
	    }
	    $('#view_absent').html(absent_html);
	    //$('#review_absent_dialog').dialog('open');
	}
    }

    function verify_accession_list() {
	var accession_list_id = $('#accessions_list_select').val();
	var accession_list = JSON.stringify(list.getList(accession_list_id));
	var doFuzzySearch = $('#fuzzy_check').val();
	alert(accession_list);

	$.ajax({
	    type: 'POST',
	    url: '/ajax/accession_list/verify',
	    async: false,
	    dataType: "json",
	    data: {
                'accession_list': accession_list,
		'do_fuzzy_search': doFuzzySearch,
	    },
	    success: function (response) {
                if (response.error) {
		    alert(response.error);
                } else {
		    //var text = JSON.stringify(response, null, '\t');
		    //alert(text);
		    review_verification_results(response);
                }
	    },
	    error: function () {
                alert('An error occurred in processing. sorry');
	    }
        });
    }

    $( "#add_accessions_dialog" ).dialog({
	autoOpen: false,
	modal: true,
	autoResize:true,
        width: 500,
        position: ['top', 150],
	buttons: {
	    Ok: function() {
		verify_accession_list();
		//$(this).dialog( "close" );
		//location.reload();
	    }
	}
    });

    $('#add_accessions_link').click(function () {
        $('#add_accessions_dialog').dialog("open");
	$("#list_div").append(list.listSelect("accessions"));
	//$( "#fuzzy_check" ).button();
    });

});
<|endoftext|>


<commit_before>import expect from 'expect';
import Incarnate from './Incarnate';

const MOCK_INSTANCE = { x: 10 };
const MOCK_DEPENDENCY = { y: 100 };
const MOCK_DEPENDENCY_DEPENDENCY = { z: 1000 };
const MOCK_CTX_PROP_VALUE = 'MOCK_CTX_PROP_VALUE';
const MOCK_ARG_1_VALUE = 'MOCK_ARG_1_VALUE';
const MOCK_ARG_2_VALUE = 'MOCK_ARG_2_VALUE';

let CACHE_COUNT;

module.exports = {
  'Incarnate': {
    'should be a class': () => {
      expect(Incarnate).toBeA(Function);
    },
    'resolvePath': {
      beforeEach: () => {
        CACHE_COUNT = 0;
      },
      'should be a function': () => {
        const inc = new Incarnate({
          map: {}
        });

        expect(inc.resolvePath).toBeA(Function);
      },
      'should resolve a path asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'mock': {
              args: [],
              factory: async () => {
                return await new Promise((res, rej) => {
                  setTimeout(() => res(MOCK_INSTANCE), 0);
                });
              }
            }
          }
        });
        const instance = await inc.resolvePath('mock');

        expect(instance).toBe(MOCK_INSTANCE);
      },
      'should resolve an injected dependency asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'mock-dep': {
              args: [],
              factory: async () => {
                return await new Promise((res, rej) => {
                  setTimeout(() => res(MOCK_DEPENDENCY), 0);
                });
              }
            },
            'mock': {
              args: [
                'mock-dep'
              ],
              factory: async (mockDep) => {
                return mockDep;
              }
            }
          }
        });
        const instance = await inc.resolvePath('mock');

        expect(instance).toBe(MOCK_DEPENDENCY);
      },
      'should resolve injected dependencies recursively and asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'mock-dep-dep': {
              args: [],
              factory: async () => {
                return await new Promise((res, rej) => {
                  setTimeout(() => res(MOCK_DEPENDENCY_DEPENDENCY), 0);
                });
              }
            },
            'mock-dep': {
              args: [
                'mock-dep-dep'
              ],
              factory: (mockDepDep) => {
                return mockDepDep;
              }
            },
            'mock': {
              args: [
                'mock-dep'
              ],
              factory: (mockDep) => {
                return mockDep;
              }
            }
          }
        });
        const instance = await inc.resolvePath('mock');

        expect(instance).toBe(MOCK_DEPENDENCY_DEPENDENCY);
      },
      'should resolve a context specific dependency asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'mock-dep-dep': {
              args: [],
              factory: () => {
                return MOCK_DEPENDENCY_DEPENDENCY;
              }
            },
            'mock-dep': {
              args: [
                'mock-dep-dep',
                async (ctx) => {
                  return await new Promise((res, rej) => {
                    setTimeout(() => res(ctx.mockCtxProp), 0);
                  });
                }
              ],
              factory: (mockDepDep, mockCtxProp) => {
                return {
                  a: mockDepDep,
                  b: mockCtxProp
                };
              }
            },
            'mock': {
              args: [
                'mock-dep'
              ],
              factory: (mockDep) => {
                return mockDep;
              }
            }
          },
          context: {
            mockCtxProp: MOCK_CTX_PROP_VALUE
          }
        });
        const instance = await inc.resolvePath('mock');

        expect(instance.b).toBe(MOCK_CTX_PROP_VALUE);
      },
      'should resolve args asynchronously and in parallel': async () => {
        const inc = new Incarnate({
          map: {
            'mock': {
              args: [
                async () => await new Promise((res, rej) => setTimeout(() => res(MOCK_ARG_1_VALUE), 10)),
                async () => await new Promise((res, rej) => setTimeout(() => res(MOCK_ARG_2_VALUE), 10))
              ],
              factory: async (arg1, arg2) => {
                return {
                  a: arg1,
                  b: arg2
                };
              }
            }
          }
        });
        const start = new Date().getTime();
        const instance = await inc.resolvePath('mock');
        const diff = new Date().getTime() - start;

        expect(instance).toBeAn(Object);
        expect(instance.a).toBe(MOCK_ARG_1_VALUE);
        expect(instance.b).toBe(MOCK_ARG_2_VALUE);
        expect(diff < 20).toBe(true);
      },
      'should resolve deeply nested dependencies asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'nested': async ctx => {
              return await new Promise((res, rej) => {
                setTimeout(() => res({
                  'mock-dep': {
                    args: [],
                    factory: async () => {
                      return await new Promise((res2, rej2) => {
                        setTimeout(() => res2(ctx.mockCtxProp), 0);
                      });
                    }
                  }
                }), 0);
              });
            },
            'mock-dep': {
              args: [],
              factory: () => MOCK_DEPENDENCY
            },
            'mock': {
              args: [
                'mock-dep',
                'nested/mock-dep'
              ],
              factory: async (arg1, arg2) => {
                return await new Promise((res, rej) => {
                  setTimeout(() => res({
                    a: arg1,
                    b: arg2
                  }), 0);
                });
              }
            }
          },
          context: {
            mockCtxProp: MOCK_CTX_PROP_VALUE
          },
          pathDelimiter: '/'
        });
        const instance = await inc.resolvePath('mock');

        expect(instance).toBeAn(Object);
        expect(instance.a).toBe(MOCK_DEPENDENCY);
        expect(instance.b).toBe(MOCK_CTX_PROP_VALUE);
      },
      'should cache dependencies': async () => {
        const map = {
          'mock-dep': {
            args: [],
            factory: async () => {
              return await new Promise((res, rej) => {
                const cacheCount = CACHE_COUNT;

                setTimeout(() => res(cacheCount), 0);
                CACHE_COUNT += 1;
              });
            }
          },
          'mock': {
            args: [
              'mock-dep'
            ],
            factory: async (arg1) => {
              return {
                a: arg1
              };
            }
          }
        };
        const context = {};
        const cache = {};
        const inc = new Incarnate({
          map,
          context,
          cacheMap: cache
        });
        const instance = await inc.resolvePath('mock');
        const dependency = await inc.resolvePath('mock-dep');

        expect(cache['mock-dep']).toBe(dependency);
        expect(CACHE_COUNT).toBe(1);
        expect(instance).toBeAn(Object);
        expect(instance.a).toBe(0);
        expect(dependency).toBe(0);
      },
      'should not cache dependencies marked with cache = `false`': async () => {
        const map = {
          'mock-dep': {
            args: [],
            cache: false,
            factory: async () => {
              return await new Promise((res, rej) => {
                const cacheCount = CACHE_COUNT;

                setTimeout(() => res(cacheCount), 0);
                CACHE_COUNT += 1;
              });
            }
          },
          'mock': {
            args: [
              'mock-dep'
            ],
            factory: async (arg1) => {
              return {
                a: arg1
              };
            }
          }
        };
        const context = {};
        const cache = {};
        const inc = new Incarnate({
          map,
          context,
          cacheMap: cache
        });
        const instance = await inc.resolvePath('mock');
        const dependency = await inc.resolvePath('mock-dep');

        expect(cache['mock-dep']).toNotBe(dependency);
        expect(CACHE_COUNT).toBe(2);
        expect(instance).toBeAn(Object);
        expect(instance.a).toBe(0);
        expect(dependency).toBe(1);
      }
    }
  }
};
<commit_msg>test(Incarnate) Add a test for cache invalidation and lifecycle features.<commit_after>import expect from 'expect';
import Incarnate from './Incarnate';

const MOCK_INSTANCE = { x: 10 };
const MOCK_DEPENDENCY = { y: 100 };
const MOCK_DEPENDENCY_DEPENDENCY = { z: 1000 };
const MOCK_CTX_PROP_VALUE = 'MOCK_CTX_PROP_VALUE';
const MOCK_ARG_1_VALUE = 'MOCK_ARG_1_VALUE';
const MOCK_ARG_2_VALUE = 'MOCK_ARG_2_VALUE';

let CACHE_COUNT;

module.exports = {
  'Incarnate': {
    'should be a class': () => {
      expect(Incarnate).toBeA(Function);
    },
    'resolvePath': {
      beforeEach: () => {
        CACHE_COUNT = 0;
      },
      'should be a function': () => {
        const inc = new Incarnate({
          map: {}
        });

        expect(inc.resolvePath).toBeA(Function);
      },
      'should resolve a path asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'mock': {
              args: [],
              factory: async () => {
                return await new Promise((res, rej) => {
                  setTimeout(() => res(MOCK_INSTANCE), 0);
                });
              }
            }
          }
        });
        const instance = await inc.resolvePath('mock');

        expect(instance).toBe(MOCK_INSTANCE);
      },
      'should resolve an injected dependency asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'mock-dep': {
              args: [],
              factory: async () => {
                return await new Promise((res, rej) => {
                  setTimeout(() => res(MOCK_DEPENDENCY), 0);
                });
              }
            },
            'mock': {
              args: [
                'mock-dep'
              ],
              factory: async (mockDep) => {
                return mockDep;
              }
            }
          }
        });
        const instance = await inc.resolvePath('mock');

        expect(instance).toBe(MOCK_DEPENDENCY);
      },
      'should resolve injected dependencies recursively and asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'mock-dep-dep': {
              args: [],
              factory: async () => {
                return await new Promise((res, rej) => {
                  setTimeout(() => res(MOCK_DEPENDENCY_DEPENDENCY), 0);
                });
              }
            },
            'mock-dep': {
              args: [
                'mock-dep-dep'
              ],
              factory: (mockDepDep) => {
                return mockDepDep;
              }
            },
            'mock': {
              args: [
                'mock-dep'
              ],
              factory: (mockDep) => {
                return mockDep;
              }
            }
          }
        });
        const instance = await inc.resolvePath('mock');

        expect(instance).toBe(MOCK_DEPENDENCY_DEPENDENCY);
      },
      'should resolve a context specific dependency asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'mock-dep-dep': {
              args: [],
              factory: () => {
                return MOCK_DEPENDENCY_DEPENDENCY;
              }
            },
            'mock-dep': {
              args: [
                'mock-dep-dep',
                async (ctx) => {
                  return await new Promise((res, rej) => {
                    setTimeout(() => res(ctx.mockCtxProp), 0);
                  });
                }
              ],
              factory: (mockDepDep, mockCtxProp) => {
                return {
                  a: mockDepDep,
                  b: mockCtxProp
                };
              }
            },
            'mock': {
              args: [
                'mock-dep'
              ],
              factory: (mockDep) => {
                return mockDep;
              }
            }
          },
          context: {
            mockCtxProp: MOCK_CTX_PROP_VALUE
          }
        });
        const instance = await inc.resolvePath('mock');

        expect(instance.b).toBe(MOCK_CTX_PROP_VALUE);
      },
      'should resolve args asynchronously and in parallel': async () => {
        const inc = new Incarnate({
          map: {
            'mock': {
              args: [
                async () => await new Promise((res, rej) => setTimeout(() => res(MOCK_ARG_1_VALUE), 10)),
                async () => await new Promise((res, rej) => setTimeout(() => res(MOCK_ARG_2_VALUE), 10))
              ],
              factory: async (arg1, arg2) => {
                return {
                  a: arg1,
                  b: arg2
                };
              }
            }
          }
        });
        const start = new Date().getTime();
        const instance = await inc.resolvePath('mock');
        const diff = new Date().getTime() - start;

        expect(instance).toBeAn(Object);
        expect(instance.a).toBe(MOCK_ARG_1_VALUE);
        expect(instance.b).toBe(MOCK_ARG_2_VALUE);
        expect(diff < 20).toBe(true);
      },
      'should resolve deeply nested dependencies asynchronously': async () => {
        const inc = new Incarnate({
          map: {
            'nested': async ctx => {
              return await new Promise((res, rej) => {
                setTimeout(() => res({
                  'mock-dep': {
                    args: [],
                    factory: async () => {
                      return await new Promise((res2, rej2) => {
                        setTimeout(() => res2(ctx.mockCtxProp), 0);
                      });
                    }
                  }
                }), 0);
              });
            },
            'mock-dep': {
              args: [],
              factory: () => MOCK_DEPENDENCY
            },
            'mock': {
              args: [
                'mock-dep',
                'nested/mock-dep'
              ],
              factory: async (arg1, arg2) => {
                return await new Promise((res, rej) => {
                  setTimeout(() => res({
                    a: arg1,
                    b: arg2
                  }), 0);
                });
              }
            }
          },
          context: {
            mockCtxProp: MOCK_CTX_PROP_VALUE
          },
          pathDelimiter: '/'
        });
        const instance = await inc.resolvePath('mock');

        expect(instance).toBeAn(Object);
        expect(instance.a).toBe(MOCK_DEPENDENCY);
        expect(instance.b).toBe(MOCK_CTX_PROP_VALUE);
      },
      'should cache dependencies': async () => {
        const map = {
          'mock-dep': {
            args: [],
            factory: async () => {
              return await new Promise((res, rej) => {
                const cacheCount = CACHE_COUNT;

                setTimeout(() => res(cacheCount), 0);
                CACHE_COUNT += 1;
              });
            }
          },
          'mock': {
            args: [
              'mock-dep'
            ],
            factory: async (arg1) => {
              return {
                a: arg1
              };
            }
          }
        };
        const context = {};
        const cache = {};
        const inc = new Incarnate({
          map,
          context,
          cacheMap: cache
        });
        const instance = await inc.resolvePath('mock');
        const dependency = await inc.resolvePath('mock-dep');

        expect(cache['mock-dep']).toBe(dependency);
        expect(CACHE_COUNT).toBe(1);
        expect(instance).toBeAn(Object);
        expect(instance.a).toBe(0);
        expect(dependency).toBe(0);
      },
      'should not cache dependencies marked with cache = `false`': async () => {
        const map = {
          'mock-dep': {
            args: [],
            cache: false,
            factory: async () => {
              return await new Promise((res, rej) => {
                const cacheCount = CACHE_COUNT;

                setTimeout(() => res(cacheCount), 0);
                CACHE_COUNT += 1;
              });
            }
          },
          'mock': {
            args: [
              'mock-dep'
            ],
            factory: async (arg1) => {
              return {
                a: arg1
              };
            }
          }
        };
        const context = {};
        const cache = {};
        const inc = new Incarnate({
          map,
          context,
          cacheMap: cache
        });
        const instance = await inc.resolvePath('mock');
        const dependency = await inc.resolvePath('mock-dep');

        expect(cache['mock-dep']).toNotBe(dependency);
        expect(CACHE_COUNT).toBe(2);
        expect(instance).toBeAn(Object);
        expect(instance.a).toBe(0);
        expect(dependency).toBe(1);
      },
      'should enable invalidation of cached dependencies including all dependants': async () => {
        const map = {
          'mock-dep': {
            args: [],
            factory: async () => {
              return await new Promise((res, rej) => {
                const cacheCount = CACHE_COUNT;

                setTimeout(() => res(cacheCount), 0);
                CACHE_COUNT += 1;
              });
            }
          },
          'mock': {
            args: [
              'mock-dep',
              (ctx, inc) => {
                return () => inc.invalidate(['mock-dep']);
              }
            ],
            factory: async (arg1, arg2) => {
              return {
                a: arg1,
                b: arg2
              };
            }
          }
        };
        const context = {};
        const cache = {};
        const inc = new Incarnate({
          map,
          context,
          cacheMap: cache
        });
        const instance1 = await inc.resolvePath('mock');
        instance1.b();
        const dependency = await inc.resolvePath('mock-dep');
        const instance2 = await inc.resolvePath('mock');

        expect(instance2).toNotBe(instance1);
        expect(cache['mock-dep']).toBe(dependency);
        expect(CACHE_COUNT).toBe(2);
        expect(instance1).toBeAn(Object);
        expect(instance1.a).toBe(0);
        expect(instance2).toBeAn(Object);
        expect(instance2.a).toBe(1);
        expect(dependency).toBe(1);
      }
    }
  }
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, View, TouchableHighlight, Text } from 'react-native';
import Popover from 'react-native-popover-view';
import Badge from './Badge';
import { SUSSOL_ORANGE } from '../globalStyles';
import { generalStrings } from '../localization';
import { routeList } from '../navigation/selectors';
import { UIDatabase } from '../database';

export class InfoBadge extends React.PureComponent {
  state = {
    isPopOverVisible: false,
    rect: {},
  };

  getMyInfo() {
    const { routeName } = this.props;
    const dataType = routeName in routeList ? routeList[routeName] : '';

    return [
      {
        count:
          dataType !== ''
            ? UIDatabase.objects(dataType).filtered('status != "finalised"').length
            : 0,
        title: `${generalStrings.unfinalised} ${generalStrings[routeName]}`,
      },
    ];
  }

  showPopover() {
    // Open popover and determine where to open it on canvas
    this.touchableContainer.measure((ox, oy, width, height, px, py) => {
      this.setState({
        isPopOverVisible: true,
        rect: { x: px, y: py, width, height },
      });
    });
  }

  closePopover() {
    this.setState({ isPopOverVisible: false });
  }

  render() {
    const { children, mainWrapperStyle, popoverPosition } = this.props;
    const { isPopOverVisible, rect } = this.state;
    const info = this.getMyInfo();

    // Get total of all the count variables in the info array. We want to show it on the badge
    const pendingCount = info.reduce((total, item) => total + (item.count || 0), 0);

    // Since having multiple digit text can break the badge, we are showing 99+
    // if the number is greater then 99.
    const unfinalisedCountText = pendingCount > 99 ? '99+' : pendingCount;

    return (
      <View style={{ position: 'relative' }}>
        {children}
        {pendingCount !== 0 && (
          <View style={[localStyles.mainWrapperStyle, mainWrapperStyle]}>
            <TouchableHighlight
              ref={ref => {
                this.touchableContainer = ref;
              }}
              style={localStyles.touchableContainerStyle}
              onPress={() => this.showPopover()}
            >
              <Badge
                value={unfinalisedCountText}
                badgeStyle={localStyles.badgeStyle}
                textStyle={localStyles.badgeFontStyle}
              />
            </TouchableHighlight>
            <Popover
              isVisible={isPopOverVisible}
              fromRect={rect}
              onRequestClose={() => this.closePopover()}
              popoverStyle={{ padding: 10, backgroundColor: SUSSOL_ORANGE }}
              arrowStyle={{ backgroundColor: SUSSOL_ORANGE }}
              backgroundStyle={{ backgroundColor: 'transparent' }}
              placement={popoverPosition}
            >
              <Text>
                {info.map(
                  (item, key) =>
                    item.count > 0 &&
                    item.text !== '' && (
                      // eslint-disable-next-line react/no-array-index-key
                      <Text key={key} style={{ color: '#FFF', fontSize: 12 }}>
                        {key === 0 ? '' : '\n'}
                        {item.title} : {item.count || item.text}
                      </Text>
                    )
                )}
              </Text>
            </Popover>
          </View>
        )}
      </View>
    );
  }
}

export default InfoBadge;

InfoBadge.propTypes = {
  // eslint-disable-next-line react/forbid-prop-types
  routeName: PropTypes.string.isRequired,
  children: PropTypes.element.isRequired,
  // eslint-disable-next-line react/forbid-prop-types
  mainWrapperStyle: PropTypes.object,
  popoverPosition: PropTypes.string,
};

InfoBadge.defaultProps = {
  mainWrapperStyle: {},
  popoverPosition: 'auto',
};

const localStyles = StyleSheet.create({
  mainWrapperStyle: {
    position: 'absolute',
    top: 0,
    right: 8,
  },
  touchableContainerStyle: {
    borderRadius: 10,
    backgroundColor: '#FFF',
    borderColor: '#FFF',
  },
  badgeStyle: {
    width: 45,
    backgroundColor: SUSSOL_ORANGE,
    alignItems: 'center',
    justifyContent: 'center',
  },
  badgeFontStyle: {
    fontSize: 10,
    color: '#FFF',
  },
});
<commit_msg>Extract style<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, View, TouchableHighlight, Text } from 'react-native';
import Popover from 'react-native-popover-view';
import Badge from './Badge';
import { SUSSOL_ORANGE } from '../globalStyles';
import { generalStrings } from '../localization';
import { routeList } from '../navigation/selectors';
import { UIDatabase } from '../database';

export class InfoBadge extends React.PureComponent {
  state = {
    isPopOverVisible: false,
    rect: {},
  };

  getMyInfo() {
    const { routeName } = this.props;
    const dataType = routeName in routeList ? routeList[routeName] : '';

    return [
      {
        count:
          dataType !== ''
            ? UIDatabase.objects(dataType).filtered('status != "finalised"').length
            : 0,
        title: `${generalStrings.unfinalised} ${generalStrings[routeName]}`,
      },
    ];
  }

  showPopover() {
    // Open popover and determine where to open it on canvas
    this.touchableContainer.measure((ox, oy, width, height, px, py) => {
      this.setState({
        isPopOverVisible: true,
        rect: { x: px, y: py, width, height },
      });
    });
  }

  closePopover() {
    this.setState({ isPopOverVisible: false });
  }

  render() {
    const { children, mainWrapperStyle, popoverPosition } = this.props;
    const { isPopOverVisible, rect } = this.state;
    const info = this.getMyInfo();

    // Get total of all the count variables in the info array. We want to show it on the badge
    const pendingCount = info.reduce((total, item) => total + (item.count || 0), 0);

    // Since having multiple digit text can break the badge, we are showing 99+
    // if the number is greater then 99.
    const unfinalisedCountText = pendingCount > 99 ? '99+' : pendingCount;

    return (
      <View style={{ position: 'relative' }}>
        {children}
        {pendingCount !== 0 && (
          <View style={[localStyles.mainWrapperStyle, mainWrapperStyle]}>
            <TouchableHighlight
              ref={ref => {
                this.touchableContainer = ref;
              }}
              style={localStyles.touchableContainerStyle}
              onPress={() => this.showPopover()}
            >
              <Badge
                value={unfinalisedCountText}
                badgeStyle={localStyles.badgeStyle}
                textStyle={localStyles.badgeFontStyle}
              />
            </TouchableHighlight>
            <Popover
              isVisible={isPopOverVisible}
              fromRect={rect}
              onRequestClose={() => this.closePopover()}
              popoverStyle={{ padding: 10, backgroundColor: SUSSOL_ORANGE }}
              arrowStyle={{ backgroundColor: SUSSOL_ORANGE }}
              backgroundStyle={{ backgroundColor: 'transparent' }}
              placement={popoverPosition}
            >
              <Text>
                {info.map(
                  (item, key) =>
                    item.count > 0 &&
                    item.text !== '' && (
                      // eslint-disable-next-line react/no-array-index-key
                      <Text key={key} style={localStyles.badgeTextStyle}>
                        {key === 0 ? '' : '\n'}
                        {item.title} : {item.count || item.text}
                      </Text>
                    )
                )}
              </Text>
            </Popover>
          </View>
        )}
      </View>
    );
  }
}

export default InfoBadge;

InfoBadge.propTypes = {
  // eslint-disable-next-line react/forbid-prop-types
  routeName: PropTypes.string.isRequired,
  children: PropTypes.element.isRequired,
  // eslint-disable-next-line react/forbid-prop-types
  mainWrapperStyle: PropTypes.object,
  popoverPosition: PropTypes.string,
};

InfoBadge.defaultProps = {
  mainWrapperStyle: {},
  popoverPosition: 'auto',
};

const localStyles = StyleSheet.create({
  mainWrapperStyle: {
    position: 'absolute',
    top: 0,
    right: 8,
  },
  touchableContainerStyle: {
    borderRadius: 10,
    backgroundColor: '#FFF',
    borderColor: '#FFF',
  },
  badgeStyle: {
    width: 45,
    backgroundColor: SUSSOL_ORANGE,
    alignItems: 'center',
    justifyContent: 'center',
  },
  badgeFontStyle: {
    fontSize: 10,
    color: '#FFF',
  },
  badgeTextStyle: {
    color: '#FFF',
    fontSize: 12,
  },
});
<|endoftext|>


<commit_before>'use strict';

define(['./module', 'qrcodejs'], function (directives, QRCode) {
  directives.directive('qrSaveButton', ['$window', function($window) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        var div = $window.document.createElement('div');
        var qrcode = new QRCode(div, {
          width : attrs.width,
          height : attrs.height,
          correctLevel : QRCode.CorrectLevel.H,
          useSVG: true
        });
        qrcode.makeCode(attrs.data);
        div.firstChild.setAttribute('width', '400');
        div.firstChild.setAttribute('height', '400');
        element[0].setAttribute('href','data:image/svg+xml;charset=utf-8,' +
          encodeURIComponent(div.innerHTML));
        element[0].setAttribute('download', attrs.data + '.svg');
      }
    };
  }]);
});<commit_msg>Save QRs as png.<commit_after>'use strict';

define(['./module', 'qrcodejs'], function (directives, QRCode) {
  directives.directive('qrSaveButton', ['$window', '$timeout', function($window, $timeout) {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        var div = $window.document.createElement('div');
        var qrcode = new QRCode(div, {
          width : attrs.width || 400,
          height : attrs.height || 400,
          correctLevel : QRCode.CorrectLevel.H
        });
        qrcode.makeCode(attrs.data);
        $timeout(function() {
          var data = div.lastChild.getAttribute('src');
          element[0].setAttribute('href', data);
          element[0].setAttribute('download', attrs.data + '.png');
        }, 1);
      }

    };
  }]);
});<|endoftext|>


<commit_before>function esprimaToAST(prog) {
  var toList = function (array) {
    var r = {tag: "[]"};
    for (var i = array.length - 1; i >= 0; i--) {
      r = {tag: "::", head: array[i], tail: r};
    }
    return r;
  };

  var toLoc = function (pos) {
    if (pos === null) {throw "null position in esprima AST";};
    return {file: "input.js",
            start: {line: pos.start.line, col: pos.start.column},
            stop:  {line: pos.end.line, col: pos.end.column}};
  };

  var trProg = function (prog) {
    if (prog.type !== "Program") {
      throw ("trProg error: " + prog.type);
    };
    var r = {loc: toLoc(prog.loc), type: "prog"};
    r.tag = "Coq_prog_intro";
    // TODO deal with strictness
    r.strictness = false;
    r.elements = toList(prog.body.map(trStatAsElement));
    return r;
  };

  var trStatAsElement = function (stat) {
    var loc = toLoc(stat.loc);
    var r = {loc: loc, type: "element"};
    if (stat.type === "FunctionDeclaration") {
      r.tag = "Coq_element_func_decl";
      r.func_name = stat.id ;
      r.arg_names = trParams(r.params);
      // TODO this could be detected by stat.expression of type bool
      if (stat.body.type !== "BlockStatement") {
        throw ("stat.body.type !== BlockStatement");
      };
      // TODO we don't know how to get source
      var blockStat = stat.body;
      var prog = {loc: loc, type: "prog", tag: "Coq_prog_intro",
                  strictness: false,
                  elements: toList(blockStat.body.map(trStatAsElement))};
      r.body = {loc: loc, type: "funcbody", tag: "Coq_funcbody_intro",
                prog: prog, source: ""};
    } else if (stat.type === "Statement") {
      r.tag = "Coq_element_stat";
      r.stat = trStat(stat);
    } else {
      throw ("trStatAsElement error: " + stat.type);
    }
    return r;
  };

  var trStat = function (stat) {
    var r = {loc: toLoc(stat.loc), type: "stat"};
    if (stat.type === "ExpressionStatement") {
      r.tag = "Coq_stat_expr";
      // TODO why is it different than Parser API that says expr
      r.expr = trExpr(stat.expression);
    } else if (stat.type === "BlockStatement") {
      r.tag = "Coq_stat_block";
      r.stats = toList(stat.body.map(trStat));
    } else {
      throw ("trStat error: " + stat.type);
    };
    return r;
  };

  var trExprAsLiteral = function (expr) {
    var r = {loc: toLoc(expr.loc), type: "literal"};
    var v = expr.value;
    var t = typeof(v);
    if (t === "null") {
      r.tag = "Coq_literal_null";
    } else if (t === "bool") {
      r.tag = "Coq_literal_bool";
      r.value = v;
    } else if (t === "number") {
      r.tag = "Coq_literal_number";
      r.value = v;
    } else if (t === "string") {
      r.tag = "Coq_literal_string";
      r.value = v;
    } else {
      throw ("trExprAsLiteral error: " + t);
    };
  };

  var trExpr = function (expr) {
    var r = {loc: toLoc(expr.loc), type: "expr"};
    if (expr.type === "ThisExpression") {
      r.tag = "Coq_expr_this";
    } else if (expr.tag === "Identifier") {
      r.tag = "Coq_expr_identifier";
      r.name = expr.name;
    } else if (expr.tag === "Literal") {
      r.tag = "Coq_expr_literal";
      r.value = trExprAsLiteral(expr);
    } else {
      throw ("trExpr error: " + expr.type);
    };
    return r;
  };

  return trProg(prog);
}
<commit_msg>variable declarations<commit_after>function esprimaToAST(prog) {
  var toList = function (array) {
    var r = {tag: "[]"};
    for (var i = array.length - 1; i >= 0; i--) {
      r = {tag: "::", head: array[i], tail: r};
    }
    return r;
  };

  var toLoc = function (pos) {
    if (pos === null) {throw "null position in esprima AST";};
    return {file: "input.js",
            start: {line: pos.start.line, col: pos.start.column},
            stop:  {line: pos.end.line, col: pos.end.column}};
  };

  var trProg = function (prog) {
    if (prog.type !== "Program") {
      throw ("trProg error: " + prog.type);
    };
    var r = {loc: toLoc(prog.loc), type: "prog"};
    r.tag = "Coq_prog_intro";
    // TODO deal with strictness
    r.strictness = false;
    r.elements = toList(prog.body.map(trStatAsElement));
    return r;
  };

  var trStatAsElement = function (stat) {
    var loc = toLoc(stat.loc);
    var r = {loc: loc, type: "element"};
    if (stat.type === "FunctionDeclaration") {
      r.tag = "Coq_element_func_decl";
      r.func_name = stat.id ;
      r.arg_names = trParams(r.params);
      // TODO this could be detected by stat.expression of type bool
      if (stat.body.type !== "BlockStatement") {
        throw ("stat.body.type !== BlockStatement");
      };
      // TODO we don't know how to get source
      var blockStat = stat.body;
      var prog = {loc: loc, type: "prog", tag: "Coq_prog_intro",
                  strictness: false,
                  elements: toList(blockStat.body.map(trStatAsElement))};
      r.body = {loc: loc, type: "funcbody", tag: "Coq_funcbody_intro",
                prog: prog, source: ""};
    } else /* if (stat.type <: "Statement") */  {
      r.tag = "Coq_element_stat";
      r.stat = trStat(stat);
    } // else {
    //   throw ("trStatAsElement error: " + stat.type);
    // }
    return r;
  };

  // return string
  var trPattern = function (pat) {
    if (pat.type === "Identifier") {
      return pat.name;
    } else {
      throw ("trPattern error: " + pat.type);
    }
  };

  // return the encoding of a pair
  var trVarDecl = function (decl) {
    var id = trPattern(decl.id);
    var eo = {type: "option"};
    if (decl.init === null) {
      eo.tag = "None";
    } else {
      eo.tag = "Some";
      eo.value = trExpr(decl.init);
    }
    return [id,eo];
  };

  var trStat = function (stat) {
    var r = {loc: toLoc(stat.loc), type: "stat"};
    if (stat.type === "ExpressionStatement") {
      r.tag = "Coq_stat_expr";
      // TODO why is it different than Parser API that says expr
      r.expr = trExpr(stat.expression);
    } else if (stat.type === "BlockStatement") {
      r.tag = "Coq_stat_block";
      r.stats = toList(stat.body.map(trStat));
    } else if (stat.type === "VariableDeclaration") {
      r.tag = "Coq_stat_var_decl";
      r.decls = toList(stat.declarations.map(trVarDecl));
    } else {
      throw ("trStat error: " + stat.type);
    };
    return r;
  };

  var trExprAsLiteral = function (expr) {
    var r = {loc: toLoc(expr.loc), type: "literal"};
    var v = expr.value;
    var t = typeof(v);
    if (t === "null") {
      r.tag = "Coq_literal_null";
    } else if (t === "bool") {
      r.tag = "Coq_literal_bool";
      r.value = v;
    } else if (t === "number") {
      r.tag = "Coq_literal_number";
      r.value = v;
    } else if (t === "string") {
      r.tag = "Coq_literal_string";
      r.value = v;
    } else {
      throw ("trExprAsLiteral error: " + t);
    };
    return r;
  };

  var trExpr = function (expr) {
    var r = {loc: toLoc(expr.loc), type: "expr"};
    if (expr.type === "ThisExpression") {
      r.tag = "Coq_expr_this";
    } else if (expr.type === "Identifier") {
      r.tag = "Coq_expr_identifier";
      r.name = expr.name;
    } else if (expr.type === "Literal") {
      r.tag = "Coq_expr_literal";
      r.value = trExprAsLiteral(expr);
    } else {
      throw ("trExpr error: " + expr.type);
    };
    return r;
  };

  return trProg(prog);
}

function testParse(s) {
  var p = esprima.parse(s,{loc: true});
  console.log(p);
  console.log(esprimaToAST(p));
}
<|endoftext|>


<commit_before>var path = require('path');
var expect = require('chai').expect;
var pkg = path.normalize(
  path.join(__dirname, '..', '..', '..', 'package.json'));
var types = require('../../..').types;

describe('cli-command:', function() {

  it('should group arguments into object', function(done) {
    var cli = require('../../..')(pkg);
    var scheme = 'http';
    var host = 'nodejs.org';
    var port = '80';
    var args = ['-s', scheme, '-h', host, '--port=' + port];
    cli
      .option('-s, --scheme <scheme>',
        'transport scheme', types.object('server'))
      .option('-h, --host <host>',
        'server hostname', types.object('server'))
      .option('-p, --port <n>',
        'server port', types.object('server'))
    cli.parse(args);
    expect(cli.server).to.eql({scheme: scheme, host: host, port: port });
    done();
  });

  it('should group arguments into object (nested array)', function(done) {
    var cli = require('../../..')(pkg);
    var scheme = 'http';
    var node = 'nodejs.org';
    var npm = 'npmjs.org';
    var port = '80';
    var args = ['-s', scheme, '-h', node, '--host=' + npm, '--port=' + port];
    cli
      .option('-s, --scheme <scheme>',
        'transport scheme', types.object('server'))
      .option('-h, --host <host...>',
        'server hostname', types.object('server'))
      .option('-p, --port <n>',
        'server port', types.object('server'))
    cli.parse(args);
    expect(cli.server).to.eql({scheme: scheme, host: [node, npm], port: port });
    done();
  });
})
<commit_msg>Remove migrated object type test.<commit_after><|endoftext|>


<commit_before>//viewmodel for the assess page
function pageViewModel(gvm) {
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.werkficheID = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheID");}, gvm);
    gvm.werkficheName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheName");}, gvm);
    gvm.werkficheDate = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheDate");}, gvm);
    gvm.werkficheAction = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheAction");}, gvm);

    gvm.availableCourses = ko.observableArray([]);
    gvm.availableStudentlists = ko.observableArray([]);
    gvm.availableStudents = ko.observableArray([]);

    gvm.currentCourseId = null;
    gvm.currentStudentlistId = null;
    gvm.currentStudentId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownrapporten/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-courseRapport span:first").text(item.course);
                    $(".btn-studentlist span:first").text(item.studentlist);
                    $('.btn-student span:first').text(item.student);
                    gvm.currentCourseId = item.courseid;
                    gvm.currentStudentlistId = item.studentlistid;
                    gvm.currentStudentId = item.studentid;
                    gvm.updateCourseRapport();
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateCourseRapport();
            }
        });
    }

    //Houdt bij wat geselecteerd wordt
    //Wordt opgeroepen bij iedere wijziging (niet ingevulde velden = NULL)
    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["user"] = gvm.userId;
        data["course"] = $(".btn-courseRapport span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["studentlist"] = $('.btn-studentlist span:first').text();
        data["studentlistid"] = gvm.currentStudentlistId;
        data["student"] = $(".btn-student span:first").text();
        data["studentid"] = gvm.currentStudentId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdownsRapport",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateCourseRapport = function() {
        $.getJSON('/api/coursefromteacher/' + gvm.userId, function(data) {
            console.log(gvm.userId);
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                //  Put item in list
                gvm.availableCourses.push(item);

                // Add listener to listitem
                $("#coursebtn-" + item.id).click(function(){
                    gvm.currentCourseId = item.id;
                    gvm.currentStudentlistId = null;
                    gvm.currentStudentId = null;
                    gvm.updateStudentlists(item.id, gvm.userId);
                    $(".btn-courseRapport span:first").text($(this).text());
                    $(".btn-studentlist span:first").text("Studentlist");
                    $('.btn-student span:first').text("Student");
                    gvm.saveLastSelectedDropdowns();
                });
            });
        });
    };

    /*
     * Update the student data
     */
    gvm.updateStudentlists = function(cid, uid) {
        //get all studentlists
        $.getJSON('api/studentlistdrop/' + cid + '/' + uid, function(data) {
            gvm.availableStudentlists.removeAll();
            $.each(data, function(i,item) {
                // Put item in list
                gvm.availableStudentlists.push(item);

                // Add listener to listitem
                $("#studentlistbtn-" + item.id).click(function(){
                    gvm.currentStudentlistId = item.id;
                    gvm.currentStudentId = null;
                    gvm.updateStudents(item.id);
                    $(".btn-studentlist span:first").text($(this).text());
                    $('.btn-student span:first').text("Student");
                    gvm.saveLastSelectedDropdowns();
                });
            })
        })
    }

    /*
     * Update the student data
     */
    gvm.updateStudents = function(id) {
        //get all students who follow that course
        $.getJSON('api/studentdrop/' + id, function(data) {
            gvm.availableStudents.removeAll();
            $.each(data, function(i,item) {
                // Put item in list
                gvm.availableStudents.push(item);

                // Add listener to listitem
                $("#studentbtn-" + item.id).click(function(){
                    gvm.currentStudentId = item.id;
                    $(".btn-student span:first").text($(this).text());
                    gvm.saveLastSelectedDropdowns();
                });
            })
        })
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, name, lastname, mail, score) {
        // Push data
        var tblOject = {tstudid: id, tname: name, tlname: lastname, tmail: mail, tscore: score};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function getAllWorksheets() {
    $.getJSON('/api/worksheets/' + gvm.courseid, function(data) {
        $.each(data, function(i, item) {
            console.log(data);
        });
    });
}

function loadTablePage(pagenr)
{
    $.getJSON('/api/worksheets/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id,  item.firstname, item.lastname, item.mail);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });

    $('#addGroupForm').hide();

    $('#addWorksheetBtn').click(function() {
        $("#addGroupForm").show();
        $('#worksheetComplete').autocomplete({ source: getAllWorksheets() });
    });

    $('#addNewWorksheetBtn').click(function() {

        console.log("toevoegen")
        //effectief toevoegen
        //table herladen

        //Indien gewenst toevoegformulier weer verbergen.
        $('#addGroupForm').hide();
    });
}<commit_msg>Make it possible to add worksheets for a specific course.<commit_after>var $selectedcourseid;

//viewmodel for the assess page
function pageViewModel(gvm) {
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.werkficheID = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheID");}, gvm);
    gvm.werkficheName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheName");}, gvm);
    gvm.werkficheDate = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheDate");}, gvm);
    gvm.werkficheAction = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheAction");}, gvm);

    gvm.availableCourses = ko.observableArray([]);
    gvm.availableStudentlists = ko.observableArray([]);
    gvm.availableStudents = ko.observableArray([]);

    gvm.currentCourseId = null;
    gvm.currentStudentlistId = null;
    gvm.currentStudentId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownrapporten/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-courseRapport span:first").text(item.course);
                    $(".btn-studentlist span:first").text(item.studentlist);
                    $('.btn-student span:first').text(item.student);
                    gvm.currentCourseId = item.courseid;
                    gvm.currentStudentlistId = item.studentlistid;
                    gvm.currentStudentId = item.studentid;
                    gvm.updateCourseRapport();
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateCourseRapport();
            }
        });
    }

    //Houdt bij wat geselecteerd wordt
    //Wordt opgeroepen bij iedere wijziging (niet ingevulde velden = NULL)
    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["user"] = gvm.userId;
        data["course"] = $(".btn-courseRapport span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["studentlist"] = $('.btn-studentlist span:first').text();
        data["studentlistid"] = gvm.currentStudentlistId;
        data["student"] = $(".btn-student span:first").text();
        data["studentid"] = gvm.currentStudentId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdownsRapport",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateCourseRapport = function() {
        $.getJSON('/api/coursefromteacher/' + gvm.userId, function(data) {
            console.log(gvm.userId);
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                //  Put item in list
                gvm.availableCourses.push(item);

                // Add listener to listitem
                $("#coursebtn-" + item.id).click(function(){
                    gvm.currentCourseId = item.id;
                    $selectedcourseid = item.id;
                    gvm.currentStudentlistId = null;
                    gvm.currentStudentId = null;
                    gvm.updateStudentlists(item.id, gvm.userId);
                    $(".btn-courseRapport span:first").text($(this).text());
                    $(".btn-studentlist span:first").text("Studentlist");
                    $('.btn-student span:first').text("Student");
                    gvm.saveLastSelectedDropdowns();
                });
            });
        });
    };

    /*
     * Update the student data
     */
    gvm.updateStudentlists = function(cid, uid) {
        //get all studentlists
        $.getJSON('api/studentlistdrop/' + cid + '/' + uid, function(data) {
            gvm.availableStudentlists.removeAll();
            $.each(data, function(i,item) {
                // Put item in list
                gvm.availableStudentlists.push(item);

                // Add listener to listitem
                $("#studentlistbtn-" + item.id).click(function(){
                    gvm.currentStudentlistId = item.id;
                    gvm.currentStudentId = null;
                    gvm.updateStudents(item.id);
                    $(".btn-studentlist span:first").text($(this).text());
                    $('.btn-student span:first').text("Student");
                    gvm.saveLastSelectedDropdowns();
                });
            })
        })
    }

    /*
     * Update the student data
     */
    gvm.updateStudents = function(id) {
        //get all students who follow that course
        $.getJSON('api/studentdrop/' + id, function(data) {
            gvm.availableStudents.removeAll();
            $.each(data, function(i,item) {
                // Put item in list
                gvm.availableStudents.push(item);

                // Add listener to listitem
                $("#studentbtn-" + item.id).click(function(){
                    gvm.currentStudentId = item.id;
                    $(".btn-student span:first").text($(this).text());
                    gvm.saveLastSelectedDropdowns();
                });
            })
        })
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, name, lastname, mail, score) {
        // Push data
        var tblOject = {tstudid: id, tname: name, tlname: lastname, tmail: mail, tscore: score};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function getAllWorksheets() {
    $.getJSON('/api/worksheets/' + $selectedcourseid, function(data) {
        $.each(data, function(i, item) {
            console.log(data);
        });
    });
}

function loadTablePage(pagenr)
{
    $.getJSON('/api/worksheets/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id,  item.firstname, item.lastname, item.mail);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });

    $('#addGroupForm').hide();

    $('#addWorksheetBtn').click(function() {
        $("#addGroupForm").show();
        $('#worksheetComplete').autocomplete({ source: getAllWorksheets() });
    });

    $('#addNewWorksheetBtn').click(function() {

        console.log("toevoegen")
        //effectief toevoegen
        //table herladen

        //Indien gewenst toevoegformulier weer verbergen.
        $('#addGroupForm').hide();
    });
}<|endoftext|>


<commit_before>// JenScript -  JavaScript SVG Framework
// Product of JenSoftAPI - Visualization Frameworks
// version : @VERSION
//
// Author : JenSoft API
// Author : Sebastien Janaud
//
// Web Site : http://www.jensoftapi.com/
// Twitter  : http://twitter.com/JenSoftAPI
//
//
// Copyright (C) 2008 - 2015 JenScript, product by JenSoftAPI company, France.
// build: @DATE
//
// All Rights reserved
<commit_msg>update header<commit_after>// JenScript -  JavaScript HTML5/SVG Library
// Product of JenSoftAPI - Visualization Java & JS Libraries
// version : @VERSION
// Author : Sebastien Janaud
// Web Site : http://jenscript.io
// Twitter  : http://twitter.com/JenSoftAPI
// Copyright (C) 2008 - 2015 JenScript, product by JenSoftAPI company, France.
// build: @DATE
// All Rights reserved
<|endoftext|>