<commit_before>const MAIN_BLOCK = 'dual-listbox';

const CONTAINER_ELEMENT = 'dual-lsitbox__container';
const AVAILABLE_ELEMENT = 'dual-listbox__available';
const SELECTED_ELEMENT = 'dual-listbox__selected';
const TITLE_ELEMENT = 'dual-listbox__title';
const ITEM_ELEMENT = 'dual-listbox__item';
const BUTTONS_ELEMENT = 'dual-listbox__buttons';
const BUTTON_ELEMENT = 'dual-listbox__button';
const SEARCH_ELEMENT = 'dual-listbox__search';

const SELECTED_MODIFIER = 'dual-listbox__item--selected';

/**
 * Dual select interface allowing the user to select items from a list of provided options.
 * @class
 */
class DualListbox {
    constructor(selector, options={}) {
        this.setDefaults();
        if (this.isDomElement(selector)) {
            this.select = selector;
        } else {
            this.select = document.querySelector(selector);
        }

        this.selected = [];
        this.available = [];

        this._initOptions(options);
        this._initReusableElements();
        this._splitSelectOptions(this.select);
        this._buildDualListbox(this.select.parentNode);
        this._addActions();

        this.redraw();
    }

    /**
     * Sets the default values that can be overwritten.
     */
    setDefaults() {
        this.addEvent = null;
        this.removeEvent = null;
        this.availableTitle = 'Available options';
        this.selectedTitle = 'Selected options';
        this.addButtonText = 'add';
        this.removeButtonText = 'remove';
        this.addAllButtonText = 'add all';
        this.removeAllButtonText = 'remove all';
        this.searchPlaceholder = 'Search';
    }

    /**
     * Add the listItem to the selected list.
     *
     * @param {NodeElement} listItem
     */
    addSelected(listItem) {
        let index = this.available.indexOf(listItem);
        if (index > -1) {
            this.available.splice(index, 1);
            this.selected.push(listItem);
            this._selectOption(listItem.dataset.id);
            this.redraw();
        }
    }

    /**
     * Redraws the Dual listbox content
     */
    redraw() {
        this.updateAvailableListbox();
        this.updateSelectedListbox();
    }

    /**
     * Removes the listItem from the selected list.
     *
     * @param {NodeElement} listItem
     */
    removeSelected(listItem) {
        let index = this.selected.indexOf(listItem);
        if (index > -1) {
            this.selected.splice(index, 1);
            this.available.push(listItem);
            this._deselectOption(listItem.dataset.id);
            this.redraw();
        }
    }

    /**
     * Filters the listboxes with the given searchString.
     *
     * @param {Object} searchString
     */
    searchLists(searchString, dualListbox) {
        let items = dualListbox.querySelectorAll(`.${ITEM_ELEMENT}`);
        let lowerCaseSearchString = searchString.toLowerCase();

        for(let i = 0; i < items.length; i++) {
            let item = items[i];

            if(searchString) {
                if(item.textContent.toLowerCase().indexOf(lowerCaseSearchString) === -1) {
                    item.style.display = 'none';
                } else {
                    item.style.display = 'list-item';
                }
            } else {
                item.style.display = 'list-item';
            }
        }
    }

    /**
     * Update the elements in the availeble listbox;
     */
    updateAvailableListbox() {
        this.availebleList.innerHTML = '';
        this.availebleList.appendChild(this.availableListTitle);
        for(let i = 0; i < this.available.length; i++) {
            let listItem= this.available[i];
            this.availebleList.appendChild(listItem);
        }
    }

    /**
     * Update the elements in the selected listbox;
     */
    updateSelectedListbox() {
        this.selectedList.innerHTML = '';
        this.selectedList.appendChild(this.selectedListTitle);
        for(let i = 0; i < this.selected.length; i++) {
            let listItem= this.selected[i];
            this.selectedList.appendChild(listItem);
        }
    }

    //
    //
    // PRIVATE FUNCTIONS
    //
    //

    /**
     * Action to set all listItems to selected.
     */
    _actionAllSelected(event) {
        event.preventDefault();

        while(this.available.length > 0) {
            this.addSelected(this.available[0]);
        }
    }

    /**
     * Action to set one listItem to selected.
     */
    _actionItemSelected(event) {
        event.preventDefault();

        let selected = this.dualListbox.querySelector(`.${SELECTED_MODIFIER}`);
        if(selected) {
            this.addSelected(selected);
        }
    }

    /**
     * Action to set all listItems to available.
     */
    _actionAllDeselected(event) {
        event.preventDefault();

        while(this.selected.length > 0) {
            this.removeSelected(this.selected[0]);
        }
    }

    /**
     * Action to set one listItem to available.
     */
    _actionItemDeselected(event) {
        event.preventDefault();

        let selected = this.dualListbox.querySelector(`.${SELECTED_MODIFIER}`);
        if(selected) {
            this.removeSelected(selected);
        }
    }

    /**
     * Action when double clicked on a listItem.
     */
    _actionItemDoubleClick(listItem, event=null) {
        if(event) {
            event.preventDefault();
            event.stopPropagation();
        }

        if (this.selected.indexOf(listItem) > -1) {
            this.removeSelected(listItem);
        } else {
            this.addSelected(listItem);
        }
    }

    /**
     * Action when single clicked on a listItem.
     */
    _actionItemClick(listItem, dualListbox, event=null) {
        if(event) {
            event.preventDefault();
        }

        let items = dualListbox.querySelectorAll(`.${ITEM_ELEMENT}`);

        for(let i = 0; i < items.length; i++) {
            let value = items[i];
            if (value !== listItem) {
                value.classList.remove(SELECTED_MODIFIER);
            }
        }

        if(listItem.classList.contains(SELECTED_MODIFIER)) {
            listItem.classList.remove(SELECTED_MODIFIER);
        } else{
            listItem.classList.add(SELECTED_MODIFIER);
        }
    }

    /**
     * @Private
     * Adds the needed actions to the elements.
     */
    _addActions() {
        this._addButtonActions();
        this._addSearchActions();
    }

    /**
     * Adds the actions to the buttons that are created.
     */
    _addButtonActions() {
        this.add_all_button.addEventListener('click', (event) => this._actionAllSelected(event));
        this.add_button.addEventListener('click', (event) => this._actionItemSelected(event));
        this.remove_button.addEventListener('click', (event) => this._actionItemDeselected(event));
        this.remove_all_button.addEventListener('click', (event) => this._actionAllDeselected(event));
    }

    /**
     * Adds the click items to the listItem.
     *
     * @param {Object} listItem
     */
    _addClickActions(listItem) {
        listItem.addEventListener('dblclick', (event) => this._actionItemDoubleClick(listItem, event));
        listItem.addEventListener('click', (event) => this._actionItemClick(listItem, this.dualListbox, event));
        return listItem;
    }

    /**
     * @Private
     * Adds the actions to the search input.
     */
    _addSearchActions() {
        this.search.addEventListener('change', (event) => this.searchLists(event.target.value, this.dualListbox));
        this.search.addEventListener('keyup', (event) => this.searchLists(event.target.value, this.dualListbox));
    }

    /**
     * @Private
     * Builds the Dual listbox and makes it visible to the user.
     */
    _buildDualListbox(container) {
        this.select.style.display = 'none';

        this.dualListBoxContainer.appendChild(this.availebleList);
        this.dualListBoxContainer.appendChild(this.buttons);
        this.dualListBoxContainer.appendChild(this.selectedList);

        this.dualListbox.appendChild(this.search);
        this.dualListbox.appendChild(this.dualListBoxContainer);

        container.insertBefore(this.dualListbox, this.select);
    }

    /**
     * Creates the buttons to add/remove the selected item.
     */
    _createButtons() {
        this.buttons = document.createElement('div');
        this.buttons.classList.add(BUTTONS_ELEMENT);

        this.add_all_button = document.createElement('button');
        this.add_all_button.classList.add(BUTTON_ELEMENT);
        this.add_all_button.innerHTML = this.addAllButtonText;

        this.add_button = document.createElement('button');
        this.add_button.classList.add(BUTTON_ELEMENT);
        this.add_button.innerHTML = this.addButtonText;

        this.remove_button = document.createElement('button');
        this.remove_button.classList.add(BUTTON_ELEMENT);
        this.remove_button.innerHTML = this.removeButtonText;

        this.remove_all_button = document.createElement('button');
        this.remove_all_button.classList.add(BUTTON_ELEMENT);
        this.remove_all_button.innerHTML = this.removeAllButtonText;

        this.buttons.appendChild(this.add_all_button);
        this.buttons.appendChild(this.add_button);
        this.buttons.appendChild(this.remove_button);
        this.buttons.appendChild(this.remove_all_button);
    }

    /**
     * @Private
     * Creates the listItem out of the option.
     */
    _createListItem(option) {
        let listItem = document.createElement('li');

        listItem.classList.add(ITEM_ELEMENT);
        listItem.innerHTML = option.innerHTML;
        listItem.dataset.id = option.value;

        this._addClickActions(listItem);

        return listItem;
    }

    /**
     * @Private
     * Creates the search input.
     */
    _createSearch() {
        this.search = document.createElement('input');
        this.search.classList.add(SEARCH_ELEMENT);
        this.search.placeholder = this.searchPlaceholder;
    }

    /**
     * @Private
     * Deselects the option with the matching value
     *
     * @param {Object} value
     */
    _deselectOption(value) {
        let options = this.select.options;

        for(let i = 0; i < options.length; i++) {
            let option = options[i];
            if(option.value === value) {
                option.selected = false;
            }
        }

        if(this.removeEvent) {
            this.removeEvent(value);
        }
    }

    /**
     * @Private
     * Set the option variables to this.
     */
    _initOptions(options) {
        for(var key in options) {
            this[key] = options[key];
        }
    }

    /**
     * @Private
     * Creates all the static elements for the Dual listbox.
     */
    _initReusableElements() {
        this.dualListbox = document.createElement('div');
        this.dualListbox.classList.add(MAIN_BLOCK);
        if(this.select.id) {
            this.dualListbox.classList.add(this.select.id);
        }

        this.dualListBoxContainer = document.createElement('div');
        this.dualListBoxContainer.classList.add(CONTAINER_ELEMENT);

        this.availebleList = document.createElement('ul');
        this.availebleList.classList.add(AVAILABLE_ELEMENT);

        this.selectedList = document.createElement('ul');
        this.selectedList.classList.add(SELECTED_ELEMENT);

        this.availableListTitle = document.createElement('li');
        this.availableListTitle.classList.add(TITLE_ELEMENT);
        this.availableListTitle.innerText = this.availableTitle;

        this.selectedListTitle = document.createElement('li');
        this.selectedListTitle.classList.add(TITLE_ELEMENT);
        this.selectedListTitle.innerText = this.selectedTitle;

        this._createButtons();
        this._createSearch();
    }

    /**
     * @Private
     * Selects the option with the matching value
     *
     * @param {Object} value
     */
    _selectOption(value) {
        let options = this.select.options;

        for(let i = 0; i < options.length; i++) {
            let option = options[i];
            if(option.value === value) {
                option.selected = true;
            }
        }

        if(this.addEvent) {
            this.addEvent(value);
        }
    }

    /**
     * @Private
     * Splits the select options and places them in the correct list.
     */
    _splitSelectOptions(select) {
        let options = select.options;

        for(let i = 0; i < options.length; i++) {
            let option = options[i];
            let listItem = this._createListItem(option);

            if(option.attributes.selected) {
                this.selected.push(listItem);
            } else {
                this.available.push(listItem);
            }
        }
    }

    /**
     * @Private
     * Returns true if argument is a DOM element
     */
    isDomElement(o) {
        return (
            typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
                o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"
        );
    }
}

export default DualListbox;
export { DualListbox };
<commit_msg>Moved the empty variable declarations to the top.<commit_after>const MAIN_BLOCK = 'dual-listbox';

const CONTAINER_ELEMENT = 'dual-lsitbox__container';
const AVAILABLE_ELEMENT = 'dual-listbox__available';
const SELECTED_ELEMENT = 'dual-listbox__selected';
const TITLE_ELEMENT = 'dual-listbox__title';
const ITEM_ELEMENT = 'dual-listbox__item';
const BUTTONS_ELEMENT = 'dual-listbox__buttons';
const BUTTON_ELEMENT = 'dual-listbox__button';
const SEARCH_ELEMENT = 'dual-listbox__search';

const SELECTED_MODIFIER = 'dual-listbox__item--selected';

/**
 * Dual select interface allowing the user to select items from a list of provided options.
 * @class
 */
class DualListbox {
    constructor(selector, options={}) {
        this.setDefaults();
        this.selected = [];
        this.available = [];

        if (this.isDomElement(selector)) {
            this.select = selector;
        } else {
            this.select = document.querySelector(selector);
        }

        this._initOptions(options);
        this._initReusableElements();
        this._splitSelectOptions(this.select);
        this._buildDualListbox(this.select.parentNode);
        this._addActions();

        this.redraw();
    }

    /**
     * Sets the default values that can be overwritten.
     */
    setDefaults() {
        this.addEvent = null;
        this.removeEvent = null;
        this.availableTitle = 'Available options';
        this.selectedTitle = 'Selected options';
        this.addButtonText = 'add';
        this.removeButtonText = 'remove';
        this.addAllButtonText = 'add all';
        this.removeAllButtonText = 'remove all';
        this.searchPlaceholder = 'Search';
    }

    /**
     * Add the listItem to the selected list.
     *
     * @param {NodeElement} listItem
     */
    addSelected(listItem) {
        let index = this.available.indexOf(listItem);
        if (index > -1) {
            this.available.splice(index, 1);
            this.selected.push(listItem);
            this._selectOption(listItem.dataset.id);
            this.redraw();
        }
    }

    /**
     * Redraws the Dual listbox content
     */
    redraw() {
        this.updateAvailableListbox();
        this.updateSelectedListbox();
    }

    /**
     * Removes the listItem from the selected list.
     *
     * @param {NodeElement} listItem
     */
    removeSelected(listItem) {
        let index = this.selected.indexOf(listItem);
        if (index > -1) {
            this.selected.splice(index, 1);
            this.available.push(listItem);
            this._deselectOption(listItem.dataset.id);
            this.redraw();
        }
    }

    /**
     * Filters the listboxes with the given searchString.
     *
     * @param {Object} searchString
     */
    searchLists(searchString, dualListbox) {
        let items = dualListbox.querySelectorAll(`.${ITEM_ELEMENT}`);
        let lowerCaseSearchString = searchString.toLowerCase();

        for(let i = 0; i < items.length; i++) {
            let item = items[i];

            if(searchString) {
                if(item.textContent.toLowerCase().indexOf(lowerCaseSearchString) === -1) {
                    item.style.display = 'none';
                } else {
                    item.style.display = 'list-item';
                }
            } else {
                item.style.display = 'list-item';
            }
        }
    }

    /**
     * Update the elements in the availeble listbox;
     */
    updateAvailableListbox() {
        this.availebleList.innerHTML = '';
        this.availebleList.appendChild(this.availableListTitle);
        for(let i = 0; i < this.available.length; i++) {
            let listItem= this.available[i];
            this.availebleList.appendChild(listItem);
        }
    }

    /**
     * Update the elements in the selected listbox;
     */
    updateSelectedListbox() {
        this.selectedList.innerHTML = '';
        this.selectedList.appendChild(this.selectedListTitle);
        for(let i = 0; i < this.selected.length; i++) {
            let listItem= this.selected[i];
            this.selectedList.appendChild(listItem);
        }
    }

    //
    //
    // PRIVATE FUNCTIONS
    //
    //

    /**
     * Action to set all listItems to selected.
     */
    _actionAllSelected(event) {
        event.preventDefault();

        while(this.available.length > 0) {
            this.addSelected(this.available[0]);
        }
    }

    /**
     * Action to set one listItem to selected.
     */
    _actionItemSelected(event) {
        event.preventDefault();

        let selected = this.dualListbox.querySelector(`.${SELECTED_MODIFIER}`);
        if(selected) {
            this.addSelected(selected);
        }
    }

    /**
     * Action to set all listItems to available.
     */
    _actionAllDeselected(event) {
        event.preventDefault();

        while(this.selected.length > 0) {
            this.removeSelected(this.selected[0]);
        }
    }

    /**
     * Action to set one listItem to available.
     */
    _actionItemDeselected(event) {
        event.preventDefault();

        let selected = this.dualListbox.querySelector(`.${SELECTED_MODIFIER}`);
        if(selected) {
            this.removeSelected(selected);
        }
    }

    /**
     * Action when double clicked on a listItem.
     */
    _actionItemDoubleClick(listItem, event=null) {
        if(event) {
            event.preventDefault();
            event.stopPropagation();
        }

        if (this.selected.indexOf(listItem) > -1) {
            this.removeSelected(listItem);
        } else {
            this.addSelected(listItem);
        }
    }

    /**
     * Action when single clicked on a listItem.
     */
    _actionItemClick(listItem, dualListbox, event=null) {
        if(event) {
            event.preventDefault();
        }

        let items = dualListbox.querySelectorAll(`.${ITEM_ELEMENT}`);

        for(let i = 0; i < items.length; i++) {
            let value = items[i];
            if (value !== listItem) {
                value.classList.remove(SELECTED_MODIFIER);
            }
        }

        if(listItem.classList.contains(SELECTED_MODIFIER)) {
            listItem.classList.remove(SELECTED_MODIFIER);
        } else{
            listItem.classList.add(SELECTED_MODIFIER);
        }
    }

    /**
     * @Private
     * Adds the needed actions to the elements.
     */
    _addActions() {
        this._addButtonActions();
        this._addSearchActions();
    }

    /**
     * Adds the actions to the buttons that are created.
     */
    _addButtonActions() {
        this.add_all_button.addEventListener('click', (event) => this._actionAllSelected(event));
        this.add_button.addEventListener('click', (event) => this._actionItemSelected(event));
        this.remove_button.addEventListener('click', (event) => this._actionItemDeselected(event));
        this.remove_all_button.addEventListener('click', (event) => this._actionAllDeselected(event));
    }

    /**
     * Adds the click items to the listItem.
     *
     * @param {Object} listItem
     */
    _addClickActions(listItem) {
        listItem.addEventListener('dblclick', (event) => this._actionItemDoubleClick(listItem, event));
        listItem.addEventListener('click', (event) => this._actionItemClick(listItem, this.dualListbox, event));
        return listItem;
    }

    /**
     * @Private
     * Adds the actions to the search input.
     */
    _addSearchActions() {
        this.search.addEventListener('change', (event) => this.searchLists(event.target.value, this.dualListbox));
        this.search.addEventListener('keyup', (event) => this.searchLists(event.target.value, this.dualListbox));
    }

    /**
     * @Private
     * Builds the Dual listbox and makes it visible to the user.
     */
    _buildDualListbox(container) {
        this.select.style.display = 'none';

        this.dualListBoxContainer.appendChild(this.availebleList);
        this.dualListBoxContainer.appendChild(this.buttons);
        this.dualListBoxContainer.appendChild(this.selectedList);

        this.dualListbox.appendChild(this.search);
        this.dualListbox.appendChild(this.dualListBoxContainer);

        container.insertBefore(this.dualListbox, this.select);
    }

    /**
     * Creates the buttons to add/remove the selected item.
     */
    _createButtons() {
        this.buttons = document.createElement('div');
        this.buttons.classList.add(BUTTONS_ELEMENT);

        this.add_all_button = document.createElement('button');
        this.add_all_button.classList.add(BUTTON_ELEMENT);
        this.add_all_button.innerHTML = this.addAllButtonText;

        this.add_button = document.createElement('button');
        this.add_button.classList.add(BUTTON_ELEMENT);
        this.add_button.innerHTML = this.addButtonText;

        this.remove_button = document.createElement('button');
        this.remove_button.classList.add(BUTTON_ELEMENT);
        this.remove_button.innerHTML = this.removeButtonText;

        this.remove_all_button = document.createElement('button');
        this.remove_all_button.classList.add(BUTTON_ELEMENT);
        this.remove_all_button.innerHTML = this.removeAllButtonText;

        this.buttons.appendChild(this.add_all_button);
        this.buttons.appendChild(this.add_button);
        this.buttons.appendChild(this.remove_button);
        this.buttons.appendChild(this.remove_all_button);
    }

    /**
     * @Private
     * Creates the listItem out of the option.
     */
    _createListItem(option) {
        let listItem = document.createElement('li');

        listItem.classList.add(ITEM_ELEMENT);
        listItem.innerHTML = option.innerHTML;
        listItem.dataset.id = option.value;

        this._addClickActions(listItem);

        return listItem;
    }

    /**
     * @Private
     * Creates the search input.
     */
    _createSearch() {
        this.search = document.createElement('input');
        this.search.classList.add(SEARCH_ELEMENT);
        this.search.placeholder = this.searchPlaceholder;
    }

    /**
     * @Private
     * Deselects the option with the matching value
     *
     * @param {Object} value
     */
    _deselectOption(value) {
        let options = this.select.options;

        for(let i = 0; i < options.length; i++) {
            let option = options[i];
            if(option.value === value) {
                option.selected = false;
            }
        }

        if(this.removeEvent) {
            this.removeEvent(value);
        }
    }

    /**
     * @Private
     * Set the option variables to this.
     */
    _initOptions(options) {
        for(var key in options) {
            this[key] = options[key];
        }
    }

    /**
     * @Private
     * Creates all the static elements for the Dual listbox.
     */
    _initReusableElements() {
        this.dualListbox = document.createElement('div');
        this.dualListbox.classList.add(MAIN_BLOCK);
        if(this.select.id) {
            this.dualListbox.classList.add(this.select.id);
        }

        this.dualListBoxContainer = document.createElement('div');
        this.dualListBoxContainer.classList.add(CONTAINER_ELEMENT);

        this.availebleList = document.createElement('ul');
        this.availebleList.classList.add(AVAILABLE_ELEMENT);

        this.selectedList = document.createElement('ul');
        this.selectedList.classList.add(SELECTED_ELEMENT);

        this.availableListTitle = document.createElement('li');
        this.availableListTitle.classList.add(TITLE_ELEMENT);
        this.availableListTitle.innerText = this.availableTitle;

        this.selectedListTitle = document.createElement('li');
        this.selectedListTitle.classList.add(TITLE_ELEMENT);
        this.selectedListTitle.innerText = this.selectedTitle;

        this._createButtons();
        this._createSearch();
    }

    /**
     * @Private
     * Selects the option with the matching value
     *
     * @param {Object} value
     */
    _selectOption(value) {
        let options = this.select.options;

        for(let i = 0; i < options.length; i++) {
            let option = options[i];
            if(option.value === value) {
                option.selected = true;
            }
        }

        if(this.addEvent) {
            this.addEvent(value);
        }
    }

    /**
     * @Private
     * Splits the select options and places them in the correct list.
     */
    _splitSelectOptions(select) {
        let options = select.options;

        for(let i = 0; i < options.length; i++) {
            let option = options[i];
            let listItem = this._createListItem(option);

            if(option.attributes.selected) {
                this.selected.push(listItem);
            } else {
                this.available.push(listItem);
            }
        }
    }

    /**
     * @Private
     * Returns true if argument is a DOM element
     */
    isDomElement(o) {
        return (
            typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
                o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"
        );
    }
}

export default DualListbox;
export { DualListbox };
<|endoftext|>


<commit_before>export { FiltersArray_One };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as ActivationEscaping from "../ActivationEscaping.js";
import * as BoundsArraySet from "../BoundsArraySet.js";
import * as Weights from "../../Unpacker/Weights.js";

//!!! ...unfinished... (2022/07/26)
// Embedding assert if input bounds per channel larger than vocabulary count per table.

//!!! ...unfinished... (2022/07/25)
// Perhaps, provide a parameter control whether different input channel uses the same
// or different look-up (i.e. vocabulary) table.

/**
 * A large table which is composed of all vocabulary table of every input channel. It is
 * mainly used by Embedding.AddGatherReshape.
 *
 *
 * Embedding could achieve non-linear mapping (just like any perceptron). But it is achieved by lookup table (instead
 * of weighted sum, bias and activation function). This implies:
 *   - It may use more (CPU or GPU) memory, but may use less (CPU or GPU) computation.
 *   - It can only achieve channel expansion, and can not achieve channel aggregation. (because no weighted sum)
 *   - It can only represent context-independent (not context-dependent) information. (because no weighted sum)
 *   - It can only handle integer input (i.e. int32, not float32).
 *
 * It is useful as the first layer of text or image processing because their inputs are all integer (e.g. character codes,
 * word indices, color codes, etc). And, the first layer only needs carry context-independent information (and all the other
 * layers after it will produce context-dependent information).
 *
 * This object always accepts tensor3d (dtype = int32).
 *   - The axis 0 is height. (Image height) (Text lines and usually only 1 line.)
 *   - The axis 1 is width. (Image width) (Text length (e.g. character count).)
 *   - The axis 2 is channel. (Image color channel) (Text character code channel and usually only 1 channel.)
 *
 * An embedding layer contains one params (this.params) and inChannels embedding vocabulary tables.
 *   - Every input channel has one embedding vocabulary table.
 *   - Every embedding vocabulary table has vocabularyCountPerInputChannel vocabularies.
 *   - Every vocabulary has channelMultiplier embedding channels.
 *
 *
 *
 * @member {boolean} bInitOk
 *  If true, this object initialized (i.e. initer()) successfully.
 *
 * @member {number} weightElementOffsetBegin
 *   The position which is started (inclusive) to extract from inputWeightArray by initer().
 *
 * @member {number} weightElementOffsetEnd
 *   The position which is ended to (non-inclusive) extract from inputWeightArray by initer(). Where to extract next weights.
 * Only meaningful when ( this.bInitOk == true ).
 *
 * @param {number} input_channelCount
 *   The input channel count.
 *
 * @member {number} channelMultiplier
 *   Every vocabulary will have how many embedding channels. Every input channel will be expanded into so many
 * embedding channels. It could be viewed as embeddingChannelCountPerInputChannel.
 *
 * @member {number} vocabularyCountPerInputChannel
 *   Every input channel will have how many vocabularies. This is also vocabulary count per vocabulary table (because
 * every input channel has a vocabulary table). For an image data (R-G-B-A four channels), there will be 256
 * vocabularies per input channel because every channel is represented by one byte (8 bits) which has 2^8 = 256 kinds
 * of possible values.
 *
 * @member {boolean} bEmbedVocabularyId
 *   If true, one of embedding channels will be an auto-generated vocabulary id (i.e. 0, 1, 2, ...). So only
 * ( channelMultiplier - 1 ) embedding channels will be extracted from inputWeightArray. The extra vocabulary id
 * channel achieves residual connection. Residual connection means apply_and_destroy_or_keep() will append (concatenate)
 * input to output. Since apply_and_destroy_or_keep()'s input is just vocabulary id (one channel or multiple channels),
 * pre-embedded vocabulary id inside the embedding table acheives the same effect by less computation (but more memory).
 *
 * @member {number} output_channelCount
 *   Output channel count. It is always depending on channelMultiplier and equals to ( inChannels * channelMultiplier ).
 *
 * @member {BoundsArraySet.InputsOutputs} boundsArraySet
 *   The element value bounds (per channel) of this embedding.
 *
 * @see Weight.Root
 *
 */
class FiltersArray_One extends Weights.Root {

  /**
   * Used as default Embedding.FiltersArray_One provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Embedding.FiltersArray_One.Pool", FiltersArray_One, FiltersArray_One.setAsConstructor );

  /**
   *
   */
  constructor(
    input_channelCount,
    channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
  ) {
    super();
    FiltersArray_One.setAsConstructor_self.call( this,
      input_channelCount,
      channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
    );
  }

  /** @override */
  static setAsConstructor(
    input_channelCount,
    channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
  ) {
    super.setAsConstructor();
    FiltersArray_One.setAsConstructor_self.call( this,
      input_channelCount,
      channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
    );
    return this;
  }

  /** @override */
  static setAsConstructor_self(
    input_channelCount,
    channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
  ) {
    this.input_channelCount = input_channelCount;
    this.channelMultiplier = channelMultiplier;
    this.vocabularyCountPerInputChannel = vocabularyCountPerInputChannel;
    this.bEmbedVocabularyId = bEmbedVocabularyId;

    // this.boundsArraySet = BoundsArraySet.InputsOutputs.Pool.get_or_create_by();
  }

  /** @override */
  disposeResources() {

!!! ...unfinished... (2022/07/27)

    if ( this.filtersArray ) {
      this.filtersArray.disposeResources_and_recycleToPool();
      this.filtersArray = null;
    }

    super.disposeResources();
  }

  /**
   * Generator for initializing this object.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray
   *   The element value bounds (per channel) of input. Usually, it is The .output of the previous convolution-bias-activation value bounds
   * set of this pointwise convolution. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @return {boolean}
   *   Return true, if successfully. Return false, if failed.
   *
   */
  init( inputWeightArray, weightElementOffsetBegin, inputScaleBoundsArray ) {

    if ( this.input_channelCount != inputScaleBoundsArray.length )
      throw Error( `Embedding.FiltersArray_One.init(): `
        + `input_channelCount ( ${this.input_channelCount} ) should be the same as `
        + `output_channelCount of previous operation ( ${inputScaleBoundsArray.length} ).`
      );

    if ( !inputScaleBoundsArray.scaleArraySet.undo.is_all_EQ_byN( 1 ) )
      throw Error( `Embedding.FiltersArray_One.init(): `
        + `The .output.scaleArraySet.undo ( ${inputScaleBoundsArray.scaleArraySet.undo.scales} ) `
        + `of previous operation `
        + `should be all one (i.e. should not have activation escaping scaling).`
      );

    let vocabularyIdMax = this.vocabularyCountPerInputChannel - 1; // maximum legal vocabulary id.
    if ( !inputScaleBoundsArray.boundsArray.is_all_IN_byLowerUpper( 0, vocabularyIdMax ) )
      throw Error( `Embedding.FiltersArray_One.init(): `
        + `The .output.boundsArray ( ${inputScaleBoundsArray.boundsArray} ) `
        + `of previous operation `
        + `should be all within [ 0, ${vocabularyIdMax} ].`
      );

  }

}
<commit_msg>Embedding_FiltersArray_One<commit_after>export { Embedding_FiltersArray_One as FiltersArray_One };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
//import * as ActivationEscaping from "../ActivationEscaping.js";
//import * as BoundsArraySet from "../BoundsArraySet.js";
import { FiltersArray_Base } from "./Embedding_FiltersArray_One.js";

//!!! ...unfinished... (2022/07/25)
// Perhaps, provide a parameter control whether different input channel uses the same
// or different look-up (i.e. vocabulary) table.

/**
 * A large table which is composed of all vocabulary table of every input channel. It is
 * mainly used by Embedding.AddGatherReshape.
 *
 *
 *
 *
 * @member {Racyclable.Array} filtersArray
 *   The embedding vocabulary look-up table. It is composed by merging all input channels'
 * vocabulary.
 *
 * @see Embedding.FiltersArray_Base
 *
 */
class Embedding_FiltersArray_One extends FiltersArray_Base {

  /**
   * Used as default Embedding.FiltersArray_One provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Embedding.FiltersArray_One.Pool",
    Embedding_FiltersArray_One, Embedding_FiltersArray_One.setAsConstructor );

  /**
   *
   */
   constructor(
    input_height, input_width, input_channelCount,
    channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
  ) {
    super(
      input_height, input_width, input_channelCount,
      channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
    );
    Embedding_FiltersArray_Base.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor(
    input_channelCount,
    channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
  ) {
    super.setAsConstructor(
      input_height, input_width, input_channelCount,
      channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
    );
    Embedding_FiltersArray_Base.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor_self() {
  }

  /** @override */
  disposeResources() {

!!! ...unfinished... (2022/07/27)

    if ( this.filtersArray ) {
      this.filtersArray.disposeResources_and_recycleToPool();
      this.filtersArray = null;
    }

    super.disposeResources();
  }

  /**
   * Generator for initializing this object.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray
   *   The element value bounds (per channel) of input. Usually, it is The .output of the previous convolution-bias-activation value bounds
   * set of this pointwise convolution. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @return {boolean}
   *   Return true, if successfully. Return false, if failed.
   *
   */
  init( inputWeightArray, weightElementOffsetBegin, inputScaleBoundsArray ) {

    // Calcualte weights extracting beginning and ending position.
    if ( !super.init( inputWeightArray, weightElementOffsetBegin, this.tensorWeightCountExtracted ) ) {
      return false;  // e.g. input array does not have enough data.
    }

//!!! ...unfinished... (2022/07/27) filtersArray

    return true;
  }

}
<|endoftext|>


<commit_before>

// Detects whether input type="file" is available on the platform
// E.g. iOS < 6 and some android version don't support this

//  It's useful if you want to hide the upload feature of your app on devices that
//  don't support it (iphone, ipad, etc).

Modernizr.addTest('fileinput', function() {
    var elem = document.createElement('input');
    elem.type = 'file';
    return !elem.disabled;
});
<commit_msg>Added fileinput test mobile UA blacklist for issue #772<commit_after>// Detects whether input type="file" is available on the platform
// E.g. iOS < 6 and some android version don't support this

//  It's useful if you want to hide the upload feature of your app on devices that
//  don't support it (iphone, ipad, etc).

Modernizr.addTest('fileinput', function() {
    if(navigator.userAgent.match(/(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0)|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|Pre\/1.2|Kindle\/(1.0|2.0|2.5|3.0))/)) {
        return false;
    }
    var elem = document.createElement('input');
    elem.type = 'file';
    return !elem.disabled;
});
<|endoftext|>


<commit_before>var attributeCount = 0;

var addLabel = function () {
    if (!validateInputs()) {
        return;
    }
    var attributes = getCustomAttributesArray();
    if (attributes != null) {
        $('#add-label-btn').buttonLoader('start');
        jagg.post("/site/blocks/label/label-add/ajax/label-edit.jag", {
            action: $('#action').val(),
            labelName: $('#labelName').val().trim(),
            uuid: $('#uuid').val(),
            description: htmlEscape($('#description').val()),
            attributes: JSON.stringify(attributes)
        }, function (result) {
            if (result.error == false) {
                location.href = 'label-list'
            } else {
                $('#add-label-btn').buttonLoader('stop');
                jagg.message({ content: result.message, type: "error" });
            }
        },
            "json");
    }
};

var getCustomAttributesArray = function () {
    customAttributesArray = new Array();
    var hostValid = "At least one host is required";
    $('#custom-attribute-tbody tr').each(function () {
        var attributeValue = $(this).find('input[name^=attributeValue]').val();
        var attributeObj = {};
        attributeObj.value = attributeValue;
        customAttributesArray.push(attributeObj);
    });
    if (customAttributesArray.length == 0) {
        document.getElementById("mandate-host").innerHTML = hostValid;
        return null;
    }
    return customAttributesArray;
}

function removeCustomAttribute(count) {
    $('#attribute' + count).remove();
}

function htmlEscape(str) {
    if (str == null || str == "") {
        return "";
    }
    return String(str)
        .replace(/&/g, '&')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/</g, '<')
        .replace(/>/g, '>');
}

function populateCustomerAttributes(attributesList) {
    var attributes = attributesList;
    var tBody = $('#custom-attribute-tbody');
    if (attributes != null) {
        $.each(attributes, function (index, value) {
            ++attributeCount;
            addCustomAttributeInitially(tBody, attributeCount, index, value);
        });
    }
}

function addCustomAttribute(element, count) {
    var elementId = element.attr('id');
    element.parent().append(
        '
' +
        '

	' +
        '<input type="text" class="form-control" id="attributeValue' + count + '" name="attributeValue' + count + '" placeholder="Value"/>	' +
        '  ' +
        '  		' +
        '
'
    );
}

function addCustomAttributeInitially(element, count, name, value) {
    var elementId = element.attr('id');
    element.parent().append(
        '
' +
        '

	' +
        '<input type="text" class="form-control" id="attributeValue' + count + '" name="attributeValue' + count + '" />	' +
        '  ' +
        '  	' +
        '
'
    );
    $('#attributeValue' + count).val(value);
}

$(document).ready(function () {
    $('#add-attribute-btn').on('click', function () {
        document.getElementById("mandate-host").innerHTML = "";
        ++attributeCount;
        var tBody = $('#custom-attribute-tbody');
        addCustomAttribute(tBody, attributeCount);
    });

});

function validateInput(text, element, errorMsg) {
    var elementId = element.attr('id');
    text = text.trim();
    if (text == "") {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + errorMsg + '');
        return false;
    } else {
        $('#label' + elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}

function validateLength(text, element, errorMsg) {
    var elementId = element.attr('id');
    text = text.trim();
    if(text.length > 255) {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + errorMsg + '');
        return false;
    } else {
        $('#label' + elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}

function validateInputCharactors(text, element, errorMsg) {
    var elementId = element.attr('id');
    var illegalChars = /([~!&@#;%^*+={}$\|\\<>\"\',])/;
    text = text.trim();
    if (illegalChars.test(text)) {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + errorMsg + '');
        return false;
    } else {
        $('#label' + elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}

function validateAttributesInput(text, element, requiredMsg, invalidErrorMsg) {
    var elementId = element.attr('id');
    text = text.trim();
    var illegalChars = /([~!&@#;%^*+={}\|\\<>\"\',])/;
    if (text == "") {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + requiredMsg + '');
        return false;
    } else if (text.match(illegalChars)) {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + invalidErrorMsg + '');
        return false;
    } else if(text.length > 255){
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + invalidErrorMsg + '');
    } else {
        $('#label' + elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}

function validateInputs() {
    //validate name
    var requiredMsg = $('#errorMsgRequired').val();
    var invalidErrorMsg = $('#errorMessageInvalid').val();
    var illegalChars = $('#errorMessageIllegalChar').val();
    var errorHasSpacesMsg = $('#errorMessageSpaces').val();
    var lengthIsTooLong = $('#errorMessageTooLengthy').val();
    var labelName = $('#labelName');
    var labelNameTxt = labelName.val();

    if (!validateInput(labelNameTxt, labelName, requiredMsg)) {
        return false;
    }
    if (!validateLength(labelNameTxt, labelName, lengthIsTooLong)) {
            return false;
    }
    if (!validateInputCharactors(labelNameTxt, labelName, illegalChars)) {
        return false;
    }
    if (!validateForSpaces(labelNameTxt, labelName, errorHasSpacesMsg)) {
        return false;
    }
    var isInvalidAttribute = false;
    $('#custom-attribute-tbody tr').each(function () {
        var attributeValueElement = $(this).find('input[name^=attributeValue]');
        var attributeValue = attributeValueElement.val();
        if (!validateAttributesInput(attributeValue, attributeValueElement, requiredMsg, invalidErrorMsg)) {
            isInvalidAttribute = true;
            return false;
        }
    });
    if (isInvalidAttribute) {
        return false;
    }
    return true;
}

function validateForSpaces(text, element, errorMsg) {
    var elementId = element.attr('id');
    text = text.trim();
    if(text.indexOf(' ') >= 0) {
        element.css("border", "1px solid red");
        $('#label'+elementId).remove();
        element.parent().append('' + errorMsg + '');
        return false;
    } else {
        $('#label'+elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}
<commit_msg>fix formatting issue in edit.js<commit_after>var attributeCount = 0;

var addLabel = function () {
    if (!validateInputs()) {
        return;
    }
    var attributes = getCustomAttributesArray();
    if (attributes != null) {
        $('#add-label-btn').buttonLoader('start');
        jagg.post("/site/blocks/label/label-add/ajax/label-edit.jag", {
            action: $('#action').val(),
            labelName: $('#labelName').val().trim(),
            uuid: $('#uuid').val(),
            description: htmlEscape($('#description').val()),
            attributes: JSON.stringify(attributes)
        }, function (result) {
            if (result.error == false) {
                location.href = 'label-list'
            } else {
                $('#add-label-btn').buttonLoader('stop');
                jagg.message({ content: result.message, type: "error" });
            }
        },
            "json");
    }
};

var getCustomAttributesArray = function () {
    customAttributesArray = new Array();
    var hostValid = "At least one host is required";
    $('#custom-attribute-tbody tr').each(function () {
        var attributeValue = $(this).find('input[name^=attributeValue]').val();
        var attributeObj = {};
        attributeObj.value = attributeValue;
        customAttributesArray.push(attributeObj);
    });
    if (customAttributesArray.length == 0) {
        document.getElementById("mandate-host").innerHTML = hostValid;
        return null;
    }
    return customAttributesArray;
}

function removeCustomAttribute(count) {
    $('#attribute' + count).remove();
}

function htmlEscape(str) {
    if (str == null || str == "") {
        return "";
    }
    return String(str)
        .replace(/&/g, '&')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/</g, '<')
        .replace(/>/g, '>');
}

function populateCustomerAttributes(attributesList) {
    var attributes = attributesList;
    var tBody = $('#custom-attribute-tbody');
    if (attributes != null) {
        $.each(attributes, function (index, value) {
            ++attributeCount;
            addCustomAttributeInitially(tBody, attributeCount, index, value);
        });
    }
}

function addCustomAttribute(element, count) {
    var elementId = element.attr('id');
    element.parent().append(
        '
' +
        '

	' +
        '<input type="text" class="form-control" id="attributeValue' + count + '" name="attributeValue' + count + '" placeholder="Value"/>	' +
        '  ' +
        '  		' +
        '
'
    );
}

function addCustomAttributeInitially(element, count, name, value) {
    var elementId = element.attr('id');
    element.parent().append(
        '
' +
        '

	' +
        '<input type="text" class="form-control" id="attributeValue' + count + '" name="attributeValue' + count + '" />	' +
        '  ' +
        '  	' +
        '
'
    );
    $('#attributeValue' + count).val(value);
}

$(document).ready(function () {
    $('#add-attribute-btn').on('click', function () {
        document.getElementById("mandate-host").innerHTML = "";
        ++attributeCount;
        var tBody = $('#custom-attribute-tbody');
        addCustomAttribute(tBody, attributeCount);
    });

});

function validateInput(text, element, errorMsg) {
    var elementId = element.attr('id');
    text = text.trim();
    if (text == "") {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + errorMsg + '');
        return false;
    } else {
        $('#label' + elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}

function validateLength(text, element, errorMsg) {
    var elementId = element.attr('id');
    text = text.trim();
    if (text.length > 255) {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + errorMsg + '');
        return false;
    } else {
        $('#label' + elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}

function validateInputCharactors(text, element, errorMsg) {
    var elementId = element.attr('id');
    var illegalChars = /([~!&@#;%^*+={}$\|\\<>\"\',])/;
    text = text.trim();
    if (illegalChars.test(text)) {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + errorMsg + '');
        return false;
    } else {
        $('#label' + elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}

function validateAttributesInput(text, element, requiredMsg, invalidErrorMsg) {
    var elementId = element.attr('id');
    text = text.trim();
    var illegalChars = /([~!&@#;%^*+={}\|\\<>\"\',])/;
    if (text == "") {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + requiredMsg + '');
        return false;
    } else if (text.match(illegalChars)) {
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + invalidErrorMsg + '');
        return false;
    } else if(text.length > 255){
        element.css("border", "1px solid red");
        $('#label' + elementId).remove();
        element.parent().append('' + invalidErrorMsg + '');
    } else {
        $('#label' + elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}

function validateInputs() {
    //validate name
    var requiredMsg = $('#errorMsgRequired').val();
    var invalidErrorMsg = $('#errorMessageInvalid').val();
    var illegalChars = $('#errorMessageIllegalChar').val();
    var errorHasSpacesMsg = $('#errorMessageSpaces').val();
    var lengthIsTooLong = $('#errorMessageTooLengthy').val();
    var labelName = $('#labelName');
    var labelNameTxt = labelName.val();

    if (!validateInput(labelNameTxt, labelName, requiredMsg)) {
        return false;
    }
    if (!validateLength(labelNameTxt, labelName, lengthIsTooLong)) {
            return false;
    }
    if (!validateInputCharactors(labelNameTxt, labelName, illegalChars)) {
        return false;
    }
    if (!validateForSpaces(labelNameTxt, labelName, errorHasSpacesMsg)) {
        return false;
    }
    var isInvalidAttribute = false;
    $('#custom-attribute-tbody tr').each(function () {
        var attributeValueElement = $(this).find('input[name^=attributeValue]');
        var attributeValue = attributeValueElement.val();
        if (!validateAttributesInput(attributeValue, attributeValueElement, requiredMsg, invalidErrorMsg)) {
            isInvalidAttribute = true;
            return false;
        }
    });
    if (isInvalidAttribute) {
        return false;
    }
    return true;
}

function validateForSpaces(text, element, errorMsg) {
    var elementId = element.attr('id');
    text = text.trim();
    if(text.indexOf(' ') >= 0) {
        element.css("border", "1px solid red");
        $('#label'+elementId).remove();
        element.parent().append('' + errorMsg + '');
        return false;
    } else {
        $('#label'+elementId).remove();
        element.css("border", "1px solid #cccccc");
        return true;
    }
}
<|endoftext|>


<commit_before>(function ($, $document, gAuthor) {

    var consoleToAreaWidthRatio = 0.9,
        consoleToAreaHeightRatio = 0.5;

    var sizeEditor = function () {

        var defaultHeight = $('#consolearea').height() * consoleToAreaHeightRatio;
        $('#resizable').height(Lockr.get('editorHeight', defaultHeight))

        editor.resize();
    };

    var styleEditor = function () {
        window.editor = ace.edit("editor");
        editor.setTheme("ace/theme/twilight");
        (function () {
            editor.session.setMode("ace/mode/groovy");
        }());
    };

    var showEditor = function () {
        var lastScript = Lockr.get('lastScript');
        if (lastScript) {
            editor.setValue(lastScript, -1);
        }

        $('#consolearea').show();
        $('#formarea').hide();
    };

    var hideAllPanels = function () {
        $(".info-error, .info-result, .info-output, .info-meta").hide();
    };

    var resetAllMessages = function () {
        clearInfoPanel();
        hideAllPanels();
    };

    var clearInfoPanel = function () {
        $(".info-message").empty();
    };

    var clearEditor = function () {
        Lockr.rm('lastScript');
        editor.setValue("");
    };

    var initializeEditorToolbar = function(){
        $('.create-new').click(function () {
            if ($(this).hasClass('disabled')) {
                return;
            }

            // clear message and local storage for this editor session
            Lockr.rm('lastScript');

            resetAllMessages();
            editor.getSession().setValue('def resource = resourceResolver.getResource("/content"); \nprintln resource.path');
            printToMeta("New document created.");
        });

        $('.execute-script').click(function () {
            console.log("Triggered script execution... ");
            if ($(this).hasClass('disabled')) {
                return;
            }

            clearInfoPanel();

            var script = editor.getSession().getValue();
            if (script.length) {

                editor.setReadOnly(true);
                var posting = $.post(CQ.shared.HTTP.getContextPath() + '/bin/asconsole/groovy/post.json', {
                    script: script
                });

                posting.done(function (xhrMessage) {
                    console.log(xhrMessage);

                    clearInfoPanel();

                    if (xhrMessage.failed) {
                        setPanelVisibility(true, true, true);
                        $(".info-message-error").append(xhrMessage.error);
                    } else {
                        setPanelVisibility(true, true, false);
                    }

                    if (xhrMessage.result && xhrMessage.result !== "null" && xhrMessage.result !== "") {
                        $(".info-message-result").append(xhrMessage.result);
                    } else {
                        $(".info-message-result").append("No result");
                    }

                    if (xhrMessage.output && xhrMessage.output !== "null" && xhrMessage.output !== "") {
                        $(".info-message-output").append(xhrMessage.output);
                    } else {
                        $(".info-message-output").append("No output");
                    }
                    printToMeta(xhrMessage.executionTime + " ms");
                });

                posting.fail(function (xhrMessage) {
                    console.log("Fail");
                    console.log(xhrMessage);

                    setPanelVisibility(true, true, true);
                    if (xhrMessage.status == 403) {
                        //missing permissions
                        console.log("Missing permissions")
                    } else {
                        console.log("Unable to execute script");
                    }
                });

                posting.always(function () {
                    editor.setReadOnly(false);
                });
            }

            focusEndOfEditorDocument();
        });

        $('.clear-editor').click(function () {
            clearInfoPanel();
            clearEditor();
            hideAllPanels();

            printToMeta("Editor and localStorage [lastScript] cleared");

            focusEndOfEditorDocument();
        });

        $('.save-script').click(function () {
            clearInfoPanel();
            var script = editor.getSession().getValue()
            saveScriptToLocalStore(script);
            // TODO now open modal to allow saving the node
        });
    };

    var saveScriptToLocalStore = function (script) {
        Lockr.set('lastScript', script);
        printToMeta("Script saved to localStorage var [lastScript]");
    };

    var focusEndOfEditorDocument = function(){

        editor.focus();
        var session = editor.getSession();
        var count = session.getLength();

        editor.gotoLine(count, session.getLine(count-1).length);
    }

    setPanelVisibility = function (result, output, error) {
        if (result) {
            $(".info-result").show();
        } else {
            $(".info-result").hide();
        }

        if (output) {
            $(".info-output").show();
        } else {
            $(".info-output").hide();
        }

        if (error) {
            $(".info-error").show();
        } else {
            $(".info-error").hide();
        }
    };

    var printToMeta = function(message) {
        window.console.log(message);
        $(".info-meta").show();
        $(".info-meta").fadeIn('slow');
        $(".info-message-meta").text(message);
        setTimeout(function () {
            $(".info-meta").fadeOut('slow');
            $(".info-meta").hide();
        }, 3500);
    };

    $(document).ready(function () {
        console.log("Loading editor... ");
        hideAllPanels();
        styleEditor();
        sizeEditor();
        showEditor();
        initializeEditorToolbar();
        printToMeta("Editor has been successfully loaded... ");
    });
})
(Granite.$, $(document), Granite.author);
/*
 AemScriptConsole.localStorage = function () {

 }

 $(function () {

 AemScriptConsole.initEditor();
 AemScriptConsole.initTheme();
 AemScriptConsole.initApplicationToolbar();
 AemScriptConsole.initEditorToolbarActions();
 AemScriptConsole.initFormToolbarActions();

 });*/<commit_msg>Removed obsolete initilization code<commit_after>(function ($, $document, gAuthor) {

    var consoleToAreaWidthRatio = 0.9,
        consoleToAreaHeightRatio = 0.5;

    var sizeEditor = function () {

        var defaultHeight = $('#consolearea').height() * consoleToAreaHeightRatio;
        $('#resizable').height(Lockr.get('editorHeight', defaultHeight))

        editor.resize();
    };

    var styleEditor = function () {
        window.editor = ace.edit("editor");
        editor.setTheme("ace/theme/twilight");
        (function () {
            editor.session.setMode("ace/mode/groovy");
        }());
    };

    var showEditor = function () {
        var lastScript = Lockr.get('lastScript');
        if (lastScript) {
            editor.setValue(lastScript, -1);
        }

        $('#consolearea').show();
        $('#formarea').hide();
    };

    var hideAllPanels = function () {
        $(".info-error, .info-result, .info-output, .info-meta").hide();
    };

    var resetAllMessages = function () {
        clearInfoPanel();
        hideAllPanels();
    };

    var clearInfoPanel = function () {
        $(".info-message").empty();
    };

    var clearEditor = function () {
        Lockr.rm('lastScript');
        editor.setValue("");
    };

    var initializeEditorToolbar = function(){
        $('.create-new').click(function () {
            if ($(this).hasClass('disabled')) {
                return;
            }

            // clear message and local storage for this editor session
            Lockr.rm('lastScript');

            resetAllMessages();
            editor.getSession().setValue('def resource = resourceResolver.getResource("/content"); \nprintln resource.path');
            printToMeta("New document created.");
        });

        $('.execute-script').click(function () {
            console.log("Triggered script execution... ");
            if ($(this).hasClass('disabled')) {
                return;
            }

            clearInfoPanel();

            var script = editor.getSession().getValue();
            if (script.length) {

                editor.setReadOnly(true);
                var posting = $.post(CQ.shared.HTTP.getContextPath() + '/bin/asconsole/groovy/post.json', {
                    script: script
                });

                posting.done(function (xhrMessage) {
                    console.log(xhrMessage);

                    clearInfoPanel();

                    if (xhrMessage.failed) {
                        setPanelVisibility(true, true, true);
                        $(".info-message-error").append(xhrMessage.error);
                    } else {
                        setPanelVisibility(true, true, false);
                    }

                    if (xhrMessage.result && xhrMessage.result !== "null" && xhrMessage.result !== "") {
                        $(".info-message-result").append(xhrMessage.result);
                    } else {
                        $(".info-message-result").append("No result");
                    }

                    if (xhrMessage.output && xhrMessage.output !== "null" && xhrMessage.output !== "") {
                        $(".info-message-output").append(xhrMessage.output);
                    } else {
                        $(".info-message-output").append("No output");
                    }
                    printToMeta(xhrMessage.executionTime + " ms");
                });

                posting.fail(function (xhrMessage) {
                    console.log("Fail");
                    console.log(xhrMessage);

                    setPanelVisibility(true, true, true);
                    if (xhrMessage.status == 403) {
                        //missing permissions
                        console.log("Missing permissions")
                    } else {
                        console.log("Unable to execute script");
                    }
                });

                posting.always(function () {
                    editor.setReadOnly(false);
                });
            }

            focusEndOfEditorDocument();
        });

        $('.clear-editor').click(function () {
            clearInfoPanel();
            clearEditor();
            hideAllPanels();

            printToMeta("Editor and localStorage [lastScript] cleared");

            focusEndOfEditorDocument();
        });

        $('.save-script').click(function () {
            clearInfoPanel();
            var script = editor.getSession().getValue()
            saveScriptToLocalStore(script);
            // TODO now open modal to allow saving the node
        });
    };

    var saveScriptToLocalStore = function (script) {
        Lockr.set('lastScript', script);
        printToMeta("Script saved to localStorage var [lastScript]");
    };

    var focusEndOfEditorDocument = function(){

        editor.focus();
        var session = editor.getSession();
        var count = session.getLength();

        editor.gotoLine(count, session.getLine(count-1).length);
    }

    setPanelVisibility = function (result, output, error) {
        if (result) {
            $(".info-result").show();
        } else {
            $(".info-result").hide();
        }

        if (output) {
            $(".info-output").show();
        } else {
            $(".info-output").hide();
        }

        if (error) {
            $(".info-error").show();
        } else {
            $(".info-error").hide();
        }
    };

    var printToMeta = function(message) {
        window.console.log(message);
        $(".info-meta").show();
        $(".info-meta").fadeIn('slow');
        $(".info-message-meta").text(message);
        setTimeout(function () {
            $(".info-meta").fadeOut('slow');
            $(".info-meta").hide();
        }, 3500);
    };

    $(document).ready(function () {
        console.log("Loading editor... ");
        hideAllPanels();
        styleEditor();
        sizeEditor();
        showEditor();
        initializeEditorToolbar();
        printToMeta("Editor has been successfully loaded... ");
    });
})
(Granite.$, $(document), Granite.author);<|endoftext|>


<commit_before>import PropTypes from "prop-types";
import React from "react";
import { useLocation } from "react-router-dom";
import useSWR from "swr";

import Button from "@agir/front/genericComponents/Button";
import { RawFeatherIcon } from "@agir/front/genericComponents/FeatherIcon";
import PageFadeIn from "@agir/front/genericComponents/PageFadeIn";
import Skeleton from "@agir/front/genericComponents/Skeleton";
import Spacer from "@agir/front/genericComponents/Spacer";

import StyledPageContainer from "@agir/voting_proxies/Common/StyledPageContainer";
import NotFoundPage from "@agir/front/notFoundPage/NotFoundPage";
import VotingProxyWidget from "./VotingProxyWidget";

import { getVotingProxyEndpoint } from "@agir/voting_proxies/Common/api";

const groupRequestByProxy = (requests) => {
  const byProxy = {};

  requests.forEach((request) => {
    byProxy[request.votingProxy.id] = byProxy[request.votingProxy.id] || {
      ...request.votingProxy,
      status: request.status,
      votingProxyRequests: [],
      votingDates: [],
    };
    byProxy[request.votingProxy.id].votingProxyRequests.push(request);
    byProxy[request.votingProxy.id].votingDates.push(request.votingDate);
  });

  return Object.values(byProxy);
};

const getVotingProxyRequestsIdsFromURLSearchParams = (search) => {
  if (!search) {
    return null;
  }
  const searchParams = new URLSearchParams(search);
  const ids = searchParams.get("vpr");
  if (!ids) {
    return null;
  }
  return ids;
};

const VotingProxyRequestDetails = () => {
  const { search } = useLocation();
  const votingProxyRequestsIds =
    getVotingProxyRequestsIdsFromURLSearchParams(search);

  const { data, error } = useSWR(
    getVotingProxyEndpoint(
      "acceptedVotingProxyRequests",
      null,
      votingProxyRequestsIds && { vpr: votingProxyRequestsIds }
    ),
    {
      revalidateIfStale: false,
      revalidateOnFocus: false,
      revalidateOnReconnect: false,
    }
  );

  if (error?.response?.status === 404) {
    // The voting proxy does not exist or is no longer available
    return <NotFoundPage isTopBar={false} reloadOnReconnection={false} />;
  }

  return (

  );
};
VotingProxyRequestDetails.propTypes = {};
export default VotingProxyRequestDetails;
<commit_msg>fix: missing word in VotingProxyRequestDetails.js<commit_after>import PropTypes from "prop-types";
import React from "react";
import { useLocation } from "react-router-dom";
import useSWR from "swr";

import Button from "@agir/front/genericComponents/Button";
import { RawFeatherIcon } from "@agir/front/genericComponents/FeatherIcon";
import PageFadeIn from "@agir/front/genericComponents/PageFadeIn";
import Skeleton from "@agir/front/genericComponents/Skeleton";
import Spacer from "@agir/front/genericComponents/Spacer";

import StyledPageContainer from "@agir/voting_proxies/Common/StyledPageContainer";
import NotFoundPage from "@agir/front/notFoundPage/NotFoundPage";
import VotingProxyWidget from "./VotingProxyWidget";

import { getVotingProxyEndpoint } from "@agir/voting_proxies/Common/api";

const groupRequestByProxy = (requests) => {
  const byProxy = {};

  requests.forEach((request) => {
    byProxy[request.votingProxy.id] = byProxy[request.votingProxy.id] || {
      ...request.votingProxy,
      status: request.status,
      votingProxyRequests: [],
      votingDates: [],
    };
    byProxy[request.votingProxy.id].votingProxyRequests.push(request);
    byProxy[request.votingProxy.id].votingDates.push(request.votingDate);
  });

  return Object.values(byProxy);
};

const getVotingProxyRequestsIdsFromURLSearchParams = (search) => {
  if (!search) {
    return null;
  }
  const searchParams = new URLSearchParams(search);
  const ids = searchParams.get("vpr");
  if (!ids) {
    return null;
  }
  return ids;
};

const VotingProxyRequestDetails = () => {
  const { search } = useLocation();
  const votingProxyRequestsIds =
    getVotingProxyRequestsIdsFromURLSearchParams(search);

  const { data, error } = useSWR(
    getVotingProxyEndpoint(
      "acceptedVotingProxyRequests",
      null,
      votingProxyRequestsIds && { vpr: votingProxyRequestsIds }
    ),
    {
      revalidateIfStale: false,
      revalidateOnFocus: false,
      revalidateOnReconnect: false,
    }
  );

  if (error?.response?.status === 404) {
    // The voting proxy does not exist or is no longer available
    return <NotFoundPage isTopBar={false} reloadOnReconnection={false} />;
  }

  return (

  );
};
VotingProxyRequestDetails.propTypes = {};
export default VotingProxyRequestDetails;
<|endoftext|>


<commit_before>/* eslint-disable no-console */
'use strict';

const spawnSync = require('child_process').spawnSync;
const fs = require('fs');
const path = require('path');

const conf = {};
const confUiFile = './patternlab-config.json';

let sourceDir;

if (fs.existsSync(confUiFile)) {
  const confUiStr = fs.readFileSync(confUiFile, 'utf8');

  try {
    conf.ui = JSON.parse(confUiStr);
  }
  catch (err) {
    throw err;
  }

  if (conf.ui) {
    sourceDir = conf.ui.paths.source.root;
  }
}

// Conf file may not exists at this point of installation. Hard-code in that case.
else {
  sourceDir = 'source';
}

// First, create empty source dir so the postinstall script doesn't write the main profile there.
if (!fs.existsSync(sourceDir)) {
  fs.mkdirSync(sourceDir);
  fs.mkdirSync(`${sourceDir}/_data`);
  fs.mkdirSync(`${sourceDir}/_patterns`);
  fs.mkdirSync(`${sourceDir}/_styles`);
  fs.writeFileSync(`${sourceDir}/_data/data.json`, '{}');
  fs.writeFileSync(`${sourceDir}/_data/listitems.json`, '{}');
}

// Return if node_modules is already installed. (Avoid infinite loops!)
if (fs.existsSync('node_modules')) {
  console.warn('Fepper is already installed! Aborting!');

  return;
}

// Else, run npm install.
else {
  spawnSync('npm', ['install'], {stdio: 'inherit'});
}

// Check if patterns dir is already populated.
const patternsDirContent = fs.readdirSync(`${sourceDir}/_patterns`);

// Return if already populated.
if (patternsDirContent.length) {
  console.warn(`${sourceDir} dir already has content! Aborting base install!`);

  return;
}

// Delete the empty source dir so a new one can be copied over.
fs.rmdirSync(sourceDir);

// Copy over the base profile source dir.
const binGulp = path.resolve('node_modules', '.bin', 'gulp');
const spawnedObj =
  spawnSync(binGulp, ['--gulpfile', 'node_modules/fepper/tasker.js', 'install:copy-base'], {stdio: 'inherit'});

// Output to install.log.
const installLog = 'install.log';

fs.writeFileSync(installLog, '');

if (spawnedObj.stderr) {
  fs.appendFileSync(installLog, `${spawnedObj.stderr}\n`);
}

fs.appendFileSync(installLog, `Process exited with status ${spawnedObj.status}.\n`);

// Compile UI.
spawnSync('node', ['node_modules/fepper/index.js', 'ui:compile'], {stdio: 'inherit'});
<commit_msg>refining base install<commit_after>/* eslint-disable no-console */
'use strict';

const spawnSync = require('child_process').spawnSync;
const fs = require('fs');
const path = require('path');

const conf = {};
const confUiFile = './patternlab-config.json';

let sourceDir;

if (fs.existsSync(confUiFile)) {
  const confUiStr = fs.readFileSync(confUiFile, 'utf8');

  try {
    conf.ui = JSON.parse(confUiStr);
  }
  catch (err) {
    throw err;
  }

  if (conf.ui) {
    sourceDir = conf.ui.paths.source.root;
  }
}

// Conf file may not exists at this point of installation. Hard-code in that case.
else {
  sourceDir = 'source';
}

// First, create empty source dir so the postinstall script doesn't write the main profile there.
if (!fs.existsSync(sourceDir)) {
  fs.mkdirSync(sourceDir);
  fs.mkdirSync(`${sourceDir}/_data`);
  fs.mkdirSync(`${sourceDir}/_patterns`);
  fs.mkdirSync(`${sourceDir}/_styles`);
  fs.writeFileSync(`${sourceDir}/_data/data.json`, '{}');
  fs.writeFileSync(`${sourceDir}/_data/listitems.json`, '{}');
}

// Return if node_modules is already installed. (Avoid infinite loops!)
if (fs.existsSync('node_modules')) {
  console.warn('Fepper is already installed! Aborting!');

  return;
}

// Else, run npm install.
else {
  spawnSync('npm', ['install'], {stdio: 'inherit'});
}

// Check if patterns dir is already populated.
const patternsDirContent = fs.readdirSync(`${sourceDir}/_patterns`);

// Return if already populated.
if (patternsDirContent.length) {
  console.warn(`${sourceDir} dir already has content! Aborting base install!`);

  return;
}

// Delete the source dir so a new one can be copied over.
fs.unlinkSync(`${sourceDir}/_data/listitems.json`);
fs.unlinkSync(`${sourceDir}/_data/data.json`);
fs.rmdirSync(`${sourceDir}/_styles`);
fs.rmdirSync(`${sourceDir}/_patterns`);
fs.rmdirSync(`${sourceDir}/_data`);
fs.rmdirSync(sourceDir);

// Copy over the base profile source dir.
const binGulp = path.resolve('node_modules', '.bin', 'gulp');
const spawnedObj =
  spawnSync(binGulp, ['--gulpfile', 'node_modules/fepper/tasker.js', 'install:copy-base'], {stdio: 'inherit'});

// Output to install.log.
const installLog = 'install.log';

fs.writeFileSync(installLog, '');

if (spawnedObj.stderr) {
  fs.appendFileSync(installLog, `${spawnedObj.stderr}\n`);
}

fs.appendFileSync(installLog, `Process exited with status ${spawnedObj.status}.\n`);

// Compile UI.
spawnSync('node', ['node_modules/fepper/index.js', 'ui:compile'], {stdio: 'inherit'});
<|endoftext|>


<commit_before>'use strict';

const spawnSync = require('child_process').spawnSync;
const fs = require('fs');
const path = require('path');

const conf = {};
const confFile = './conf.yml';
const confUiFile = './patternlab-config.json';
const enc = 'utf8';
const fepperPath = path.resolve('node_modules', 'fepper');
const prefFile = './pref.yml';

let extendDir;
let sourceDir;

if (fs.existsSync(confFile)) {
  const confStr = fs.readFileSync(confFile, enc);
  const confLines = confStr.split('\n');

  for (let confLine of confLines) {
    const keyVal = confLine.split(':');

    if (keyVal[0].trim() === 'extend_dir' && keyVal[1]) {
      extendDir = keyVal[1].trim();
    }
  }
}
// confFile may not exists at this point of installation. Hard-code in that case.
else {
  extendDir = 'extend';
}

if (fs.existsSync(confUiFile)) {
  const confUiStr = fs.readFileSync(confUiFile, enc);

  try {
    conf.ui = JSON.parse(confUiStr);
  }
  catch (err) {
    throw err;
  }

  if (conf.ui) {
    sourceDir = conf.ui.paths.source.root;
  }
}
// confUiFile may not exists at this point of installation. Hard-code in that case.
else {
  sourceDir = 'source';
}

// Create empty extend and source dirs so the postinstall script doesn't write the main profile there.
if (!fs.existsSync(extendDir)) {
  fs.mkdirSync(extendDir);
}

if (!fs.existsSync(sourceDir)) {
  fs.mkdirSync(sourceDir);
  fs.mkdirSync(`${sourceDir}/_data`);
  fs.mkdirSync(`${sourceDir}/_patterns`);
  fs.mkdirSync(`${sourceDir}/_styles`);
  fs.writeFileSync(`${sourceDir}/_data/data.json`, '{}');
  fs.writeFileSync(`${sourceDir}/_data/listitems.json`, '{}');
}

// Output to install.log.
const installLog = 'install.log';
let spawnedObj;

fs.writeFileSync(installLog, '');

// Only run npm install if not already installed.
if (!fs.existsSync('node_modules')) {
  let binNpm = 'npm';

  // Spawn npm.cmd if Windows and not BASH.
  if (process.env.ComSpec && process.env.ComSpec.toLowerCase() === 'c:\\windows\\system32\\cmd.exe') {
    binNpm = 'npm.cmd';
  }

  spawnedObj = spawnSync(binNpm, ['install', '--ignore-scripts'], {stdio: 'inherit'});
}

if (spawnedObj && spawnedObj.stderr) {
  fs.appendFileSync(installLog, `${spawnedObj.stderr}\n`);
}

if (!fs.existsSync(confFile)) {
  fs.copyFileSync(path.resolve(fepperPath, 'excludes', 'conf.yml'), confFile);
}

if (!fs.existsSync(confUiFile)) {
  fs.copyFileSync(path.resolve(fepperPath, 'excludes', 'patternlab-config.json'), confUiFile);
}

if (!fs.existsSync(prefFile)) {
  fs.copyFileSync(path.resolve(fepperPath, 'excludes', 'pref.yml'), prefFile);
}

// Delete the source and extend dirs so new ones can be copied over.
// fs.rmdirSync will throw an error if directory is already populated.
fs.unlinkSync(`${sourceDir}/_data/listitems.json`);
fs.unlinkSync(`${sourceDir}/_data/data.json`);
fs.rmdirSync(`${sourceDir}/_styles`);
fs.rmdirSync(`${sourceDir}/_patterns`);
fs.rmdirSync(`${sourceDir}/_data`);
fs.rmdirSync(sourceDir);
fs.rmdirSync(extendDir);

const binPath = path.resolve('node_modules', '.bin');
const winGulp = path.resolve(binPath, 'gulp.cmd');

let binGulp = path.resolve(binPath, 'gulp');

// Spawn gulp.cmd if Windows and not BASH.
if (process.env.ComSpec && process.env.ComSpec.toLowerCase() === 'c:\\windows\\system32\\cmd.exe') {
  binGulp = winGulp;
}

// Copy over the base profile source dir.
const spawnedObj1 =
  spawnSync(binGulp, ['--gulpfile', path.resolve(fepperPath, 'tasker.js'), 'install:copy-base'], {stdio: 'inherit'});

if (spawnedObj1.stderr) {
  fs.appendFileSync(installLog, `${spawnedObj1.stderr}\n`);
}

// Complete installation. run/install.js handles its own logging so no need to log here.
spawnSync('node', [path.resolve('run', 'install.js')], {stdio: 'inherit'});
<commit_msg>fixing install-base script<commit_after>'use strict';

const spawnSync = require('child_process').spawnSync;
const fs = require('fs');
const path = require('path');

const conf = {};
const confFile = './conf.yml';
const confUiFile = './patternlab-config.json';
const enc = 'utf8';
const fepperPath = path.resolve('node_modules', 'fepper');
const prefFile = './pref.yml';

let extendDir;
let sourceDir;

if (fs.existsSync(confFile)) {
  const confStr = fs.readFileSync(confFile, enc);
  const confLines = confStr.split('\n');

  for (let confLine of confLines) {
    const keyVal = confLine.split(':');

    if (keyVal[0].trim() === 'extend_dir' && keyVal[1]) {
      extendDir = keyVal[1].trim();
    }
  }
}
// confFile may not exists at this point of installation. Hard-code in that case.
else {
  extendDir = 'extend';
}

if (fs.existsSync(confUiFile)) {
  const confUiStr = fs.readFileSync(confUiFile, enc);

  try {
    conf.ui = JSON.parse(confUiStr);
  }
  catch (err) {
    throw err;
  }

  if (conf.ui) {
    sourceDir = conf.ui.paths.source.root;
  }
}
// confUiFile may not exists at this point of installation. Hard-code in that case.
else {
  sourceDir = 'source';
}

// Create empty extend and source dirs so the postinstall script doesn't write the main profile there.
const existsAlreadyExtendDir = fs.existsSync(extendDir);
const existsAlreadySourceDir = fs.existsSync(sourceDir);

if (!existsAlreadyExtendDir) {
  fs.mkdirSync(extendDir);
}

if (!existsAlreadySourceDir) {
  fs.mkdirSync(sourceDir);
  fs.mkdirSync(`${sourceDir}/_data`);
  fs.mkdirSync(`${sourceDir}/_patterns`);
  fs.mkdirSync(`${sourceDir}/_styles`);
  fs.writeFileSync(`${sourceDir}/_data/data.json`, '{}');
  fs.writeFileSync(`${sourceDir}/_data/listitems.json`, '{}');
}

// Output to install.log.
const installLog = 'install.log';
let spawnedObj;

fs.writeFileSync(installLog, '');

// Only run npm install if not already installed.
if (!fs.existsSync('node_modules')) {
  let binNpm = 'npm';

  // Spawn npm.cmd if Windows and not BASH.
  if (process.env.ComSpec && process.env.ComSpec.toLowerCase() === 'c:\\windows\\system32\\cmd.exe') {
    binNpm = 'npm.cmd';
  }

  spawnedObj = spawnSync(binNpm, ['install', '--ignore-scripts'], {stdio: 'inherit'});
}

if (spawnedObj && spawnedObj.stderr) {
  fs.appendFileSync(installLog, `${spawnedObj.stderr}\n`);
}

if (!fs.existsSync(confFile)) {
  fs.copyFileSync(path.resolve(fepperPath, 'excludes', 'conf.yml'), confFile);
}

if (!fs.existsSync(confUiFile)) {
  fs.copyFileSync(path.resolve(fepperPath, 'excludes', 'patternlab-config.json'), confUiFile);
}

if (!fs.existsSync(prefFile)) {
  fs.copyFileSync(path.resolve(fepperPath, 'excludes', 'pref.yml'), prefFile);
}

// Delete placeholder source and extend dirs so new ones can be copied over.
if (!existsAlreadySourceDir) {
  fs.unlinkSync(`${sourceDir}/_data/listitems.json`);
  fs.unlinkSync(`${sourceDir}/_data/data.json`);
  fs.rmdirSync(`${sourceDir}/_styles`);
  fs.rmdirSync(`${sourceDir}/_patterns`);
  fs.rmdirSync(`${sourceDir}/_data`);
  fs.rmdirSync(sourceDir);
}

if (!existsAlreadyExtendDir) {
  fs.rmdirSync(extendDir);
}

const binPath = path.resolve('node_modules', '.bin');
const winGulp = path.resolve(binPath, 'gulp.cmd');

let binGulp = path.resolve(binPath, 'gulp');

// Spawn gulp.cmd if Windows and not BASH.
if (process.env.ComSpec && process.env.ComSpec.toLowerCase() === 'c:\\windows\\system32\\cmd.exe') {
  binGulp = winGulp;
}

// Copy over the base profile source dir.
const spawnedObj1 =
  spawnSync(binGulp, ['--gulpfile', path.resolve(fepperPath, 'tasker.js'), 'install:copy-base'], {stdio: 'inherit'});

if (spawnedObj1.stderr) {
  fs.appendFileSync(installLog, `${spawnedObj1.stderr}\n`);
}

// Complete installation. run/install.js handles its own logging so no need to log here.
spawnSync('node', [path.resolve('run', 'install.js')], {stdio: 'inherit'});
<|endoftext|>


<commit_before>'use strict';
var app = angular.module('angularApp')

  .controller('PublicationSampleSearchCtrl', function (publicationService,navigationService,groupService,$rootScope,$scope,$http,$location) {
    $rootScope.tabs = navigationService.get();
    $rootScope.groups = groupService.getGroups.data.get();

    $scope.doSearch = function() {
      $scope.dirtyForm = [];
      if ($scope.id) {
          if (!parseInt($scope.id)) {
            $scope.dirtyForm.push("SampleId must be a number");
          };
      }
      else {
            $scope.dirtyForm.push("SampleId cannot be blank");
      };

      if ($scope.dirtyForm.length==0) {
        $location.path('/publicationSampleInformation').search({'id': $scope.id,'type':$scope.type});
        // $location.path("/publicationSampleInformation").replace();
      };
    };

    $scope.publicationDoiData = publicationService.publicationDoiData;

    // $scope.$on('$viewContentLoaded', function(){
    //   $http({method: 'GET', url: '/caNanoLab/rest/publication/setup'}).
    //   success(function(data, status, headers, config) {
    //     $scope.data = data;
    //     $scope.researchArea = {};
    //     $scope.searchPublicationForm.researchArea = [];
    //     for (var x=0;x<data.publicationResearchAreas.length;x++) {
    //       $scope.researchArea[$scope.data.publicationResearchAreas[x]]=false;
    //     }
    //   }).
    //   error(function(data, status, headers, config) {
    //       // called asynchronously if an error occurs
    //       // or server returns response with an error status.
    //   $scope.message = data;
    //   });
    // });

    // $scope.displayPubMed = function() {
    //   if ($scope.searchPublicationForm.category=='book chapter'||$scope.searchPublicationForm.category=='report') {
    //     $scope.pubMed = true;
    //   }
    //   else {
    //     $scope.pubMed = false;
    //   }
    // };

    // $scope.doSearch = function() {
    //   $scope.loader = true;
    //   for (var key in $scope.researchArea) {
    //     if ($scope.researchArea[key]) {
    //       $scope.searchPublicationForm.researchArea.push(key)
    //     }

    //   }

    //   $http({method: 'POST', url: '/caNanoLab/rest/publication/searchPublication',data: $scope.searchPublicationForm}).
    //   success(function(data, status, headers, config) {
    //     // $rootScope.sampleData = data;
    //     $scope.publicationData.data = data;
    //     $location.path("/publicationResults").replace();

    //   }).
    //   error(function(data, status, headers, config) {
    //     // called asynchronously if an error occurs
    //     // or server returns response with an error status.
    //     // $rootScope.sampleData = data;
    //     $scope.loader = false;
    //     $scope.message = data;
    //   });
    // };

    // $scope.resetForm = function() {
    //   $scope.searchPublicationForm = {};
    // };

  });
<commit_msg>Change val. message from SampleId to ID<commit_after>'use strict';
var app = angular.module('angularApp')

  .controller('PublicationSampleSearchCtrl', function (publicationService,navigationService,groupService,$rootScope,$scope,$http,$location) {
    $rootScope.tabs = navigationService.get();
    $rootScope.groups = groupService.getGroups.data.get();

    $scope.doSearch = function() {
      $scope.dirtyForm = [];
      if ($scope.id) {
          if (!parseInt($scope.id)) {
            $scope.dirtyForm.push("ID must be a number");
          };
      }
      else {
            $scope.dirtyForm.push("ID cannot be blank");
      };

      if ($scope.dirtyForm.length==0) {
        $location.path('/publicationSampleInformation').search({'id': $scope.id,'type':$scope.type});
        // $location.path("/publicationSampleInformation").replace();
      };
    };

    $scope.publicationDoiData = publicationService.publicationDoiData;

    // $scope.$on('$viewContentLoaded', function(){
    //   $http({method: 'GET', url: '/caNanoLab/rest/publication/setup'}).
    //   success(function(data, status, headers, config) {
    //     $scope.data = data;
    //     $scope.researchArea = {};
    //     $scope.searchPublicationForm.researchArea = [];
    //     for (var x=0;x<data.publicationResearchAreas.length;x++) {
    //       $scope.researchArea[$scope.data.publicationResearchAreas[x]]=false;
    //     }
    //   }).
    //   error(function(data, status, headers, config) {
    //       // called asynchronously if an error occurs
    //       // or server returns response with an error status.
    //   $scope.message = data;
    //   });
    // });

    // $scope.displayPubMed = function() {
    //   if ($scope.searchPublicationForm.category=='book chapter'||$scope.searchPublicationForm.category=='report') {
    //     $scope.pubMed = true;
    //   }
    //   else {
    //     $scope.pubMed = false;
    //   }
    // };

    // $scope.doSearch = function() {
    //   $scope.loader = true;
    //   for (var key in $scope.researchArea) {
    //     if ($scope.researchArea[key]) {
    //       $scope.searchPublicationForm.researchArea.push(key)
    //     }

    //   }

    //   $http({method: 'POST', url: '/caNanoLab/rest/publication/searchPublication',data: $scope.searchPublicationForm}).
    //   success(function(data, status, headers, config) {
    //     // $rootScope.sampleData = data;
    //     $scope.publicationData.data = data;
    //     $location.path("/publicationResults").replace();

    //   }).
    //   error(function(data, status, headers, config) {
    //     // called asynchronously if an error occurs
    //     // or server returns response with an error status.
    //     // $rootScope.sampleData = data;
    //     $scope.loader = false;
    //     $scope.message = data;
    //   });
    // };

    // $scope.resetForm = function() {
    //   $scope.searchPublicationForm = {};
    // };

  });
<|endoftext|>


<commit_before>
import path from 'path'
import {APP_SRC_DIR} from '../../environment';

export const alias = {
	src: 			path.resolve(APP_SRC_DIR),
	components:		path.resolve(APP_SRC_DIR, 'components'),
	constants:		path.resolve(APP_SRC_DIR, 'constants'),
	data:			path.resolve(APP_SRC_DIR, 'data'),
	'app-history':	path.resolve(APP_SRC_DIR, 'history'),
	middleware: 	path.resolve(APP_SRC_DIR, 'middleware'),
	models:			path.resolve(APP_SRC_DIR, 'models'),
	scenes:			path.resolve(APP_SRC_DIR, 'scenes'),
	scss:			path.resolve(APP_SRC_DIR, 'scss'),
	services:		path.resolve(APP_SRC_DIR, 'services'),
	selectors:		path.resolve(APP_SRC_DIR, 'selectors'),
	utils:			path.resolve(APP_SRC_DIR, 'utils')
};<commit_msg>Remove unused aliases<commit_after>
import path from 'path'
import {APP_SRC_DIR} from '../../environment';

export const alias = {
	src: 			path.resolve(APP_SRC_DIR),
	components:		path.resolve(APP_SRC_DIR, 'components'),
	constants:		path.resolve(APP_SRC_DIR, 'constants'),
	data:			path.resolve(APP_SRC_DIR, 'data'),
	services:		path.resolve(APP_SRC_DIR, 'services'),
	selectors:		path.resolve(APP_SRC_DIR, 'selectors'),
	utils:			path.resolve(APP_SRC_DIR, 'utils')
};<|endoftext|>