<commit_before>/**
 * GoogleChart Component Stories.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * Internal dependencies
 */
import GoogleChart from './GoogleChart';
import { WithTestRegistry } from '../../../tests/js/utils';

const Template = ( args ) => <GoogleChart { ...args } />;

const data = [
	[
		{ label: 'Day', type: 'date' },
		{ p: { html: true, role: 'tooltip' }, role: 'tooltip', type: 'string' },
		{ label: 'Impressions', type: 'number' },
		{ label: 'Previous period', type: 'number' },
	],
];

const chartOptions = {
	chart: {
		title: 'Search Traffic Summary',
	},
	curveType: 'function',
	height: 270,
	width: '100%',
	chartArea: {
		height: '80%',
		width: '100%',
		left: 60,
	},
	legend: {
		position: 'top',
		textStyle: {
			color: '#616161',
			fontSize: 12,
		},
	},
	hAxis: {
		format: 'M/d/yy',
		gridlines: {
			color: '#fff',
		},
		textStyle: {
			color: '#616161',
			fontSize: 12,
		},
		ticks: [],
	},
	vAxis: {
		direction: 1,
		gridlines: {
			color: '#eee',
		},
		minorGridlines: {
			color: '#eee',
		},
		textStyle: {
			color: '#616161',
			fontSize: 12,
		},
		titleTextStyle: {
			color: '#616161',
			fontSize: 12,
			italic: false,
		},
		viewWindow: {
			min: 0,
		},
	},
	series: {
		0: {
			color: '#4285f4',
			targetAxisIndex: 0,
		},
		1: {
			color: '#4285f4',
			targetAxisIndex: 0,
			lineDashStyle: [ 3, 3 ],
			lineWidth: 1,
		},
	},
	tooltip: {
		isHtml: true, // eslint-disable-line sitekit/acronym-case
		trigger: 'both',
	},
	focusTarget: 'category',
	crosshair: {
		color: 'gray',
		opacity: 0.1,
		orientation: 'vertical',
		trigger: 'both',
	},
};

export const GatheringDataChart = Template.bind( {} );
GatheringDataChart.storyName = 'Gathering Data';
GatheringDataChart.args = {
	chartType: 'LineChart',
	data,
	options: chartOptions,
	gatheringData: true,
};
GatheringDataChart.parameters = {
	features: [ 'zeroDataStates' ],
};

export default {
	title: 'Components/GoogleChart',
	component: GoogleChart,
	decorators: [
		( Story, { parameters } ) => {
			return (
				<WithTestRegistry features={ parameters.features || [] }>
					<Story />
				</WithTestRegistry>
			);
		},
	],
};
<commit_msg>Remove unnecessary data for gathering data chart story.<commit_after>/**
 * GoogleChart Component Stories.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * Internal dependencies
 */
import GoogleChart from './GoogleChart';
import { WithTestRegistry } from '../../../tests/js/utils';

const Template = ( args ) => <GoogleChart { ...args } />;

const data = [
	[
		{ label: 'Day', type: 'date' },
		{ p: { html: true, role: 'tooltip' }, role: 'tooltip', type: 'string' },
		{ label: 'Impressions', type: 'number' },
		{ label: 'Previous period', type: 'number' },
	],
];

const chartOptions = {
	chart: {
		title: 'Search Traffic Summary',
	},
	curveType: 'function',
	height: 270,
	width: '100%',
	chartArea: {
		height: '80%',
		width: '100%',
		left: 60,
	},
	legend: {
		position: 'top',
		textStyle: {
			color: '#616161',
			fontSize: 12,
		},
	},
	hAxis: {
		format: 'M/d/yy',
		gridlines: {
			color: '#fff',
		},
		textStyle: {
			color: '#616161',
			fontSize: 12,
		},
		ticks: [],
	},
	vAxis: {
		direction: 1,
		gridlines: {
			color: '#eee',
		},
		minorGridlines: {
			color: '#eee',
		},
		textStyle: {
			color: '#616161',
			fontSize: 12,
		},
		titleTextStyle: {
			color: '#616161',
			fontSize: 12,
			italic: false,
		},
		viewWindow: {
			min: 0,
		},
	},
	series: {
		0: {
			color: '#4285f4',
			targetAxisIndex: 0,
		},
		1: {
			color: '#4285f4',
			targetAxisIndex: 0,
			lineDashStyle: [ 3, 3 ],
			lineWidth: 1,
		},
	},
};

export const GatheringDataLineChart = Template.bind( {} );
GatheringDataLineChart.storyName = 'Gathering Data - Line';
GatheringDataLineChart.args = {
	chartType: 'LineChart',
	data,
	options: chartOptions,
	gatheringData: true,
};
GatheringDataLineChart.parameters = {
	features: [ 'zeroDataStates' ],
};

export default {
	title: 'Components/GoogleChart',
	component: GoogleChart,
	decorators: [
		( Story, { parameters } ) => {
			return (
				<WithTestRegistry features={ parameters.features || [] }>
					<Story />
				</WithTestRegistry>
			);
		},
	],
};
<|endoftext|>


<commit_before>// This file containts lxchat bussines logic
//Self-Invoking Anonymous Function Notation
// !function(){}(); // easy to read, the result is unimportant.
// (function(){})(); // like above but more parens.
// (function(){}()); // Douglas Crockford's style when you need function results.
// Further reading: http://javascript.crockford.com/code.html then search for invoked immediately

// function definitions section
window.lxchatSetData = function(newMessage) {
    var currentUser = $(".user_label:eq(0)").text().trim();

    /*Today's date splitted*/
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1;
    var curr_year = d.getFullYear();

    if (newMessage != '') {
        var newMessage = "[" + "%2B" + "] " + " [" + curr_date + " - " + curr_month + " - " + curr_year + "]  " + currentUser + " : " + newMessage + " [" + "%2B" + "]\n\n";
    }

    var currentForm = document.forms['DetailView'];
    if (!currentForm) {
        currentForm = document.forms['EditView'];
    }
    var record_id = currentForm.record.value;
    var module_name = currentForm.module.value;

    var data = "method=" + "lxChat" + "&chat_c=" + newMessage + "&record_id=" + record_id + "&module=" + module_name + "&array_position=" + lxchat_array_position + "&save=" + 1;
    $.ajax({
        // beforeSend is a pre-request callback function that can be used to modify the jqXHR.
        beforeSend: function(jqXHR, settings) {
            console.groupCollapsed("LxChat Logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatSetData()', 'ajax beforeSend');
            console.log("*** start ***");
            console.log("beforeSend callback:", settings.url);
            console.groupEnd();
        },
        url: 'lxajax.php',
        type: 'POST',
        data: data,
        // success is a function to be called if the request succeeds.
        success: function(data, status, jqXHR) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatSetData()', 'ajax success');
            console.log("success callback:", status);
            console.log("data:", data);
            $("#lxchatnewmsg").val('');
            lxchatGetData();
            console.groupEnd();
        },
        // error is a function to be called if the request fails.
        error: function(jqXHR, status, error) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatSetData()', 'ajax error');
            console.log("error callback:", status);
            console.log("Function lxchatSetData error:", error);
            console.groupEnd();
        }, // end error
        // complete is a function to be called when the request finishes (after success and error callbacks are executed).
        // complete: function(jqXHR, status) {
        // },
        datatype: "text"
    })
}

window.lxchatGetData = function() {
    var currentForm = document.forms['DetailView'];
    if (!currentForm) {
        currentForm = document.forms['EditView'];
    }
    var record_id = currentForm.record.value;
    var module_name = currentForm.module.value;
    var data = "method=" + "lxChat" + "&record_id=" + record_id + "&module=" + module_name + "&array_position=" + lxchat_array_position;
    $.ajax({
        // beforeSend is a pre-request callback function that can be used to modify the jqXHR.
        beforeSend: function(jqXHR, settings) {
            console.groupCollapsed("LxChat Logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatGetData()', 'ajax beforeSend');
            console.log("*** start ***");
            console.log("beforeSend callback:", settings.url);
            console.groupEnd();
        },
        url: 'lxajax.php',
        type: 'GET',
        data: data,
        // success is a function to be called if the request succeeds.
        success: function(data, status, jqXHR) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatGetData()', 'ajax success');
            console.log("success callback:", status);
            console.log("data:", data);
            $("textarea#" + lxchatfield).val(data);
            $('#lxchatcontent').val(data).trigger('autosize');
            $("#lxchatSave").removeAttr("disabled");
            console.groupEnd();
        },
        // error is a function to be called if the request fails.
        error: function(jqXHR, status, error) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatGetData()', 'ajax error');
            console.log("error callback:", status);
            console.log("Function lxchatGetData error:", error);
            console.groupEnd();
        }, // end error
        // complete is a function to be called when the request finishes (after success and error callbacks are executed).
        complete: function(jqXHR, status) {
            var textarea = document.getElementById('lxchatcontent');
            textarea.scrollTop = textarea.scrollHeight;
        },
        datatype: "text"
    })
}

window.lxchatRender = function(lxchatfield) {
    if (!$("#lxchat").length) {
        var currentUser = $(".user_label:eq(0)").text().trim();
        //Current lxchatfield text
        lxchatfieldtext = $('#' + lxchatfield).text();
        //Current crm field must be hide
        $('#' + lxchatfield).hide();
        //lxchat div added
        $('
CHAT
').insertAfter('#' + lxchatfield);
        $('#lxchat').attr('style', 'position:relative'); //aca no estaba esta línea
        $('#lxchat').attr('style', 'width: 400px; border: 3px solid #6495ED;border-radius:5px;text-align:left;background-color: #BCD2EE;');
        $('#lxchat').append('<textarea id="lxchatcontent" cols="80" rows="6" readonly="readonly" style="width: 100%; overflow: scroll; background-color: #F6FAFD;">' + lxchatfieldtext + '</textarea>');
        $('#lxchatcontent').attr('style', 'width: 100%; height: 200px;background-color: #F6FAFD;');
        //Textarea for new messages added
        $('
<textarea id="lxchatnewmsg" tabindex="0" title="" cols="80" rows="6" style="width: 400px;height: 90px;background-color: #F6FAFD;"></textarea>').insertAfter('#lxchat');
        //Save new messages button added
        $('
<input id="lxchatSave" type="button" value="enviar mensaje" />').insertAfter('#lxchatnewmsg');
        $(document).on("click", "#lxchatSave", function(event) {
            $("#lxchatSave").attr("disabled", true);
            lxchatSetData($("#lxchatnewmsg").val());
        });
    }
}

window.lxchatFindFieldToRender = function() {
    var currentForm = document.forms['DetailView'];
    if (!currentForm) {
        currentForm = document.forms['EditView'];
    }
    var record_id = currentForm.record.value;
    var module_name = currentForm.module.value;
    var lxajaxdata = "method=" +
    "lxChatConfigOverrideField";
    $.ajax({
        // beforeSend is a pre-request callback function that can be used to modify the jqXHR.
        beforeSend: function(jqXHR, settings) {
            console.groupCollapsed("LxChat Logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatFindFieldToRender()', 'ajax beforeSend');
            console.log("*** start ***");
            console.log("beforeSend callback:", settings.url);
            console.groupEnd();
        },
        url: 'lxajax.php',
        type: 'GET',
        data: lxajaxdata,
        // success is a function to be called if the request succeeds.
        success: function(data, status, jqXHR) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatFindFieldToRender()', 'ajax success');
            console.log("success callback:", status);
            console.log("data:", data);
            fieldsArray = JSON.parse(data);
            for (var i = 0; i < fieldsArray.length; i++) {
                if ($(document).find("#" + fieldsArray[i]).length) {
                    if (!record_id) {
                        console.log("lxchat doesn't render when record_id isn't present");
                        lxShowCRMfield(fieldsArray[i]);
                    } else {
                        lxchatRender(fieldsArray[i]);
                        lxchatfield = fieldsArray[i];
                        lxchat_array_position = i;
                    }
                }
            }
        },
        // error is a function to be called if the request fails.
        error: function(jqXHR, status, error) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatFindFieldToRender()', 'ajax error');
            console.log("error callback:", status);
            console.log("Function lxchatFindFieldToRender error:", error);
            console.groupEnd();
        }, // end error
        // complete is a function to be called when the request finishes (after success and error callbacks are executed).
        complete: function(jqXHR, status) {
            var textarea = document.getElementById('lxchatcontent');
            if (textarea) {
                textarea.scrollTop = textarea.scrollHeight;
            }
        },
        datatype: "text"
    })
    // }
}

// Observers definitions
!function() {
    if ($("#edit_button").length || $("#SAVE").length || $("#SAVE_HEADER").length) {
        // now it ensures that lxchat isn't already present
        if (!$("#lxchat").length) {
            lxchatFindFieldToRender();
        }
    }
    // On other modules
    // create an observer instance
    // https://developer.mozilla.org/en/docs/Web/API/MutationObserver
    var observer = new MutationObserver(function(mutations) {

        // If a specific mutation is need iterate over the array
        // mutations.forEach(function(mutation) {
        // There are 3 types attributes, childList and characterData
        // if (mutation.type == "attributes") {
        // if (mutation.target.nodeName == "DIV" && mutation.target.id == 'tabcontent0') {
        /*when found do your code*/
        // console.log(mutation);
        //}
        //}
        // });

        // If any change will trigger the effect check only if the array exists
        // if (mutations) { /*your code*/ }
        if (mutations) {
            $(document).ready(function() {
                var lxchatfield = '';
                var lxchat_array_position = '';
                // if #edit_button exists is a detailview, if not, then if a #SAVE or #SAVE_HEADER button exists is a editview
                if ($("#edit_button").length || $("#SAVE").length || $("#SAVE_HEADER").length) {
                    // now it ensures that lxchat isn't already present
                    if (!$("#lxchat").length) {
                        lxchatFindFieldToRender();
                    }
                }
            });
            // if needed only once, you can stop observing with observer.disconnect();
            // observer.disconnect();
        }
    });
    // Observer target
    var target = document.querySelector('#content');
    // configuration of the observer:
    // NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.
    var config = {
        attributes: true,
        childList: true,
        characterData: true,
        subtree: true
    };
    // pass in the target node, as well as the observer options
    observer.observe(target, config);
    // end observer
}();

// eof
<commit_msg>refactor: placeholder added<commit_after>// This file containts lxchat bussines logic
//Self-Invoking Anonymous Function Notation
// !function(){}(); // easy to read, the result is unimportant.
// (function(){})(); // like above but more parens.
// (function(){}()); // Douglas Crockford's style when you need function results.
// Further reading: http://javascript.crockford.com/code.html then search for invoked immediately

// function definitions section
window.lxchatSetData = function(newMessage) {
    var currentUser = $(".user_label:eq(0)").text().trim();

    /*Today's date splitted*/
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1;
    var curr_year = d.getFullYear();

    if (newMessage != '') {
        var newMessage = "[" + "%2B" + "] " + " [" + curr_date + " - " + curr_month + " - " + curr_year + "]  " + currentUser + " : " + newMessage + " [" + "%2B" + "]\n\n";
    }

    var currentForm = document.forms['DetailView'];
    if (!currentForm) {
        currentForm = document.forms['EditView'];
    }
    var record_id = currentForm.record.value;
    var module_name = currentForm.module.value;

    var data = "method=" + "lxChat" + "&chat_c=" + newMessage + "&record_id=" + record_id + "&module=" + module_name + "&array_position=" + lxchat_array_position + "&save=" + 1;
    $.ajax({
        // beforeSend is a pre-request callback function that can be used to modify the jqXHR.
        beforeSend: function(jqXHR, settings) {
            console.groupCollapsed("LxChat Logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatSetData()', 'ajax beforeSend');
            console.log("*** start ***");
            console.log("beforeSend callback:", settings.url);
            console.groupEnd();
        },
        url: 'lxajax.php',
        type: 'POST',
        data: data,
        // success is a function to be called if the request succeeds.
        success: function(data, status, jqXHR) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatSetData()', 'ajax success');
            console.log("success callback:", status);
            console.log("data:", data);
            $("#lxchatnewmsg").val('');
            lxchatGetData();
            console.groupEnd();
        },
        // error is a function to be called if the request fails.
        error: function(jqXHR, status, error) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatSetData()', 'ajax error');
            console.log("error callback:", status);
            console.log("Function lxchatSetData error:", error);
            console.groupEnd();
        }, // end error
        // complete is a function to be called when the request finishes (after success and error callbacks are executed).
        // complete: function(jqXHR, status) {
        // },
        datatype: "text"
    })
}

window.lxchatGetData = function() {
    var currentForm = document.forms['DetailView'];
    if (!currentForm) {
        currentForm = document.forms['EditView'];
    }
    var record_id = currentForm.record.value;
    var module_name = currentForm.module.value;
    var data = "method=" + "lxChat" + "&record_id=" + record_id + "&module=" + module_name + "&array_position=" + lxchat_array_position;
    $.ajax({
        // beforeSend is a pre-request callback function that can be used to modify the jqXHR.
        beforeSend: function(jqXHR, settings) {
            console.groupCollapsed("LxChat Logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatGetData()', 'ajax beforeSend');
            console.log("*** start ***");
            console.log("beforeSend callback:", settings.url);
            console.groupEnd();
        },
        url: 'lxajax.php',
        type: 'GET',
        data: data,
        // success is a function to be called if the request succeeds.
        success: function(data, status, jqXHR) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatGetData()', 'ajax success');
            console.log("success callback:", status);
            console.log("data:", data);
            $("textarea#" + lxchatfield).val(data);
            $('#lxchatcontent').val(data).trigger('autosize');
            $("#lxchatSave").removeAttr("disabled");
            console.groupEnd();
        },
        // error is a function to be called if the request fails.
        error: function(jqXHR, status, error) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatGetData()', 'ajax error');
            console.log("error callback:", status);
            console.log("Function lxchatGetData error:", error);
            console.groupEnd();
        }, // end error
        // complete is a function to be called when the request finishes (after success and error callbacks are executed).
        complete: function(jqXHR, status) {
            var textarea = document.getElementById('lxchatcontent');
            textarea.scrollTop = textarea.scrollHeight;
        },
        datatype: "text"
    })
}

window.lxchatRender = function(lxchatfield) {
    if (!$("#lxchat").length) {
        var currentUser = $(".user_label:eq(0)").text().trim();
        //Current lxchatfield text
        lxchatfieldtext = $('#' + lxchatfield).text();
        //Current crm field must be hide
        $('#' + lxchatfield).hide();
        //lxchat div added
        $('
CHAT
').insertAfter('#' + lxchatfield);
        $('#lxchat').attr('style', 'position:relative'); //aca no estaba esta línea
        $('#lxchat').attr('style', 'width: 400px; border: 3px solid #6495ED;border-radius:5px;text-align:left;background-color: #BCD2EE;');
        $('#lxchat').append('<textarea id="lxchatcontent" cols="80" rows="6" readonly="readonly" style="width: 100%; overflow: scroll; background-color: #F6FAFD;">' + lxchatfieldtext + '</textarea>');
        $('#lxchatcontent').attr('style', 'width: 100%; height: 200px;background-color: #F6FAFD;');
        //Textarea for new messages added
        $('
<textarea id="lxchatnewmsg" placeholder="¿Quieres compartir alguna novedad, '+currentUser+'?" tabindex="0" title="" cols="80" rows="6" style="width: 400px;height: 90px;background-color: #F6FAFD;"></textarea>').insertAfter('#lxchat');
        //Save new messages button added
        $('
<input id="lxchatSave" type="button" value="enviar mensaje" />').insertAfter('#lxchatnewmsg');
        $(document).on("click", "#lxchatSave", function(event) {
            $("#lxchatSave").attr("disabled", true);
            lxchatSetData($("#lxchatnewmsg").val());
        });
    }
}

window.lxchatFindFieldToRender = function() {
    var currentForm = document.forms['DetailView'];
    if (!currentForm) {
        currentForm = document.forms['EditView'];
    }
    var record_id = currentForm.record.value;
    var module_name = currentForm.module.value;
    var lxajaxdata = "method=" +
    "lxChatConfigOverrideField";
    $.ajax({
        // beforeSend is a pre-request callback function that can be used to modify the jqXHR.
        beforeSend: function(jqXHR, settings) {
            console.groupCollapsed("LxChat Logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatFindFieldToRender()', 'ajax beforeSend');
            console.log("*** start ***");
            console.log("beforeSend callback:", settings.url);
            console.groupEnd();
        },
        url: 'lxajax.php',
        type: 'GET',
        data: lxajaxdata,
        // success is a function to be called if the request succeeds.
        success: function(data, status, jqXHR) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatFindFieldToRender()', 'ajax success');
            console.log("success callback:", status);
            console.log("data:", data);
            fieldsArray = JSON.parse(data);
            for (var i = 0; i < fieldsArray.length; i++) {
                if ($(document).find("#" + fieldsArray[i]).length) {
                    if (!record_id) {
                        console.log("lxchat doesn't render when record_id isn't present");
                        lxShowCRMfield(fieldsArray[i]);
                    } else {
                        lxchatRender(fieldsArray[i]);
                        lxchatfield = fieldsArray[i];
                        lxchat_array_position = i;
                    }
                }
            }
        },
        // error is a function to be called if the request fails.
        error: function(jqXHR, status, error) {
            console.groupCollapsed("LxChat logic '%s' '%s' '%s' '%s'", module_name, 'lx-chat.js', 'lxchatFindFieldToRender()', 'ajax error');
            console.log("error callback:", status);
            console.log("Function lxchatFindFieldToRender error:", error);
            console.groupEnd();
        }, // end error
        // complete is a function to be called when the request finishes (after success and error callbacks are executed).
        complete: function(jqXHR, status) {
            var textarea = document.getElementById('lxchatcontent');
            if (textarea) {
                textarea.scrollTop = textarea.scrollHeight;
            }
        },
        datatype: "text"
    })
    // }
}

// Observers definitions
!function() {
    if ($("#edit_button").length || $("#SAVE").length || $("#SAVE_HEADER").length) {
        // now it ensures that lxchat isn't already present
        if (!$("#lxchat").length) {
            lxchatFindFieldToRender();
        }
    }
    // On other modules
    // create an observer instance
    // https://developer.mozilla.org/en/docs/Web/API/MutationObserver
    var observer = new MutationObserver(function(mutations) {

        // If a specific mutation is need iterate over the array
        // mutations.forEach(function(mutation) {
        // There are 3 types attributes, childList and characterData
        // if (mutation.type == "attributes") {
        // if (mutation.target.nodeName == "DIV" && mutation.target.id == 'tabcontent0') {
        /*when found do your code*/
        // console.log(mutation);
        //}
        //}
        // });

        // If any change will trigger the effect check only if the array exists
        // if (mutations) { /*your code*/ }
        if (mutations) {
            $(document).ready(function() {
                var lxchatfield = '';
                var lxchat_array_position = '';
                // if #edit_button exists is a detailview, if not, then if a #SAVE or #SAVE_HEADER button exists is a editview
                if ($("#edit_button").length || $("#SAVE").length || $("#SAVE_HEADER").length) {
                    // now it ensures that lxchat isn't already present
                    if (!$("#lxchat").length) {
                        lxchatFindFieldToRender();
                    }
                }
            });
            // if needed only once, you can stop observing with observer.disconnect();
            // observer.disconnect();
        }
    });
    // Observer target
    var target = document.querySelector('#content');
    // configuration of the observer:
    // NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.
    var config = {
        attributes: true,
        childList: true,
        characterData: true,
        subtree: true
    };
    // pass in the target node, as well as the observer options
    observer.observe(target, config);
    // end observer
}();

// eof
<|endoftext|>


<commit_before>var loadImage = require('./loadImage')
var loadBinary = require('./loadBinary')
var loadText = require('./loadText')
var loadJSON = require('./loadJSON')

/**
 * Load provided resources
 * @param   {Object} resources - map of resources, see example
 * @param   {Function} callback function(err, resources), see example
 * @returns {Object}   - with same properties are resource list but resolved to the actual data
 *
 * @example
 * var resources = {
 *   img     : { image: __dirname + '/tex.jpg'},
 *   hdrImg  : { binary: __dirname + '/tex.hdr'}
 *   data    : { json: __dirname + '/data.json'},
 *   hello   : { text: __dirname + '/hello.txt'}
 * }
 * load(resources, function(err, res) {
 *   res.img    //{Image} in a Browser or {SkCanvas} in Plask
 *   res.hdrImg //{ArrayBuffer}
 *   res.data   //{JSON}
 *   res.hello  //{String}
 * })
 */
function load (resources, callback) {
  var results = {}
  var errors = {}
  var hadErrors = false

  // TODO: use `async` module instead?
  var loadedResources = 0
  var resourceNames = Object.keys(resources)
  var numResources = resourceNames.length

  function onFinish () {
    if (hadErrors) {
      callback(errors, null)
    } else {
      callback(null, results)
    }
  }

  resourceNames.forEach(function (name) {
    function onLoaded (err, data) {
      if (err) {
        hadErrors = true
        errors[name] = err
      } else {
        results[name] = data
      }

      if (++loadedResources === numResources) {
        onFinish()
      }
    }

    var res = resources[name]
    if (res.image) {
      loadImage(res.image, onLoaded)
    } else if (res.text) {
      loadText(res.text, onLoaded)
    } else if (res.json) {
      loadJSON(res.json, onLoaded)
    } else if (res.binary) {
      loadBinary(res.binary, onLoaded)
    } else {
      onLoaded('pex-io/load unknown resource type ' + Object.keys(res), null)
    }
  })

  if (resourceNames.length === 0) {
    onFinish()
  }
}

module.exports = load
<commit_msg>Add exception handling to load<commit_after>var loadImage = require('./loadImage')
var loadBinary = require('./loadBinary')
var loadText = require('./loadText')
var loadJSON = require('./loadJSON')

/**
 * Load provided resources
 * @param   {Object} resources - map of resources, see example
 * @param   {Function} callback function(err, resources), see example
 * @returns {Object}   - with same properties are resource list but resolved to the actual data
 *
 * @example
 * var resources = {
 *   img     : { image: __dirname + '/tex.jpg'},
 *   hdrImg  : { binary: __dirname + '/tex.hdr'}
 *   data    : { json: __dirname + '/data.json'},
 *   hello   : { text: __dirname + '/hello.txt'}
 * }
 * load(resources, function(err, res) {
 *   res.img    //{Image} in a Browser or {SkCanvas} in Plask
 *   res.hdrImg //{ArrayBuffer}
 *   res.data   //{JSON}
 *   res.hello  //{String}
 * })
 */
function load (resources, callback) {
  var results = {}
  var errors = {}
  var hadErrors = false

  // TODO: use `async` module instead?
  var loadedResources = 0
  var resourceNames = Object.keys(resources)
  var numResources = resourceNames.length

  function onFinish () {
    try {
      if (hadErrors) {
        callback(errors, null)
      } else {
        callback(null, results)
      }
    } catch (e) {
      console.log(e)
      console.log(e.stack)
    }
  }

  resourceNames.forEach(function (name) {
    function onLoaded (err, data) {
      if (err) {
        hadErrors = true
        errors[name] = err
      } else {
        results[name] = data
      }

      if (++loadedResources === numResources) {
        onFinish()
      }
    }

    var res = resources[name]
    if (res.image) {
      loadImage(res.image, onLoaded)
    } else if (res.text) {
      loadText(res.text, onLoaded)
    } else if (res.json) {
      loadJSON(res.json, onLoaded)
    } else if (res.binary) {
      loadBinary(res.binary, onLoaded)
    } else {
      onLoaded('pex-io/load unknown resource type ' + Object.keys(res), null)
    }
  })

  if (resourceNames.length === 0) {
    onFinish()
  }
}

module.exports = load
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   xTuple Postbooks - Business Management System Framework
// Copyright: ©2012 OpenMFG LLC, d/b/a xTuple
// ==========================================================================

/*globals XM */

/**
  @scope XM.Taxable
  @mixin

*/
XM.Taxable = {
  /** @scope XM.Taxable */

  /**
    A common helper function that will accept an array of tax data and
    distill it into a tax detail array and total, the results of which
    will be set on this object.

    The each of the array contents passed must include a taxCode and tax
    property.

    @param {Array} tax data to parse
    @param {String} tax detail property name to set
    @param {String} tax total property name to set
  */
  setTaxDetail: function(value, taxDetailProperty, taxTotalProperty) {
    var store = this.get('store'),
        taxTotal = 0; taxDetail = [],
        isSCobj = SC.kindOf(value, SC.Object);
    for(var i = 0; i < value.get('length'); i++) {
      var storeKey, taxCode, detail,
          item = isSCobj ? value.objectAt(i) : value[i],
          tax = isSCobj ? item.get('tax') : item.tax;
      if (isSCobj) taxCode = item.get('taxCode')
      else {
        storeKey = store.loadRecord(XM.TaxCode, item.taxCode);
        taxCode = store.materializeRecord(storeKey);
      }
      taxTotal = taxTotal + tax,
      detail = SC.Object.create({
        taxCode: taxCode,
        tax: SC.Math.round(tax, XT.MONEY_SCALE)
      });
      taxDetail.push(detail);
    }
    this.setIfChanged(taxDetailProperty, taxDetail);
    this.setIfChanged(taxTotalProperty, SC.Math.round(taxTotal, XT.SALES_PRICE_SCALE));
  }

};
<commit_msg>still tweaking rounding issues.<commit_after>// ==========================================================================
// Project:   xTuple Postbooks - Business Management System Framework
// Copyright: ©2012 OpenMFG LLC, d/b/a xTuple
// ==========================================================================

/*globals XM */

/**
  @scope XM.Taxable
  @mixin

*/
XM.Taxable = {
  /** @scope XM.Taxable */

  /**
    A common helper function that will accept an array of tax data and
    distill it into a tax detail array and total, the results of which
    will be set on this object.

    The each of the array contents passed must include a taxCode and tax
    property.

    @param {Array} tax data to parse
    @param {String} tax detail property name to set
    @param {String} tax total property name to set
  */
  setTaxDetail: function(value, taxDetailProperty, taxTotalProperty) {
    var store = this.get('store'),
        taxTotal = 0; taxDetail = [],
        isSCobj = SC.kindOf(value, SC.Object);
    for(var i = 0; i < value.get('length'); i++) {
      var storeKey, taxCode, detail,
          item = isSCobj ? value.objectAt(i) : value[i],
          tax = isSCobj ? item.get('tax') : item.tax;
      if (isSCobj) taxCode = item.get('taxCode')
      else {
        storeKey = store.loadRecord(XM.TaxCode, item.taxCode);
        taxCode = store.materializeRecord(storeKey);
      }
      taxTotal = taxTotal + tax,
      detail = SC.Object.create({
        taxCode: taxCode,
        tax: SC.Math.round(tax, XT.SALES_PRICE_SCALE)
      });
      taxDetail.push(detail);
    }
    this.setIfChanged(taxDetailProperty, taxDetail);
    this.setIfChanged(taxTotalProperty, SC.Math.round(taxTotal, XT.SALES_PRICE_SCALE));
  }

};
<|endoftext|>


<commit_before>function addEvent(elm, evType, fn, useCapture) {
  if (elm.addEventListener) {
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent) {
    var r = elm.attachEvent('on' + evType, fn);
    return r;
  } else {
    elm['on' + evType] = fn;
  }
}

function init() {

  var rootul = document.getElementById('menuroot');
  var lis = rootul.getElementsByTagName('li');
    for (var i = 0; i < lis.length; i++) {
      var node = lis[i];

      if (node.className == 'toplist' &&
      		node.nodeName.toLowerCase() == 'li' &&
         	node.getElementsByTagName('ul').length > 0) {
         	var cname = node.className;
        addEvent(node, 'click', getClickFor(node), false);
        node.getElementsByTagName('a')[0].className += ' subheader';
      }
    }

}

/*
function init() {
  var uls = document.getElementsByTagName('ul');
  for (var u = 0; u < uls.length; u++) {
    if (uls[u].className.search(/\bslidingmenu\b/) == -1) continue;
    var lis = uls[u].getElementsByTagName('li');
    for (var i = 0; i < lis.length; i++) {
      var node = lis[i];
      if (node.nodeName.toLowerCase() == 'li' &&
          node.getElementsByTagName('ul').length > 0) {
        addEvent(node, 'click', getClickFor(node), false);
        node.getElementsByTagName('a')[0].className += ' subheader';
      }
    }
  }
}
*/

addEvent(window, 'load', init, false);

function getClickFor(node) {
  return function(e) { mclick(e, node); };
}

function mclick(e, targetElement) {
  var el = window.event ? targetElement : e ? e.currentTarget : null;
  if (!el) return;

  for (var i = 0; i < el.childNodes.length; i++) {
    var cnode = el.childNodes[i];

    var parentUl = el.parentNode;
    if(cnode.nodeName.toLowerCase() == 'ul' ) {
        if( cnode.style.display != 'block' ) {
  			closeAllSideMenu();
     		cnode.style.display = 'block';
     		var uls = cnode.getElementsByTagName('ul');
  			for (var u = 0; u < uls.length; u++) {
     			uls[u].style.display = 'block';
     		}

    	} else if(parentUl.nodeName.toLowerCase() == 'ul'
    		/* && parentUl.className == 'slidingmenu' */ ) {

    		cnode.style.display = 'none';
    		var uls = cnode.getElementsByTagName('ul');
     		for (var j = 0; j < uls.length; j++) {
     			uls[j].style.display = 'none';
     		}
    	}
    }
    if (window.event) {
      window.event.cancelBubble = true;
    }
    if (e && e.stopPropagation && e.preventDefault) {
      e.stopPropagation();
    }
  }
}

function closeAllSideMenu ()
{
	var ulroot = document.getElementById('menuroot');
	var menuuls = ulroot.getElementsByTagName('ul');
	for(var k=0; k<menuuls.length; k++) {
		menuuls[k].style.display = 'none';
	}
}<commit_msg>modified event handler<commit_after>function addEvent(elm, evType, fn, useCapture) {
  if (elm.addEventListener) {
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent) {
    var r = elm.attachEvent('on' + evType, fn);
    return r;
  } else {
    elm['on' + evType] = fn;
  }
}

function init() {
  var rootul = document.getElementById('menuroot');
  var lis = rootul.getElementsByTagName('li');
    for (var i = 0; i < lis.length; i++) {
      var node = lis[i];

      if(node.nodeName.toLowerCase() == 'li' &&
         node.getElementsByTagName('ul').length > 0) {

         	if(node.className == 'toplist') {
        		addEvent(node, 'click', getClickFor(node), false);
        		node.getElementsByTagName('a')[0].className += ' subheader';
        	} else {
        		addEvent(node, 'click', cancelBubling, false);
        	}
      }
   }
}

addEvent(window, 'load', init, false);

function getClickFor(node) {
  return function(e) { mclick(e, node); };
}

function mclick(e, targetElement) {
  var el = window.event ? targetElement : e ? e.currentTarget : null;
  if (!el) return;

  for (var i = 0; i < el.childNodes.length; i++) {
    var cnode = el.childNodes[i];

    var parentUl = el.parentNode;
    if(cnode.nodeName.toLowerCase() == 'ul' ) {
        if( cnode.style.display != 'block' ) {
  			closeAllSideMenu();
     		cnode.style.display = 'block';
     		var uls = cnode.getElementsByTagName('ul');
  			for (var u = 0; u < uls.length; u++) {
     			uls[u].style.display = 'block';
     		}

    	} else if(parentUl.nodeName.toLowerCase() == 'ul'
    		/* && parentUl.className == 'slidingmenu' */ ) {

    		cnode.style.display = 'none';
    		var uls = cnode.getElementsByTagName('ul');
     		for (var j = 0; j < uls.length; j++) {
     			uls[j].style.display = 'none';
     		}
    	}
    }
    if (window.event) {
      window.event.cancelBubble = true;
    }
    if (e && e.stopPropagation && e.preventDefault) {
      e.stopPropagation();
    }
  }
}

function closeAllSideMenu ()
{
	var ulroot = document.getElementById('menuroot');
	var menuuls = ulroot.getElementsByTagName('ul');
	for(var k=0; k<menuuls.length; k++) {
		menuuls[k].style.display = 'none';
	}
}

function cancelBubling(e) {
	if (window.event) {
      window.event.cancelBubble = true;
    }
    if (e && e.stopPropagation && e.preventDefault) {
      e.stopPropagation();
    }
}<|endoftext|>


<commit_before>import {
    event as d3_event,
    select as d3_select
} from 'd3-selection';

import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js';

import * as sexagesimal from '@mapbox/sexagesimal';
import { t } from '../util/locale';
import { geoExtent, geoChooseEdge } from '../geo';
import { modeSelect } from '../modes';
import { osmEntity } from '../osm';
import { svgIcon } from '../svg';
import { services } from '../services';
import { uiCmd } from './cmd';

import {
    utilDisplayName,
    utilDisplayType,
    utilEntityOrMemberSelector,
    utilNoAuto
} from '../util';

export function uiFeatureList(context) {
    var keybinding = d3_keybinding('feature-list');
    var _geocodeResults;

    function featureList(selection) {
        var header = selection
            .append('div')
            .attr('class', 'header fillL cf');

        header
            .append('h3')
            .text(t('inspector.feature_list'));

        var searchWrap = selection
            .append('div')
            .attr('class', 'search-header');

        var search = searchWrap
            .append('input')
            .attr('placeholder', t('inspector.search'))
            .attr('type', 'search')
            .call(utilNoAuto)
            .on('keypress', keypress)
            .on('keydown', keydown)
            .on('input', inputevent);

        searchWrap
            .call(svgIcon('#icon-search', 'pre-text'));

        var listWrap = selection
            .append('div')
            .attr('class', 'inspector-body');

        var list = listWrap
            .append('div')
            .attr('class', 'feature-list cf');

        context
            .on('exit.feature-list', clearSearch);
        context.map()
            .on('drawn.feature-list', mapDrawn);

        keybinding
            .on(uiCmd('⌘F'), focusSearch);

        d3_select(document)
            .call(keybinding);

        function focusSearch() {
            var mode = context.mode() && context.mode().id;
            if (mode !== 'browse') return;

            d3_event.preventDefault();
            search.node().focus();
        }

        function keydown() {
            if (d3_event.keyCode === 27) {  // escape
                search.node().blur();
            }
        }

        function keypress() {
            var q = search.property('value'),
                items = list.selectAll('.feature-list-item');
            if (d3_event.keyCode === 13 && q.length && items.size()) {  // return
                click(items.datum());
            }
        }

        function inputevent() {
            _geocodeResults = undefined;
            drawList();
        }

        function clearSearch() {
            search.property('value', '');
            drawList();
        }

        function mapDrawn(e) {
            if (e.full) {
                drawList();
            }
        }

        function features() {
            var entities = {},
                result = [],
                graph = context.graph(),
                q = search.property('value').toLowerCase();

            if (!q) return result;

            var idMatch = q.match(/^([nwr])([0-9]+)$/);

            if (idMatch) {
                result.push({
                    id: idMatch[0],
                    geometry: idMatch[1] === 'n' ? 'point' : idMatch[1] === 'w' ? 'line' : 'relation',
                    type: idMatch[1] === 'n' ? t('inspector.node') : idMatch[1] === 'w' ? t('inspector.way') : t('inspector.relation'),
                    name: idMatch[2]
                });
            }

            var locationMatch = sexagesimal.pair(q.toUpperCase()) || q.match(/^(-?\d+\.?\d*)\s+(-?\d+\.?\d*)$/);

            if (locationMatch) {
                var loc = [parseFloat(locationMatch[0]), parseFloat(locationMatch[1])];
                result.push({
                    id: -1,
                    geometry: 'point',
                    type: t('inspector.location'),
                    name: loc[0].toFixed(6) + ', ' + loc[1].toFixed(6),
                    location: loc
                });
            }

            function addEntity(entity) {
                if (entity.id in entities || result.length > 200)
                    return;

                entities[entity.id] = true;

                var name = utilDisplayName(entity) || '';
                if (name.toLowerCase().indexOf(q) >= 0) {
                    var matched = context.presets().match(entity, graph),
                        type = (matched && matched.name()) || utilDisplayType(entity.id);
                    result.push({
                        id: entity.id,
                        entity: entity,
                        geometry: context.geometry(entity.id),
                        type: type,
                        name: name
                    });
                }

                graph.parentRelations(entity).forEach(function(parent) {
                    addEntity(parent);
                });
            }

            var visible = context.surface().selectAll('.point, .line, .area').nodes();
            for (var i = 0; i < visible.length && result.length <= 200; i++) {
                addEntity(visible[i].__data__);
            }

            (_geocodeResults || []).forEach(function(d) {
                // https://github.com/openstreetmap/iD/issues/1890
                if (d.osm_type && d.osm_id) {
                    result.push({
                        id: osmEntity.id.fromOSM(d.osm_type, d.osm_id),
                        geometry: d.osm_type === 'relation' ? 'relation' : d.osm_type === 'way' ? 'line' : 'point',
                        type: d.type !== 'yes' ? (d.type.charAt(0).toUpperCase() + d.type.slice(1)).replace('_', ' ')
                                               : (d.class.charAt(0).toUpperCase() + d.class.slice(1)).replace('_', ' '),
                        name: d.display_name,
                        extent: new geoExtent(
                            [parseFloat(d.boundingbox[3]), parseFloat(d.boundingbox[0])],
                            [parseFloat(d.boundingbox[2]), parseFloat(d.boundingbox[1])])
                    });
                }
            });

            return result;
        }

        function drawList() {
            var value = search.property('value'),
                results = features();

            list.classed('filtered', value.length);

            var noResultsWorldwide = _geocodeResults && _geocodeResults.length === 0;

            var resultsIndicator = list.selectAll('.no-results-item')
                .data([0])
                .enter()
                .append('button')
                .property('disabled', true)
                .attr('class', 'no-results-item')
                .call(svgIcon('#icon-alert', 'pre-text'));

            resultsIndicator.append('span')
                .attr('class', 'entity-name');

            list.selectAll('.no-results-item .entity-name')
                .text(noResultsWorldwide ? t('geocoder.no_results_worldwide') : t('geocoder.no_results_visible'));

            if (services.geocoder) {
              list.selectAll('.geocode-item')
                  .data([0])
                  .enter()
                  .append('button')
                  .attr('class', 'geocode-item')
                  .on('click', geocoderSearch)
                  .append('div')
                  .attr('class', 'label')
                  .append('span')
                  .attr('class', 'entity-name')
                  .text(t('geocoder.search'));
            }

            list.selectAll('.no-results-item')
                .style('display', (value.length && !results.length) ? 'block' : 'none');

            list.selectAll('.geocode-item')
                .style('display', (value && _geocodeResults === undefined) ? 'block' : 'none');

            list.selectAll('.feature-list-item')
                .data([-1])
                .remove();

            var items = list.selectAll('.feature-list-item')
                .data(results, function(d) { return d.id; });

            var enter = items.enter()
                .insert('button', '.geocode-item')
                .attr('class', 'feature-list-item')
                .on('mouseover', mouseover)
                .on('mouseout', mouseout)
                .on('click', click);

            var label = enter
                .append('div')
                .attr('class', 'label');

            label
                .each(function(d) {
                    d3_select(this)
                        .call(svgIcon('#icon-' + d.geometry, 'pre-text'));
                });

            label
                .append('span')
                .attr('class', 'entity-type')
                .text(function(d) { return d.type; });

            label
                .append('span')
                .attr('class', 'entity-name')
                .text(function(d) { return d.name; });

            enter
                .style('opacity', 0)
                .transition()
                .style('opacity', 1);

            items.order();

            items.exit()
                .remove();
        }

        function mouseover(d) {
            if (d.id === -1) return;

            context.surface().selectAll(utilEntityOrMemberSelector([d.id], context.graph()))
                .classed('hover', true);
        }

        function mouseout() {
            context.surface().selectAll('.hover')
                .classed('hover', false);
        }

        function click(d) {
            d3_event.preventDefault();
            if (d.location) {
                context.map().centerZoom([d.location[1], d.location[0]], 20);
            }
            else if (d.entity) {
                if (d.entity.type === 'node') {
                    context.map().center(d.entity.loc);
                } else if (d.entity.type === 'way') {
                    var center = context.projection(context.map().center()),
                        edge = geoChooseEdge(context.childNodes(d.entity), center, context.projection);
                    context.map().center(edge.loc);
                }
                context.enter(modeSelect(context, [d.entity.id]));
            } else {
                context.zoomToEntity(d.id);
            }
        }

        function geocoderSearch() {
            services.geocoder.search(search.property('value'), function (err, resp) {
                _geocodeResults = resp || [];
                drawList();
            });
        }
    }

    return featureList;
}
<commit_msg>Fix feature list / current view searching (closes #4690)<commit_after>import {
    event as d3_event,
    select as d3_select
} from 'd3-selection';

import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js';

import * as sexagesimal from '@mapbox/sexagesimal';
import { t } from '../util/locale';
import { geoExtent, geoChooseEdge } from '../geo';
import { modeSelect } from '../modes';
import { osmEntity } from '../osm';
import { svgIcon } from '../svg';
import { services } from '../services';
import { uiCmd } from './cmd';

import {
    utilDisplayName,
    utilDisplayType,
    utilEntityOrMemberSelector,
    utilNoAuto
} from '../util';

export function uiFeatureList(context) {
    var keybinding = d3_keybinding('feature-list');
    var _geocodeResults;

    function featureList(selection) {
        var header = selection
            .append('div')
            .attr('class', 'header fillL cf');

        header
            .append('h3')
            .text(t('inspector.feature_list'));

        var searchWrap = selection
            .append('div')
            .attr('class', 'search-header');

        var search = searchWrap
            .append('input')
            .attr('placeholder', t('inspector.search'))
            .attr('type', 'search')
            .call(utilNoAuto)
            .on('keypress', keypress)
            .on('keydown', keydown)
            .on('input', inputevent);

        searchWrap
            .call(svgIcon('#icon-search', 'pre-text'));

        var listWrap = selection
            .append('div')
            .attr('class', 'inspector-body');

        var list = listWrap
            .append('div')
            .attr('class', 'feature-list cf');

        context
            .on('exit.feature-list', clearSearch);
        context.map()
            .on('drawn.feature-list', mapDrawn);

        keybinding
            .on(uiCmd('⌘F'), focusSearch);

        d3_select(document)
            .call(keybinding);

        function focusSearch() {
            var mode = context.mode() && context.mode().id;
            if (mode !== 'browse') return;

            d3_event.preventDefault();
            search.node().focus();
        }

        function keydown() {
            if (d3_event.keyCode === 27) {  // escape
                search.node().blur();
            }
        }

        function keypress() {
            var q = search.property('value'),
                items = list.selectAll('.feature-list-item');
            if (d3_event.keyCode === 13 && q.length && items.size()) {  // return
                click(items.datum());
            }
        }

        function inputevent() {
            _geocodeResults = undefined;
            drawList();
        }

        function clearSearch() {
            search.property('value', '');
            drawList();
        }

        function mapDrawn(e) {
            if (e.full) {
                drawList();
            }
        }

        function features() {
            var entities = {},
                result = [],
                graph = context.graph(),
                q = search.property('value').toLowerCase();

            if (!q) return result;

            var idMatch = q.match(/^([nwr])([0-9]+)$/);

            if (idMatch) {
                result.push({
                    id: idMatch[0],
                    geometry: idMatch[1] === 'n' ? 'point' : idMatch[1] === 'w' ? 'line' : 'relation',
                    type: idMatch[1] === 'n' ? t('inspector.node') : idMatch[1] === 'w' ? t('inspector.way') : t('inspector.relation'),
                    name: idMatch[2]
                });
            }

            var locationMatch = sexagesimal.pair(q.toUpperCase()) || q.match(/^(-?\d+\.?\d*)\s+(-?\d+\.?\d*)$/);

            if (locationMatch) {
                var loc = [parseFloat(locationMatch[0]), parseFloat(locationMatch[1])];
                result.push({
                    id: -1,
                    geometry: 'point',
                    type: t('inspector.location'),
                    name: loc[0].toFixed(6) + ', ' + loc[1].toFixed(6),
                    location: loc
                });
            }

            function addEntity(entity) {
                if (entity.id in entities || result.length > 200)
                    return;

                entities[entity.id] = true;

                var name = utilDisplayName(entity) || '';
                if (name.toLowerCase().indexOf(q) >= 0) {
                    var matched = context.presets().match(entity, graph),
                        type = (matched && matched.name()) || utilDisplayType(entity.id);
                    result.push({
                        id: entity.id,
                        entity: entity,
                        geometry: context.geometry(entity.id),
                        type: type,
                        name: name
                    });
                }

                graph.parentRelations(entity).forEach(function(parent) {
                    addEntity(parent);
                });
            }

            var visible = context.surface().selectAll('.point, .line, .area').nodes();
            for (var i = 0; i < visible.length && result.length <= 200; i++) {
                var datum = visible[i].__data__;
                var entity = datum && datum.properties && datum.properties.entity;
                if (entity) { addEntity(entity); }
            }

            (_geocodeResults || []).forEach(function(d) {
                // https://github.com/openstreetmap/iD/issues/1890
                if (d.osm_type && d.osm_id) {
                    result.push({
                        id: osmEntity.id.fromOSM(d.osm_type, d.osm_id),
                        geometry: d.osm_type === 'relation' ? 'relation' : d.osm_type === 'way' ? 'line' : 'point',
                        type: d.type !== 'yes' ? (d.type.charAt(0).toUpperCase() + d.type.slice(1)).replace('_', ' ')
                                               : (d.class.charAt(0).toUpperCase() + d.class.slice(1)).replace('_', ' '),
                        name: d.display_name,
                        extent: new geoExtent(
                            [parseFloat(d.boundingbox[3]), parseFloat(d.boundingbox[0])],
                            [parseFloat(d.boundingbox[2]), parseFloat(d.boundingbox[1])])
                    });
                }
            });

            return result;
        }

        function drawList() {
            var value = search.property('value'),
                results = features();

            list.classed('filtered', value.length);

            var noResultsWorldwide = _geocodeResults && _geocodeResults.length === 0;

            var resultsIndicator = list.selectAll('.no-results-item')
                .data([0])
                .enter()
                .append('button')
                .property('disabled', true)
                .attr('class', 'no-results-item')
                .call(svgIcon('#icon-alert', 'pre-text'));

            resultsIndicator.append('span')
                .attr('class', 'entity-name');

            list.selectAll('.no-results-item .entity-name')
                .text(noResultsWorldwide ? t('geocoder.no_results_worldwide') : t('geocoder.no_results_visible'));

            if (services.geocoder) {
              list.selectAll('.geocode-item')
                  .data([0])
                  .enter()
                  .append('button')
                  .attr('class', 'geocode-item')
                  .on('click', geocoderSearch)
                  .append('div')
                  .attr('class', 'label')
                  .append('span')
                  .attr('class', 'entity-name')
                  .text(t('geocoder.search'));
            }

            list.selectAll('.no-results-item')
                .style('display', (value.length && !results.length) ? 'block' : 'none');

            list.selectAll('.geocode-item')
                .style('display', (value && _geocodeResults === undefined) ? 'block' : 'none');

            list.selectAll('.feature-list-item')
                .data([-1])
                .remove();

            var items = list.selectAll('.feature-list-item')
                .data(results, function(d) { return d.id; });

            var enter = items.enter()
                .insert('button', '.geocode-item')
                .attr('class', 'feature-list-item')
                .on('mouseover', mouseover)
                .on('mouseout', mouseout)
                .on('click', click);

            var label = enter
                .append('div')
                .attr('class', 'label');

            label
                .each(function(d) {
                    d3_select(this)
                        .call(svgIcon('#icon-' + d.geometry, 'pre-text'));
                });

            label
                .append('span')
                .attr('class', 'entity-type')
                .text(function(d) { return d.type; });

            label
                .append('span')
                .attr('class', 'entity-name')
                .text(function(d) { return d.name; });

            enter
                .style('opacity', 0)
                .transition()
                .style('opacity', 1);

            items.order();

            items.exit()
                .remove();
        }

        function mouseover(d) {
            if (d.id === -1) return;

            context.surface().selectAll(utilEntityOrMemberSelector([d.id], context.graph()))
                .classed('hover', true);
        }

        function mouseout() {
            context.surface().selectAll('.hover')
                .classed('hover', false);
        }

        function click(d) {
            d3_event.preventDefault();
            if (d.location) {
                context.map().centerZoom([d.location[1], d.location[0]], 20);
            }
            else if (d.entity) {
                if (d.entity.type === 'node') {
                    context.map().center(d.entity.loc);
                } else if (d.entity.type === 'way') {
                    var center = context.projection(context.map().center()),
                        edge = geoChooseEdge(context.childNodes(d.entity), center, context.projection);
                    context.map().center(edge.loc);
                }
                context.enter(modeSelect(context, [d.entity.id]));
            } else {
                context.zoomToEntity(d.id);
            }
        }

        function geocoderSearch() {
            services.geocoder.search(search.property('value'), function (err, resp) {
                _geocodeResults = resp || [];
                drawList();
            });
        }
    }

    return featureList;
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule Clipboard
 */
'use strict';

var Clipboard = require('NativeModules').Clipboard;

/**
 * `Clipboard` gives you an interface for setting and getting content from Clipboard on both iOS and Android
 */
module.exports = {
  /**
   * Get content of string type, this method returns a `Promise`, so you can use following code to get clipboard content
   * ```javascript
   * async _getContent() {
   *   var content = await Clipboard.getString();
   * }
   * ```
   */
  getString() {
    if (arguments.length > 0) {
      let callback = arguments[0];
      console.warn('Clipboard.getString(callback) is deprecated. Use the returned Promise instead');
      Clipboard.getString().then(callback);
      return;
    }
    return Clipboard.getString();
  },
  /**
   * Set content of string type. You can use following code to set clipboard content
   * ```javascript
   * _setContent() {
   *   Clipboard.setString('hello world');
   * }
   * ```
   * @param the content to be stored in the clipboard.
   */
  setString(content) {
    Clipboard.setString(content);
  }
};
<commit_msg>Annotate Clipboard module<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule Clipboard
 * @flow
 */
'use strict';

const Clipboard = require('NativeModules').Clipboard;
const deprecatedCallback = require('deprecatedCallback');

/**
 * `Clipboard` gives you an interface for setting and getting content from Clipboard on both iOS and Android
 */
module.exports = {
  /**
   * Get content of string type, this method returns a `Promise`, so you can use following code to get clipboard content
   * ```javascript
   * async _getContent() {
   *   var content = await Clipboard.getString();
   * }
   * ```
   */
  getString(): Promise<string> {
    return deprecatedCallback(
      Clipboard.getString(),
      Array.prototype.slice.call(arguments),
      'success-first',
      'Clipboard.getString(callback) is deprecated. Use the returned Promise instead'
    );
  },
  /**
   * Set content of string type. You can use following code to set clipboard content
   * ```javascript
   * _setContent() {
   *   Clipboard.setString('hello world');
   * }
   * ```
   * @param the content to be stored in the clipboard.
   */
  setString(content: string) {
    Clipboard.setString(content);
  }
};
<|endoftext|>


<commit_before>/*global require, global*/

var test = require('tape');
var fs = require('fs');
var path = require('path');

var Screen = require('base-widget/spec/util').screenFactory;
var Editor = require('../.');

test("Editor", function (t) {
  var screen = new Screen();
  screen.key('C-q', function () { process.exit(); });
  var editor = new Editor({parent: screen});

  t.test(".open", function (st) {
    st.test("should throw EACCES for a file with perms 000", function (sst) {
      sst.plan(1);

      var perms000File = path.resolve(__dirname, 'fixtures/perms-000');

      // can't be checked in with 000 perms
      var originalPerms = (fs.statSync(perms000File).mode.toString(8).match(/[0-7]{3}$/) || [])[0] || '644';
      fs.chmodSync(perms000File, '000');

      editor.open(perms000File)
        .then(function () { sst.ok(false); })
        .catch(function (err) { sst.equal(err.code, 'EACCES'); })
        .finally(function () { fs.chmodSync(perms000File, originalPerms); })
        .done();
    });
  });

  t.on('end', function () {
    Editor.highlightClient.done(function (client) {
      client.dontRespawn = true;
      editor.detach();
    });
  });
});
<commit_msg>fix(perms): spec/Editor.js executable<commit_after>#!/usr/bin/env node
/*global require, global*/

var test = require('tape');
var fs = require('fs');
var path = require('path');

var Screen = require('base-widget/spec/util').screenFactory;
var Editor = require('../.');

test("Editor", function (t) {
  var screen = new Screen();
  screen.key('C-q', function () { process.exit(); });
  var editor = new Editor({parent: screen});

  t.test(".open", function (st) {
    st.test("should throw EACCES for a file with perms 000", function (sst) {
      sst.plan(1);

      var perms000File = path.resolve(__dirname, 'fixtures/perms-000');

      // can't be checked in with 000 perms
      var originalPerms = (fs.statSync(perms000File).mode.toString(8).match(/[0-7]{3}$/) || [])[0] || '644';
      fs.chmodSync(perms000File, '000');

      editor.open(perms000File)
        .then(function () { sst.ok(false); })
        .catch(function (err) { sst.equal(err.code, 'EACCES'); })
        .finally(function () { fs.chmodSync(perms000File, originalPerms); })
        .done();
    });
  });

  t.on('end', function () {
    Editor.highlightClient.done(function (client) {
      client.dontRespawn = true;
      editor.detach();
    });
  });
});
<|endoftext|>


<commit_before>const Generator = require('yeoman-generator')
const chalk = require('chalk')
const yosay = require('yosay')
const clear = require('clear-terminal')
const random = require('randomstring')
const commandExists = require('command-exists')

// Importing modules
const promptsFunction = require('./modules/prompt')
const pkg = require('../../package.json')

// Package JSON
const writePackageJson = require('./modules/writing/packageJSON')

// Copy Source Files
const copySources = require('./modules/writing/copySources')

// Add MySQL Database
const addDB = require('./modules/writing/addDB')

// And Action!
module.exports = class extends Generator {
  constructor (args, opts) {
    super(args, opts)
    this.pkg = pkg

    this.promptsFunction = promptsFunction.bind(this)

    // Package.json
    this.writePackageJson = writePackageJson.bind(this)

    // Add Database
    this.addDB = addDB.bind(this)

    // Copy Sources
    this.copySources = copySources.bind(this)

    // Command Checks
    this.commands = {
      composer: false,
      yarn: false,
      git: false,
      wget: false,
      wp: false,
      mysql: false
    }

    // Function for Generate Salt Keys
    var saltKeys = []

    for (var i = 0; i < 8; i++) {
      saltKeys.push(random.generate({
        length: 64,
        charset: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!§$%/()=_;:,.^'
      }))
    }
    this.saltKeys = saltKeys
  }

    // Initializing
  async initializing () {
    this.log(`${chalk.magenta('Cleaning Directory')}`)

    for (const command in this.commands) {
      try {
        await commandExists(command)
        this.commands[command] = true
      } catch (e) {
        if (e) this.log(e)
      }
    }
  }

  prompting () {
    // Custom Greeting
    var welcome =
          '\n ' + chalk.styles.cyan.open +
          '\n        ___                      ___         ___            ___      ' +
          '\n       /\\__\\          ___       /\\  \\       /\\  \\          /\\__\\     ' +
          '\n      /:/  /         /\\  \\      \\:\\  \\      \\:\\  \\        /::|  |    ' +
          '\n     /:/__/          \\:\\  \\      \\:\\  \\      \\:\\  \\      /:|:|  |    ' +
          '\n    /::\\__\\____      /::\\__\\     /::\\  \\     /::\\  \\    /:/|:|  |__  ' +
          '\n   /:/\\:::::\\__\\  __/:/\\/__/    /:/\\:\\__\\   /:/\\:\\__\\  /:/ |:| /\\__\\ ' +
          '\n   \\/_|:|~~|~    /\\/:/  /      /:/  \\/__/  /:/  \\/__/  \\/__|:|/:/  / ' +
          '\n      |:|  |     \\::/__/      /:/  /      /:/  /           |:/:/  /  ' +
          '\n      |:|  |      \\:\\__\\      \\/__/       \\/__/            |::/  /   ' +
          '\n      |:|  |       \\/__/                                   /:/  /    ' +
          '\n       \\|__|                                               \\/__/     ' +
          '\n  ' + chalk.styles.cyan.close +
          '\n                                                       v.' + chalk.bold(this.pkg.version) +
          '\n  ' +
          '\n   Authors: Sascha Fuchs (@gisugosu) ' +
          '\n   URL    : http://kittn.de   ' +
          '\n '
    clear()
    this.log(welcome)

    // Now ask some questions already
    const prompts = promptsFunction()
    return this.prompt(prompts).then(props => {
      // To access props later use this.props.someAnswer;
      this.props = props
      this.props.saltKeys = this.saltKeys
    })
  }

  async writing () {
    this.log(`${chalk.magenta('Writing package.json')}`)

    // Additional Props
    this.props.projectpath = process.cwd()

    // Write Package.json
    this.writePackageJson().writing(this)

    // Add Database if user wants to
    this.addDB().writing(this)

    // Copy Source Files and Folders
    this.copySources().writing(this)
  }

  install () {
    if (this.commands.yarn) {
      // this.yarnInstall()
    } else {
      this.npmInstall()
    }

    // Goodbye
    this.on('end', () => {
      const goodbye =
              '\n ' + chalk.styles.yellow.open +
              '\n                    __    .__  __    __ ' +
              '\n                    |  | _|__|/  |__/  |_  ____ ' +
              '\n                    |  |/ /  \\   __\\   __\\/    \\ ' +
              '\n                    |    <|  ||  |  |  | |   |  \\ ' +
              '\n                    |__|_ \\__||__|  |__| |___|  / ' +
              '\n                    \\/                   \\/  ' +
              '\n  ' + chalk.styles.yellow.close + chalk.styles.green.open +
              '\n   Now we are finished. Make your last settings and start `npm run init`.' +
              '\n      When npm is finished activate `npm run dev` and happy Coding.' +
              '\n ' + chalk.styles.green.close
      this.log(goodbye)
    })
  }
}
<commit_msg>Reactivate yarn<commit_after>const Generator = require('yeoman-generator')
const chalk = require('chalk')
const yosay = require('yosay')
const clear = require('clear-terminal')
const random = require('randomstring')
const commandExists = require('command-exists')

// Importing modules
const promptsFunction = require('./modules/prompt')
const pkg = require('../../package.json')

// Package JSON
const writePackageJson = require('./modules/writing/packageJSON')

// Copy Source Files
const copySources = require('./modules/writing/copySources')

// Add MySQL Database
const addDB = require('./modules/writing/addDB')

// And Action!
module.exports = class extends Generator {
  constructor (args, opts) {
    super(args, opts)
    this.pkg = pkg

    this.promptsFunction = promptsFunction.bind(this)

    // Package.json
    this.writePackageJson = writePackageJson.bind(this)

    // Add Database
    this.addDB = addDB.bind(this)

    // Copy Sources
    this.copySources = copySources.bind(this)

    // Command Checks
    this.commands = {
      composer: false,
      yarn: false,
      git: false,
      wget: false,
      wp: false,
      mysql: false
    }

    // Function for Generate Salt Keys
    var saltKeys = []

    for (var i = 0; i < 8; i++) {
      saltKeys.push(random.generate({
        length: 64,
        charset: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!§$%/()=_;:,.^'
      }))
    }
    this.saltKeys = saltKeys
  }

    // Initializing
  async initializing () {
    this.log(`${chalk.magenta('Cleaning Directory')}`)

    for (const command in this.commands) {
      try {
        await commandExists(command)
        this.commands[command] = true
      } catch (e) {
        if (e) this.log(e)
      }
    }
  }

  prompting () {
    // Custom Greeting
    var welcome =
          '\n ' + chalk.styles.cyan.open +
          '\n        ___                      ___         ___            ___      ' +
          '\n       /\\__\\          ___       /\\  \\       /\\  \\          /\\__\\     ' +
          '\n      /:/  /         /\\  \\      \\:\\  \\      \\:\\  \\        /::|  |    ' +
          '\n     /:/__/          \\:\\  \\      \\:\\  \\      \\:\\  \\      /:|:|  |    ' +
          '\n    /::\\__\\____      /::\\__\\     /::\\  \\     /::\\  \\    /:/|:|  |__  ' +
          '\n   /:/\\:::::\\__\\  __/:/\\/__/    /:/\\:\\__\\   /:/\\:\\__\\  /:/ |:| /\\__\\ ' +
          '\n   \\/_|:|~~|~    /\\/:/  /      /:/  \\/__/  /:/  \\/__/  \\/__|:|/:/  / ' +
          '\n      |:|  |     \\::/__/      /:/  /      /:/  /           |:/:/  /  ' +
          '\n      |:|  |      \\:\\__\\      \\/__/       \\/__/            |::/  /   ' +
          '\n      |:|  |       \\/__/                                   /:/  /    ' +
          '\n       \\|__|                                               \\/__/     ' +
          '\n  ' + chalk.styles.cyan.close +
          '\n                                                       v.' + chalk.bold(this.pkg.version) +
          '\n  ' +
          '\n   Authors: Sascha Fuchs (@gisugosu) ' +
          '\n   URL    : http://kittn.de   ' +
          '\n '
    clear()
    this.log(welcome)

    // Now ask some questions already
    const prompts = promptsFunction()
    return this.prompt(prompts).then(props => {
      // To access props later use this.props.someAnswer;
      this.props = props
      this.props.saltKeys = this.saltKeys
    })
  }

  async writing () {
    this.log(`${chalk.magenta('Writing package.json')}`)

    // Additional Props
    this.props.projectpath = process.cwd()

    // Write Package.json
    this.writePackageJson().writing(this)

    // Add Database if user wants to
    this.addDB().writing(this)

    // Copy Source Files and Folders
    this.copySources().writing(this)
  }

  install () {
    if (this.commands.yarn) {
      this.yarnInstall()
    } else {
      this.npmInstall()
    }

    // Goodbye
    this.on('end', () => {
      const goodbye =
              '\n ' + chalk.styles.yellow.open +
              '\n                    __    .__  __    __ ' +
              '\n                    |  | _|__|/  |__/  |_  ____ ' +
              '\n                    |  |/ /  \\   __\\   __\\/    \\ ' +
              '\n                    |    <|  ||  |  |  | |   |  \\ ' +
              '\n                    |__|_ \\__||__|  |__| |___|  / ' +
              '\n                    \\/                   \\/  ' +
              '\n  ' + chalk.styles.yellow.close + chalk.styles.green.open +
              '\n   Now we are finished. Make your last settings and start `npm run init`.' +
              '\n      When npm is finished activate `npm run dev` and happy Coding.' +
              '\n ' + chalk.styles.green.close
      this.log(goodbye)
    })
  }
}
<|endoftext|>


<commit_before>CT.admin.db = {
	"init": function() {
		CT.admin.db.starred = CT.dom.id("dbstarred");
		CT.admin.core.init("db", function() {
			CT.db.init({
				cb: function(schema) {
					var skeys = Object.keys(schema);
					CT.panel.simple(skeys, "db");
					skeys.forEach(function(modelName) {
						CT.db.pager(modelName);
					});
				},
				builder: CT.admin.db._build,
				post_pager: CT.admin.db._post_pager
			});
		}, true);
	},
	"_post_pager": function(key, modelName, startYear) {
		var pnode = CT.dom.id("dbpanel" + key);
		pnode.insertBefore(CT.dom.node([
			CT.dom.button("new query", function() {
				CT.db.query({
					modelName: modelName,
					startYear: startYear || 1970, // gotta start somewhere...
					showHelp: true
				}, "fade");
			}),
			CT.dom.button("new " + modelName, function() {
				CT.admin.db.starLink(CT.db.getDefaults(modelName,
					{ "label": "new " + modelName }), modelName).onclick();
			})
		], "div", "right"), pnode.firstChild);
	},
	"_build": function(modelName) {
		return function(obj) {
			return (new CT.admin.db.Editor(modelName, obj)).node;
		};
	},
	"_add": function(modelName, d) {
		CT.panel.add(d.label, false, modelName);
		CT.dom.id(modelName + "content" + d.label.replace(/ /g,
			"")).appendChild(CT.admin.db._build(modelName)(d));
	},
	"star": function(k) {
		var d = CT.data.get(k), key = "starreditem" + d.label.replace(/ /g, ""),
			b = CT.dom.button(CT.dom.id(key) ? "Unstar" : "Star", function() {
				if (b.innerHTML == "Star") {
					b.innerHTML = "Unstar";
					CT.admin.db.starLink(d);
				} else {
					b.innerHTML = "Star";
					CT.dom.remove(CT.dom.id(key));
				}
			});
		return b;
	},
	"starLink": function(d, modelName) {
		var label = d.label,
			k = "starreditem" + label.replace(/ /g, ""),
			slink = CT.dom.id(k);
		if (!slink) {
			slink = CT.dom.node(CT.dom.link(label, function() {
				var dobj = {}, nslabel = label.replace(/ /g, "");
				dobj.db = modelName || CT.db.key2model(d.key);
				dobj[dobj.db] = label;
				if (!CT.dom.id(dobj.db + "panel" + nslabel))
					CT.admin.db._add(dobj.db, d);
				CT.panel.drill(dobj);
			}), "div", "pointer", k);
			CT.admin.db.starred.appendChild(slink);
		}
		return slink.firstChild;
	}
};

CT.admin.db.Editor = CT.Class({
	"CLASSNAME": "CT.admin.db.Editor",
	"_order": ["string", "text", "integer", "float", "datetime", "boolean", "list", "keylist", "key"],
	"_submit": function() {
		var data = this.data, changes = {};
		if (data.key)
			changes.key = data.key;
		else
			changes.modelName = this.modelName;
		this.inputs.forEach(function(ip) {
			var val = ip.getValue();
			if (val != data[ip.rowKey])
				changes[ip.rowKey] = val;
		});
		CT.admin.core.q("edit", function(resp) {
			for (var k in changes)
				data[k] = changes[k];
			if (!data.key) {
				data.key = resp.key;
				CT.data.add(data);
			}
			if (data.label != resp.label) {
				CT.panel.rename(data.label, resp.label, changes.modelName, "starred");
				CT.dom.id()
				data.label = resp.label;
			}
			alert("you did it");
		}, "edit failed", { data: changes }, "/_db");
	},
	"_row": function(k) {
		var val = this.data[k], valcell, ptype,
			rownode = CT.dom.node("", "div", "lister");
		rownode.appendChild(CT.dom.node(k + ":", "div", "keycell"));
		ptype = rownode.ptype = this.schema[k];
		if (CT.db.edit.isSupported(ptype, k)) {
			valcell = CT.db.edit.input(k, ptype, val, this.modelName, {
				startYear: 1970 // gotta start somewhere, might as well be epoch...
			});
			this.inputs.push(valcell);
			if (valcell.addButton) { // list, keylist
				rownode.appendChild(valcell.addButton);
				rownode.appendChild(valcell.empty);
			}
		} else
			valcell = CT.dom.node(val || "null", "span");
		rownode.appendChild(valcell);
		return rownode;
	},
	"_table": function() {
		var k, r, d = this.data, n = this.node = CT.dom.node();
		this._order.forEach(function(t) {
			n[t] = CT.dom.node();
			n.appendChild(n[t]);
		});
		n.appendChild(CT.dom.br());
		for (k in d) {
			r = this._row(k);
			(k != "_label" && n[r.ptype] || n).appendChild(r);
		}
		d.key && n.appendChild(CT.dom.node(CT.dom.button("Delete", function() {
			var label = d.label;
			if (!confirm("really delete " + label + "?"))
				return;
			CT.dom.remove(CT.dom.id("starreditem" + label.replace(/ /g, "")));
			CT.admin.core.q("delete", function() {
				n.parentNode.parentNode.parentNode.parentNode.pager.remove(d);
				alert("deleted: " + label);
			}, "failed to delete " + label, {
				"key": d.key
			}, "/_db");
		}, "red"), "div", "right"));
		n.appendChild(CT.dom.button("Submit", this._submit));
		d.key && n.appendChild(CT.admin.db.star(d.key));
	},
	"init": function(model, data) {
		this.modelName = model;
		this.schema = CT.db.getSchema(model);
		this.data = data;
		this.inputs = [];
		this._table();
	}
});<commit_msg>CT.admin.db: fixed CT.db.edit.getDefaults() reference<commit_after>CT.admin.db = {
	"init": function() {
		CT.admin.db.starred = CT.dom.id("dbstarred");
		CT.admin.core.init("db", function() {
			CT.db.init({
				cb: function(schema) {
					var skeys = Object.keys(schema);
					CT.panel.simple(skeys, "db");
					skeys.forEach(function(modelName) {
						CT.db.pager(modelName);
					});
				},
				builder: CT.admin.db._build,
				post_pager: CT.admin.db._post_pager
			});
		}, true);
	},
	"_post_pager": function(key, modelName, startYear) {
		var pnode = CT.dom.id("dbpanel" + key);
		pnode.insertBefore(CT.dom.node([
			CT.dom.button("new query", function() {
				CT.db.query({
					modelName: modelName,
					startYear: startYear || 1970, // gotta start somewhere...
					showHelp: true
				}, "fade");
			}),
			CT.dom.button("new " + modelName, function() {
				CT.admin.db.starLink(CT.db.edit.getDefaults(modelName,
					{ "label": "new " + modelName }), modelName).onclick();
			})
		], "div", "right"), pnode.firstChild);
	},
	"_build": function(modelName) {
		return function(obj) {
			return (new CT.admin.db.Editor(modelName, obj)).node;
		};
	},
	"_add": function(modelName, d) {
		CT.panel.add(d.label, false, modelName);
		CT.dom.id(modelName + "content" + d.label.replace(/ /g,
			"")).appendChild(CT.admin.db._build(modelName)(d));
	},
	"star": function(k) {
		var d = CT.data.get(k), key = "starreditem" + d.label.replace(/ /g, ""),
			b = CT.dom.button(CT.dom.id(key) ? "Unstar" : "Star", function() {
				if (b.innerHTML == "Star") {
					b.innerHTML = "Unstar";
					CT.admin.db.starLink(d);
				} else {
					b.innerHTML = "Star";
					CT.dom.remove(CT.dom.id(key));
				}
			});
		return b;
	},
	"starLink": function(d, modelName) {
		var label = d.label,
			k = "starreditem" + label.replace(/ /g, ""),
			slink = CT.dom.id(k);
		if (!slink) {
			slink = CT.dom.node(CT.dom.link(label, function() {
				var dobj = {}, nslabel = label.replace(/ /g, "");
				dobj.db = modelName || CT.db.key2model(d.key);
				dobj[dobj.db] = label;
				if (!CT.dom.id(dobj.db + "panel" + nslabel))
					CT.admin.db._add(dobj.db, d);
				CT.panel.drill(dobj);
			}), "div", "pointer", k);
			CT.admin.db.starred.appendChild(slink);
		}
		return slink.firstChild;
	}
};

CT.admin.db.Editor = CT.Class({
	"CLASSNAME": "CT.admin.db.Editor",
	"_order": ["string", "text", "integer", "float", "datetime", "boolean", "list", "keylist", "key"],
	"_submit": function() {
		var data = this.data, changes = {};
		if (data.key)
			changes.key = data.key;
		else
			changes.modelName = this.modelName;
		this.inputs.forEach(function(ip) {
			var val = ip.getValue();
			if (val != data[ip.rowKey])
				changes[ip.rowKey] = val;
		});
		CT.admin.core.q("edit", function(resp) {
			for (var k in changes)
				data[k] = changes[k];
			if (!data.key) {
				data.key = resp.key;
				CT.data.add(data);
			}
			if (data.label != resp.label) {
				CT.panel.rename(data.label, resp.label, changes.modelName, "starred");
				CT.dom.id()
				data.label = resp.label;
			}
			alert("you did it");
		}, "edit failed", { data: changes }, "/_db");
	},
	"_row": function(k) {
		var val = this.data[k], valcell, ptype,
			rownode = CT.dom.node("", "div", "lister");
		rownode.appendChild(CT.dom.node(k + ":", "div", "keycell"));
		ptype = rownode.ptype = this.schema[k];
		if (CT.db.edit.isSupported(ptype, k)) {
			valcell = CT.db.edit.input(k, ptype, val, this.modelName, {
				startYear: 1970 // gotta start somewhere, might as well be epoch...
			});
			this.inputs.push(valcell);
			if (valcell.addButton) { // list, keylist
				rownode.appendChild(valcell.addButton);
				rownode.appendChild(valcell.empty);
			}
		} else
			valcell = CT.dom.node(val || "null", "span");
		rownode.appendChild(valcell);
		return rownode;
	},
	"_table": function() {
		var k, r, d = this.data, n = this.node = CT.dom.node();
		this._order.forEach(function(t) {
			n[t] = CT.dom.node();
			n.appendChild(n[t]);
		});
		n.appendChild(CT.dom.br());
		for (k in d) {
			r = this._row(k);
			(k != "_label" && n[r.ptype] || n).appendChild(r);
		}
		d.key && n.appendChild(CT.dom.node(CT.dom.button("Delete", function() {
			var label = d.label;
			if (!confirm("really delete " + label + "?"))
				return;
			CT.dom.remove(CT.dom.id("starreditem" + label.replace(/ /g, "")));
			CT.admin.core.q("delete", function() {
				n.parentNode.parentNode.parentNode.parentNode.pager.remove(d);
				alert("deleted: " + label);
			}, "failed to delete " + label, {
				"key": d.key
			}, "/_db");
		}, "red"), "div", "right"));
		n.appendChild(CT.dom.button("Submit", this._submit));
		d.key && n.appendChild(CT.admin.db.star(d.key));
	},
	"init": function(model, data) {
		this.modelName = model;
		this.schema = CT.db.getSchema(model);
		this.data = data;
		this.inputs = [];
		this._table();
	}
});<|endoftext|>


<commit_before>// Math.random() devuelve número aleatorio entre 0 y 1.
var numero = Math.random();

if (numero <= 0.5) { console.log("\n" + numero + " MENOR que 0,5 \n" ); }
else { console.log("\n" + numero + " MAYOR que 0,5 \n"); }

<commit_msg>random versión 2<commit_after>// Math.random() devuelve número aleatorio entre 0 y 1.
var numero = Math.random();

var str = " MAYOR que 0,5";

if (numero <= 0.5) { str = " MENOR que 0,5"; }

console.log("\n" + numero + str + "\n"); }

<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",<commit_msg>Correcting style<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling <|endoftext|>


<commit_before>$.widget("dataclips.insight", {
  options: {
    adjustHeight: function(){}
  },
  _create: function(){
    this.element
      .attr("width", "100%")
      .attr("scrolling", "no")
      .attr("frameborder", "no")
      .prop("allowfullscreen", true)
      .attr("src", this.options.src);
  },
  _init: function(){
    this.filters = {};

    this.frameWindow = this.element.get(0).contentWindow;

    var self = this;
    var options     = this.options;
    var frame       = this.element.get(0);
    var iframe      = this.element;

    // resizing
    var resizeIframe = function(){
      frame.height = options.adjustHeight() || 500;
    };
    window.addEventListener('resize', resizeIframe, true);

    frame.addEventListener('load', function(){
      self.setFilter(self.options.defaultFilter);
      resizeIframe();
      self._trigger("load");
    }, true);

    // communication
    window.addEventListener('message', function (e) {
      if (e.source === self.frameWindow) {
        self._trigger("proxy", null, e.data);

        if (e.data['row-clicked']) {
          var record = e.data["row-clicked"];
          self._trigger("rowClick", null, record);
        }

      }
    });
  },

  _sendMessage: function(message){
    this.frameWindow.postMessage(message, '*');
  },

  refresh: function(){
    this._sendMessage({refresh: true});
  },

  setFilter: function(filters) {
    this.filters = $.extend(this.filters, filters);
    this._sendMessage({filters: this.filters});
  }
});
<commit_msg>fix back button browser bug<commit_after>$.widget("dataclips.insight", {
  options: {
    adjustHeight: function(){}
  },
  _create: function(){
    this.element
      .attr("width", "100%")
      .attr("scrolling", "no")
      .attr("frameborder", "no")
      .prop("allowfullscreen", true)
      .attr("src", this.options.src + '?format=html');
  },
  _init: function(){
    this.filters = {};

    this.frameWindow = this.element.get(0).contentWindow;

    var self = this;
    var options     = this.options;
    var frame       = this.element.get(0);
    var iframe      = this.element;

    // resizing
    var resizeIframe = function(){
      frame.height = options.adjustHeight() || 500;
    };
    window.addEventListener('resize', resizeIframe, true);

    frame.addEventListener('load', function(){
      self.setFilter(self.options.defaultFilter);
      resizeIframe();
      self._trigger("load");
    }, true);

    // communication
    window.addEventListener('message', function (e) {
      if (e.source === self.frameWindow) {
        self._trigger("proxy", null, e.data);

        if (e.data['row-clicked']) {
          var record = e.data["row-clicked"];
          self._trigger("rowClick", null, record);
        }

      }
    });
  },

  _sendMessage: function(message){
    this.frameWindow.postMessage(message, '*');
  },

  refresh: function(){
    this._sendMessage({refresh: true});
  },

  setFilter: function(filters) {
    this.filters = $.extend(this.filters, filters);
    this._sendMessage({filters: this.filters});
  }
});
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var App = require('app');

App.MainServiceItemView = Em.View.extend({
  templateName: require('templates/main/service/item'),
  maintenance: function(){
    var options = [];
    var service = this.get('controller.content');
    var hosts = App.Host.find().content.length;
    var allMasters = this.get('controller.content.hostComponents').filterProperty('isMaster').mapProperty('componentName').uniq();
    var disabled = this.get('controller.isStopDisabled');
    switch (service.get('serviceName')) {
      case 'GANGLIA':
      case 'NAGIOS':
        break;
      case 'YARN':
      case 'HDFS':
      case 'MAPREDUCE':
        if (App.supports.reassignMaster && hosts > 1) {
          allMasters.forEach(function (hostComponent) {
            if (App.reassignableComponents.contains(hostComponent)) {
              options.push({action: 'reassignMaster', context: hostComponent,
                'label': Em.I18n.t('services.service.actions.reassign.master').format(App.format.role(hostComponent)), disabled: false});
            }
          })
        }
      default:
        options.push({action: 'runSmokeTest', 'label': Em.I18n.t('services.service.actions.run.smoke'), disabled:disabled});
        options.push({action: 'manageConfigurationGroups', 'label': Em.I18n.t('services.service.actions.manage_configuration_groups'), disabled:false});
    }
    return options;
  }.property('controller.content', 'controller.isStopDisabled'),
  isMaintenanceActive: function() {
    return this.get('maintenance').length !== 0;
  }.property('maintenance'),
  hasConfigTab: function(){
    return this.get("controller.content.isConfigurable");
  }.property('controller.content.isConfigurable'),

  didInsertElement: function () {
    this.get('controller').setStartStopState();
  },
  service:function () {
    var svc = this.get('controller.content');
    var svcName = svc.get('serviceName');
    if (svcName) {
      switch (svcName.toLowerCase()) {
        case 'hdfs':
          svc = App.HDFSService.find().objectAt(0);
          break;
        case 'yarn':
          svc = App.YARNService.find().objectAt(0);
          break;
        case 'mapreduce':
          svc = App.MapReduceService.find().objectAt(0);
          break;
        case 'hbase':
          svc = App.HBaseService.find().objectAt(0);
          break;
        case 'flume':
          svc = App.FlumeService.find().objectAt(0);
          break;
        default:
          break;
      }
    }
    return svc;
  }.property('controller.content.serviceName').volatile()
});
<commit_msg>AMBARI-3767. Provide basic config-group management dialog. Additional patch. (akovalenko)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var App = require('app');

App.MainServiceItemView = Em.View.extend({
  templateName: require('templates/main/service/item'),
  maintenance: function(){
    var options = [];
    var service = this.get('controller.content');
    var hosts = App.Host.find().content.length;
    var allMasters = this.get('controller.content.hostComponents').filterProperty('isMaster').mapProperty('componentName').uniq();
    var disabled = this.get('controller.isStopDisabled');
    switch (service.get('serviceName')) {
      case 'GANGLIA':
      case 'NAGIOS':
        break;
      case 'YARN':
      case 'HDFS':
      case 'MAPREDUCE':
        if (App.supports.reassignMaster && hosts > 1) {
          allMasters.forEach(function (hostComponent) {
            if (App.reassignableComponents.contains(hostComponent)) {
              options.push({action: 'reassignMaster', context: hostComponent,
                'label': Em.I18n.t('services.service.actions.reassign.master').format(App.format.role(hostComponent)), disabled: false});
            }
          })
        }
      default:
        options.push({action: 'runSmokeTest', 'label': Em.I18n.t('services.service.actions.run.smoke'), disabled:disabled});
    }
    if (App.supports.hostOverrides && service.get('serviceName') !== 'GANGLIA') {
      options.push({action: 'manageConfigurationGroups', 'label': Em.I18n.t('services.service.actions.manage_configuration_groups'), disabled: false});
    }
    return options;
  }.property('controller.content', 'controller.isStopDisabled'),
  isMaintenanceActive: function() {
    return this.get('maintenance').length !== 0;
  }.property('maintenance'),
  hasConfigTab: function(){
    return this.get("controller.content.isConfigurable");
  }.property('controller.content.isConfigurable'),

  didInsertElement: function () {
    this.get('controller').setStartStopState();
  },
  service:function () {
    var svc = this.get('controller.content');
    var svcName = svc.get('serviceName');
    if (svcName) {
      switch (svcName.toLowerCase()) {
        case 'hdfs':
          svc = App.HDFSService.find().objectAt(0);
          break;
        case 'yarn':
          svc = App.YARNService.find().objectAt(0);
          break;
        case 'mapreduce':
          svc = App.MapReduceService.find().objectAt(0);
          break;
        case 'hbase':
          svc = App.HBaseService.find().objectAt(0);
          break;
        case 'flume':
          svc = App.FlumeService.find().objectAt(0);
          break;
        default:
          break;
      }
    }
    return svc;
  }.property('controller.content.serviceName').volatile()
});
<|endoftext|>