<commit_before>/*
Script: ART.Widget.js

License:
	MIT-style license.
*/

// Base widget class. Based on » http://gist.github.com/85837
(function(){

var counting, focused;

ART.Widget = new Class({

	Implements: [Options, Events],

	ns: 'art',
	name: 'widget',

	options: {
		// onShow: $empty,
		// onHide: $empty,
		// onFocus: $empty,
		// onBlur: $empty,
		// onEnable: $empty,
		// onDisable: $empty,
		// onDestroy: $empty,
		// onAdoption: $empty(parentWidget),
		// onOrphan: $empty(previousParent),
		// id: null,
		// style: null,
		renderWhileHidden: false,
		className: '',
		keyboardOptions: {
			active: false
		},
		parentWidget: null,
		element: null
	},

	initialize: function(options){
		this.latchEvents('adoption');
		this.pseudos = [];
		this.childWidgets = [];
		var parent, kbManager;
		if (options) {
			if (options.parentWidget) {
				parent = options.parentWidget;
				delete options.parentWidget;
			}
			if (options.keyboardOptions && options.keyboardOptions.manager) {
				kbManager = options.keyboardOptions.manager;
				delete options.keyboardOptions.manager;
			}
		}
		this.setOptions(options);
		this.prefix = this.ns + '-' + this.name;
		this.element = this.options.element || new Element('div');
		this.element.set({
			id: this.element.get('id') || this.options.id || this.prefix+new Date().getTime()
		}).store(this.prefix, this).store('widget', this);
		this.element.addClass([this.ns, this.prefix, this.options.className].join(' '));
		this.classes = this.options.classes;
		this.classes = (this.options.className) ? this.options.className.split(' ') : [];

		var kbOptions = $merge(this.options.keyboardOptions, options ? options.keyboardOptions || {} : {});
		kbOptions.manager = kbManager || (parent ? parent.keyboard : null);
		this.keyboard = new Keyboard(kbOptions);
		this.keyboard.widget = this;
		this.keyboard.addEvent('deactivate', this.blur.bind(this));

		if (parent) this.setParent(parent);
	},

	getSelector: function(){
		var selector = (this.parentWidget) ? this.parentWidget.getSelector() + ' ' : '';
		selector += this.name;
		if (this.classes.length) selector += '.' + this.classes.join('.');
		if (this.pseudos.length) selector += ':' + this.pseudos.join(':');
		return selector;
	},

	addPseudo: function(pseudo){
		this.pseudos.include(pseudo);
	},

	removePseudo: function(pseudo){
		this.pseudos.erase(pseudo);
	},

	setParent: function(widget, initing){
		if (!initing) this.removeParent();
		this.parentWidget = widget;
		widget.childWidgets.include(this);
		this.parentWidget.keyboard.manage(this.keyboard);
		this.enable();
		this.fireEvent('adoption', widget);
		return this;
	},

	removeParent: function(){
		this.prevParent = this.parentWidget || this.prevParent;
		if (!this.prevParent) return;
		if (this.parentWidget) {
			this.parentWidget.childWidgets.erase(this);
			Keyboard.manager.manage(this.keyboard);
			this.parentWidget = null;
		}
		this.fireEvent('orphan', this.prevParent);
	},

	// render

	requireToRender: function(){
		this.requiredToRender = this.requiredToRender || [];
		$A(arguments).each(function(requirement) {
			this.requiredToRender.push(requirement);
		}, this);
	},

	readyToRender: function() {
		if (!this.requiredToRender || !this.requiredToRender.length) return;
		$A(arguments).each(function(requirement) {
			this.requiredToRender.erase(requirement);
		}, this);
	},

	redraw: function(){
		if (counting) this._counters();
		this.childWidgets.each(function(child) {
			child.render();
		});
		return this;
	},

	isReadyToRender: function(){
		var isReady = (!this.requiredToRender || !this.requiredToRender.length) && !this.destroyed && (this.options.renderWhileHidden || !this.hidden);
		if (isReady && this.parentWidget) isReady = this.parentWidget.isReadyToRender();
		return isReady;
	},

	render: function(override){
		if (this.isReadyToRender()) this.redraw(override);
		return this;
	},

	// special states

	//not visible
	hide: function(){
		if (!this.hidden){
			this.hidden = true;
			this.fireEvent('hide');
			this.element.addClass(this.prefix + '-hidden');
			this.addPseudo('hidden');
			this.render();
		}
		return this;
	},

	//engaged; the button is down, the select list is expanded, the mouse is clicking this thing
	activate: function(){
		if (!this.active){
			this.active = true;
			this.fireEvent('activate');
			this.element.addClass(this.prefix + '-active');
			this.addPseudo('active');
			this.render();
		}
		return this;
	},

	//has keyboard control
	focus: function(){
		if (!this.keyboard.isActive()){
			this.keyboard.activate();
			this.focused = true;
			this.fireEvent('focus');
			this.element.addClass(this.prefix + '-focused');
			this.addPseudo('focus');
			focused = this;
			this.render();
		}
		return this;
	},

	//non-interactive
	disable: function(byParent){
		this.disabledByParent = false;
		if (!this.disabled){
			if (byParent) this.disabledByParent = true;
			this.blur();
			this.fireEvent('disable');
			this.keyboard.deactivate();
			this.childWidgets.each(function(child){
				child.disable(true);
			});
			this.element.addClass(this.prefix + '-disabled');
			this.addPseudo('disabled');
			this.disabled = true;
			this.render();
		}
		return this;
	},

	// normal states
	//visible
	show: function(){
		if (this.hidden){
			this.hidden = false;
			this.fireEvent('show');
			this.element.removeClass(this.prefix + '-hidden');
			this.removePseudo('hidden');
			this.render();
		}
		return this;
	},
	//the button is released, the select list is contracted, the mouse is up
	deactivate: function(){
		if (this.active){
			this.active = false;
			this.fireEvent('deactivate');
			this.element.removeClass(this.prefix + '-active');
			this.removePseudo('active');
			this.render();
		}
		return this;
	},

	//focus has shifted to another widget
	blur: function(){
		if (this.focused){
			this.focused = false;
			this.fireEvent('blur');
			this.keyboard.deactivate();
			this.element.removeClass(this.prefix + '-focused');
			this.removePseudo('focus');
			this.render();
		}
		return this;
	},
	//the widget is interactable
	enable: function(){
		if (this.parentWidget && this.parentWidget.disabled) {
			this.disabledByParent = true;
			return this;
		};
		delete this.disabledByParent;
		if (this.disabled){
			this.disabled = false;
			this.fireEvent('enable');
			this.element.removeClass(this.prefix + '-disabled');
			this.removePseudo('disabled');
			this.render();
		}
		this.childWidgets.each(function(child){
			if (child.disabledByParent) {
				child.enable();
				delete child.disabledByParent;
			}
		});
		return this;
	},

	attachKeys: function(events){
		this.keyboard.addEvents(events);
	},

	detachKeys: function(events) {
		this.keyboard.removeEvents(events);
	},

	addShortcut: function(name, shortcut) {
		this.keyboard.addShortcut(name, shortcut);
	},

	addShortcuts: function(obj) {
		this.keyboard.addShortcuts(obj);
	},

	removeShortcut: function(name) {
		this.keyboard.removeShortcut(name);
	},

	removeShortcuts: function(names) {
		this.keyboard.removeShortcuts(names);
	},

	getShortcut: function(name) {
		return this.keyboard.getShortcut(name);
	},

	getShortcuts: function() {
		return this.keyboard.getShortcuts();
	},

	destroy: function(){
		this.removeParent();
		$A(this.childWidgets).each(function(widget) {
			widget.destroy();
		});
		if (this.childWidgets.length && window.console && console.warn) {
			this.childWidgets.each(function(widget) {
				console.warn("warning: %s called the destroy method of %s but it failed. Ensure that destroy method calls this.parent", this.prefix, widget.prefix);
			}, this);
		}
		this.element.destroy();
		this.destroyed = true;
		return this.fireEvent('destroy');
	},

	// toElement

	toElement: function(){
		return this.element;
	},

	_redrawCount: 0,
	_counters: function(){
		this._redrawCount++;
		$clear(this._countTimer);
		this._countTimer = (function(){
			this._redrawCount = 0;
		}).delay(1000, this);
		console.log('redraw %s: ', this.name, this._redrawCount, this.element);
	}

});

ART._counts = function(){
	counting = !counting;
	if (counting) console.log('counting widget renders');
	else console.log('disabling widget render counts');
};

})();<commit_msg>adding add/remove class functionality to widget<commit_after>/*
Script: ART.Widget.js

License:
	MIT-style license.
*/

// Base widget class. Based on » http://gist.github.com/85837
(function(){

var counting, focused;

ART.Widget = new Class({

	Implements: [Options, Events],

	ns: 'art',
	name: 'widget',

	options: {
		// onShow: $empty,
		// onHide: $empty,
		// onFocus: $empty,
		// onBlur: $empty,
		// onEnable: $empty,
		// onDisable: $empty,
		// onDestroy: $empty,
		// onAdoption: $empty(parentWidget),
		// onOrphan: $empty(previousParent),
		// id: null,
		// style: null,
		renderWhileHidden: false,
		className: '',
		keyboardOptions: {
			active: false
		},
		parentWidget: null,
		element: null
	},

	initialize: function(options){
		this.latchEvents('adoption');
		this.pseudos = [];
		this.childWidgets = [];
		var parent, kbManager;
		if (options) {
			if (options.parentWidget) {
				parent = options.parentWidget;
				delete options.parentWidget;
			}
			if (options.keyboardOptions && options.keyboardOptions.manager) {
				kbManager = options.keyboardOptions.manager;
				delete options.keyboardOptions.manager;
			}
		}
		this.setOptions(options);
		this.prefix = this.ns + '-' + this.name;
		this.element = this.options.element || new Element('div');
		this.element.set({
			id: this.element.get('id') || this.options.id || this.prefix+new Date().getTime()
		}).store(this.prefix, this).store('widget', this);
		this.element.addClass([this.ns, this.prefix, this.options.className].join(' '));
		this.classes = this.options.classes;
		this.classes = (this.options.className) ? this.options.className.split(' ') : [];

		var kbOptions = $merge(this.options.keyboardOptions, options ? options.keyboardOptions || {} : {});
		kbOptions.manager = kbManager || (parent ? parent.keyboard : null);
		this.keyboard = new Keyboard(kbOptions);
		this.keyboard.widget = this;
		this.keyboard.addEvent('deactivate', this.blur.bind(this));

		if (parent) this.setParent(parent);
	},

	addClass: function(className){
		this.classes.include(className);
		return this;
	},

	removeClass: function(className) {
		this.classes.erase(className);
		return this;
	},

	getSelector: function(){
		var selector = (this.parentWidget) ? this.parentWidget.getSelector() + ' ' : '';
		selector += this.name;
		if (this.classes.length) selector += '.' + this.classes.join('.');
		if (this.pseudos.length) selector += ':' + this.pseudos.join(':');
		return selector;
	},

	addPseudo: function(pseudo){
		this.pseudos.include(pseudo);
	},

	removePseudo: function(pseudo){
		this.pseudos.erase(pseudo);
	},

	setParent: function(widget, initing){
		if (!initing) this.removeParent();
		this.parentWidget = widget;
		widget.childWidgets.include(this);
		this.parentWidget.keyboard.manage(this.keyboard);
		this.enable();
		this.fireEvent('adoption', widget);
		return this;
	},

	removeParent: function(){
		this.prevParent = this.parentWidget || this.prevParent;
		if (!this.prevParent) return;
		if (this.parentWidget) {
			this.parentWidget.childWidgets.erase(this);
			Keyboard.manager.manage(this.keyboard);
			this.parentWidget = null;
		}
		this.fireEvent('orphan', this.prevParent);
	},

	// render

	requireToRender: function(){
		this.requiredToRender = this.requiredToRender || [];
		$A(arguments).each(function(requirement) {
			this.requiredToRender.push(requirement);
		}, this);
	},

	readyToRender: function() {
		if (!this.requiredToRender || !this.requiredToRender.length) return;
		$A(arguments).each(function(requirement) {
			this.requiredToRender.erase(requirement);
		}, this);
	},

	redraw: function(){
		if (counting) this._counters();
		this.childWidgets.each(function(child) {
			child.render();
		});
		return this;
	},

	isReadyToRender: function(){
		var isReady = (!this.requiredToRender || !this.requiredToRender.length) && !this.destroyed && (this.options.renderWhileHidden || !this.hidden);
		if (isReady && this.parentWidget) isReady = this.parentWidget.isReadyToRender();
		return isReady;
	},

	render: function(override){
		if (this.isReadyToRender()) this.redraw(override);
		return this;
	},

	// special states

	//not visible
	hide: function(){
		if (!this.hidden){
			this.hidden = true;
			this.fireEvent('hide');
			this.element.addClass(this.prefix + '-hidden');
			this.addPseudo('hidden');
			this.render();
		}
		return this;
	},

	//engaged; the button is down, the select list is expanded, the mouse is clicking this thing
	activate: function(){
		if (!this.active){
			this.active = true;
			this.fireEvent('activate');
			this.element.addClass(this.prefix + '-active');
			this.addPseudo('active');
			this.render();
		}
		return this;
	},

	//has keyboard control
	focus: function(){
		if (!this.keyboard.isActive()){
			this.keyboard.activate();
			this.focused = true;
			this.fireEvent('focus');
			this.element.addClass(this.prefix + '-focused');
			this.addPseudo('focus');
			focused = this;
			this.render();
		}
		return this;
	},

	//non-interactive
	disable: function(byParent){
		this.disabledByParent = false;
		if (!this.disabled){
			if (byParent) this.disabledByParent = true;
			this.blur();
			this.fireEvent('disable');
			this.keyboard.deactivate();
			this.childWidgets.each(function(child){
				child.disable(true);
			});
			this.element.addClass(this.prefix + '-disabled');
			this.addPseudo('disabled');
			this.disabled = true;
			this.render();
		}
		return this;
	},

	// normal states
	//visible
	show: function(){
		if (this.hidden){
			this.hidden = false;
			this.fireEvent('show');
			this.element.removeClass(this.prefix + '-hidden');
			this.removePseudo('hidden');
			this.render();
		}
		return this;
	},
	//the button is released, the select list is contracted, the mouse is up
	deactivate: function(){
		if (this.active){
			this.active = false;
			this.fireEvent('deactivate');
			this.element.removeClass(this.prefix + '-active');
			this.removePseudo('active');
			this.render();
		}
		return this;
	},

	//focus has shifted to another widget
	blur: function(){
		if (this.focused){
			this.focused = false;
			this.fireEvent('blur');
			this.keyboard.deactivate();
			this.element.removeClass(this.prefix + '-focused');
			this.removePseudo('focus');
			this.render();
		}
		return this;
	},
	//the widget is interactable
	enable: function(){
		if (this.parentWidget && this.parentWidget.disabled) {
			this.disabledByParent = true;
			return this;
		};
		delete this.disabledByParent;
		if (this.disabled){
			this.disabled = false;
			this.fireEvent('enable');
			this.element.removeClass(this.prefix + '-disabled');
			this.removePseudo('disabled');
			this.render();
		}
		this.childWidgets.each(function(child){
			if (child.disabledByParent) {
				child.enable();
				delete child.disabledByParent;
			}
		});
		return this;
	},

	attachKeys: function(events){
		this.keyboard.addEvents(events);
	},

	detachKeys: function(events) {
		this.keyboard.removeEvents(events);
	},

	addShortcut: function(name, shortcut) {
		this.keyboard.addShortcut(name, shortcut);
	},

	addShortcuts: function(obj) {
		this.keyboard.addShortcuts(obj);
	},

	removeShortcut: function(name) {
		this.keyboard.removeShortcut(name);
	},

	removeShortcuts: function(names) {
		this.keyboard.removeShortcuts(names);
	},

	getShortcut: function(name) {
		return this.keyboard.getShortcut(name);
	},

	getShortcuts: function() {
		return this.keyboard.getShortcuts();
	},

	destroy: function(){
		this.removeParent();
		$A(this.childWidgets).each(function(widget) {
			widget.destroy();
		});
		if (this.childWidgets.length && window.console && console.warn) {
			this.childWidgets.each(function(widget) {
				console.warn("warning: %s called the destroy method of %s but it failed. Ensure that destroy method calls this.parent", this.prefix, widget.prefix);
			}, this);
		}
		this.element.destroy();
		this.destroyed = true;
		return this.fireEvent('destroy');
	},

	// toElement

	toElement: function(){
		return this.element;
	},

	_redrawCount: 0,
	_counters: function(){
		this._redrawCount++;
		$clear(this._countTimer);
		this._countTimer = (function(){
			this._redrawCount = 0;
		}).delay(1000, this);
		console.log('redraw %s: ', this.name, this._redrawCount, this.element);
	}

});

ART._counts = function(){
	counting = !counting;
	if (counting) console.log('counting widget renders');
	else console.log('disabling widget render counts');
};

})();<|endoftext|>


<commit_before>var _ = require('underscore');

var socketio = {};
var config, player;

// called when nodeplayer is started to initialize the plugin
// do any necessary initialization here
socketio.init = function(_player, callback, errCallback) {
    player = _player;
    config = _player.config;

    if(!player.expressServer) {
        errCallback('module must be initialized after expressjs module!');
    } else {
        socketio.io = require('socket.io')(player.expressServer);
        socketio.io.on('connection', function(socket) {
            if(player.queue[0]) {
                socket.emit('playback', {
                    songID: player.queue[0].songID,
                    format: player.queue[0].format,
                    backendName: player.queue[0].backendName,
                    duration: player.queue[0].duration,
                    position: player.playbackPosition + (new Date() - player.playbackStart),
                    playbackStart: player.playbackStart
                });
            }
            socket.emit('queue', player.queue);
        });

        player.socketio = socketio;

        console.log('listening on port ' + (process.env.PORT || config.port));
        callback();
    }
};

socketio.onSongChange = function(player) {
    socketio.io.emit('playback', {
        songID: player.queue[0].songID,
        format: player.queue[0].format,
        backendName: player.queue[0].backendName,
        duration: player.queue[0].duration,
        position: player.playbackPosition + (new Date() - player.playbackStart),
        playbackStart: player.playbackStart
    });
    socketio.io.emit('queue', player.queue);
};

socketio.onSongPause = function(player) {
    socketio.io.emit('playback', null);
};

socketio.onQueueModify = function(player) {
    socketio.io.emit('queue', player.queue);
};

socketio.onEndOfQueue = function(player) {
    socketio.io.emit('playback', null);
    socketio.io.emit('queue', player.queue);
};

module.exports = socketio;
<commit_msg>send current position when pausing, just set playbackStart to null<commit_after>var _ = require('underscore');

var socketio = {};
var config, player;

// called when nodeplayer is started to initialize the plugin
// do any necessary initialization here
socketio.init = function(_player, callback, errCallback) {
    player = _player;
    config = _player.config;

    if(!player.expressServer) {
        errCallback('module must be initialized after expressjs module!');
    } else {
        socketio.io = require('socket.io')(player.expressServer);
        socketio.io.on('connection', function(socket) {
            if(player.queue[0]) {
                socket.emit('playback', {
                    songID: player.queue[0].songID,
                    format: player.queue[0].format,
                    backendName: player.queue[0].backendName,
                    duration: player.queue[0].duration,
                    position: player.playbackPosition + (new Date() - player.playbackStart),
                    playbackStart: player.playbackStart
                });
            }
            socket.emit('queue', player.queue);
        });

        player.socketio = socketio;

        console.log('listening on port ' + (process.env.PORT || config.port));
        callback();
    }
};

socketio.onSongChange = function(player) {
    socketio.io.emit('playback', {
        songID: player.queue[0].songID,
        format: player.queue[0].format,
        backendName: player.queue[0].backendName,
        duration: player.queue[0].duration,
        position: player.playbackPosition + (new Date() - player.playbackStart),
        playbackStart: player.playbackStart
    });
    socketio.io.emit('queue', player.queue);
};

socketio.onSongPause = function(player) {
    socketio.io.emit('playback', {
        songID: player.queue[0].songID,
        format: player.queue[0].format,
        backendName: player.queue[0].backendName,
        duration: player.queue[0].duration,
        position: player.playbackPosition + (new Date() - player.playbackStart),
        playbackStart: null
    });
};

socketio.onQueueModify = function(player) {
    socketio.io.emit('queue', player.queue);
};

socketio.onEndOfQueue = function(player) {
    socketio.io.emit('playback', null);
    socketio.io.emit('queue', player.queue);
};

module.exports = socketio;
<|endoftext|>


<commit_before>/*
Script: ART.Widget.js

License:
	MIT-style license.
*/

// Base widget class. Based on » http://gist.github.com/85837
(function(){

var counting, focused;

ART.Widget = new Class({

	Implements: [Options, Events],

	ns: 'art',
	name: 'widget',

	options: {
		// onShow: $empty,
		// onHide: $empty,
		// onFocus: $empty,
		// onBlur: $empty,
		// onEnable: $empty,
		// onDisable: $empty,
		// onDestroy: $empty,
		// onAdoption: $empty(parentWidget),
		// onOrphan: $empty(previousParent),
		// id: null,
		// style: null,
		renderWhileHidden: false,
		className: '',
		keyboardOptions: {
			active: true
		},
		parentWidget: null
	},

	initialize: function(options){
		this.latchEvents('adoption');
		this.pseudos = [];
		this.childWidgets = [];
		this.keyboard = new Keyboard();
		this.keyboard.widget = this;
		var parent;
		if (options) {
			if (options.parentWidget) {
				parent = options.parentWidget;
				delete options.parentWidget;
			}
		}
		this.setOptions(options);
		this.keyboard.setOptions(this.options.keyboardOptions).setup();
		this.prefix = this.ns + '-' + this.name;
		this.element = new Element('div', {
			id: this.options.id || this.prefix+new Date().getTime(),
			'class': this.options.className
		}).store(this.prefix, this).store('widget', this);
		this.element.addClass(this.ns).addClass(this.prefix);
		this.classes = this.options.classes;
		this.classes = (this.options.className) ? this.options.className.split(' ') : [];
		if (parent) this.setParent(parent);
	},

	getSelector: function(){
		var selector = (this.parentWidget) ? this.parentWidget.getSelector() + ' ' : '';
		selector += this.name;
		if (this.classes.length) selector += '.' + this.classes.join('.');
		if (this.pseudos.length) selector += ':' + this.pseudos.join(':');
		return selector;
	},

	addPseudo: function(pseudo){
		this.pseudos.include(pseudo);
	},

	removePseudo: function(pseudo){
		this.pseudos.erase(pseudo);
	},

	setParent: function(widget, initing){
		if (!initing) this.removeParent();
		this.parentWidget = widget;
		widget.childWidgets.include(this);
		this.parentWidget.keyboard.manage(this.keyboard);
		this.enable();
		this.fireEvent('adoption', widget);
		return this;
	},

	removeParent: function(){
		this.prevParent = this.parentWidget || this.prevParent;
		if (!this.prevParent) return;
		if (this.parentWidget) {
			this.parentWidget.childWidgets.erase(this);
			Keyboard.manager.manage(this.keyboard);
			this.parentWidget = null;
		}
		this.fireEvent('orphan', this.prevParent);
	},

	// render

	requireToRender: function(){
		this.requiredToRender = this.requiredToRender || [];
		$A(arguments).each(function(requirement) {
			this.requiredToRender.push(requirement);
		}, this);
	},

	readyToRender: function() {
		if (!this.requiredToRender || !this.requiredToRender.length) return;
		$A(arguments).each(function(requirement) {
			this.requiredToRender.erase(requirement);
		}, this);
	},

	redraw: function(){
		if (counting) this._counters();
		this.childWidgets.each(function(child) {
			child.render();
		});
		return this;
	},

	isReadyToRender: function(){
		var isReady = (!this.requiredToRender || !this.requiredToRender.length) && !this.destroyed && (this.options.renderWhileHidden || !this.hidden);
		if (isReady && this.parentWidget) isReady = this.parentWidget.isReadyToRender();
		return isReady;
	},

	render: function(override){
		if (this.isReadyToRender()) this.redraw(override);
		return this;
	},

	// special states

	hide: function(){
		if (!this.hidden){
			this.hidden = true;
			this.fireEvent('hide');
			this.element.addClass(this.prefix + '-hidden');
			this.addPseudo('hidden');
			this.render();
		}
		return this;
	},

	activate: function(){
		if (!this.active){
			this.active = true;
			this.fireEvent('activate');
			this.element.addClass(this.prefix + '-active');
			this.addPseudo('active');
			this.render();
		}
		return this;
	},

	focus: function(){
		if (!this.focused){
			this.focused = true;
			this.fireEvent('focus');
			this.element.addClass(this.prefix + '-focused');
			this.addPseudo('focus');
			if (focused) focused.blur();
			this.keyboard.activate();
			focused = this;
			this.render();
		}
		return this;
	},

	disable: function(byParent){
		this.disabledByParent = false;
		if (!this.disabled){
			if (byParent) this.disabledByParent = true;
			this.blur();
			this.fireEvent('disable');
			this.keyboard.deactivate();
			this.childWidgets.each(function(child){
				child.disable(true);
			});
			this.element.addClass(this.prefix + '-disabled');
			this.addPseudo('disabled');
			this.disabled = true;
			this.render();
		}
		return this;
	},

	// normal states

	show: function(){
		if (this.hidden){
			this.hidden = false;
			this.fireEvent('show');
			this.element.removeClass(this.prefix + '-hidden');
			this.removePseudo('hidden');
			this.render();
		}
		return this;
	},

	deactivate: function(){
		if (this.active){
			this.active = false;
			this.fireEvent('deactivate');
			this.element.removeClass(this.prefix + '-active');
			this.removePseudo('active');
			this.render();
		}
		return this;
	},

	blur: function(){
		if (this.focused){
			this.focused = false;
			this.fireEvent('blur');
			this.element.removeClass(this.prefix + '-focused');
			this.removePseudo('focus');
			this.render();
		}
		return this;
	},

	enable: function(){
		if (this.parentWidget && this.parentWidget.disabled) {
			this.disabledByParent = true;
			return this;
		};
		delete this.disabledByParent;
		if (this.disabled){
			this.disabled = false;
			this.keyboard.activate();
			this.fireEvent('enable');
			this.element.removeClass(this.prefix + '-disabled');
			this.removePseudo('disabled');
			this.render();
		}
		this.childWidgets.each(function(child){
			if (child.disabledByParent) {
				child.enable();
				delete child.disabledByParent;
			}
		});
		return this;
	},

	attachKeys: function(events){
		this.keyboard.addEvents(events);
	},

	detachKeys: function(events) {
		this.keyboard.removeEvents(events);
	},

	destroy: function(){
		this.removeParent();
		for (var kids = 0; kids < this.childWidgets.length; kids++) {
			this.childWidgets[0].destroy();
		}
		if (this.childWidgets.length && window.console && console.warn) {
			this.childWidgets.each(function(widget) {
				console.warn("warning: %s called the destroy method of %s but it failed. Ensure that destroy method calls this.parent", this.pefix, widget.prefix);
			});
		}
		this.element.destroy();
		this.destroyed = true;
		return this.fireEvent('destroy');
	},

	// toElement

	toElement: function(){
		return this.element;
	},

	_redrawCount: 0,
	_counters: function(){
		this._redrawCount++;
		$clear(this._countTimer);
		this._countTimer = (function(){
			this._redrawCount = 0;
		}).delay(1000, this);
		console.log('redraw %s: ', this.name, this._redrawCount, this.element);
	}

});

ART._counts = function(){
	counting = !counting;
	if (counting) console.log('counting widget renders');
	else console.log('disabling widget render counts');
};

})();<commit_msg>fixing my warning and destroy stuff in widget...<commit_after>/*
Script: ART.Widget.js

License:
	MIT-style license.
*/

// Base widget class. Based on » http://gist.github.com/85837
(function(){

var counting, focused;

ART.Widget = new Class({

	Implements: [Options, Events],

	ns: 'art',
	name: 'widget',

	options: {
		// onShow: $empty,
		// onHide: $empty,
		// onFocus: $empty,
		// onBlur: $empty,
		// onEnable: $empty,
		// onDisable: $empty,
		// onDestroy: $empty,
		// onAdoption: $empty(parentWidget),
		// onOrphan: $empty(previousParent),
		// id: null,
		// style: null,
		renderWhileHidden: false,
		className: '',
		keyboardOptions: {
			active: true
		},
		parentWidget: null
	},

	initialize: function(options){
		this.latchEvents('adoption');
		this.pseudos = [];
		this.childWidgets = [];
		this.keyboard = new Keyboard();
		this.keyboard.widget = this;
		var parent;
		if (options) {
			if (options.parentWidget) {
				parent = options.parentWidget;
				delete options.parentWidget;
			}
		}
		this.setOptions(options);
		this.keyboard.setOptions(this.options.keyboardOptions).setup();
		this.prefix = this.ns + '-' + this.name;
		this.element = new Element('div', {
			id: this.options.id || this.prefix+new Date().getTime(),
			'class': this.options.className
		}).store(this.prefix, this).store('widget', this);
		this.element.addClass(this.ns).addClass(this.prefix);
		this.classes = this.options.classes;
		this.classes = (this.options.className) ? this.options.className.split(' ') : [];
		if (parent) this.setParent(parent);
	},

	getSelector: function(){
		var selector = (this.parentWidget) ? this.parentWidget.getSelector() + ' ' : '';
		selector += this.name;
		if (this.classes.length) selector += '.' + this.classes.join('.');
		if (this.pseudos.length) selector += ':' + this.pseudos.join(':');
		return selector;
	},

	addPseudo: function(pseudo){
		this.pseudos.include(pseudo);
	},

	removePseudo: function(pseudo){
		this.pseudos.erase(pseudo);
	},

	setParent: function(widget, initing){
		if (!initing) this.removeParent();
		this.parentWidget = widget;
		widget.childWidgets.include(this);
		this.parentWidget.keyboard.manage(this.keyboard);
		this.enable();
		this.fireEvent('adoption', widget);
		return this;
	},

	removeParent: function(){
		this.prevParent = this.parentWidget || this.prevParent;
		if (!this.prevParent) return;
		if (this.parentWidget) {
			this.parentWidget.childWidgets.erase(this);
			Keyboard.manager.manage(this.keyboard);
			this.parentWidget = null;
		}
		this.fireEvent('orphan', this.prevParent);
	},

	// render

	requireToRender: function(){
		this.requiredToRender = this.requiredToRender || [];
		$A(arguments).each(function(requirement) {
			this.requiredToRender.push(requirement);
		}, this);
	},

	readyToRender: function() {
		if (!this.requiredToRender || !this.requiredToRender.length) return;
		$A(arguments).each(function(requirement) {
			this.requiredToRender.erase(requirement);
		}, this);
	},

	redraw: function(){
		if (counting) this._counters();
		this.childWidgets.each(function(child) {
			child.render();
		});
		return this;
	},

	isReadyToRender: function(){
		var isReady = (!this.requiredToRender || !this.requiredToRender.length) && !this.destroyed && (this.options.renderWhileHidden || !this.hidden);
		if (isReady && this.parentWidget) isReady = this.parentWidget.isReadyToRender();
		return isReady;
	},

	render: function(override){
		if (this.isReadyToRender()) this.redraw(override);
		return this;
	},

	// special states

	hide: function(){
		if (!this.hidden){
			this.hidden = true;
			this.fireEvent('hide');
			this.element.addClass(this.prefix + '-hidden');
			this.addPseudo('hidden');
			this.render();
		}
		return this;
	},

	activate: function(){
		if (!this.active){
			this.active = true;
			this.fireEvent('activate');
			this.element.addClass(this.prefix + '-active');
			this.addPseudo('active');
			this.render();
		}
		return this;
	},

	focus: function(){
		if (!this.focused){
			this.focused = true;
			this.fireEvent('focus');
			this.element.addClass(this.prefix + '-focused');
			this.addPseudo('focus');
			if (focused) focused.blur();
			this.keyboard.activate();
			focused = this;
			this.render();
		}
		return this;
	},

	disable: function(byParent){
		this.disabledByParent = false;
		if (!this.disabled){
			if (byParent) this.disabledByParent = true;
			this.blur();
			this.fireEvent('disable');
			this.keyboard.deactivate();
			this.childWidgets.each(function(child){
				child.disable(true);
			});
			this.element.addClass(this.prefix + '-disabled');
			this.addPseudo('disabled');
			this.disabled = true;
			this.render();
		}
		return this;
	},

	// normal states

	show: function(){
		if (this.hidden){
			this.hidden = false;
			this.fireEvent('show');
			this.element.removeClass(this.prefix + '-hidden');
			this.removePseudo('hidden');
			this.render();
		}
		return this;
	},

	deactivate: function(){
		if (this.active){
			this.active = false;
			this.fireEvent('deactivate');
			this.element.removeClass(this.prefix + '-active');
			this.removePseudo('active');
			this.render();
		}
		return this;
	},

	blur: function(){
		if (this.focused){
			this.focused = false;
			this.fireEvent('blur');
			this.element.removeClass(this.prefix + '-focused');
			this.removePseudo('focus');
			this.render();
		}
		return this;
	},

	enable: function(){
		if (this.parentWidget && this.parentWidget.disabled) {
			this.disabledByParent = true;
			return this;
		};
		delete this.disabledByParent;
		if (this.disabled){
			this.disabled = false;
			this.keyboard.activate();
			this.fireEvent('enable');
			this.element.removeClass(this.prefix + '-disabled');
			this.removePseudo('disabled');
			this.render();
		}
		this.childWidgets.each(function(child){
			if (child.disabledByParent) {
				child.enable();
				delete child.disabledByParent;
			}
		});
		return this;
	},

	attachKeys: function(events){
		this.keyboard.addEvents(events);
	},

	detachKeys: function(events) {
		this.keyboard.removeEvents(events);
	},

	destroy: function(){
		this.removeParent();
		$A(this.childWidgets).each(function(widget) {
			widget.destroy();
		});
		if (this.childWidgets.length && window.console && console.warn) {
			this.childWidgets.each(function(widget) {
				console.warn("warning: %s called the destroy method of %s but it failed. Ensure that destroy method calls this.parent", this.prefix, widget.prefix);
			}, this);
		}
		this.element.destroy();
		this.destroyed = true;
		return this.fireEvent('destroy');
	},

	// toElement

	toElement: function(){
		return this.element;
	},

	_redrawCount: 0,
	_counters: function(){
		this._redrawCount++;
		$clear(this._countTimer);
		this._countTimer = (function(){
			this._redrawCount = 0;
		}).delay(1000, this);
		console.log('redraw %s: ', this.name, this._redrawCount, this.element);
	}

});

ART._counts = function(){
	counting = !counting;
	if (counting) console.log('counting widget renders');
	else console.log('disabling widget render counts');
};

})();<|endoftext|>


<commit_before>Template.tickerFormation.helpers({
    sortFormation: function (formation) {
        var getValue = function(value) {
            var pos = POSITIONS.indexOf(value.gamePosition);
            return pos < 0 ? 9999 : 1 + pos;
        };

        return formation.sort(function (value1, value2) {
            return getValue(value1) - getValue(value2);
        });
    }
});

Template.tickerFormationEntry.helpers({
    isInFormation: function (position) {
        return position && position != POS_NA;
    }
});<commit_msg>sorting substitute players by position<commit_after>Template.tickerFormation.helpers({
    sortFormation: function (formation) {
        var offset = POSITIONS.length;
        var getValue = function(value) {
            var pos = POSITIONS.indexOf(value.gamePosition);

            if (pos < 0) {
                pos = offset + POSITIONS.indexOf(value.position);
            }

            return pos < 0 ? 9999 : 1 + pos;
        };

        return formation.sort(function (value1, value2) {
            return getValue(value1) - getValue(value2);
        });
    }
});

Template.tickerFormationEntry.helpers({
    isInFormation: function (position) {
        return position && position != POS_NA;
    }
});<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/destroyObject',
        '../Core/Matrix4',
        '../Core/MeshFilters',
        '../Core/PrimitiveType',
        '../Renderer/BufferUsage',
        '../Renderer/VertexLayout',
        '../Renderer/CommandLists',
        '../Renderer/DrawCommand',
        './SceneMode'
    ], function(
        destroyObject,
        Matrix4,
        MeshFilters,
        PrimitiveType,
        BufferUsage,
        VertexLayout,
        CommandLists,
        DrawCommand,
        SceneMode) {
    "use strict";

    /**
     * DOC_TBA
     */
    var Primitive = function(mesh, appearance) {
        /**
         * DOC_TBA
         */
        this.mesh = mesh;

        /**
         * DOC_TBA
         */
        this.appearance = appearance;

        /**
         * DOC_TBA
         */
        this.modelMatrix = Matrix4.IDENTITY.clone();

        /**
         * DOC_TBA
         */
        this.show = true;

        this._sp = undefined;
        this._rs = undefined;
        this._va = undefined;

        this._commands = [];
        this._commandLists = new CommandLists();
    };

    /**
     * @private
     */
    Primitive.prototype.update = function(context, frameState, commandList) {
        if (!this.show || (frameState.mode !== SceneMode.SCENE3D)) {
// TODO: support Columbus view and 2D
            return;
        }

// TODO: throw if mesh and appearance are not defined

        if (typeof this._va === 'undefined') {
            var attributeIndices = MeshFilters.createAttributeIndices(this.mesh);
            var appearance = this.appearance;

            this._va = context.createVertexArrayFromMesh({
                mesh : this.mesh,
                attributeIndices : attributeIndices,
                bufferUsage : BufferUsage.STATIC_DRAW,
                vertexLayout : VertexLayout.INTERLEAVED
            });
            this._sp = context.getShaderCache().replaceShaderProgram(this._sp, appearance.vertexShaderSource, appearance.getFragmentShaderSource(), attributeIndices);
            this._rs = context.createRenderState(appearance.renderState);

            var command = new DrawCommand();
// TODO: this assumes indices in the mesh - and only one set
            command.primitiveType = this.mesh.indexLists[0].primitiveType;
            command.vertexArray = this._va;
            command.renderState = this._rs;
            command.shaderProgram = this._sp;
            command.uniformMap = appearance.material._uniforms;
// TODO:    command.boundingVolume =
            this._commands.push(command);
        }

        if (frameState.passes.color) {
            var commands = this._commands;
            var len = commands.length;
            for (var i = 0; i < len; ++i) {
                commands[i].modelMatrix = this.modelMatrix;
                this._commandLists.colorList[i] = commands[i];
            }
            commandList.push(this._commandLists);
        }
    };

    /**
     * DOC_TBA
     */
    Primitive.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * DOC_TBA
     */
    Primitive.prototype.destroy = function() {
        this._sp = this._sp && this._sp.release();
        this._va = this._va && this._va.destroy();
        return destroyObject(this);
    };

    return Primitive;
});<commit_msg>Add owner to generic primitive command<commit_after>/*global define*/
define([
        '../Core/destroyObject',
        '../Core/Matrix4',
        '../Core/MeshFilters',
        '../Core/PrimitiveType',
        '../Renderer/BufferUsage',
        '../Renderer/VertexLayout',
        '../Renderer/CommandLists',
        '../Renderer/DrawCommand',
        './SceneMode'
    ], function(
        destroyObject,
        Matrix4,
        MeshFilters,
        PrimitiveType,
        BufferUsage,
        VertexLayout,
        CommandLists,
        DrawCommand,
        SceneMode) {
    "use strict";

    /**
     * DOC_TBA
     */
    var Primitive = function(mesh, appearance) {
        /**
         * DOC_TBA
         */
        this.mesh = mesh;

        /**
         * DOC_TBA
         */
        this.appearance = appearance;

        /**
         * DOC_TBA
         */
        this.modelMatrix = Matrix4.IDENTITY.clone();

        /**
         * DOC_TBA
         */
        this.show = true;

        this._sp = undefined;
        this._rs = undefined;
        this._va = undefined;

        this._commands = [];
        this._commandLists = new CommandLists();
    };

    /**
     * @private
     */
    Primitive.prototype.update = function(context, frameState, commandList) {
        if (!this.show || (frameState.mode !== SceneMode.SCENE3D)) {
// TODO: support Columbus view and 2D
            return;
        }

// TODO: throw if mesh and appearance are not defined

        if (typeof this._va === 'undefined') {
            var attributeIndices = MeshFilters.createAttributeIndices(this.mesh);
            var appearance = this.appearance;

            this._va = context.createVertexArrayFromMesh({
                mesh : this.mesh,
                attributeIndices : attributeIndices,
                bufferUsage : BufferUsage.STATIC_DRAW,
                vertexLayout : VertexLayout.INTERLEAVED
            });
            this._sp = context.getShaderCache().replaceShaderProgram(this._sp, appearance.vertexShaderSource, appearance.getFragmentShaderSource(), attributeIndices);
            this._rs = context.createRenderState(appearance.renderState);

            var command = new DrawCommand();
// TODO: best owner?  Include mesh?
            command.owner = this;
// TODO: this assumes indices in the mesh - and only one set
            command.primitiveType = this.mesh.indexLists[0].primitiveType;
            command.vertexArray = this._va;
            command.renderState = this._rs;
            command.shaderProgram = this._sp;
            command.uniformMap = appearance.material._uniforms;
// TODO:    command.boundingVolume =
            this._commands.push(command);
        }

        if (frameState.passes.color) {
            var commands = this._commands;
            var len = commands.length;
            for (var i = 0; i < len; ++i) {
                commands[i].modelMatrix = this.modelMatrix;
                this._commandLists.colorList[i] = commands[i];
            }
            commandList.push(this._commandLists);
        }
    };

    /**
     * DOC_TBA
     */
    Primitive.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * DOC_TBA
     */
    Primitive.prototype.destroy = function() {
        this._sp = this._sp && this._sp.release();
        this._va = this._va && this._va.destroy();
        return destroyObject(this);
    };

    return Primitive;
});<|endoftext|>


<commit_before>L.Control.Screenshot = L.Control.extend({
    includes: L.Mixin.Events,
    options: {
        position: 'topleft',
    },
    statics: {
        TITLE:  'Screenshot'
    },

    initialize: function (url, getcontext) {
        this.url = url;
        this.getcontext = getcontext;
    },

    screenshot: function () {
        // Screenshot effect
        $('

')
            .appendTo(document.body)
            .fadeOut();

        var fullContext = this.getcontext();
        // Hack to download response attachment in Ajax
        $('<form action="' + this.url + '" method="post">' +
        '<textarea name="printcontext">' + fullContext + '</textarea>' +
        '</form>').appendTo('body').submit().remove();
        this.fire('triggered');
    },

    onAdd: function(map) {
        this.map = map;
        this._container = L.DomUtil.create('div', 'leaflet-control-zoom leaflet-control leaflet-bar');
        var link = L.DomUtil.create('a', 'leaflet-control-zoom-out screenshot-control', this._container);
        link.href = '#';
        link.title = L.Control.Screenshot.TITLE;

        L.DomEvent
            .addListener(link, 'click', L.DomEvent.stopPropagation)
            .addListener(link, 'click', L.DomEvent.preventDefault)
            .addListener(link, 'click', this.screenshot, this);
        return this._container;
    }
});

/**
 * Shows a static label in the middle of the Polyline.
 * It will be hidden on zoom levels below ``LABEL_MIN_ZOOM``.
 */
MapEntity.showLineLabel = function (layer, options) {
    var LABEL_MIN_ZOOM = 6;

    var rgb = parseColor(options.color);

    layer.bindLabel(options.text, {noHide: true, className: options.className});

    var __layerOnAdd = layer.onAdd;
    layer.onAdd = function (map) {
        __layerOnAdd.call(layer, map);
        if (map.getZoom() >= LABEL_MIN_ZOOM) {
            layer._showLabel();
        }
        map.on('zoomend', hideOnZoomOut);
    };

    var __layerOnRemove = layer.onRemove;
    layer.onRemove = function () {
        layer._map.off('zoomend', hideOnZoomOut);
        if (layer._hideLabel) layer._hideLabel();
        __layerOnRemove.call(layer);
    };

    var __layerShowLabel = layer._showLabel;
    layer._showLabel = function () {
        __layerShowLabel.call(layer, {latlng: midLatLng(layer)});
        layer.label._container.title = options.title;
        layer.label._container.style.backgroundColor = 'rgba('+rgb.join(',')+ ',0.8)';
        layer.label._container.style.borderColor = 'rgba('+rgb.join(',')+ ',0.6)';
    };

    function hideOnZoomOut() {
        if (layer._map.getZoom() < LABEL_MIN_ZOOM)
            if (layer._hideLabel) layer._hideLabel();
        else
            if (layer._showLabel) layer._showLabel();
    }

    function midLatLng(line) {
        var mid = Math.floor(line.getLatLngs().length/2);
        return L.latLng(line.getLatLngs()[mid]);
    }
};

$(window).on('entity:map', function (e, data) {
    var map = data.map,
        $container = $(map._container),
        readonly = $container.data('readonly');

    // Replace default layer switcher with Leaflet.GroupedLayerSwitcher
    if (map.layerscontrol) {
        map.layerscontrol.removeFrom(map);
    }
    var baseLayers = {};
    var overlaysLayers = {};
    for (var l in map.layerscontrol._layers) {
        var layer = map.layerscontrol._layers[l];
        if (layer.overlay)
            overlaysLayers[layer.name] = layer.layer;
        else
            baseLayers[layer.name] = layer.layer;
    }
    var layerscontrol = L.control.groupedLayers(baseLayers, {'': overlaysLayers});
    map.layerscontrol = layerscontrol.addTo(map);

    if (readonly) {
        // Set map readonly
        map.dragging.disable();
        map.touchZoom.disable();
        map.doubleClickZoom.disable();
        map.scrollWheelZoom.disable();
        map.boxZoom.disable();
    }

    map.attributionControl.setPrefix('');

    var mapBounds = $container.data('mapextent');
    if (mapBounds) {
        map.fitBounds(mapBounds);
        var maxZoom = $container.data('fitmaxzoom');
        if (map.getZoom() > maxZoom) {
            console.log('Limited zoom to ', maxZoom, '. Was ', map.getZoom());
            map.setZoom(maxZoom);
        }
        map.resetviewControl.getBounds = function () { return mapBounds; };
    }

    map.addControl(new L.Control.FullScreen());
    map.addControl(new L.Control.MeasureControl());

    map.on("moveend", function () {
        var bounds = map.getBounds();
        $('#id_in_bbox').val(`${bounds.getSouthWest().lng},${bounds.getSouthWest().lat},${bounds.getNorthEast().lng},${bounds.getNorthEast().lat}`);
    });
});

$(window).on('entity:map:detail', function (e, data) {
    var map = data.map,
        $container = $(map._container);

    // Map screenshot button
    var screenshot = new L.Control.Screenshot(window.SETTINGS.urls.screenshot, function () {
        context = MapEntity.Context.getFullContext(map);
        context['selector'] = '#detailmap';
        return JSON.stringify(context);
    });
    map.addControl(screenshot);

    // Restore map context, only for screenshoting purpose
    var context = getURLParameter('context');
    if (context && typeof context == 'object') {
        MapEntity.Context.restoreFullContext(map, context);
    }

    // Save map context : will be restored on next form (e.g. interventions, ref story #182)
    $(window).unload(function () {
        MapEntity.Context.saveFullContext(map, {prefix: 'detail'});
    });

    // Show object geometry in detail map
    var $singleObject = $container.find('.geojsonfeature'),
        objectLayer = null;
    if ($singleObject.length > 0) {
        objectLayer = _showSingleObject(JSON.parse($singleObject.text()));
    }

    $(window).trigger('detailmap:ready', {map: map,
                                          layer: objectLayer,
                                          context: context,
                                          modelname: data.modelname});

    function _showSingleObject(geojson) {
        var DETAIL_STYLE = L.Util.extend(window.SETTINGS.map.styles.detail, {clickable: false});

        // Apparence of geometry for export can be controlled via setting
        if (context && context.print) {
            var specified = window.SETTINGS.map.styles.print[data.modelname];
            if (specified) {
                DETAIL_STYLE = L.Util.extend(DETAIL_STYLE, specified);
            }
        }

        // Add layers
        var objectLayer = new L.ObjectsLayer(geojson, {
            style: DETAIL_STYLE,
            indexing: false,
            modelname: data.modelname
        });
        map.addLayer(objectLayer);
        map.on('layeradd', function (e) {
            if (!e.layer.properties && objectLayer._map) {
                objectLayer.bringToFront();
            }
        });

        // Show objects enumeration
        var sublayers = objectLayer.getLayers();
        if (sublayers.length === 1) {
            // Single layer, but multi-* or geometrycollection
            if (typeof sublayers[0].getLayers === 'function') {
                sublayers[0].showEnumeration();
            }
        }
        else {
            objectLayer.showEnumeration();
        }

        return objectLayer;
    }
});

$(window).on('entity:map:list', function (e, data) {
    var map = data.map,
        bounds = L.latLngBounds(data.options.extent);

    map.removeControl(map.attributionControl);
    map.doubleClickZoom.disable();

    map.addControl(new L.Control.Information());
    map.addControl(new L.Control.ResetView(bounds));

    /*
     * Objects Layer
     * .......................
     */
    function getUrl(properties, layer) {
        return window.SETTINGS.urls.detail.replace(new RegExp('modelname', 'g'), data.modelname)
                                          .replace('0', properties.pk);
    }

    var style = window.SETTINGS.map.styles[data.modelname];
    if (style === undefined) {
        style = window.SETTINGS.map.styles.others;
    }
    if (!(typeof window.SETTINGS.map.styles.others === "function")) {
        var style = L.Util.extend({}, style);
    }
    var objectsLayer = new L.ObjectsLayer(null, {
        objectUrl: getUrl,
        style: style,
        modelname: data.modelname,
        onEachFeature: function (geojson, layer) {
            if (geojson.properties.name) layer.bindLabel(geojson.properties.name);
        }
    });
    objectsLayer.on('highlight select', function (e) {
        if (data.modelname != 'site' && e.layer._map !== null) e.layer.bringToFront();
    });

    map.addLayer(objectsLayer);
    objectsLayer.load(window.SETTINGS.urls.layer.replace(new RegExp('modelname', 'g'), data.modelname));

    var nameHTML = '▣ ' + data.objectsname;
    map.layerscontrol.addOverlay(objectsLayer, nameHTML, tr("Objects"));

    var dt = MapEntity.mainDatatable;

    /*
     * Assemble components
     * .......................
     */
    var mapsync = new L.MapListSync(dt,
                                    map,
                                    objectsLayer, {
                                        filter: {
                                            form: $('#mainfilter'),
                                            submitbutton: $('#filter'),
                                            resetbutton: $('#reset'),
                                            bboxfield: $('#id_bbox'),
                                        }
                                    });
    mapsync.on('reloaded', function (data) {
        // Show and save number of results
        MapEntity.history.saveListInfo({model: data.modelname,
                                        nb: data.nbrecords});
        // Show layer info
        objectsLayer.fire('info', {info : (data.nbrecords + ' ' + tr("results"))});
    });

    // Main filter
    var t = new MapEntity.TogglableFilter();
    mapsync.on('reloaded', function (data) {
        t.setsubmit();
    });

    // Map screenshot button
    var screenshot = new L.Control.Screenshot(window.SETTINGS.urls.screenshot, function () {
        context = MapEntity.Context.getFullContext(map, {
            filter: '#mainfilter',
            datatable: dt
        });
        context['selector'] = '#mainmap';
        return JSON.stringify(context);
    });
    map.addControl(screenshot);

    /*
     * Allow to load files locally.
     */
    var pointToLayer = function (feature, latlng) {
            return L.circleMarker(latlng, {style: window.SETTINGS.map.styles.filelayer})
                    .setRadius(window.SETTINGS.map.styles.filelayer.radius);
        },
        onEachFeature = function (feature, layer) {
            if (feature.properties.name) {
                layer.bindLabel(feature.properties.name);
            }
        },
        filecontrol = L.Control.fileLayerLoad({
            fitBounds: true,
            layerOptions: {style: window.SETTINGS.map.styles.filelayer,
                           pointToLayer: pointToLayer,
                           onEachFeature: onEachFeature}
        });
    map.filecontrol = filecontrol;
    map.addControl(filecontrol);

    // Restore map view, layers and filter from any available context
    // Get context from URL parameter, if any
    var mapViewContext = getURLParameter('context'),
        layerLabel = $('

').append(nameHTML).text();
    MapEntity.Context.restoreFullContext(map,
        // From URL param
        mapViewContext,
        // Parameters
        {
            filter: '#mainfilter',
            datatable: dt,
            objectsname: layerLabel,
            // We can have several contexts in the application (mainly 'detail' and 'list')
            // Using prefixes is a way to manage this.
            prefix: 'list',
        }
    );
    $(window).unload(function () {
        MapEntity.Context.saveFullContext(map, {
            filter: '#mainfilter',
            datatable: dt,
            prefix: 'list',
        });
    });
});
<commit_msg>use new in_bbox field<commit_after>L.Control.Screenshot = L.Control.extend({
    includes: L.Mixin.Events,
    options: {
        position: 'topleft',
    },
    statics: {
        TITLE:  'Screenshot'
    },

    initialize: function (url, getcontext) {
        this.url = url;
        this.getcontext = getcontext;
    },

    screenshot: function () {
        // Screenshot effect
        $('

')
            .appendTo(document.body)
            .fadeOut();

        var fullContext = this.getcontext();
        // Hack to download response attachment in Ajax
        $('<form action="' + this.url + '" method="post">' +
        '<textarea name="printcontext">' + fullContext + '</textarea>' +
        '</form>').appendTo('body').submit().remove();
        this.fire('triggered');
    },

    onAdd: function(map) {
        this.map = map;
        this._container = L.DomUtil.create('div', 'leaflet-control-zoom leaflet-control leaflet-bar');
        var link = L.DomUtil.create('a', 'leaflet-control-zoom-out screenshot-control', this._container);
        link.href = '#';
        link.title = L.Control.Screenshot.TITLE;

        L.DomEvent
            .addListener(link, 'click', L.DomEvent.stopPropagation)
            .addListener(link, 'click', L.DomEvent.preventDefault)
            .addListener(link, 'click', this.screenshot, this);
        return this._container;
    }
});

/**
 * Shows a static label in the middle of the Polyline.
 * It will be hidden on zoom levels below ``LABEL_MIN_ZOOM``.
 */
MapEntity.showLineLabel = function (layer, options) {
    var LABEL_MIN_ZOOM = 6;

    var rgb = parseColor(options.color);

    layer.bindLabel(options.text, {noHide: true, className: options.className});

    var __layerOnAdd = layer.onAdd;
    layer.onAdd = function (map) {
        __layerOnAdd.call(layer, map);
        if (map.getZoom() >= LABEL_MIN_ZOOM) {
            layer._showLabel();
        }
        map.on('zoomend', hideOnZoomOut);
    };

    var __layerOnRemove = layer.onRemove;
    layer.onRemove = function () {
        layer._map.off('zoomend', hideOnZoomOut);
        if (layer._hideLabel) layer._hideLabel();
        __layerOnRemove.call(layer);
    };

    var __layerShowLabel = layer._showLabel;
    layer._showLabel = function () {
        __layerShowLabel.call(layer, {latlng: midLatLng(layer)});
        layer.label._container.title = options.title;
        layer.label._container.style.backgroundColor = 'rgba('+rgb.join(',')+ ',0.8)';
        layer.label._container.style.borderColor = 'rgba('+rgb.join(',')+ ',0.6)';
    };

    function hideOnZoomOut() {
        if (layer._map.getZoom() < LABEL_MIN_ZOOM)
            if (layer._hideLabel) layer._hideLabel();
        else
            if (layer._showLabel) layer._showLabel();
    }

    function midLatLng(line) {
        var mid = Math.floor(line.getLatLngs().length/2);
        return L.latLng(line.getLatLngs()[mid]);
    }
};

$(window).on('entity:map', function (e, data) {
    var map = data.map,
        $container = $(map._container),
        readonly = $container.data('readonly');

    // Replace default layer switcher with Leaflet.GroupedLayerSwitcher
    if (map.layerscontrol) {
        map.layerscontrol.removeFrom(map);
    }
    var baseLayers = {};
    var overlaysLayers = {};
    for (var l in map.layerscontrol._layers) {
        var layer = map.layerscontrol._layers[l];
        if (layer.overlay)
            overlaysLayers[layer.name] = layer.layer;
        else
            baseLayers[layer.name] = layer.layer;
    }
    var layerscontrol = L.control.groupedLayers(baseLayers, {'': overlaysLayers});
    map.layerscontrol = layerscontrol.addTo(map);

    if (readonly) {
        // Set map readonly
        map.dragging.disable();
        map.touchZoom.disable();
        map.doubleClickZoom.disable();
        map.scrollWheelZoom.disable();
        map.boxZoom.disable();
    }

    map.attributionControl.setPrefix('');

    var mapBounds = $container.data('mapextent');
    if (mapBounds) {
        map.fitBounds(mapBounds);
        var maxZoom = $container.data('fitmaxzoom');
        if (map.getZoom() > maxZoom) {
            console.log('Limited zoom to ', maxZoom, '. Was ', map.getZoom());
            map.setZoom(maxZoom);
        }
        map.resetviewControl.getBounds = function () { return mapBounds; };
    }

    map.addControl(new L.Control.FullScreen());
    map.addControl(new L.Control.MeasureControl());

    map.on("moveend", function () {
        var bounds = map.getBounds();
        $('#id_in_bbox').val(`${bounds.getSouthWest().lng},${bounds.getSouthWest().lat},${bounds.getNorthEast().lng},${bounds.getNorthEast().lat}`);
    });
});

$(window).on('entity:map:detail', function (e, data) {
    var map = data.map,
        $container = $(map._container);

    // Map screenshot button
    var screenshot = new L.Control.Screenshot(window.SETTINGS.urls.screenshot, function () {
        context = MapEntity.Context.getFullContext(map);
        context['selector'] = '#detailmap';
        return JSON.stringify(context);
    });
    map.addControl(screenshot);

    // Restore map context, only for screenshoting purpose
    var context = getURLParameter('context');
    if (context && typeof context == 'object') {
        MapEntity.Context.restoreFullContext(map, context);
    }

    // Save map context : will be restored on next form (e.g. interventions, ref story #182)
    $(window).unload(function () {
        MapEntity.Context.saveFullContext(map, {prefix: 'detail'});
    });

    // Show object geometry in detail map
    var $singleObject = $container.find('.geojsonfeature'),
        objectLayer = null;
    if ($singleObject.length > 0) {
        objectLayer = _showSingleObject(JSON.parse($singleObject.text()));
    }

    $(window).trigger('detailmap:ready', {map: map,
                                          layer: objectLayer,
                                          context: context,
                                          modelname: data.modelname});

    function _showSingleObject(geojson) {
        var DETAIL_STYLE = L.Util.extend(window.SETTINGS.map.styles.detail, {clickable: false});

        // Apparence of geometry for export can be controlled via setting
        if (context && context.print) {
            var specified = window.SETTINGS.map.styles.print[data.modelname];
            if (specified) {
                DETAIL_STYLE = L.Util.extend(DETAIL_STYLE, specified);
            }
        }

        // Add layers
        var objectLayer = new L.ObjectsLayer(geojson, {
            style: DETAIL_STYLE,
            indexing: false,
            modelname: data.modelname
        });
        map.addLayer(objectLayer);
        map.on('layeradd', function (e) {
            if (!e.layer.properties && objectLayer._map) {
                objectLayer.bringToFront();
            }
        });

        // Show objects enumeration
        var sublayers = objectLayer.getLayers();
        if (sublayers.length === 1) {
            // Single layer, but multi-* or geometrycollection
            if (typeof sublayers[0].getLayers === 'function') {
                sublayers[0].showEnumeration();
            }
        }
        else {
            objectLayer.showEnumeration();
        }

        return objectLayer;
    }
});

$(window).on('entity:map:list', function (e, data) {
    var map = data.map,
        bounds = L.latLngBounds(data.options.extent);

    map.removeControl(map.attributionControl);
    map.doubleClickZoom.disable();

    map.addControl(new L.Control.Information());
    map.addControl(new L.Control.ResetView(bounds));

    /*
     * Objects Layer
     * .......................
     */
    function getUrl(properties, layer) {
        return window.SETTINGS.urls.detail.replace(new RegExp('modelname', 'g'), data.modelname)
                                          .replace('0', properties.pk);
    }

    var style = window.SETTINGS.map.styles[data.modelname];
    if (style === undefined) {
        style = window.SETTINGS.map.styles.others;
    }
    if (!(typeof window.SETTINGS.map.styles.others === "function")) {
        var style = L.Util.extend({}, style);
    }
    var objectsLayer = new L.ObjectsLayer(null, {
        objectUrl: getUrl,
        style: style,
        modelname: data.modelname,
        onEachFeature: function (geojson, layer) {
            if (geojson.properties.name) layer.bindLabel(geojson.properties.name);
        }
    });
    objectsLayer.on('highlight select', function (e) {
        if (data.modelname != 'site' && e.layer._map !== null) e.layer.bringToFront();
    });

    map.addLayer(objectsLayer);
    objectsLayer.load(window.SETTINGS.urls.layer.replace(new RegExp('modelname', 'g'), data.modelname));

    var nameHTML = '▣ ' + data.objectsname;
    map.layerscontrol.addOverlay(objectsLayer, nameHTML, tr("Objects"));

    var dt = MapEntity.mainDatatable;

    /*
     * Assemble components
     * .......................
     */
    var mapsync = new L.MapListSync(dt,
                                    map,
                                    objectsLayer, {
                                        filter: {
                                            form: $('#mainfilter'),
                                            submitbutton: $('#filter'),
                                            resetbutton: $('#reset'),
                                            bboxfield: $('#id_in_bbox'),
                                        }
                                    });
    mapsync.on('reloaded', function (data) {
        // Show and save number of results
        MapEntity.history.saveListInfo({model: data.modelname,
                                        nb: data.nbrecords});
        // Show layer info
        objectsLayer.fire('info', {info : (data.nbrecords + ' ' + tr("results"))});
    });

    // Main filter
    var t = new MapEntity.TogglableFilter();
    mapsync.on('reloaded', function (data) {
        t.setsubmit();
    });

    // Map screenshot button
    var screenshot = new L.Control.Screenshot(window.SETTINGS.urls.screenshot, function () {
        context = MapEntity.Context.getFullContext(map, {
            filter: '#mainfilter',
            datatable: dt
        });
        context['selector'] = '#mainmap';
        return JSON.stringify(context);
    });
    map.addControl(screenshot);

    /*
     * Allow to load files locally.
     */
    var pointToLayer = function (feature, latlng) {
            return L.circleMarker(latlng, {style: window.SETTINGS.map.styles.filelayer})
                    .setRadius(window.SETTINGS.map.styles.filelayer.radius);
        },
        onEachFeature = function (feature, layer) {
            if (feature.properties.name) {
                layer.bindLabel(feature.properties.name);
            }
        },
        filecontrol = L.Control.fileLayerLoad({
            fitBounds: true,
            layerOptions: {style: window.SETTINGS.map.styles.filelayer,
                           pointToLayer: pointToLayer,
                           onEachFeature: onEachFeature}
        });
    map.filecontrol = filecontrol;
    map.addControl(filecontrol);

    // Restore map view, layers and filter from any available context
    // Get context from URL parameter, if any
    var mapViewContext = getURLParameter('context'),
        layerLabel = $('

').append(nameHTML).text();
    MapEntity.Context.restoreFullContext(map,
        // From URL param
        mapViewContext,
        // Parameters
        {
            filter: '#mainfilter',
            datatable: dt,
            objectsname: layerLabel,
            // We can have several contexts in the application (mainly 'detail' and 'list')
            // Using prefixes is a way to manage this.
            prefix: 'list',
        }
    );
    $(window).unload(function () {
        MapEntity.Context.saveFullContext(map, {
            filter: '#mainfilter',
            datatable: dt,
            prefix: 'list',
        });
    });
});
<|endoftext|>


<commit_before>var showAlert;

var showGuessAlert;

function fnSaveUserAnswer(questionid, selectedoption)
{
	$.ajax({
		'type'		: 'POST',
		'url'		: strBaseURL+'tonaltest/saveuseranswer',
		'ajax' 		: true,
		'data' 		: { questionid : questionid, selectedoption : selectedoption },
		'success' 	: function(){},
		'failure' 	: function(){}
	});
}

function fnShowAlert()
{
	clearInterval(showAlert);

	clearTimeout(showGuessAlert);

	$('.alert-danger').fadeIn().delay(4000).fadeOut(400);

	showGuessAlert = setTimeout(function(){
		$('.alert-warning').fadeIn().delay(4000).fadeOut(400);
	}, 5000);
}

$('document').ready(function(){
   // More Info Audio
   setTimeout(function(){
		$(function () {
		 //Find the audio control on the page
		   var audioPlay = document.getElementById('TestAudioData');
		  // Attaches an event ended and it gets fired when current playing song get ended
		   audioPlay.addEventListener('ended', function() {

		   		clearInterval(showAlert);

				clearTimeout(showGuessAlert);

				$('.tonal-test-wrapper .tonal-test-view .option-view label').css('pointer-events','inherit');

				showAlert = setInterval(function(){
					fnShowAlert();
				},3000);
		   });

	   });
   },6000);

   $("input.custom-radio-button").bind('click', function()
	{

		if(!$("input.custom-radio-button:checked").val()) {
			fnShowAlert();
		}else
		{
			clearInterval(showAlert);

			clearTimeout(showGuessAlert);

			fnSaveUserAnswer($("input.custom-radio-button:checked").attr("data-role-id"), $("input.custom-radio-button:checked").attr("data-role-option"));

			setTimeout(function(){

				if((parseInt($("#hdnQuestionNo").val())+1) == arrQuestions.length)
				{
					//$('.NextButtonWrapper').show();
					setTimeout(function(){
						window.location.href = $("#aNextButtonWrapper").attr('href');
					},5000);
				}

				var intNextQuestion = parseInt($("#hdnQuestionNo").val())+1;

				if(arrQuestions.length > intNextQuestion)
				{
					$("#hdnQuestionNo").val(intNextQuestion);

					$("#TestAudioData").attr('src', strBaseURL+arrQuestions[intNextQuestion].audiopath);

					$("input.custom-radio-button").attr("checked",false);

					for(var intCtr = 1; intCtr<= arrQuestions[intNextQuestion].optionscount; intCtr++)
					{
						$("#id_"+intCtr).attr('data-role-id', arrQuestions[intNextQuestion].id);

						$strOldClass = $("#id_"+intCtr).attr('class');

						$("#id_"+intCtr).removeClass($strOldClass);

						$("#id_"+intCtr).addClass('radiobtn-custom-'+arrQuestions[intNextQuestion].optioncolor);

						$("#id_"+intCtr).addClass('custom-radio-button');

						$strLblClass = $("#lbl_"+intCtr).attr("class");

						$("#lbl_"+intCtr).removeClass($strLblClass);

						$("#lbl_"+intCtr).addClass('btn-'+arrQuestions[intNextQuestion].optioncolor);

					}

					$('.tonal-test-wrapper .tonal-test-view .option-view label').css('pointer-events','none');

					audioPlay1 = document.getElementById('TestAudioData');

					audioPlay1.play();

					$("#h1QuestionCode").html(arrQuestions[intNextQuestion].questioncode);
				}

			}, 3000);
		}
	});

});<commit_msg>disabled refresh for tonal test page<commit_after>var showAlert;

var showGuessAlert;

function fnSaveUserAnswer(questionid, selectedoption)
{
	$.ajax({
		'type'		: 'POST',
		'url'		: strBaseURL+'tonaltest/saveuseranswer',
		'ajax' 		: true,
		'data' 		: { questionid : questionid, selectedoption : selectedoption },
		'success' 	: function(){},
		'failure' 	: function(){}
	});
}

function fnShowAlert()
{
	clearInterval(showAlert);

	clearTimeout(showGuessAlert);

	$('.alert-danger').fadeIn().delay(4000).fadeOut(400);

	showGuessAlert = setTimeout(function(){
		$('.alert-warning').fadeIn().delay(4000).fadeOut(400);
	}, 5000);
}

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

function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };

$(document).on("keydown", disableF5);

   // More Info Audio
   setTimeout(function(){
		$(function () {
		 //Find the audio control on the page
		   var audioPlay = document.getElementById('TestAudioData');
		  // Attaches an event ended and it gets fired when current playing song get ended
		   audioPlay.addEventListener('ended', function() {

		   		clearInterval(showAlert);

				clearTimeout(showGuessAlert);

				$('.tonal-test-wrapper .tonal-test-view .option-view label').css('pointer-events','inherit');

				showAlert = setInterval(function(){
					fnShowAlert();
				},3000);
		   });

	   });
   },6000);

   $("input.custom-radio-button").bind('click', function()
	{

		if(!$("input.custom-radio-button:checked").val()) {
			fnShowAlert();
		}else
		{
			clearInterval(showAlert);

			clearTimeout(showGuessAlert);

			fnSaveUserAnswer($("input.custom-radio-button:checked").attr("data-role-id"), $("input.custom-radio-button:checked").attr("data-role-option"));

			setTimeout(function(){

				if((parseInt($("#hdnQuestionNo").val())+1) == arrQuestions.length)
				{
					//$('.NextButtonWrapper').show();
					setTimeout(function(){
						window.location.href = $("#aNextButtonWrapper").attr('href');
					},5000);
				}

				var intNextQuestion = parseInt($("#hdnQuestionNo").val())+1;

				if(arrQuestions.length > intNextQuestion)
				{
					$("#hdnQuestionNo").val(intNextQuestion);

					$("#TestAudioData").attr('src', strBaseURL+arrQuestions[intNextQuestion].audiopath);

					$("input.custom-radio-button").attr("checked",false);

					for(var intCtr = 1; intCtr<= arrQuestions[intNextQuestion].optionscount; intCtr++)
					{
						$("#id_"+intCtr).attr('data-role-id', arrQuestions[intNextQuestion].id);

						$strOldClass = $("#id_"+intCtr).attr('class');

						$("#id_"+intCtr).removeClass($strOldClass);

						$("#id_"+intCtr).addClass('radiobtn-custom-'+arrQuestions[intNextQuestion].optioncolor);

						$("#id_"+intCtr).addClass('custom-radio-button');

						$strLblClass = $("#lbl_"+intCtr).attr("class");

						$("#lbl_"+intCtr).removeClass($strLblClass);

						$("#lbl_"+intCtr).addClass('btn-'+arrQuestions[intNextQuestion].optioncolor);

					}

					$('.tonal-test-wrapper .tonal-test-view .option-view label').css('pointer-events','none');

					audioPlay1 = document.getElementById('TestAudioData');

					audioPlay1.play();

					$("#h1QuestionCode").html(arrQuestions[intNextQuestion].questioncode);
				}

			}, 3000);
		}
	});

});<|endoftext|>


<commit_before>export { ShuffleInfo };
export { ShuffleInfoPool };

import * as Pool from "../../../util/Pool.js";
import { ShuffleInfo as ChannelShuffler_ShuffleInfo } from "../ChannelShuffler_ShuffleInfo.js";

/**
 *
 */
class ShuffleInfo extends ChannelShuffler_ShuffleInfo {

  constructor( concatenatedShape, outputGroupCount ) {
    super( concatenatedShape, outputGroupCount );
  }

//!!! (2022/06/25 Remarked) Inherits from Recyclable.Base instead.
//   /**
//    * After calling this method, this object should be viewed as disposed and should not be operated again.
//    *
//    * Sub-class should override this method for recycling to its pool (and NEVER call super.disposeResources_and_recycleToPool()).
//    */
//   disposeResources_and_recycleToPool() {
//     this.disposeResources();
//     ShuffleInfoPool.Singleton.recycle( this );
//   }

  /**
   * Permute the input tensor by reshape-transpose-reshape.
   *
   * @param {tf.tensor} concatenatedTensor
   *   An single tensor (not array) to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor}
   *   A shuffled tensor. Its size is the same as concatenatedTensor but its last dimension is shuffled.
   */
  reshapeTransposeReshape_dispose_finally( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    try {
      let t2 = t1.transpose( this.transposePermutation );

      try {
        return t2.reshape( this.concatenatedShape );

      } finally {
        t2.dispose();
      }

    } finally {
      t1.dispose();
    }
  }

  reshapeTransposeReshape_dispose_direct( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    return t3;
  }

  reshapeTransposeReshape_tidy( concatenatedTensor ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshape", () => {
      return concatenatedTensor
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape );
    });
  }

  /**
   * Permute and split the input tensor by reshape-transpose-reshape-split.
   *
   * @param {tf.tensor} concatenatedTensor
   *   An single tensor (not array) to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor[]}
   *   An array of shuffled tensors. Their total channel count is the same as concatenatedTensor, but their
   * last dimensions are shuffled.
   */
  reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_finally( concatenatedTensor );

    try {
      return t.split( this.outputGroupCount, this.lastAxisId );

    } finally {
      t.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_direct( concatenatedTensor );

    try {
      return t.split( this.outputGroupCount, this.lastAxisId );

    } finally {
      t.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_finally( concatenatedTensor );

    let tArray = t.split( this.outputGroupCount, this.lastAxisId );
    t.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_direct( concatenatedTensor );

    let tArray = t.split( this.outputGroupCount, this.lastAxisId );
    t.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    try {
      let t2 = t1.transpose( this.transposePermutation );

      try {
        let t3 = t2.reshape( this.concatenatedShape );

        try {
          return t3.split( this.outputGroupCount, this.lastAxisId );

        } finally {
          t3.dispose();
        }

      } finally {
        t2.dispose();
      }

    } finally {
      t1.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    let tArray = t3.split( this.outputGroupCount, this.lastAxisId );
    t3.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_tidy( concatenatedTensor ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshapeSplit", () => {
      return concatenatedTensor
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape )
        .split( this.outputGroupCount, this.lastAxisId );
    });
  }

  /**
   * Concatenate and permute the input tensor by concat-reshape-transpose-reshape.
   *
   * @param {tf.tensor[]} tensorArray
   *   An array of tensors to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor}
   *   A shuffled tensor. Its total channel count is the same as concatenated tensorArray, but their
   * last dimensions are shuffled.
   */
  concatReshapeTransposeReshape_dispose_direct_call( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let t = this.reshapeTransposeReshape( concatenatedTensor );
    concatenatedTensor.dispose();

    return t;
  }

  /**
   * Concatenate, permute and split the input tensor by concat-reshape-transpose-reshape-split.
   *
   * @param {tf.tensor[]} tensorArray
   *   An array of tensors to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor[]}
   *   An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their
   * last dimensions are shuffled.
   */
  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_tidy( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_tidy( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_tidy( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_tidy( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      let t1 = concatenatedTensor.reshape( this.intermediateShape );

      try {
        let t2 = t1.transpose( this.transposePermutation );

        try {
          let t3 = t2.reshape( this.concatenatedShape );

          try {
            return t3.split( this.outputGroupCount, this.lastAxisId );

          } finally {
            t3.dispose();
          }

        } finally {
          t2.dispose();
        }

      } finally {
        t1.dispose();
      }

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let t1 = concatenatedTensor.reshape( this.intermediateShape );
    concatenatedTensor.dispose();

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    let tArray = t3.split( this.outputGroupCount, this.lastAxisId );
    t3.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_tidy( tensorArray ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.concatReshapeTransposeReshapeSplit", () => {
      return tf.concat( tensorArray, this.lastAxisId )
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape )
        .split( this.outputGroupCount, this.lastAxisId );
    });
  }

}

/**
 * Providing ChannelShuffler.PerformanceTest.ShuffleInfo
 *
 */
class ShuffleInfoPool extends Pool.Root {

  constructor() {
    super( "ChannelShuffler.PerformanceTest.ShuffleInfoPool", ShuffleInfo, ShuffleInfo.setAsConstructor );
  }

}

/**
 * Used as default ChannelShuffler.PerformanceTest.ShuffleInfo provider for conforming to Recyclable interface.
 */
ShuffleInfo.Pool = new ShuffleInfoPool();

<commit_msg>Update ChannelShuffler_PerformanceTest_ShuffleInfo.js<commit_after>export { ShuffleInfo };

import * as Pool from "../../../util/Pool.js";
import { ShuffleInfo as ChannelShuffler_ShuffleInfo } from "../ChannelShuffler_ShuffleInfo.js";

/**
 *
 */
class ShuffleInfo extends ChannelShuffler_ShuffleInfo {

  /**
   * Used as default ChannelShuffler.PerformanceTest.ShuffleInfo provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "ChannelShuffler.PerformanceTest.ShuffleInfoPool", ShuffleInfo, ShuffleInfo.setAsConstructor );

  constructor( concatenatedShape, outputGroupCount ) {
    super( concatenatedShape, outputGroupCount );
    ShuffleInfo.setAsConstructor_self.call( this, concatenatedShape, outputGroupCount );
  }

  /** @override */
  static setAsConstructor_self( concatenatedShape, outputGroupCount ) {
  }

  /** @override */
  static setAsConstructor( concatenatedShape, outputGroupCount ) {
    super.setAsConstructor( concatenatedShape, outputGroupCount );
    ShuffleInfo.setAsConstructor_self.call( this, concatenatedShape, outputGroupCount );
    return this;
  }

  /** @override */
  disposeResources() {
   super.disposeResources();
  }

  /**
   * Permute the input tensor by reshape-transpose-reshape.
   *
   * @param {tf.tensor} concatenatedTensor
   *   An single tensor (not array) to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor}
   *   A shuffled tensor. Its size is the same as concatenatedTensor but its last dimension is shuffled.
   */
  reshapeTransposeReshape_dispose_finally( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    try {
      let t2 = t1.transpose( this.transposePermutation );

      try {
        return t2.reshape( this.concatenatedShape );

      } finally {
        t2.dispose();
      }

    } finally {
      t1.dispose();
    }
  }

  reshapeTransposeReshape_dispose_direct( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    return t3;
  }

  reshapeTransposeReshape_tidy( concatenatedTensor ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshape", () => {
      return concatenatedTensor
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape );
    });
  }

  /**
   * Permute and split the input tensor by reshape-transpose-reshape-split.
   *
   * @param {tf.tensor} concatenatedTensor
   *   An single tensor (not array) to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor[]}
   *   An array of shuffled tensors. Their total channel count is the same as concatenatedTensor, but their
   * last dimensions are shuffled.
   */
  reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_finally( concatenatedTensor );

    try {
      return t.split( this.outputGroupCount, this.lastAxisId );

    } finally {
      t.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_direct( concatenatedTensor );

    try {
      return t.split( this.outputGroupCount, this.lastAxisId );

    } finally {
      t.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_finally( concatenatedTensor );

    let tArray = t.split( this.outputGroupCount, this.lastAxisId );
    t.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor ) {
    let t = this.reshapeTransposeReshape_dispose_direct( concatenatedTensor );

    let tArray = t.split( this.outputGroupCount, this.lastAxisId );
    t.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    try {
      let t2 = t1.transpose( this.transposePermutation );

      try {
        let t3 = t2.reshape( this.concatenatedShape );

        try {
          return t3.split( this.outputGroupCount, this.lastAxisId );

        } finally {
          t3.dispose();
        }

      } finally {
        t2.dispose();
      }

    } finally {
      t1.dispose();
    }
  }

  reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor ) {
    let t1 = concatenatedTensor.reshape( this.intermediateShape );

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    let tArray = t3.split( this.outputGroupCount, this.lastAxisId );
    t3.dispose();

    return tArray;
  }

  reshapeTransposeReshapeSplit_tidy( concatenatedTensor ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshapeSplit", () => {
      return concatenatedTensor
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape )
        .split( this.outputGroupCount, this.lastAxisId );
    });
  }

  /**
   * Concatenate and permute the input tensor by concat-reshape-transpose-reshape.
   *
   * @param {tf.tensor[]} tensorArray
   *   An array of tensors to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor}
   *   A shuffled tensor. Its total channel count is the same as concatenated tensorArray, but their
   * last dimensions are shuffled.
   */
  concatReshapeTransposeReshape_dispose_direct_call( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let t = this.reshapeTransposeReshape( concatenatedTensor );
    concatenatedTensor.dispose();

    return t;
  }

  /**
   * Concatenate, permute and split the input tensor by concat-reshape-transpose-reshape-split.
   *
   * @param {tf.tensor[]} tensorArray
   *   An array of tensors to be processed. It should conform to this.concatenatedShape.
   *
   * @return {tf.tensor[]}
   *   An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their
   * last dimensions are shuffled.
   */
  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_finally( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_dispose_direct( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally_call_tidy( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      return this.reshapeTransposeReshapeSplit_tidy( concatenatedTensor );

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct_call_tidy( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let tArray = this.reshapeTransposeReshapeSplit_tidy( concatenatedTensor );
    concatenatedTensor.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_dispose_finally( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    try {
      let t1 = concatenatedTensor.reshape( this.intermediateShape );

      try {
        let t2 = t1.transpose( this.transposePermutation );

        try {
          let t3 = t2.reshape( this.concatenatedShape );

          try {
            return t3.split( this.outputGroupCount, this.lastAxisId );

          } finally {
            t3.dispose();
          }

        } finally {
          t2.dispose();
        }

      } finally {
        t1.dispose();
      }

    } finally {
      concatenatedTensor.dispose();
    }
  }

  concatReshapeTransposeReshapeSplit_dispose_direct( tensorArray ) {
    let concatenatedTensor = tf.concat( tensorArray, this.lastAxisId );

    let t1 = concatenatedTensor.reshape( this.intermediateShape );
    concatenatedTensor.dispose();

    let t2 = t1.transpose( this.transposePermutation );
    t1.dispose();

    let t3 = t2.reshape( this.concatenatedShape );
    t2.dispose();

    let tArray = t3.split( this.outputGroupCount, this.lastAxisId );
    t3.dispose();

    return tArray;
  }

  concatReshapeTransposeReshapeSplit_tidy( tensorArray ) {
    return tf.tidy( "ChannelShuffler.ShuffleInfo.concatReshapeTransposeReshapeSplit", () => {
      return tf.concat( tensorArray, this.lastAxisId )
        .reshape( this.intermediateShape )
        .transpose( this.transposePermutation )
        .reshape( this.concatenatedShape )
        .split( this.outputGroupCount, this.lastAxisId );
    });
  }

}

<|endoftext|>