<commit_before>/**
 * helpfunctie om aan een element van de DOM te komen
 */
function getElemId(id) {
	return document.getElementById(id);
}

/**
 * Een tekst invoegen in een textarea
 */
function voegin(tekst, id) {
	var tekstveld = getElemId(id);
	tekstveld.focus();
	var selectie;
	//IE en Opera
	if (document.selection) {
		selectie  = document.selection.createRange();
		prevRange = selectie.duplicate();
		prevRange.moveStart("character", -1);
		insertAtCursor(selectie, tekst);
		return;
	} else if (tekstveld.selectionStart || tekstveld.selectionStart == '0') { //MOZILLA/NETSCAPE
		var start = tekstveld.selectionStart;
		var end   = tekstveld.selectionEnd;
		tekstveld.value = tekstveld.value.substr(0, start)
		+ tekst
		+ tekstveld.value.substr(end, tekstveld.value.length);
		tekstveld.selectionStart = start + 1;
		tekstveld.selectionEnd = start + tekst.length;
		return;
	} else {
	  tekstveld.value += tekst;
	}
 }

/**
 * Wordt aangeroepen vanuit voegin
* doet het eigenlijke werk
*/
function insertAtCursor(range, tekst) {
	range.text = tekst;
	range.collapse(false);
	range.select();
}

// wordt aangeroepen wanneer de gebruiker in het werkveld typt
function controleer(e) {	// eerst  de character code ophalen
	e = getEvent(e);
	var code = getCode(e);
	if (code == 13) {
		getFeedback('enter key');
		stop(e);
		return false;
	}
	else {
		switch (code) {
			// - voor negatie
			case 45 :
				voegin(String.fromCharCode(172), "work");
				stop(e);
				return false;
			// = voor equivalentie
			case 61:
				voegin(String.fromCharCode(8596), "work");
				stop(e);
				return false;
			//  o voor or
			case 111 :
				voegin(String.fromCharCode(8744), "work");
				stop(e);
				return false;
			// i  voor implicatie
			case 105 :
				voegin(String.fromCharCode(8594), "work");
				stop(e);
				return false;
			// a voor and
			case 97 :
				voegin(String.fromCharCode(8743), "work");
				stop(e);
				return false;
			// laat p, q, r, t, f, T, F, ( en ) door
			case 112 : case 113 : case 114 : case 116 : case 102 : case 84 : case 70 : case 40 : case 41 :
			     	 return true;
			// drop alle andere invoer
			default :
				stop(e);
				return false;
		}
	}
	//e.returnValue = true;
	return true;
}

// vertaal asci karaktercode naar unicode
function vertaal(charcode) {
	switch (charcode) {
	// - voor negatie
	case 45 :
		return String.fromCharCode(172);
		break;
	// = voor equivalentie
	case 61:
		return String.fromCharCode(8596);
		break;
	//  o voor or
	case 111 :
		return String.fromCharCode(8744);
		break;
	// i  voor implicatie
	case 105 :
		return String.fromCharCode(8594);
		break;
	// a voor and
	case 97 :
		return String.fromCharCode(8743);
		break;
	default :
		return String.fromCharCode(charCode);
	}
}

// expressie in ascii omzetten naar unicode voor in div
function presenteer(opgave) {
	var resultaatstring = opgave.replace(/~/, '¬ ');
	while (resultaatstring != resultaatstring.replace(/~/, '¬ ')) {
		resultaatstring = resultaatstring.replace(/~/, '¬ ');
	}
	while (resultaatstring != resultaatstring.replace('<->', '↔')) {
		resultaatstring = resultaatstring.replace('<->', '↔');
	}
	while (resultaatstring != resultaatstring.replace('->', '→')) {
		resultaatstring = resultaatstring.replace('->', '→');
	}
	while (resultaatstring != resultaatstring.replace('||', '∨')) {
		resultaatstring = resultaatstring.replace('||', '∨');
	}
	while (resultaatstring != resultaatstring.replace('/\\', '∧')) {
		resultaatstring = resultaatstring.replace('/\\', '∧');
	 }
	return resultaatstring;
}

// expressie in ascii omzetten naar unicode voor in textarea
function presenteertekst(opgave) {
	var resultaatstring = opgave.replace('~', String.fromCharCode(172));
	while (resultaatstring != resultaatstring.replace(/~/, String.fromCharCode(172))) {
		resultaatstring = resultaatstring.replace(/~/, String.fromCharCode(172));
	}
	while (resultaatstring != resultaatstring.replace('<->', String.fromCharCode(8596))) {
		resultaatstring = resultaatstring.replace('<->', String.fromCharCode(8596));
	}
	while (resultaatstring != resultaatstring.replace('->', String.fromCharCode(8594))) {
		resultaatstring = resultaatstring.replace('->', String.fromCharCode(8594));
	}
	while (resultaatstring != resultaatstring.replace('||', String.fromCharCode(8744))) {
		resultaatstring = resultaatstring.replace('||', String.fromCharCode(8744));
	}
	while (resultaatstring != resultaatstring.replace('/\\', String.fromCharCode(8743))) {
		resultaatstring = resultaatstring.replace('/\\', String.fromCharCode(8743));
	 }
	return resultaatstring;
}

//  expressie in unicode uit textarea omzetten naar ascii
function naarAscii(expressie) {
	var resultaatstring = expressie.replace(String.fromCharCode(172), '~');
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(172), '~')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(172), '~');
	}
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(8596), '<->')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(8596), '<->');
	}
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(8594), '->')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(8594), '->');
	}
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(8744), '||')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(8744), '||');
	}
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(8743), '/\\\\')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(8743), '/\\\\');
	}
        return resultaatstring;
}

// hulpfunctie: domeinspecifieke karakters vervangen, en enters en tabs verwijderen: vanuit textarea naar exas
function werkveldNaarExas(expressie) {
	return schoon(naarAscii(expressie));
}

/**
* Om event handlers aan objecten te kunnen hangen
*/
function addEventSimple(object,event,fn) {
        if (object.addEventListener)
                object.addEventListener(event,fn,false);
        else if (object.attachEvent)
                object.attachEvent('on'+event,fn);
}

function removeEventSimple(object,event,fn) {
        if (object.removeEventListener)
	        object.removeEventListener(event,fn,false);
        else if (object.detachEvent)
                object.detachEvent('on'+event,fn);
}

/**
 * Om cross-browser het event-object te pakken te krijgen
 */
function getEvent(event) {
	if (typeof event == "undefined") {
		var event = window.event;
	}
	return event;
}

/**
 * om cross-browser de keycode te pakken te krijgen
 */
function getCode(event) {
	var code;
	if (event.keyCode) {
		// Opera en IE
		code = event.keyCode;
	}
	else {
		// Firefox
		code = event.which;
	}
	return code;
}

/**
 * om cross-browser de default action te voorkomen
  */
function stop(event) {
	event.cancelBubble = true;
	event.returnValue = false;
	if (event.stopPropagation) {
		event.stopPropagation();
		event.preventDefault();
	}
}

/**
 * Een functie om tabs en nieuwe regeltekens weg te halen,
  */
function schoon(tekst) {
	var oplossing = tekst.replace("\n", "");
	oplossing = oplossing.replace("\r", "");
	oplossing = oplossing.replace("\t", "");
	return oplossing;
}

/**
 * Om cross-browser aan de juiste selectie te komen
*/
function getRangeObject(selectionObject) {
	if (selectionObject.getRangeAt)
		return selectionObject.getRangeAt(0);
	else { // Safari!
		var range = document.createRange();
		range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
		range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
		return range;
	}
}
<commit_msg>Fixing allowed keyboard characters<commit_after>/**
 * helpfunctie om aan een element van de DOM te komen
 */
function getElemId(id) {
	return document.getElementById(id);
}

/**
 * Een tekst invoegen in een textarea
 */
function voegin(tekst, id) {
	var tekstveld = getElemId(id);
	tekstveld.focus();
	var selectie;
	//IE en Opera
	if (document.selection) {
		selectie  = document.selection.createRange();
		prevRange = selectie.duplicate();
		prevRange.moveStart("character", -1);
		insertAtCursor(selectie, tekst);
		return;
	} else if (tekstveld.selectionStart || tekstveld.selectionStart == '0') { //MOZILLA/NETSCAPE
		var start = tekstveld.selectionStart;
		var end   = tekstveld.selectionEnd;
		tekstveld.value = tekstveld.value.substr(0, start)
		+ tekst
		+ tekstveld.value.substr(end, tekstveld.value.length);
		tekstveld.selectionStart = start + 1;
		tekstveld.selectionEnd = start + tekst.length;
		return;
	} else {
	  tekstveld.value += tekst;
	}
 }

/**
 * Wordt aangeroepen vanuit voegin
* doet het eigenlijke werk
*/
function insertAtCursor(range, tekst) {
	range.text = tekst;
	range.collapse(false);
	range.select();
}

// wordt aangeroepen wanneer de gebruiker in het werkveld typt
function controleer(e) {	// eerst  de character code ophalen
	e = getEvent(e);
	var code = getCode(e);
	if (code == 13) {
		getFeedback('enter key');
		stop(e);
		return false;
	}
	else {
		switch (code) {
			// - voor negatie
			case 45 :
				voegin(String.fromCharCode(172), "work");
				stop(e);
				return false;
			// = voor equivalentie
			case 61:
				voegin(String.fromCharCode(8596), "work");
				stop(e);
				return false;
			//  o voor or
			case 111 :
				voegin(String.fromCharCode(8744), "work");
				stop(e);
				return false;
			// i  voor implicatie
			case 105 :
				voegin(String.fromCharCode(8594), "work");
				stop(e);
				return false;
			// a voor and
			case 97 :
				voegin(String.fromCharCode(8743), "work");
				stop(e);
				return false;
			// laat p, q, r, T, F, ( en ) en spatie door
			case 112 : case 113 : case 114 : case 32 : case 84 : case 70 : case 40 : case 41 :
			     	 return true;
			// drop alle andere invoer
			default :
				stop(e);
				return false;
		}
	}
	//e.returnValue = true;
	return true;
}

// vertaal asci karaktercode naar unicode
function vertaal(charcode) {
	switch (charcode) {
	// - voor negatie
	case 45 :
		return String.fromCharCode(172);
		break;
	// = voor equivalentie
	case 61:
		return String.fromCharCode(8596);
		break;
	//  o voor or
	case 111 :
		return String.fromCharCode(8744);
		break;
	// i  voor implicatie
	case 105 :
		return String.fromCharCode(8594);
		break;
	// a voor and
	case 97 :
		return String.fromCharCode(8743);
		break;
	default :
		return String.fromCharCode(charCode);
	}
}

// expressie in ascii omzetten naar unicode voor in div
function presenteer(opgave) {
	var resultaatstring = opgave.replace(/~/, '¬ ');
	while (resultaatstring != resultaatstring.replace(/~/, '¬ ')) {
		resultaatstring = resultaatstring.replace(/~/, '¬ ');
	}
	while (resultaatstring != resultaatstring.replace('<->', '↔')) {
		resultaatstring = resultaatstring.replace('<->', '↔');
	}
	while (resultaatstring != resultaatstring.replace('->', '→')) {
		resultaatstring = resultaatstring.replace('->', '→');
	}
	while (resultaatstring != resultaatstring.replace('||', '∨')) {
		resultaatstring = resultaatstring.replace('||', '∨');
	}
	while (resultaatstring != resultaatstring.replace('/\\', '∧')) {
		resultaatstring = resultaatstring.replace('/\\', '∧');
	 }
	return resultaatstring;
}

// expressie in ascii omzetten naar unicode voor in textarea
function presenteertekst(opgave) {
	var resultaatstring = opgave.replace('~', String.fromCharCode(172));
	while (resultaatstring != resultaatstring.replace(/~/, String.fromCharCode(172))) {
		resultaatstring = resultaatstring.replace(/~/, String.fromCharCode(172));
	}
	while (resultaatstring != resultaatstring.replace('<->', String.fromCharCode(8596))) {
		resultaatstring = resultaatstring.replace('<->', String.fromCharCode(8596));
	}
	while (resultaatstring != resultaatstring.replace('->', String.fromCharCode(8594))) {
		resultaatstring = resultaatstring.replace('->', String.fromCharCode(8594));
	}
	while (resultaatstring != resultaatstring.replace('||', String.fromCharCode(8744))) {
		resultaatstring = resultaatstring.replace('||', String.fromCharCode(8744));
	}
	while (resultaatstring != resultaatstring.replace('/\\', String.fromCharCode(8743))) {
		resultaatstring = resultaatstring.replace('/\\', String.fromCharCode(8743));
	 }
	return resultaatstring;
}

//  expressie in unicode uit textarea omzetten naar ascii
function naarAscii(expressie) {
	var resultaatstring = expressie.replace(String.fromCharCode(172), '~');
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(172), '~')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(172), '~');
	}
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(8596), '<->')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(8596), '<->');
	}
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(8594), '->')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(8594), '->');
	}
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(8744), '||')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(8744), '||');
	}
	while (resultaatstring != resultaatstring.replace(String.fromCharCode(8743), '/\\\\')) {
		resultaatstring = resultaatstring.replace(String.fromCharCode(8743), '/\\\\');
	}
        return resultaatstring;
}

// hulpfunctie: domeinspecifieke karakters vervangen, en enters en tabs verwijderen: vanuit textarea naar exas
function werkveldNaarExas(expressie) {
	return schoon(naarAscii(expressie));
}

/**
* Om event handlers aan objecten te kunnen hangen
*/
function addEventSimple(object,event,fn) {
        if (object.addEventListener)
                object.addEventListener(event,fn,false);
        else if (object.attachEvent)
                object.attachEvent('on'+event,fn);
}

function removeEventSimple(object,event,fn) {
        if (object.removeEventListener)
	        object.removeEventListener(event,fn,false);
        else if (object.detachEvent)
                object.detachEvent('on'+event,fn);
}

/**
 * Om cross-browser het event-object te pakken te krijgen
 */
function getEvent(event) {
	if (typeof event == "undefined") {
		var event = window.event;
	}
	return event;
}

/**
 * om cross-browser de keycode te pakken te krijgen
 */
function getCode(event) {
	var code;
	if (event.keyCode) {
		// Opera en IE
		code = event.keyCode;
	}
	else {
		// Firefox
		code = event.which;
	}
	return code;
}

/**
 * om cross-browser de default action te voorkomen
  */
function stop(event) {
	event.cancelBubble = true;
	event.returnValue = false;
	if (event.stopPropagation) {
		event.stopPropagation();
		event.preventDefault();
	}
}

/**
 * Een functie om tabs en nieuwe regeltekens weg te halen,
  */
function schoon(tekst) {
	var oplossing = tekst.replace("\n", "");
	oplossing = oplossing.replace("\r", "");
	oplossing = oplossing.replace("\t", "");
	return oplossing;
}

/**
 * Om cross-browser aan de juiste selectie te komen
*/
function getRangeObject(selectionObject) {
	if (selectionObject.getRangeAt)
		return selectionObject.getRangeAt(0);
	else { // Safari!
		var range = document.createRange();
		range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
		range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
		return range;
	}
}
<|endoftext|>


<commit_before>/**
 * Function to execute drag 'n drop functionality of the beverages in consumer view
 */
function dragNDrop() {
    'use strict';
    var sidebar = document.getElementById("sidebar");

    /**
     * Function to change the id of the sidebar
     * @use To highlight the sidebar when dragging an object
     * @param elementToBeChanged is the element which id is changed
     */
    function changeSidebarId(elementToBeChanged) {
        if (elementToBeChanged.id == "sidebar") {
            elementToBeChanged.setAttribute('id', 'sidebarHighlighted');
        } else {
            elementToBeChanged.id = "sidebar";
        }
    }

    /**
     * Function that does the actual dragging and dropping
     */
    $(function() {
        $(".product").draggable({
            revert: "invalid", // when not dropped, the item will revert back to its initial position
            containment: "document",
            helper: function(e, ui) {
                /* console.log($(this).clone());*/
                return $(this).clone();
            },
            cursor: "grab",
            start: function(event, ui) {
                // Function call to highlight the sidebar once dragging starts
                changeSidebarId(sidebar);
            },
            stop: function(event, ui) {
                // Function call to stop highlighting of the sidebar once dragging stops
                changeSidebarId(sidebar);
            }

        });

        $("#sidebar").droppable({
            //      accept: ".product",
            drop: function(event, ui) {
                var name = $(ui.draggable).find('p:eq(0)').html();
                var priceString = $(ui.draggable).find('p:eq(1)').html();
                var price = priceString.split(" ")[0];
                var id = availableBevIds[name]; //Fetching the id corresponding to the name
                if (typeof id == "undefined") {
                    id = 0;
                }
                addProduct(id, name, parseFloat(price));
            },
            out: function(event, ui) {
                // Not sure if this is needed in the project work.
            }
        });
    });
}

function switchView() {
    'use strict';
    $('#toggle_div :checkbox').on('change', function(event) {
        if (this.checked) {
            document.location = './admin_view.php';
        } else {
            document.location = './index.php';
        }
    });
}<commit_msg>fixed so admin toggle now links correctly<commit_after>/**
 * Function to execute drag 'n drop functionality of the beverages in consumer view
 */
function dragNDrop() {
    'use strict';
    var sidebar = document.getElementById("sidebar");

    /**
     * Function to change the id of the sidebar
     * @use To highlight the sidebar when dragging an object
     * @param elementToBeChanged is the element which id is changed
     */
    function changeSidebarId(elementToBeChanged) {
        if (elementToBeChanged.id == "sidebar") {
            elementToBeChanged.setAttribute('id', 'sidebarHighlighted');
        } else {
            elementToBeChanged.id = "sidebar";
        }
    }

    /**
     * Function that does the actual dragging and dropping
     */
    $(function() {
        $(".product").draggable({
            revert: "invalid", // when not dropped, the item will revert back to its initial position
            containment: "document",
            helper: function(e, ui) {
                /* console.log($(this).clone());*/
                return $(this).clone();
            },
            cursor: "grab",
            start: function(event, ui) {
                // Function call to highlight the sidebar once dragging starts
                changeSidebarId(sidebar);
            },
            stop: function(event, ui) {
                // Function call to stop highlighting of the sidebar once dragging stops
                changeSidebarId(sidebar);
            }

        });

        $("#sidebar").droppable({
            //      accept: ".product",
            drop: function(event, ui) {
                var name = $(ui.draggable).find('p:eq(0)').html();
                var priceString = $(ui.draggable).find('p:eq(1)').html();
                var price = priceString.split(" ")[0];
                var id = availableBevIds[name]; //Fetching the id corresponding to the name
                if (typeof id == "undefined") {
                    id = 0;
                }
                addProduct(id, name, parseFloat(price));
            },
            out: function(event, ui) {
                // Not sure if this is needed in the project work.
            }
        });
    });
}

function switchView() {
    'use strict';
    $('#toggle_div :checkbox').on('change', function(event) {
        if (this.checked) {
            document.location = './admin_stock.php';
        } else {
            document.location = './index.php';
        }
    });
}<|endoftext|>


<commit_before>openerp.web_kanban_gauge = function (instance) {

/**
 * Kanban widgets: GaugeWidget
 *
 */
var _t = instance.web._t,
   _lt = instance.web._lt;
instance.web_kanban.GaugeWidget = instance.web_kanban.AbstractField.extend({
    className: "oe_gauge",
    start: function() {
        var self = this;
        var parent = this.getParent();
        var max = 100;
        if (this.options.max_field) {
            max = this.getParent().record[this.options.max_field].raw_value;
        }
        var label = this.options.label || "";
        if (this.options.label_field) {
            label = this.getParent().record[this.options.label_field].raw_value;
        }
        var val = this.field.value;
        var value = _.isArray(val) && val.length ? val[val.length-1]['value'] : val;
        var title = this.$node.html() || this.field.string;
        // var unique_id = _.uniqueId("JustGage");

        this.$el.empty()
            .attr('style', this.$node.attr('style') + ';position:relative; display:inline-block;');

        this.gage = new JustGage({
            parentNode: this.$el[0],
            // id: unique_id,
            value: value,
            title: title,
            min: 0,
            max: max,
            relativeGaugeSize: true,
            humanFriendly: true,
            titleFontColor: '#333333',
            valueFontColor: '#333333',
            labelFontColor: '#000',
            label: label,
            levelColors: [
                "#ff0000",
                "#f9c802",
                "#a9d70b"
            ],
        });
        this.gage.refresh(value, max);

        var flag_open = false;
        if (this.options.action_change) {
            var $svg = this.$el.find('svg');
            var css = {
                'text-align': 'center',
                'position': 'absolute',
                'width': this.$el.outerWidth() + 'px',
                'top': (this.$el.outerHeight()/2-5) + 'px'
            };

            this.$el.click(function (event) {
                event.stopPropagation();
                flag_open = false;
                if (!parent.view.is_action_enabled('edit')) {
                    return;
                }
                if (!self.$el.find(".oe_justgage_edit").size()) {
                    $div = $('
');
                    $div.css(css);
                    $input = $('<input/>').val(value);
                    $input.css({
                        'text-align': 'center',
                        'margin': 'auto',
                        'width': ($svg.outerWidth()-40) + 'px'
                    });
                    $div.append($input);
                    self.$el.prepend($div)
                    $input.focus()
                        .keydown(function (event) {
                            event.stopPropagation();
                            if(isNaN($input.val())){
                                self.do_warn(_t("Wrong value entered!"), _t("Only Integer Value should be valid."));
                                $div.remove();
                            } else {
                                if (event.keyCode == 13 || event.keyCode == 9) {
                                    var val = self.parse_client($input.val());
                                    if ($input.val() != value) {
                                        parent.view.dataset.call(self.options.action_change, [parent.id, $input.val()]).then(function () {
                                            parent.do_reload();
                                        });
                                    } else {
                                        $div.remove();
                                    }
                                }
                            }
                        })
                        .click(function (event) {
                            event.stopPropagation();
                            flag_open = false;
                        })
                        .blur(function (event) {
                            if(!flag_open) {
                                self.$el.find(".oe_justgage_edit").remove();
                            } else {
                                flag_open = false;
                                setTimeout(function () {$input.focus();}, 0);
                            }
                        });
                }
            }).mousedown(function () {
                flag_open = true;
            });

            if (!+value) {
                $svg.fadeTo(0, 0.3);
                $div = $('
').text(_t("Click to change value"));
                $div.css(css);
                this.$el.append($div);
            }
        }
    },

    parse_client: function(value) {
        return openerp.web.parse_value(value, { type:"integer" });
    },

});

instance.web_kanban.fields_registry.add("gauge", "instance.web_kanban.GaugeWidget");

}
<commit_msg>[FIX] replace integer with float in validation<commit_after>openerp.web_kanban_gauge = function (instance) {

/**
 * Kanban widgets: GaugeWidget
 *
 */
var _t = instance.web._t,
   _lt = instance.web._lt;
instance.web_kanban.GaugeWidget = instance.web_kanban.AbstractField.extend({
    className: "oe_gauge",
    start: function() {
        var self = this;
        var parent = this.getParent();
        var max = 100;
        if (this.options.max_field) {
            max = this.getParent().record[this.options.max_field].raw_value;
        }
        var label = this.options.label || "";
        if (this.options.label_field) {
            label = this.getParent().record[this.options.label_field].raw_value;
        }
        var val = this.field.value;
        var value = _.isArray(val) && val.length ? val[val.length-1]['value'] : val;
        var title = this.$node.html() || this.field.string;
        // var unique_id = _.uniqueId("JustGage");

        this.$el.empty()
            .attr('style', this.$node.attr('style') + ';position:relative; display:inline-block;');

        this.gage = new JustGage({
            parentNode: this.$el[0],
            // id: unique_id,
            value: value,
            title: title,
            min: 0,
            max: max,
            relativeGaugeSize: true,
            humanFriendly: true,
            titleFontColor: '#333333',
            valueFontColor: '#333333',
            labelFontColor: '#000',
            label: label,
            levelColors: [
                "#ff0000",
                "#f9c802",
                "#a9d70b"
            ],
        });
        this.gage.refresh(value, max);

        var flag_open = false;
        if (this.options.action_change) {
            var $svg = this.$el.find('svg');
            var css = {
                'text-align': 'center',
                'position': 'absolute',
                'width': this.$el.outerWidth() + 'px',
                'top': (this.$el.outerHeight()/2-5) + 'px'
            };

            this.$el.click(function (event) {
                event.stopPropagation();
                flag_open = false;
                if (!parent.view.is_action_enabled('edit')) {
                    return;
                }
                if (!self.$el.find(".oe_justgage_edit").size()) {
                    $div = $('
');
                    $div.css(css);
                    $input = $('<input/>').val(value);
                    $input.css({
                        'text-align': 'center',
                        'margin': 'auto',
                        'width': ($svg.outerWidth()-40) + 'px'
                    });
                    $div.append($input);
                    self.$el.prepend($div)
                    $input.focus()
                        .keydown(function (event) {
                            event.stopPropagation();
                            if(isNaN($input.val())){
                                self.do_warn(_t("Wrong value entered!"), _t("Only Integer Value should be valid."));
                                $div.remove();
                            } else {
                                if (event.keyCode == 13 || event.keyCode == 9) {
                                    var val = self.parse_client($input.val());
                                    if ($input.val() != value) {
                                        parent.view.dataset.call(self.options.action_change, [parent.id, $input.val()]).then(function () {
                                            parent.do_reload();
                                        });
                                    } else {
                                        $div.remove();
                                    }
                                }
                            }
                        })
                        .click(function (event) {
                            event.stopPropagation();
                            flag_open = false;
                        })
                        .blur(function (event) {
                            if(!flag_open) {
                                self.$el.find(".oe_justgage_edit").remove();
                            } else {
                                flag_open = false;
                                setTimeout(function () {$input.focus();}, 0);
                            }
                        });
                }
            }).mousedown(function () {
                flag_open = true;
            });

            if (!+value) {
                $svg.fadeTo(0, 0.3);
                $div = $('
').text(_t("Click to change value"));
                $div.css(css);
                this.$el.append($div);
            }
        }
    },

    parse_client: function(value) {
        return openerp.web.parse_value(value, { type:"float" });
    },

});

instance.web_kanban.fields_registry.add("gauge", "instance.web_kanban.GaugeWidget");

}
<|endoftext|>


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

/**
 * @fileoverview Generating Java for loop blocks.
 * @author toebes@extremenetworks.com (John Toebes)
 * Based on Python version by q.neutron@gmail.com (Quynh Neutron)
 */
'use strict';

goog.provide('Blockly.Java.loops');

goog.require('Blockly.Java');

Blockly.Java['controls_repeat'] = function(block) {
  // Repeat n times (internal number).
  var repeats = parseInt(block.getFieldValue('TIMES'), 10);
  var branch = Blockly.Java.statementToCode(block, 'DO');
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;
  var loopVar = Blockly.Java.variableDB_.getDistinctName(
      'count', Blockly.Variables.NAME_TYPE);
  var code = 'for (int ' + loopVar + '=0; '+
                  loopVar+' < ' + repeats + ';'+
                  loopVar+'++) {\n' +
               branch +
             '} // end for\n';
  return code;
};

Blockly.Java['controls_repeat_ext'] = function(block) {
  // Repeat n times (external number).
  var repeats = Blockly.Java.valueToCode(block, 'TIMES',
      Blockly.Java.ORDER_NONE) || '0';
  if (Blockly.isNumber(repeats)) {
    repeats = parseInt(repeats, 10);
  } else {
    repeats = 'int(' + repeats + ')';
  }
  var branch = Blockly.Java.statementToCode(block, 'DO');
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;
  var loopVar = Blockly.Java.variableDB_.getDistinctName(
      'count', Blockly.Variables.NAME_TYPE);
  var code = 'for (int ' + loopVar + '=0; '+
                           loopVar +' < ' + repeats + ';'+
                           loopVar + '++) {\n' +
                branch +
             '} // end for\n';
  return code;
};

Blockly.Java['controls_whileUntil'] = function(block) {
  // Do while/until loop.
  var until = block.getFieldValue('MODE') == 'UNTIL';
  var argument0 = Blockly.Java.valueToCode(block, 'BOOL',
      until ? Blockly.Java.ORDER_LOGICAL_NOT :
      Blockly.Java.ORDER_NONE) || 'false';
  var branch = Blockly.Java.statementToCode(block, 'DO');
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;

  if ((until && (argument0 === 'true')) || (!until && (argument0 === 'false'))){
    var argvar = Blockly.Java.variableDB_.getDistinctName(
      argument0, Blockly.Variables.NAME_TYPE);
    Blockly.Java.stashStatement('boolean ' + argvar + ' = ' + argument0 + ';\n');
    argument0 = argvar;
  }

  if (until) {
    argument0 = '!' + argument0;
  }
  return 'while (' + argument0 + ') {\n' +
           branch +
         '} // end while\n';
};

Blockly.Java['controls_for'] = function(block) {
  // For loop.
  var variable0 = Blockly.Java.variableDB_.getName(
      block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
  var vartype0 = Blockly.Java.GetVariableType(block.getFieldValue('VAR'));
  var argument0 = Blockly.Java.valueToCode(block, 'FROM',
      Blockly.Java.ORDER_NONE) || '0';
  var argument1 = Blockly.Java.valueToCode(block, 'TO',
      Blockly.Java.ORDER_NONE) || '0';
  var increment = Blockly.Java.valueToCode(block, 'BY',
      Blockly.Java.ORDER_NONE) || '1';
  var branch = Blockly.Java.statementToCode(block, 'DO');
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;

  var variable0Type = Blockly.Java.GetVariableType(block.getFieldValue('VAR'));

  var code = '';
  var range;

  if (Blockly.isNumber(argument0) &&
      Blockly.isNumber(argument1) &&
      Blockly.isNumber(increment)) {
    // All parameters are simple numbers.
    argument0 = parseFloat(argument0);
    argument1 = parseFloat(argument1);
    increment = Math.abs(parseFloat(increment));
    var direction = '<=';
    var doincrement = '++';
    // All parameters are integers.
    if (argument0 > argument1) {
      // Count down.
      direction = '>=';
      increment = -increment;
    }
    if (variable0Type === 'Var') {
      code = 'for (' + variable0 + '.setObject(' + argument0 + '); ' +
                       variable0 + '.getObjectAsDouble() ' +
                                               direction + argument1 + '; ' +
                       variable0 + '.incrementObject(' + increment + ')) ';
    } else {
      if (increment < 0) {
        doincrement = ' -= ' + Math.abs(increment);
      } else if (increment != 1) {
        doincrement = ' += ' + increment;
      }
      code += 'for (' + variable0 + ' = ' + argument0 + '; ' +
                        variable0 + direction + argument1 + '; ' +
                        variable0 + doincrement + ')';
    }
  } else {
    // Cache non-trivial values to variables to prevent repeated look-ups.
    var startVar = argument0;
    if (!argument0.match(/^\w+$/) && !Blockly.isNumber(argument0)) {
      startVar = Blockly.Java.variableDB_.getDistinctName(
          variable0 + '_start', Blockly.Variables.NAME_TYPE);
      code += 'double ' + startVar + ' = ' + argument0 + ';\n';
    }
    var endVar = argument1;
    if (!argument1.match(/^\w+$/) && !Blockly.isNumber(argument1)) {
      var endVar = Blockly.Java.variableDB_.getDistinctName(
          variable0 + '_end', Blockly.Variables.NAME_TYPE);
      code += 'double ' + endVar + ' = ' + argument1 + ';\n';
    }
    // Determine loop direction at start, in case one of the bounds
    // changes during loop execution.
    var incVar = Blockly.Java.variableDB_.getDistinctName(
        variable0 + '_inc', Blockly.Variables.NAME_TYPE);
    code += 'double ' + incVar + ' = ';
    if (Blockly.isNumber(increment)) {
      code += Math.abs(increment) + ';\n';
    } else {
      code += 'Math.abs(' + increment + ');\n';
    }
    code += 'if (' + startVar + ' > ' + endVar + ') {\n';
    code += Blockly.Java.INDENT + incVar + ' = -' + incVar + ';\n';
    code += '}\n';
    if (variable0Type === 'Var') {
      code += 'for (' + variable0 + '.setObject(' + startVar + ');\n' +
          '     ' + incVar + ' >= 0 ? ' +
          variable0 + '.getObjectAsDouble() <= ' + endVar + ' : ' +
          variable0 + '.getObjectAsDouble()  >= ' + endVar + ';\n' +
                        variable0 + '.incrementObject(' + incVar + ')) ';
    } else {
      code += 'for (' + variable0 + ' = ' + startVar + ';\n' +
          '     ' + incVar + ' >= 0 ? ' +
          variable0 + ' <= ' + endVar + ' : ' +
          variable0 + ' >= ' + endVar + ';\n' +
          '     ' + variable0 + ' += ' + incVar + ')';
    }
  }
  code += ' {\n' +
              branch +
           '} // end for\n';
  return code;
};

Blockly.Java['controls_forEach'] = function(block) {
  // For each loop.
  var variable0 = Blockly.Java.variableDB_.getName(
      block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
  var vartype0 = Blockly.Java.GetVariableType(block.getFieldValue('VAR'));
  var argument0 = Blockly.Java.valueToCode(block, 'LIST',
      Blockly.Java.ORDER_RELATIONAL) || '[]';
  var branch = Blockly.Java.statementToCode(block, 'DO');
  var setvar0;
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;

  var loopVar = Blockly.Java.variableDB_.getDistinctName(
      'it', Blockly.Variables.NAME_TYPE);
  if (vartype0 === 'Var') {
    setvar0 = variable0 + '.setObject(' + loopVar + '.next())';
  } else {
    setvar0 = variable0 + ' = ' + loopVar + '.next()';
  }

  Blockly.Java.addImport('java.util.Iterator');
  var code = 'for (Iterator ' + loopVar + ' = ' +
                  argument0 + '.iterator(); ' + loopVar + '.hasNext();) {\n'+
             '  ' + setvar0 + ';\n'
              + branch + '} // end for\n';
  return code;
};

Blockly.Java['controls_flow_statements'] = function(block) {
  // Flow statements: continue, break.
  switch (block.getFieldValue('FLOW')) {
    case 'BREAK':
      return 'break;\n';
    case 'CONTINUE':
      return 'continue;\n';
  }
  throw 'Unknown flow statement.';
};
<commit_msg>Fix indentation for loops to use Blocky.Java.Indent<commit_after>/**
 * @license
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Generating Java for loop blocks.
 * @author toebes@extremenetworks.com (John Toebes)
 * Based on Python version by q.neutron@gmail.com (Quynh Neutron)
 */
'use strict';

goog.provide('Blockly.Java.loops');

goog.require('Blockly.Java');

Blockly.Java['controls_repeat'] = function(block) {
  // Repeat n times (internal number).
  var repeats = parseInt(block.getFieldValue('TIMES'), 10);
  var branch = Blockly.Java.statementToCode(block, 'DO');
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;
  var loopVar = Blockly.Java.variableDB_.getDistinctName(
      'count', Blockly.Variables.NAME_TYPE);
  var code = 'for (int ' + loopVar + '=0; '+
                  loopVar+' < ' + repeats + ';'+
                  loopVar+'++) {\n' +
               branch +
             '} // end for\n';
  return code;
};

Blockly.Java['controls_repeat_ext'] = function(block) {
  // Repeat n times (external number).
  var repeats = Blockly.Java.valueToCode(block, 'TIMES',
      Blockly.Java.ORDER_NONE) || '0';
  if (Blockly.isNumber(repeats)) {
    repeats = parseInt(repeats, 10);
  } else {
    repeats = 'int(' + repeats + ')';
  }
  var branch = Blockly.Java.statementToCode(block, 'DO');
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;
  var loopVar = Blockly.Java.variableDB_.getDistinctName(
      'count', Blockly.Variables.NAME_TYPE);
  var code = 'for (int ' + loopVar + '=0; '+
                           loopVar +' < ' + repeats + ';'+
                           loopVar + '++) {\n' +
                branch +
             '} // end for\n';
  return code;
};

Blockly.Java['controls_whileUntil'] = function(block) {
  // Do while/until loop.
  var until = block.getFieldValue('MODE') == 'UNTIL';
  var argument0 = Blockly.Java.valueToCode(block, 'BOOL',
      until ? Blockly.Java.ORDER_LOGICAL_NOT :
      Blockly.Java.ORDER_NONE) || 'false';
  var branch = Blockly.Java.statementToCode(block, 'DO');
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;

  if ((until && (argument0 === 'true')) || (!until && (argument0 === 'false'))){
    var argvar = Blockly.Java.variableDB_.getDistinctName(
      argument0, Blockly.Variables.NAME_TYPE);
    Blockly.Java.stashStatement('boolean ' + argvar + ' = ' + argument0 + ';\n');
    argument0 = argvar;
  }

  if (until) {
    argument0 = '!' + argument0;
  }
  return 'while (' + argument0 + ') {\n' +
           branch +
         '} // end while\n';
};

Blockly.Java['controls_for'] = function(block) {
  // For loop.
  var variable0 = Blockly.Java.variableDB_.getName(
      block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
  var vartype0 = Blockly.Java.GetVariableType(block.getFieldValue('VAR'));
  var argument0 = Blockly.Java.valueToCode(block, 'FROM',
      Blockly.Java.ORDER_NONE) || '0';
  var argument1 = Blockly.Java.valueToCode(block, 'TO',
      Blockly.Java.ORDER_NONE) || '0';
  var increment = Blockly.Java.valueToCode(block, 'BY',
      Blockly.Java.ORDER_NONE) || '1';
  var branch = Blockly.Java.statementToCode(block, 'DO');
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;

  var variable0Type = Blockly.Java.GetVariableType(block.getFieldValue('VAR'));

  var code = '';
  var range;

  if (Blockly.isNumber(argument0) &&
      Blockly.isNumber(argument1) &&
      Blockly.isNumber(increment)) {
    // All parameters are simple numbers.
    argument0 = parseFloat(argument0);
    argument1 = parseFloat(argument1);
    increment = Math.abs(parseFloat(increment));
    var direction = '<=';
    var doincrement = '++';
    // All parameters are integers.
    if (argument0 > argument1) {
      // Count down.
      direction = '>=';
      increment = -increment;
    }
    if (variable0Type === 'Var') {
      code = 'for (' + variable0 + '.setObject(' + argument0 + '); ' +
                       variable0 + '.getObjectAsDouble() ' +
                                               direction + argument1 + '; ' +
                       variable0 + '.incrementObject(' + increment + ')) ';
    } else {
      if (increment < 0) {
        doincrement = ' -= ' + Math.abs(increment);
      } else if (increment != 1) {
        doincrement = ' += ' + increment;
      }
      code += 'for (' + variable0 + ' = ' + argument0 + '; ' +
                        variable0 + direction + argument1 + '; ' +
                        variable0 + doincrement + ')';
    }
  } else {
    // Cache non-trivial values to variables to prevent repeated look-ups.
    var startVar = argument0;
    if (!argument0.match(/^\w+$/) && !Blockly.isNumber(argument0)) {
      startVar = Blockly.Java.variableDB_.getDistinctName(
          variable0 + '_start', Blockly.Variables.NAME_TYPE);
      code += 'double ' + startVar + ' = ' + argument0 + ';\n';
    }
    var endVar = argument1;
    if (!argument1.match(/^\w+$/) && !Blockly.isNumber(argument1)) {
      var endVar = Blockly.Java.variableDB_.getDistinctName(
          variable0 + '_end', Blockly.Variables.NAME_TYPE);
      code += 'double ' + endVar + ' = ' + argument1 + ';\n';
    }
    // Determine loop direction at start, in case one of the bounds
    // changes during loop execution.
    var incVar = Blockly.Java.variableDB_.getDistinctName(
        variable0 + '_inc', Blockly.Variables.NAME_TYPE);
    code += 'double ' + incVar + ' = ';
    if (Blockly.isNumber(increment)) {
      code += Math.abs(increment) + ';\n';
    } else {
      code += 'Math.abs(' + increment + ');\n';
    }
    code += 'if (' + startVar + ' > ' + endVar + ') {\n';
    code += Blockly.Java.INDENT + incVar + ' = -' + incVar + ';\n';
    code += '}\n';
    if (variable0Type === 'Var') {
      code += 'for (' + variable0 + '.setObject(' + startVar + ');\n' +
          Blockly.Java.INDENT + incVar + ' >= 0 ? ' +
          variable0 + '.getObjectAsDouble() <= ' + endVar + ' : ' +
          variable0 + '.getObjectAsDouble()  >= ' + endVar + ';\n' +
                        variable0 + '.incrementObject(' + incVar + ')) ';
    } else {
      code += 'for (' + variable0 + ' = ' + startVar + ';\n' +
          Blockly.Java.INDENT + incVar + ' >= 0 ? ' +
          variable0 + ' <= ' + endVar + ' : ' +
          variable0 + ' >= ' + endVar + ';\n' +
          Blockly.Java.INDENT + variable0 + ' += ' + incVar + ')';
    }
  }
  code += ' {\n' +
              branch +
           '} // end for\n';
  return code;
};

Blockly.Java['controls_forEach'] = function(block) {
  // For each loop.
  var variable0 = Blockly.Java.variableDB_.getName(
      block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
  var vartype0 = Blockly.Java.GetVariableType(block.getFieldValue('VAR'));
  var argument0 = Blockly.Java.valueToCode(block, 'LIST',
      Blockly.Java.ORDER_RELATIONAL) || '[]';
  var branch = Blockly.Java.statementToCode(block, 'DO');
  var setvar0;
  branch = Blockly.Java.addLoopTrap(branch, block.id) ||
      Blockly.Java.PASS;

  var loopVar = Blockly.Java.variableDB_.getDistinctName(
      'it', Blockly.Variables.NAME_TYPE);
  if (vartype0 === 'Var') {
    setvar0 = variable0 + '.setObject(' + loopVar + '.next())';
  } else {
    setvar0 = variable0 + ' = ' + loopVar + '.next()';
  }

  Blockly.Java.addImport('java.util.Iterator');
  var code = 'for (Iterator ' + loopVar + ' = ' +
                  argument0 + '.iterator(); ' + loopVar + '.hasNext();) {\n'+
             Blockly.Java.INDENT + setvar0 + ';\n'
              + branch + '} // end for\n';
  return code;
};

Blockly.Java['controls_flow_statements'] = function(block) {
  // Flow statements: continue, break.
  switch (block.getFieldValue('FLOW')) {
    case 'BREAK':
      return 'break;\n';
    case 'CONTINUE':
      return 'continue;\n';
  }
  throw 'Unknown flow statement.';
};
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Promise = require('../../promise');

/**
 Returns an object that treats Oracle's inabilities to do certain queries.
 */

/**
  A wrapper that fixes Oracle's inability to cleanly drop constraints on multiple tables if the calls are made at the same time
  @param  {Object} options
 */
const dropAllTables = function(options) {

  options = options || {};
  const skip = options.skip || [];
  const promises = [];

  //As oracle uppercase all tables names, we create a mapping array with everything in upperCase
  const upperSkip = skip.map(table => {
    return table.toUpperCase();
  });

  return this.showAllTables(options).then(tableNames => {

    tableNames.forEach(tableName => {
      if (Object.keys(tableName).length > 0) {
        if (upperSkip.indexOf(tableName.tableName) === -1) {
          // promises.push(this.dropTable(tableName, _.assign({}, options, { cascade: true }) ));
          promises.push(this.QueryGenerator.dropTableQuery(tableName, false));
        }
      } else {
        if (upperSkip.indexOf(tableName) === -1) {
          // promises.push(this.dropTable(tableName, _.assign({}, options, { cascade: true }) ));
          promises.push(this.QueryGenerator.dropTableQuery(tableName, false));
        }
      }
    });
    if (promises.length > 0) {
      const finalSql = [
        'BEGIN ',
        promises.join(''),
        ' EXCEPTION WHEN OTHERS THEN IF SQLCODE != -942 THEN',
        ' RAISE; END IF;',
        'END;'
      ].join('');

      return this.sequelize.query(finalSql, options);
    }
    return true;

  });
};

/**
  A wrapper that fixes Oracle's inability to cleanly remove columns from existing tables if they have a default constraint.

  @method removeColumn
  @for    QueryInterface

  @param  {String} tableName     The name of the table.
  @param  {String} attributeName The name of the attribute that we want to remove.
  @param  {Object} options
  @param  {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
 @private
 */
const removeColumn = function(tableName, attributeName, options) {
  options = Object.assign({ raw: true }, options || {});

  const constraintsSql = [];

  //We start by searching if the primary key is an identity
  const descriptionTableQuery = this.QueryGenerator.isIdentityPrimaryKey(tableName);
  return this.sequelize.query(descriptionTableQuery, options)
  .spread(PKResult => {

    for (let i = 0; i < PKResult.length; i++) {
      //We iterate through the primary keys to determine if we are working on it
      if (PKResult[i].column_name === attributeName.toUpperCase()) {
        //The column we are working on is in the PK AND is an identity column, we have to drop the identity
        const dropIdentitySql = this.QueryGenerator.dropIdentityColumn(tableName, attributeName);
        constraintsSql.push({
          sql : dropIdentitySql,
          options
        });
        break;
      }
    }

    //This method return all constraints on a table with a given attribute
    const findConstraintSql = this.QueryGenerator.getConstraintsOnColumn(tableName, attributeName);
    return this.sequelize.query(findConstraintSql, options)
    .spread(results => {
      if (!results.length && constraintsSql.length === 0) {
        // No default constraint found -- we can cleanly remove the column
        return;
      }

      //Function to execute the different remove one by one
      const deleteRecursively = function(constraints, idx, sequelizeInstance) {
        if (constraints.length > 0) {
          if (idx < constraints.length) {
            const elem = constraints[idx];
            idx++;
            //While elements, we execute the query
            return sequelizeInstance.query(elem.sql, elem.options)
            .then(() => {
              return deleteRecursively(constraints, idx, sequelizeInstance);
            });
          } else {
            //Done, we get out
            return Promise.resolve({});
          }
        } else {
          return Promise.resolve({});
        }
      };

      results.forEach(result => {
        //For each constraint, we get the sql
        constraintsSql.push({
          sql : this.QueryGenerator.dropConstraintQuery(tableName, result.constraint_name),
          options
        });
      });

      // const dropConstraintSql = this.QueryGenerator.dropConstraintQuery(tableName, results[0].name);
      return deleteRecursively(constraintsSql, 0, this.sequelize);
    })
    .then(() => {
      const removeSql = this.QueryGenerator.removeColumnQuery(tableName, attributeName);
      return this.sequelize.query(removeSql, options);
    });

  });

};

/**
 * A wrapper that adds the currentModel of the describe in options
 * This is used for mapping the real column names to those returned by Oracle
 */
const addOptionsForDescribe = function(tableName, options) {
  if (this.sequelize && this.sequelize.models && Object.keys(this.sequelize.models).length > 0) {
    const keys = Object.keys(this.sequelize.models);
    let i = 0, found = false;
    while (i < keys.length && !found) {
      const model = this.sequelize.models[keys[i]];
      if (model.tableName === tableName) {
        if (options) {
          options['describeModelAttributes'] = model.attributes;
        } else {
          options = {
            'describeModelAttributes' : model.attributes
          };
        }
        found = true;
      }
      i++;
    }
  }
  return options;
};

module.exports = {
  dropAllTables,
  removeColumn,
  addOptionsForDescribe
};
<commit_msg>fix(linting) : removing unused import<commit_after>'use strict';

const Promise = require('../../promise');

/**
 Returns an object that treats Oracle's inabilities to do certain queries.
 */

/**
  A wrapper that fixes Oracle's inability to cleanly drop constraints on multiple tables if the calls are made at the same time
  @param  {Object} options
 */
const dropAllTables = function(options) {

  options = options || {};
  const skip = options.skip || [];
  const promises = [];

  //As oracle uppercase all tables names, we create a mapping array with everything in upperCase
  const upperSkip = skip.map(table => {
    return table.toUpperCase();
  });

  return this.showAllTables(options).then(tableNames => {

    tableNames.forEach(tableName => {
      if (Object.keys(tableName).length > 0) {
        if (upperSkip.indexOf(tableName.tableName) === -1) {
          // promises.push(this.dropTable(tableName, _.assign({}, options, { cascade: true }) ));
          promises.push(this.QueryGenerator.dropTableQuery(tableName, false));
        }
      } else {
        if (upperSkip.indexOf(tableName) === -1) {
          // promises.push(this.dropTable(tableName, _.assign({}, options, { cascade: true }) ));
          promises.push(this.QueryGenerator.dropTableQuery(tableName, false));
        }
      }
    });
    if (promises.length > 0) {
      const finalSql = [
        'BEGIN ',
        promises.join(''),
        ' EXCEPTION WHEN OTHERS THEN IF SQLCODE != -942 THEN',
        ' RAISE; END IF;',
        'END;'
      ].join('');

      return this.sequelize.query(finalSql, options);
    }
    return true;

  });
};

/**
  A wrapper that fixes Oracle's inability to cleanly remove columns from existing tables if they have a default constraint.

  @method removeColumn
  @for    QueryInterface

  @param  {String} tableName     The name of the table.
  @param  {String} attributeName The name of the attribute that we want to remove.
  @param  {Object} options
  @param  {Boolean|Function} [options.logging] A function that logs the sql queries, or false for explicitly not logging these queries
 @private
 */
const removeColumn = function(tableName, attributeName, options) {
  options = Object.assign({ raw: true }, options || {});

  const constraintsSql = [];

  //We start by searching if the primary key is an identity
  const descriptionTableQuery = this.QueryGenerator.isIdentityPrimaryKey(tableName);
  return this.sequelize.query(descriptionTableQuery, options)
  .spread(PKResult => {

    for (let i = 0; i < PKResult.length; i++) {
      //We iterate through the primary keys to determine if we are working on it
      if (PKResult[i].column_name === attributeName.toUpperCase()) {
        //The column we are working on is in the PK AND is an identity column, we have to drop the identity
        const dropIdentitySql = this.QueryGenerator.dropIdentityColumn(tableName, attributeName);
        constraintsSql.push({
          sql : dropIdentitySql,
          options
        });
        break;
      }
    }

    //This method return all constraints on a table with a given attribute
    const findConstraintSql = this.QueryGenerator.getConstraintsOnColumn(tableName, attributeName);
    return this.sequelize.query(findConstraintSql, options)
    .spread(results => {
      if (!results.length && constraintsSql.length === 0) {
        // No default constraint found -- we can cleanly remove the column
        return;
      }

      //Function to execute the different remove one by one
      const deleteRecursively = function(constraints, idx, sequelizeInstance) {
        if (constraints.length > 0) {
          if (idx < constraints.length) {
            const elem = constraints[idx];
            idx++;
            //While elements, we execute the query
            return sequelizeInstance.query(elem.sql, elem.options)
            .then(() => {
              return deleteRecursively(constraints, idx, sequelizeInstance);
            });
          } else {
            //Done, we get out
            return Promise.resolve({});
          }
        } else {
          return Promise.resolve({});
        }
      };

      results.forEach(result => {
        //For each constraint, we get the sql
        constraintsSql.push({
          sql : this.QueryGenerator.dropConstraintQuery(tableName, result.constraint_name),
          options
        });
      });

      // const dropConstraintSql = this.QueryGenerator.dropConstraintQuery(tableName, results[0].name);
      return deleteRecursively(constraintsSql, 0, this.sequelize);
    })
    .then(() => {
      const removeSql = this.QueryGenerator.removeColumnQuery(tableName, attributeName);
      return this.sequelize.query(removeSql, options);
    });

  });

};

/**
 * A wrapper that adds the currentModel of the describe in options
 * This is used for mapping the real column names to those returned by Oracle
 */
const addOptionsForDescribe = function(tableName, options) {
  if (this.sequelize && this.sequelize.models && Object.keys(this.sequelize.models).length > 0) {
    const keys = Object.keys(this.sequelize.models);
    let i = 0, found = false;
    while (i < keys.length && !found) {
      const model = this.sequelize.models[keys[i]];
      if (model.tableName === tableName) {
        if (options) {
          options['describeModelAttributes'] = model.attributes;
        } else {
          options = {
            'describeModelAttributes' : model.attributes
          };
        }
        found = true;
      }
      i++;
    }
  }
  return options;
};

module.exports = {
  dropAllTables,
  removeColumn,
  addOptionsForDescribe
};
<|endoftext|>


<commit_before><commit_msg>Fix markup.all<commit_after><|endoftext|>


<commit_before>// Define module using Universal Module Definition pattern
// https://github.com/umdjs/umd/blob/master/amdWeb.js

(function (root, deps, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(deps, factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.

    module.exports = factory.apply(this, deps.map(function(dep){ return require(dep);}));
  } else {
    // Browser globals (root is window)
    root.returnExports = factory.apply(this, deps.map(function(dep){ return root[dep];}));
  }
}(this, ['lodash', 'vega', 'vl.templates'], function (lodash, vg, mixins){

  var vl = {
    version:  "0.0.1", // semantic versioning
    vg:       vg,      // stash d3 for use
  };

  var defaultOpts = {
    width: 200,
    height: 200,
    "padding": {"top": 30, "left": 50, "bottom": 30, "right": 30},
    legends: false, // on for big visualization
    markscolor: "steelblue",
    markshovercolor: "red",
    fillplotopacity: 0.2,
    plotsize: 100
  }

  function traverse(node, fn){
    if(_.isArray(node)){
      // console.log('isArray',node);
      _.each(node, function(child){
        traverse(child, fn);
      });
    }
    if(!_.isObject(node)) return;
    fn(node);
    _.each(node, function(child, key){
      // console.log('accessing child key', key, child);
      traverse(child, fn);
    })
  }

  function getVGSpec(chart, schema, data, opt){
    var spec = mixins.spec(), props = {}, marksOpt={}, marks;

    var fieldX = (chart.fields.x||{})[0],
      fieldY = (chart.fields.y||{})[0],
      fieldColor = (chart.fields.color||{})[0],
      fieldShape = (chart.fields.shape||{})[0];

    // TODO(kanitw): support table algebra
    if(fieldX) props.field_x = 'data.' + fieldX.key;
    if(fieldY) props.field_y = 'data.' + fieldY.key;
    if(fieldColor) props.field_color = 'data.' + fieldColor.key;
    if(fieldShape) props.field_shape = 'data.' + fieldShape.key;

    //TODO:(kanitw): update scale based on x,y fields

    console.log("fields", fieldX, fieldY);

    if(chart.chart_type == "BAR"){
      spec.data = mixins.data();
      spec.scales = [
        mixins.scale_qnt('x'),
        mixins.scale_ord('y')
      ];

      //TODO make this code less redundant
      if(fieldColor){
        spec.scales.push(fieldColor.dataType == "quantitative" ? mixins.scale_color_quant() : mixins.scale_color_ord());
        marksOpt.color = {scale:"color", field: "__field_color__"};
      }

      spec.axes = mixins.axes();
      spec.marks = [
        mixins.marks_bar()
      ];

    }else if(chart.chart_type == "PLOT"){
      spec.data = mixins.data();
      spec.scales = [
        fieldX.dataType == "quantitative" ? mixins.scale_qnt('x') : mixins.scale_ord('x', {points:true}),
        fieldY.dataType == "quantitative" ? mixins.scale_qnt('y') : mixins.scale_ord('y', {points:true})
      ];

      //TODO make this code less redundant
      if(fieldColor){
        spec.scales.push(fieldColor.dataType == "quantitative" ? mixins.scale_color_quant() : mixins.scale_color_ord());
        marksOpt.color = {scale:"color", field: "__field_color__"};
      }
      if(fieldShape){
        spec.scales.push(mixins.scale_shape()) ;
        marksOpt.shape = {scale:"shape", field: "__field_shape__"};
        props.plotsize = 50;
      }

      //TODO make this code less redundant
      if(fieldColor){
        spec.scales.push(fieldColor.dataType == "quantitative" ? mixins.scale_color_quant() : mixins.scale_color_ord());
      }

      spec.axes = mixins.axes();
      if(chart.fields.size){
        spec.scales.push(mixins.scale_size());
        props.field_size = 'data.' + chart.fields.size[0].key;
        marksOpt.size = {scale:"size", field: "__field_size__"};
      }
      spec.marks = [
        mixins.marks_plot(marksOpt)
      ];

    }else{
      // TODO(kanitw): zening please add map case here!
      return null;
    }

    // ADD COLOR

    //
    // Determine properties
    // TODO(kanitw): create scale for color, shape, size

    // TODO(kanitw): adjust properties

    traverse(spec, function(node){
      // console.log('traverse replace', node);
      _.each(node, function(val, key, node){
        if( val && _.isString(val) &&
            val.indexOf("__")===0 &&
            val.lastIndexOf("__") ===val.length-2)
        { //is __placeholder
          var propName = val.substring(2, val.length-2);
          node[key] = props[propName] || opt[propName];
          // console.log('placeholder', val, node);
        }
      })
    });

    return spec;
  }

  vl.parse = function(chart, schema, data, element, opt){
    opt = _.merge(opt || {}, defaultOpts)
    return getVGSpec(chart, schema, data, opt);
  };

  return vl;
}));<commit_msg>(comments)<commit_after>// Define module using Universal Module Definition pattern
// https://github.com/umdjs/umd/blob/master/amdWeb.js

(function (root, deps, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(deps, factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.

    module.exports = factory.apply(this, deps.map(function(dep){ return require(dep);}));
  } else {
    // Browser globals (root is window)
    root.returnExports = factory.apply(this, deps.map(function(dep){ return root[dep];}));
  }
}(this, ['lodash', 'vega', 'vl.templates'], function (lodash, vg, mixins){

  var vl = {
    version:  "0.0.1", // semantic versioning
    vg:       vg,      // stash d3 for use
  };

  var defaultOpts = {
    width: 200,
    height: 200,
    "padding": {"top": 30, "left": 50, "bottom": 30, "right": 30},
    legends: false, // on for big visualization
    markscolor: "steelblue",
    markshovercolor: "red",
    fillplotopacity: 0.2,
    plotsize: 100
  }

  function traverse(node, fn){
    if(_.isArray(node)){
      // console.log('isArray',node);
      _.each(node, function(child){
        traverse(child, fn);
      });
    }
    if(!_.isObject(node)) return;
    fn(node);
    _.each(node, function(child, key){
      // console.log('accessing child key', key, child);
      traverse(child, fn);
    })
  }

  function getVGSpec(chart, schema, data, opt){
    var spec = mixins.spec(), props = {}, marksOpt={}, marks;

    var fieldX = (chart.fields.x||{})[0], //FIXME support 1 x only for now
      fieldY = (chart.fields.y||{})[0], //FIXME
      fieldColor = (chart.fields.color||{})[0],
      fieldShape = (chart.fields.shape||{})[0];

    // TODO(kanitw): support table algebra
    if(fieldX) props.field_x = 'data.' + fieldX.key;
    if(fieldY) props.field_y = 'data.' + fieldY.key;
    if(fieldColor) props.field_color = 'data.' + fieldColor.key;
    if(fieldShape) props.field_shape = 'data.' + fieldShape.key;

    //TODO:(kanitw): update scale based on x,y fields

    console.log("fields", fieldX, fieldY);

    if(chart.chart_type == "BAR"){
      spec.data = mixins.data();
      spec.scales = [
        mixins.scale_qnt('x'),
        mixins.scale_ord('y')
      ];

      //TODO make this code less redundant
      if(fieldColor){
        spec.scales.push(fieldColor.dataType == "quantitative" ? mixins.scale_color_quant() : mixins.scale_color_ord());
        marksOpt.color = {scale:"color", field: "__field_color__"};
      }

      spec.axes = mixins.axes();
      spec.marks = [
        mixins.marks_bar()
      ];

    }else if(chart.chart_type == "PLOT"){
      spec.data = mixins.data();
      spec.scales = [
        fieldX.dataType == "quantitative" ? mixins.scale_qnt('x') : mixins.scale_ord('x', {points:true}),
        fieldY.dataType == "quantitative" ? mixins.scale_qnt('y') : mixins.scale_ord('y', {points:true})
      ];

      //TODO make this code less redundant
      if(fieldColor){
        spec.scales.push(fieldColor.dataType == "quantitative" ? mixins.scale_color_quant() : mixins.scale_color_ord());
        marksOpt.color = {scale:"color", field: "__field_color__"};
      }
      if(fieldShape){
        spec.scales.push(mixins.scale_shape()) ;
        marksOpt.shape = {scale:"shape", field: "__field_shape__"};
        props.plotsize = 50;
      }

      //TODO make this code less redundant
      if(fieldColor){
        spec.scales.push(fieldColor.dataType == "quantitative" ? mixins.scale_color_quant() : mixins.scale_color_ord());
      }

      spec.axes = mixins.axes();
      if(chart.fields.size){
        spec.scales.push(mixins.scale_size());
        props.field_size = 'data.' + chart.fields.size[0].key;
        marksOpt.size = {scale:"size", field: "__field_size__"};
      }
      spec.marks = [
        mixins.marks_plot(marksOpt)
      ];

    }else{
      // TODO(kanitw): zening please add map case here!
      return null;
    }

    // ADD COLOR

    //
    // Determine properties
    // TODO(kanitw): create scale for color, shape, size

    // TODO(kanitw): adjust properties

    //traversing the spec and replace placeholder properties
    traverse(spec, function(node){
      // console.log('traverse replace', node);
      _.each(node, function(val, key, node){
        if( val && _.isString(val) &&
            val.indexOf("__")===0 &&
            val.lastIndexOf("__") ===val.length-2)
        { //is __placeholder__
          var propName = val.substring(2, val.length-2);
          node[key] = props[propName] || opt[propName];
          // console.log('placeholder', val, node);
        }
      })
    });

    return spec;
  }

  vl.parse = function(chart, schema, data, element, opt){
    opt = _.merge(opt || {}, defaultOpts)
    return getVGSpec(chart, schema, data, opt);
  };

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


<commit_before>'use strict';
const _ = require('lodash');
const askName = require('inquirer-npm-name');
const parseAuthor = require('parse-author');
const Base = require('yeoman-generator').Base;
const patchPackageJSON = require('../../utils').patchPackageJSON;
const originUrl = require('git-remote-origin-url');

// based on https://github.com/yeoman/generator-node/blob/master/generators/app/index.js

class PackageJSONGenerator extends Base {

  constructor(args, options) {
    super(args, options);

    // readme content
    this.option('readme');
  }

  initializing() {
    const pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    this.props = {
      description: pkg.description,
      homepage: pkg.homepage
    };

    var authorName = 'Caleydo Team';
    if (_.isObject(pkg.author)) {
      authorName = pkg.author.name;
      this.props.authorEmail = pkg.author.email;
      this.props.authorUrl = pkg.author.url;
    } else if (_.isString(pkg.author)) {
      let info = parseAuthor(pkg.author);
      authorName = info.name;
      this.props.authorEmail = info.email;
      this.props.authorUrl = info.url;
    }

    this.config.defaults({
      name: pkg.name || this.determineAppname(),
      author: authorName,
      today: (new Date()).toUTCString(),
      githubAccount: 'phovea'
    });

    return originUrl(this.destinationPath()).then((url) => {
      this.originUrl = url;
    }, () => {
      this.originUrl = '';
    });
  }

  _promptForName() {
    return askName({
      name: 'name',
      message: 'Plugin Name',
      default: this.config.get('name'),
      filter: _.snakeCase
    }, this).then((props) => {
      this.config.set('name', props.name);
    });
  }

  _promptDescription() {
    return this.prompt([{
      name: 'description',
      message: 'Description',
      default: this.config.get('description')
    }, {
      name: 'homepage',
      message: 'Project homepage url',
      default: 'https://phovea.caleydo.org'
    }, {
      name: 'authorName',
      message: 'Author\'s Name',
      default: this.user.git.name(),
      store: true
    }, {
      name: 'authorEmail',
      message: 'Author\'s Email',
      default: this.user.git.email(),
      store: true
    }, {
      name: 'authorUrl',
      message: 'Author\'s Homepage',
      store: true
    }, {
      name: 'githubAccount',
      message: 'GitHub username or organization',
      default: this.config.get('githubAccount'),
      store: true
    }]).then((props) => {
      this.props.description = props.description;
      this.props.homepage = props.homepage;
      this.config.set('author', props.authorName);
      this.props.authorEmail = props.authorEmail;
      this.props.authorUrl = props.authorUrl;
      this.config.set('githubAccount', props.githubAccount);
    });
  }

  prompting() {
    return this._promptForName().then(() => this._promptDescription());
  }

  writing() {
    const config = _.extend({}, this.props, this.config.getAll());

    if (this.originUrl) {
      config.repository = this.originUrl;
    } else {
      config.repository = `https://github.com/${config.githubAccount}/${config.name}.git`;
    }
    patchPackageJSON.call(this, config);

    config.content = this.options.readme || '';
    this.fs.copyTpl(this.templatePath('README.tmpl.md'), this.destinationPath('README.md'), config);

    const includeDot = {
      globOptions: {
        dot: true
      }
    };
    this.fs.copy(this.templatePath('plain/**/*'), this.destinationPath(), includeDot);
  }

  end() {
    this.spawnCommandSync('git', ['init'], {
      cwd: this.destinationPath()
    });
  }
}

module.exports = PackageJSONGenerator;
<commit_msg>use github user name detection<commit_after>'use strict';
const _ = require('lodash');
const askName = require('inquirer-npm-name');
const parseAuthor = require('parse-author');
const Base = require('yeoman-generator').Base;
const patchPackageJSON = require('../../utils').patchPackageJSON;
const originUrl = require('git-remote-origin-url');

// based on https://github.com/yeoman/generator-node/blob/master/generators/app/index.js

class PackageJSONGenerator extends Base {

  constructor(args, options) {
    super(args, options);

    // readme content
    this.option('readme');
  }

  initializing() {
    const pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    this.props = {
      description: pkg.description,
      homepage: pkg.homepage
    };

    var authorName = 'Caleydo Team';
    if (_.isObject(pkg.author)) {
      authorName = pkg.author.name;
      this.props.authorEmail = pkg.author.email;
      this.props.authorUrl = pkg.author.url;
    } else if (_.isString(pkg.author)) {
      let info = parseAuthor(pkg.author);
      authorName = info.name;
      this.props.authorEmail = info.email;
      this.props.authorUrl = info.url;
    }

    this.config.defaults({
      name: pkg.name || this.determineAppname(),
      author: authorName,
      today: (new Date()).toUTCString(),
      githubAccount: this.github ? this.github.username() || 'phovea'
    });

    return originUrl(this.destinationPath()).then((url) => {
      this.originUrl = url;
    }, () => {
      this.originUrl = '';
    });
  }

  _promptForName() {
    return askName({
      name: 'name',
      message: 'Plugin Name',
      default: this.config.get('name'),
      filter: _.snakeCase
    }, this).then((props) => {
      this.config.set('name', props.name);
    });
  }

  _promptDescription() {
    return this.prompt([{
      name: 'description',
      message: 'Description',
      default: this.config.get('description')
    }, {
      name: 'homepage',
      message: 'Project homepage url',
      default: 'https://phovea.caleydo.org'
    }, {
      name: 'authorName',
      message: 'Author\'s Name',
      default: this.user.git.name(),
      store: true
    }, {
      name: 'authorEmail',
      message: 'Author\'s Email',
      default: this.user.git.email(),
      store: true
    }, {
      name: 'authorUrl',
      message: 'Author\'s Homepage',
      store: true
    }, {
      name: 'githubAccount',
      message: 'GitHub username or organization',
      default: this.config.get('githubAccount'),
      store: true
    }]).then((props) => {
      this.props.description = props.description;
      this.props.homepage = props.homepage;
      this.config.set('author', props.authorName);
      this.props.authorEmail = props.authorEmail;
      this.props.authorUrl = props.authorUrl;
      this.config.set('githubAccount', props.githubAccount);
    });
  }

  prompting() {
    return this._promptForName().then(() => this._promptDescription());
  }

  writing() {
    const config = _.extend({}, this.props, this.config.getAll());

    if (this.originUrl) {
      config.repository = this.originUrl;
    } else {
      config.repository = `https://github.com/${config.githubAccount}/${config.name}.git`;
    }
    patchPackageJSON.call(this, config);

    config.content = this.options.readme || '';
    this.fs.copyTpl(this.templatePath('README.tmpl.md'), this.destinationPath('README.md'), config);

    const includeDot = {
      globOptions: {
        dot: true
      }
    };
    this.fs.copy(this.templatePath('plain/**/*'), this.destinationPath(), includeDot);
  }

  end() {
    this.spawnCommandSync('git', ['init'], {
      cwd: this.destinationPath()
    });
  }
}

module.exports = PackageJSONGenerator;
<|endoftext|>


<commit_before>module.exports = ({ Plugin, types: t }) => {
  const mangleNamesVisitors = {
    Scope({ scope }) {
      const bindings = scope.bindings;
      scope.bindings = {};

      const names = Object.keys(bindings);

      let i = 0;
      for (let name of names) {
        let binding = bindings[name];
        let bindingRefs = this.refs.get(binding);
        if (!bindingRefs) {
          continue;
        }

        let newName;

        do {
          newName = this.charset.getIdentifier(i);
          i += 1;
        } while (!(t.isValidIdentifier(newName)
            && canUse(newName, scope, bindingRefs, this.refs)));

        // WARNING: this is a destructive operation, use scope.rename for
        // a safer operation, however, it does full tree traversal for every
        // rename:
        scope.bindings[newName] = binding;
        for (let ref of bindingRefs) {
          ref.node.name = newName;
        }
      }
    },
  };

  const collectVisitor = {
    'ReferencedIdentifier|BindingIdentifier'(path) {
      const { scope, node } = path;
      recordRef(this.refs, scope.getBinding(node.name), path);
    },

    Literal({ node }) {
      this.charset.consider(String(node.value));
    },

    Identifier(path) {
      if ((path.parentPath.isMemberExpression() && path.key === 'property') ||
          (path.parentPath.isObjectProperty() && path.key === 'key')
      ) {
        this.charset.consider(path.node.name);
      }
    },
  };

  return {
    visitor: {
      Program(path) {
        // If the source code is small then considering the source program
        // text is not good because it creates non-determinisim.
        // Found that in general the source : minified ratio is ~ 1 : 3
        const shouldConsiderSource = (path.getSource().length / 3) > 32000;

        const charset = new Charset(shouldConsiderSource);
        // We want to take control of the sequencing and make sure our visitors
        // run in isolation.
        const refs = new Map();
        path.traverse(collectVisitor, {
          refs,
          charset,
        });

        charset.sort();

        path.traverse(mangleNamesVisitors, {
          refs,
          charset,
        });
      },
    },
  };

  function canUse(name, scope, refs, refsMap) {
    // Competing binding in the definition scope.
    const competingBinding = scope.getBinding(name);
    if (competingBinding) {
      /**
       * Go through all references then crawl their scopes upwards,
       * looking to see if one of these references is in this scope.
       */
      const bindingRefs = refsMap.get(competingBinding);
      for (let ref of bindingRefs) {
        let myScope = ref.scope;
        do {
          if (myScope === scope) {
            return false;
          }
          myScope = myScope.parent;
        } while (myScope);

      }
      return true;
    }
    return true;
  }

  function recordRef(refs, binding, refPath) {
    if (!refs.has(binding)) {
      refs.set(binding, []);
    }
    refs.get(binding).push(refPath);
  }
};

const CHARSET = ('abcdefghijklmnopqrstuvwxyz' +
                 'ABCDEFGHIJKLMNOPQRSTUVWXYZ$').split('');

class Charset {
  constructor(shouldConsider) {
    this.shouldConsider = shouldConsider;
    this.chars = CHARSET.slice();
    this.frequency = {};
    this.chars.forEach(c => this.frequency[c] = 0);
    this.finalized = false;
  }

  consider(str) {
    if (!this.shouldConsider) {
      return;
    }

    str.split('').forEach(c => {
      if (this.frequency[c] != null) {
        this.frequency[c]++;
      }
    });
  }

  sort() {
    if (this.shouldConsider) {
      this.chars = this.chars.sort(
        (a, b) => this.frequency[b] - this.frequency[a]
      );
    }

    this.finalized = true;
  }

  getIdentifier(num) {
    if (!this.finalized) {
      throw new Error('Should sort first');
    }

    let ret = '';
    num++;
    do {
      num--;
      ret += this.chars[num % this.chars.length];
      num = Math.floor(num / this.chars.length);
    } while (num > 0);
    return ret;
  }
}
<commit_msg>add _<commit_after>module.exports = ({ Plugin, types: t }) => {
  const mangleNamesVisitors = {
    Scope({ scope }) {
      const bindings = scope.bindings;
      scope.bindings = {};

      const names = Object.keys(bindings);

      let i = 0;
      for (let name of names) {
        let binding = bindings[name];
        let bindingRefs = this.refs.get(binding);
        if (!bindingRefs) {
          continue;
        }

        let newName;

        do {
          newName = this.charset.getIdentifier(i);
          i += 1;
        } while (!(t.isValidIdentifier(newName)
            && canUse(newName, scope, bindingRefs, this.refs)));

        // WARNING: this is a destructive operation, use scope.rename for
        // a safer operation, however, it does full tree traversal for every
        // rename:
        scope.bindings[newName] = binding;
        for (let ref of bindingRefs) {
          ref.node.name = newName;
        }
      }
    },
  };

  const collectVisitor = {
    'ReferencedIdentifier|BindingIdentifier'(path) {
      const { scope, node } = path;
      recordRef(this.refs, scope.getBinding(node.name), path);
    },

    Literal({ node }) {
      this.charset.consider(String(node.value));
    },

    Identifier(path) {
      if ((path.parentPath.isMemberExpression() && path.key === 'property') ||
          (path.parentPath.isObjectProperty() && path.key === 'key')
      ) {
        this.charset.consider(path.node.name);
      }
    },
  };

  return {
    visitor: {
      Program(path) {
        // If the source code is small then considering the source program
        // text is not good because it creates non-determinisim.
        // Found that in general the source : minified ratio is ~ 1 : 3
        const shouldConsiderSource = (path.getSource().length / 3) > 32000;

        const charset = new Charset(shouldConsiderSource);
        // We want to take control of the sequencing and make sure our visitors
        // run in isolation.
        const refs = new Map();
        path.traverse(collectVisitor, {
          refs,
          charset,
        });

        charset.sort();

        path.traverse(mangleNamesVisitors, {
          refs,
          charset,
        });
      },
    },
  };

  function canUse(name, scope, refs, refsMap) {
    // Competing binding in the definition scope.
    const competingBinding = scope.getBinding(name);
    if (competingBinding) {
      /**
       * Go through all references then crawl their scopes upwards,
       * looking to see if one of these references is in this scope.
       */
      const bindingRefs = refsMap.get(competingBinding);
      for (let ref of bindingRefs) {
        let myScope = ref.scope;
        do {
          if (myScope === scope) {
            return false;
          }
          myScope = myScope.parent;
        } while (myScope);

      }
      return true;
    }
    return true;
  }

  function recordRef(refs, binding, refPath) {
    if (!refs.has(binding)) {
      refs.set(binding, []);
    }
    refs.get(binding).push(refPath);
  }
};

const CHARSET = ('abcdefghijklmnopqrstuvwxyz' +
                 'ABCDEFGHIJKLMNOPQRSTUVWXYZ$_').split('');

class Charset {
  constructor(shouldConsider) {
    this.shouldConsider = shouldConsider;
    this.chars = CHARSET.slice();
    this.frequency = {};
    this.chars.forEach(c => this.frequency[c] = 0);
    this.finalized = false;
  }

  consider(str) {
    if (!this.shouldConsider) {
      return;
    }

    str.split('').forEach(c => {
      if (this.frequency[c] != null) {
        this.frequency[c]++;
      }
    });
  }

  sort() {
    if (this.shouldConsider) {
      this.chars = this.chars.sort(
        (a, b) => this.frequency[b] - this.frequency[a]
      );
    }

    this.finalized = true;
  }

  getIdentifier(num) {
    if (!this.finalized) {
      throw new Error('Should sort first');
    }

    let ret = '';
    num++;
    do {
      num--;
      ret += this.chars[num % this.chars.length];
      num = Math.floor(num / this.chars.length);
    } while (num > 0);
    return ret;
  }
}
<|endoftext|>


<commit_before><commit_msg>projectpage<commit_after><|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////////////////////////
// Grunt config customisations
function gruntAliases(options) {
	const aliases = {
		lint: {
			description: 'Lint files in the project.',
			tasks: [
				'eslint'
			]
		}
	};

	if (options.nodeServer) {
		aliases.serve = {
			description: 'Start server and watch for file changes',
			tasks: [
				'express',
				'watch'
			]
		};

		aliases['build:server'] = {
			description: 'Build task for server files',
			tasks: [
				'eslint:server',
				'uglify:server',
				'sync:server'
			]
		};

		if (options.polymerApp) {
			aliases['build:bower'] = {
				description: 'Build task for bower components',
				tasks: [
					'minifyPolymer:bower',
					'minifyPolymerCSS:bower',
					'uglify:bower'
				]
			};

			aliases['build:components'] = {
				description: 'Build task for custom components',
				tasks: [
					'minifyPolymer:components',
					'sass:components',
					'uglify:components'
				]
			};

			aliases['build:views'] = {
				description: 'Build task for views',
				tasks: [
					'minifyPolymer:views',
					'sass:views',
					'uglify:views'
				]
			};
		}
	}

	return aliases;
}

function gruntEslint(options) {
	const eslint = {
		options: {
			format: 'node_modules/eslint-formatter-pretty'
		},
		project: {
			files: [
				{
					expand: true,
					src: [
						'gruntfile.js',
						'grunt/*.js'
					]
				}
			]
		}
	};

	if (options.nodeServer) {
		eslint.server = {
			files: 'server/**/*.js'
		};

		eslint.components = {
			files: ['public/custom-components/**/*.js']
		};

		eslint.views = {
			src: ['public/scripts/**/*.js']
		};
	}

	return eslint;
}

function gruntExpress(options) {
	const express = {};

	if (options.nodeServer) {
		express.all = {
			options: {
				script: 'build/server/start.js'
			}
		};
	}

	return express;
}

function gruntSync(options) {
	const sync = {};

	if (options.nodeServer) {
		sync.server = {
			files: {
				'build/.env': '.env'
			}
		};
	}

	return sync;
}

function gruntUglify(options) {
	const uglify = {};

	if (options.nodeServer) {
		uglify.server = {
			files: [
				{
					expand: true,
					cwd: 'server/',
					src: ['**/*.js'],
					dest: 'build/server/'
				}
			]
		};

		if (options.polymerApp) {
			uglify.bower = {
				files: [
					{
						expand: true,
						cwd: 'public/bower_components/',
						src: [
							'**/*.js',
							'!**/*.min.js',
							'!**/{grunt,gulp}file.js',
							'!**/{demo,demos,docs,explainer,node_modules,test,tests}/**/*'
						],
						dest: 'build/public/bower_components/'
					}
				]
			};

			uglify.components = {
				files: [
					{
						expand: true,
						cwd: 'public/custom-components/',
						src: ['**/*.js'],
						dest: 'build/public/custom-components/'
					}
				]
			};

			uglify.views = {
				files: [
					{
						expand: true,
						cwd: 'public/scripts/',
						src: ['**/*.js'],
						dest: 'build/scripts/'
					}
				]
			};
		}
	}

	return uglify;
}

function gruntWatch(options) {
	const watch = {};

	if (options.nodeServer) {
		watch.options = {
			spawn: false,
			interrupt: true
		};

		watch.server = {
			options: {
				reload: true
			},
			files: [
				'gruntfile.js',
				'grunt/*.js',
				'server/**/*.js'
			],
			tasks: [
				'express:stop',
				'eslint:server',
				'build:server',
				'express'
			]
		};

		if (options.polymerApp) {
			watch.bower = {
				files: ['bower.json'],
				tasks: ['build:bower']
			};

			watch.components = {
				files: ['public/custom-components/**/*'],
				tasks: [
					'eslint:components',
					'build:components'
				]
			};

			watch['sass-partials'] = {
				files: ['public/stylesheets/partials/*.scss'],
				tasks: ['sass']
			},

			watch.views = {
				files: [
					'public/*.html',
					'public/stylesheets/*.scss',
					'public/scripts/**/*.js'
				],
				tasks: [
					'eslint:views',
					'build:views'
				]
			};
		}
	}

	return watch;
}

function gruntBower(options) {
	const bower = {};

	if (options.polymerApp) {
		bower.options = {
			copy: false,
			targetDir: 'public/bower-components/',
			layout: 'byComponent'
		};

		bower.development = {
			options: { verbose: true }
		};

		bower.production = {
			options: {
				bowerOptions: { production: true }
			}
		};
	}

	return bower;
}

function gruntMinifyPolymer(options) {
	const minifyPolymer = {};

	if (options.polymerApp) {
		minifyPolymer.bower = {
			files: [
				{
					expand: true,
					cwd: 'public/bower_components/',
					src: [
						'**/*.html',
						'!**/{index,demo}.html',
						'!**/{demo,demos,docs,explainer,node_modules,test,tests}/**/*'
					],
					dest: 'build/public/bower_components/'
				}
			]
		};

		minifyPolymer.components = {
			files: [
				{
					expand: true,
					cwd: 'public/custom-components/',
					src: ['**/*.html'],
					dest: 'build/public/custom-components/'
				}
			]
		};

		minifyPolymer.views = {
			files: [
				{
					expand: true,
					cwd: 'public/',
					src: ['*.html'],
					dest: 'build/public/'
				}
			]
		};
	}

	return minifyPolymer;
}

function gruntMinifyPolymerCss(options) {
	const minifyPolymerCss = {};

	if (options.polymerApp) {
		minifyPolymerCss.bower = {
			files: [
				{
					expand: true,
					cwd: 'public/bower_components/',
					src: [
						'**/*.css',
						'!**/{index,demo}.css',
						'!**/{demo,demos,docs,explainer,node_modules,test,tests}/**/*'
					],
					dest: 'build/public/bower_components/'
				}
			]
		};
	}

	return minifyPolymerCss;
}

function gruntSass(options) {
	const sass = {};

	if (options.polymerApp) {
		sass.components = {
			files: [
				{
					expand: true,
					cwd: 'public/custom-components/',
					src: ['**/*.scss'],
					ext: '.css',
					dest: 'build/public/custom-components/'
				}
			]
		};

		sass.views = {
			files: [
				{
					expand: true,
					cwd: 'public/stylesheets/',
					src: ['*.scss'],
					ext: '.css',
					dest: 'build/public/stylesheets/'
				}
			]
		};
	}

	return sass;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Initialisation and preparation for writing
function prepareConfigs(options) {
	const grunt = {};

	// App
	grunt.aliases = gruntAliases(options);
	grunt.eslint = gruntEslint(options);

	// Node Server
	grunt.express = gruntExpress(options);
	grunt.sync = gruntSync(options);
	grunt.uglify = gruntUglify(options);
	grunt.watch = gruntWatch(options);

	// Polymer App
	grunt.bower = gruntBower(options);
	grunt.minifyPolymer = gruntMinifyPolymer(options);
	grunt.minifyPolymerCss = gruntMinifyPolymerCss(options);
	grunt.sass = gruntSass(options);

	return grunt;
}

function stringifyConfigs(configs) {
	const stringifiedConfigs = [];
	const keys = Object.keys(configs);

	keys.map((key) => {
		if (Object.keys(configs[key]).length !== 0) {
			stringifiedConfigs.push({
				file: `grunt/${key}.js`,
				content: `module.exports = ${JSON.stringify(configs[key], null, '\t')};`
			});
		}
	});

	return stringifiedConfigs;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Exports
exports.prepareConfigs = prepareConfigs;
exports.stringifyConfigs = stringifyConfigs;
<commit_msg>Fix target directory for uglify.views task.<commit_after>///////////////////////////////////////////////////////////////////////////////////////////////////
// Grunt config customisations
function gruntAliases(options) {
	const aliases = {
		lint: {
			description: 'Lint files in the project.',
			tasks: [
				'eslint'
			]
		}
	};

	if (options.nodeServer) {
		aliases.serve = {
			description: 'Start server and watch for file changes',
			tasks: [
				'express',
				'watch'
			]
		};

		aliases['build:server'] = {
			description: 'Build task for server files',
			tasks: [
				'eslint:server',
				'uglify:server',
				'sync:server'
			]
		};

		if (options.polymerApp) {
			aliases['build:bower'] = {
				description: 'Build task for bower components',
				tasks: [
					'minifyPolymer:bower',
					'minifyPolymerCSS:bower',
					'uglify:bower'
				]
			};

			aliases['build:components'] = {
				description: 'Build task for custom components',
				tasks: [
					'minifyPolymer:components',
					'sass:components',
					'uglify:components'
				]
			};

			aliases['build:views'] = {
				description: 'Build task for views',
				tasks: [
					'minifyPolymer:views',
					'sass:views',
					'uglify:views'
				]
			};
		}
	}

	return aliases;
}

function gruntEslint(options) {
	const eslint = {
		options: {
			format: 'node_modules/eslint-formatter-pretty'
		},
		project: {
			files: [
				{
					expand: true,
					src: [
						'gruntfile.js',
						'grunt/*.js'
					]
				}
			]
		}
	};

	if (options.nodeServer) {
		eslint.server = {
			files: 'server/**/*.js'
		};

		eslint.components = {
			files: ['public/custom-components/**/*.js']
		};

		eslint.views = {
			src: ['public/scripts/**/*.js']
		};
	}

	return eslint;
}

function gruntExpress(options) {
	const express = {};

	if (options.nodeServer) {
		express.all = {
			options: {
				script: 'build/server/start.js'
			}
		};
	}

	return express;
}

function gruntSync(options) {
	const sync = {};

	if (options.nodeServer) {
		sync.server = {
			files: {
				'build/.env': '.env'
			}
		};
	}

	return sync;
}

function gruntUglify(options) {
	const uglify = {};

	if (options.nodeServer) {
		uglify.server = {
			files: [
				{
					expand: true,
					cwd: 'server/',
					src: ['**/*.js'],
					dest: 'build/server/'
				}
			]
		};

		if (options.polymerApp) {
			uglify.bower = {
				files: [
					{
						expand: true,
						cwd: 'public/bower_components/',
						src: [
							'**/*.js',
							'!**/*.min.js',
							'!**/{grunt,gulp}file.js',
							'!**/{demo,demos,docs,explainer,node_modules,test,tests}/**/*'
						],
						dest: 'build/public/bower_components/'
					}
				]
			};

			uglify.components = {
				files: [
					{
						expand: true,
						cwd: 'public/custom-components/',
						src: ['**/*.js'],
						dest: 'build/public/custom-components/'
					}
				]
			};

			uglify.views = {
				files: [
					{
						expand: true,
						cwd: 'public/scripts/',
						src: ['**/*.js'],
						dest: 'build/public/scripts/'
					}
				]
			};
		}
	}

	return uglify;
}

function gruntWatch(options) {
	const watch = {};

	if (options.nodeServer) {
		watch.options = {
			spawn: false,
			interrupt: true
		};

		watch.server = {
			options: {
				reload: true
			},
			files: [
				'gruntfile.js',
				'grunt/*.js',
				'server/**/*.js'
			],
			tasks: [
				'express:stop',
				'eslint:server',
				'build:server',
				'express'
			]
		};

		if (options.polymerApp) {
			watch.bower = {
				files: ['bower.json'],
				tasks: ['build:bower']
			};

			watch.components = {
				files: ['public/custom-components/**/*'],
				tasks: [
					'eslint:components',
					'build:components'
				]
			};

			watch['sass-partials'] = {
				files: ['public/stylesheets/partials/*.scss'],
				tasks: ['sass']
			},

			watch.views = {
				files: [
					'public/*.html',
					'public/stylesheets/*.scss',
					'public/scripts/**/*.js'
				],
				tasks: [
					'eslint:views',
					'build:views'
				]
			};
		}
	}

	return watch;
}

function gruntBower(options) {
	const bower = {};

	if (options.polymerApp) {
		bower.options = {
			copy: false,
			targetDir: 'public/bower-components/',
			layout: 'byComponent'
		};

		bower.development = {
			options: { verbose: true }
		};

		bower.production = {
			options: {
				bowerOptions: { production: true }
			}
		};
	}

	return bower;
}

function gruntMinifyPolymer(options) {
	const minifyPolymer = {};

	if (options.polymerApp) {
		minifyPolymer.bower = {
			files: [
				{
					expand: true,
					cwd: 'public/bower_components/',
					src: [
						'**/*.html',
						'!**/{index,demo}.html',
						'!**/{demo,demos,docs,explainer,node_modules,test,tests}/**/*'
					],
					dest: 'build/public/bower_components/'
				}
			]
		};

		minifyPolymer.components = {
			files: [
				{
					expand: true,
					cwd: 'public/custom-components/',
					src: ['**/*.html'],
					dest: 'build/public/custom-components/'
				}
			]
		};

		minifyPolymer.views = {
			files: [
				{
					expand: true,
					cwd: 'public/',
					src: ['*.html'],
					dest: 'build/public/'
				}
			]
		};
	}

	return minifyPolymer;
}

function gruntMinifyPolymerCss(options) {
	const minifyPolymerCss = {};

	if (options.polymerApp) {
		minifyPolymerCss.bower = {
			files: [
				{
					expand: true,
					cwd: 'public/bower_components/',
					src: [
						'**/*.css',
						'!**/{index,demo}.css',
						'!**/{demo,demos,docs,explainer,node_modules,test,tests}/**/*'
					],
					dest: 'build/public/bower_components/'
				}
			]
		};
	}

	return minifyPolymerCss;
}

function gruntSass(options) {
	const sass = {};

	if (options.polymerApp) {
		sass.components = {
			files: [
				{
					expand: true,
					cwd: 'public/custom-components/',
					src: ['**/*.scss'],
					ext: '.css',
					dest: 'build/public/custom-components/'
				}
			]
		};

		sass.views = {
			files: [
				{
					expand: true,
					cwd: 'public/stylesheets/',
					src: ['*.scss'],
					ext: '.css',
					dest: 'build/public/stylesheets/'
				}
			]
		};
	}

	return sass;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Initialisation and preparation for writing
function prepareConfigs(options) {
	const grunt = {};

	// App
	grunt.aliases = gruntAliases(options);
	grunt.eslint = gruntEslint(options);

	// Node Server
	grunt.express = gruntExpress(options);
	grunt.sync = gruntSync(options);
	grunt.uglify = gruntUglify(options);
	grunt.watch = gruntWatch(options);

	// Polymer App
	grunt.bower = gruntBower(options);
	grunt.minifyPolymer = gruntMinifyPolymer(options);
	grunt.minifyPolymerCss = gruntMinifyPolymerCss(options);
	grunt.sass = gruntSass(options);

	return grunt;
}

function stringifyConfigs(configs) {
	const stringifiedConfigs = [];
	const keys = Object.keys(configs);

	keys.map((key) => {
		if (Object.keys(configs[key]).length !== 0) {
			stringifiedConfigs.push({
				file: `grunt/${key}.js`,
				content: `module.exports = ${JSON.stringify(configs[key], null, '\t')};`
			});
		}
	});

	return stringifiedConfigs;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Exports
exports.prepareConfigs = prepareConfigs;
exports.stringifyConfigs = stringifyConfigs;
<|endoftext|>