<commit_before>import $ from "jquery";
import SimpleBar from "simplebar";

import render_read_receipts from "../templates/read_receipts.hbs";
import render_read_receipts_modal from "../templates/read_receipts_modal.hbs";

import * as channel from "./channel";
import {$t, $t_html} from "./i18n";
import * as loading from "./loading";
import * as overlays from "./overlays";
import * as people from "./people";
import * as popovers from "./popovers";
import * as ui_report from "./ui_report";

export function show_user_list(message_id) {
    $("body").append(render_read_receipts_modal());
    overlays.open_modal("read_receipts_modal", {
        autoremove: true,
        on_show: () => {
            loading.make_indicator($("#read_receipts_modal .loading_indicator"));
            channel.get({
                url: `/json/messages/${message_id}/read_receipts`,
                success(data) {
                    const users = data.user_ids.map((id) => {
                        const user = people.get_by_user_id(id);
                        return {
                            user_id: user.user_id,
                            full_name: user.full_name,
                            avatar_url: people.small_avatar_url_for_person(user),
                        };
                    });
                    users.sort(people.compare_by_name);

                    loading.destroy_indicator($("#read_receipts_modal .loading_indicator"));
                    if (users.length === 0) {
                        $("#read_receipts_modal .read_receipts_info").text(
                            $t({defaultMessage: "No one has read this message yet."}),
                        );
                    } else {
                        $("#read_receipts_modal .read_receipts_info").html(
                            $t_html(
                                {
                                    defaultMessage:
                                        "{num_of_people, plural, one {This message has been <z-link>read</z-link> by one person:} other {This message has been <z-link>read</z-link> by {num_of_people} people:}}",
                                },
                                {
                                    num_of_people: users.length,
                                    "z-link": (content_html) =>
                                        `<a href="/help/read-receipts">${content_html}</a>`,
                                },
                            ),
                        );
                        $("#read_receipts_modal .modal__container").addClass(
                            "showing_read_receipts_list",
                        );
                        $("#read_receipts_modal .modal__content").append(
                            render_read_receipts({users}),
                        );
                        new SimpleBar($("#read_receipts_modal .modal__content")[0]);
                    }
                },
                error(xhr) {
                    ui_report.error("", xhr, $("#read_receipts_error"));
                    loading.destroy_indicator($("#read_receipts_modal .loading_indicator"));
                },
            });
        },
        on_hide: () => {
            // Ensure any user info popovers are closed
            popovers.hide_all();
        },
    });
}
<commit_msg>Revert "read_receipts: Use 'one person' instead of '1 person'."<commit_after>import $ from "jquery";
import SimpleBar from "simplebar";

import render_read_receipts from "../templates/read_receipts.hbs";
import render_read_receipts_modal from "../templates/read_receipts_modal.hbs";

import * as channel from "./channel";
import {$t, $t_html} from "./i18n";
import * as loading from "./loading";
import * as overlays from "./overlays";
import * as people from "./people";
import * as popovers from "./popovers";
import * as ui_report from "./ui_report";

export function show_user_list(message_id) {
    $("body").append(render_read_receipts_modal());
    overlays.open_modal("read_receipts_modal", {
        autoremove: true,
        on_show: () => {
            loading.make_indicator($("#read_receipts_modal .loading_indicator"));
            channel.get({
                url: `/json/messages/${message_id}/read_receipts`,
                success(data) {
                    const users = data.user_ids.map((id) => {
                        const user = people.get_by_user_id(id);
                        return {
                            user_id: user.user_id,
                            full_name: user.full_name,
                            avatar_url: people.small_avatar_url_for_person(user),
                        };
                    });
                    users.sort(people.compare_by_name);

                    loading.destroy_indicator($("#read_receipts_modal .loading_indicator"));
                    if (users.length === 0) {
                        $("#read_receipts_modal .read_receipts_info").text(
                            $t({defaultMessage: "No one has read this message yet."}),
                        );
                    } else {
                        $("#read_receipts_modal .read_receipts_info").html(
                            $t_html(
                                {
                                    defaultMessage:
                                        "{num_of_people, plural, one {This message has been <z-link>read</z-link> by {num_of_people} person:} other {This message has been <z-link>read</z-link> by {num_of_people} people:}}",
                                },
                                {
                                    num_of_people: users.length,
                                    "z-link": (content_html) =>
                                        `<a href="/help/read-receipts">${content_html}</a>`,
                                },
                            ),
                        );
                        $("#read_receipts_modal .modal__container").addClass(
                            "showing_read_receipts_list",
                        );
                        $("#read_receipts_modal .modal__content").append(
                            render_read_receipts({users}),
                        );
                        new SimpleBar($("#read_receipts_modal .modal__content")[0]);
                    }
                },
                error(xhr) {
                    ui_report.error("", xhr, $("#read_receipts_error"));
                    loading.destroy_indicator($("#read_receipts_modal .loading_indicator"));
                },
            });
        },
        on_hide: () => {
            // Ensure any user info popovers are closed
            popovers.hide_all();
        },
    });
}
<|endoftext|>


<commit_before>function MPU(plugin_host) {
	var m_plugin_host = plugin_host;
	var m_callback = null;
	var m_debugoutput_time = Date.now();
	var m_quat = new THREE.Quaternion(0, 0, 0, 1);
	var m_north_diff = 0;
	var m_north = 0;

	var self = {
		// return THREE.Quaternion
		get_quaternion : function() {
			return m_quat.clone();
		},
		get_north : function() {
			return m_north;
		},
		set_attitude : function(pitch, yaw, roll) {
			var quat = new THREE.Quaternion()
				.setFromEuler(new THREE.Euler(THREE.Math.degToRad(pitch), THREE.Math
					.degToRad(yaw), THREE.Math.degToRad(roll), "YXZ"));
			m_quat = quat;
		},
		set_callback : function(callback) {
			m_callback = callback;
		},
		init : function() {
			if (navigator.devicemotion) {
				var options = {
					frequency : 1000 / 100
				}; // 100fps

				var watchID_attitude = navigator.devicemotion
					.watchAttitude(self.onSuccess_attitude, self.onError_attitude, options);
			} else {
				self.initDeviceOrientationEventLisener();
			}
		},

		onSuccess_attitude : function(attitude) {
			var quat = new THREE.Quaternion()
				.setFromEuler(new THREE.Euler(THREE.Math
					.degToRad(attitude.beta), THREE.Math
					.degToRad(attitude.alpha), THREE.Math
					.degToRad(-attitude.gamma), "YXZ"));
			m_quat = quat;
		},

		onError_attitude : function(error) {
			alert('Sensor error: ' + error);
		},

		onSuccess_accel : function(acceleration) {
			lat = Math.round(Math.atan2(-acceleration.z, -acceleration.x) * 180
				/ Math.PI);
			if (lat < -90) {
				lat = -180 - lat;
			}
			if (lat > 90) {
				lat = 180 - lat;
			}
		},

		onError_accel : function() {
			console.log('onError!');
		},

		// onSuccess: Get the current heading
		onSuccess_compass : function(heading) {
			// console.log('Heading: ' + heading.magneticHeading);
			lon = heading.magneticHeading;
		},

		// onError: Failed to get the heading
		onError_compass : function(compassError) {
			alert('Compass Error: ' + compassError.code);
		},

		initDeviceOrientationEventLisener : function() {
			window
				.addEventListener('deviceorientation', function(attitude) {
					if (attitude['detail']) {
						attitude = attitude['detail'];
					}
					var time = Date.now();
					if (attitude.alpha != null) {
						var quat = new THREE.Quaternion()
							.setFromEuler(new THREE.Euler(THREE.Math
								.degToRad(attitude.beta), THREE.Math
								.degToRad(attitude.alpha), THREE.Math
								.degToRad(-attitude.gamma), "YXZ"));
						var offset_quat = new THREE.Quaternion()
							.setFromEuler(new THREE.Euler(THREE.Math
								.degToRad(0), THREE.Math
								.degToRad(-window.orientation), THREE.Math
								.degToRad(0), "YXZ"));
						quat = quat.multiply(offset_quat);

						m_north = -attitude.webkitCompassHeading
							- window.orientation;
						var euler = new THREE.Euler()
							.setFromQuaternion(quat, "YXZ");
						if (Math.abs(euler.x * 180 / Math.PI) < 45
							&& Math.abs(euler.z * 180 / Math.PI) < 45) {
							m_north_diff = euler.y * 180 / Math.PI - m_north;
						}
						var north_diff_quat = new THREE.Quaternion()
							.setFromEuler(new THREE.Euler(THREE.Math
								.degToRad(0), THREE.Math
								.degToRad(-m_north_diff), THREE.Math
								.degToRad(0), "YXZ"));
						quat = north_diff_quat.multiply(quat);

						m_quat = quat;
						if (time - m_debugoutput_time > 500) {
							var euler = new THREE.Euler()
								.setFromQuaternion(quat, "YXZ");
							m_debugoutput_time = time;
							// console.log(attitude);
							m_plugin_host
								.log(sprintf("north=%.3f, diff=%.3f, x=%.3f, y=%.3f, z=%.3f", m_north, m_north_diff, euler.x
									* 180 / Math.PI, euler.y * 180 / Math.PI, euler.z
									* 180 / Math.PI), 5);
						}
					}
				});
		}
	};
	return self;
}<commit_msg>debug deviceorientation in android<commit_after>function MPU(plugin_host) {
	var m_plugin_host = plugin_host;
	var m_callback = null;
	var m_debugoutput_time = Date.now();
	var m_quat = new THREE.Quaternion(0, 0, 0, 1);
	var m_north_diff = 0;
	var m_north = 0;

	var self = {
		// return THREE.Quaternion
		get_quaternion : function() {
			return m_quat.clone();
		},
		get_north : function() {
			return m_north;
		},
		set_attitude : function(pitch, yaw, roll) {
			var quat = new THREE.Quaternion()
				.setFromEuler(new THREE.Euler(THREE.Math.degToRad(pitch), THREE.Math
					.degToRad(yaw), THREE.Math.degToRad(roll), "YXZ"));
			m_quat = quat;
		},
		set_callback : function(callback) {
			m_callback = callback;
		},
		init : function() {
			if (navigator.devicemotion) {
				var options = {
					frequency : 1000 / 100
				}; // 100fps

				var watchID_attitude = navigator.devicemotion
					.watchAttitude(self.onSuccess_attitude, self.onError_attitude, options);
			} else {
				self.initDeviceOrientationEventLisener();
			}
		},

		onSuccess_attitude : function(attitude) {
			var quat = new THREE.Quaternion()
				.setFromEuler(new THREE.Euler(THREE.Math
					.degToRad(attitude.beta), THREE.Math
					.degToRad(attitude.alpha), THREE.Math
					.degToRad(-attitude.gamma), "YXZ"));
			m_quat = quat;
		},

		onError_attitude : function(error) {
			alert('Sensor error: ' + error);
		},

		onSuccess_accel : function(acceleration) {
			lat = Math.round(Math.atan2(-acceleration.z, -acceleration.x) * 180
				/ Math.PI);
			if (lat < -90) {
				lat = -180 - lat;
			}
			if (lat > 90) {
				lat = 180 - lat;
			}
		},

		onError_accel : function() {
			console.log('onError!');
		},

		// onSuccess: Get the current heading
		onSuccess_compass : function(heading) {
			// console.log('Heading: ' + heading.magneticHeading);
			lon = heading.magneticHeading;
		},

		// onError: Failed to get the heading
		onError_compass : function(compassError) {
			alert('Compass Error: ' + compassError.code);
		},

		initDeviceOrientationEventLisener : function() {
			window.ondeviceorientation = function(evt){
				console.log(evt);
			}
			window.onorientationchange = function(evt){
				console.log(evt);
			}
			window
				.addEventListener('deviceorientation', function(attitude) {
					if (attitude['detail']) {
						attitude = attitude['detail'];
					}
					var time = Date.now();
					if (attitude.alpha != null) {
						var quat = new THREE.Quaternion()
							.setFromEuler(new THREE.Euler(THREE.Math
								.degToRad(attitude.beta), THREE.Math
								.degToRad(attitude.alpha), THREE.Math
								.degToRad(-attitude.gamma), "YXZ"));
						var offset_quat = new THREE.Quaternion()
							.setFromEuler(new THREE.Euler(THREE.Math
								.degToRad(0), THREE.Math
								.degToRad(-window.orientation), THREE.Math
								.degToRad(0), "YXZ"));
						quat = quat.multiply(offset_quat);

						m_north = -attitude.webkitCompassHeading
							- window.orientation;
						var euler = new THREE.Euler()
							.setFromQuaternion(quat, "YXZ");
						if (Math.abs(euler.x * 180 / Math.PI) < 45
							&& Math.abs(euler.z * 180 / Math.PI) < 45) {
							m_north_diff = euler.y * 180 / Math.PI - m_north;
						}
						var north_diff_quat = new THREE.Quaternion()
							.setFromEuler(new THREE.Euler(THREE.Math
								.degToRad(0), THREE.Math
								.degToRad(-m_north_diff), THREE.Math
								.degToRad(0), "YXZ"));
						quat = north_diff_quat.multiply(quat);

						m_quat = quat;
						if (time - m_debugoutput_time > 500) {
							var euler = new THREE.Euler()
								.setFromQuaternion(quat, "YXZ");
							m_debugoutput_time = time;
							// console.log(attitude);
							m_plugin_host
								.log(sprintf("north=%.3f, diff=%.3f, x=%.3f, y=%.3f, z=%.3f", m_north, m_north_diff, euler.x
									* 180 / Math.PI, euler.y * 180 / Math.PI, euler.z
									* 180 / Math.PI), 5);
						}
					}
				});
		}
	};
	return self;
}<|endoftext|>


<commit_before>// Nav.js
// Shows nested navs smoothly when main nav links are clicked or hovered over

var timeoutId = 0;
var thisNav;
var isDone;
var isTabOpen = false;

function showNav() {
	isDone = false;
	thisNav.css('z-index', 100).slideDown(300, function() {isDone = true;});
	isTabOpen = true;
}

function hideNav() {
	isDone = false;
	thisNav.css('z-index', 50).slideUp(200, function() {isDone = true;});
}

function clickToggle() {
	if(isDone == true) {
		$(this).next().slideToggle(300);
		return false;
	}
}

// Disable default show on hover from css
$('body').removeClass('no-javascript');

// Show nested nav on hover, and hide nested nav on mouse leave
$('.nav-link').on({
	mouseenter: function() {
		thisNav = $(this).children('ul');
		if (isTabOpen == true) {
			timeoutId = setTimeout(showNav, 150);
		} else {
			timeoutId = setTimeout(showNav, 0);
		}
		isTabOpen = true;
	},
	mouseleave: function() {
		clearTimeout(timeoutId);
		hideNav();
	}
});

// Alternatively toggles nested nav on click (this is for mobile)
$('.nav-link > a').on('click', clickToggle);

//Prevent nav link from opening
$('.nav-link > a').click (function (e) {
        e.preventDefault();
        return false;
    }
);

// $('#myElement').mousedown(function() {
//     timeoutId = setTimeout(myFunction, 1000);
// }).bind('mouseup mouseleave', function() {
//     clearTimeout(timeoutId);
// });<commit_msg>Removed unnecessary javascript function<commit_after>// Nav.js
// Shows nested navs smoothly when main nav links are clicked or hovered over

var timeoutId = 0;
var thisNav;
var isDone;
var isTabOpen = false;

function showNav() {
	isDone = false;
	thisNav.css('z-index', 100).slideDown(300, function() {isDone = true;});
	isTabOpen = true;
}

function hideNav() {
	isDone = false;
	thisNav.css('z-index', 50).slideUp(200, function() {isDone = true;});
}

function clickToggle() {
	if(isDone == true) {
		$(this).next().slideToggle(300);
		return false;
	}
}

// Disable default show on hover from css
$('body').removeClass('no-javascript');

// Show nested nav on hover, and hide nested nav on mouse leave
$('.nav-link').on({
	mouseenter: function() {
		thisNav = $(this).children('ul');
		if (isTabOpen == true) {
			timeoutId = setTimeout(showNav, 150);
		} else {
			timeoutId = setTimeout(showNav, 0);
		}
		isTabOpen = true;
	},
	mouseleave: function() {
		clearTimeout(timeoutId);
		hideNav();
	}
});

// Alternatively toggles nested nav on click (this is for mobile)
$('.nav-link > a').on('click', clickToggle);

// $('#myElement').mousedown(function() {
//     timeoutId = setTimeout(myFunction, 1000);
// }).bind('mouseup mouseleave', function() {
//     clearTimeout(timeoutId);
// });<|endoftext|>


<commit_before>/*
 * plt.js 0.2.0
 *
 * http://github.com/nasser/pltjs
 *
 * Copyright (c) 2014 Ramsey Nasser
 * Licensend under the MIT license.
 */

// configuration object
// refreshes every second by default
var PLT = {
  refresh: false,
  refreshTime: 1000,

  parser: null
};

$(function() {
  // inject css style to format code elements and body text
  var cssNode = document.createElement('style');
  cssNode.innerHTML = "body { font-family: sans-serif; }";
  cssNode.innerHTML += "code { display: block; white-space: pre; margin-bottom: 1em; }";
  cssNode.innerHTML += "#repl { height: 1em; }";
  cssNode.innerHTML += "#repl .error { color: red; }";
  cssNode.innerHTML += "#repl pre { background: #eee; padding: 5px; }";
  cssNode.innerHTML += "textarea { opacity:0 }";
  cssNode.innerHTML += ".jqconsole-cursor { background: gray; }";
  document.body.appendChild(cssNode);

  // extract PEG grammar from <grammar> element and build parser
  var grammarElement = $("grammar");
  PLT.parser = PEG.buildParser(grammarElement.text())
  grammarElement.remove();

  var stringifiedParse = function(source) {
    return JSON.stringify(PLT.parser.parse(source));
  }

  // build repl object
  $('
').
    appendTo("body");
  var repl = $("#repl").jqconsole("", '> ');
  $("#repl div").attr('style', '');

  var startPrompt = function () {
    repl.Prompt(true, function (input) {
      try {
        var evalfn = PLT.repl || stringifiedParse;
        repl.Write(evalfn(input) + '\n', 'jqconsole-output');
      } catch(err) {
        repl.Write(err.message + "\n", 'error');
      }
      startPrompt();

      // scroll to the repl when on new line
      repl.$console.get(0).scrollIntoView();
    });
  }
  startPrompt();

  // scroll to the repl when a key is pressed
  repl.$input_source.keypress(function() { repl.$console.get(0).scrollIntoView(); });

  // focus the repl by default
  repl.Focus();

  $('
' + $('title').text() + '
').
    prependTo("body");

  // collect all correct code examples and try and parse them
  var goods = document.querySelectorAll("code:not([bad])")
  for (var i = 0; i < goods.length; i++) {
    try {
      var str = stringifiedParse(goods[i].textContent);

      // Look for expected attribute like this:
      if(goods[i].attributes.getNamedItem('expect')){
        var expectedValue = goods[i].attributes.getNamedItem('expect').value;

        // Validate that the expected value matches the returned value
        if(expectedValue != str){
          var error = new Error('Expected '+expectedValue+" but got "+str)
          error.line = 0;
          throw error;
        }
      }
      // the code parsed, append result in grey
      goods[i].innerHTML += "\n↳ " + str + "";

    } catch (err) {
      // the code did not parse, append result in red

      // Add carrot to show the position of the error
      var carrot = '';
      if(err.line == goods[i].textContent.split('\n').length){
        carrot = Array(err.column).join(' ')+'^\n'
      }

      // If there is line info, add information about where the error is
      var lineError = '';
      if(err.line){
        lineError = "
\t" + "Line " + err.line + " Column "+err.column;
      }

      goods[i].innerHTML += "\n"+carrot+"↳ " + err.message + lineError + "";
    }
  }

  // collect all incorrect code examples and try and parse them
  var bads = document.querySelectorAll("code[bad]")
  for (var i = 0; i < bads.length; i++) {
    try {
      var str = stringifiedParse(goods[i].textContent);
      // the code parsed, append result in red
      bads[i].innerHTML += "\n↳ " + str + "";

    } catch (err) {
      // the code did not parse, append result in gray
      bads[i].innerHTML += "\n↳ " + err.message + "";

    }
  }

  // refresh the page if refreshing is enabled
  setInterval(function() { if(PLT.refresh) window.location.reload(true) }, PLT.refreshTime);
});
<commit_msg>Replace ^ with ↑<commit_after>/*
 * plt.js 0.2.0
 *
 * http://github.com/nasser/pltjs
 *
 * Copyright (c) 2014 Ramsey Nasser
 * Licensend under the MIT license.
 */

// configuration object
// refreshes every second by default
var PLT = {
  refresh: false,
  refreshTime: 1000,

  parser: null
};

$(function() {
  // inject css style to format code elements and body text
  var cssNode = document.createElement('style');
  cssNode.innerHTML = "body { font-family: sans-serif; }";
  cssNode.innerHTML += "code { display: block; white-space: pre; margin-bottom: 1em; }";
  cssNode.innerHTML += "#repl { height: 1em; }";
  cssNode.innerHTML += "#repl .error { color: red; }";
  cssNode.innerHTML += "#repl pre { background: #eee; padding: 5px; }";
  cssNode.innerHTML += "textarea { opacity:0 }";
  cssNode.innerHTML += ".jqconsole-cursor { background: gray; }";
  document.body.appendChild(cssNode);

  // extract PEG grammar from <grammar> element and build parser
  var grammarElement = $("grammar");
  PLT.parser = PEG.buildParser(grammarElement.text())
  grammarElement.remove();

  var stringifiedParse = function(source) {
    return JSON.stringify(PLT.parser.parse(source));
  }

  // build repl object
  $('
').
    appendTo("body");
  var repl = $("#repl").jqconsole("", '> ');
  $("#repl div").attr('style', '');

  var startPrompt = function () {
    repl.Prompt(true, function (input) {
      try {
        var evalfn = PLT.repl || stringifiedParse;
        repl.Write(evalfn(input) + '\n', 'jqconsole-output');
      } catch(err) {
        repl.Write(err.message + "\n", 'error');
      }
      startPrompt();

      // scroll to the repl when on new line
      repl.$console.get(0).scrollIntoView();
    });
  }
  startPrompt();

  // scroll to the repl when a key is pressed
  repl.$input_source.keypress(function() { repl.$console.get(0).scrollIntoView(); });

  // focus the repl by default
  repl.Focus();

  $('
' + $('title').text() + '
').
    prependTo("body");

  // collect all correct code examples and try and parse them
  var goods = document.querySelectorAll("code:not([bad])")
  for (var i = 0; i < goods.length; i++) {
    try {
      var str = stringifiedParse(goods[i].textContent);

      // Look for expected attribute like this:
      if(goods[i].attributes.getNamedItem('expect')){
        var expectedValue = goods[i].attributes.getNamedItem('expect').value;

        // Validate that the expected value matches the returned value
        if(expectedValue != str){
          var error = new Error('Expected '+expectedValue+" but got "+str)
          error.line = 0;
          throw error;
        }
      }
      // the code parsed, append result in grey
      goods[i].innerHTML += "\n↳ " + str + "";

    } catch (err) {
      // the code did not parse, append result in red

      // Add carrot to show the position of the error
      var carrot = '';
      if(err.line == goods[i].textContent.split('\n').length){
        carrot = Array(err.column).join(' ')+'↑\n'
      }

      // If there is line info, add information about where the error is
      var lineError = '';
      if(err.line){
        lineError = "
\t" + "Line " + err.line + " Column "+err.column;
      }

      goods[i].innerHTML += "\n"+carrot+"↳ " + err.message + lineError + "";
    }
  }

  // collect all incorrect code examples and try and parse them
  var bads = document.querySelectorAll("code[bad]")
  for (var i = 0; i < bads.length; i++) {
    try {
      var str = stringifiedParse(goods[i].textContent);
      // the code parsed, append result in red
      bads[i].innerHTML += "\n↳ " + str + "";

    } catch (err) {
      // the code did not parse, append result in gray
      bads[i].innerHTML += "\n↳ " + err.message + "";

    }
  }

  // refresh the page if refreshing is enabled
  setInterval(function() { if(PLT.refresh) window.location.reload(true) }, PLT.refreshTime);
});
<|endoftext|>


<commit_before>var Qlb = {};

Qlb.Environment = function(table, outer) {
  this.table = table
  this.outer = outer
  this.find = function (sym) { return this.table[sym] === undefined ? (this.outer ? this.outer.find(sym) : undefined) : this.table[sym] }
  this.merge = function(other) { for(var name in other) this.table[name] = other[name] }
}

Qlb.globalEnvironment = new Qlb.Environment({});

Qlb.init = function(onloaded) {
  // Load grammar from separate file, because dealing with JavaScripts lack of
  // multiline strings AND Arabic input is just too much. Just too much.
  jx.load("/peg/qlb.peg", function(grammar) {
    // Load grammar
    Qlb.parser = PEG.buildParser(grammar);

    // Default console is window consle
    if(Qlb.console === 'undefined') Qlb.console = window.console;

    Qlb.eval = function(exp, env) {
      if(typeof exp == "string") {            // evaling string/symbol TODO make this better
        var sym = env.find(exp);
        return sym || exp;

      } else if(!(exp instanceof Array)) {    // evaling literal
        return exp;

      } else {                                // evaling list
        var first = exp[0]
        var rest = exp.slice(1)

        if(first == "حرفي") {
          return rest

        } else if(first == "إفعل") {
          rest = rest.map(function(e) { return Qlb.eval(e, env) });
          return rest[rest.length - 1];

        } else if(first == "إذا") {
          var test = rest[0],
              ifex = rest[1],
              elex = rest[2]

          return Qlb.eval(Qlb.eval(test, env) ? ifex : elex, env)

        } else if(first == "حدد") {
          var sym = rest[0],
              val = rest[1]
          return (env.table[sym] = Qlb.eval(val, env))

        } else if(first == "لامدا") {
          var params = rest[0],
              body = rest.slice(1)

          return function() {
            var table = {}
            for (var i = 0; i < params.length; i++)
              table[params[i]] = arguments[i]

            return Qlb.eval(body, new Qlb.Environment(table, env))
          }

        } else {
          var exps = exp.map(function(p) { return Qlb.eval(p, env) })
          if(typeof exps[0] == "function")
            // first element evaluates to a function
            return exps.shift().apply(this, exps)

          else
            // return last element
            return exps[exps.length - 1];

        }
      }
    }

    Qlb.execute = function(code) {
      try {
        var ast = Qlb.parser.parse(code);
        var val;
        for (var i = 0; i < ast.length; i++) {
          val = Qlb.eval(ast[i], Qlb.globalEnvironment);
        };
        return val;

      } catch(e) {
        Qlb.handleUncaughtException(e);

      }
    }

    Qlb.handleUncaughtException = function(e) {
      switch(e.name) {
        case "SyntaxError":
          Qlb.console.warn("خطأ: حرف '" + e.found + "' غير متوقع");
          break;

        default:
          throw e;

      }
    }

    if(onloaded) onloaded();
  });
}

<commit_msg>Fix symbol lookup bug<commit_after>var Qlb = {};

Qlb.Environment = function(table, outer) {
  this.table = table
  this.outer = outer
  this.find = function (sym) { return this.table[sym] === undefined ? (this.outer ? this.outer.find(sym) : undefined) : this.table[sym] }
  this.merge = function(other) { for(var name in other) this.table[name] = other[name] }
}

Qlb.globalEnvironment = new Qlb.Environment({});

Qlb.init = function(onloaded) {
  // Load grammar from separate file, because dealing with JavaScripts lack of
  // multiline strings AND Arabic input is just too much. Just too much.
  jx.load("/peg/qlb.peg", function(grammar) {
    // Load grammar
    Qlb.parser = PEG.buildParser(grammar);

    // Default console is window consle
    if(Qlb.console === 'undefined') Qlb.console = window.console;

    Qlb.eval = function(exp, env) {
      if(typeof exp == "string") {            // evaling string/symbol TODO make this better
        var sym = env.find(exp);
        if(sym === undefined) return exp;
        else return sym;

      } else if(!(exp instanceof Array)) {    // evaling literal
        return exp;

      } else {                                // evaling list
        var first = exp[0]
        var rest = exp.slice(1)

        if(first == "حرفي") {
          return rest

        } else if(first == "إفعل") {
          rest = rest.map(function(e) { return Qlb.eval(e, env) });
          return rest[rest.length - 1];

        } else if(first == "إذا") {
          var test = rest[0],
              ifex = rest[1],
              elex = rest[2]

          return Qlb.eval(Qlb.eval(test, env) ? ifex : elex, env)

        } else if(first == "حدد") {
          var sym = rest[0],
              val = rest[1]
          return (env.table[sym] = Qlb.eval(val, env))

        } else if(first == "لامدا") {
          var params = rest[0],
              body = rest.slice(1)

          return function() {
            var table = {}
            for (var i = 0; i < params.length; i++)
              table[params[i]] = arguments[i]

            return Qlb.eval(body, new Qlb.Environment(table, env))
          }

        } else {
          var exps = exp.map(function(p) { return Qlb.eval(p, env) })
          if(typeof exps[0] == "function")
            // first element evaluates to a function
            return exps.shift().apply(this, exps)

          else
            // return last element
            return exps[exps.length - 1];

        }
      }
    }

    Qlb.execute = function(code) {
      try {
        var ast = Qlb.parser.parse(code);
        var val;
        for (var i = 0; i < ast.length; i++) {
          val = Qlb.eval(ast[i], Qlb.globalEnvironment);
        };
        return val;

      } catch(e) {
        Qlb.handleUncaughtException(e);

      }
    }

    Qlb.handleUncaughtException = function(e) {
      switch(e.name) {
        case "SyntaxError":
          Qlb.console.warn("خطأ: حرف '" + e.found + "' غير متوقع");
          break;

        default:
          throw e;

      }
    }

    if(onloaded) onloaded();
  });
}

<|endoftext|>


<commit_before>$(document).ready(function() {
	//Initialzing navbar for mobile devices
   $('select').material_select();

   var cultural = $('#culturalevents');
   var technical = $('#technicalevents');

   //form registration by jquery
   $('.submit').click(function(e){
   	e.preventDefault();
    $(this).addClass("disabled");
   	var name = $('#name').val();
   	var roll = $('#roll').val();
   	var branch = $('#branch').val();
   	var year = $('#year').val();
   	var email = $('#email').val();
   	var phone = $('#phone').val();

   	//Took me an hour but finally made it work. 2DeepJS4u
   	//Solo Events
   var checkedEvents = $('#culturalsolo input:checked');
   var events = [];
   events = checkedEvents.each(function(){events.push($(this).attr('id'))});
   var eventnames = [];
   for(i=0;i<events.length;i++) {eventnames.push(events[i].id);}
   eventnames = eventnames.toString(); //this variable holds solo event names
	console.log(eventnames);

	//Group Events
	var checkedEventsg = $('#culturalgroup input:checked');
	var eventsg = [];
	eventsg = checkedEventsg.each(function(){eventsg.push($(this).attr('id'))});

	var eventnamesg = [];
	for(i=0;i<eventsg.length;i++) {eventnamesg.push(eventsg[i].id);}
	for(i=0;i<eventnamesg.length;i++) {
		var temp = '#'+eventnamesg[i]+'text';

		var names = $(temp).val();
		eventnamesg[i] = eventnamesg[i]+'('+names+')';
	}

	eventnamesg = eventnamesg.toString(); //this variable holds group event names
	console.log(eventnamesg);

	//Technical Events
	   var tcheckedEvents = $('#technicalevents input:checked');
	   var tevents = [];
	   tevents = tcheckedEvents.each(function(){tevents.push($(this).attr('id'))});
	   var teventnames = [];
	   for(i=0;i<tevents.length;i++) {teventnames.push(tevents[i].id);}
	   teventnames = teventnames.toString(); //this variable holds solo event names
		console.log(teventnames);

   	$.post('register.php',{name:name, roll:roll, branch:branch, year:year, email:email, phone:phone, eventnames:eventnames, eventnamesg:eventnamesg,teventnames:teventnames}, function(return_data){
		alert(return_data);
	});

    window.location.replace("index.html");

   });

   //Initially register button is hidden and it will be shown when event type is selected
  $('.submit').css("display","none");

  	//This changes the events list acc. to dropdown selection
   $(document).on('change','#eventtype',function(){
   					$('.submit').show();
                   var option = $(this).find("option:selected").attr('value');
                   if(option=='cultural'){
                   	cultural.toggle();
                   	technical.css("display","none");
                   }else{
                   	cultural.css("display","none")
                   	technical.toggle();
                   }
             });

   //Initially all textareas for group event member names are hidden unless their respective event name is checked from above
   //Hide them all on load
   $("div[id$='form']").css("display","none"); //hides all textarea unless ticked by upper tickbox

   //Show when event name is checked
   $('#banjo').click(function(){$('#banjoform').toggle()});
   $('#sargam').click(function(){$('#sargamform').toggle()});
   $('#nritya').click(function(){$('#nrityaform').toggle()});
   $('#manch').click(function(){$('#manchform').toggle()});
   $('#gudgudi').click(function(){$('#gudgudiform').toggle()});
   $('#tamaasha').click(function(){$('#tamaashaform').toggle()});
   $('#filmy').click(function(){$('#filmyform').toggle()});
   $('#saregamapa').click(function(){$('#saregamapaform').toggle()});
   $('#drishyam').click(function(){$('#drishyamform').toggle()});
   $('#admad').click(function(){$('#admadform').toggle()});

 });<commit_msg>tech section error solved<commit_after>$(document).ready(function() {
	//Initialzing navbar for mobile devices
   $('select').material_select();

   var cultural = $('#culturalevents');
   var technical = $('#technicalevents');

   //form registration by jquery
   $('.submit').click(function(e){
   	e.preventDefault();
    $(this).addClass("disabled");
   	var name = $('#name').val();
   	var roll = $('#roll').val();
   	var branch = $('#branch').val();
   	var year = $('#year').val();
   	var email = $('#email').val();
   	var phone = $('#phone').val();

   	//Took me an hour but finally made it work. 2DeepJS4u
   	//Solo Events
   var checkedEvents = $('#culturalsolo input:checked');
   var events = [];
   events = checkedEvents.each(function(){events.push($(this).attr('id'))});
   var eventnames = [];
   for(i=0;i<events.length;i++) {eventnames.push(events[i].id);}
   eventnames = eventnames.toString(); //this variable holds solo event names
	console.log(eventnames);

	//Group Events
	var checkedEventsg = $('#culturalgroup input:checked');
	var eventsg = [];
	eventsg = checkedEventsg.each(function(){eventsg.push($(this).attr('id'))});

	var eventnamesg = [];
	for(i=0;i<eventsg.length;i++) {eventnamesg.push(eventsg[i].id);}
	for(i=0;i<eventnamesg.length;i++) {
		var temp = '#'+eventnamesg[i]+'text';

		var names = $(temp).val();
		eventnamesg[i] = eventnamesg[i]+'('+names+')';
	}

	eventnamesg = eventnamesg.toString(); //this variable holds group event names
	console.log(eventnamesg);

	//Technical Events
	   var tcheckedEvents = $('#technicalevents input:checked');
	   var tevents = [];
	   tevents = tcheckedEvents.each(function(){tevents.push($(this).attr('id'))});
	   var teventnames = [];
	   for(i=0;i<tevents.length;i++) {teventnames.push(tevents[i].id);}
	   teventnames = teventnames.toString(); //this variable holds solo event names
		console.log(teventnames);

   	$.post('register.php',{name:name, roll:roll, branch:branch, year:year, email:email, phone:phone, eventnames:eventnames, eventnamesg:eventnamesg,teventnames:teventnames}, function(return_data){
		alert(return_data);
    window.location.replace("index.html");
	});

   });

   //Initially register button is hidden and it will be shown when event type is selected
  $('.submit').css("display","none");

  	//This changes the events list acc. to dropdown selection
   $(document).on('change','#eventtype',function(){
   					$('.submit').show();
                   var option = $(this).find("option:selected").attr('value');
                   if(option=='cultural'){
                   	cultural.toggle();
                   	technical.css("display","none");
                   }else{
                   	cultural.css("display","none")
                   	technical.toggle();
                   }
             });

   //Initially all textareas for group event member names are hidden unless their respective event name is checked from above
   //Hide them all on load
   $("div[id$='form']").css("display","none"); //hides all textarea unless ticked by upper tickbox

   //Show when event name is checked
   $('#banjo').click(function(){$('#banjoform').toggle()});
   $('#sargam').click(function(){$('#sargamform').toggle()});
   $('#nritya').click(function(){$('#nrityaform').toggle()});
   $('#manch').click(function(){$('#manchform').toggle()});
   $('#gudgudi').click(function(){$('#gudgudiform').toggle()});
   $('#tamaasha').click(function(){$('#tamaashaform').toggle()});
   $('#filmy').click(function(){$('#filmyform').toggle()});
   $('#saregamapa').click(function(){$('#saregamapaform').toggle()});
   $('#drishyam').click(function(){$('#drishyamform').toggle()});
   $('#admad').click(function(){$('#admadform').toggle()});

 });<|endoftext|>


<commit_before>/**
 * Class to represent a course. Should be used in a list to represent a schedule.
 * Has functions avaliable to manipulate the data and present things in different ways.
 *
 * @constructor
 * @author Bradley Cai
 */
function Course(quarter, name, nameID, bldg, room, gt, units,
                hour1, min1, hour2, min2, days) {

    //General information
    this.quarter = quarter; //written as a string in the format of "season####"
    this.name = name;
    this.nameID = nameID; //ID written under the name of the course. (ex. CHEM-001A-060)
    this.bldg = bldg; //String of the bldg
    this.room = room; //String of room number
    this.gt = gt; //GT - Grade type. No one knows what this is
    this.units = units; //Expressed as a double

    //Time information
    this.hour1 = hour1; //Hour class begins. Integer between 0-23
    this.min1 = min1; //Integer between 0-59
    this.hour2 = hour2; //Hour when class ends.
    this.min2 = min2;

    //Array information
    this.blocks = 2*(this.hour2 - this.hour1) - (this.min2 - this.min1)/30; //How many 30 minute blocks it takes (ex 60 is 2 blocks)
    this.duration = 30 * this.blocks; //Duration of class in minutes (ex. 60 for 60 minutes)
    this.pos = ((this.hour1 * 60 + this.min1) - 420)/30; //Position on the hourList
    this.days = [false, false, false, false, false, false]; //Array of days as booleans.

    for(var i = 0; i < days.length; i++) {
        switch(days.charAt(i)) {
            case "M":
                this.days[0] = true;
                break;
            case "T":
                this.days[1] = true;
                break;
            case "W":
                this.days[2] = true;
                break;
            case "R":
                this.days[3] = true;
                break;
            case "F":
                this.days[4] = true;
                break;
            case "S":
                this.days[5] = true;
                break;
        }
    }
}
var courseList = 0;
var hourList = 0;

/**
 * Test function to fill courseList with dummy courses
 *
 */
function createTestCourses() {

    var list = new Array();

    /*Example courses. Will be filled from user input in the final version */
    list.push(new Course("FALL", "INTRO: CS FOR SCI,MATH&ENGR I", "CS -010 -001", "BRNHL", "A125", "None", 4,
                    9, 0, 10, 0, "MWF"));
    list.push(new Course("FALL", "INTRO: CS FOR SCI,MATH&ENGR I", "CS -010 -001", "BRNHL", "A125", "None", 4,
                    15, 30, 17, 0, "TR"));

    return list;
}
function createHourList() {
    //Initialize a 2-D array. Each item within the array is an array.
    hourList = new Array(32)
    for (var i = 0; i < 32; i++) {
        hourList[i] = new Array(6);
    }

    for (var c = 0; c < courseList.length; c++) { //for each course
        var current = courseList[c];
        for (var day = 0; day < current.days.length; day++) { //for each day of the week
            if (current.days[day] == true) {
                //console.log(courseList[c].pos + " " + day);
                for (var b = 0; b < current.blocks; b++) {//for each block

                    hourList[current.pos + b][day] = courseList[c];
                }
            }
        }
    }
}

function createTableString() {
    var tableString =
"
\n \

\n \

\n \
            	\n \
            Monday	\n \
            Tuesday	\n \
            Wednesday	\n \
            Thursday	\n \
            Friday	\n \
            Saturday	\n \

\n \

\n \

\n";

    var hour = 0;
    for (var row = 0; row < 32; row++) { //for each tr/row (700 730 800 etc). 30 is the amount of rows. See blocks

        //Creates the row with an hour ID to keep things readable
        tableString += "
\n";
        if (row < 11) {
            hour = (row * 30 + 420)/60;
        }
        else {
            hour = (row * 30 + 420)/60 - 12;
        }

        //Creates the first column of times
        if (row % 2 == 0) { //To make each rowspan 2 time column
            if (Math.floor(row/15) == 0) {
                tableString += "" + hour + "AM	\n" }
            else {
                tableString += "" + hour + "PM	\n" }
        }

        //Creates the courses in the table
        for (var col = 0; col < 6; col++) { // for each td/day (mon - sat = 6). Starts
            courseAtI = hourList[row][col];
            if (!(courseAtI == null)) {
                if (hourList[row - 1][col] == null) {
                    var popoutString;
                    switch (courseAtI.blocks) {
                        case 1:
                            tableString += "" + courseAtI.nameID + "	\n";
                            break;
                        case 2:
                            tableString += "" + courseAtI.nameID
                            + "
" + courseAtI.duration + " minutes	\n";
                            break;
                        default:
                            tableString += "" + courseAtI.nameID
                            + "
" + courseAtI.duration + " minutes
" + courseAtI.bldg + " "
                            + courseAtI.room + "	\n"
                            break;
                    }

                }
            }
            else {
                tableString += "	\n";
            }
        }
    }
    tableString += "
";
    return tableString;
}

function createTable(tableString) {
    var tableSpace = document.getElementById("table-space");

    tableSpace.innerHTML = tableString;
    console.log(tableString);
}<commit_msg>Added more documentation in ucr.js to make it a bit more digestable<commit_after>/**
 * Class to represent a course. Should be used in a list to represent a schedule.
 * Has functions avaliable to manipulate the data and present things in different ways.
 *
 * @constructor
 * @author Bradley Cai
 */
function Course(quarter, name, nameID, bldg, room, gt, units,
                hour1, min1, hour2, min2, days) {

    //General information
    this.quarter = quarter; //written as a string in the format of "season####"
    this.name = name;
    this.nameID = nameID; //ID written under the name of the course. (ex. CHEM-001A-060)
    this.bldg = bldg; //String of the bldg
    this.room = room; //String of room number
    this.gt = gt; //GT - Grade type. No one knows what this is
    this.units = units; //Expressed as a double

    //Time information
    this.hour1 = hour1; //Hour class begins. Integer between 0-23
    this.min1 = min1; //Integer between 0-59
    this.hour2 = hour2; //Hour when class ends.
    this.min2 = min2;

    //Array information
    this.blocks = 2*(this.hour2 - this.hour1) - (this.min2 - this.min1)/30; //How many 30 minute blocks it takes (ex 60 is 2 blocks)
    this.duration = 30 * this.blocks; //Duration of class in minutes (ex. 60 for 60 minutes)
    this.pos = ((this.hour1 * 60 + this.min1) - 420)/30; //Position on the hourList
    this.days = [false, false, false, false, false, false]; //Array of days as booleans.

    for(var i = 0; i < days.length; i++) {
        switch(days.charAt(i)) {
            case "M":
                this.days[0] = true;
                break;
            case "T":
                this.days[1] = true;
                break;
            case "W":
                this.days[2] = true;
                break;
            case "R":
                this.days[3] = true;
                break;
            case "F":
                this.days[4] = true;
                break;
            case "S":
                this.days[5] = true;
                break;
        }
    }
}
var courseList = 0;
var hourList = 0;

/**
 * Test function to fill an array with dummy courses.
 *
 * @return - A fake courseList of courses.
 */
function createTestCourses() {

    var list = new Array();

    /*Example courses. Will be filled from user input in the final version */
    list.push(new Course("FALL", "INTRO: CS FOR SCI,MATH&ENGR I", "CS -010 -001", "BRNHL", "A125", "None", 4,
                    9, 0, 10, 0, "MWF"));
    list.push(new Course("FALL", "INTRO: CS FOR SCI,MATH&ENGR I", "CS -010 -001", "BRNHL", "A125", "None", 4,
                    15, 30, 17, 0, "TR"));

    return list;
}

/**
 * Creates a 2D array whose rows are time in 30 minute blocks and columns days of the week.
 * The spot on a calender where the courses takes place in time on a certain day will fill
 * that postion on the array.
 *
 */
function createHourList() {
    //Initialize a 2-D array. Each item within the array is an array.
    hourList = new Array(32)
    for (var i = 0; i < 32; i++) {
        hourList[i] = new Array(6);
    }

    for (var c = 0; c < courseList.length; c++) { //for each course
        var current = courseList[c];
        for (var day = 0; day < current.days.length; day++) { //for each day of the week
            if (current.days[day] == true) {
                //console.log(courseList[c].pos + " " + day);
                for (var b = 0; b < current.blocks; b++) {//for each block

                    hourList[current.pos + b][day] = courseList[c];
                }
            }
        }
    }
}

/**
 * Creates a string for the innerHTML element of the table. You can view the html in the console log
 *
 * More is explained inside.
 *
 */
function createTableString() {
    //This creates the first row of days
    var tableString =
"
\n \

\n \

\n \
            	\n \
            Monday	\n \
            Tuesday	\n \
            Wednesday	\n \
            Thursday	\n \
            Friday	\n \
            Saturday	\n \

\n \

\n \

\n";

    //This creates the body of the table
    var hour = 0;
    for (var row = 0; row < 32; row++) { //for each tr/row (700 730 800 etc). 32 is the amount of rows. See blocks

        //Starts off the row with an hour ID to keep things readable
        tableString += "
\n";

        //This is the 12 hour clock mechanism
        if (row < 11) {
            hour = (row * 30 + 420)/60;
        }
        else {
            hour = (row * 30 + 420)/60 - 12;
        }

        //This creates the first column of times and adds AM or PM based on time of day
        if (row % 2 == 0) { //To make each rowspan 2 time column
            if (Math.floor(row/15) == 0) {
                tableString += "" + hour + "AM	\n" }
            else {
                tableString += "" + hour + "PM	\n" }
        }

        //This creates the courses in the table
        for (var col = 0; col < 6; col++) { // for each td/day (mon - sat = 6)
            courseAtI = hourList[row][col];

            //This displays the course info per course, instead of per block
            if (!(courseAtI == null)) {
                if (hourList[row - 1][col] == null) {
                    var popoutString;
                    switch (courseAtI.blocks) {
                        case 1:
                            tableString += "" + courseAtI.nameID + "	\n";
                            break;
                        case 2:
                            tableString += "" + courseAtI.nameID
                            + "
" + courseAtI.duration + " minutes	\n";
                            break;
                        default:
                            tableString += "" + courseAtI.nameID
                            + "
" + courseAtI.duration + " minutes
" + courseAtI.bldg + " "
                            + courseAtI.room + "	\n"
                            break;
                    }

                }
            }
            else {
                tableString += "	\n";
            }
        }
    }
    tableString += "
";
    return tableString;
}

/**
 * This will find the div with an ID of "table-space" and then insert the innerHTML that createTableString() made.
 * Will also display the tableString on the console log
 *
 */
function createTable(tableString) {
    var tableSpace = document.getElementById("table-space");

    tableSpace.innerHTML = tableString;
    console.log(tableString);
}<|endoftext|>


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

var ZIP = function(aData) {
	this.clean();
	if (isDef(aData)) load(aData);
}

ZIP.prototype.clean = function() {
	this.__zipData = new java.util.concurrent.ConcurrentHashMap();
	this.__zipEntries = new java.util.concurrent.ConcurrentHashMap();
}

ZIP.prototype.load = function(aData) {
	this.clean();

	var bais = new java.io.ByteArrayInputStream(aData);
	var zis = new java.util.zip.ZipInputStream(bais);
	var ze;

	while((ze = zis.getNextEntry()) != null) {
		this.__zipEntries.put(ze.getName(), ze);
		this.__zipData.put(ze.getName(), org.apache.commons.io.IOUtils.toByteArray(zis));
	}

	return this;
}

ZIP.prototype.close = function() {
	this.clean();
	if (isDef(this.__zipFile)) this.__zipFile.close();
}

ZIP.prototype.getFile = function(aName) {
	if (this.__zipData.containsKey(aName)) {
		return this.__zipData.get(aName);
	} else {
		return org.apache.commons.io.IOUtils.toByteArray(this.__zipFile.getInputStream(this.__zipEntries.get(aName)));
	}
}

ZIP.prototype.putFile = function(aName, aData) {
	var bytes;

	if (aData instanceof Java.type("byte[]")) {
		bytes = aData;
	} else {
		bytes = new java.lang.String(String(aData)).getBytes();
	}

	var e = new java.util.zip.ZipEntry(aName);
	this.__zipEntries.put(aName, e);
	this.__zipData.put(aName, bytes);
}

ZIP.prototype.remove = function(aName) {
	this.__zipEntries.remove(aName);
	this.__zipData.remove(aName);

	return this;
}

ZIP.prototype.streamGetFile = function(aFilePath, aName) {
	var ne;
	var zis = new java.util.zip.ZipInputStream(new java.io.FileInputStream(aFilePath));

	try {
		do {
			ne = zis.getNextEntry();
			if (ne.getName().equals(aName)) {
				var zipFile = new java.util.zip.ZipFile(aFilePath);

				try {
					return org.apache.commons.io.IOUtils.toByteArray(zipFile.getInputStream(ne));
				} catch(e) {
					throw e;
				} finally {
					zipFile.close();
				}
			}
		} while(ne != null);
	} catch(e) {
		throw e;
	} finally {
		zis.close();
	}

	return null;
}

ZIP.prototype.streamGetFileStream = function(aFilePath, aName) {
	var ne;
	var zis = new java.util.zip.ZipInputStream(new java.io.FileInputStream(aFilePath));

	try {
		do {
			ne = zis.getNextEntry();
			if (ne.getName().equals(aName)) {
				var zipFile = new java.util.zip.ZipFile(aFilePath);
				try {
					return zipFile.getInputStream(ne);
				} catch(e) {
					throw e;
				}
			}
		} while(ne != null);
	} catch(e) {
		throw e;
	} finally {
		zis.close();
	}

	return null;
}

ZIP.prototype.streamPutFile = function(aFilePath, aName, aData) {
	var path = java.nio.file.Paths.get(aFilePath);
	var uri = java.net.URI.create("jar:" + path.toUri());
	var env = new java.util.HashMap();

	env.put("create", "true");

	try {
		var fs = java.nio.file.FileSystems.newFileSystem(uri, env);
		var nf = fs.getPath(aName, [ "" ]);

		try {
			if (nf.getParent() != null && java.nio.file.Files.notExists(nf.getParent())) {
				java.nio.file.Files.createDirectories(nf.getParent());
			}

			if (!java.nio.file.Files.isDirectory(nf)) {
				java.nio.file.Files.write(nf, aData, [
					java.nio.file.StandardOpenOption.CREATE,
					java.nio.file.StandardOpenOption.TRUNCATE_EXISTING,
					java.nio.file.StandardOpenOption.WRITE
				]);
			} else {
				if (java.nio.file.Files.notExists(nf))
					java.nio.file.Files.createDirectory(nf);
			}

			fs.close();
		} catch(e) {
			if (!(e instanceof java.nio.file.NoSuchFileException)) throw e;
		}
	} catch(e) {
		throw e;
	}
}

ZIP.prototype.load = function(aData) {
	this.clean();

	var bais = new java.io.ByteArrayInputStream(aData);
	var zis = new java.util.zip.ZipInputStream(bais);
	var ze;

	while((ze = zis.getNextEntry()) != null) {
		this.__zipEntries.put(ze.getName(), ze);
		this.__zipData.put(ze.getName(), org.apache.commons.io.IOUtils.toByteArray(zis));
	}

	return this;
}

ZIP.prototype.loadFile = function(aFilename) {
	this.clean();

	this.__zipFile = new java.util.zip.ZipFile(aFilename);
	var ze;
	var e = this.__zipFile.entries();

	while(e.hasMoreElements()) {
		ze = e.nextElement();
		this.__zipEntries.put(ze.getName(), ze);
	}

	return this;
}

ZIP.prototype.list = function(aFilePath) {
	var names = {};
	var zes = new java.util.HashMap();

	if (isDef(aFilePath)) {
		var _zis = new java.util.zip.ZipInputStream(new java.io.FileInputStream(String(aFilePath)));
		var _ze;
		do {
			_ze = _zis.getNextEntry();
			if (_ze != null) zes.put(_ze.getName(), _ze);
		} while(_ze != null);
	} else {
		zes = this.__zipEntries;
	}

	var entries = Java.from(zes.keySet());
	for(var ze in entries) {
		names[zes.get(entries[ze]).getName()] = {
		   "name": zes.get(entries[ze]).getName(),
		   "size": zes.get(entries[ze]).getSize(),
		   "compressedSize": zes.get(entries[ze]).getCompressedSize(),
		   "comment": zes.get(entries[ze]).getComment(),
		   "crc": zes.get(entries[ze]).getCrc(),
		   "time": zes.get(entries[ze]).getTime()
		};
	}

	return names;
}

ZIP.prototype.generate = function(options, dontReload) {
	var baos = java.io.ByteArrayOutputStream();
	var zos = java.util.zip.ZipOutputStream(baos);

	if (isDef(options)) {
		if (isDef(options.compressionLevel))
			zos.setLevel(options.compressionLevel);
	}

	var entries = Java.from(this.__zipEntries.keySet());
	for(var ze in entries) {
		var newZe = new java.util.zip.ZipEntry(this.__zipEntries.get(entries[ze]).getName());
		zos.putNextEntry(newZe);
		if (this.__zipData.containsKey(newZe.getName()))
			org.apache.commons.io.IOUtils.write(this.__zipData.get(this.__zipEntries.get(ze).getName()), zos);
		else
			if (!newZe.isDirectory())
				org.apache.commons.io.IOUtils.copy(this.__zipFile.getInputStream(newZe), zos);

		zos.closeEntry();
	}

	zos.flush();
	zos.finish();
	zos.close();
	baos.flush();
	baos.close();

	if (!dontReload) this.load(baos.toByteArray());

	return baos.toByteArray();
}<commit_msg>Updated comments of js/ZIP<commit_after>/*
 *  Copyright 2017 Nuno Aguiar <nuno@aguiar.name>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * <odoc>
 * <key>ZIP.ZIP(anArrayOfBytes) : ZIP</key>
 * Creates a ZIP object instance. If anArrayOfBytes is provided it will read it as a ZIP compressed contents into
 * the ZIP object.
 * </odoc>
 */
var ZIP = function(aData) {
	this.clean();
	if (isDef(aData)) load(aData);
}

/**
 * <odoc>
 * <key>ZIP.clean()</key>
 * Will clean all internal data regarding any previously ZIP contents handled by this object.
 * </odoc>
 */
ZIP.prototype.clean = function() {
	this.__zipData = new java.util.concurrent.ConcurrentHashMap();
	this.__zipEntries = new java.util.concurrent.ConcurrentHashMap();
}

/**
 * <odoc>
 * <key>ZIP.load(anArrayOfBytes)</key>
 * Loads anArrayOfBytes ZIP contents into the internal object structures.
 * </odoc>
 */
ZIP.prototype.load = function(aData) {
	this.clean();

	var bais = new java.io.ByteArrayInputStream(aData);
	var zis = new java.util.zip.ZipInputStream(bais);
	var ze;

	while((ze = zis.getNextEntry()) != null) {
		this.__zipEntries.put(ze.getName(), ze);
		this.__zipData.put(ze.getName(), org.apache.commons.io.IOUtils.toByteArray(zis));
	}

	return this;
}

/**
 * <odoc>
 * <key>ZIP.close()</key>
 * Will close the ZIP file associated with this object.
 * </odoc>
 */
ZIP.prototype.close = function() {
	this.clean();
	if (isDef(this.__zipFile)) this.__zipFile.close();
}

/**
 * <odoc>
 * <key>ZIP.getFile(aFilename) : anArrayOfBytes</key>
 * Will uncompress the corresponding aFilename from the ZIP contents into an arrays of bytes.
 * </odoc>
 */
ZIP.prototype.getFile = function(aName) {
	if (this.__zipData.containsKey(aName)) {
		return this.__zipData.get(aName);
	} else {
		return org.apache.commons.io.IOUtils.toByteArray(this.__zipFile.getInputStream(this.__zipEntries.get(aName)));
	}
}

/**
 * <odoc>
 * <key>ZIP.putFile(aFilename, anArrayOfBytes)</key>
 * Will add anArrayOfBytes to the ZIP contents as aFilename.
 * </odoc>
 */
ZIP.prototype.putFile = function(aName, aData) {
	var bytes;

	if (aData instanceof Java.type("byte[]")) {
		bytes = aData;
	} else {
		bytes = new java.lang.String(String(aData)).getBytes();
	}

	var e = new java.util.zip.ZipEntry(aName);
	this.__zipEntries.put(aName, e);
	this.__zipData.put(aName, bytes);
}

/**
 * <odoc>
 * <key>ZIP.remove(aFilename)</key>
 * Will remove aFilename from the ZIP contents.
 * </odoc>
 */
ZIP.prototype.remove = function(aName) {
	this.__zipEntries.remove(aName);
	this.__zipData.remove(aName);

	return this;
}

/**
 * <odoc>
 * <key>ZIP.streamGetFile(aFilePath, aName) : anArrayOfBytes</key>
 * Retrieves aName file from aFilePath zip file without loading the zip file contents into memory returning the
 * file contents as an array of bytes.
 * </odoc>
 */
ZIP.prototype.streamGetFile = function(aFilePath, aName) {
	var ne;
	var zis = new java.util.zip.ZipInputStream(new java.io.FileInputStream(aFilePath));

	try {
		do {
			ne = zis.getNextEntry();
			if (ne.getName().equals(aName)) {
				var zipFile = new java.util.zip.ZipFile(aFilePath);

				try {
					return org.apache.commons.io.IOUtils.toByteArray(zipFile.getInputStream(ne));
				} catch(e) {
					throw e;
				} finally {
					zipFile.close();
				}
			}
		} while(ne != null);
	} catch(e) {
		throw e;
	} finally {
		zis.close();
	}

	return null;
}

/**
 * <odoc>
 * <key>ZIP.streamGetFileStream(aFilePath, aName) : JavaInputStream</key>
 * Retrieves aName file from aFilePath zip file without loading the zip file contents into memory returning a
 * Java InputStream.
 * </odoc>
 */
ZIP.prototype.streamGetFileStream = function(aFilePath, aName) {
	var ne;
	var zis = new java.util.zip.ZipInputStream(new java.io.FileInputStream(aFilePath));

	try {
		do {
			ne = zis.getNextEntry();
			if (ne.getName().equals(aName)) {
				var zipFile = new java.util.zip.ZipFile(aFilePath);
				try {
					return zipFile.getInputStream(ne);
				} catch(e) {
					throw e;
				}
			}
		} while(ne != null);
	} catch(e) {
		throw e;
	} finally {
		zis.close();
	}

	return null;
}

/**
 * <odoc>
 * <key>ZIP.streamPutFile(aFilePath, aName, anArrayOfBytes)</key>
 * Sets a aName file on the aFilePath ZIP provided with the anArrayOfBytes provided. All missing directories
 * will be created.
 * </odoc>
 */
ZIP.prototype.streamPutFile = function(aFilePath, aName, aData) {
	var path = java.nio.file.Paths.get(aFilePath);
	var uri = java.net.URI.create("jar:" + path.toUri());
	var env = new java.util.HashMap();

	env.put("create", "true");

	try {
		var fs = java.nio.file.FileSystems.newFileSystem(uri, env);
		var nf = fs.getPath(aName, [ "" ]);

		try {
			if (nf.getParent() != null && java.nio.file.Files.notExists(nf.getParent())) {
				java.nio.file.Files.createDirectories(nf.getParent());
			}

			if (!java.nio.file.Files.isDirectory(nf)) {
				java.nio.file.Files.write(nf, aData, [
					java.nio.file.StandardOpenOption.CREATE,
					java.nio.file.StandardOpenOption.TRUNCATE_EXISTING,
					java.nio.file.StandardOpenOption.WRITE
				]);
			} else {
				if (java.nio.file.Files.notExists(nf))
					java.nio.file.Files.createDirectory(nf);
			}

			fs.close();
		} catch(e) {
			if (!(e instanceof java.nio.file.NoSuchFileException)) throw e;
		}
	} catch(e) {
		throw e;
	}
}

/**
 * <odoc>
 * <key>ZIP.load(anArrayOfBytes)</key>
 * Loads anArrayOfBytes ZIP contents into the internal object structures.
 * </odoc>
 */
ZIP.prototype.load = function(aData) {
	this.clean();

	var bais = new java.io.ByteArrayInputStream(aData);
	var zis = new java.util.zip.ZipInputStream(bais);
	var ze;

	while((ze = zis.getNextEntry()) != null) {
		this.__zipEntries.put(ze.getName(), ze);
		this.__zipData.put(ze.getName(), org.apache.commons.io.IOUtils.toByteArray(zis));
	}

	return this;
}

/**
 * <odoc>
 * <key>ZIP.loadFile(aFilename)</key>
 * Will load a ZIP file aFilename into the ZIP object internal structure.
 * </odoc>
 */
ZIP.prototype.loadFile = function(aFilename) {
	this.clean();

	this.__zipFile = new java.util.zip.ZipFile(aFilename);
	var ze;
	var e = this.__zipFile.entries();

	while(e.hasMoreElements()) {
		ze = e.nextElement();
		this.__zipEntries.put(ze.getName(), ze);
	}

	return this;
}

/**
 * <odoc>
 * <key>ZIP.list() : Map</key>
 * Will list all files and folders of the loaded ZIP contents into a Map with name, size, compressedSize, comment,
 * crc and time.
 * </odoc>
 */
ZIP.prototype.list = function(aFilePath) {
	var names = {};
	var zes = new java.util.HashMap();

	if (isDef(aFilePath)) {
		var _zis = new java.util.zip.ZipInputStream(new java.io.FileInputStream(String(aFilePath)));
		var _ze;
		do {
			_ze = _zis.getNextEntry();
			if (_ze != null) zes.put(_ze.getName(), _ze);
		} while(_ze != null);
	} else {
		zes = this.__zipEntries;
	}

	var entries = Java.from(zes.keySet());
	for(var ze in entries) {
		names[zes.get(entries[ze]).getName()] = {
		   "name": zes.get(entries[ze]).getName(),
		   "size": zes.get(entries[ze]).getSize(),
		   "compressedSize": zes.get(entries[ze]).getCompressedSize(),
		   "comment": zes.get(entries[ze]).getComment(),
		   "crc": zes.get(entries[ze]).getCrc(),
		   "time": zes.get(entries[ze]).getTime()
		};
	}

	return names;
}

/**
 * <odoc>
 * <key>ZIP.generate(aMapOfOptions, dontReload) : anArrayOfBytes</key>
 * Will generate a ZIP anArrayOfBytes contents (that can then by saved into a file) given the provided options (a map
 * where you can specify the compressionLevel as a number). If dontReload = true then the internal ZIP object contents
 * won't be reloaded after generating. Example:\
 * \
 * plugin("ZIP");\
 * var zip = new ZIP();\
 * var text = new java.lang.String("Some example test to zip into a zip file");\
 * var openaf = io.readFileBytes("c:\\apps\\OpenAF\\openaf.jar");\
 * zip.putFile("text.txt", text.getBytes());\
 * zip.putFile("openaf.jar", openaf);\
 * var newZip = zip.generate({"compressionLevel": 9});\
 * var zip = new ZIP(newZip);\
 * print(beautifier(zip.list()));\
 * \
 * </odoc>
 */
ZIP.prototype.generate = function(options, dontReload) {
	var baos = java.io.ByteArrayOutputStream();
	var zos = java.util.zip.ZipOutputStream(baos);

	if (isDef(options)) {
		if (isDef(options.compressionLevel))
			zos.setLevel(options.compressionLevel);
	}

	var entries = Java.from(this.__zipEntries.keySet());
	for(var ze in entries) {
		var newZe = new java.util.zip.ZipEntry(this.__zipEntries.get(entries[ze]).getName());
		zos.putNextEntry(newZe);
		if (this.__zipData.containsKey(newZe.getName()))
			org.apache.commons.io.IOUtils.write(this.__zipData.get(this.__zipEntries.get(ze).getName()), zos);
		else
			if (!newZe.isDirectory())
				org.apache.commons.io.IOUtils.copy(this.__zipFile.getInputStream(newZe), zos);

		zos.closeEntry();
	}

	zos.flush();
	zos.finish();
	zos.close();
	baos.flush();
	baos.close();

	if (!dontReload) this.load(baos.toByteArray());

	return baos.toByteArray();
}
<|endoftext|>


<commit_before>/*
	@author: guokai
	@email/gtalk: badkaikai@gmail.com
	@blog/website: http://benben.cc
	@license: apache license,version 2.0

	@usage: http://paulguo.github.com/Juicer
	@version: 0.1.1
	@build: 110626120407
*/

(function() {
	this.__cache={};
	this.__re={
		'_for':/{@for\s+([^}]*)}([\s\S]*){@\/for}/igm,
		'_if':/{@if\s+([^}]*)}([\s\S]*){@\/if}/igm,
		'_unit':/\[#(.*?)(\s+condition=["|'](.*?)["|'])?\]/igm,
		'_forstart':/{@for[^}]*?}/igm,
		'_forend':/{@\/for}/igm,
		'_ifstart':/{@if[^}]*?}/igm,
		'_ifend':/{@\/if}/igm,
		'_function':/^function[^{]*?{([\s\S]*)}$/igm
	};

	this.__recursive=function(str,o,c) {
		var p=[],s=str,o=str.match(o)||[],c=str.match(c)||[];

		var _build=function(str,o,i) {
			var s=str.substr(0,str.indexOf(o[i]));
			var e=str.substr(str.indexOf(o[i])+o[i].length);
			return s+_noop(o[i].length)+e;
		};

		var _noop=function(l) {
			var s=[];
			for(var i=0;i<l;i++) s.push('-');
			return s.join('');
		};

		var _judge=function(arr) {
			for(var i=0,c=0,p=0,t=[];i<arr.length;i++) {
				if(!c) p=i;
				if(arr[i]=='o') c++;
				if(arr[i]=='c') c--;
				if(!c && arr[i]) t.push(s.substr(p,i+1-p));
			}
			return t;
		};

		for(var i=0;i<o.length;i++) {
			p[str.indexOf(o[i])]='o';
			str=_build(str,o,i);
		}

		for(var i=0;i<c.length;i++) {
			p[str.indexOf(c[i])+c[i].length-1]='c';
			str=_build(str,c,i);
		}

		return _judge(p);
	};

	this.__replace=function(str,a,b) {
		var s=str.substr(0,str.indexOf(a));
		var e=str.substr(str.indexOf(a)+a.length);
		return s+b+e;
	};

	this.__replaceAll=function(str,start,end,cb) {
		for(var i=0,__f=__recursive(str,start,end);i<__f.length;i++) {
			str=__replace(str,__f[i],cb(__f[i]));
		}
		return str;
	};

	this.__reference=function(str,re) {
		var ret;
		str.replace(re,function() {
			ret=arguments;
			return ret[0];
		});
		return ret;
	};

	this.__evalString=new Function('exp',
		'return exp;'
	);

	this.__compile=function(tpl,option) {
		return new Function('tpl','data','option',__reference(__juicer.toString(),__re._function)[1]);
	};

	this.__render=function(data) {

	};

	var __juicer=function(tpl,data,option) {
		var fn=arguments.callee;
		var html=tpl;
		var opt={cache:false};

		var _for=function(str) {
			var ref=__reference(str,__re._for),chain=ref[1],inner=ref[2];
			if(!data[chain]) return '';
			for(var i=0,t=[];i<data[chain].length;i++) {
				t.push(fn(inner,data[chain][i],opt));
			}
			return t.join('');
		};

		var _if=function(str) {
			var ref=__reference(str,__re._if),condition=ref[1],inner=ref[2];
			if(__evalString(fn(condition,data,opt))) {
				return fn(inner,data,opt);
			}
			return '';
		};

		var _unit=function($a,$1,$2,$3) {
			if(!$3 || __evalString(fn($3,data,opt))) {
				return data && data[$1]?typeof(data[$1])=='object'?true:data[$1]:'';
			}
			return '';
		};

		if(__cache[tpl]) return __cache[tpl];

		html=__replaceAll(html,__re._forstart,__re._forend,_for);
		html=__replaceAll(html,__re._ifstart,__re._ifend,_if);
		html=html.replace(__re._unit,_unit);

		if(!option || option.cache!==false) {
			__cache[tpl]=html;
		}

		return html;
	};

	__juicer.compile=__compile;
	this.juicer=__juicer;
})();
<commit_msg>change to new Function() to run again jsperf.<commit_after>/*
	@author: guokai
	@email/gtalk: badkaikai@gmail.com
	@blog/website: http://benben.cc
	@license: apache license,version 2.0

	@usage: http://paulguo.github.com/Juicer
	@version: 0.1.1
	@build: 110626120407
*/

(function() {
	this.__cache={};
	this.__re={
		'_for':/{@for\s+([^}]*)}([\s\S]*){@\/for}/igm,
		'_if':/{@if\s+([^}]*)}([\s\S]*){@\/if}/igm,
		'_unit':/\[#(.*?)(\s+condition=["|'](.*?)["|'])?\]/igm,
		'_forstart':/{@for[^}]*?}/igm,
		'_forend':/{@\/for}/igm,
		'_ifstart':/{@if[^}]*?}/igm,
		'_ifend':/{@\/if}/igm,
		'_function':/^function[^{]*?{([\s\S]*)}$/igm
	};

	this.__recursive=function(str,o,c) {
		var p=[],s=str,o=str.match(o)||[],c=str.match(c)||[];

		var _build=function(str,o,i) {
			var s=str.substr(0,str.indexOf(o[i]));
			var e=str.substr(str.indexOf(o[i])+o[i].length);
			return s+_noop(o[i].length)+e;
		};

		var _noop=function(l) {
			var s=[];
			for(var i=0;i<l;i++) s.push('-');
			return s.join('');
		};

		var _judge=function(arr) {
			for(var i=0,c=0,p=0,t=[];i<arr.length;i++) {
				if(!c) p=i;
				if(arr[i]=='o') c++;
				if(arr[i]=='c') c--;
				if(!c && arr[i]) t.push(s.substr(p,i+1-p));
			}
			return t;
		};

		for(var i=0;i<o.length;i++) {
			p[str.indexOf(o[i])]='o';
			str=_build(str,o,i);
		}

		for(var i=0;i<c.length;i++) {
			p[str.indexOf(c[i])+c[i].length-1]='c';
			str=_build(str,c,i);
		}

		return _judge(p);
	};

	this.__replace=function(str,a,b) {
		var s=str.substr(0,str.indexOf(a));
		var e=str.substr(str.indexOf(a)+a.length);
		return s+b+e;
	};

	this.__replaceAll=function(str,start,end,cb) {
		for(var i=0,__f=__recursive(str,start,end);i<__f.length;i++) {
			str=__replace(str,__f[i],cb(__f[i]));
		}
		return str;
	};

	this.__reference=function(str,re) {
		var ret;
		str.replace(re,function() {
			ret=arguments;
			return ret[0];
		});
		return ret;
	};

	this.__evalString=new Function('exp',
		'return exp;'
	);

	this.__juicer=function(tpl,data,option) {
		//var fn=arguments.callee;
		var fn=__juicer;
		var html=tpl;
		var opt={cache:false};

		var _for=function(str) {
			var ref=__reference(str,__re._for),chain=ref[1],inner=ref[2];
			if(!data[chain]) return '';
			for(var i=0,t=[];i<data[chain].length;i++) {
				t.push(fn(inner,data[chain][i],opt));
			}
			return t.join('');
		};

		var _if=function(str) {
			var ref=__reference(str,__re._if),condition=ref[1],inner=ref[2];
			if(__evalString(fn(condition,data,opt))) {
				return fn(inner,data,opt);
			}
			return '';
		};

		var _unit=function($a,$1,$2,$3) {
			if(!$3 || __evalString(fn($3,data,opt))) {
				return data && data[$1]?typeof(data[$1])=='object'?true:data[$1]:'';
			}
			return '';
		};

		if(__cache[tpl]) return __cache[tpl];

		html=__replaceAll(html,__re._forstart,__re._forend,_for);
		html=__replaceAll(html,__re._ifstart,__re._ifend,_if);
		html=html.replace(__re._unit,_unit);

		if(!option || option.cache!==false) {
			__cache[tpl]=html;
		}

		return html;
	};

	this.juicer=function(tpl,data) {
		var body=__reference(__juicer.toString(),__re._function)[1];
		return new Function('tpl,data,option',body)(tpl,data);
	};
})();
<|endoftext|>


<commit_before>var battlefield;
var user;

var welcomeText =
"Welcome stranger.\nPlease say me your name: ";

var nameEntered = false;
var enteredText = "";

function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

window.onload = function() {

	battlefield = document.getElementById("input");
	console.log(battlefield);

	battlefield.value += welcomeText;
	moveCaretToEnd(battlefield);

	battlefield.onkeydown = textAreaKeyPress;
}

function textAreaKeyPress(event) {
    var key;
    var keyValue;
    if (event) {
       key = event.keyCode;
       keyValue = String.fromCharCode(key);
    } else {
       key = e.which;
    }

    console.log(keyValue);
    if (key == 13) {
        enterPressed();
	return false;
    } else if (key == 8) {
	backspacePressed();
    } else if (key == 46) {
	deletePressed();
	return false;
    } else {
 	enteredText += keyValue;
    }
    return true;
}

function enterPressed() {
        if (!nameEntered) {
  		user = enteredText.toLowerCase();
		nameEntered = true;
	}

        enteredText = "";

	console.log(user);
	battlefield.value += "\n" + user + "@thegame $ ";
	moveCaretToEnd(battlefield);
}

function backspacePressed() {
	enteredText = enteredText.substring(0, enteredText.length - 1);
}

function deletePressed() {

}
<commit_msg>backspace blocking in js<commit_after>var battlefield;
var user;

var welcomeText =
"Welcome stranger.\nPlease say me your name: ";

var nameEntered = false;
var enteredText = "";

function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

window.onload = function() {

	battlefield = document.getElementById("input");
	console.log(battlefield);

	battlefield.value += welcomeText;
	moveCaretToEnd(battlefield);

	battlefield.onkeydown = textAreaKeyPress;
}

function textAreaKeyPress(event) {
    var key;
    var keyValue;
    if (event) {
       key = event.keyCode;
       keyValue = String.fromCharCode(key);
    } else {
       key = e.which;
    }

    console.log(keyValue);
    if (key == 13) {
        enterPressed();
	return false;
    } else if (key == 8) {
	return backspacePressed();
    } else if (key == 46) {
	deletePressed();
	return false;
    } else {
 	enteredText += keyValue;
    }
    return true;
}

function enterPressed() {
        if (!nameEntered) {
  		user = enteredText.toLowerCase();
		nameEntered = true;
	}

        enteredText = "";

	console.log(user);
	battlefield.value += "\n" + user + "@thegame $ ";
	moveCaretToEnd(battlefield);
}

function backspacePressed() {
	if (enteredText.length > 0) {
		enteredText = enteredText.substring(0, enteredText.length - 1);
		battlefield.value = battlefield.substring(0, enteredText.lenght -1);
	}
	return false;
}

function deletePressed() {

}
<|endoftext|>


<commit_before>// --------------------
// Overlook
// Models initialisation
// --------------------

// modules
var Sequelize = require('sequelize-extra'),
	Promise = require('bluebird-extra'),
	_ = require('overlook-utils');

// libraries
var authentication = require('./authentication');

// exports

exports = module.exports = {
	init: function(dbOptions, modelsPath) {
		// init sequelize
		console.log('DB initialising');

		var options = {
			logging: console.log,
			define: {
				labels: true,
				camelThrough: true
			},
			hierarchy: {
				levelFieldAttributes: {secret: true}
			}
		};

		var sequelize = new Sequelize(dbOptions.database, dbOptions.user, dbOptions.password, options);

		// define models from model definitions files
		console.log('DB models importing from files');

		var defineOptions = {
			fields: {
				createdById: function(modelName) {
				  return {
						reference: 'user',
						asReverse: _.pluralize(modelName) + 'Created',
						allowNull: true
					};
				},
				updatedById: function(modelName) {
					return {
						reference: 'user',
						asReverse: _.pluralize(modelName) + 'Updated',
						allowNull: true
					};
				}
			},
			primaryKeyType: Sequelize.INTEGER.UNSIGNED,
			primaryKeyFirst: true,
			autoAssociate: true,
			associateThrough: true,
			onDelete: 'restrict',
			onUpdate: 'restrict',
			loadOptions: {
				flatten: true,
				flattenPrefix: true,
				flattenCamel: true
			}
		};

		sequelize.defineFromFolder(modelsPath, defineOptions);

		// initialise virtual fields
		sequelize.initVirtualFields();

		console.log('DB initialised');

		// done
		return sequelize;
	},

	stock: function(sequelize) {
		// initialise public and root users
		var models = sequelize.models;

		// define users, roles, permissions
		var users = {
			system: {
				name: 'System',
				email: 'system@system.com',
				isActive: false
			},
			root: {
				name: 'Root',
				email: 'root@root.com',
				isActive: true
			},
			public: {
				name: 'Public',
				email: 'public@public.com',
				isActive: false
			}
		};

		var roles = {
			root: {name: 'Root'},
			admin: {name: 'Admin'},
			user: {name: 'User'},
			public: {name: 'Public'}
		};

		var permissions = {
			root: {name: 'Root'},
			admin: {name: 'Admin'},
			user: {name: 'User'}
		};

		// create users
		var systemId;
		return Promise.try(function() {
			// create system user
			return models.user.findOrCreate({where: {type: 'system'}, defaults: users.system})
			.spread(function(user, created) {
				users.system = user;
				systemId = user.id;

				// record system user as created by itself
				if (created) {
					user.createdById = user.updatedById = systemId;
					return user.save();
				}
			});
		}).then(function() {
			return Promise.all([
				// create all other users
				Promise.forIn(users, function(userParams, userName) {
					if (userName == 'system') return;

					userParams.createdById = userParams.updatedById = systemId;

					return models.user.findOrCreate({where: {type: userName}, defaults: userParams})
					.spread(function(user) {
						users[userName] = user;
					});
				}),

				// create roles
				Promise.forIn(roles, function(roleParams, roleName) {
					roleParams.createdById = roleParams.updatedById = systemId;

					return models.role.findOrCreate({where: {type: roleName}, defaults: roleParams})
					.spread(function(role) {
						roles[roleName] = role;
					});
				}),

				// create permissions
				Promise.forIn(permissions, function(permissionParams, permissionName) {
					permissionParams.createdById = permissionParams.updatedById = systemId;

					return models.permission.findOrCreate({where: {type: permissionName}, defaults: permissionParams})
					.spread(function(permission) {
						permissions[permissionName] = permission;
					});
				})
			]);
		}).then(function() {
			return Promise.all([
				// set password for root user
				(function() {
					if (users.root.passwordHash) return;

					return authentication.makeHashAndKey('password')
					.spread(function(hash, key) {
						users.root.passwordHash = hash;
						users.root.cookieKey = key;
						return users.root.save();
					};
				})(),

				// assign users to roles
				users.root.setRoles([roles.root], {createdById: systemId, updatedById: systemId}),
				users.public.setRoles([roles.public], {createdById: systemId, updatedById: systemId}),

				// assign permissions to roles
				roles.root.addPermissions([permissions.root, permissions.admin, permissions.user], {createdById: users.system.id, updatedById: users.system.id}),
				roles.admin.addPermission(permissions.admin, {createdById: systemId, updatedById: systemId}),
				roles.user.addPermission(permissions.user, {createdById: systemId, updatedById: systemId})
			]);
		}).then(function() {
			// return users, roles, permissions
			return [users, roles, permissions];
		});
	}
};
<commit_msg>Give root user all permissions<commit_after>// --------------------
// Overlook
// Models initialisation
// --------------------

// modules
var Sequelize = require('sequelize-extra'),
	Promise = require('bluebird-extra'),
	_ = require('overlook-utils');

// libraries
var authentication = require('./authentication');

// exports

exports = module.exports = {
	init: function(dbOptions, modelsPath) {
		// init sequelize
		console.log('DB initialising');

		var options = {
			logging: console.log,
			define: {
				labels: true,
				camelThrough: true
			},
			hierarchy: {
				levelFieldAttributes: {secret: true}
			}
		};

		var sequelize = new Sequelize(dbOptions.database, dbOptions.user, dbOptions.password, options);

		// define models from model definitions files
		console.log('DB models importing from files');

		var defineOptions = {
			fields: {
				createdById: function(modelName) {
				  return {
						reference: 'user',
						asReverse: _.pluralize(modelName) + 'Created',
						allowNull: true
					};
				},
				updatedById: function(modelName) {
					return {
						reference: 'user',
						asReverse: _.pluralize(modelName) + 'Updated',
						allowNull: true
					};
				}
			},
			primaryKeyType: Sequelize.INTEGER.UNSIGNED,
			primaryKeyFirst: true,
			autoAssociate: true,
			associateThrough: true,
			onDelete: 'restrict',
			onUpdate: 'restrict',
			loadOptions: {
				flatten: true,
				flattenPrefix: true,
				flattenCamel: true
			}
		};

		sequelize.defineFromFolder(modelsPath, defineOptions);

		// initialise virtual fields
		sequelize.initVirtualFields();

		console.log('DB initialised');

		// done
		return sequelize;
	},

	stock: function(sequelize) {
		// initialise public and root users
		var models = sequelize.models;

		// define users, roles, permissions
		var users = {
			system: {
				name: 'System',
				email: 'system@system.com',
				isActive: false
			},
			root: {
				name: 'Root',
				email: 'root@root.com',
				isActive: true
			},
			public: {
				name: 'Public',
				email: 'public@public.com',
				isActive: false
			}
		};

		var roles = {
			root: {name: 'Root'},
			admin: {name: 'Admin'},
			user: {name: 'User'},
			public: {name: 'Public'}
		};

		var permissions = {
			root: {name: 'Root'},
			admin: {name: 'Admin'},
			user: {name: 'User'}
		};

		// create users
		var systemId;
		return Promise.try(function() {
			// create system user
			return models.user.findOrCreate({where: {type: 'system'}, defaults: users.system})
			.spread(function(user, created) {
				users.system = user;
				systemId = user.id;

				// record system user as created by itself
				if (created) {
					user.createdById = user.updatedById = systemId;
					return user.save();
				}
			});
		}).then(function() {
			return Promise.all([
				// create all other users
				Promise.forIn(users, function(userParams, userName) {
					if (userName == 'system') return;

					userParams.createdById = userParams.updatedById = systemId;

					return models.user.findOrCreate({where: {type: userName}, defaults: userParams})
					.spread(function(user) {
						users[userName] = user;
					});
				}),

				// create roles
				Promise.forIn(roles, function(roleParams, roleName) {
					roleParams.createdById = roleParams.updatedById = systemId;

					return models.role.findOrCreate({where: {type: roleName}, defaults: roleParams})
					.spread(function(role) {
						roles[roleName] = role;
					});
				}),

				// create permissions
				Promise.forIn(permissions, function(permissionParams, permissionName) {
					permissionParams.createdById = permissionParams.updatedById = systemId;

					return models.permission.findOrCreate({where: {type: permissionName}, defaults: permissionParams})
					.spread(function(permission) {
						permissions[permissionName] = permission;
					});
				})
			]);
		}).then(function() {
			return Promise.all([
				// set password for root user
				(function() {
					if (users.root.passwordHash) return;

					return authentication.makeHashAndKey('password')
					.spread(function(hash, key) {
						users.root.passwordHash = hash;
						users.root.cookieKey = key;
						return users.root.save();
					};
				})(),

				// assign users to roles
				users.root.setRoles([roles.root], {createdById: systemId, updatedById: systemId}),
				users.public.setRoles([roles.public], {createdById: systemId, updatedById: systemId}),

				// assign all permissions to root role
				models.permission.findAll()
				.eachParallel(function(permissions) {
					return roles.root.addPermission(permission, {createdById: systemId, updatedById: systemId});
				}),

				// assign permissions to other roles
				roles.admin.addPermission(permissions.admin, {createdById: systemId, updatedById: systemId}),
				roles.user.addPermission(permissions.user, {createdById: systemId, updatedById: systemId})
			]);
		}).then(function() {
			// return users, roles, permissions
			return [users, roles, permissions];
		});
	}
};
<|endoftext|>