<commit_before>/**
 * A class for dynamically generating menus.
 *
 * hash structure:
 * var hash = [
 * 	{
 * 		'label':"Menu label",
 * 		'id':"a_unique_id", // optional, not used if not present
 * 		'class':"menu_label", // optional, generated if not present
 * 		'handler':function(e, data) {}, // a handler. will be listening via delegation
 * 		'data':{} // some data, passed as second param to onClick handler
 * 		}
 *
 * ];
 *
 *
 *
 * @param {object} opts options
 * @param {array}  opts.items menu item objects
 * @param {array}  opts.items.label item label (shown to user)
 * @param {string} [opts.items.id] item element id - not used if not present
 * @param {string} [opts.items.class] item element class - generated if not present
 * @param {function} opts.items.handler click event handler, will be listening via delegation
 * @param {object} [opts.items.data] passed as second param to onClick handler
 *
 * @param {string} [opts.base_id] the id attribute for the menu's base element. default is 'spaz_menu'
 * @param {string} [opts.base_class] the class attribute for the menu's base element. default is 'spaz_menu'
 * @param {string} [opts.li_class] the class attribute for the menu's base element. default is 'spaz_menu_li'
 * @param {string} [opts.show_immediately] whether or not to immediately show the menu on creation. Default is TRUE
 */
SpazMenu = function(trigger_event, opts) {
	this.trigger_event = trigger_event;
	this.opts = sch.defaults({
		'items'     :[],
		'base_id'   :'spaz_menu',
		'base_class':'spaz_menu',
		'li_class'  :'spaz_menu_li',
		'show_immediately':true
	}, opts);

	this.items = this.opts.items;

	this.create();

	if (this.opts.show_immediately) {
		this.show(this.trigger_event);
	}
};

/**
 * Creates the menu, but doesn't show
 */
SpazMenu.prototype.create = function() {

	var that = this;

	// create base DOM elements
	jQuery('body').append(this._tplBase());

	// iterate over items
	var item, itemhtml;
	for (var i=0; i < this.items.length; i++) {
		item = this.items[i];
		if (!item['class']) {
			item['class'] = this._generateItemClass(item);
		}
		itemhtml = this._tplItem(item);

		// -- add item DOM element
		jQuery('#'+this.opts.base_id).append(itemhtml);

		// -- add delegated handler
		jQuery(document).delegate('.'+item['class'], 'click', {'item':item, 'spazmenu':this}, function(e, data) {
			e.data.item.handler.call(this, e, e.data.item.data||data);
			e.data.spazmenu.hide();
			e.data.spazmenu.destroy();
		});

	}
};

/**
 * shows a created menu
 */
SpazMenu.prototype.show = function(e, data) {
	sch.debug('show');
	this._postionBeforeShow(e, data);
	jQuery('#'+this.opts.base_id).show();
	this._reposition(e, data);
};

/**
 * hides a created menu
 */
SpazMenu.prototype.hide = function() {
	sch.debug('hide');
	jQuery('#'+this.opts.base_id).hide();
};

/**
 * destroys a menu completely (DOM and JS object)
 */
SpazMenu.prototype.destroy = function() {
	sch.debug('destroy');

	// iterate over item hash
	var item;
	for (var i=0; i < this.items.length; i++) {
		item = this.items[i];
		if (!item['class']) {
			item['class'] = this._generateItemClass(item);
		}

		// -- remove each delegated handler
		jQuery(document).undelegate('.'+item['class'], 'click');
	}

	// remove base DOM element
	jQuery('#'+this.opts.base_id).remove();
};

/**
 * sets the position of the menu right before we show it
 */
SpazMenu.prototype._postionBeforeShow = function(e, data) {
	sch.debug('_postionBeforeShow');
	var jqtrigger = jQuery(e.target);
	var top  = jqtrigger.position().top + jqtrigger.height();
	var left = jqtrigger.position().left+ jqtrigger.width();
	jQuery('#'+this.opts.base_id).css('top', top);
	jQuery('#'+this.opts.base_id).css('left', left);
};

/**
 * Repositions the menu after showing in case we're outside the viewport boundaries
 */
SpazMenu.prototype._reposition = function(e, data) {
	sch.debug('_reposition');
};

SpazMenu.prototype._generateItemClass = function(item) {
	return item.label.replace(/[^a-z]/gi, '_').toLowerCase();
};

SpazMenu.prototype._tplBase = function() {

	var html = '';

	html += '
';
	html += '
';
	html += '
';
	html += '
';

	sch.debug(html);

	return html;
};

SpazMenu.prototype._tplItem = function(i) {
	var html = '';

	html += '
'+i.label+'
';

	sch.debug(html);

	return html;
};<commit_msg>minor docblock updates<commit_after>/**
 * A class for dynamically generating menus.
 *
 * hash structure:
 * var hash = [
 * 	{
 * 		'label':"Menu label",
 * 		'id':"a_unique_id", // optional, not used if not present
 * 		'class':"menu_label", // optional, generated if not present
 * 		'handler':function(e, data) {}, // a handler. will be listening via delegation
 * 		'data':{} // some data, passed as second param to onClick handler
 * 		}
 *
 * ];
 *
 *
 * @param {object} trigger_event the event that is triggering the creation of this menu. needed for positioning
 *
 * @param {object} opts options
 *
 * @param {array}  opts.items menu item objects
 * @param {array}  opts.items.label item label (shown to user)
 * @param {string} [opts.items.id] item element id - not used if not present
 * @param {string} [opts.items.class] item element class - generated if not present
 * @param {function} opts.items.handler click event handler, will be listening via delegation
 * @param {object} [opts.items.data] passed as second param to onClick handler
 *
 * @param {string} [opts.base_id] the id attribute for the menu's base element. default is 'spaz_menu'
 * @param {string} [opts.base_class] the class attribute for the menu's base element. default is 'spaz_menu'
 * @param {string} [opts.li_class] the class attribute for the menu's base element. default is 'spaz_menu_li'
 * @param {string} [opts.show_immediately] whether or not to immediately show the menu on creation. Default is TRUE
 */
SpazMenu = function(trigger_event, opts) {
	this.trigger_event = trigger_event;
	this.opts = sch.defaults({
		'items'     :[],
		'base_id'   :'spaz_menu',
		'base_class':'spaz_menu',
		'li_class'  :'spaz_menu_li',
		'show_immediately':true
	}, opts);

	this.items = this.opts.items;

	this.create();

	if (this.opts.show_immediately) {
		this.show(this.trigger_event);
	}
};

/**
 * Creates the menu, but doesn't show
 */
SpazMenu.prototype.create = function() {

	var that = this;

	// create base DOM elements
	jQuery('body').append(this._tplBase());

	// iterate over items
	var item, itemhtml;
	for (var i=0; i < this.items.length; i++) {
		item = this.items[i];
		if (!item['class']) {
			item['class'] = this._generateItemClass(item);
		}
		itemhtml = this._tplItem(item);

		// -- add item DOM element
		jQuery('#'+this.opts.base_id).append(itemhtml);

		// -- add delegated handler
		jQuery(document).delegate('.'+item['class'], 'click', {'item':item, 'spazmenu':this}, function(e, data) {
			e.data.item.handler.call(this, e, e.data.item.data||data);
			e.data.spazmenu.hide();
			e.data.spazmenu.destroy();
		});

	}
};

/**
 * shows a created menu
 */
SpazMenu.prototype.show = function(e, data) {
	sch.debug('show');
	this._postionBeforeShow(e, data);
	jQuery('#'+this.opts.base_id).show();
	this._reposition(e, data);
};

/**
 * hides a created menu
 */
SpazMenu.prototype.hide = function() {
	sch.debug('hide');
	jQuery('#'+this.opts.base_id).hide();
};

/**
 * destroys a menu completely (DOM and JS object)
 */
SpazMenu.prototype.destroy = function() {
	sch.debug('destroy');

	// iterate over item hash
	var item;
	for (var i=0; i < this.items.length; i++) {
		item = this.items[i];
		if (!item['class']) {
			item['class'] = this._generateItemClass(item);
		}

		// -- remove each delegated handler
		jQuery(document).undelegate('.'+item['class'], 'click');
	}

	// remove base DOM element
	jQuery('#'+this.opts.base_id).remove();
};

/**
 * sets the position of the menu right before we show it
 */
SpazMenu.prototype._postionBeforeShow = function(e, data) {
	sch.debug('_postionBeforeShow');
	var jqtrigger = jQuery(e.target);
	var top  = jqtrigger.position().top + jqtrigger.height();
	var left = jqtrigger.position().left+ jqtrigger.width();
	jQuery('#'+this.opts.base_id).css('top', top);
	jQuery('#'+this.opts.base_id).css('left', left);
};

/**
 * Repositions the menu after showing in case we're outside the viewport boundaries
 */
SpazMenu.prototype._reposition = function(e, data) {
	sch.debug('_reposition');
};

/**
 * this generates the item class if one has not been provided
 */
SpazMenu.prototype._generateItemClass = function(item) {
	return item.label.replace(/[^a-z]/gi, '_').toLowerCase();
};

/**
 * generates the html for the base DOM elements
 */
SpazMenu.prototype._tplBase = function() {

	var html = '';

	html += '
';
	html += '
';
	html += '
';
	html += '
';

	sch.debug(html);

	return html;
};

/**
 * generates the HTML for a menu item
 * @param {object} i the item object
 */
SpazMenu.prototype._tplItem = function(i) {
	var html = '';

	html += '
'+i.label+'
';

	sch.debug(html);

	return html;
};<|endoftext|>


<commit_before>import Messages from "../constants/Messages";
import Util from "../helpers/Util";

import ValidConstraints from "./ValidConstraints";

const applicationFieldValidationErrors = Util.deepFreeze({
  appId: [
    "ID must not be empty",
    "Path must not contain whitespace",
    "Path contains invalid characters " +
      "(allowed: lowercase letters, digits, hyphens, \".\", \"..\")",
    "Path is not well-formed"
  ],
  constraints: [
    "Invalid constraints format or operator. Supported operators are " +
    ValidConstraints.map((c) => `'${c}'`).join(", ") +
    ". See https://mesosphere.github.io/marathon/docs/constraints.html"
  ],
  containerVolumes: [
    "Container Path must be a valid path",
    "Host Path must be a valid path",
    "Mode must not be empty",
    "Container Path and Host Path must be set."
  ],
  localVolumes: [
    "Size must be a non-negative number",
    "Container Path must be a valid path",
    "Container Path and Size must be set"
  ],
  cpus: ["CPUs must be a number greater than or equal to 0.01"],
  disk: ["Disk Space must be a non-negative number"],
  dockerImage: ["Image cannot contain whitespaces"],
  dockerParameters: ["Key cannot be blank"],
  env: ["Key cannot be blank"],
  executor: ["Invalid executor format"],
  healthChecks: [
    "Incorrect protocol given",
    "Command must not be emtpy",
    "Path must not be empty",
    "Port Index must be a non-negative number",
    "Port Number must be a valid port between 0 - 65535",
    "Grace Period must be a non-negative number",
    "Interval must be a non-negative number",
    "Timeout must be a non-negative number",
    "Maximal Consecutive Failures must be a non-negative number"
  ],
  instances: ["Instances must be a non-negative number"],
  labels: ["Key cannot be blank"],
  mem: ["Memory must be a number greater than or equal to 32"],
  portDefinitions: [
    "Port must be a valid port",
    "Protocol must be either 'tcp' or 'udp'"
  ],
});

const generalErrors = Util.deepFreeze({
  appCreation:
    "App creation unsuccessful. Check your app settings and try again.",
  appLocked: "App is currently locked by one or more deployments. " +
    "Press the button again to forcefully change and deploy " +
    "the new configuration.",
  unknownServerError: "Unknown server error. Could not create or apply app.",
  unauthorizedAccess: `App creation unsuccessful. ${Messages.UNAUTHORIZED}`,
  forbiddenAccess: `App creation unsuccessful. ${Messages.FORBIDDEN}`,
  errorPrefix: "Error:"
});

const serverResponseMappings = Util.deepFreeze({
  "error.path.missing": "Specify a path",
  "error.minLength": "Command may not be blank",
  "error.expected.jsnumber": "A number is expected",
  "error.expected.jsstring": "A string is expected"
});

const AppFormErrorMessages = {
  getFieldMessage: function (fieldId, index = 0) {
    if (applicationFieldValidationErrors[fieldId] != null &&
        applicationFieldValidationErrors[fieldId][index] != null) {
      return applicationFieldValidationErrors[fieldId][index];
    }
    return "Undefined error";
  },

  getGeneralMessage: function (key) {
    if (generalErrors[key] != null) {
      return generalErrors[key];
    }
    return "General error";
  },

  lookupServerResponseMessage: function (serverMessage) {
    if (serverResponseMappings[serverMessage] != null) {
      return serverResponseMappings[serverMessage];
    }
    return serverMessage;
  }
};

export default Util.deepFreeze(AppFormErrorMessages);
<commit_msg>Constraints should be uppercase<commit_after>import Messages from "../constants/Messages";
import Util from "../helpers/Util";

import ValidConstraints from "./ValidConstraints";

const applicationFieldValidationErrors = Util.deepFreeze({
  appId: [
    "ID must not be empty",
    "Path must not contain whitespace",
    "Path contains invalid characters " +
      "(allowed: lowercase letters, digits, hyphens, \".\", \"..\")",
    "Path is not well-formed"
  ],
  constraints: [
    "Invalid constraints format or operator. Supported operators are " +
    ValidConstraints.map((c) => `'${c.toUpperCase()}'`).join(", ") +
    ". See https://mesosphere.github.io/marathon/docs/constraints.html"
  ],
  containerVolumes: [
    "Container Path must be a valid path",
    "Host Path must be a valid path",
    "Mode must not be empty",
    "Container Path and Host Path must be set."
  ],
  localVolumes: [
    "Size must be a non-negative number",
    "Container Path must be a valid path",
    "Container Path and Size must be set"
  ],
  cpus: ["CPUs must be a number greater than or equal to 0.01"],
  disk: ["Disk Space must be a non-negative number"],
  dockerImage: ["Image cannot contain whitespaces"],
  dockerParameters: ["Key cannot be blank"],
  env: ["Key cannot be blank"],
  executor: ["Invalid executor format"],
  healthChecks: [
    "Incorrect protocol given",
    "Command must not be emtpy",
    "Path must not be empty",
    "Port Index must be a non-negative number",
    "Port Number must be a valid port between 0 - 65535",
    "Grace Period must be a non-negative number",
    "Interval must be a non-negative number",
    "Timeout must be a non-negative number",
    "Maximal Consecutive Failures must be a non-negative number"
  ],
  instances: ["Instances must be a non-negative number"],
  labels: ["Key cannot be blank"],
  mem: ["Memory must be a number greater than or equal to 32"],
  portDefinitions: [
    "Port must be a valid port",
    "Protocol must be either 'tcp' or 'udp'"
  ],
});

const generalErrors = Util.deepFreeze({
  appCreation:
    "App creation unsuccessful. Check your app settings and try again.",
  appLocked: "App is currently locked by one or more deployments. " +
    "Press the button again to forcefully change and deploy " +
    "the new configuration.",
  unknownServerError: "Unknown server error. Could not create or apply app.",
  unauthorizedAccess: `App creation unsuccessful. ${Messages.UNAUTHORIZED}`,
  forbiddenAccess: `App creation unsuccessful. ${Messages.FORBIDDEN}`,
  errorPrefix: "Error:"
});

const serverResponseMappings = Util.deepFreeze({
  "error.path.missing": "Specify a path",
  "error.minLength": "Command may not be blank",
  "error.expected.jsnumber": "A number is expected",
  "error.expected.jsstring": "A string is expected"
});

const AppFormErrorMessages = {
  getFieldMessage: function (fieldId, index = 0) {
    if (applicationFieldValidationErrors[fieldId] != null &&
        applicationFieldValidationErrors[fieldId][index] != null) {
      return applicationFieldValidationErrors[fieldId][index];
    }
    return "Undefined error";
  },

  getGeneralMessage: function (key) {
    if (generalErrors[key] != null) {
      return generalErrors[key];
    }
    return "General error";
  },

  lookupServerResponseMessage: function (serverMessage) {
    if (serverResponseMappings[serverMessage] != null) {
      return serverResponseMappings[serverMessage];
    }
    return serverMessage;
  }
};

export default Util.deepFreeze(AppFormErrorMessages);
<|endoftext|>


<commit_before>/*
 * bootpag - jQuery plugin for dynamic pagination
 *
 * Copyright (c) 2012 botmonster@7items.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://botmonster.github.com/jquery-bootpag
 *
 * Version:  1.0
 *
 */
(function($, window) {

    $.fn.bootpag = function(options){

        var $owner = this,
            settings = $.extend({
                total: 0,
                page: 1,
                maxVisible: null,
                leaps: true,
                href: 'javascript:void(0);',
                hrefVariable: '{{number}}',
                next: '»',
                prev: '«'
            }, options || {});

        if(settings.total <= 0)
            return this;
        if(!settings.maxVisible){
            settings.maxVisible = settings.total;
        }

        function paginationClick(){

            var me = $(this), lp;

            if(me.hasClass('disabled')){
                return;
            }
            var page = parseInt(me.attr('data-lp'), 10),
                vis = Math.floor(page / settings.maxVisible) * settings.maxVisible,
                $page = me.parent().find('li');

            $page.removeClass('disabled');
            lp = page - 1 < 1 ? 1 :
                    settings.leaps && page - 1 > settings.maxVisible ?
                        Math.floor((page - 1) / settings.maxVisible) * settings.maxVisible : page - 1;
            $page
                .first()
                .toggleClass('disabled', page === 1)
                .attr('data-lp', lp)
                .find('a').attr('href', href(lp));
            lp = page + 1 > settings.total ? settings.total :
                    settings.leaps && page + 1 < settings.total - settings.maxVisible ?
                        vis + settings.maxVisible + 1: page + 1;
            $page
                .last()
                .toggleClass('disabled', page === settings.total)
                .attr('data-lp', lp)
                .find('a').attr('href', href(lp));;

            var $currPage = $page.filter('[data-lp='+page+']');
            if(!$currPage.not('.next,.prev').length){
                var d = page <= vis ? -settings.maxVisible : 0;
                $page.not('.next,.prev').each(function(index){
                    lp = index + 1 + vis + d;
                    $(this)
                        .attr('data-lp', lp)
                        .toggle(lp <= settings.total)
                        .find('a').html(lp).attr('href', href(lp));
                });
                $currPage = $page.filter('[data-lp='+page+']');
            }
            $currPage.addClass('disabled');
            $owner.trigger('page', page);
        }

        function href(c){

            return settings.href.replace(settings.hrefVariable, c);
        }

        return this.each(function(){

            var lp, me = $(this),
                p = ['
'];

            if(settings.prev){
                p.push('
'+settings.prev+'
');
            }
            for(var c = 1; c <= Math.min(settings.total, settings.maxVisible); c++){
                p.push('
'+c+'
');
            }
            if(settings.next){
                lp = settings.leaps && settings.total > settings.maxVisible
                    ? Math.min(settings.maxVisible + 1, settings.total) : 2;
                p.push('
'+settings.next+'
');
            }
            p.push('
');
            me.append(p.join('')).addClass('pagination');
            me.find('li[data-lp=1]').addClass('disabled');
            me.find('li').click(paginationClick);
        });
    }

})(jQuery, window);
<commit_msg>fix #1 - Initial page parameter isn't respected<commit_after>/*
 * bootpag - jQuery plugin for dynamic pagination
 *
 * Copyright (c) 2013 botmonster@7items.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://botmonster.github.com/jquery-bootpag
 *
 * Version:  1.0.1
 *
 */
(function($, window) {

    $.fn.bootpag = function(options){

        var $owner = this,
            settings = $.extend({
                total: 0,
                page: 1,
                maxVisible: null,
                leaps: true,
                href: 'javascript:void(0);',
                hrefVariable: '{{number}}',
                next: '»',
                prev: '«'
            }, options || {});

        if(settings.total <= 0)
            return this;

        if(!settings.maxVisible){
            settings.maxVisible = settings.total;
        }

        function renderPage(page){

            var lp,
                vis = Math.floor(page / settings.maxVisible) * settings.maxVisible,
                $page = $owner.find('li');

            $page.removeClass('disabled');
            lp = page - 1 < 1 ? 1 :
                    settings.leaps && page - 1 > settings.maxVisible ?
                        Math.floor((page - 1) / settings.maxVisible) * settings.maxVisible : page - 1;
            $page
                .first()
                .toggleClass('disabled', page === 1)
                .attr('data-lp', lp)
                .find('a').attr('href', href(lp));
            lp = page + 1 > settings.total ? settings.total :
                    settings.leaps && page + 1 < settings.total - settings.maxVisible ?
                        vis + settings.maxVisible + 1: page + 1;
            $page
                .last()
                .toggleClass('disabled', page === settings.total)
                .attr('data-lp', lp)
                .find('a').attr('href', href(lp));;

            var $currPage = $page.filter('[data-lp='+page+']');
            if(!$currPage.not('.next,.prev').length){
                var d = page <= vis ? -settings.maxVisible : 0;
                $page.not('.next,.prev').each(function(index){
                    lp = index + 1 + vis + d;
                    $(this)
                        .attr('data-lp', lp)
                        .toggle(lp <= settings.total)
                        .find('a').html(lp).attr('href', href(lp));
                });
                $currPage = $page.filter('[data-lp='+page+']');
            }
            $currPage.addClass('disabled');
            $owner.trigger('page', page);
        }

        function paginationClick(){

            var me = $(this);

            if(me.hasClass('disabled')){
                return;
            }
            renderPage(parseInt(me.attr('data-lp'), 10));
        }

        function href(c){

            return settings.href.replace(settings.hrefVariable, c);
        }

        return this.each(function(){

            var lp, me = $(this),
                p = ['
'];

            if(settings.prev){
                p.push('
'+settings.prev+'
');
            }
            for(var c = 1; c <= Math.min(settings.total, settings.maxVisible); c++){
                p.push('
'+c+'
');
            }
            if(settings.next){
                lp = settings.leaps && settings.total > settings.maxVisible
                    ? Math.min(settings.maxVisible + 1, settings.total) : 2;
                p.push('
'+settings.next+'
');
            }
            p.push('
');
            me.append(p.join('')).addClass('pagination');
            me.find('li').click(paginationClick);
            renderPage(settings.page);
        });
    }

})(jQuery, window);
<|endoftext|>


<commit_before>(function($) {
  $.shining = function() {
    $.shining.slides = {
      get length()      { return this._slides.length },
      get current()     { return (typeof this._current == 'undefined' ? this._slides[0] : this._slides[this._current]) },
      set current(_new) { this._current = this._slides.indexOf(_new); return this.current },
      get all()         { return this._slides },
      get first()       { return this._slides[0] },
      get last()        { return this._slides[ this._slides.length - 1 ] },
      get next()        { return this._slides[ this._slides.indexOf(this.current) + 1 ] },
      get previous()    { return this._slides[ this._slides.indexOf(this.current) - 1 ] },
      add: function(slides) { return Array.prototype.push.apply(this._slides, slides) },
      _slides: [],
      _current: 0
    };

    String.prototype.markup = function() { return this + '.html' };
    String.prototype.script = function() { return this + '.js' };
    String.prototype.style =  function() { return this + '.css' };

    $.extend($.shining, {
      firstSlide:     function() { getSlide($.shining.slides.first) },
      lastSlide:      function() { getSlide($.shining.slides.last ) },
      nextSlide:      function() { getSlide($.shining.slides.next) },
      previousSlide:  function() { getSlide($.shining.slides.previous) }
    });

    function init()         {
      $(document).ready(function() {
        $('#controls').ondistance(
          300,
          function(controls) { $(controls).addClass('fades-in') },
          function(controls) { $(controls).removeClass('fades-in') }
        );
        $('#controls #first').    click(function() { $.shining.firstSlide() });
        $('#controls #previous'). click(function() { $.shining.previousSlide() });
        $('#controls #next').     click(function() { $.shining.nextSlide() });
        $('#controls #last').     click(function() { $.shining.lastSlide() });
        $('#stage').centralize();
      });
      $(window).resize(function() { $('#stage').centralize() });
      $(document).click(function(event) {
        if ($(event.target).is('a')) return false;
        if (event.pageX < ($(window).width() / 2)) {
          $.shining.previousSlide();
        } else {
          $.shining.nextSlide();
        }
      })
      loadConfig(function() {
        getSlide($.shining.slides.current);
        setTitle($.shining.config.title);
        setTheme($.shining.config.theme);
      });
    }

    function getSlide(name) {
      if (!name) return false;
      if ($.shining.config.transitions) {
        $('#stage').removeClass('fades-in');
        setTimeout(
          function() {
            loadSlide(name);
            setTimeout(
              function() {
                $('#stage').addClass('fades-in');
                $.shining.scripts.run($.shining.currentScript);
              },
            200);
          }, 200);
      } else {
        loadSlide(name);
      }
    }

    function setTitle(title) {
      if (!title) { return false };
      $('title').text(title);
    }

    function setTheme(name) {
      if (!name || name == "default") { return false };
      var path = $('link.theme').attr('href').replace('default.css', name + 'css');
      return $('link.theme').attr('href', path);
    }

    // private
    function slide(name) {
      return 'slides/' + name;
    }

    function vendored() {
      return $('script:first').attr('src').match(/^vendor/);
    }

    function loadSlide(name) {
      $('#stage').load(
        slide(name).markup(),
        function(data) {
          $.shining.slides.current = name;
          $('link.slide').remove(); // remove now previous slide styles
          if (SyntaxHighlighter) SyntaxHighlighter.highlight();
          $('#stage').centralize();
          $.shining.scripts.reap();
          if (data) {
            loadSlideScript(name);
            loadSlideStyle(name);
          }
        }
      );
    }

    function loadSlideScript(name) {
      $.get(slide(name).script(), function(script) {
        if ($.shining.config.transitions) {
          $.shining.currentScript = script;
        } else {
          $.shining.scripts.run(script)
        }
      })
    }

    function loadSlideStyle(name) {
      $('head').append('<link rel="stylesheet" type="text/css" href="' + slide(name).style() + '" media="all" class="slide"/>')
    }

    function loadConfig(callback) {
      $.getJSON('config.json', function(config) {
        $.shining.config = config;
        $.shining.slides.add(config.slides);
        if (config.transitions) {
          $('#stage').addClass('transparent fades-in');
        }
        callback.call();
      });
    }

    $.shining.scripts = {
      LINE: /^(\d[.\d]*),[\s]*(.*)/,
      parsed: [], processes: [],
      nextSlide:      function() { $.shining.nextSlide() },
      previousSlide:  function() { $.shining.previousSlide() },
      at:             function(seconds, method) {
        $.shining.scripts.processes.push(setTimeout(method, parseFloat(seconds) * 1000))
      },
      parse:          function(script) {
        var lines = script.split("\n"), tokens, parsed = [];
        for (var i = 0; lines.length > i; i++) {
          if ($.shining.scripts.LINE.test(lines[i])) {
            var tokens = lines[i].match($.shining.scripts.LINE);
            var time = tokens[1], code = tokens[2];
            parsed.push(time);
            if (code.length) parsed.push(code);
          } else {
            if (isNaN(parsed[parsed.length - 1])) {
              parsed[parsed.length - 1] += ("; " + lines[i]);
            } else {
              parsed.push(lines[i]);
            }
          }
        }
        return parsed;
      },
      run:          function(script) {
        var parsed = $.shining.scripts.parse(script), all = [];
        for (var i = 0; parsed.length > i; i += 2) {
          all.push(["at(", parsed[i], ", function() { ", parsed[i+1], " })"].join(''));
        }
        with($.shining.scripts) { eval(all.join(';')) };
      },
      reap: function() {
        $($.shining.scripts.processes).map(function() { clearTimeout(this) });
        return $.shining.scripts.processes = [];
      }
    }

    init();
  }
  // boots!
  $.shining();

})(jQuery);

// Dependencies!!

/*
 * JSizes - JQuery plugin v0.33
 *
 * Licensed under the revised BSD License.
 * Copyright 2008-2010 Bram Stein
 * All rights reserved.
 */
(function(b){var a=function(c){return parseInt(c,10)||0};b.each(["min","max"],function(d,c){b.fn[c+"Size"]=function(g){var f,e;if(g){if(g.width!==undefined){this.css(c+"-width",g.width)}if(g.height!==undefined){this.css(c+"-height",g.height)}return this}else{f=this.css(c+"-width");e=this.css(c+"-height");return{width:(c==="max"&&(f===undefined||f==="none"||a(f)===-1)&&Number.MAX_VALUE)||a(f),height:(c==="max"&&(e===undefined||e==="none"||a(e)===-1)&&Number.MAX_VALUE)||a(e)}}}});b.fn.isVisible=function(){return this.is(":visible")};b.each(["border","margin","padding"],function(d,c){b.fn[c]=function(e){if(e){if(e.top!==undefined){this.css(c+"-top"+(c==="border"?"-width":""),e.top)}if(e.bottom!==undefined){this.css(c+"-bottom"+(c==="border"?"-width":""),e.bottom)}if(e.left!==undefined){this.css(c+"-left"+(c==="border"?"-width":""),e.left)}if(e.right!==undefined){this.css(c+"-right"+(c==="border"?"-width":""),e.right)}return this}else{return{top:a(this.css(c+"-top"+(c==="border"?"-width":""))),bottom:a(this.css(c+"-bottom"+(c==="border"?"-width":""))),left:a(this.css(c+"-left"+(c==="border"?"-width":""))),right:a(this.css(c+"-right"+(c==="border"?"-width":"")))}}}})})(jQuery);

// http://github.com/juliocesar/jquery-ondistance
(function($){$.fn.ondistance=function(specified,close,far){var elt=this.get(0),last=new Date().getTime();$(document).mousemove(function(e){var current=new Date().getTime();if(current-last<500)return;var offset=$(elt).offset(),center={x:offset.left+($(elt).width()/2),y:offset.top+($(elt).height()/2)},last=current,distance=parseInt(Math.sqrt(Math.pow(e.pageX-center.x,2)+Math.pow(e.pageY-center.y,2)));if(specified>=distance){if($(elt).data('mouseclose')==true)return false;$(elt).data('mouseclose',true);close(elt);}else{if($(elt).data('mouseclose')==false)return false;$(elt).data('mouseclose',false);far(elt);}})}})(jQuery);

// centralizes an element vertically
(function($){$.fn.centralize=function(){var self=this.get(0);windowHeight=document.documentElement.clientHeight,elementHeight=(self.offsetHeight+$(self).padding().top+$(self).padding().bottom);$(self).css('position','relative').css('top',(windowHeight/2)-(elementHeight/2)+'px');};})(jQuery);<commit_msg>and we got ourselves a CSS parser ladies and gents<commit_after>(function($) {
  $.shining = function() {
    $.shining.slides = {
      get length()      { return this._slides.length },
      get current()     { return (typeof this._current == 'undefined' ? this._slides[0] : this._slides[this._current]) },
      set current(_new) { this._current = this._slides.indexOf(_new); return this.current },
      get all()         { return this._slides },
      get first()       { return this._slides[0] },
      get last()        { return this._slides[ this._slides.length - 1 ] },
      get next()        { return this._slides[ this._slides.indexOf(this.current) + 1 ] },
      get previous()    { return this._slides[ this._slides.indexOf(this.current) - 1 ] },
      add: function(slides) { return Array.prototype.push.apply(this._slides, slides) },
      _slides: [],
      _current: 0
    };

    String.prototype.markup = function() { return this + '.html' };
    String.prototype.script = function() { return this + '.js' };
    String.prototype.style =  function() { return this + '.css' };

    $.extend($.shining, {
      firstSlide:     function() { getSlide($.shining.slides.first) },
      lastSlide:      function() { getSlide($.shining.slides.last ) },
      nextSlide:      function() { getSlide($.shining.slides.next) },
      previousSlide:  function() { getSlide($.shining.slides.previous) }
    });

    function init()         {
      $(document).ready(function() {
        $('#controls').ondistance(
          300,
          function(controls) { $(controls).addClass('fades-in') },
          function(controls) { $(controls).removeClass('fades-in') }
        );
        $('#controls #first').    click(function() { $.shining.firstSlide() });
        $('#controls #previous'). click(function() { $.shining.previousSlide() });
        $('#controls #next').     click(function() { $.shining.nextSlide() });
        $('#controls #last').     click(function() { $.shining.lastSlide() });
        $('#stage').centralize();
      });
      $(window).resize(function() { $('#stage').centralize() });
      $(document).click(function(event) {
        if ($(event.target).is('a')) return false;
        if (event.pageX < ($(window).width() / 2)) {
          $.shining.previousSlide();
        } else {
          $.shining.nextSlide();
        }
      })
      loadConfig(function() {
        getSlide($.shining.slides.current);
        setTitle($.shining.config.title);
        setTheme($.shining.config.theme);
        parseEffects();
      });
    }

    function getSlide(name) {
      if (!name) return false;
      if ($.shining.config.transitions) {
        $('#stage').removeClass('fades-in');
        setTimeout(
          function() {
            loadSlide(name);
            setTimeout(
              function() {
                $('#stage').addClass('fades-in');
                $.shining.scripts.run($.shining.currentScript);
              },
            200);
          }, 200);
      } else {
        loadSlide(name);
      }
    }

    function setTitle(title) {
      if (!title) { return false };
      $('title').text(title);
    }

    function setTheme(name) {
      if (!name || name == "default") { return false };
      var path = $('link.theme').attr('href').replace('default.css', name + 'css');
      return $('link.theme').attr('href', path);
    }

    // private
    function slide(name) {
      return 'slides/' + name;
    }

    function vendored() {
      return $('script:first').attr('src').match(/^vendor/);
    }

    function loadSlide(name) {
      $('#stage').load(
        slide(name).markup(),
        function(data) {
          $.shining.slides.current = name;
          $('link.slide').remove(); // remove now previous slide styles
          if (SyntaxHighlighter) SyntaxHighlighter.highlight();
          $('#stage').centralize();
          $.shining.scripts.reap();
          if (data) {
            loadSlideScript(name);
            loadSlideStyle(name);
          }
        }
      );
    }

    function loadSlideScript(name) {
      $.get(slide(name).script(), function(script) {
        if ($.shining.config.transitions) {
          $.shining.currentScript = script;
        } else {
          $.shining.scripts.run(script)
        }
      })
    }

    function loadSlideStyle(name) {
      $('head').append('<link rel="stylesheet" type="text/css" href="' + slide(name).style() + '" media="all" class="slide"/>')
    }

    function loadConfig(callback) {
      $.getJSON('config.json', function(config) {
        $.shining.config = config;
        $.shining.slides.add(config.slides);
        if (config.transitions) {
          $('#stage').addClass('transparent fades-in');
        }
        callback.call();
      });
    }

    function parseEffects() {
      $.get($('link[href$=effects.css]').attr('href'),
        function(css) {
          // window.cs = css;
          $.shining.effects = $.parseCSS(css)
        }
      );
    }

    $.shining.scripts = {
      LINE: /^(\d[.\d]*),[\s]*(.*)/,
      parsed: [], processes: [],
      nextSlide:      function() { $.shining.nextSlide() },
      previousSlide:  function() { $.shining.previousSlide() },
      at:             function(seconds, method) {
        $.shining.scripts.processes.push(setTimeout(method, parseFloat(seconds) * 1000))
      },
      parse:          function(script) {
        var lines = script.split("\n"), tokens, parsed = [];
        for (var i = 0; lines.length > i; i++) {
          if ($.shining.scripts.LINE.test(lines[i])) {
            var tokens = lines[i].match($.shining.scripts.LINE);
            var time = tokens[1], code = tokens[2];
            parsed.push(time);
            if (code.length) parsed.push(code);
          } else {
            if (isNaN(parsed[parsed.length - 1])) {
              parsed[parsed.length - 1] += ("; " + lines[i]);
            } else {
              parsed.push(lines[i]);
            }
          }
        }
        return parsed;
      },
      run:          function(script) {
        var parsed = $.shining.scripts.parse(script), all = [];
        for (var i = 0; parsed.length > i; i += 2) {
          all.push(["at(", parsed[i], ", function() { ", parsed[i+1], " })"].join(''));
        }
        with($.shining.scripts) { eval(all.join(';')) };
      },
      reap: function() {
        $($.shining.scripts.processes).map(function() { clearTimeout(this) });
        return $.shining.scripts.processes = [];
      }
    }

    init();
  }
  // boots!
  $.shining();

})(jQuery);

// Dependencies!!

/*
 * JSizes - JQuery plugin v0.33
 *
 * Licensed under the revised BSD License.
 * Copyright 2008-2010 Bram Stein
 * All rights reserved.
 */
(function(b){var a=function(c){return parseInt(c,10)||0};b.each(["min","max"],function(d,c){b.fn[c+"Size"]=function(g){var f,e;if(g){if(g.width!==undefined){this.css(c+"-width",g.width)}if(g.height!==undefined){this.css(c+"-height",g.height)}return this}else{f=this.css(c+"-width");e=this.css(c+"-height");return{width:(c==="max"&&(f===undefined||f==="none"||a(f)===-1)&&Number.MAX_VALUE)||a(f),height:(c==="max"&&(e===undefined||e==="none"||a(e)===-1)&&Number.MAX_VALUE)||a(e)}}}});b.fn.isVisible=function(){return this.is(":visible")};b.each(["border","margin","padding"],function(d,c){b.fn[c]=function(e){if(e){if(e.top!==undefined){this.css(c+"-top"+(c==="border"?"-width":""),e.top)}if(e.bottom!==undefined){this.css(c+"-bottom"+(c==="border"?"-width":""),e.bottom)}if(e.left!==undefined){this.css(c+"-left"+(c==="border"?"-width":""),e.left)}if(e.right!==undefined){this.css(c+"-right"+(c==="border"?"-width":""),e.right)}return this}else{return{top:a(this.css(c+"-top"+(c==="border"?"-width":""))),bottom:a(this.css(c+"-bottom"+(c==="border"?"-width":""))),left:a(this.css(c+"-left"+(c==="border"?"-width":""))),right:a(this.css(c+"-right"+(c==="border"?"-width":"")))}}}})})(jQuery);

// http://github.com/juliocesar/jquery-ondistance
(function($){$.fn.ondistance=function(specified,close,far){var elt=this.get(0),last=new Date().getTime();$(document).mousemove(function(e){var current=new Date().getTime();if(current-last<500)return;var offset=$(elt).offset(),center={x:offset.left+($(elt).width()/2),y:offset.top+($(elt).height()/2)},last=current,distance=parseInt(Math.sqrt(Math.pow(e.pageX-center.x,2)+Math.pow(e.pageY-center.y,2)));if(specified>=distance){if($(elt).data('mouseclose')==true)return false;$(elt).data('mouseclose',true);close(elt);}else{if($(elt).data('mouseclose')==false)return false;$(elt).data('mouseclose',false);far(elt);}})}})(jQuery);

// centralizes an element vertically
(function($){$.fn.centralize=function(){var self=this.get(0);windowHeight=document.documentElement.clientHeight,elementHeight=(self.offsetHeight+$(self).padding().top+$(self).padding().bottom);$(self).css('position','relative').css('top',(windowHeight/2)-(elementHeight/2)+'px');};})(jQuery);

// Trimmed down/modified version of the original Javascript/jQuery CSS parser
// by Danny.
// http://bililite.com/blog/2009/01/16/jquery-css-parser/
(function($){$.parseCSS=function(str){var ret={};str=munge(str).replace(/@(([^;`]|`[^b]|`b[^%])*(`b%)?);?/g,function(s,rule){return'';});$.each(str.split('`b%'),function(i,css){css=css.split('%b`');if(css.length<2)return;css[0]=restore(css[0]);ret[css[0]]=$.extend(ret[css[0]]||{},parsedeclarations(css[1]));});return ret;};$.parseCSS.mediumApplies=(window.media&&window.media.query)||function(str){if(!str)return true;if(str in media)return media[str];var style=$('<style media="'+str+'">body {position: relative; z-index: 1;}</style>').appendTo('head');return media[str]=[$('body').css('z-index')==1,style.remove()][0];};$.parseCSS.parseArguments=function(str){if(!str)return[];var ret=[],mungedArguments=munge(str,true).split(/\s+/);for(var i=0;i<mungedArguments.length;++i){var a=restore(mungedArguments[i]);try{ret.push(eval('('+a+')'));}catch(err){ret.push(a);}}
return ret;};var media={};var munged={};function parsedeclarations(index){var str=munged[index].replace(/^{|}$/g,'');str=munge(str);var parsed={};$.each(str.split(';'),function(i,decl){decl=decl.split(':');if(decl.length<2)return;parsed[restore(decl[0])]=restore(decl[1]);});return parsed;}
var REbraces=/{[^{}]*}/,REfull=/\[[^\[\]]*\]|{[^{}]*}|\([^()]*\)|function(\s+\w+)?(\s*%b`\d+`b%){2}/,REatcomment=/\/\*@((?:[^\*]|\*[^\/])*)\*\//g,REcomment_string=/(?:\/\*(?:[^\*]|\*[^\/])*\*\/)|(\\.|"(?:[^\\\"]|\\.|\\\n)*"|'(?:[^\\\']|\\.|\\\n)*')/g,REmunged=/%\w`(\d+)`\w%/,uid=0;function munge(str,full){str=str.replace(REatcomment,'$1').replace(REcomment_string,function(s,string){if(!string)return'';var replacement='%s`'+(++uid)+'`s%';munged[uid]=string.replace(/^\\/,'');return replacement;});var RE=full?REfull:REbraces;while(match=RE.exec(str)){replacement='%b`'+(++uid)+'`b%';munged[uid]=match[0];str=str.replace(RE,replacement);}
return str;}
function restore(str){if(str===undefined)return str;while(match=REmunged.exec(str)){str=str.replace(REmunged,munged[match[1]]);}
return $.trim(str);}
var RESGMLcomment=/<!--([^-]|-[^-])*-->/g;var REnotATag=/(>)[^<]*/g;var REtag=/<(\w+)([^>]*)>/g;})(jQuery);<|endoftext|>


<commit_before>var DocsParser = require("../docsparser");
var xregexp = require('../xregexp').XRegExp;
var escape = require('../utils').escape;
var util = require('util');

function JavaParser(settings) {
    DocsParser.call(this, settings);
}

JavaParser.prototype = Object.create(DocsParser.prototype);

JavaParser.prototype.setup_settings = function() {
    var identifier = '[a-zA-Z_$][a-zA-Z_$0-9]*';
    this.settings = {
        'curlyTypes': false,
        'typeInfo': false,
        'typeTag': 'type',
        'varIdentifier': identifier,
        'fnIdentifier':  identifier,
        'fnOpener': identifier + '(?:\\s+' + identifier + ')?\\s*\\(',
        'commentCloser': ' */',
        'bool': 'Boolean',
        'function': 'Function'
    };
};

JavaParser.prototype.parse_function = function(line) {
    line = line.trim();
    var regex = xregexp(
        // Modifiers
        '(?:(public|protected|private|static|abstract|final|transient|synchronized|native|strictfp)\\s+)*' +
        // Return value
        '(?P<retval>[a-zA-Z_$][\\<\\>\\., a-zA-Z_$0-9]+)\\s+' +
        // Method name
        '(?P<name>' + this.settings.fnIdentifier + ')\\s*' +
        // Params
        '\\((?P<args>.*?)\\)\\s*' +
        // # Throws ,
        '(?:throws\\s*(?P<throwed>[a-zA-Z_$0-9\\.,\\s]*))?'
        );

    var matches = xregexp.exec(line, regex);
    if(matches === null)
        return null;

    var name = matches.name || '';
    var retval = matches.retval || null;

    var arg_throws;
    if (matches.throwed) {
        arg_throws = matches.throwed.trim().split(/\s*,\s*/);
    } else {
        arg_throws = null;
    }

    var args;
    if (matches.args) {
        args = matches.args.trim();
    } else {
        args = null;
    }

    return [name, args, retval, arg_throws];
};

JavaParser.prototype.parse_var = function(line) {
    return null;
};

JavaParser.prototype.guess_type_from_value = function(val) {
    return null;
};

JavaParser.prototype.format_function = function(name, args, retval, throws_args, options) {
    if (typeof options === 'undefined') {
        options = {};
    }

    var out = DocsParser.prototype.format_function.call(this, name, args, retval, options);

    if(throws_args) {
        throws_args.forEach(function (type) {
            out.push(util.format('@throws %s ${1:[description]}', escape(type)));
        });
    }

    return out;
};

JavaParser.prototype.get_function_return_type = function(name, retval) {
    if(retval === 'void')
        return null;
    else
        return retval;
};

JavaParser.prototype.get_definition = function(editor, pos, read_line) {
    var maxLines = 25;  // don't go further than this

    var definition = '';
    var open_curly_annotation = false;
    var open_paren_annotation = false;

    var i, len;
    for(i=0; i < maxLines; i++) {
        var line = read_line(editor, pos);
        if(line == null)
            break;

        pos.row+= 1;
        // Move past empty lines
        if(line.search(/^\s*$/) > -1)
            continue;

        // strip comments
        line = line.replace(/\/\/.*/, '');
        line = line.replace(/\/\*.*\*\//, '');
        if(definition === '') {
            // Must check here for function opener on same line as annotation
            if(this.settings.fnOpener && (line.search(RegExp(this.settings.fnOpener)) > -1)) {

            }
            // Handle Annotations
            else if(line.search(/^\s*@/) > -1) {
                if((line.search('{') > -1) && line.search('}') === -1)
                    open_curly_annotation = true;
                if((line.search('\\(') > -1) && line.search('\\)') === -1)
                    open_paren_annotation = true;
                continue;
            }
            else if(open_curly_annotation) {
                if(line.search('}') > -1)
                    open_curly_annotation = false;
                continue;
            }
            else if(open_paren_annotation) {
                if(line.search('\\)') > -1)
                    open_paren_annotation = false;
            }
            else if(line.search(/^\s*$/) > -1)
                continue;
            // Check for function
            else if(!(this.settings.fnOpener) || line.search(RegExp(this.settings.fnOpener)) === -1) {
                definition = line;
                break;
            }
        }
        definition+= line;
        if((line.indexOf(';') > -1) || (line.indexOf('{') > -1)) {
            var regex = new RegExp('\\s*[;{]\\s*$', 'g');
            definition = definition.replace(regex, '');
            break;
        }
    }
    return definition;
};

module.exports = JavaParser;
<commit_msg>Allow brackets in return value<commit_after>var DocsParser = require("../docsparser");
var xregexp = require('../xregexp').XRegExp;
var escape = require('../utils').escape;
var util = require('util');

function JavaParser(settings) {
    DocsParser.call(this, settings);
}

JavaParser.prototype = Object.create(DocsParser.prototype);

JavaParser.prototype.setup_settings = function() {
    var identifier = '[a-zA-Z_$][a-zA-Z_$0-9]*';
    this.settings = {
        'curlyTypes': false,
        'typeInfo': false,
        'typeTag': 'type',
        'varIdentifier': identifier,
        'fnIdentifier':  identifier,
        'fnOpener': identifier + '(?:\\s+' + identifier + ')?\\s*\\(',
        'commentCloser': ' */',
        'bool': 'Boolean',
        'function': 'Function'
    };
};

JavaParser.prototype.parse_function = function(line) {
    line = line.trim();
    var regex = xregexp(
        // Modifiers
        '(?:(public|protected|private|static|abstract|final|transient|synchronized|native|strictfp)\\s+)*' +
        // Return value
        '(?P<retval>[a-zA-Z_$\[\]][\\<\\>\\., a-zA-Z_$0-9\[\]]+)\\s+' +
        // Method name
        '(?P<name>' + this.settings.fnIdentifier + ')\\s*' +
        // Params
        '\\((?P<args>.*?)\\)\\s*' +
        // # Throws ,
        '(?:throws\\s*(?P<throwed>[a-zA-Z_$0-9\\.,\\s]*))?'
        );

    var matches = xregexp.exec(line, regex);
    if(matches === null)
        return null;

    var name = matches.name || '';
    var retval = matches.retval || null;

    var arg_throws;
    if (matches.throwed) {
        arg_throws = matches.throwed.trim().split(/\s*,\s*/);
    } else {
        arg_throws = null;
    }

    var args;
    if (matches.args) {
        args = matches.args.trim();
    } else {
        args = null;
    }

    return [name, args, retval, arg_throws];
};

JavaParser.prototype.parse_var = function(line) {
    return null;
};

JavaParser.prototype.guess_type_from_value = function(val) {
    return null;
};

JavaParser.prototype.format_function = function(name, args, retval, throws_args, options) {
    if (typeof options === 'undefined') {
        options = {};
    }

    var out = DocsParser.prototype.format_function.call(this, name, args, retval, options);

    if(throws_args) {
        throws_args.forEach(function (type) {
            out.push(util.format('@throws %s ${1:[description]}', escape(type)));
        });
    }

    return out;
};

JavaParser.prototype.get_function_return_type = function(name, retval) {
    if(retval === 'void')
        return null;
    else
        return retval;
};

JavaParser.prototype.get_definition = function(editor, pos, read_line) {
    var maxLines = 25;  // don't go further than this

    var definition = '';
    var open_curly_annotation = false;
    var open_paren_annotation = false;

    var i, len;
    for(i=0; i < maxLines; i++) {
        var line = read_line(editor, pos);
        if(line == null)
            break;

        pos.row+= 1;
        // Move past empty lines
        if(line.search(/^\s*$/) > -1)
            continue;

        // strip comments
        line = line.replace(/\/\/.*/, '');
        line = line.replace(/\/\*.*\*\//, '');
        if(definition === '') {
            // Must check here for function opener on same line as annotation
            if(this.settings.fnOpener && (line.search(RegExp(this.settings.fnOpener)) > -1)) {

            }
            // Handle Annotations
            else if(line.search(/^\s*@/) > -1) {
                if((line.search('{') > -1) && line.search('}') === -1)
                    open_curly_annotation = true;
                if((line.search('\\(') > -1) && line.search('\\)') === -1)
                    open_paren_annotation = true;
                continue;
            }
            else if(open_curly_annotation) {
                if(line.search('}') > -1)
                    open_curly_annotation = false;
                continue;
            }
            else if(open_paren_annotation) {
                if(line.search('\\)') > -1)
                    open_paren_annotation = false;
            }
            else if(line.search(/^\s*$/) > -1)
                continue;
            // Check for function
            else if(!(this.settings.fnOpener) || line.search(RegExp(this.settings.fnOpener)) === -1) {
                definition = line;
                break;
            }
        }
        definition+= line;
        if((line.indexOf(';') > -1) || (line.indexOf('{') > -1)) {
            var regex = new RegExp('\\s*[;{]\\s*$', 'g');
            definition = definition.replace(regex, '');
            break;
        }
    }
    return definition;
};

module.exports = JavaParser;
<|endoftext|>


<commit_before>/*jshint esversion: 6 */

/*
  Manage Information Node View With a current selected node
*/
var AskomicsNodeView = function () {
  //var prefix = "nodeview_";

  {
    // Switch between close and open eye icon for unselected
    $("#showNode").click(function() {
        var sparqlId = $("#objectName").text();
        var node = graphBuilder.getInstanciedNodeFromSparqlId(sparqlId);
        graphBuilder.switchActiveNode(node);

        if (node.actif) {
            $(this).removeClass('glyphicon-eye-close');
            $(this).addClass('glyphicon-eye-open');
        } else {
            $(this).removeClass('glyphicon-eye-open');
            $(this).addClass('glyphicon-eye-close');
        }
    });

    // Node deletion
    $("#deleteNode").click(function() {
        var sparqlId = $("#objectName").text();
        var node = graphBuilder.getInstanciedNodeFromSparqlId(sparqlId);
        if ( node ) {
          listLinksRemoved = graphBuilder.removeInstanciedNode(node);
          forceLayoutManager.removeSuggestions();
          forceLayoutManager.update();
          attributesView.remove(node);
          nodeView.clean();
          for (var l of listLinksRemoved) {
            linksView.remove(l);
          }
        }
    });

    $('#help').click(function() {
      var sparqlId = $("#objectName").text();
        console.log('---> sparqlId: '+sparqlId);
        try{
          var elem = graphBuilder.getInstanciedNodeFromSparqlId(sparqlId);
        }catch(err){
          try{
            var elem = graphBuilder.getInstanciedLinkFromSparqlId(sparqlId);
          }catch(err){
            console.log('there is no node or link with id '+sparqlId);
            return;
          }
        }
        if (elem) {
          if (elem.hasOwnProperty('strict')) { // if link (only link have a key strict)
            if (elem.positionable) {
              help_title = 'Positionable link '+elem.label;
              help_str = 'There is a relation of position between '+elem.source.label+' and '+elem.target.label+'.';
              help_str += ' You can choose different kind of positionable relation.';
              help_str += 'This relation are explained on the following figure:';
              $('#help_figure').attr('src', '/static/images/positionable.png').attr('alt', 'bliblibli').css('width', '650px');
              $('#help_figure').removeClass( "hidden" );
            }else{
              help_title = 'Link '+elem.label;
              help_str = 'There is a relation between '+elem.source.label+' and '+elem.target.label+'.';
              help_str += ' This mean that blablabla';
            }
          }else{ // else, it is a node
            if (elem.positionable) { // a positionable node
              help_title = 'positionable node '+elem.label;
              help_str = elem.label+' is a positionable node. You can click on the positionable link to change the query.';
              help_str += ' Choose which attributes you want to see on the right panel.';
              help_str += ' Filter this attributes by choosing values';
            }else{ // a normal node
              help_title = 'Node '+elem.label;
              help_str = ' Choose which attributes you want to see on the right panel.';
              help_str += ' Filter this attributes by choosing values';
            }
          }
          displayModal(help_title, help_str, 'ok');
        }
    })
  }

  // take a string and return an entity with a sub index
  AskomicsNodeView.prototype.formatLabelEntity = function(node) {
    if ( node === undefined )
      throw new Error("AskomicsNodeView.prototype.formatLabelEntity : node is not defined !");

    var re = new RegExp(/(\d+)$/);
    var indiceEntity = node.name.match(re);
    if ( indiceEntity === null || indiceEntity.length <= 0 )
      indiceEntity = ["unknown"];
    var labelEntity = node.name.replace(re,"");
    return $('').text(labelEntity).append($('').text(indiceEntity[0]));
  };

  AskomicsNodeView.prototype.clean = function () {
    $("#objectName").text("");
    $("#showNode").hide();
    $("#deleteNode").hide();
  };

  AskomicsNodeView.prototype.show = function (node) {
    if ( node === undefined ) {
      throw new Error("AskomicsNodeView.prototype.set : node is undefined !");
    }

    this.clean();

    $("#objectName").html(this.formatLabelEntity(node));
    $("#showNode").show();
    $("#deleteNode").show();
    if ( node.actif ) {
      $("#showNode").removeClass('glyphicon-eye-close');
      $("#showNode").addClass('glyphicon-eye-open');
    } else {
      $("#showNode").removeClass('glyphicon-eye-open');
      $("#showNode").addClass('glyphicon-eye-close');
    }
  };

  AskomicsNodeView.prototype.remove = function (node) {
    //$("#"+prefix+node.SPARQLid).remove();
    this.clean();
  };

  AskomicsNodeView.prototype.hide = function (node) {
    //$("#"+prefix+node.SPARQLid).hide();
    this.clean();
  };

  AskomicsNodeView.prototype.hideAll = function (node) {
    //$("div[id*='"+ prefix +"']" ).hide();
    this.clean();
  };

  AskomicsNodeView.prototype.create = function (node) {
  //  var nodeView = $("

").attr("id",prefix+node.SPARQLid);
  };
};
<commit_msg>bugfix on help message<commit_after>/*jshint esversion: 6 */

/*
  Manage Information Node View With a current selected node
*/
var AskomicsNodeView = function () {
  //var prefix = "nodeview_";

  {
    // Switch between close and open eye icon for unselected
    $("#showNode").click(function() {
        var sparqlId = $("#objectName").text();
        var node = graphBuilder.getInstanciedNodeFromSparqlId(sparqlId);
        graphBuilder.switchActiveNode(node);

        if (node.actif) {
            $(this).removeClass('glyphicon-eye-close');
            $(this).addClass('glyphicon-eye-open');
        } else {
            $(this).removeClass('glyphicon-eye-open');
            $(this).addClass('glyphicon-eye-close');
        }
    });

    // Node deletion
    $("#deleteNode").click(function() {
        var sparqlId = $("#objectName").text();
        var node = graphBuilder.getInstanciedNodeFromSparqlId(sparqlId);
        if ( node ) {
          listLinksRemoved = graphBuilder.removeInstanciedNode(node);
          forceLayoutManager.removeSuggestions();
          forceLayoutManager.update();
          attributesView.remove(node);
          nodeView.clean();
          for (var l of listLinksRemoved) {
            linksView.remove(l);
          }
        }
    });

    $('#help').click(function() {
      var sparqlId = $("#objectName").text();
        console.log('---> sparqlId: '+sparqlId);
        try{
          var elem = graphBuilder.getInstanciedNodeFromSparqlId(sparqlId);
        }catch(err){
          try{
            var elem = graphBuilder.getInstanciedLinkFromSparqlId(sparqlId);
          }catch(err){
            console.log('there is no node or link with id '+sparqlId);
            return;
          }
        }
        if (elem) {
          console.log('---> elem: '+JSON.stringify(elem));
          if (elem.hasOwnProperty('linkindex')) { // if link (only link have a key strict)
            if (elem.positionable) {
              help_title = 'Positionable link '+elem.label;
              help_str = 'There is a relation of position between '+elem.source.label+' and '+elem.target.label+'.';
              help_str += ' You can choose different kind of positionable relation.';
              help_str += 'This relations are explained on the following figure:';
              $('#help_figure').attr('src', '/static/images/positionable.png').attr('alt', 'positionable').css('width', '650px');
              $('#help_figure').removeClass( "hidden" );
            }else{
              help_title = 'Link '+elem.label;
              help_str = 'There is a relation between '+elem.source.label+' and '+elem.target.label+'.';
              help_str += ' This mean that attribute '+elem.target.label+' of '+elem.source.label+' is an entity.';
              $('#help_figure').addClass( "hidden" );
            }
          }else{ // else, it is a node
            if (elem.positionable) { // a positionable node
              help_title = 'positionable node '+elem.label;
              help_str = elem.label+' is a positionable node. You can click on the positionable link to change the query.';
              help_str += ' Choose which attributes you want to see on the right panel.';
              help_str += ' Filter this attributes by choosing values';
              $('#help_figure').addClass( "hidden" );
            }else{ // a normal node
              help_title = 'Node '+elem.label;
              help_str = ' Choose which attributes you want to see on the right panel.';
              help_str += ' Filter this attributes by choosing values';
              $('#help_figure').addClass( "hidden" );
            }
          }
          displayModal(help_title, help_str, 'ok');
        }
    })
  }

  // take a string and return an entity with a sub index
  AskomicsNodeView.prototype.formatLabelEntity = function(node) {
    if ( node === undefined )
      throw new Error("AskomicsNodeView.prototype.formatLabelEntity : node is not defined !");

    var re = new RegExp(/(\d+)$/);
    var indiceEntity = node.name.match(re);
    if ( indiceEntity === null || indiceEntity.length <= 0 )
      indiceEntity = ["unknown"];
    var labelEntity = node.name.replace(re,"");
    return $('').text(labelEntity).append($('').text(indiceEntity[0]));
  };

  AskomicsNodeView.prototype.clean = function () {
    $("#objectName").text("");
    $("#showNode").hide();
    $("#deleteNode").hide();
  };

  AskomicsNodeView.prototype.show = function (node) {
    if ( node === undefined ) {
      throw new Error("AskomicsNodeView.prototype.set : node is undefined !");
    }

    this.clean();

    $("#objectName").html(this.formatLabelEntity(node));
    $("#showNode").show();
    $("#deleteNode").show();
    if ( node.actif ) {
      $("#showNode").removeClass('glyphicon-eye-close');
      $("#showNode").addClass('glyphicon-eye-open');
    } else {
      $("#showNode").removeClass('glyphicon-eye-open');
      $("#showNode").addClass('glyphicon-eye-close');
    }
  };

  AskomicsNodeView.prototype.remove = function (node) {
    //$("#"+prefix+node.SPARQLid).remove();
    this.clean();
  };

  AskomicsNodeView.prototype.hide = function (node) {
    //$("#"+prefix+node.SPARQLid).hide();
    this.clean();
  };

  AskomicsNodeView.prototype.hideAll = function (node) {
    //$("div[id*='"+ prefix +"']" ).hide();
    this.clean();
  };

  AskomicsNodeView.prototype.create = function (node) {
  //  var nodeView = $("

").attr("id",prefix+node.SPARQLid);
  };
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import IconAccessible from 'material-ui/svg-icons/action/accessible';
import IconAccessibility from 'material-ui/svg-icons/action/accessibility';
import IconVisibility from 'material-ui/svg-icons/action/visibility';
import IconHearing from 'material-ui/svg-icons/av/hearing';
import IconNew from 'material-ui/svg-icons/content/add';
import {orange500} from 'material-ui/styles/colors';

import {List, ListItem} from 'material-ui/List';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

const style = {
    postit: {
        backgroundColor: '#FFFFA5'
    },
    errorStyle: {
        color: orange500,
    },
    deleteButton: {
        height: 48
    }
};

class AdaptionsField extends Component {

    constructor(props) {
        super(props);
        const chipIcons =  {'Tilrettelegging 1':<IconAccessible/>,'Tilrettelegging 2':<IconAccessibility/>,'Tilrettelegging 3':<IconVisibility/>,'Tilrettelegging 4':<IconHearing/>};

        let selected = $('#adaptions').val().split(",");
        let unselected = [];
        if (selected[0] == "") {
            selected = [];
            unselected = Object.keys(chipIcons);
        }
        else {
            for (let key in chipIcons) {
                if (selected.indexOf(key) == -1) {
                    unselected.push(key);
                }
            }
        }

        this.state = {
            chipIcons: chipIcons,
            selected: selected,
            unselected: unselected,
            value: ""
        };

        this.add = this.add.bind(this);
        this.remove = this.remove.bind(this);
        this.addNew = this.addNew.bind(this);
        this.addNewButton = this.addNewButton.bind(this);
        this.deleteItem = this.deleteItem.bind(this);
        this.inputChange = this.inputChange.bind(this);
        this.notExists = this.notExists.bind(this);
    }

    render() {

        $('#adaptions').val(this.state.selected);

        let selected = this.state.selected.map(name => {
            let icon = this.state.chipIcons[name];
            let deleteButton = null;
            if (Object.keys(this.state.chipIcons).indexOf(name) == -1) {
                deleteButton = <FlatButton
                    label="slett"
                    primary={true}
                    onTouchTap={this.deleteItem.bind(null, {name})}
                    style={style.deleteButton}
                />
                icon = <IconNew/>
            }
            return (
                <ListItem
                    key={name}
                    primaryText={name}
                    leftIcon={icon}
                    onTouchTap={this.remove.bind(null, {name})}
                    rightIconButton={deleteButton}
                />
            )
        });

        let unselected = this.state.unselected.map( name => {
            let icon = this.state.chipIcons[name];
            let deleteButton = null;
            if (Object.keys(this.state.chipIcons).indexOf(name) == -1) {
                deleteButton = <FlatButton
                    label="slett"
                    primary={true}
                    onTouchTap={this.deleteItem.bind(null, {name})}
                    style={style.deleteButton}
                />
                icon = <IconNew/>
            }
            return (
                <ListItem
                    key={name}
                    primaryText={name}
                    leftIcon={icon}
                    onTouchTap={this.add.bind(null, {name})}
                    rightIconButton={deleteButton}
                />
            )
        });

        let showButton = false;
        let errorText = null;

        if(this.state.value != "") {
            if (!this.notExists(this.state.value)) {
                console.log(this.notExists(this.state.value))
                errorText = "Denne tilretteleggingen finnes allerede"
            }
            else {
                showButton = true;
            }
        }

        return (

Tilrettelegginger

                <Paper zDepth={1}>

                        help

                            Klikk på en tilrettelegging for å flytte den over til den andre listen

                        <Paper className="adaptions-box" zDepth={1} style={style.postit}>

Alle tilrettelegginger

                            <List className="adaptions-holder">
                                {unselected}
                            </List>
                        </Paper>
                        <Paper className="adaptions-box" zDepth={1} style={style.postit}>

Valgte tilrettelegginger

                                {selected}

                        </Paper>

                            <form onSubmit={this.addNew}>
                            <TextField
                                ref="AdaptionInput"
                                hintText="Navn på tilrettelegging"
                                value = {this.state.value}
                                floatingLabelText="Legg til ny tilrettelegging"
                                fullWidth={true}
                                onKeyPress={this.addNew}
                                onChange={this.inputChange}
                                errorStyle={style.errorStyle}
                                errorText={errorText}
                            />
                            </form>

                        <RaisedButton
                            label="Legg til"
                            className='adaptions-add-button'
                            onTouchTap={this.addNewButton}
                            primary={showButton}
                            disabled={!showButton}
                        />

                </Paper>

        )
    }

    add(item) {
        let selected = this.state.selected.concat(item.name);
        this.state.unselected.splice(this.state.unselected.indexOf(item.name), 1);
        this.setState({selected: selected, unselected: this.state.unselected});
    }

    remove(item) {
        let unselected = this.state.unselected.concat(item.name);
        this.state.selected.splice(this.state.selected.indexOf(item.name), 1);
        this.setState({selected: this.state.selected, unselected: unselected});
    }

    addNew(event) {
        if (event.key == 'Enter') {
            event.preventDefault();
            this.addNewButton()
        }
        return false;
    }

    addNewButton(event) {
        let value = this.state.value;
        if (this.notExists(value) && value != "") {
            let selected = this.state.selected.concat(value);
            this.setState({selected: selected, value: ""});
        }
    }

    notExists(name) {
        return (this.state.selected.indexOf(name) == -1 && this.state.unselected.indexOf(name) == -1);
    }

    deleteItem(event) {
        let name = event.name;
        if (this.state.selected.indexOf(name) != -1) {
            this.state.selected.splice(this.state.selected.indexOf(name), 1);
            this.setState({selected: this.state.selected});
        }
        else {
            this.state.unselected.splice(this.state.unselected.indexOf(name), 1);
            this.setState({unselected: this.state.unselected});
        }
    }

    inputChange(event, newValue) {
        this.setState({value: newValue});
    }
}

export default AdaptionsField;
<commit_msg>cleaned AdaptionsField<commit_after>import React, {Component} from 'react';
import IconAccessible from 'material-ui/svg-icons/action/accessible';
import IconAccessibility from 'material-ui/svg-icons/action/accessibility';
import IconVisibility from 'material-ui/svg-icons/action/visibility';
import IconHearing from 'material-ui/svg-icons/av/hearing';
import IconNew from 'material-ui/svg-icons/content/add';
import {orange500} from 'material-ui/styles/colors';
import {List, ListItem} from 'material-ui/List';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import injectTapEventPlugin from 'react-tap-event-plugin';

injectTapEventPlugin();

const style = {
    postit: {
        backgroundColor: '#FFFFA5'
    },
    errorStyle: {
        color: orange500,
    },
    deleteButton: {
        height: 48
    }
};

class AdaptionsField extends Component {

    constructor(props) {
        super(props);
        const chipIcons = {
            'Tilrettelegging 1': <IconAccessible/>,
            'Tilrettelegging 2': <IconAccessibility/>,
            'Tilrettelegging 3': <IconVisibility/>,
            'Tilrettelegging 4': <IconHearing/>
        };

        let selected = $('#adaptions').val().split(",");
        let unselected = [];
        if (selected[0] == "") {
            selected = [];
            unselected = Object.keys(chipIcons);
        }
        else {
            for (let key in chipIcons) {
                if (selected.indexOf(key) == -1) {
                    unselected.push(key);
                }
            }
        }

        this.state = {
            chipIcons: chipIcons,
            selected: selected,
            unselected: unselected,
            value: ""
        };

        this.add = this.add.bind(this);
        this.remove = this.remove.bind(this);
        this.addNew = this.addNew.bind(this);
        this.addNewButton = this.addNewButton.bind(this);
        this.deleteItem = this.deleteItem.bind(this);
        this.inputChange = this.inputChange.bind(this);
        this.notExists = this.notExists.bind(this);
    }

    render() {

        $('#adaptions').val(this.state.selected);

        let selected = this.state.selected.map(name => {
            let icon = this.state.chipIcons[name];
            let deleteButton = null;
            if (Object.keys(this.state.chipIcons).indexOf(name) == -1) {
                deleteButton = <FlatButton
                    label="slett"
                    primary={true}
                    onTouchTap={this.deleteItem.bind(null, {name})}
                    style={style.deleteButton}
                />
                icon = <IconNew/>
            }
            return (
                <ListItem
                    key={name}
                    primaryText={name}
                    leftIcon={icon}
                    onTouchTap={this.remove.bind(null, {name})}
                    rightIconButton={deleteButton}
                />
            )
        });

        let unselected = this.state.unselected.map(name => {
            let icon = this.state.chipIcons[name];
            let deleteButton = null;
            if (Object.keys(this.state.chipIcons).indexOf(name) == -1) {
                deleteButton = <FlatButton
                    label="slett"
                    primary={true}
                    onTouchTap={this.deleteItem.bind(null, {name})}
                    style={style.deleteButton}
                />
                icon = <IconNew/>
            }
            return (
                <ListItem
                    key={name}
                    primaryText={name}
                    leftIcon={icon}
                    onTouchTap={this.add.bind(null, {name})}
                    rightIconButton={deleteButton}
                />
            )
        });

        let showButton = false;
        let errorText = null;

        if (this.state.value != "") {
            if (!this.notExists(this.state.value)) {
                console.log(this.notExists(this.state.value));
                errorText = "Denne tilretteleggingen finnes allerede";
            }
            else {
                showButton = true;
            }
        }

        return (

Tilrettelegginger

                <Paper zDepth={1}>

                        help

                            Klikk på en tilrettelegging for å flytte den over til den andre listen

                        <Paper className="adaptions-box" zDepth={1} style={style.postit}>

Alle tilrettelegginger

                            <List className="adaptions-holder">
                                {unselected}
                            </List>
                        </Paper>
                        <Paper className="adaptions-box" zDepth={1} style={style.postit}>

Valgte tilrettelegginger

                                {selected}

                        </Paper>

                            <form onSubmit={this.addNew}>
                                <TextField
                                    ref="AdaptionInput"
                                    hintText="Navn på tilrettelegging"
                                    value={this.state.value}
                                    floatingLabelText="Legg til ny tilrettelegging"
                                    fullWidth={true}
                                    onKeyPress={this.addNew}
                                    onChange={this.inputChange}
                                    errorStyle={style.errorStyle}
                                    errorText={errorText}
                                />
                            </form>

                        <RaisedButton
                            label="Legg til"
                            className='adaptions-add-button'
                            onTouchTap={this.addNewButton}
                            primary={showButton}
                            disabled={!showButton}
                        />

                </Paper>

        )
    }

    add(item) {
        let selected = this.state.selected.concat(item.name);
        this.state.unselected.splice(this.state.unselected.indexOf(item.name), 1);
        this.setState({selected: selected, unselected: this.state.unselected});
    }

    remove(item) {
        let unselected = this.state.unselected.concat(item.name);
        this.state.selected.splice(this.state.selected.indexOf(item.name), 1);
        this.setState({selected: this.state.selected, unselected: unselected});
    }

    addNew(event) {
        if (event.key == 'Enter') {
            event.preventDefault();
            this.addNewButton()
        }
        return false;
    }

    addNewButton(event) {
        let value = this.state.value;
        if (this.notExists(value) && value != "") {
            let selected = this.state.selected.concat(value);
            this.setState({selected: selected, value: ""});
        }
    }

    notExists(name) {
        return (this.state.selected.indexOf(name) == -1 && this.state.unselected.indexOf(name) == -1);
    }

    deleteItem(event) {
        let name = event.name;
        if (this.state.selected.indexOf(name) != -1) {
            this.state.selected.splice(this.state.selected.indexOf(name), 1);
            this.setState({selected: this.state.selected});
        }
        else {
            this.state.unselected.splice(this.state.unselected.indexOf(name), 1);
            this.setState({unselected: this.state.unselected});
        }
    }

    inputChange(event, newValue) {
        this.setState({value: newValue});
    }
}

export default AdaptionsField;
<|endoftext|>


<commit_before>
var QuantityPresenter = function(quantity) {
  this.quantity = quantity;

  this.integer = Math.floor(this.quantity);
  this.remainder = quantity - this.integer;

  this.fractions = {
    0: "",
    0.25: "\u00BC",
    0.5: "\u00BD",
    0.75: "\u00BE",
    0.142: "\u2150",
    0.111: "\u2151",
    0.1: "\u2152",
    0.333: "\u2153",
    0.667: "\u2154",
    0.2: "\u2155",
    0.4: "\u2156",
    0.6: "\u2157",
    0.8: "\u2158",
    0.167: "\u2159",
    0.833: "\u215A",
    0.125: "\u215B",
    0.375: "\u215C",
    0.625: "\u215D",
    0.875: "\u215E",
  };

  this.closestFraction = Object.keys(this.fractions).find(function(fraction) {
    return Math.abs(this.remainder - parseFloat(fraction)) < 0.01;
  }.bind(this))

  if (this.closestFraction) {
    this.integerAsString = this.integer == 0 ? '' : '' + this.integer
    this.quantityForDisplay = this.integerAsString + this.fractions[this.closestFraction];
  } else {
    this.quantityForDisplay = '' + this.quantity;
  }
};

module.exports = QuantityPresenter;<commit_msg>fix potential bug with 1/7th lookup<commit_after>
var QuantityPresenter = function(quantity) {
  this.quantity = quantity;

  this.integer = Math.floor(this.quantity);
  this.remainder = quantity - this.integer;

  this.fractions = {
    0: "",
    0.25: "\u00BC",
    0.5: "\u00BD",
    0.75: "\u00BE",
    0.1428: "\u2150",
    0.111: "\u2151",
    0.1: "\u2152",
    0.333: "\u2153",
    0.667: "\u2154",
    0.2: "\u2155",
    0.4: "\u2156",
    0.6: "\u2157",
    0.8: "\u2158",
    0.167: "\u2159",
    0.833: "\u215A",
    0.125: "\u215B",
    0.375: "\u215C",
    0.625: "\u215D",
    0.875: "\u215E",
  };

  this.closestFraction = Object.keys(this.fractions).find(function(fraction) {
    return Math.abs(this.remainder - parseFloat(fraction)) < 0.01;
  }.bind(this))

  if (this.closestFraction) {
    this.integerAsString = this.integer == 0 ? '' : '' + this.integer
    this.quantityForDisplay = this.integerAsString + this.fractions[this.closestFraction];
  } else {
    this.quantityForDisplay = '' + this.quantity;
  }
};

module.exports = QuantityPresenter;<|endoftext|>


<commit_before>// raspistill - o shot - $SHOTTIME.jpg--nopreview--exposure sports--timeout 1

var starttime = Date.now();
var endtime;
var cameraParams = [];
var filePath = "bingo.jpg"
cameraParams.push('-vf');
cameraParams.push('-hf');
cameraParams.push('-np');
cameraParams.push('-ex', "sports")
cameraParams.push('-o', filePath);
cameraParams.push('-t', 0)

starttime = Date.now();
var spawn = require('child_process').spawn('raspistill', cameraParams);
spawn.on('exit', function(code) {
    endtime = Date.now();
    console.info("> saved [" + filePath + "]" + " exit code, " + code + " time: ", (endtime - starttime) / 1000);

});

spawn.on('error', function() {
    if (self.config.verboseLogging) {
        console.error("> there was an error capturing image [" + filePath + "]");
    }
    reject();
});
<commit_msg>testing imagecapture<commit_after>// raspistill - o shot - $SHOTTIME.jpg--nopreview--exposure sports--timeout 1

var starttime = Date.now();
var endtime;
var cameraParams = [];
var filePath = "bingo.jpg"
cameraParams.push('-vf');
cameraParams.push('-hf');
cameraParams.push('-np');
//cameraParams.push('-ex', "sports")
cameraParams.push('-o', filePath);
cameraParams.push('-t', 0)

starttime = Date.now();
var spawn = require('child_process').spawn('raspistill', cameraParams);
spawn.on('exit', function(code) {
    endtime = Date.now();
    console.info("> saved [" + filePath + "]" + " exit code, " + code + " time: ", (endtime - starttime) / 1000);

});

spawn.on('error', function() {
    if (self.config.verboseLogging) {
        console.error("> there was an error capturing image [" + filePath + "]");
    }
    reject();
});
<|endoftext|>


<commit_before>'use babel'

import path from 'path'
import {BufferedProcess, CompositeDisposable} from 'atom'
import {findCached} from 'atom-linter'

/**
 * Returns the value if defined, or a default value if not
 * @param {a} val - The value to check if undef
 * @param {b} default - the default value
 * @return {a|b}
 */
function withDefault(val, defaultVal) {
  return typeof val === 'undefined' ? defaultVal : val
}

/**
 * Supported grammerScopes for linter-liferay
 * @type {Array.<string>}
 */
const grammarScopes = [
  'source.css.scss',
  'source.css',
  'source.js.jsx',
  'source.js',
  'source.velocity',
  'text.html.jsp',
  'text.html.mustache',
  'text.html'
]

/**
 * Check to see if configuration file exists
 * @param {string} filePath - Path to the file
 * @return {Boolean}
 */
function getConfigPath(filePath) {
  const configFile = (0, findCached)(filePath, ['.csfrc.js', '.csfrc.yaml', '.csfrc.yml', '.csfrc.json', '.csfrc', 'csf.config.js'])
  if (configFile) {
    return true
  }

  const packagePath = (0, findCached)(filePath, 'package.json')
  if (packagePath && Boolean(require(packagePath).csfConfig)) {
    return true
  }
  return null
}

/**
 * Regex used to parse check_sf's output. Each capture
 * group corresponds to the following value:
 *
 * $1 lineStart
 * $2 lineEnd
 * $3 column
 * $4 message
 *
 * @type {RegExp}
 */
const regex = /Lines?\s+(\d+)(\-\d+)?(?:,\s+Column\s+)?(\d+)?:\s+(.*)/i

/**
 * Class for managing the linting files and responding to
 * config changes
 */
export default class LinterLiferay {
  /**
   * Create a LinterLiferay
   */
  constructor() {
    this._subscriptions = new CompositeDisposable()

    this._subscriptions.add(atom.config.observe(
      'linter-liferay.lintJS',
      () => this._args = this._formatArgs()
    ))

    this._subscriptions.add(atom.config.observe(
      'linter-liferay.checkSFPath',
      newVal => this._cmd = newVal
    ))

    this._subscriptions.add(atom.config.observe(
      'linter-liferay.requireConfig',
      newVal => this._requireConfig = newVal
    ))

    this._pathMap = {}

    this._subscriptions.add(
      atom.workspace.onDidOpen(event => {
        const {uri} = event

        if (this._requireConfig && !(uri in this._pathMap)) {
          if (getConfigPath(uri)) {
            this._pathMap[uri] = true
          }
          else {
            this._pathMap[uri] = false
          }
        }
      })
    )
  }

  /**
   * Creates a process to read the ouput of check_sf
   * @param {string} path - Path to the file
   * @param {function} cb - The function to call with the output
   * @return {BufferedProcess}
   */
  _createProcess(filePath, cb) {
    const output = []

    return new BufferedProcess({
      command: this._cmd,
      args: [...this._args, filePath],
      options: {
        cwd: path.dirname(filePath)
      },
      stdout: data => output.push(data),
      exit: code => {
        const result = code === 0 ? output : [];

        cb(result)
      }
    })
  }

  /**
   * Formats and returns the arguments for check_sf
   * @return {Array.<string>}
   */
  _formatArgs() {
    const args = ['--no-color', '--show-columns']

    if (!atom.config.get('linter-liferay.lintJS')) {
      args.push('--no-lint')
    }

    return args
  }

  /**
   * Performs the actual lint operation
   * @param {TextEditor} editor - The editor being linted
   * @return {Promise}
   **/
  _lint(editor) {
    const filePath = editor.getPath()

    if (this._requireConfig && !this._pathMap[filePath]) {
      return
    }
    else {
        return new Promise((resolve, reject) => {
          const process = this._createProcess(
            filePath,
            output => resolve(this._getMessages(editor, output))
          )

          process.onWillThrowError(({error, handle}) => {
            atom.notifications.addError(
              `Cannot execute ${this._cmd}`,
              {
                detail: error.message,
                dismissable: true
              }
            )

            handle()
            reject(error)
          })
        })
    }
  }

  /**
   * Converts a RegExp exec result to a linter-liferay
   * match object
   * @param {Array} result
   * @return {Object}
   */
  _getMatch(result) {
    return {
      column: result[3],
      lineEnd: result[2],
      lineStart: result[1],
      message: result[4]
    }
  }

  /**
   * Parses check_sf's output into linter messages
   * @param {TextEditor} editor - The editor being linted
   * @param {Array.<string>} output - The output from check_sf
   * @return {Array.<Object>}
   */
  _getMessages(editor, output) {
    return output.reduce(
      (messages, next) => {
        const result = regex.exec(next)

        if (result) {
          const match = this._getMatch(result)

          messages.push({
            filePath: editor.getPath(),
            range: this._getRange(editor, match),
            type: 'warning',
            text: match.message
          })
        }

        return messages
      },
      []
    )
  }

  /**
   * Computes the range for a given match
   * @param {TextEditor} editor - The editor being linted
   * @param {Object} match - The match object
   * @return {Array.<Array.<number>>}
   */
  _getRange(editor, match) {
    const rowStart = match.lineStart
    const rowEnd = withDefault(match.lineEnd, rowStart)

    const colStart = withDefault(match.column, 1)

    let colEnd = 1
    const lineText = editor.lineTextForBufferRow(rowEnd - 1)
    if (lineText) {
      colEnd = lineText.length
    }

    // Ranges are 0-based
    return [
      [rowStart - 1, colStart - 1],
      [rowEnd - 1, colEnd - 1]
    ]
  }

  /**
   * Returns a provider for the linter plugin
   * @return {Object}
   */
  provideLinter() {
    return {
      grammarScopes,
      scope: 'file',
      lintOnFly: true,
      lint: editor => this._lint(editor),
      name: 'liferay'
    }
  }

  /**
   * Destroys the linter-liferay instance, cleaning up any
   * subscriptions.
   */
  destroy() {
    this._subscriptions.dispose()
  }
}
<commit_msg>Source Formatting<commit_after>'use babel'

import path from 'path'
import {BufferedProcess, CompositeDisposable} from 'atom'
import {findCached} from 'atom-linter'

/**
 * Returns the value if defined, or a default value if not
 * @param {a} val - The value to check if undef
 * @param {b} default - the default value
 * @return {a|b}
 */
function withDefault(val, defaultVal) {
  return typeof val === 'undefined' ? defaultVal : val
}

/**
 * Supported grammerScopes for linter-liferay
 * @type {Array.<string>}
 */
const grammarScopes = [
  'source.css.scss',
  'source.css',
  'source.js.jsx',
  'source.js',
  'source.velocity',
  'text.html.jsp',
  'text.html.mustache',
  'text.html'
]

/**
 * Check to see if configuration file exists
 * @param {string} filePath - Path to the file
 * @return {Boolean}
 */
function getConfigPath(filePath) {
  const configFile = findCached(
    filePath,
    ['.csfrc.js', '.csfrc.yaml', '.csfrc.yml', '.csfrc.json', '.csfrc', 'csf.config.js']
  )

  if (configFile) {
    return true
  }

  const packagePath = findCached(filePath, 'package.json')

  return packagePath && Boolean(require(packagePath).csfConfig)
}

/**
 * Regex used to parse check_sf's output. Each capture
 * group corresponds to the following value:
 *
 * $1 lineStart
 * $2 lineEnd
 * $3 column
 * $4 message
 *
 * @type {RegExp}
 */
const regex = /Lines?\s+(\d+)(\-\d+)?(?:,\s+Column\s+)?(\d+)?:\s+(.*)/i

/**
 * Class for managing the linting files and responding to
 * config changes
 */
export default class LinterLiferay {
  /**
   * Create a LinterLiferay
   */
  constructor() {
    this._subscriptions = new CompositeDisposable()

    this._subscriptions.add(atom.config.observe(
      'linter-liferay.lintJS',
      () => this._args = this._formatArgs()
    ))

    this._subscriptions.add(atom.config.observe(
      'linter-liferay.checkSFPath',
      newVal => this._cmd = newVal
    ))

    this._subscriptions.add(atom.config.observe(
      'linter-liferay.requireConfig',
      newVal => this._requireConfig = newVal
    ))

    this._pathMap = {}

    this._subscriptions.add(
      atom.workspace.onDidOpen(({uri}) => {
        if (this._requireConfig && !(uri in this._pathMap)) {
            this._pathMap[uri] = getConfigPath(uri)
        }
      })
    )
  }

  /**
   * Creates a process to read the ouput of check_sf
   * @param {string} path - Path to the file
   * @param {function} cb - The function to call with the output
   * @return {BufferedProcess}
   */
  _createProcess(filePath, cb) {
    const output = []

    return new BufferedProcess({
      command: this._cmd,
      args: [...this._args, filePath],
      options: {
        cwd: path.dirname(filePath)
      },
      stdout: data => output.push(data),
      exit: code => {
        const result = code === 0 ? output : [];

        cb(result)
      }
    })
  }

  /**
   * Formats and returns the arguments for check_sf
   * @return {Array.<string>}
   */
  _formatArgs() {
    const args = ['--no-color', '--show-columns']

    if (!atom.config.get('linter-liferay.lintJS')) {
      args.push('--no-lint')
    }

    return args
  }

  /**
   * Performs the actual lint operation
   * @param {TextEditor} editor - The editor being linted
   * @return {Promise}
   **/
  _lint(editor) {
    const filePath = editor.getPath()

    if (this._requireConfig && !this._pathMap[filePath]) {
      return
    }
    else {
      return new Promise((resolve, reject) => {
        const process = this._createProcess(
          filePath,
          output => resolve(this._getMessages(editor, output))
        )

        process.onWillThrowError(({error, handle}) => {
          atom.notifications.addError(
            `Cannot execute ${this._cmd}`,
            {
              detail: error.message,
              dismissable: true
            }
          )

          handle()
          reject(error)
        })
      })
    }
  }

  /**
   * Converts a RegExp exec result to a linter-liferay
   * match object
   * @param {Array} result
   * @return {Object}
   */
  _getMatch(result) {
    return {
      column: result[3],
      lineEnd: result[2],
      lineStart: result[1],
      message: result[4]
    }
  }

  /**
   * Parses check_sf's output into linter messages
   * @param {TextEditor} editor - The editor being linted
   * @param {Array.<string>} output - The output from check_sf
   * @return {Array.<Object>}
   */
  _getMessages(editor, output) {
    return output.reduce(
      (messages, next) => {
        const result = regex.exec(next)

        if (result) {
          const match = this._getMatch(result)

          messages.push({
            filePath: editor.getPath(),
            range: this._getRange(editor, match),
            type: 'warning',
            text: match.message
          })
        }

        return messages
      },
      []
    )
  }

  /**
   * Computes the range for a given match
   * @param {TextEditor} editor - The editor being linted
   * @param {Object} match - The match object
   * @return {Array.<Array.<number>>}
   */
  _getRange(editor, match) {
    const rowStart = match.lineStart
    const rowEnd = withDefault(match.lineEnd, rowStart)

    const colStart = withDefault(match.column, 1)

    let colEnd = 1
    const lineText = editor.lineTextForBufferRow(rowEnd - 1)
    if (lineText) {
      colEnd = lineText.length
    }

    // Ranges are 0-based
    return [
      [rowStart - 1, colStart - 1],
      [rowEnd - 1, colEnd - 1]
    ]
  }

  /**
   * Returns a provider for the linter plugin
   * @return {Object}
   */
  provideLinter() {
    return {
      grammarScopes,
      scope: 'file',
      lintOnFly: true,
      lint: editor => this._lint(editor),
      name: 'liferay'
    }
  }

  /**
   * Destroys the linter-liferay instance, cleaning up any
   * subscriptions.
   */
  destroy() {
    this._subscriptions.dispose()
  }
}
<|endoftext|>