<commit_before>!function ($) {

	$.fn.TouchUI.DOM = {

		pluginLoaded: function() {
			if( document.location.hash === "#touch" || document.location.href.indexOf("?touch") !== -1 || this.DOM.cookies.get("active") === "true") {
				$("html").attr("id", this.id);

				// Force mobile browser to set the window size to their format
				$('<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, user-scalable=no, minimal-ui">').appendTo("head");
				$('<meta name="apple-mobile-web-app-capable" content="yes">').appendTo("head");
				$('<meta name="mobile-web-app-capable" content="yes">').appendTo("head");
				$('').prependTo("#terminal-output");

				this.isActive = true;

				// Enforce active cookie
				this.DOM.cookies.set("active", "true");

				// Create keyboard cookie if not existing
				if(this.DOM.cookies.get("keyboardActive") === undefined) {
					if(!this.isTouch) {
						this.DOM.cookies.set("keyboardActive", "true");
					} else {
						this.DOM.cookies.set("keyboardActive", "false");
					}
				}

				// Create hide navbar on click if not existing
				if(this.DOM.cookies.get("hideNavbarActive") === undefined) {
					this.DOM.cookies.set("hideNavbarActive", "false");
				}

				// Create fullscreen cookie if not existing and trigger pNotification
				if(this.DOM.cookies.get("fullscreen") === undefined) {
					this.DOM.cookies.set("fullscreen", "false");
					this.fullscreen.ask.call(this);
				} else {
					//Cookie say user wants fullscreen, ask it!
					if(this.DOM.cookies.get("fullscreen") === "true") {
						this.fullscreen.ask.call(this);
					}
				}

				// Get state of cookies
				this.keyboard.isActive = (this.DOM.cookies.get("keyboardActive") === "true");
				this.animate.isHidebarActive = (this.DOM.cookies.get("hideNavbarActive") === "true");
				this.isFullscreen = (this.DOM.cookies.get("fullscreen") === "true");

				// Set new printer tab as active
				$(".octoprint-container .tab-content .active").removeClass('active');

				this.DOM.create.printer.init( this.DOM.create.tabbar );
				this.DOM.create.printer.menu.$elm.find('a').trigger("click");
			}
		},

		init: function() {

			this.DOM.move.connection.init( this.DOM.create.tabbar );
			this.DOM.move.settings.init( this.DOM.create.tabbar );
			this.DOM.move.gcode.init( this.DOM.create.tabbar );
			this.DOM.move.controls.init();

			if ($("#webcam_container").length > 0) {
				this.DOM.create.webcam.init( this.DOM.create.tabbar );
			}

			// Remove unwanted spaces
			$("#navbar_settings2 a").html($("#navbar_settings2 a").text().trim());

			//Add hr before the settings icon
			$('

').insertBefore("#navbar_settings2");

			// Move all other items from tabbar into dropdown
			this.DOM.move.tabs.init();

			// Add class with how many tab-items
			$("#tabs, #navbar").addClass("items-" + $("#tabs li:not(.hidden_touch)").length);
		},

		create: {

			// Tabbar helper
			tabbar: {

				createItem: function(itemId, linkId, toggle, text) {
					text = (text) ? text : "";
					return $('
'+text+'
');
				}

			},

			// Create a print status and files link and tab
			printer: {

				menu: {
					cloneTo: "#tabs"
				},

				container: {
					cloneTo: "#temp"
				},

				move: {
					$state: $("#state_wrapper"),
					$files: $("#files_wrapper")
				},

				init: function( tabbar ) {
					this.menu.$elm = tabbar.createItem("print_link", "printer", "tab").prependTo(this.menu.cloneTo);
					this.container.$elm = $('

').insertBefore(this.container.cloneTo);

					// Move the contents of the hidden accordions to the new print status and files tab
					this.move.$state.appendTo(this.container.$elm.find(".row-fluid"));
					this.move.$files.insertAfter(this.container.$elm.find(".row-fluid #state_wrapper"));
				}
			},

			// Create a tab with webcam feed, and move timelapse into settings dropdown
			webcam: {

				menu: {
					webcam: {
						cloneTo: "#term_link"
					},
					timelapse: {
						$cloneContainer: $("#timelapse_link"),
						cloneId: "timelapse_link2",
						cloneTo: "#conn_link2"
					}
				},

				container: {
					cloneTo: "#timelapse",

					webcam: {
						$container: $("#webcam_container"),
						cloneTo: "#webcam"
					}
				},

				init: function( tabbar ) {
					var self = this;

					this.menu.timelapse.$elm = this.menu.timelapse.$cloneContainer
						.clone()
						.attr("id", this.menu.timelapse.cloneId)
						.insertAfter(this.menu.timelapse.cloneTo)
						.click(function(e) {
							e.preventDefault();
							e.stopPropagation();

							self.menu.timelapse.$cloneContainer.find("a").click();
						});

					this.container.$elm = $('

').insertAfter(this.container.cloneTo);
					this.menu.webcam.$elm = tabbar.createItem("webcam_link", "webcam", "tab").insertBefore(this.menu.webcam.cloneTo);

					this.container.webcam.$container.next().appendTo(this.container.webcam.cloneTo);
					this.container.webcam.$container.prependTo(this.container.webcam.cloneTo);

					// Hide orginal link
					this.menu.timelapse.$cloneContainer.addClass("hidden_touch");

				}
			}
		},

		move: {

			// Move all items, exepct this mainTabItems into the dropdown
			tabs: {
				mainTabItems: ['#print_link', '#temp_link', '#control_link', '#webcam_link', '#term_link', '.hidden_touch'],
				init: function() {
					$items = $("#tabs li:not("+this.mainTabItems+")");
					$items.each(function(ind, elm) {
						var $elm = $(elm);

						// Clone the items into the dropdown, and make it click the orginal link
						$elm.clone().attr("id", $elm.attr("id")+"2").appendTo("#login_dropdown_loggedin").click(function(e) {
							$elm.click();
							e.preventDefault();
							return false;
						});
						$elm.addClass("hidden_touch");
					});

					var dropdownMenu = $("#navbar_systemmenu").find(".dropdown-menu");
					$("#navbar_systemmenu").appendTo("#login_dropdown_loggedin").find("a").on("mousedown touchstart", function(e) {
						$(e.target).toggleClass("active");
						dropdownMenu.toggleClass("dropdown-menu").toggleClass("dropdown").toggleClass("open");

						e.stopPropagation();
						e.preventDefault();
						return false;
					}).click(function(e) {
						e.preventDefault();
						return false;
					}).text($("#navbar_systemmenu").find('a').text().trim());

					var navBarTmp = $("#navbar_plugin_navbartemp").appendTo("#login_dropdown_loggedin");
					$("").insertBefore(navBarTmp);
					$("").insertAfter(navBarTmp);
				}
			},

			//Move the connection accordion tab to a modal and add it to the settings dropdown
			connection: {
				$container: null,
				containerId: "connection_dialog",
				$cloneContainer: $("#usersettings_dialog"),
				$cloneModal: $("#connection_wrapper"),
				cloneTo: "#login_dropdown_loggedin",

				init: function( tabbar ) {
					var text = this.$cloneModal.find(".accordion-heading").text().trim();

					// Clone usersettings modal
					this.$container = this.$cloneContainer.clone().attr("id", this.containerId).insertAfter(this.$cloneContainer);
					this.$containerBody = this.$container.find(".modal-body");

					// Remove all html from clone
					this.$containerBody.html("");

					// Append tab contents to modal
					this.$cloneModal.appendTo(this.$containerBody);

					// Set modal header to accordion header
					this.$container.find(".modal-header h3").text(text);

					// Create a link in the dropdown
					this.$menuItem = tabbar.createItem("conn_link2", this.containerId, "modal", text).prependTo(this.cloneTo);
				}
			},

			// Move the G-CODE viewer, hide the orginal and place it in the dropdown
			gcode: {
				$item: $("#gcode_link"),
				cloneId: "gcode_link2",
				cloneTo: "#conn_link2",

				init: function() {
					var self = this;

					this.$item.clone().attr("id", this.cloneId).insertAfter(this.cloneTo).click(function(e) {
						e.preventDefault();
						e.stopPropagation();

						self.$item.find("a").click();
					});

					this.$item.addClass("hidden_touch");
				}
			},

			// Move the settings option into the dropdown for more screen
			settings: {
				$item: $("#navbar_settings"),
				cloneId: "navbar_settings2",
				cloneTo: "#conn_link2",
				findLinkWithin: "#navbar_show_settings",

				init: function( tabbar ) {
					var self = this;

					// Clone the navbar settings item
					this.$cloneItem = this.$item.clone().attr("id", this.cloneId).insertAfter(this.cloneTo);

					// Remove binding and clicks from clone
					this.$cloneItem.find(this.findLinkWithin).attr("data-bind", "").attr("id", "").click(function(e) {
						e.preventDefault();

						// Pass on the click to the orginal element
						self.$item.find(self.findLinkWithin).click();
					});
				}
			},

			// Move feed rate into new div and move flow rate
			controls: {

				init: function() {

					var jogPanels = $('#control > .jog-panel');

					$(jogPanels[0]).attr("id", "x-y-panel");
					$(jogPanels[1]).attr("id", "e-panel");
					$(jogPanels[2]).attr("id", "extra-panel");

					var tmp = $('

').insertAfter($(jogPanels[2]));

					$(jogPanels[0]).children('button:last-child').appendTo(tmp);
					$(jogPanels[0]).children('[type="number"]:last-child').appendTo(tmp);
					$(jogPanels[0]).children('.slider:last-child').appendTo(tmp);

					$(jogPanels[1]).find('div > button:last-child').appendTo(tmp);
					$(jogPanels[1]).find('div > [type="number"]:last-child').appendTo(tmp);
					$(jogPanels[1]).find('div > .slider:last-child').appendTo(tmp);

				}

			}

		},

		cookies: {

			get: function(key) {
				var name = "TouchUI." + key + "=";
				var ca = document.cookie.split(';');
				for(var i=0; i<ca.length; i++) {
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1);
					if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
				}
				return undefined;
			},

			set: function(key, value) {
				var d = new Date();
				d.setTime(d.getTime()+(360*24*60*60*1000));
				var expires = "expires="+d.toUTCString();
				document.cookie = "TouchUI." + key + "=" + value + "; " + expires;
			},

			toggleBoolean: function(key) {
				var value = $.parseJSON(this.get(key) || "false");

				if(value === true) {
					this.set(key, "false");
				} else {
					this.set(key, "true");
				}

				return !value;

			}

		}

	};

}(window.jQuery);
<commit_msg>Update minor bugs<commit_after>!function ($) {

	$.fn.TouchUI.DOM = {

		pluginLoaded: function() {
			if(
				document.location.hash === "#touch" ||
				document.location.href.indexOf("?touch") > 0 ||
				this.DOM.cookies.get("active") === "true"
			) {
				$("html").attr("id", this.id);

				// Force mobile browser to set the window size to their format
				$('<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, user-scalable=no, minimal-ui">').appendTo("head");
				$('<meta name="apple-mobile-web-app-capable" content="yes">').appendTo("head");
				$('<meta name="mobile-web-app-capable" content="yes">').appendTo("head");
				$('').prependTo("#terminal-output");

				this.isActive = true;

				// Enforce active cookie
				this.DOM.cookies.set("active", "true");

				// Create keyboard cookie if not existing
				if(this.DOM.cookies.get("keyboardActive") === undefined) {
					if(!this.isTouch) {
						this.DOM.cookies.set("keyboardActive", "true");
					} else {
						this.DOM.cookies.set("keyboardActive", "false");
					}
				}

				// Create hide navbar on click if not existing
				if(this.DOM.cookies.get("hideNavbarActive") === undefined) {
					this.DOM.cookies.set("hideNavbarActive", "false");
				}

				// Create fullscreen cookie if not existing and trigger pNotification
				if(this.DOM.cookies.get("fullscreen") === undefined) {
					this.DOM.cookies.set("fullscreen", "false");
					this.fullscreen.ask.call(this);
				} else {
					//Cookie say user wants fullscreen, ask it!
					if(this.DOM.cookies.get("fullscreen") === "true") {
						this.fullscreen.ask.call(this);
					}
				}

				// Get state of cookies
				this.keyboard.isActive = (this.DOM.cookies.get("keyboardActive") === "true");
				this.animate.isHidebarActive = (this.DOM.cookies.get("hideNavbarActive") === "true");
				this.isFullscreen = (this.DOM.cookies.get("fullscreen") === "true");

				// Set new printer tab as active
				$(".octoprint-container .tab-content .active").removeClass('active');

				this.DOM.create.printer.init( this.DOM.create.tabbar );
				this.DOM.create.printer.menu.$elm.find('a').trigger("click");
			}
		},

		init: function() {

			this.DOM.move.connection.init( this.DOM.create.tabbar );
			this.DOM.move.settings.init( this.DOM.create.tabbar );
			this.DOM.move.gcode.init( this.DOM.create.tabbar );
			this.DOM.move.controls.init();

			if ($("#webcam_container").length > 0) {
				this.DOM.create.webcam.init( this.DOM.create.tabbar );
			}

			// Remove unwanted spaces
			$("#navbar_settings2 a").html($("#navbar_settings2 a").text().trim());

			//Add hr before the settings icon
			$('

').insertBefore("#navbar_settings2");

			// Move all other items from tabbar into dropdown
			this.DOM.move.tabs.init();

			// Add class with how many tab-items
			$("#tabs, #navbar").addClass("items-" + $("#tabs li:not(.hidden_touch)").length);
		},

		create: {

			// Tabbar helper
			tabbar: {

				createItem: function(itemId, linkId, toggle, text) {
					text = (text) ? text : "";
					return $('
'+text+'
');
				}

			},

			// Create a print status and files link and tab
			printer: {

				menu: {
					cloneTo: "#tabs"
				},

				container: {
					cloneTo: "#temp"
				},

				move: {
					$state: $("#state_wrapper"),
					$files: $("#files_wrapper")
				},

				init: function( tabbar ) {
					this.menu.$elm = tabbar.createItem("print_link", "printer", "tab").prependTo(this.menu.cloneTo);
					this.container.$elm = $('

').insertBefore(this.container.cloneTo);

					// Move the contents of the hidden accordions to the new print status and files tab
					this.move.$state.appendTo(this.container.$elm.find(".row-fluid"));
					this.move.$files.insertAfter(this.container.$elm.find(".row-fluid #state_wrapper"));
				}
			},

			// Create a tab with webcam feed, and move timelapse into settings dropdown
			webcam: {

				menu: {
					webcam: {
						cloneTo: "#term_link"
					},
					timelapse: {
						$cloneContainer: $("#timelapse_link"),
						cloneId: "timelapse_link2",
						cloneTo: "#conn_link2"
					}
				},

				container: {
					cloneTo: "#timelapse",

					webcam: {
						$container: $("#webcam_container"),
						cloneTo: "#webcam"
					}
				},

				init: function( tabbar ) {
					var self = this;

					this.menu.timelapse.$elm = this.menu.timelapse.$cloneContainer
						.clone()
						.attr("id", this.menu.timelapse.cloneId)
						.insertAfter(this.menu.timelapse.cloneTo)
						.click(function(e) {
							e.preventDefault();
							e.stopPropagation();

							self.menu.timelapse.$cloneContainer.find("a").click();
						});

					this.container.$elm = $('

').insertAfter(this.container.cloneTo);
					this.menu.webcam.$elm = tabbar.createItem("webcam_link", "webcam", "tab").insertBefore(this.menu.webcam.cloneTo);

					this.container.webcam.$container.next().appendTo(this.container.webcam.cloneTo);
					this.container.webcam.$container.prependTo(this.container.webcam.cloneTo);

					// Hide orginal link
					this.menu.timelapse.$cloneContainer.addClass("hidden_touch");

				}
			}
		},

		move: {

			// Move all items, exepct this mainTabItems into the dropdown
			tabs: {
				mainTabItems: ['#print_link', '#temp_link', '#control_link', '#webcam_link', '#term_link', '.hidden_touch'],
				init: function() {
					$items = $("#tabs li:not("+this.mainTabItems+")");
					$items.each(function(ind, elm) {
						var $elm = $(elm);

						// Clone the items into the dropdown, and make it click the orginal link
						$elm.clone().attr("id", $elm.attr("id")+"2").appendTo("#login_dropdown_loggedin").click(function(e) {
							$elm.click();
							e.preventDefault();
							return false;
						});
						$elm.addClass("hidden_touch");
					});

					var dropdownMenu = $("#navbar_systemmenu").find(".dropdown-menu");
					$("#navbar_systemmenu").appendTo("#login_dropdown_loggedin").find("a").on("mousedown touchstart", function(e) {
						$(e.target).toggleClass("active");
						dropdownMenu.toggleClass("dropdown-menu").toggleClass("dropdown").toggleClass("open");

						e.stopPropagation();
						e.preventDefault();
						return false;
					}).click(function(e) {
						e.preventDefault();
						return false;
					}).text($("#navbar_systemmenu").find('a').text().trim());

					if( $("#navbar_plugin_navbartemp").length > 0 ) {
						var navBarTmp = $("#navbar_plugin_navbartemp").appendTo("#login_dropdown_loggedin");
						$("").insertBefore(navBarTmp);
						$("").insertAfter(navBarTmp);
					}
				}
			},

			//Move the connection accordion tab to a modal and add it to the settings dropdown
			connection: {
				$container: null,
				containerId: "connection_dialog",
				$cloneContainer: $("#usersettings_dialog"),
				$cloneModal: $("#connection_wrapper"),
				cloneTo: "#login_dropdown_loggedin",

				init: function( tabbar ) {
					var text = this.$cloneModal.find(".accordion-heading").text().trim();

					// Clone usersettings modal
					this.$container = this.$cloneContainer.clone().attr("id", this.containerId).insertAfter(this.$cloneContainer);
					this.$containerBody = this.$container.find(".modal-body");

					// Remove all html from clone
					this.$containerBody.html("");

					// Append tab contents to modal
					this.$cloneModal.appendTo(this.$containerBody);

					// Set modal header to accordion header
					this.$container.find(".modal-header h3").text(text);

					// Create a link in the dropdown
					this.$menuItem = tabbar.createItem("conn_link2", this.containerId, "modal", text).prependTo(this.cloneTo);
				}
			},

			// Move the G-CODE viewer, hide the orginal and place it in the dropdown
			gcode: {
				$item: $("#gcode_link"),
				cloneId: "gcode_link2",
				cloneTo: "#conn_link2",

				init: function() {
					var self = this;

					this.$item.clone().attr("id", this.cloneId).insertAfter(this.cloneTo).click(function(e) {
						e.preventDefault();
						e.stopPropagation();

						self.$item.find("a").click();
					});

					this.$item.addClass("hidden_touch");
				}
			},

			// Move the settings option into the dropdown for more screen
			settings: {
				$item: $("#navbar_settings"),
				cloneId: "navbar_settings2",
				cloneTo: "#conn_link2",
				findLinkWithin: "#navbar_show_settings",

				init: function( tabbar ) {
					var self = this;

					// Clone the navbar settings item
					this.$cloneItem = this.$item.clone().attr("id", this.cloneId).insertAfter(this.cloneTo);

					// Remove binding and clicks from clone
					this.$cloneItem.find(this.findLinkWithin).attr("data-bind", "").attr("id", "").click(function(e) {
						e.preventDefault();

						// Pass on the click to the orginal element
						self.$item.find(self.findLinkWithin).click();
					});
				}
			},

			// Move feed rate into new div and move flow rate
			controls: {

				init: function() {

					var jogPanels = $('#control > .jog-panel');

					$(jogPanels[0]).attr("id", "x-y-panel");
					$(jogPanels[1]).attr("id", "e-panel");
					$(jogPanels[2]).attr("id", "extra-panel");

					var tmp = $('

').insertAfter($(jogPanels[2]));

					$(jogPanels[0]).children('button:last-child').appendTo(tmp);
					$(jogPanels[0]).children('[type="number"]:last-child').appendTo(tmp);
					$(jogPanels[0]).children('.slider:last-child').appendTo(tmp);

					$(jogPanels[1]).find('div > button:last-child').appendTo(tmp);
					$(jogPanels[1]).find('div > [type="number"]:last-child').appendTo(tmp);
					$(jogPanels[1]).find('div > .slider:last-child').appendTo(tmp);

				}

			}

		},

		cookies: {

			get: function(key) {
				var name = "TouchUI." + key + "=";
				var ca = document.cookie.split(';');
				for(var i=0; i<ca.length; i++) {
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1);
					if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
				}
				return undefined;
			},

			set: function(key, value) {
				var d = new Date();
				d.setTime(d.getTime()+(360*24*60*60*1000));
				var expires = "expires="+d.toUTCString();
				document.cookie = "TouchUI." + key + "=" + value + "; " + expires;
			},

			toggleBoolean: function(key) {
				var value = $.parseJSON(this.get(key) || "false");

				if(value === true) {
					this.set(key, "false");
				} else {
					this.set(key, "true");
				}

				return !value;

			}

		}

	};

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


<commit_before>import {assign, joinParams} from './helpers';

export const HTTP_METHOD_GET = 'GET';
export const HTTP_METHOD_PUT = 'PUT';
export const HTTP_METHOD_POST = 'POST';
export const HTTP_METHOD_DELETE = 'DELETE';
export const ALLOWED_METHODS = [
    HTTP_METHOD_GET,
    HTTP_METHOD_PUT,
    HTTP_METHOD_POST,
    HTTP_METHOD_DELETE
];

export const CONTENT_TYPE_JSON = 'application/json';
export const MIN_SUCCESSFUL_HTTP_CODE = 200;
export const MAX_SUCCESSFUL_HTTP_CODE = 299;

export const ERROR_XHR_NOT_FOUND = 'Constructor XMLHttpRequest not found';
export const ERROR_PROMISE_NOT_FOUND = 'Constructor Promise not found';
export const ERROR_UNKNOWN_HTTP_METHOD = 'Unknown HTTP method';
export const ERROR_UNACCEPTABLE_HTTP_CODE = 'Unacceptable HTTP code';
export const ERROR_INVALID_DATA = 'Invalid data for sending';
export const ERROR_JSON_PARSE = 'Invalid JSON';

export const ERROR_CONNECTION_TIMEOUT = 'Connection timeout';
export const ERROR_RESOURCE_ABORTED = 'Resource has been aborted';
export const ERROR_RESOURCE_FAILED = 'Resource failed to load';

/**
 * @todo: cors
 * @class HTTP-transport based on XHR
 * @property {String} path Common path
 * @property {Number} timeout Timeout (in milliseconds)
 * @property {Object} headers Common headers
 * @property {Array} opened List of opened requests
 * @property {XMLHttpRequest} XMLHttpRequest XHR interface
 * @property {Boolean} cors ```true``` if supported Cross-Origin Resource Sharing
 * @see https://xhr.spec.whatwg.org/
 * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
 * @see http://www.html5rocks.com/en/tutorials/cors/
 */
class FetchPlease {
    /**
     * @param {String} path Common path for all requests
     * @param {Object} [settings] Object with settings
     * @param {Number} [settings.timeout = 0]
     * @param {Object} [settings.XMLHttpRequest = global.XMLHttpRequest]
     * @param {Object|Function} [settings.headers = {}]
     */
    constructor(path = '', settings = {}) {
        this.path = path;
        this.opened = [];

        assign(this, {
            timeout: 0,
            headers: {},
            XMLHttpRequest: global.XMLHttpRequest
        }, settings);

        let {XMLHttpRequest} = this;
        if (XMLHttpRequest) {
            this.cors = 'withCredentials' in (new XMLHttpRequest());
        }
    }

    /**
     * Creates XHR instance and Promise instance
     * @param {String} method HTTP method
     * @param {String} path
     * @param {Object} data
     * @param {Object} settings
     * @return {Object}
     */
    request(method, path, data = null, settings = null) {
        if (!this.XMLHttpRequest) {
            throw new Error(ERROR_XHR_NOT_FOUND);
        }

        if (!global.Promise) {
            throw new Error(ERROR_PROMISE_NOT_FOUND);
        }

        if (ALLOWED_METHODS.indexOf(method) === -1) {
            throw new Error(ERROR_UNKNOWN_HTTP_METHOD);
        }

        let xhr = new this.XMLHttpRequest(),
            promise = new Promise(function (resolve, reject) {
                xhr.addEventListener('error', () => reject(ERROR_RESOURCE_FAILED));
                xhr.addEventListener('abort', () => reject(ERROR_RESOURCE_ABORTED));
                xhr.addEventListener('timeout', () => reject(ERROR_CONNECTION_TIMEOUT));
                xhr.addEventListener('load', () => {
                    if (xhr.status) {
                        resolve(xhr);
                    }
                });
            });

        settings = settings || {};

        let handleJson = settings.handleJson || this.handleJson,
            handleError = settings.handleError || this.handleError,
            handleResponse = settings.handleResponse || this.handleResponse;

        promise = promise
            // Remove request from list of opened requests
            .then(
                () => this.close(xhr),
                (reason) => {
                    this.close(xhr);
                    throw new Error(reason);
                }
            )
            // Handle response
            .then(handleResponse)
            // Handle JSON in response
            .then(handleJson)
            // Handle errors
            .catch(handleError);

        // Add optinal `onProgress` handler
        if (settings.onProgress) {
            xhr.addEventListener('progress', settings.onProgress);
        }

        // Form URL without normalizing and open request
        let url = this.path + path;
        xhr.open(method, url);

        // Set headers
        // Order of method's calls is important
        // You must call setRequestHeader() after open(), but before send()
        // @see: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#setRequestHeader()
        let headers = assign(
            {},
            typeof this.headers === 'function' ? this.headers() : this.headers,
            settings.headers
        );
        this.setHeaders(xhr, headers);

        // Set timeout (before send() too)
        // @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Example_using_a_timeout
        let timeout = this.timeout || settings.timeout || 0;
        xhr.timeout = timeout;

        // Serialize data and send request
        data = this.serialize(data);
        xhr.send(data);

        // Add request into list of opened requests
        this.add(xhr);

        return {xhr, promise};
    }

    /**
     * Serializes data for request
     * @param {*} data
     * @return {String|FormData|Blob}
     */
    serialize(data) {
        // Do nothing with FormData instance
        if (global.FormData && data instanceof FormData) {
            return data;
        }

        // Do nothing with Blob instance
        if (global.Blob && data instanceof Blob) {
            return data;
        }

        // Do nothing with string or null
        if (data === null || typeof data === 'string') {
            return data;
        }

        try {
            // Serialize other data as JSON
            return JSON.stringify(data);
        } catch (e) {
            throw new Error(ERROR_INVALID_DATA);
        }
    }

    /**
     * Iterates given headers and set them for XHR object
     * @param {XMLHttpRequest} xhr
     * @param {Object} headers
     * @return {XMLHttpRequest}
     */
    setHeaders(xhr, headers = {}) {
        return Object.keys(headers).reduce((xhr, header) => {
            let value = headers[header];

            if (value !== false && value !== null && value !== undefined) {
                xhr.setRequestHeader(header, value);
            }

            return xhr;
        }, xhr);
    }

    /**
     * Aborts all opened requests
     */
    abort() {
        this.opened.forEach((xhr) => xhr.abort());
    }

    /**
     * Adds request to list of opened requests
     * @param {XMLHttpRequest} xhr
     */
    add(xhr) {
        this.opened.push(xhr);
    }

    /**
     * Deletes request from list of opened requests
     * @param {XMLHttpRequest} xhr
     * @return {XMLHtpRequest}
     */
    close(xhr) {
        let idx = this.opened.indexOf(xhr);
        if (idx !== -1) {
            this.opened.splice(idx, 1);
        }
        return xhr;
    }

    /**
     * Sends GET request
     * @param {String} url
     * @param {Object} [params]
     * @param {Object} [settings]
     * @return {Promise}
     */
    get(url, params, settings) {
        let {promise} = this.getRequest(url, params, settings);
        return promise;
    }

    /**
     * Sends PUT request
     * @param {String} url
     * @param {Object} data
     * @param {Object} [settings]
     * @return {Promise}
     */
    put(url, data, settings) {
        let {promise} = this.putRequest(url, data, settings);
        return promise;
    }

    /**
     * Sends POST request
     * @param {String} url
     * @param {Object} data
     * @param {Object} [settings]
     * @return {Promise}
     */
    post(url, data, settings) {
        let {promise} = this.postRequest(url, data, settings);
        return promise;
    }

    /**
     * Sends DELETE request
     * @param {String} url
     * @param {Object} [params]
     * @param {Object} [settings]
     * @return {Promise}
     */
    delete(url, params, settings) {
        let {promise} = this.deleteRequest(url, params, settings);
        return promise;
    }

    /**
     * Sends same GET request but returns object with instances of XHR and Promise
     * @param {String} url
     * @param {Object} [params]
     * @param {Object} [settings]
     * @return {Object}
     */
    getRequest(url, params = null, settings = null) {
        url = joinParams(url, params);
        return this.request(HTTP_METHOD_GET, url, null, settings);
    }

    /**
     * Sends same PUT request but returns object with instances of XHR and Promise
     * @param {String} url
     * @param {Object} data
     * @param {Object} [settings]
     * @return {Object}
     */
    putRequest(url, data, settings = null) {
        return this.request(HTTP_METHOD_PUT, url, data, settings);
    }

    /**
     * Sends same POST request but returns object with instances of XHR and Promise
     * @param {String} url
     * @param {Object} data
     * @param {Object} [settings]
     * @return {Object}
     */
    postRequest(url, data, settings = null) {
        return this.request(HTTP_METHOD_POST, url, data, settings);
    }

    /**
     * Sends same DELETE request but returns object with instances of XHR and Promise
     * @param {String} url
     * @param {Object} [params]
     * @param {Object} [settings]
     * @return {Object}
     */
    deleteRequest(url, params = null, settings = null) {
        url = joinParams(url, params);
        return this.request(HTTP_METHOD_DELETE, url, null, settings);
    }

    /**
     * Handles JSON in response
     * @param {XMLHttpRequest} xhr
     * @param {String} xhr.responseText
     * @return {Object}
     */
    handleJson(xhr) {
        let {responseText} = xhr,
            contentType = xhr.getResponseHeader('Content-Type') || '';

        contentType = contentType.toLowerCase();

        // If header Content-Type has value "application/json" then parse text as JSON
        if (contentType.indexOf(CONTENT_TYPE_JSON) !== -1) {
            try {
                return JSON.parse(responseText);
            } catch (e) {
                throw new Error(ERROR_JSON_PARSE);
            }
        }

        // Just return given xhr
        return xhr;
    }

    /**
     * Handles XHR response
     * @param {XMLHttpRequest} xhr
     * @param {Number} xhr.status
     * @see https://xhr.spec.whatwg.org/#interface-xmlhttprequest
     * @return {XMLHttpRequest}
     */
    handleResponse(xhr) {
        let {status} = xhr;

        // If status < 200 or status >= 200 then return error
        if (status < MIN_SUCCESSFUL_HTTP_CODE || status > MAX_SUCCESSFUL_HTTP_CODE) {
            let error = new Error(ERROR_UNACCEPTABLE_HTTP_CODE);
            error.statusCode = status;
            throw error;
        }

        // Just return given xhr
        return xhr;
    }

    /**
     * Handles any occured errors
     * @param {Error} error
     * @return {Error}
     */
    handleError(error) {
        // Really do nothing
        throw error;
    }
}

export default FetchPlease;
<commit_msg>Implement CORS<commit_after>import {assign, joinParams} from './helpers';

export const HTTP_METHOD_GET = 'GET';
export const HTTP_METHOD_PUT = 'PUT';
export const HTTP_METHOD_POST = 'POST';
export const HTTP_METHOD_DELETE = 'DELETE';
export const ALLOWED_METHODS = [
    HTTP_METHOD_GET,
    HTTP_METHOD_PUT,
    HTTP_METHOD_POST,
    HTTP_METHOD_DELETE
];

export const CONTENT_TYPE_JSON = 'application/json';
export const MIN_SUCCESSFUL_HTTP_CODE = 200;
export const MAX_SUCCESSFUL_HTTP_CODE = 299;

export const ERROR_XHR_NOT_FOUND = 'Constructor XMLHttpRequest not found';
export const ERROR_PROMISE_NOT_FOUND = 'Constructor Promise not found';
export const ERROR_UNKNOWN_HTTP_METHOD = 'Unknown HTTP method';
export const ERROR_UNACCEPTABLE_HTTP_CODE = 'Unacceptable HTTP code';
export const ERROR_INVALID_DATA = 'Invalid data for sending';
export const ERROR_JSON_PARSE = 'Invalid JSON';

export const ERROR_CONNECTION_TIMEOUT = 'Connection timeout';
export const ERROR_RESOURCE_ABORTED = 'Resource has been aborted';
export const ERROR_RESOURCE_FAILED = 'Resource failed to load';

/**
 * @class HTTP-transport based on XHR
 * @property {String} path Common path
 * @property {Number} timeout Timeout (in milliseconds)
 * @property {Object} headers Common headers
 * @property {Array} opened List of opened requests
 * @property {XMLHttpRequest} XMLHttpRequest XHR interface
 * @property {Boolean} cors ```true``` if supported Cross-Origin Resource Sharing
 * @see https://xhr.spec.whatwg.org/
 * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
 * @see http://www.html5rocks.com/en/tutorials/cors/
 */
class FetchPlease {
    /**
     * @param {String} path Common path for all requests
     * @param {Object} [settings] Object with settings
     * @param {Number} [settings.timeout = 0]
     * @param {Object} [settings.XMLHttpRequest = global.XMLHttpRequest]
     * @param {Object|Function} [settings.headers = {}]
     */
    constructor(path = '', settings = {}) {
        this.path = path;
        this.opened = [];

        assign(this, {
            timeout: 0,
            headers: {},
            XMLHttpRequest: global.XMLHttpRequest
        }, settings);

        let {XMLHttpRequest} = this;
        if (XMLHttpRequest) {
            this.cors = 'withCredentials' in (new XMLHttpRequest()) && settings.cors;
        }
    }

    /**
     * Creates XHR instance and Promise instance
     * @param {String} method HTTP method
     * @param {String} path
     * @param {Object} data
     * @param {Object} settings
     * @return {Object}
     */
    request(method, path, data = null, settings = null) {
        if (!this.XMLHttpRequest) {
            throw new Error(ERROR_XHR_NOT_FOUND);
        }

        if (!global.Promise) {
            throw new Error(ERROR_PROMISE_NOT_FOUND);
        }

        if (ALLOWED_METHODS.indexOf(method) === -1) {
            throw new Error(ERROR_UNKNOWN_HTTP_METHOD);
        }

        let xhr = new this.XMLHttpRequest(),
            promise = new Promise(function (resolve, reject) {
                xhr.addEventListener('error', () => reject(ERROR_RESOURCE_FAILED));
                xhr.addEventListener('abort', () => reject(ERROR_RESOURCE_ABORTED));
                xhr.addEventListener('timeout', () => reject(ERROR_CONNECTION_TIMEOUT));
                xhr.addEventListener('load', () => {
                    if (xhr.status) {
                        resolve(xhr);
                    }
                });
            });

        settings = settings || {};

        let handleJson = settings.handleJson || this.handleJson,
            handleError = settings.handleError || this.handleError,
            handleResponse = settings.handleResponse || this.handleResponse;

        promise = promise
            // Remove request from list of opened requests
            .then(
                () => this.close(xhr),
                (reason) => {
                    this.close(xhr);
                    throw new Error(reason);
                }
            )
            // Handle response
            .then(handleResponse)
            // Handle JSON in response
            .then(handleJson)
            // Handle errors
            .catch(handleError);

        // Add optinal `onProgress` handler
        if (settings.onProgress) {
            xhr.addEventListener('progress', settings.onProgress);
        }

        // Form URL without normalizing and open request
        let url = this.path + path;
        xhr.open(method, url);

        // Set headers
        // Order of method's calls is important
        // You must call setRequestHeader() after open(), but before send()
        // @see: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#setRequestHeader()
        let headers = assign(
            {},
            typeof this.headers === 'function' ? this.headers() : this.headers,
            settings.headers
        );
        this.setHeaders(xhr, headers);

        // Set timeout (before send() too)
        // @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Example_using_a_timeout
        let timeout = this.timeout || settings.timeout || 0;
        xhr.timeout = timeout;

        // Serialize data and send request
        data = this.serialize(data);

        if (this.cors) {
            xhr.withCredentials = true;
        }

        xhr.send(data);

        // Add request into list of opened requests
        this.add(xhr);

        return {xhr, promise};
    }

    /**
     * Serializes data for request
     * @param {*} data
     * @return {String|FormData|Blob}
     */
    serialize(data) {
        // Do nothing with FormData instance
        if (global.FormData && data instanceof FormData) {
            return data;
        }

        // Do nothing with Blob instance
        if (global.Blob && data instanceof Blob) {
            return data;
        }

        // Do nothing with string or null
        if (data === null || typeof data === 'string') {
            return data;
        }

        try {
            // Serialize other data as JSON
            return JSON.stringify(data);
        } catch (e) {
            throw new Error(ERROR_INVALID_DATA);
        }
    }

    /**
     * Iterates given headers and set them for XHR object
     * @param {XMLHttpRequest} xhr
     * @param {Object} headers
     * @return {XMLHttpRequest}
     */
    setHeaders(xhr, headers = {}) {
        return Object.keys(headers).reduce((xhr, header) => {
            let value = headers[header];

            if (value !== false && value !== null && value !== undefined) {
                xhr.setRequestHeader(header, value);
            }

            return xhr;
        }, xhr);
    }

    /**
     * Aborts all opened requests
     */
    abort() {
        this.opened.forEach((xhr) => xhr.abort());
    }

    /**
     * Adds request to list of opened requests
     * @param {XMLHttpRequest} xhr
     */
    add(xhr) {
        this.opened.push(xhr);
    }

    /**
     * Deletes request from list of opened requests
     * @param {XMLHttpRequest} xhr
     * @return {XMLHtpRequest}
     */
    close(xhr) {
        let idx = this.opened.indexOf(xhr);
        if (idx !== -1) {
            this.opened.splice(idx, 1);
        }
        return xhr;
    }

    /**
     * Sends GET request
     * @param {String} url
     * @param {Object} [params]
     * @param {Object} [settings]
     * @return {Promise}
     */
    get(url, params, settings) {
        let {promise} = this.getRequest(url, params, settings);
        return promise;
    }

    /**
     * Sends PUT request
     * @param {String} url
     * @param {Object} data
     * @param {Object} [settings]
     * @return {Promise}
     */
    put(url, data, settings) {
        let {promise} = this.putRequest(url, data, settings);
        return promise;
    }

    /**
     * Sends POST request
     * @param {String} url
     * @param {Object} data
     * @param {Object} [settings]
     * @return {Promise}
     */
    post(url, data, settings) {
        let {promise} = this.postRequest(url, data, settings);
        return promise;
    }

    /**
     * Sends DELETE request
     * @param {String} url
     * @param {Object} [params]
     * @param {Object} [settings]
     * @return {Promise}
     */
    delete(url, params, settings) {
        let {promise} = this.deleteRequest(url, params, settings);
        return promise;
    }

    /**
     * Sends same GET request but returns object with instances of XHR and Promise
     * @param {String} url
     * @param {Object} [params]
     * @param {Object} [settings]
     * @return {Object}
     */
    getRequest(url, params = null, settings = null) {
        url = joinParams(url, params);
        return this.request(HTTP_METHOD_GET, url, null, settings);
    }

    /**
     * Sends same PUT request but returns object with instances of XHR and Promise
     * @param {String} url
     * @param {Object} data
     * @param {Object} [settings]
     * @return {Object}
     */
    putRequest(url, data, settings = null) {
        return this.request(HTTP_METHOD_PUT, url, data, settings);
    }

    /**
     * Sends same POST request but returns object with instances of XHR and Promise
     * @param {String} url
     * @param {Object} data
     * @param {Object} [settings]
     * @return {Object}
     */
    postRequest(url, data, settings = null) {
        return this.request(HTTP_METHOD_POST, url, data, settings);
    }

    /**
     * Sends same DELETE request but returns object with instances of XHR and Promise
     * @param {String} url
     * @param {Object} [params]
     * @param {Object} [settings]
     * @return {Object}
     */
    deleteRequest(url, params = null, settings = null) {
        url = joinParams(url, params);
        return this.request(HTTP_METHOD_DELETE, url, null, settings);
    }

    /**
     * Handles JSON in response
     * @param {XMLHttpRequest} xhr
     * @param {String} xhr.responseText
     * @return {Object}
     */
    handleJson(xhr) {
        let {responseText} = xhr,
            contentType = xhr.getResponseHeader('Content-Type') || '';

        contentType = contentType.toLowerCase();

        // If header Content-Type has value "application/json" then parse text as JSON
        if (contentType.indexOf(CONTENT_TYPE_JSON) !== -1) {
            try {
                return JSON.parse(responseText);
            } catch (e) {
                throw new Error(ERROR_JSON_PARSE);
            }
        }

        // Just return given xhr
        return xhr;
    }

    /**
     * Handles XHR response
     * @param {XMLHttpRequest} xhr
     * @param {Number} xhr.status
     * @see https://xhr.spec.whatwg.org/#interface-xmlhttprequest
     * @return {XMLHttpRequest}
     */
    handleResponse(xhr) {
        let {status} = xhr;

        // If status < 200 or status >= 200 then return error
        if (status < MIN_SUCCESSFUL_HTTP_CODE || status > MAX_SUCCESSFUL_HTTP_CODE) {
            let error = new Error(ERROR_UNACCEPTABLE_HTTP_CODE);
            error.statusCode = status;
            throw error;
        }

        // Just return given xhr
        return xhr;
    }

    /**
     * Handles any occured errors
     * @param {Error} error
     * @return {Error}
     */
    handleError(error) {
        // Really do nothing
        throw error;
    }
}

export default FetchPlease;
<|endoftext|>


<commit_before>$(document).ready(function(){
  $('button').click(function(e){
    e.preventDefault();
    var userName = $('input:text').val();
    useName(userName);
    message(userName);
    localStorage.setItem('currentUser', userName);
    return userName;
  });
});

function useName(currentUser, goodDayOrBadDay) { //params of currentUser and what kind of day it is
  var makeGoodorBad = function(goodOrBad) {  //makeGoodorBad - to display correct kind of day later
    var node = document.createElement('p'); //creating proper elements and appending to DOM
    var textnode = document.createTextNode('Hey ' + currentUser + ', ' + goodOrBad);
    node.appendChild(textnode);
    document.getElementById('output').appendChild(node);
  };
  return makeGoodorBad;
}

  //here cometh the Closure
function message (currentUser){

  var goodDay = useName(currentUser, 'itsgood');
  goodDay('what a great day for biking!');

  var badDay = useName(currentUser, 'itsbad');
  badDay('maybe leave the bike at home today....');

  var soSoDay = useName(currentUser, 'itssoso');
  soSoDay('Conditions are not ideal. Depends on you, dude...');
};

//Event Listeners for Submit Button
submitButton.addEventListener('click', validateUserName);

function validateUserName(e) {
  e.preventDefault();
  var userName = document.forms['nameInput']['fname'].value;
  if (userName == null || userName == '') {
    $('#userAlert').show();
    $('#output').hide();
  }else {
    $('#userAlert').hide();
    $('#output').show();
    $('#nameForm').hide();
  }
};
<commit_msg>fixed problem where message would display twice after incorrect input. Moved calling message() into else clause.  Now only being called once.<commit_after>$(document).ready(function(){
  $('button').click(function(e){
    e.preventDefault();
    var userName = $('input:text').val();
    useName(userName);
    localStorage.setItem('currentUser', userName);
    return userName;
  });
});

function useName(currentUser, goodDayOrBadDay) { //params of currentUser and what kind of day it is
  var makeGoodorBad = function(goodOrBad) {  //makeGoodorBad - to display correct kind of day later
    var node = document.createElement('p'); //creating proper elements and appending to DOM
    var textnode = document.createTextNode('Hey ' + currentUser + ', ' + goodOrBad);
    node.appendChild(textnode);
    document.getElementById('output').appendChild(node);
  };
  return makeGoodorBad;
}

  //here cometh the Closure
function message (currentUser){

  var goodDay = useName(currentUser, 'itsgood');
  goodDay('what a great day for biking!');

  var badDay = useName(currentUser, 'itsbad');
  badDay('maybe leave the bike at home today....');

  var soSoDay = useName(currentUser, 'itssoso');
  soSoDay('Conditions are not ideal. Depends on you, dude...');
};

//Event Listeners for Submit Button
submitButton.addEventListener('click', validateUserName);

function validateUserName(e) {
  e.preventDefault();
  var userName = document.forms['nameInput']['fname'].value;
  if (userName == null || userName == '') {
    $('#userAlert').show();
    $('#output').hide();
  }else {
    message(userName);
    $('#userAlert').hide();
    $('#output').show();
    $('#nameForm').hide();
  }
};
<|endoftext|>


<commit_before>/*
 *  ShotgunPoker.js
 *  2014/06/19
 *  @auther minimo
 *  This Program is MIT license.
 */

//namespace tiger
shotgun = {
    core: null,
};

tm.define("shotgun.CanvasApp", {
    superClass: tm.app.CanvasApp,

    //ＢＧＭ＆効果音
    bgm: null,
    bgmIsPlay: false,
    bgmVolume: 1.0,
    seVolume: 1.0,

    //スコア保存
    lastScore: 0,
    highScore: 0,

    //各種設定
    useJoker: USE_JOKER,
    returnJoker: RETURN_JOKER,
    handList: null,

    init: function(id) {
        this.superInit(id);
        this.resize(SC_W, SC_H).fitWindow();
        this.fps = fps;
        this.background = "rgba(0, 0, 0, 0)";
        this.keyboard = tm.input.Keyboard(window);

        shotgun.core = this;

        var loadingScene = tm.ui["LoadingScene"]({
            assets: assets,
            width: SC_W,
            height: SC_H,
            nextScene: function() {
                this._onLoadAssets();
                return shotgun.TitleScene();
            }.bind(this),
        });
        loadingScene.bg.canvas.clearColor("black");
        this.replaceScene(loadingScene);

        //役名一覧
        this.handList = [];
        this.handList[0]  = {name: "MISS", point: MISS};
        this.handList[1]  = {name: "NO HAND", point: NOHAND};
        this.handList[2]  = {name: "ONE PAIR", point: ONEPAIR};
        this.handList[3]  = {name: "TWO PAIR", point: TWOPAIR};
        this.handList[4]  = {name: "FLASH", point: FLASH};
        this.handList[5]  = {name: "THREE CARD", point: THREECARD};
        this.handList[6]  = {name: "FULL HOUSE", point: FULLHOUSE};
        this.handList[7]  = {name: "STRAIGHT", point: STRAIGHT};
        this.handList[8]  = {name: "FOUR CARD", point: FOURCARD};
        this.handList[9]  = {name: "FIVE CARD", point: FIVECARD};
        this.handList[10] = {name: "STRAIGHT FLASH", point: STRAIGHTFLASH};
        this.handList[11] = {name: "R.STRAIGHT FLASH", point: ROYALSTRAIGHTFLASH};

        this.checkDevice();
    },

    //実行環境チェック
    checkDevice: function() {
        this.isPad = (navigator.userAgent.indexOf('iPad')+1?true:false);
        this.isPod = (navigator.userAgent.indexOf('iPad')+1?true:false);
        this.isPhone = (navigator.userAgent.indexOf('iPhone')+1?true:false);
        this.isAndroid = (navigator.userAgent.indexOf('Android')+1?true:false);
        this.isiOS4 = navigator.userAgent.match(/OS 4_[0-9_]+ like Mac OS X/i)!==null;
        this.isiOS5 = navigator.userAgent.match(/OS 5_[0-9_]+ like Mac OS X/i)!==null;
        this.isiOS6 = navigator.userAgent.match(/OS 6_[0-9_]+ like Mac OS X/i)!==null;

        if (PHONEGAP) {
            this.version = window.device.version;
            this.model = window.device.name;
            this.uuid = window.device.uuid;
            this.pageY = $('body').height(); me.pageX=$('body').width();
        }
    },

    _onLoadAssets: function() {
    },

    exitApp: function() {
        this.stop();
    },

    playBGM: function(asset) {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.stop();
                this.bgmIsPlay = false;
            }
        }
        this.bgm = tm.asset.AssetManager.get(asset).clone();
        if (this.bgm) {
            this.bgm.loop = true;
            this.bgm.volume = this.bgmVolume;
            this.bgm.play();
            this.bgmIsPlay = true;
        }
        return this.bgm;
    },

    stopBGM: function() {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.stop();
                this.bgmIsPlay = false;
            }
        }
    },

    pauseBGM: function() {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.pause();
                this.bgmIsPlay = false;
            }
        }
    }

    resumeBGM: function() {
        if (this.bgm) {
            if (!this.bgmIsPlay) {
                this.bgm.resume();
                this.bgmIsPlay = true;
            }
        }
    }

    playSE: function(asset) {
        var se = tm.asset.AssetManager.get(asset).clone();
        if (se) {
            se.loop = false;
            se.volume = this.seVolume;
            se.play();
        }
        return se;
    },
});

<commit_msg>bug fix<commit_after>/*
 *  ShotgunPoker.js
 *  2014/06/19
 *  @auther minimo
 *  This Program is MIT license.
 */

//namespace tiger
shotgun = {
    core: null,
};

tm.define("shotgun.CanvasApp", {
    superClass: tm.app.CanvasApp,

    //ＢＧＭ＆効果音
    bgm: null,
    bgmIsPlay: false,
    bgmVolume: 1.0,
    seVolume: 1.0,

    //スコア保存
    lastScore: 0,
    highScore: 0,

    //各種設定
    useJoker: USE_JOKER,
    returnJoker: RETURN_JOKER,
    handList: null,

    init: function(id) {
        this.superInit(id);
        this.resize(SC_W, SC_H).fitWindow();
        this.fps = fps;
        this.background = "rgba(0, 0, 0, 0)";
        this.keyboard = tm.input.Keyboard(window);

        shotgun.core = this;

        var loadingScene = tm.ui["LoadingScene"]({
            assets: assets,
            width: SC_W,
            height: SC_H,
            nextScene: function() {
                this._onLoadAssets();
                return shotgun.TitleScene();
            }.bind(this),
        });
        loadingScene.bg.canvas.clearColor("black");
        this.replaceScene(loadingScene);

        //役名一覧
        this.handList = [];
        this.handList[0]  = {name: "MISS", point: MISS};
        this.handList[1]  = {name: "NO HAND", point: NOHAND};
        this.handList[2]  = {name: "ONE PAIR", point: ONEPAIR};
        this.handList[3]  = {name: "TWO PAIR", point: TWOPAIR};
        this.handList[4]  = {name: "FLASH", point: FLASH};
        this.handList[5]  = {name: "THREE CARD", point: THREECARD};
        this.handList[6]  = {name: "FULL HOUSE", point: FULLHOUSE};
        this.handList[7]  = {name: "STRAIGHT", point: STRAIGHT};
        this.handList[8]  = {name: "FOUR CARD", point: FOURCARD};
        this.handList[9]  = {name: "FIVE CARD", point: FIVECARD};
        this.handList[10] = {name: "STRAIGHT FLASH", point: STRAIGHTFLASH};
        this.handList[11] = {name: "R.STRAIGHT FLASH", point: ROYALSTRAIGHTFLASH};

        this.checkDevice();
    },

    //実行環境チェック
    checkDevice: function() {
        this.isPad = (navigator.userAgent.indexOf('iPad')+1?true:false);
        this.isPod = (navigator.userAgent.indexOf('iPad')+1?true:false);
        this.isPhone = (navigator.userAgent.indexOf('iPhone')+1?true:false);
        this.isAndroid = (navigator.userAgent.indexOf('Android')+1?true:false);
        this.isiOS4 = navigator.userAgent.match(/OS 4_[0-9_]+ like Mac OS X/i)!==null;
        this.isiOS5 = navigator.userAgent.match(/OS 5_[0-9_]+ like Mac OS X/i)!==null;
        this.isiOS6 = navigator.userAgent.match(/OS 6_[0-9_]+ like Mac OS X/i)!==null;

        if (PHONEGAP) {
            this.version = window.device.version;
            this.model = window.device.name;
            this.uuid = window.device.uuid;
            this.pageY = $('body').height(); me.pageX=$('body').width();
        }
    },

    _onLoadAssets: function() {
    },

    exitApp: function() {
        this.stop();
    },

    playBGM: function(asset) {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.stop();
                this.bgmIsPlay = false;
            }
        }
        this.bgm = tm.asset.AssetManager.get(asset).clone();
        if (this.bgm) {
            this.bgm.loop = true;
            this.bgm.volume = this.bgmVolume;
            this.bgm.play();
            this.bgmIsPlay = true;
        }
        return this.bgm;
    },

    stopBGM: function() {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.stop();
                this.bgmIsPlay = false;
            }
        }
    },

    pauseBGM: function() {
        if (this.bgm) {
            if (this.bgmIsPlay) {
                this.bgm.pause();
                this.bgmIsPlay = false;
            }
        }
    },

    resumeBGM: function() {
        if (this.bgm) {
            if (!this.bgmIsPlay) {
                this.bgm.resume();
                this.bgmIsPlay = true;
            }
        }
    }

    playSE: function(asset) {
        var se = tm.asset.AssetManager.get(asset).clone();
        if (se) {
            se.loop = false;
            se.volume = this.seVolume;
            se.play();
        }
        return se;
    },
});

<|endoftext|>


<commit_before><commit_msg>Creates Game constructor with function to create nested array board<commit_after>function Game(startBoard) = {
  this.completed = false;
  this.board = makeBoard(startBoard);
};

Game.prototype.makeBoard = function(stringBoard){
  if (stringBoard.length !== 16){
    alert("Starting boards must be 16 digits long, you silly hobbit!");
    return false
  } else {
    var board = [];
    for (var i = 0; i < stringBoard.length; i+=4) {
      var array = [];
      for (var j = i; j < i+4; j++) {
      array.push(parseInt(stringBoard[j]));
      }
    board.push(array);
    }
  }
  return board;
};

// Game.prototype.toString = function(){

// };
<|endoftext|>


<commit_before>		//初始化引擎
		init(30,"mylegend",320,480,main,LEvent.INIT);
		//进度条显示层，背景层，方块绘制层，预览层
		var loadingLayer,backLayer,graphicsLayer,nextLayer;
		//存放图片对象的属性
		var imglist = {};
		//图片数据
		var imgData = new Array(
			{name:"backImage",path:"./image/backImage.png"},
			{name:"block1",path:"./image/block1.png"},
			{name:"block2",path:"./image/block2.png"},
			{name:"block3",path:"./image/block3.png"},
			{name:"block4",path:"./image/block4.png"}
			);
		//用于生成方块
		var box;
		//方块坐标数组初始化
		var map;
		var nodelist;
		var bitmapdataList;
		//方块区域起始位置
		var START_X1=15,START_Y1=20,START_X2=228,START_Y2=65;
		//预览方块和当前方块
		var nextBox,nowBox;
		var pointBox ={x:0,y:0};
		var speed=15,speedIndex=0,speedMax=15;
		//控制单元
		var myKey = {
			keyControl:null,
			step:1,
			stepindex:0,
			isTouchDown:false,
			touchX:0,
			touchY:0,
			touchMove:false
		};
		//main函数
		function main(){
			map =[
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0]
			];
			box = new Box();
			//背景层初始化
			backLayer = new LSprite();
			//在背景层描绘背景
			backLayer.graphics.drawRect(2,"brown",[0,0,350,480],true,"black");
			addChild(backLayer);
			//进度条显示层初始化
			loadingLayer = new LoadingSample1();
			backLayer.addChild(loadingLayer);
			//利用LLoadManage类：进度条的读取与显示
			LLoadManage.load(
				imgData,
				function(progress){
					loadingLayer.setProgress(progress);
			    },
			    function(result){
			    	imglist = result;
					backLayer.removeChild(loadingLayer);
					loadingLayer= null;
					gameInit();
			    }
			);
			//gameInit();
		}
		//游戏标题画面初始化
		function gameInit(){
			//显示游戏标题
			var title = new LTextField();
			title.x = 100;
			title.y = 100;
			title.text = "俄罗斯方块";
			title.size = 30;
			title.color ="white";
			backLayer.addChild(title);
			//提示信息
			backLayer.graphics.drawRect(1,"white",[50,250,250,30]);
			var infoText = new LTextField();
			infoText.x = 75;
			infoText.y = 250;
			infoText.size = 25;
			infoText.text = "点击页面开始游戏";
			infoText.color = "white";
			backLayer.addChild(infoText);
			//添加鼠标点击事件侦听
			infoText.addEventListener(LMouseEvent.MOUSE_UP,gameStart);
		}

<commit_msg>补充初始化变量<commit_after>		//初始化引擎
		init(30,"mylegend",320,480,main,LEvent.INIT);
		//进度条显示层，背景层，方块绘制层，预览层
		var loadingLayer,backLayer,graphicsLayer,nextLayer;
		//存放图片对象的属性
		var imglist = {};
		//图片数据
		var imgData = new Array(
			{name:"backImage",path:"./image/backImage.png"},
			{name:"block1",path:"./image/block1.png"},
			{name:"block2",path:"./image/block2.png"},
			{name:"block3",path:"./image/block3.png"},
			{name:"block4",path:"./image/block4.png"}
			);
		//用于生成方块
		var box;
		//方块坐标数组初始化
		var map;
		var nodelist;
		var bitmapdataList;
		//方块区域起始位置
		var START_X1=15,START_Y1=20,START_X2=228,START_Y2=65;
		//预览方块和当前方块
		var nextBox,nowBox;
		var pointBox ={x:0,y:0};
		var speed=15,speedIndex=0,speedMax=15;
		var point=0,pointText;
		//消除层数相关
		var del=0,delText;
		//控制单元
		var myKey = {
			keyControl:null,
			step:1,
			stepindex:0,
			isTouchDown:false,
			touchX:0,
			touchY:0,
			touchMove:false
		};
		//main函数
		function main(){
			map =[
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0],
				[0,0,0,0,0,0,0,0,0,0]
			];
			box = new Box();
			//背景层初始化
			backLayer = new LSprite();
			//在背景层描绘背景
			backLayer.graphics.drawRect(2,"brown",[0,0,350,480],true,"black");
			addChild(backLayer);
			//进度条显示层初始化
			loadingLayer = new LoadingSample1();
			backLayer.addChild(loadingLayer);
			//利用LLoadManage类：进度条的读取与显示
			LLoadManage.load(
				imgData,
				function(progress){
					loadingLayer.setProgress(progress);
			    },
			    function(result){
			    	imglist = result;
					backLayer.removeChild(loadingLayer);
					loadingLayer= null;
					gameInit();
			    }
			);
			//gameInit();
		}
		//游戏标题画面初始化
		function gameInit(){
			//显示游戏标题
			var title = new LTextField();
			title.x = 100;
			title.y = 100;
			title.text = "俄罗斯方块";
			title.size = 30;
			title.color ="white";
			backLayer.addChild(title);
			//提示信息
			backLayer.graphics.drawRect(1,"white",[50,250,250,30]);
			var infoText = new LTextField();
			infoText.x = 75;
			infoText.y = 250;
			infoText.size = 25;
			infoText.text = "点击页面开始游戏";
			infoText.color = "white";
			backLayer.addChild(infoText);
			//添加鼠标点击事件侦听
			infoText.addEventListener(LMouseEvent.MOUSE_UP,gameStart);
		}

<|endoftext|>


<commit_before>"use strict";

var Sprite = Sprite || {};

(function(exports) {

    var Frame = function(options) {
        for (var p in options) {
            this[p] = options[p];
        }
    };

    var proto = {

        constructor: Frame,

        duration: null,

        matrix: null,
        alpha: 1,
        imgName: null,

        imgInfo: 0,
        img: null,
        iw: 0,
        ih: 0,

        startTime: null,
        endTime: null,
        animation: null,

        init: function() {
            if (this.pieces) {
                this.initPieces();
                this.render = this.renderPieces;
            } else {
                this.initPiece(this);
                this.render = this.renderSelf;
            }
        },

        initPieces: function() {
            this.pieceCount = this.pieces.length;
            for (var i = 0; i < this.pieceCount; i++) {
                var p = this.pieces[i];
                this.initPiece(p);
            }
        },

        initPiece: function(p) {
            p.x = p.x || 0;
            p.y = p.y || 0;
            p.w = p.w || 0;
            p.h = p.h || 0;
            p.alpha = p.alpha || p.alpha === 0 ? p.alpha : 1;
            p.imgInfo = this.animation.getImgInfo(p.imgName);
            p.img = p.imgInfo.img;
            p.ix = p.imgInfo.x;
            p.iy = p.imgInfo.y;
            p.iw = p.imgInfo.w;
            p.ih = p.imgInfo.h;
            p.ox = p.ox || 0;
            p.oy = p.oy || 0;

        },

        renderPieces: function(context, x, y) {
            for (var i = 0; i < this.pieceCount; i++) {
                var p = this.pieces[i];
                this.renderPiece(context, p, x, y);
            }
        },
        renderPiece: function(context, p, x, y) {
            context.save();
            context.globalAlpha = p.alpha;
            var m = p.matrix;
            context.transform(m.a, m.b, m.c, m.d, m.tx + x, m.ty + y);
            context.drawImage(p.img, p.ix, p.iy, p.iw, p.ih, p.ox, p.oy, p.iw, p.ih);
            context.restore();
        },
        renderSelf: function(context, x, y) {
            this.renderPiece(context, this, x, y);
        },
        renderPieceBorder: function(context, x, y) {
            var ps, count = this.pieceCount;
            if (!count) {
                ps = [this];
                count = 1;
            } else {
                ps = this.pieces;
            }
            for (var i = 0; i < count; i++) {
                var p = ps[i];
                context.save();
                context.globalAlpha = p.alpha;
                var m = p.matrix;
                context.transform(m.a, m.b, m.c, m.d, m.e, m.f);
                context.strokeStyle = "#ff6600";
                context.strokeRect(0, 0, p.iw, p.ih);
                context.strokeRect(0, 0, 2, 2);
                context.restore();
            }
        }

    };

    for (var p in proto) {
        Frame.prototype[p] = proto[p];
    }

    exports.Frame = Frame;

})(Sprite);
<commit_msg>update<commit_after>"use strict";

var Sprite = Sprite || {};

(function(exports) {

    var Frame = function(options) {
        for (var p in options) {
            this[p] = options[p];
        }
    };

    var proto = {

        constructor: Frame,

        duration: null,
        imgName: null,
        alpha: 1,
        matrix: null,

        startTime: null,
        endTime: null,
        animation: null,

        init: function() {
            if (this.pieces) {
                this.initPieces();
                this.render = this.renderPieces;
            } else {
                this.initPiece(this);
                this.render = this.renderSelf;
            }
        },

        initPieces: function() {
            this.pieceCount = this.pieces.length;
            for (var i = 0; i < this.pieceCount; i++) {
                var p = this.pieces[i];
                this.initPiece(p);
            }
        },

        initPiece: function(p) {
            p.alpha = p.alpha || p.alpha === 0 ? p.alpha : 1;
            p.imgInfo = this.animation.getImgInfo(p.imgName);
            p.img = p.imgInfo.img;
            p.ix = p.imgInfo.x;
            p.iy = p.imgInfo.y;
            p.iw = p.imgInfo.w;
            p.ih = p.imgInfo.h;
            p.ox = p.ox || 0;
            p.oy = p.oy || 0;
            p.x = p.x || 0;
            p.y = p.y || 0;
            p.w = p.w || 0;
            p.h = p.h || 0;
        },

        renderPieces: function(context, x, y) {
            for (var i = 0; i < this.pieceCount; i++) {
                var p = this.pieces[i];
                this.renderPiece(context, p, x, y);
            }
        },

        renderPiece: function(context, p, x, y) {
            context.globalAlpha = p.alpha;
            var m = p.matrix;
            if (m) {
                context.save();
                context.transform(m.a, m.b, m.c, m.d, m.tx + x, m.ty + y);
                context.drawImage(p.img, p.ix, p.iy, p.iw, p.ih, p.ox, p.oy, p.iw, p.ih);
                context.restore();
            } else {
                context.drawImage(p.img, p.ix, p.iy, p.iw, p.ih, x + p.ox, y + p.oy, p.iw, p.ih);
            }
            context.globalAlpha = 1;
        },
        renderSelf: function(context, x, y) {
            this.renderPiece(context, this, x, y);
        },
        renderPieceBorder: function(context, x, y) {
            var ps, count = this.pieceCount;
            if (!count) {
                ps = [this];
                count = 1;
            } else {
                ps = this.pieces;
            }
            for (var i = 0; i < count; i++) {
                var p = ps[i];
                context.save();
                context.globalAlpha = p.alpha;
                var m = p.matrix;
                context.transform(m.a, m.b, m.c, m.d, m.e, m.f);
                context.strokeStyle = "#ff6600";
                context.strokeRect(0, 0, p.iw, p.ih);
                context.strokeRect(0, 0, 2, 2);
                context.restore();
            }
        }

    };

    for (var p in proto) {
        Frame.prototype[p] = proto[p];
    }

    exports.Frame = Frame;

})(Sprite);
<|endoftext|>


<commit_before>function Board(string) {
  this.input = string;
  this.board = [[0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]];
  this.firstMove = true;
}

Board.prototype.setUp = function() {
  var initialValues = this.input.split("");
  for (i=0; i<initialValues.length; i++) {
      var numToTest = parseInt(initialValues[i]);
    if (numToTest !== 0) {
      var innerArrayIndex = i%4;
      var outerArrayIndex = parseInt(i/4);
      this.board[outerArrayIndex][innerArrayIndex] = parseInt(initialValues[i]);
    }
  }
}

Board.prototype.toString = function(){
  var flattenedBoard = _.flatten(this.board);
  for (i=0; i<flattenedBoard.length; i++){
    flattenedBoard[i] = flattenedBoard[i].toString();
    if (i%4 === 3){
      flattenedBoard[i] += "\n";
    }
  }
  console.log(flattenedBoard.join(""));
}

Board.prototype.spawnNumber = function() {
  // check entire nested board for 0.
  // replace one of those 0s with a 2 or 4.
  var outerIndex = Math.floor(Math.random() * 4);
  var innerIndex = Math.floor(Math.random() * 4);
  if (this.board[outerIndex][innerIndex] === 0) {
    // 2 or 4
    if (this.firstMove === true){
      this.board[outerIndex][innerIndex] = 2;
      this.firstMove = false;
    }else {
      this.board[outerIndex][innerIndex] = Math.floor((Math.random() * 2) + 1 ) * 2;
    }
  }
  else {
    this.spawnNumber();
  }
}

Board.prototype.moveRight = function() {
  for (i=0; i<4; i++) {
    this.board[i] = _.without(this.board[i], 0);
    for (k=0; k < this.board[i].length - 1; k++) {
      if (this.board[i][k] === this.board[i][k+1]) {
        this.board[i][k+1] += this.board[i][k];
        this.board[i].splice(k, 1);
      }
    }
    var paddingAmount = 4 - this.board[i].length;
    for (j=0; j<paddingAmount; j++) {
      this.board[i].unshift(0);
    }
  }
  this.spawnNumber();
}

Board.prototype.moveLeft = function() {
  for (i=0; i<4; i++) {
    this.board[i] = _.without(this.board[i], 0);
    for (k=0; k < this.board[i].length - 1; k++) {
      if (this.board[i][k] === this.board[i][k+1]) {
        this.board[i][k+1] += this.board[i][k];
        this.board[i].splice(k, 1);
      }
    }
    var paddingAmount = 4 - this.board[i].length;
    for (j=0; j<paddingAmount; j++) {
      this.board[i].push(0);
    }
  }
  this.spawnNumber();
}

Board.prototype.moveUp = function() {
  var transposedBoard = _.zip.apply(_, this.board);
  for (i=0; i<4; i++) {
    transposedBoard[i] = _.without(transposedBoard[i], 0);
    for (k=0; k < transposedBoard[i].length - 1; k++) {
      if (transposedBoard[i][k] === transposedBoard[i][k+1]) {
        transposedBoard[i][k+1] += transposedBoard[i][k];
        transposedBoard[i].splice(k, 1);
      }
    }
    var paddingAmount = 4 - transposedBoard[i].length;
    for (j=0; j<paddingAmount; j++) {
      transposedBoard[i].push(0);
    }
  }
  this.board = _.zip.apply(_, transposedBoard);
  this.spawnNumber();
}

Board.prototype.moveDown = function() {
  var transposedBoard = _.zip.apply(_, this.board);
  for (i=0; i<4; i++) {
    transposedBoard[i] = _.without(transposedBoard[i], 0);
    for (k=0; k < transposedBoard[i].length - 1; k++) {
      if (transposedBoard[i][k] === transposedBoard[i][k+1]) {
        transposedBoard[i][k+1] += transposedBoard[i][k];
        transposedBoard[i].splice(k, 1);
      }
    }
    var paddingAmount = 4 - transposedBoard[i].length;
    for (j=0; j<paddingAmount; j++) {
      transposedBoard[i].unshift(0);
    }
  }
  this.board = _.zip.apply(_, transposedBoard);
  this.spawnNumber();
}

Board.prototype.draw = function() {
  for (outerIndex=0; outerIndex<4; outerIndex++) {
    for (innerIndex=0; innerIndex<4; innerIndex++ ) {
      document.getElementById(outerIndex + "-" + innerIndex).innerHTML = this.board[outerIndex][innerIndex];
    }
  }
}

<commit_msg>remove zeroes<commit_after>function Board(string) {
  this.input = string;
  this.board = [[0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 0, 0, 0]];
  this.firstMove = true;
}

Board.prototype.setUp = function() {
  var initialValues = this.input.split("");
  for (i=0; i<initialValues.length; i++) {
      var numToTest = parseInt(initialValues[i]);
    if (numToTest !== 0) {
      var innerArrayIndex = i%4;
      var outerArrayIndex = parseInt(i/4);
      this.board[outerArrayIndex][innerArrayIndex] = parseInt(initialValues[i]);
    }
  }
}

Board.prototype.toString = function(){
  var flattenedBoard = _.flatten(this.board);
  for (i=0; i<flattenedBoard.length; i++){
    flattenedBoard[i] = flattenedBoard[i].toString();
    if (i%4 === 3){
      flattenedBoard[i] += "\n";
    }
  }
  console.log(flattenedBoard.join(""));
}

Board.prototype.spawnNumber = function() {
  // check entire nested board for 0.
  // replace one of those 0s with a 2 or 4.
  var outerIndex = Math.floor(Math.random() * 4);
  var innerIndex = Math.floor(Math.random() * 4);
  if (this.board[outerIndex][innerIndex] === 0) {
    // 2 or 4
    if (this.firstMove === true){
      this.board[outerIndex][innerIndex] = 2;
      this.firstMove = false;
    }else {
      this.board[outerIndex][innerIndex] = Math.floor((Math.random() * 2) + 1 ) * 2;
    }
  }
  else {
    this.spawnNumber();
  }
}

Board.prototype.moveRight = function() {
  for (i=0; i<4; i++) {
    this.board[i] = _.without(this.board[i], 0);
    for (k=0; k < this.board[i].length - 1; k++) {
      if (this.board[i][k] === this.board[i][k+1]) {
        this.board[i][k+1] += this.board[i][k];
        this.board[i].splice(k, 1);
      }
    }
    var paddingAmount = 4 - this.board[i].length;
    for (j=0; j<paddingAmount; j++) {
      this.board[i].unshift(0);
    }
  }
  this.spawnNumber();
}

Board.prototype.moveLeft = function() {
  for (i=0; i<4; i++) {
    this.board[i] = _.without(this.board[i], 0);
    for (k=0; k < this.board[i].length - 1; k++) {
      if (this.board[i][k] === this.board[i][k+1]) {
        this.board[i][k+1] += this.board[i][k];
        this.board[i].splice(k, 1);
      }
    }
    var paddingAmount = 4 - this.board[i].length;
    for (j=0; j<paddingAmount; j++) {
      this.board[i].push(0);
    }
  }
  this.spawnNumber();
}

Board.prototype.moveUp = function() {
  var transposedBoard = _.zip.apply(_, this.board);
  for (i=0; i<4; i++) {
    transposedBoard[i] = _.without(transposedBoard[i], 0);
    for (k=0; k < transposedBoard[i].length - 1; k++) {
      if (transposedBoard[i][k] === transposedBoard[i][k+1]) {
        transposedBoard[i][k+1] += transposedBoard[i][k];
        transposedBoard[i].splice(k, 1);
      }
    }
    var paddingAmount = 4 - transposedBoard[i].length;
    for (j=0; j<paddingAmount; j++) {
      transposedBoard[i].push(0);
    }
  }
  this.board = _.zip.apply(_, transposedBoard);
  this.spawnNumber();
}

Board.prototype.moveDown = function() {
  var transposedBoard = _.zip.apply(_, this.board);
  for (i=0; i<4; i++) {
    transposedBoard[i] = _.without(transposedBoard[i], 0);
    for (k=0; k < transposedBoard[i].length - 1; k++) {
      if (transposedBoard[i][k] === transposedBoard[i][k+1]) {
        transposedBoard[i][k+1] += transposedBoard[i][k];
        transposedBoard[i].splice(k, 1);
      }
    }
    var paddingAmount = 4 - transposedBoard[i].length;
    for (j=0; j<paddingAmount; j++) {
      transposedBoard[i].unshift(0);
    }
  }
  this.board = _.zip.apply(_, transposedBoard);
  this.spawnNumber();
}

Board.prototype.draw = function() {
  for (outerIndex=0; outerIndex<4; outerIndex++) {
    for (innerIndex=0; innerIndex<4; innerIndex++ ) {
      if (this.board[outerIndex][innerIndex] !== 0) {
        document.getElementById(outerIndex + "-" + innerIndex).innerHTML = this.board[outerIndex][innerIndex];
      }
      else {
        document.getElementById(outerIndex + "-" + innerIndex).innerHTML = "";
      }
    }
  }
}

<|endoftext|>


<commit_before>var _ = require('busyman'),
    network = require('network'),
    request = require('./request'),
    reporter = require('./reporter'),
    msgHandlers = require('./msg_handlers');

module.exports = function (qn) {
    var so = qn.so,
        waitForIp = false;

    if (!so.has('lwm2mServer', 0)) {
        so.init('lwm2mServer', 0, {     // oid = 1
            shortServerId: null,        // rid = 0
            lifetime: qn.lifetime,      // rid = 1
            defaultMinPeriod: 1,        // rid = 2
            defaultMaxPeriod: 60,       // rid = 3
            regUpdateTrigger: {         // rid = 8
                exec: function () {
                    qn.register();
                }                       // [TODO] pub register?
            }
        });
    }

    if (!so.has('device', 0)) {
        so.init('device', 0, {          // oid = 3
            manuf: 'lwmqn',             // rid = 0
            model: 'MQ1',               // rid = 1
            reboot: {                   // rid = 4
                exec: function () {}
            },
            availPwrSrc: 0,             // rid = 6
            pwrSrcVoltage: 5000,        // rid = 7
            devType: 'generic',         // rid = 17
            hwVer: 'v1',                // rid = 18
            swVer: 'v1'                 // rid = 19
        });
    }

    if (!so.has('connMonitor', 0)) {
        so.init('connMonitor', 0, {     // oid = 4
            ip: {                       // rid = 4
                read: function (cb) {
                    network.get_active_interface(function(err, info) {
                        if (err)
                            cb(err);
                        else
                            cb(null, info.ip_address);
                    });
                }
            },
            routeIp: {                  // rid = 5
                read: function (cb) {
                    network.get_active_interface(function(err, info) {
                        if (err)
                            cb(err);
                        else
                            cb(null, info.gateway_ip);
                    });
                }
            }
        });
    }

    so.__read = so.read;    // __read is the original read
    so.read = function (oid, iid, rid, callback, opt) {
        var isReadable = so.isReadable(oid, iid, rid),
            dataToCheck;

        return so.__read(oid, iid, rid, function (err, data) {
            if (isReadable) {
                dataToCheck = data;
                process.nextTick(function () {
                    reporter.checkAndReportResource(qn, oid, iid, rid, dataToCheck);
                });
            }

            callback(err, data);
        }, opt);
    };

    so.__write = so.write;    // __write is the original write
    so.write = function (oid, iid, rid, value, callback, opt) {
        var isReadable = so.isReadable(oid, iid, rid),
            dataToCheck;

        return so.__write(oid, iid, rid, value, function (err, data) {
            if (isReadable) {
                dataToCheck = data || value;
                process.nextTick(function () {
                    reporter.checkAndReportResource(qn, oid, iid, rid, dataToCheck);
                });
            }

            callback(err, data);
        }, opt);
    };

    // set up LWMQN interfaces
    _.forEach([ 'register', 'deregister', 'notify', 'update', 'ping' ], function (intf) {
        qn._pubics[intf] = intf + '/' + qn.clientId;
        qn._subics[intf] = intf + '/response/' + qn.clientId;
    });

    qn._pubics.response = 'response/' + qn.clientId;
    qn._subics.request = 'request/' + qn.clientId;
    qn._subics.announce = 'announce';

    // set up message handlers
    qn.on('raw', function (topic, message, packet) {
        msgHandlers._rawHdlr(qn, topic, message, packet);
    });

    qn.on('_request', function (err, msg) {     // emit @ msgHandlers._rawHdlr with (err, jmsg)
        process.nextTick(function () {          // function wrapped for MT7688 node@0.12.7
            msgHandlers._reqHdlr(qn, msg);
        });
    });

    qn.on('_unconnected', function () {
        qn._connected = false;
    });

    qn.on('_connected', function () {
        qn._connected = true;
        setTimeout(function () {
            if (qn._connected)
                request.lwmqnSubAndReg(qn);     // subscribe LWMQN interfaces and register to Shepherd
        }, 100);
    });

    // get ip and mac if not given
    if (!qn.ip || !qn.mac) {
        waitForIp = true;

        network.get_active_interface(function(err, info) {
            if (!err) {
                qn.ip = qn.ip || info.ip_address.toLowerCase();
                qn.mac = info.mac_address.toLowerCase();
                qn.emit('ready');
            } else {
                qn.emit('error', err);
            }
            waitForIp = false;
        });
    }

    if (!waitForIp)
        qn.emit('ready');

    return true;
};
<commit_msg>try catch network module<commit_after>var _ = require('busyman'),
    request = require('./request'),
    reporter = require('./reporter'),
    msgHandlers = require('./msg_handlers');

try {
    var network = require('network');
} catch (e) {
    console.log('Ignore this message when running tests on Travis.');
}

module.exports = function (qn) {
    var so = qn.so,
        waitForIp = false;

    if (!so.has('lwm2mServer', 0)) {
        so.init('lwm2mServer', 0, {     // oid = 1
            shortServerId: null,        // rid = 0
            lifetime: qn.lifetime,      // rid = 1
            defaultMinPeriod: 1,        // rid = 2
            defaultMaxPeriod: 60,       // rid = 3
            regUpdateTrigger: {         // rid = 8
                exec: function () {
                    qn.register();
                }                       // [TODO] pub register?
            }
        });
    }

    if (!so.has('device', 0)) {
        so.init('device', 0, {          // oid = 3
            manuf: 'lwmqn',             // rid = 0
            model: 'MQ1',               // rid = 1
            reboot: {                   // rid = 4
                exec: function () {}
            },
            availPwrSrc: 0,             // rid = 6
            pwrSrcVoltage: 5000,        // rid = 7
            devType: 'generic',         // rid = 17
            hwVer: 'v1',                // rid = 18
            swVer: 'v1'                 // rid = 19
        });
    }

    if (!so.has('connMonitor', 0)) {
        so.init('connMonitor', 0, {     // oid = 4
            ip: {                       // rid = 4
                read: function (cb) {
                    network.get_active_interface(function(err, info) {
                        if (err)
                            cb(err);
                        else
                            cb(null, info.ip_address);
                    });
                }
            },
            routeIp: {                  // rid = 5
                read: function (cb) {
                    network.get_active_interface(function(err, info) {
                        if (err)
                            cb(err);
                        else
                            cb(null, info.gateway_ip);
                    });
                }
            }
        });
    }

    so.__read = so.read;    // __read is the original read
    so.read = function (oid, iid, rid, callback, opt) {
        var isReadable = so.isReadable(oid, iid, rid),
            dataToCheck;

        return so.__read(oid, iid, rid, function (err, data) {
            if (isReadable) {
                dataToCheck = data;
                process.nextTick(function () {
                    reporter.checkAndReportResource(qn, oid, iid, rid, dataToCheck);
                });
            }

            callback(err, data);
        }, opt);
    };

    so.__write = so.write;    // __write is the original write
    so.write = function (oid, iid, rid, value, callback, opt) {
        var isReadable = so.isReadable(oid, iid, rid),
            dataToCheck;

        return so.__write(oid, iid, rid, value, function (err, data) {
            if (isReadable) {
                dataToCheck = data || value;
                process.nextTick(function () {
                    reporter.checkAndReportResource(qn, oid, iid, rid, dataToCheck);
                });
            }

            callback(err, data);
        }, opt);
    };

    // set up LWMQN interfaces
    _.forEach([ 'register', 'deregister', 'notify', 'update', 'ping' ], function (intf) {
        qn._pubics[intf] = intf + '/' + qn.clientId;
        qn._subics[intf] = intf + '/response/' + qn.clientId;
    });

    qn._pubics.response = 'response/' + qn.clientId;
    qn._subics.request = 'request/' + qn.clientId;
    qn._subics.announce = 'announce';

    // set up message handlers
    qn.on('raw', function (topic, message, packet) {
        msgHandlers._rawHdlr(qn, topic, message, packet);
    });

    qn.on('_request', function (err, msg) {     // emit @ msgHandlers._rawHdlr with (err, jmsg)
        process.nextTick(function () {          // function wrapped for MT7688 node@0.12.7
            msgHandlers._reqHdlr(qn, msg);
        });
    });

    qn.on('_unconnected', function () {
        qn._connected = false;
    });

    qn.on('_connected', function () {
        qn._connected = true;
        setTimeout(function () {
            if (qn._connected)
                request.lwmqnSubAndReg(qn);     // subscribe LWMQN interfaces and register to Shepherd
        }, 100);
    });

    // get ip and mac if not given
    if (!qn.ip || !qn.mac) {
        waitForIp = true;

        network.get_active_interface(function(err, info) {
            if (!err) {
                qn.ip = qn.ip || info.ip_address.toLowerCase();
                qn.mac = info.mac_address.toLowerCase();
                qn.emit('ready');
            } else {
                qn.emit('error', err);
            }
            waitForIp = false;
        });
    }

    if (!waitForIp)
        qn.emit('ready');

    return true;
};
<|endoftext|>