<commit_before>// Time-stamp: "2018-04-28 10:58:08 phil"
// Section 0x is for common (global) settings (?)

/*
 * When debugging your rc file remember you can use the dumpln function to print
   arbitrary strings. Also remember that if you execute conkeror from a command
   line, it will show you any syntax or other errors in your rc file.
 */

dumpln("00common");

// Add .conkerorrc/modules/ to load_path before anything else
var ph_modules_directory=get_home_directory().clone();
ph_modules_directory.appendRelativePath(".conkerorrc");
ph_modules_directory.appendRelativePath("modules");
// "unshift" means "push" wtf
load_paths.unshift(make_uri(ph_modules_directory).spec);

//
// Utilities
//

// function shell_command_output (command) {
//     var error_text = "";
//     var output_text = "";
//     var exit_status = shell_command(
//         command,
//         $fds = [
//             {
//                 output:
//                 async_binary_string_writer("")
//             },
//             {
//                 input:
//                 async_binary_reader(
//                     function (s) {
//                         output_text += s || "";
//                     }
//                 )
//             },
//             {
//                 input:
//                 async_binary_reader(
//                     function (s) {
//                         error_text += s || "";
//                     }
//                 )
//             }
//         ]
//     );
//     if (exit_status != 0 ) {
//         throw new Error("exit_status: " + exit_status + ", error_text: " +
//                         error_text);
//     }
//     return output_text.trim();
// }

function wordwrap(str, int_width, str_break, cut) {
  //  discuss at: http://phpjs.org/functions/wordwrap/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Nick Callen
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Sakimori
  //  revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // bugfixed by: Michael Grier
  // bugfixed by: Feras ALHAEK
  //   example 1: wordwrap('Kevin van Zonneveld', 6, '|', true);
  //   returns 1: 'Kevin |van |Zonnev|eld'
  //   example 2: wordwrap('The quick brown fox jumped over the lazy dog.', 20, '
\n');
  //   returns 2: 'The quick brown fox
\njumped over the lazy
\n dog.'
  //   example 3: wordwrap('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.');
  //   returns 3: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod \ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \nveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \ncommodo consequat.'

  var m = ((arguments.length >= 2) ? arguments[1] : 75);
  var b = ((arguments.length >= 3) ? arguments[2] : '\n');
  var c = ((arguments.length >= 4) ? arguments[3] : false);

  var i, j, l, s, r;

  str += '';

  if (m < 1) {
    return str;
  }

  for (i = -1, l = (r = str.split(/\r\n|\n|\r/))
    .length; ++i < l; r[i] += s) {
    for (s = r[i], r[i] = ''; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j))
        .length ? b : '')) {
      j = c == 2 || (j = s.slice(0, m + 1)
        .match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(
          m)
        .match(/^\S*/))[0].length;
    }
  }

  return r.join('\n');
}

function ph_where_editors_executable (executable) {
    const path_to_executable = get_home_directory().clone();
    path_to_executable.appendRelativePath("editors");
    path_to_executable.appendRelativePath(executable);
    return path_to_executable.path;
}

function ph_shell_escape (text) {
    return new String(text).
        replace(/'/g, "′"). // PRIME ′. Not RIGHT SINGLE QUOTATION MARK ’.
        replace(/!/g, "¡"). // INVERTED EXCLAMATION MARK
        replace(/\*/g, "⋆"). // STAR OPERATOR ⋆. WHITE SMALL STAR ⭒ or
        // BLACK SMALL STAR ⭑ or SMALL ASTERISK ﹡ or ASTERISK OPERATOR ∗.
        replace(/\(/g, "﹙"). // SMALL LEFT PARENTHESIS ﹙
        replace(/\)/g, "﹚"); // SMALL RIGHT PARENTHESIS ﹚
}

// FIXME See:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
function ph_shell_escaper(matched_text, offset, whole) {
    var m;

    if (matched_text == "\'") {
        return "’";
    } else if (matched_text == "'") {
        return "’";
    } else if ((m = matched_text.match(/(.)'/))) {
        return m[1] + "’";
    } else {
        return matched_text;
    }
}

// TODO Merge with implementation above
// function ph_shell_escape(string) {
//   return string.replace("\n", " ").replace(/.?'/g, ph_shell_escaper);
// }

// Test:
// ph_shell_escape("http://some.uri.with/pagetitle/containing'character");

function ph_encodeURIComponent (text) {
    return encodeURIComponent(ph_shell_escape(text));
}

/**
 * setenv sets the value of a named environment variable to a given string.
 */
require("env");
let (env = Cc['@mozilla.org/process/environment;1']
         .getService(Ci.nsIEnvironment)) {
    function setenv (variable, value) {
        env.set(variable, value);
    }
}

// Minibuffer message in one line
function ph_safe_message (window, message) {
    (window || get_recent_conkeror_window()).minibuffer.message(message);
}

function ph_X11_activate (window_title_regexp) {
    shell_command_blind(
        "xdotool search --onlyvisible --name '" + window_title_regexp + "'"
            + " windowactivate"
    );
} // TODO Interactive form

function blocking_pause (milliseconds) {
    const dt = new Date();
    while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

// TODO Verify that there isn't a simpler/standard way to do this
function ph_count_conkeror_windows () {
    var window_count = 0;
    const en = window_watcher.getWindowEnumerator();
    while (en.hasMoreElements()) {
        const ignored = en.getNext();
        window_count++;
    }
    return window_count;
}

interactive("load-file",
           "(Re-)load an initialization file",
           function (I) {
               config_dir = get_home_directory().clone();
               config_dir.appendRelativePath(".conkerorrc");
               filename = (yield I.minibuffer.read($prompt = "Load file: ",
                                                   $initial_value = config_dir.path + "/",
                                                   $history = "load_file"));
               I.window.minibuffer.message("Loaded file "+filename);
               load(make_file(filename));
           }
          );

// The default page for new buffers.
homepage = "about:blank";

// default directory for downloads and shell commands.
cwd = get_home_directory().clone();
cwd.append("Desktop");

// Open the download manager buffer in the current frame, or in a new window
// with universal argument.
download_buffer_automatic_open_target = [OPEN_NEW_BUFFER, OPEN_NEW_WINDOW];

// save a keystroke when selecting a dom node by number.
hints_auto_exit_delay = 500;
hints_ambiguous_auto_exit_delay = 500;

// Open each externally-requested URL in a new buffer
url_remoting_fn = load_url_in_new_buffer;

// Scroll each isearch match to the frame's vertical center, not bottom
isearch_scroll_center_vertically = true;

// User prefs
user_pref("browser.download.manager.closeWhenDone", true);
user_pref("extensions.checkCompatibility", false);

// TODO Move to appropriate files
require("gmail");
require("twitter");
require("duckduckgo");
require("facebook");
require("gmane");
require("google-calendar");
require("google-maps");
require("wikipedia");
require("xkcd");
require("youtube-player");
require("youtube");

// Session manager
require("session.js");
session_auto_save_auto_load = true;
session_auto_save_auto_load_fn = session_auto_save_load_window_current;

// Password manager
session_pref("signon.rememberSignons", false);
session_pref("signon.expireMasterPassword", false);
session_pref("signon.SignonFileName", "signons.txt");

Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);

define_key(content_buffer_normal_keymap, "`", "follow-new-buffer-background");

// The javascript code to clear the startup-cache is as follows:

/*
   var obs = Cc["@mozilla.org/observer-service;1"]
       .getService(Ci.nsIObserverService);
   obs.notifyObservers(null, "startupcache-invalidate", null);
*/

// TODO You can put this in a command or a function for easy access.

// Make fnbb an alias for follow-new-buffer-background
interactive("fnbb",
    "Follow a link in a new buffer in the background",
    alternates(follow_new_buffer_background, follow_new_window),
    $browser_object = browser_object_links,
    $prompt = "Follow");
// Bound to ` above

interactive("duplicate-buffer", "Duplicate buffer",
            function (I) {
              browser_object_follow(I.buffer, OPEN_NEW_BUFFER, I.buffer.current_uri.spec);
            });
define_key(content_buffer_normal_keymap, "C-M-n", "duplicate-buffer");

// FIXME WTF is this buffer_list's ordering?
interactive("switch-to-other-buffer",
            "Switch to the previously open buffer",
            function (I) {
                const blist = I.window.buffers.buffer_list;
                if (blist.length > 1) {
                    switch_to_buffer(I.window, blist[1]);
                }
            });
define_key(content_buffer_normal_keymap, "f8", "switch-to-other-buffer");

// I think by the time kill_buffer_hook runs the buffer is gone so I
// patch kill_buffer

define_key(default_global_keymap, "C-T", "restore-killed-buffer-url");

var kill_buffer_original = kill_buffer_original || kill_buffer;

var killed_buffers = [];

kill_buffer = function (buffer, force) {
    if (buffer.display_uri_string) {
        killed_buffers.push({url: buffer.display_uri_string,
                             title: buffer.title,
                             history: buffer.web_navigation.sessionHistory});
    }

    kill_buffer_original(buffer,force);
};

interactive("restore-killed-buffer-url", "Loads url from a previously killed buffer",
            function restore_killed_buffer_url (I) {
                if (killed_buffers.length !== 0) {
                    var killed_buffer = yield I.minibuffer.read(
                        $prompt = "Restore killed buffer url:",
                        $completer = new all_word_completer($completions = killed_buffers,
                                                            $get_string = function (x) x.url,
                                                            $get_description = function (x) x.title),
                        $default_completion = killed_buffers[killed_buffers.length - 1],
                        $auto_complete = "url",
                        $auto_complete_initial = true,
                        $auto_complete_delay = 0,
                        $require_match = true
                    );

                    load_url_in_new_buffer(killed_buffer.url);

                    var buf = I.window.buffers.current;
                    // TODO Decide whether to assign a copy of the history
                    buf.web_navigation.sessionHistory = killed_buffer.history;
                    var original_index = buf.web_navigation.sessionHistory.index;
                    buf.web_navigation.gotoIndex(original_index);

                } else {
                    I.window.minibuffer.message("No killed buffer urls");
                }
            });

// FIXME Add 'provide'
<commit_msg>ph_X11_activate now uses shell_command_with_argument_blind.<commit_after>// Time-stamp: "2019-01-20 12:19:21 phil"
// Section 0x is for common (global) settings (?)

/*
 * When debugging your rc file remember you can use the dumpln function to print
   arbitrary strings. Also remember that if you execute conkeror from a command
   line, it will show you any syntax or other errors in your rc file.
 */

dumpln("00common");

// Add .conkerorrc/modules/ to load_path before anything else
var ph_modules_directory=get_home_directory().clone();
ph_modules_directory.appendRelativePath(".conkerorrc");
ph_modules_directory.appendRelativePath("modules");
// "unshift" means "push" wtf
load_paths.unshift(make_uri(ph_modules_directory).spec);

//
// Utilities
//

// function shell_command_output (command) {
//     var error_text = "";
//     var output_text = "";
//     var exit_status = shell_command(
//         command,
//         $fds = [
//             {
//                 output:
//                 async_binary_string_writer("")
//             },
//             {
//                 input:
//                 async_binary_reader(
//                     function (s) {
//                         output_text += s || "";
//                     }
//                 )
//             },
//             {
//                 input:
//                 async_binary_reader(
//                     function (s) {
//                         error_text += s || "";
//                     }
//                 )
//             }
//         ]
//     );
//     if (exit_status != 0 ) {
//         throw new Error("exit_status: " + exit_status + ", error_text: " +
//                         error_text);
//     }
//     return output_text.trim();
// }

function wordwrap(str, int_width, str_break, cut) {
  //  discuss at: http://phpjs.org/functions/wordwrap/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Nick Callen
  // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // improved by: Sakimori
  //  revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // bugfixed by: Michael Grier
  // bugfixed by: Feras ALHAEK
  //   example 1: wordwrap('Kevin van Zonneveld', 6, '|', true);
  //   returns 1: 'Kevin |van |Zonnev|eld'
  //   example 2: wordwrap('The quick brown fox jumped over the lazy dog.', 20, '
\n');
  //   returns 2: 'The quick brown fox
\njumped over the lazy
\n dog.'
  //   example 3: wordwrap('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.');
  //   returns 3: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod \ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim \nveniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea \ncommodo consequat.'

  var m = ((arguments.length >= 2) ? arguments[1] : 75);
  var b = ((arguments.length >= 3) ? arguments[2] : '\n');
  var c = ((arguments.length >= 4) ? arguments[3] : false);

  var i, j, l, s, r;

  str += '';

  if (m < 1) {
    return str;
  }

  for (i = -1, l = (r = str.split(/\r\n|\n|\r/))
    .length; ++i < l; r[i] += s) {
    for (s = r[i], r[i] = ''; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j))
        .length ? b : '')) {
      j = c == 2 || (j = s.slice(0, m + 1)
        .match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length || c == 1 && m || j.input.length + (j = s.slice(
          m)
        .match(/^\S*/))[0].length;
    }
  }

  return r.join('\n');
}

function ph_where_editors_executable (executable) {
    const path_to_executable = get_home_directory().clone();
    path_to_executable.appendRelativePath("editors");
    path_to_executable.appendRelativePath(executable);
    return path_to_executable.path;
}

function ph_shell_escape (text) {
    return new String(text).
        replace(/'/g, "′"). // PRIME ′. Not RIGHT SINGLE QUOTATION MARK ’.
        replace(/!/g, "¡"). // INVERTED EXCLAMATION MARK
        replace(/\*/g, "⋆"). // STAR OPERATOR ⋆. WHITE SMALL STAR ⭒ or
        // BLACK SMALL STAR ⭑ or SMALL ASTERISK ﹡ or ASTERISK OPERATOR ∗.
        replace(/\(/g, "﹙"). // SMALL LEFT PARENTHESIS ﹙
        replace(/\)/g, "﹚"); // SMALL RIGHT PARENTHESIS ﹚
}

// FIXME See:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
function ph_shell_escaper(matched_text, offset, whole) {
    var m;

    if (matched_text == "\'") {
        return "’";
    } else if (matched_text == "'") {
        return "’";
    } else if ((m = matched_text.match(/(.)'/))) {
        return m[1] + "’";
    } else {
        return matched_text;
    }
}

// TODO Merge with implementation above
// function ph_shell_escape(string) {
//   return string.replace("\n", " ").replace(/.?'/g, ph_shell_escaper);
// }

// Test:
// ph_shell_escape("http://some.uri.with/pagetitle/containing'character");

function ph_encodeURIComponent (text) {
    return encodeURIComponent(ph_shell_escape(text));
}

/**
 * setenv sets the value of a named environment variable to a given string.
 */
require("env");
let (env = Cc['@mozilla.org/process/environment;1']
         .getService(Ci.nsIEnvironment)) {
    function setenv (variable, value) {
        env.set(variable, value);
    }
}

// Minibuffer message in one line
function ph_safe_message (window, message) {
    (window || get_recent_conkeror_window()).minibuffer.message(message);
}

function ph_X11_activate (window_title_regexp) {
    shell_command_with_argument_blind(
        "xdotool search --onlyvisible --name '{}' windowactivate",
        window_title_regexp
    );
} // TODO Interactive form

function blocking_pause (milliseconds) {
    const dt = new Date();
    while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

// TODO Verify that there isn't a simpler/standard way to do this
function ph_count_conkeror_windows () {
    var window_count = 0;
    const en = window_watcher.getWindowEnumerator();
    while (en.hasMoreElements()) {
        const ignored = en.getNext();
        window_count++;
    }
    return window_count;
}

interactive("load-file",
           "(Re-)load an initialization file",
           function (I) {
               config_dir = get_home_directory().clone();
               config_dir.appendRelativePath(".conkerorrc");
               filename = (yield I.minibuffer.read($prompt = "Load file: ",
                                                   $initial_value = `${config_dir.path}/`,
                                                   $history = "load_file"));
               I.window.minibuffer.message(`Loaded file ${filename}`);
               load(make_file(filename));
           }
          );

// The default page for new buffers.
homepage = "about:blank";

// default directory for downloads and shell commands.
cwd = get_home_directory().clone();
cwd.append("Desktop");

// Open the download manager buffer in the current frame, or in a new window
// with universal argument.
download_buffer_automatic_open_target = [OPEN_NEW_BUFFER, OPEN_NEW_WINDOW];

// save a keystroke when selecting a dom node by number.
hints_auto_exit_delay = 500;
hints_ambiguous_auto_exit_delay = 500;

// Open each externally-requested URL in a new buffer
url_remoting_fn = load_url_in_new_buffer;

// Scroll each isearch match to the frame's vertical center, not bottom
isearch_scroll_center_vertically = true;

// User prefs
user_pref("browser.download.manager.closeWhenDone", true);
user_pref("extensions.checkCompatibility", false);

// TODO Move to appropriate files
require("gmail");
require("twitter");
require("duckduckgo");
require("facebook");
require("gmane");
require("google-calendar");
require("google-maps");
require("wikipedia");
require("xkcd");
require("youtube-player");
require("youtube");

// Session manager
require("session.js");
session_auto_save_auto_load = true;
session_auto_save_auto_load_fn = session_auto_save_load_window_current;

// Password manager
session_pref("signon.rememberSignons", false);
session_pref("signon.expireMasterPassword", false);
session_pref("signon.SignonFileName", "signons.txt");

Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);

define_key(content_buffer_normal_keymap, "`", "follow-new-buffer-background");

// The javascript code to clear the startup-cache is as follows:

/*
   var obs = Cc["@mozilla.org/observer-service;1"]
       .getService(Ci.nsIObserverService);
   obs.notifyObservers(null, "startupcache-invalidate", null);
*/

// TODO You can put this in a command or a function for easy access.

// Make fnbb an alias for follow-new-buffer-background
interactive("fnbb",
    "Follow a link in a new buffer in the background",
    alternates(follow_new_buffer_background, follow_new_window),
    $browser_object = browser_object_links,
    $prompt = "Follow");
// Bound to ` above

interactive("duplicate-buffer", "Duplicate buffer",
            function (I) {
              browser_object_follow(I.buffer, OPEN_NEW_BUFFER, I.buffer.current_uri.spec);
            });
define_key(content_buffer_normal_keymap, "C-M-n", "duplicate-buffer");

// FIXME WTF is this buffer_list's ordering?
interactive("switch-to-other-buffer",
            "Switch to the previously open buffer",
            function (I) {
                const blist = I.window.buffers.buffer_list;
                if (blist.length > 1) {
                    switch_to_buffer(I.window, blist[1]);
                }
            });
define_key(content_buffer_normal_keymap, "f8", "switch-to-other-buffer");

// I think by the time kill_buffer_hook runs the buffer is gone so I
// patch kill_buffer

define_key(default_global_keymap, "C-T", "restore-killed-buffer-url");

var kill_buffer_original = kill_buffer_original || kill_buffer;

var killed_buffers = [];

kill_buffer = function (buffer, force) {
    if (buffer.display_uri_string) {
        killed_buffers.push({url: buffer.display_uri_string,
                             title: buffer.title,
                             history: buffer.web_navigation.sessionHistory});
    }

    kill_buffer_original(buffer,force);
};

interactive("restore-killed-buffer-url", "Loads url from a previously killed buffer",
            function restore_killed_buffer_url (I) {
                if (killed_buffers.length !== 0) {
                    var killed_buffer = yield I.minibuffer.read(
                        $prompt = "Restore killed buffer url:",
                        $completer = new all_word_completer($completions = killed_buffers,
                                                            $get_string = function (x) x.url,
                                                            $get_description = function (x) x.title),
                        $default_completion = killed_buffers[killed_buffers.length - 1],
                        $auto_complete = "url",
                        $auto_complete_initial = true,
                        $auto_complete_delay = 0,
                        $require_match = true
                    );

                    load_url_in_new_buffer(killed_buffer.url);

                    var buf = I.window.buffers.current;
                    // TODO Decide whether to assign a copy of the history
                    buf.web_navigation.sessionHistory = killed_buffer.history;
                    var original_index = buf.web_navigation.sessionHistory.index;
                    buf.web_navigation.gotoIndex(original_index);

                } else {
                    I.window.minibuffer.message("No killed buffer urls");
                }
            });

// FIXME Add 'provide'
<|endoftext|>


<commit_before>"use strict";

var util = require('util');
var events = require('events');
var Interface = require('./interface');
var DBusError = require('./error');

var Bus = module.exports = function(_dbus, DBus, busName) {
	var self = this;

	self._dbus = _dbus;
	self.DBus = DBus;
	self.name = busName;
	self.signalHandlers = {};
	self.signalEnable = false;
	self.interfaces = {};

	switch(busName) {
	case 'system':
		self.connection = _dbus.getBus(0);
		break;

	case 'session':
		self.connection = _dbus.getBus(1);
		break;
	}

	self.on('signal', function(uniqueBusName, sender, objectPath, interfaceName, signalName, args) {

		if (objectPath == '/org/freedesktop/DBus/Local' &&
			interfaceName == 'org.freedesktop.DBus.Local' &&
			signalName == 'Disconnected') {

			self.reconnect();

			return;
		}

		var signalHash = objectPath + ':' + interfaceName;

		if (self.signalHandlers[signalHash]) {
			var args = [ signalName ].concat(args);

			var interfaceObj = self.signalHandlers[signalHash];
			interfaceObj.emit.apply(interfaceObj, args);
		}
	});

	// Register signal handler of this connection
	self.DBus.signalHandlers[self.connection.uniqueName] = self;
	self.DBus.enableSignal();
};

util.inherits(Bus, events.EventEmitter);

Object.defineProperty(Bus.prototype, 'connected', {
	get: function() {
		return this.connection !== null;
	}
});

Bus.prototype.disconnect = function(callback) {
	var self = this;

	delete self.DBus.signalHandlers[self.connection.uniqueName];

	self._dbus.releaseBus(self.connection);

	self.connection = null;

	if (callback)
		process.nextTick(callback);
};

Bus.prototype.reconnect = function(callback) {
	var self = this;

	delete self.DBus.signalHandlers[self.connection.uniqueName];

	self._dbus.releaseBus(self.connection);

	switch(self.name) {
	case 'system':
		self.connection = self._dbus.getBus(0);
		break;

	case 'session':
		self.connection = self._dbus.getBus(1);
		break;
	}

	self.DBus.signalHandlers[self.connection.uniqueName] = self;

	// Reregister signal handler
	for (var hash in self.interfaces) {
		var iface = self.interfaces[hash];

		self.registerSignalHandler(iface.serviceName, iface.objectPath, iface.interfaceName, iface);
	}

	if (callback)
		process.nextTick(callback);
};

Bus.prototype.introspect = function(serviceName, objectPath, callback) {
	var self = this;

	if (!self.connected) {
		process.nextTick(function() {
			callback(new Error('Bus is no longer connected'));
		});
		return;
	}

	// Getting scheme of specific object
	self.callMethod(self.connection,
		serviceName,
		objectPath,
		'org.freedesktop.DBus.Introspectable',
		'Introspect',
		'',
		10000,
		[],
		function(err, introspect) {

			var obj = self._parseIntrospectSource(introspect);
			if (!obj) {
				if (callback)
					callback(new Error('No introspectable'));

				return;
			}

			if (callback)
				callback(err, obj);
		});
};

Bus.prototype._parseIntrospectSource = function(source) {
	return this._dbus.parseIntrospectSource.apply(this, [ source ]);
};

Bus.prototype.getInterface = function(serviceName, objectPath, interfaceName, callback) {
	var self = this;

	if (self.interfaces[serviceName + ':' + objectPath + ':' +interfaceName]) {
		if (callback)
			process.nextTick(function() {
				callback(null, self.interfaces[serviceName + ':' + objectPath + ':' +interfaceName]);
			});

		return;
	}

	self.introspect(serviceName, objectPath, function(err, obj) {
		if (err) {
			if (callback)
				callback(err);

			return;
		}

		if (!(interfaceName in obj)) {
			if (callback)
				callback(new Error('No such interface'));

			return;
		}

		// Create a interface object based on introspect
		var iface = new Interface(self, serviceName, objectPath, interfaceName, obj[interfaceName]);
		iface.init(function() {

			self.interfaces[serviceName + ':' + objectPath + ':' +interfaceName] = iface;

			if (callback)
				callback(null, iface);
		});
	});
};

Bus.prototype.registerSignalHandler = function(serviceName, objectPath, interfaceName, interfaceObj, callback) {
	var self = this;

	self.getUniqueServiceName(serviceName, function (err, uniqueName) {
		// Make a hash
		var signalHash = objectPath + ':' + interfaceName;
		self.signalHandlers[signalHash] = interfaceObj;

		// Register interface signal handler
		self.addSignalFilter(serviceName, objectPath, interfaceName, callback);
	});
};

Bus.prototype.setMaxMessageSize = function(size) {
	this._dbus.setMaxMessageSize(this.connection, size || 1024000);
};

Bus.prototype.getUniqueServiceName = function(serviceName, callback) {
	var self = this;

	self.callMethod(self.connection,
		'org.freedesktop.DBus',
		'/',
		'org.freedesktop.DBus',
		'GetNameOwner',
		's',
		-1,
		[serviceName],
		function(err, uniqueName) {
			callback(err, uniqueName);
		});
}

Bus.prototype.addSignalFilter = function(sender, objectPath, interfaceName, callback) {
	var self = this;

	// Initializing signal if it wasn't enabled before
	if (!self.signalEnable) {
		self.signalEnable = true;
		self._dbus.addSignalFilter(self.connection, 'type=\'signal\'');
	}

	self._dbus.addSignalFilter(self.connection, 'type=\'signal\',sender=\'' + sender + '\',interface=\'' + interfaceName + '\',path=\'' + objectPath + '\'');

	process.nextTick(function() {
		if (callback)
			callback();
	});
};

Bus.prototype._sendMessageReply = function(message, value, type) {
	this._dbus.sendMessageReply(message, value, type);
};

Bus.prototype._sendErrorMessageReply = function(message, name, msg) {
	this._dbus.sendErrorMessageReply(message, name, msg);
};

function createError(name, message) {
	return new DBusError(name, message);
}

Bus.prototype.callMethod = function() {
	var args = Array.prototype.slice.call(arguments);
	args.push(createError);
	this._dbus.callMethod.apply(this, args);
};

<commit_msg>Bus.prototype.reconnect to handle null connection<commit_after>"use strict";

var util = require('util');
var events = require('events');
var Interface = require('./interface');
var DBusError = require('./error');

var Bus = module.exports = function(_dbus, DBus, busName) {
	var self = this;

	self._dbus = _dbus;
	self.DBus = DBus;
	self.name = busName;
	self.signalHandlers = {};
	self.signalEnable = false;
	self.interfaces = {};

	switch(busName) {
	case 'system':
		self.connection = _dbus.getBus(0);
		break;

	case 'session':
		self.connection = _dbus.getBus(1);
		break;
	}

	self.on('signal', function(uniqueBusName, sender, objectPath, interfaceName, signalName, args) {

		if (objectPath == '/org/freedesktop/DBus/Local' &&
			interfaceName == 'org.freedesktop.DBus.Local' &&
			signalName == 'Disconnected') {

			self.reconnect();

			return;
		}

		var signalHash = objectPath + ':' + interfaceName;

		if (self.signalHandlers[signalHash]) {
			var args = [ signalName ].concat(args);

			var interfaceObj = self.signalHandlers[signalHash];
			interfaceObj.emit.apply(interfaceObj, args);
		}
	});

	// Register signal handler of this connection
	self.DBus.signalHandlers[self.connection.uniqueName] = self;
	self.DBus.enableSignal();
};

util.inherits(Bus, events.EventEmitter);

Object.defineProperty(Bus.prototype, 'connected', {
	get: function() {
		return this.connection !== null;
	}
});

Bus.prototype.disconnect = function(callback) {
	var self = this;

	delete self.DBus.signalHandlers[self.connection.uniqueName];

	self._dbus.releaseBus(self.connection);

	self.connection = null;

	if (callback)
		process.nextTick(callback);
};

Bus.prototype.reconnect = function(callback) {
	var self = this;

	if(self.connection) {
		delete self.DBus.signalHandlers[self.connection.uniqueName];

		self._dbus.releaseBus(self.connection);
	}

	switch(self.name) {
	case 'system':
		self.connection = self._dbus.getBus(0);
		break;

	case 'session':
		self.connection = self._dbus.getBus(1);
		break;
	}

	self.DBus.signalHandlers[self.connection.uniqueName] = self;

	// Reregister signal handler
	for (var hash in self.interfaces) {
		var iface = self.interfaces[hash];

		self.registerSignalHandler(iface.serviceName, iface.objectPath, iface.interfaceName, iface);
	}

	if (callback)
		process.nextTick(callback);
};

Bus.prototype.introspect = function(serviceName, objectPath, callback) {
	var self = this;

	if (!self.connected) {
		process.nextTick(function() {
			callback(new Error('Bus is no longer connected'));
		});
		return;
	}

	// Getting scheme of specific object
	self.callMethod(self.connection,
		serviceName,
		objectPath,
		'org.freedesktop.DBus.Introspectable',
		'Introspect',
		'',
		10000,
		[],
		function(err, introspect) {

			var obj = self._parseIntrospectSource(introspect);
			if (!obj) {
				if (callback)
					callback(new Error('No introspectable'));

				return;
			}

			if (callback)
				callback(err, obj);
		});
};

Bus.prototype._parseIntrospectSource = function(source) {
	return this._dbus.parseIntrospectSource.apply(this, [ source ]);
};

Bus.prototype.getInterface = function(serviceName, objectPath, interfaceName, callback) {
	var self = this;

	if (self.interfaces[serviceName + ':' + objectPath + ':' +interfaceName]) {
		if (callback)
			process.nextTick(function() {
				callback(null, self.interfaces[serviceName + ':' + objectPath + ':' +interfaceName]);
			});

		return;
	}

	self.introspect(serviceName, objectPath, function(err, obj) {
		if (err) {
			if (callback)
				callback(err);

			return;
		}

		if (!(interfaceName in obj)) {
			if (callback)
				callback(new Error('No such interface'));

			return;
		}

		// Create a interface object based on introspect
		var iface = new Interface(self, serviceName, objectPath, interfaceName, obj[interfaceName]);
		iface.init(function() {

			self.interfaces[serviceName + ':' + objectPath + ':' +interfaceName] = iface;

			if (callback)
				callback(null, iface);
		});
	});
};

Bus.prototype.registerSignalHandler = function(serviceName, objectPath, interfaceName, interfaceObj, callback) {
	var self = this;

	self.getUniqueServiceName(serviceName, function (err, uniqueName) {
		// Make a hash
		var signalHash = objectPath + ':' + interfaceName;
		self.signalHandlers[signalHash] = interfaceObj;

		// Register interface signal handler
		self.addSignalFilter(serviceName, objectPath, interfaceName, callback);
	});
};

Bus.prototype.setMaxMessageSize = function(size) {
	this._dbus.setMaxMessageSize(this.connection, size || 1024000);
};

Bus.prototype.getUniqueServiceName = function(serviceName, callback) {
	var self = this;

	self.callMethod(self.connection,
		'org.freedesktop.DBus',
		'/',
		'org.freedesktop.DBus',
		'GetNameOwner',
		's',
		-1,
		[serviceName],
		function(err, uniqueName) {
			callback(err, uniqueName);
		});
}

Bus.prototype.addSignalFilter = function(sender, objectPath, interfaceName, callback) {
	var self = this;

	// Initializing signal if it wasn't enabled before
	if (!self.signalEnable) {
		self.signalEnable = true;
		self._dbus.addSignalFilter(self.connection, 'type=\'signal\'');
	}

	self._dbus.addSignalFilter(self.connection, 'type=\'signal\',sender=\'' + sender + '\',interface=\'' + interfaceName + '\',path=\'' + objectPath + '\'');

	process.nextTick(function() {
		if (callback)
			callback();
	});
};

Bus.prototype._sendMessageReply = function(message, value, type) {
	this._dbus.sendMessageReply(message, value, type);
};

Bus.prototype._sendErrorMessageReply = function(message, name, msg) {
	this._dbus.sendErrorMessageReply(message, name, msg);
};

function createError(name, message) {
	return new DBusError(name, message);
}

Bus.prototype.callMethod = function() {
	var args = Array.prototype.slice.call(arguments);
	args.push(createError);
	this._dbus.callMethod.apply(this, args);
};
<|endoftext|>


<commit_before>var http     = require("http");
var https    = require("https");
var sys      = require("sys");
var path     = require("path");
var fs       = require("fs");
var io       = require("socket.io");
var nstatic  = require("node-static");
var Connection = require("./connection");

var credentials;
if (path.existsSync("keys/privatekey.pem")) {
  var privateKey  = fs.readFileSync("keys/privatekey.pem", "utf8");
  var certificate = fs.readFileSync("keys/certificate.pem", "utf8");
  credentials = {key: privateKey, cert: certificate};
}

Server = module.exports = require("./klass").create();

var fileServer = new nstatic.Server(path.normalize(__dirname + "../../../public"));

Server.include({
  init: function(){
    var connectionListener = function(request, response){
      request.addListener("end", function() {

        fileServer.serve(request, response, function (err, res) {
          if (err) { // An error as occured
            sys.error("> Error serving " + request.url + " - " + err.message);
            response.writeHead(err.status || 500, err.headers);
            response.end();
          } else { // The file was served successfully
            sys.log("Serving " + request.url + " - " + res.message);
          }
        });

      });
    }

    if (credentials) {
      this.httpServer = https.createServer(credentials, connectionListener);
    } else {
      this.httpServer = http.createServer(connectionListener);
    }

    this.socket = io.listen(this.httpServer);
    this.socket.on("connection", function(stream){ Connection.inst(stream) });
  },

  listen: function(port){
    port = parseInt(port || process.env.PORT || 8080);
    this.httpServer.listen(port);
  }
});<commit_msg>module name has chaned<commit_after>var http     = require("http");
var https    = require("https");
var sys      = require("sys");
var path     = require("path");
var fs       = require("fs");
var io       = require("socket.io");
var nstatic  = require("node-static-maccman");
var Connection = require("./connection");

var credentials;
if (path.existsSync("keys/privatekey.pem")) {
  var privateKey  = fs.readFileSync("keys/privatekey.pem", "utf8");
  var certificate = fs.readFileSync("keys/certificate.pem", "utf8");
  credentials = {key: privateKey, cert: certificate};
}

Server = module.exports = require("./klass").create();

var fileServer = new nstatic.Server(path.normalize(__dirname + "../../../public"));

Server.include({
  init: function(){
    var connectionListener = function(request, response){
      request.addListener("end", function() {

        fileServer.serve(request, response, function (err, res) {
          if (err) { // An error as occured
            sys.error("> Error serving " + request.url + " - " + err.message);
            response.writeHead(err.status || 500, err.headers);
            response.end();
          } else { // The file was served successfully
            sys.log("Serving " + request.url + " - " + res.message);
          }
        });

      });
    }

    if (credentials) {
      this.httpServer = https.createServer(credentials, connectionListener);
    } else {
      this.httpServer = http.createServer(connectionListener);
    }

    this.socket = io.listen(this.httpServer);
    this.socket.on("connection", function(stream){ Connection.inst(stream) });
  },

  listen: function(port){
    port = parseInt(port || process.env.PORT || 8080);
    this.httpServer.listen(port);
  }
});<|endoftext|>


<commit_before>/*Hangman script, blah blah blah. Hope you guys like it. =)
~ SilverTactic (Siiilver)*/

var hangman = exports.hangman = {};

function hasGuessedWord(user, object) {
	for (var i in object)
		if (object[i] === Users.get(user).userid || !Users.get(user).getAlts().map(toId).indexOf(object[i]) > -1) return true;
	return false;
}

var Hangman = (function () {
	function Hangman(room, starter, word, hint) {
		this.answer = toId(word);
		this.hint = hint;
		this.room = room;
		this.starter = Users.get(starter).name;
		this.guessed = {};
		this.chances = 6;
		this.letters = {};
		this.correctguesses = 0;

		word = toId(word);
		var blanks = '';
		for (var i = 0; i < word.length; i++) {
			if (!this.letters[word[i]]) this.letters[word[i]] = {};
			if (!this.letters[word[i]].position) this.letters[word[i]].position = [];
			this.letters[word[i]].position.push(i + 1);
			if (word[i] === 'a' || word[i] === 'e' || word[i] === 'i' || word[i] === 'o' || word[i] === 'u') blanks += ' _ ';
			else blanks += ' _ ';
		}
		Rooms.rooms[room.id].add('|html|
' + Users.get(starter).name + ' has started a game of hangman!

' +
			'The word has ' + word.length + ' letters.

' + blanks + '

' +
			'Hint: ' + this.hint);
	}

	Hangman.prototype.guessword = function (user, word) {
		user = Users.get(user);
		if (this.guessed[word]) return user.sendTo(this.room, 'That word has already been guessed!');
		if (hasGuessedWord(user, this.guessed)) return user.sendTo(this.room, 'You can only guess the entire word once per game.');
		if (this.answer !== word) {
			this.chances--;
			if (this.chances === 0) {
				this.room.add('|html|' + user.name + ' guessed the word \'' + word + '\' but was not the correct answer. The man has been hanged for failing to guess the word.');
				delete hangman[this.room.id];
			} else {
				this.room.add('|html|' + user.name + ' guessed the word \'' + word + '\' but was not the correct answer...');
				this.guessed[word] = toId(user);
			}
		} else {
			this.room.add('|html|' + user.name + ' guessed the word \'' + word + '\' which is the correct answer! Congratulations!');
			delete hangman[this.room.id];
		}
	};

	Hangman.prototype.guess = function (user, target) {
		user = Users.get(user);
		if (this.guessed[target]) return user.sendTo(this.room, 'That letter has already been guessed!');
		var count = 0;
		/*for (var i in this.guessed)
			if (this.guessed[i] === user.userid || user.getAlts().indexOf(this.guessed[i]) > -1) count++;
		if (count == 3) return user.sendTo(this.room, 'You may only guess 3 times per game. Better luck next time!');*/
		//The above statement can be re-enabled if you want to limit the number of times a user can guess.

		if (!this.letters[target]) {
			this.chances--;
			if (this.chances == 0) {
				this.room.add('|html|' + user.name + ' guessed the letter \'' + target + '\' but was not in the word. The man has been hanged for failing to guess the word.');
				delete hangman[this.room.id];
			} else {
				this.room.add('|html|' + user.name + ' guessed the letter \'' + target + '\' but was not in the word...');
				this.guessed[target] = user.userid;
			}
		} else {
			this.room.add('|html|' + user.name + ' guessed the letter \'' + target + '\', which was letter ' + this.letters[target].position.join(", ") + ' of the word.');
			this.guessed[target] = user.userid;
			this.correctguesses++;
			if (this.correctguesses === Object.keys(this.letters).length) {
				this.room.add('|html|The word has been found! The answer is \'' + this.answer + '\'. Congratulations!');
				delete hangman[this.room.id];
			}
		}
	};

	Hangman.prototype.details = function () {
			var word = '',
				guessedletters = [];
			for (var i = 0; i < this.answer.length; i++) {
				if (this.guessed[this.answer[i]]) word += ' ' + this.answer[i] + ' ';
				else if (this.answer[i] == 'a' || this.answer[i] == 'e' || this.answer[i] == 'i' || this.answer[i] == 'o' || this.answer[i] == 'u')
					word += ' _ ';
				else word += ' _ ';
			}
			for (var i in this.guessed)
				guessedletters.push(i);

			guessedletters = (guessedletters.length < 1) ? 'None' : guessedletters.join(', ');
			return '
' + word + '
' +
				'Guessed letters: ' + guessedletters + '
' +
				'Chances Left: ' + this.chances + '
' +
				'Hint: ' + this.hint;
		},

		Hangman.prototype.end = function (user) {
			this.room.add('|html|The game of hangman has been ended by ' + Users.get(user).name);
			delete hangman[this.room.id];
		};
	return Hangman;
})();

var commands = {
	'': 'help',
	help: function (target, room, user, connection, cmd) {
		if (!this.canBroadcast()) return;
		this.sendReplyBox(
			'All commands are in the format \'/hangman command\', that is, prefixed with /hangman.
' +
			'Starter/Staff commands-
' +
			'- start or new word, hint - Starts a game of hangman in the room with the specified word as the answer along with a hint. All vowels use a red blank when displayed. (Alternate command - /starthangman) (Requires +, %, @, #)
' +
			'- answer or word - Allows game starter to view the answer.
' +
			'- end or delete - Ends the game of hangman in the room. (Alternate command - /endhangman) (Requires %, @, #)

' +
			'Player commands-
' +
			'- guess letter - Guesses a letter. Non-English characters cannot be guessed. (Alternate command - /guessletter)
' +
			'- guessword word - Guesses the entire word. Can only be used by the user once per game. The answer cannot contain non-English characters. (Alternate command - /guessword)
' +
			'- view or details - Allows you to view the details of the current game. These include the progress, the letters guessed, and the number of tries remaining. (Alternate command - /viewhangman)
'
		);
	},

	'new': 'start',
	start: function (target, room, user, connection, cmd) {
		if (!this.can('broadcast', null, room)) return this.sendReply('You must be ranked + or higher to start a game of hangman.');
		if (hangman[room.id]) return this.sendReply('There is already a game of hangman going on in this room.');
		if (!target) return this.sendReply('|html|/ ' + cmd + ' word, hint - Starts a game of hangman in the room with the specified word as the along with a hint.');
		var targets = target.split(',');
		var word = targets[0];
		var hint = targets[1];
		if (!toId(word)) return this.sendReply("Seriously, don't bother trying to start a game of hangman without a word.");
		if (word.match(/[^a-zA-Z]+/ig)) return this.sendReply('The word can only contain letters. Spaces, special characters, and numbers cannot be used.');
		if (toId(word).length > 15 || toId(word).length < 5) return this.sendReply('The word needs to be 5 to 15 letters long.');
		if (!hint || !hint.trim()) return this.sendReply('You need to give a hint to the answer!');

		hangman[room.id] = new Hangman(room, user.userid, toId(word), hint);
	},

	guess: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		if (Users.get(hangman[room.id].starter).userid === user.userid || Users.get(hangman[room.id].starter).getAlts().map(toId).indexOf(user.userid) > -1) return this.sendReply('You cannot guess if you\'re the one who started the game.');
		target = target.trim();
		if (target.length > 1) return this.sendReply('You can only guess one letter at a time.');
		if (target.match(/[^a-zA-Z]+/g)) return this.sendReply('You may only guess letters. You cannot guess numbers or special characters.');
		target = target.trim().toLowerCase();
		if (!target) return this.sendReply("|html|/hangman guess letter - Guesses a letter in a game of hangman.");
		if (!toId(target) || Number(target)) return this.sendReply("'" + target + "' is not a valid letter (You may only guess english letters).");

		hangman[room.id].guess(user.userid, toId(target));

	},

	guessword: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		if (Users.get(hangman[room.id].starter).userid === user.userid || Users.get(hangman[room.id].starter).getAlts().map(toId).indexOf(user.userid) > -1) return this.sendReply('You cannot guess the word if you\'re the one who started the game.');
		if (target.length < 5 || target.length > 15) return this.sendReply('Words in hangman contain a minimum of 5 letters and a maximum of 15 letters.');
		target = target.trim().toLowerCase();
		if (!target) return this.sendReply("|html|/hangman guessword word - Guesses the word in a game of hangman.");
		if ((toId(target) !== target) || parseInt(target)) return this.sendReply("You cannot include any special characters, spaces, or numbers in your answer.");

		hangman[room.id].guessword(user.userid, toId(target));
	},

	view: 'details',
	data: 'details',
	details: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		if (!this.canBroadcast()) return;
		this.sendReplyBox(hangman[room.id].details());
	},

	word: 'answer',
	answer: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		if (toId(hangman[room.id].starter) !== user.userid) return this.sendReply("Only the starter of the game can view the answer.");
		if (Users.get(hangman[room.id].starter).getAlts().map(toId).indexOf(user.userid) > -1) return this.sendReply("The game of hangman was started by your alt, " + hangman[room.id].starter + ". Use that alt/account to view the answer.");
		return this.sendReply("|html|The answer is '" + hangman[room.id].answer);
	},

	'delete': 'end',
	finish: 'end',
	end: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		hangman[room.id].end(user.name);
	}
};

exports.commands = {
	'hangman': commands,
	starthangman: commands.start,
	guessletter: commands.guess,
	guessword: commands.guessword,
	viewhangman: commands.view,
	endhangman: commands.end
};
<commit_msg>Minor edit, fixed crash.<commit_after>/*Hangman script, blah blah blah. Hope you guys like it. =)
~ SilverTactic (Siiilver)*/

var hangman = exports.hangman = {};

function hasGuessedWord(user, object) {
	for (var i in object)
		if (object[i] === Users.get(user).userid || !Users.get(user).getAlts().map(toId).indexOf(object[i]) > -1) return true;
	return false;
}

var Hangman = (function () {
	function Hangman(room, starter, word, hint) {
		this.answer = toId(word);
		this.hint = hint;
		this.room = room;
		this.starter = Users.get(starter).name;
		this.guessed = {};
		this.chances = 6;
		this.letters = {};
		this.correctguesses = 0;

		word = toId(word);
		var blanks = '';
		for (var i = 0; i < word.length; i++) {
			if (!this.letters[word[i]]) this.letters[word[i]] = {};
			if (!this.letters[word[i]].position) this.letters[word[i]].position = [];
			this.letters[word[i]].position.push(i + 1);
			if (word[i] === 'a' || word[i] === 'e' || word[i] === 'i' || word[i] === 'o' || word[i] === 'u') blanks += ' _ ';
			else blanks += ' _ ';
		}
		Rooms.rooms[room.id].add('|html|
' + Users.get(starter).name + ' has started a game of hangman!

' +
			'The word has ' + word.length + ' letters.

' + blanks + '

' +
			'Hint: ' + this.hint);
	}

	Hangman.prototype.guessword = function (user, word) {
		user = Users.get(user);
		if (this.guessed[word]) return user.sendTo(this.room, 'That word has already been guessed!');
		if (hasGuessedWord(user, this.guessed)) return user.sendTo(this.room, 'You can only guess the entire word once per game.');
		if (this.answer !== word) {
			this.chances--;
			if (this.chances === 0) {
				this.room.add('|html|' + user.name + ' guessed the word \'' + word + '\' but was not the correct answer. The man has been hanged for failing to guess the word.');
				delete hangman[this.room.id];
			} else {
				this.room.add('|html|' + user.name + ' guessed the word \'' + word + '\' but was not the correct answer...');
				this.guessed[word] = toId(user);
			}
		} else {
			this.room.add('|html|' + user.name + ' guessed the word \'' + word + '\' which is the correct answer! Congratulations!');
			delete hangman[this.room.id];
		}
	};

	Hangman.prototype.guess = function (user, target) {
		user = Users.get(user);
		if (this.guessed[target]) return user.sendTo(this.room, 'That letter has already been guessed!');
		var count = 0;
		/*for (var i in this.guessed)
			if (this.guessed[i] === user.userid || user.getAlts().indexOf(this.guessed[i]) > -1) count++;
		if (count == 3) return user.sendTo(this.room, 'You may only guess 3 times per game. Better luck next time!');*/
		//The above statement can be re-enabled if you want to limit the number of times a user can guess.

		if (!this.letters[target]) {
			this.chances--;
			if (this.chances == 0) {
				this.room.add('|html|' + user.name + ' guessed the letter \'' + target + '\' but was not in the word. The man has been hanged for failing to guess the word.');
				delete hangman[this.room.id];
			} else {
				this.room.add('|html|' + user.name + ' guessed the letter \'' + target + '\' but was not in the word...');
				this.guessed[target] = user.userid;
			}
		} else {
			this.room.add('|html|' + user.name + ' guessed the letter \'' + target + '\', which was letter ' + this.letters[target].position.join(", ") + ' of the word.');
			this.guessed[target] = user.userid;
			this.correctguesses++;
			if (this.correctguesses === Object.keys(this.letters).length) {
				this.room.add('|html|The word has been found! The answer is \'' + this.answer + '\'. Congratulations!');
				delete hangman[this.room.id];
			}
		}
	};

	Hangman.prototype.details = function () {
			var word = '',
				guessedletters = [];
			for (var i = 0; i < this.answer.length; i++) {
				if (this.guessed[this.answer[i]]) word += ' ' + this.answer[i] + ' ';
				else if (this.answer[i] == 'a' || this.answer[i] == 'e' || this.answer[i] == 'i' || this.answer[i] == 'o' || this.answer[i] == 'u')
					word += ' _ ';
				else word += ' _ ';
			}
			for (var i in this.guessed)
				guessedletters.push(i);

			guessedletters = (guessedletters.length < 1) ? 'None' : guessedletters.join(', ');
			return '
' + word + '
' +
				'Guessed letters: ' + guessedletters + '
' +
				'Chances Left: ' + this.chances + '
' +
				'Hint: ' + this.hint;
		},

		Hangman.prototype.end = function (user) {
			this.room.add('|html|The game of hangman has been ended by ' + Users.get(user).name);
			delete hangman[this.room.id];
		};
	return Hangman;
})();

var commands = {
	'': 'help',
	help: function (target, room, user, connection, cmd) {
		if (!this.canBroadcast()) return;
		this.sendReplyBox(
			'All commands are in the format \'/hangman command\', that is, prefixed with /hangman.
' +
			'Starter/Staff commands-
' +
			'- start or new word, hint - Starts a game of hangman in the room with the specified word as the answer along with a hint. All vowels use a red blank when displayed. (Alternate command - /starthangman) (Requires +, %, @, #)
' +
			'- answer or word - Allows game starter to view the answer.
' +
			'- end or delete - Ends the game of hangman in the room. (Alternate command - /endhangman) (Requires %, @, #)

' +
			'Player commands-
' +
			'- guess letter - Guesses a letter. Non-English characters cannot be guessed. (Alternate command - /guessletter)
' +
			'- guessword word - Guesses the entire word. Can only be used by the user once per game. The answer cannot contain non-English characters. (Alternate command - /guessword)
' +
			'- view or details - Allows you to view the details of the current game. These include the progress, the letters guessed, and the number of tries remaining. (Alternate command - /viewhangman)
'
		);
	},

	'new': 'start',
	start: function (target, room, user, connection, cmd) {
		if (!this.can('broadcast', null, room)) return this.sendReply('You must be ranked + or higher to start a game of hangman.');
		if (hangman[room.id]) return this.sendReply('There is already a game of hangman going on in this room.');
		if (!target) return this.sendReply('|html|/ ' + cmd + ' word, hint - Starts a game of hangman in the room with the specified word as the along with a hint.');
		var targets = target.split(',');
		var word = targets[0];
		var hint = targets[1];
		if (!toId(word)) return this.sendReply("Seriously, don't bother trying to start a game of hangman without a word.");
		if (word.match(/[^a-zA-Z]+/ig)) return this.sendReply('The word can only contain letters. Spaces, special characters, and numbers cannot be used.');
		if (toId(word).length > 15 || toId(word).length < 5) return this.sendReply('The word needs to be 5 to 15 letters long.');
		if (!hint || !hint.trim()) return this.sendReply('You need to give a hint to the answer!');

		hangman[room.id] = new Hangman(room, user.userid, toId(word), hint);
	},

	guessword: 'guess',
	guess: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		if (Users.get(hangman[room.id].starter).userid === user.userid || Users.get(hangman[room.id].starter).getAlts().map(toId).indexOf(user.userid) > -1) return this.sendReply('You cannot guess if you\'re the one who started the game.');
		target = target.trim();
		if (target.length > 1) return this.sendReply('You can only guess one letter at a time.');
		if (target.match(/[^a-zA-Z]+/g)) return this.sendReply('You may only guess letters. You cannot guess numbers or special characters.');
		target = target.trim().toLowerCase();
		if (!target) return this.sendReply("|html|/hangman guess letter - Guesses a letter in a game of hangman.");
		if (!toId(target) || Number(target)) return this.sendReply("'" + target + "' is not a valid letter (You may only guess english letters).");

		hangman[room.id].guess(user.userid, toId(target));

	},

	guessword: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		if (Users.get(hangman[room.id].starter).userid === user.userid || Users.get(hangman[room.id].starter).getAlts().map(toId).indexOf(user.userid) > -1) return this.sendReply('You cannot guess the word if you\'re the one who started the game.');
		if (target.length < 5 || target.length > 15) return this.sendReply('Words in hangman contain a minimum of 5 letters and a maximum of 15 letters.');
		target = target.trim().toLowerCase();
		if (!target) return this.sendReply("|html|/hangman guessword word - Guesses the word in a game of hangman.");
		if ((toId(target) !== target) || parseInt(target)) return this.sendReply("You cannot include any special characters, spaces, or numbers in your answer.");

		hangman[room.id].guessword(user.userid, toId(target));
	},

	view: 'details',
	data: 'details',
	details: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		if (!this.canBroadcast()) return;
		this.sendReplyBox(hangman[room.id].details());
	},

	word: 'answer',
	answer: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		if (toId(hangman[room.id].starter) !== user.userid) return this.sendReply("Only the starter of the game can view the answer.");
		if (Users.get(hangman[room.id].starter).getAlts().map(toId).indexOf(user.userid) > -1) return this.sendReply("The game of hangman was started by your alt, " + hangman[room.id].starter + ". Use that alt/account to view the answer.");
		return this.sendReply("|html|The answer is '" + hangman[room.id].answer);
	},

	'delete': 'end',
	finish: 'end',
	end: function (target, room, user) {
		if (!hangman[room.id]) return this.sendReply('There is no game of hangman going on in this room.');
		hangman[room.id].end(user.name);
	}
};

exports.commands = {
	'hangman': commands,
	starthangman: commands.start,
	guessletter: commands.guess,
	guessword: commands.guessword,
	viewhangman: commands.details,
	endhangman: commands.end
};
<|endoftext|>


<commit_before>/**
 * $Id: GZ 2010-12-19 exp$
 * Used by regions.php.
 *
 * TODO: some functions here, shall not use the Get-comand but rather modify the DOM directly.
 */

/**
 * prepare species string for $_GET
 */
function prepareSpecies(site) {
	var project_str = "projects";
	// var project_selects = document.getElementsByName(project_str);
	var src_sel = document.getElementById(project_str + "0");
	var expr = /(\w.+)\s(\w.+)/;
	expr.exec(src_sel[src_sel.selectedIndex].value);
	if (site == null) {
		site = "regions.php";
	}
	return site + "?" + project_str + "[]=" + RegExp.$1 + "+" + RegExp.$2;

	// var species_str = "species";
	// var species_select = document.getElementsByName(species_str)[0];
	// var expr = /(\w.+)\s(\w.+)/;
	// expr.exec(species_select[species_select.selectedIndex].value);
	// if (site == null) {
	// site = "regions.php";
	// }
	// return site + "?" + species_str + "=" + RegExp.$1 + "+" + RegExp.$2;
}

/**
 * Returns a $_GET string with all selected regions contained in an array
 * regions[].
 */
function prepareGetString(site) {
	// prepare species
	var str = prepareSpecies(site);

	// add the selected region to the regions textfield
	// fetch all regions textfields into a get-string
	var ele = document.getElementsByName("regions[]");
	for ( var i = 0; i < ele.length; i++) {
		var region = ele[i];
		if (region.value != '') {
			str += "&regions[]=" + region.id.substring(0, region.id.indexOf("-"))
					+ ":" + region.value;
		}
	}
	str += '&confidence_int=' + document.getElementById('conf').value;
	return str;
}
/**
 * Add the selected region to the regions textfield and call the get method with
 * the new region, rather than setting the field content directly...
 */
function addRegion(chr) {
	var str = "&regions[]=" + chr + ":"
			+ document.getElementById("start" + chr).value + "-"
			+ document.getElementById("end" + chr).value;
	window.location.href = prepareGetString() + str;
}

/**
 * delete the selected region from the regions textfield and call the get method
 * with the old region, rather than setting the field content directly...
 */
function deleteRegion(chr) {
	document.getElementById(chr).removeAttribute("name");
	window.location.href = prepareGetString();
}

/**
 * Called to go to the next page.
 *
 * @param target
 *          modus, either 'overview' or all
 */
function submit_page(target) {
	if (target == 'overview') {
		window.location.href = prepareGetString("compara.php");
	} else if (target == 'all') {
		window.location.href = prepareGetString("display_all.php");
	} else {// this
		window.location.href = prepareSpecies();
	}

}
<commit_msg>minor development changes<commit_after>/**
 * $Id: GZ 2010-12-19 exp$
 * Used by regions.php.
 *
 * TODO: some functions here, shall not use the Get-comand but rather modify the DOM directly.
 */

/**
 * prepare species string for $_GET
 */
function prepareSpecies(site) {
	var project_str = "projects";
	// var project_selects = document.getElementsByName(project_str);
	var src_sel = document.getElementById(project_str + "0");
	var expr = /(\w.+)\s(\w.+)/;
	expr.exec(src_sel[src_sel.selectedIndex].value);
	alert(src_sel[src_sel.selectedIndex].value);
	if (site == null) {
		site = "regions.php";
	}
	return site + "?" + project_str + "[]=" + RegExp.$1 + "+" + RegExp.$2;

	// var species_str = "species";
	// var species_select = document.getElementsByName(species_str)[0];
	// var expr = /(\w.+)\s(\w.+)/;
	// expr.exec(species_select[species_select.selectedIndex].value);
	// if (site == null) {
	// site = "regions.php";
	// }
	// return site + "?" + species_str + "=" + RegExp.$1 + "+" + RegExp.$2;
}

/**
 * Returns a $_GET string with all selected regions contained in an array
 * regions[].
 */
function prepareGetString(site) {
	// prepare species
	var str = prepareSpecies(site);

	// add the selected region to the regions textfield
	// fetch all regions textfields into a get-string
	var ele = document.getElementsByName("regions[]");
	for ( var i = 0; i < ele.length; i++) {
		var region = ele[i];
		if (region.value != '') {
			str += "&regions[]=" + region.id.substring(0, region.id.indexOf("-"))
					+ ":" + region.value;
		}
	}
	str += '&confidence_int=' + document.getElementById('conf').value;
	return str;
}
/**
 * Add the selected region to the regions textfield and call the get method with
 * the new region, rather than setting the field content directly...
 */
function addRegion(chr) {
	var str = "&regions[]=" + chr + ":"
			+ document.getElementById("start" + chr).value + "-"
			+ document.getElementById("end" + chr).value;
	window.location.href = prepareGetString() + str;
}

/**
 * delete the selected region from the regions textfield and call the get method
 * with the old region, rather than setting the field content directly...
 */
function deleteRegion(chr) {
	document.getElementById(chr).removeAttribute("name");
	window.location.href = prepareGetString();
}

/**
 * Called to go to the next page.
 *
 * @param target
 *          modus, either 'overview' or all
 */
function submit_page(target) {
	if (target == 'overview') {
		window.location.href = prepareGetString("compara.php");
	} else if (target == 'all') {
		window.location.href = prepareGetString("display_all.php");
	} else {// this
		window.location.href = prepareSpecies();
	}

}
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';

const propTypes = {
  className: PropTypes.string,
  children: PropTypes.node,
};

const CardTitle = ({ className, children }) => (
  <h1
    className={classnames('mdc-card__title', 'mdc-card__title--large', className)}
  >
    {children}
  </h1>
  );
CardTitle.propTypes = propTypes;
export default CardTitle;
<commit_msg>feat(CardTitle): possibility to define large title (#29)<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';

const propTypes = {
  className: PropTypes.string,
  children: PropTypes.node,
  large: PropTypes.bool,
};

const ROOT = 'mdc-card__title';
const LARGE = `${ROOT}--large`;

const CardTitle = ({ className, children, large }) => (
  <h1
    className={classnames(ROOT, {
      [LARGE]: large,
    }, className)}
  >
    {children}
  </h1>
  );
CardTitle.propTypes = propTypes;
export default CardTitle;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';

import Menu from '../shared/Menu';
import permissions from '../../lib/permissions';

class SettingsMenu extends React.Component {
  static propTypes = {
    organization: PropTypes.shape({
      name: PropTypes.string.isRequired,
      slug: PropTypes.string.isRequired,
      members: PropTypes.shape({
        count: PropTypes.number.isRequired
      }),
      invitations: PropTypes.shape({
        count: PropTypes.number.isRequired
      }),
      teams: PropTypes.shape({
        count: PropTypes.number.isRequired
      }),
      permissions: PropTypes.shape({
        organizationUpdate: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired,
        organizationInvitationCreate: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired,
        teamAdmin: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired,
        notificationServiceUpdate: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired,
        organizationBillingUpdate: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired
      })
    }),
    relay: PropTypes.object.isRequired
  };

  componentDidMount() {
    this.props.relay.forceFetch({ isMounted: true });
  }

  render() {
    return (

        <Menu>
          <Menu.Header>{this.props.organization.name}</Menu.Header>
          {this.renderButtons()}
        </Menu>

        <Menu>
          <Menu.Button
            href={`/user/settings`}
            label="Personal Settings"
          />
        </Menu>

    );
  }

  renderButtons() {
    return permissions(this.props.organization.permissions).collect(
      {
        allowed: "organizationUpdate",
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="settings"
            href={`/organizations/${this.props.organization.slug}/settings`}
            label="Settings"
          />
        )
      },
      {
        always: true,
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="users"
            link={`/organizations/${this.props.organization.slug}/users`}
            badge={this.calculateUsersCount()}
            label="Users"
          />
        )
      },
      {
        allowed: "teamAdmin",
        and: () => (Features.TeamsLaunch || Features.organizationHasTeams),
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="teams"
            link={`/organizations/${this.props.organization.slug}/teams`}
            badge={this.props.organization.teams && this.props.organization.teams.count}
            label="Teams"
          />
        )
      },
      {
        allowed: "agentTokenView",
        and: () => Features.AuditLogsLaunch,
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="eye"
            link={`/organizations/${this.props.organization.slug}/audit-log`}
            label="Audit Log"
          />
        )
      },
      {
        allowed: "notificationServiceUpdate",
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="notification-services"
            href={`/organizations/${this.props.organization.slug}/services`}
            label="Notification Services"
          />
        )
      },
      {
        allowed: "organizationUpdate",
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="sso"
            link={`/organizations/${this.props.organization.slug}/sso`}
            label="Single Sign On"
          />
        )
      },
      {
        allowed: "organizationBillingUpdate",
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="billing"
            href={`/organizations/${this.props.organization.slug}/billing`}
            label="Billing"
          />
        )
      }
    );
  }

  calculateUsersCount() {
    if (this.props.organization.members) {
      return this.props.organization.members.count + this.props.organization.invitations.count;
    }
  }
}

export default Relay.createContainer(SettingsMenu, {
  initialVariables: {
    isMounted: false
  },

  fragments: {
    organization: () => Relay.QL`
      fragment on Organization {
        name
        slug
        members @include(if: $isMounted) {
          count
        }
        invitations(state: PENDING) @include(if: $isMounted) {
          count
        }
        teams @include(if: $isMounted) {
          count
        }
        permissions {
          organizationUpdate {
            allowed
          }
          organizationInvitationCreate {
            allowed
          }
          notificationServiceUpdate {
            allowed
          }
          organizationBillingUpdate {
            allowed
          }
          teamAdmin {
            allowed
          }
          agentTokenView {
            allowed
          }
        }
      }
    `
  }
});
<commit_msg>Fix missing permission propType<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';

import Menu from '../shared/Menu';
import permissions from '../../lib/permissions';

class SettingsMenu extends React.Component {
  static propTypes = {
    organization: PropTypes.shape({
      name: PropTypes.string.isRequired,
      slug: PropTypes.string.isRequired,
      members: PropTypes.shape({
        count: PropTypes.number.isRequired
      }),
      invitations: PropTypes.shape({
        count: PropTypes.number.isRequired
      }),
      teams: PropTypes.shape({
        count: PropTypes.number.isRequired
      }),
      permissions: PropTypes.shape({
        organizationUpdate: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired,
        organizationInvitationCreate: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired,
        teamAdmin: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired,
        notificationServiceUpdate: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired,
        organizationBillingUpdate: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired,
        agentTokenView: PropTypes.shape({
          allowed: PropTypes.bool.isRequired
        }).isRequired
      })
    }),
    relay: PropTypes.object.isRequired
  };

  componentDidMount() {
    this.props.relay.forceFetch({ isMounted: true });
  }

  render() {
    return (

        <Menu>
          <Menu.Header>{this.props.organization.name}</Menu.Header>
          {this.renderButtons()}
        </Menu>

        <Menu>
          <Menu.Button
            href={`/user/settings`}
            label="Personal Settings"
          />
        </Menu>

    );
  }

  renderButtons() {
    return permissions(this.props.organization.permissions).collect(
      {
        allowed: "organizationUpdate",
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="settings"
            href={`/organizations/${this.props.organization.slug}/settings`}
            label="Settings"
          />
        )
      },
      {
        always: true,
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="users"
            link={`/organizations/${this.props.organization.slug}/users`}
            badge={this.calculateUsersCount()}
            label="Users"
          />
        )
      },
      {
        allowed: "teamAdmin",
        and: () => (Features.TeamsLaunch || Features.organizationHasTeams),
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="teams"
            link={`/organizations/${this.props.organization.slug}/teams`}
            badge={this.props.organization.teams && this.props.organization.teams.count}
            label="Teams"
          />
        )
      },
      {
        allowed: "agentTokenView",
        and: () => Features.AuditLogsLaunch,
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="eye"
            link={`/organizations/${this.props.organization.slug}/audit-log`}
            label="Audit Log"
          />
        )
      },
      {
        allowed: "notificationServiceUpdate",
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="notification-services"
            href={`/organizations/${this.props.organization.slug}/services`}
            label="Notification Services"
          />
        )
      },
      {
        allowed: "organizationUpdate",
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="sso"
            link={`/organizations/${this.props.organization.slug}/sso`}
            label="Single Sign On"
          />
        )
      },
      {
        allowed: "organizationBillingUpdate",
        render: (idx) => (
          <Menu.Button
            key={idx}
            icon="billing"
            href={`/organizations/${this.props.organization.slug}/billing`}
            label="Billing"
          />
        )
      }
    );
  }

  calculateUsersCount() {
    if (this.props.organization.members) {
      return this.props.organization.members.count + this.props.organization.invitations.count;
    }
  }
}

export default Relay.createContainer(SettingsMenu, {
  initialVariables: {
    isMounted: false
  },

  fragments: {
    organization: () => Relay.QL`
      fragment on Organization {
        name
        slug
        members @include(if: $isMounted) {
          count
        }
        invitations(state: PENDING) @include(if: $isMounted) {
          count
        }
        teams @include(if: $isMounted) {
          count
        }
        permissions {
          organizationUpdate {
            allowed
          }
          organizationInvitationCreate {
            allowed
          }
          notificationServiceUpdate {
            allowed
          }
          organizationBillingUpdate {
            allowed
          }
          teamAdmin {
            allowed
          }
          agentTokenView {
            allowed
          }
        }
      }
    `
  }
});
<|endoftext|>


<commit_before>var React = require('react/addons');
var ReactGoogleMaps = require('react-googlemaps');
var GoogleMapsAPI = window.google.maps;
var {Map,Marker, Polyline, Circle, OverlayView} = ReactGoogleMaps;
var LatLng = GoogleMapsAPI.LatLng;
import Constants from '../constants/Main.js'
import PathStore from '../stores/PathStore.js'
import assign from 'react/lib/Object.assign';

var Path = React.createClass({
    getInitialState: function () {
        return assign({}, {
            center: Constants.WarsawPosition(),
            zoom: 11
        }, PathStore.getState());
    },
    componentDidMount: function () {
        PathStore.onChange(this._handlePathStoreChange)
    },
    componentWillUnmount: function () {
        PathStore.off(this._handlePathStoreChange)
    },
    render: function () {
        var location_circle = this.state.location.coords === undefined ? null : <Circle
            strokeColor="#64b5f6"
            fillColor="#64b5f6"
            center={new LatLng(this.state.location.coords.latitude, this.state.location.coords.longitude)}
            radius={this.state.location.coords.accuracy}/>;
        if (this.state.route.path) {
            console.log("PATH");
            var points = this.state.route.path.points.coordinates.map(this._toPosition);
            console.log(points);
        }
        var route = this.state.route.path === undefined ? null :
            (
                <Polyline
                    strokeColor="#000"
                    path={this.state.route.path.points.coordinates.map(this._toPosition)}/>
            );
        var test = [Constants.WarsawPosition(), this.state.center, Constants.WarsawPosition()];
        console.log("TESTING");
        console.log(test.map(this._toPosition));
        //var route = (
        //    <Polyline
        //        strokeColor="#000"
        //        path={test.map(this._toPosition)}/>
        //);
        var overlay =
            (
                <OverlayView
                    className="myOverlay"
                    mapPane="floatPane"
                    position={Constants.WarsawPosition()}>

Title

                </OverlayView>
            );
        var preloader = !this.state.loading ? null : (

        );
        return (

                {preloader}
                <Map zoom={this.state.zoom}
                     onZoomChange={this._handleZoomChange}
                     center={this.state.center}
                     onCenterChange={this._handleCenterChange}
                     width={window.innerWidth}
                     height={window.innerHeight}>
                    {this.state.route.stations === undefined ?
                        null :
                        this.state.route.stations.map(this._renderMarker)}
                    {location_circle}
                    {route}
                </Map>

        );
    },
    _handlePathStoreChange: function () {
        this.setState(function (previousState, currentProps) {
            var state = PathStore.getState();
            if (previousState.location.coords === undefined && state.location.coords !== undefined) {
                var center = new LatLng(state.location.coords.latitude, state.location.coords.longitude);
                var radius = state.location.coords.accuracy / 500;
                var bound = this._getMapBound([new LatLng(center.A - radius, center.F - radius),
                    new LatLng(center.A + radius, center.F + radius)]);
            } else if (previousState.route.stations === undefined && state.route.stations !== undefined) {
                bound = this._getMapBound(state.route.stations.map((station)=>station.location));
            }
            if (bound !== undefined) {
                state.zoom = bound.zoom;
                state.center = bound.center;
            }
            return state;
        });
        this.setState(PathStore.getState());
    },
    _getMapBound: function (points) {
        var min_x = Infinity,
            max_x = -Infinity,
            min_y = Infinity,
            max_y = -Infinity;
        points.map(function (item, i) {
            if (item.A !== undefined) {
                min_x = Math.min(min_x, item.A);
                max_x = Math.max(max_x, item.A);
                min_y = Math.min(min_y, item.F);
                max_y = Math.max(max_y, item.F);
            } else {
                min_x = Math.min(min_x, item[0]);
                max_x = Math.max(max_x, item[0]);
                min_y = Math.min(min_y, item[1]);
                max_y = Math.max(max_y, item[1]);
            }
        });
        var scale = Math.max(max_x - min_x, max_y - min_y);
        var zoom = Math.min((16 - Math.log(scale) / Math.log(2)), 12);
        var center = new LatLng((min_x + max_x) / 2, (min_y + max_y) / 2);
        return {zoom: zoom, center: center};
    },
    _handleCenterChange: function (map) {
        this.setState({
            center: map.getCenter()
        });
    },
    _handleZoomChange: function (map) {
        this.setState({
            zoom: map.getZoom()
        });
    },
    _renderMarker: function (state, i) {
        return (
            <Marker position={this._toPosition(state.location)}
                    key={i}
                    labelContent={state.name}
                />
        );
    },
    _toPosition: function (pos) {
        if (pos.F !== undefined) {
            var res = new LatLng(pos.A, pos.F);
        } else {
            res = new LatLng(pos[0], pos[1]);
        }
        return res;
    }
});
export default Path;<commit_msg>Path showing<commit_after>var React = require('react/addons');
var ReactGoogleMaps = require('react-googlemaps');
var GoogleMapsAPI = window.google.maps;
var {Map,Marker, Polyline, Circle, OverlayView} = ReactGoogleMaps;
var LatLng = GoogleMapsAPI.LatLng;
import Constants from '../constants/Main.js'
import PathStore from '../stores/PathStore.js'
import assign from 'react/lib/Object.assign';

var Path = React.createClass({
    getInitialState: function () {
        return assign({}, {
            center: Constants.WarsawPosition(),
            zoom: 11
        }, PathStore.getState());
    },
    componentDidMount: function () {
        PathStore.onChange(this._handlePathStoreChange)
    },
    componentWillUnmount: function () {
        PathStore.off(this._handlePathStoreChange)
    },
    render: function () {
        var location_circle = this.state.location.coords === undefined ? null : <Circle
            strokeColor="#64b5f6"
            fillColor="#64b5f6"
            center={new LatLng(this.state.location.coords.latitude, this.state.location.coords.longitude)}
            radius={this.state.location.coords.accuracy}/>;
        if (this.state.route.path) {
            var points = this.state.route.path.points.coordinates.map(this._toPosition);
        }
        var route = this.state.route.path === undefined ? null :
            (
                <Polyline
                    strokeColor="#000"
                    path={this.state.route.path.points.coordinates.map(this._toPosition)}/>
            );
        var overlay =
            (
                <OverlayView
                    className="myOverlay"
                    mapPane="floatPane"
                    position={Constants.WarsawPosition()}>

Title

                </OverlayView>
            );
        var preloader = !this.state.loading ? null : (

        );
        return (

                {preloader}
                <Map zoom={this.state.zoom}
                     onZoomChange={this._handleZoomChange}
                     center={this.state.center}
                     onCenterChange={this._handleCenterChange}
                     width={window.innerWidth}
                     height={window.innerHeight}>
                    {this.state.route.stations === undefined ?
                        null :
                        this.state.route.stations.map(this._renderMarker)}
                    {location_circle}
                    {route}
                </Map>

        );
    },
    _handlePathStoreChange: function () {
        this.setState(function (previousState, currentProps) {
            var state = PathStore.getState();
            if (previousState.location.coords === undefined && state.location.coords !== undefined) {
                var center = new LatLng(state.location.coords.latitude, state.location.coords.longitude);
                var radius = state.location.coords.accuracy / 500;
                var bound = this._getMapBound([new LatLng(center.A - radius, center.F - radius),
                    new LatLng(center.A + radius, center.F + radius)]);
            } else if (previousState.route.stations === undefined && state.route.stations !== undefined) {
                bound = this._getMapBound(state.route.stations.map((station)=>station.location));
            }
            if (bound !== undefined) {
                state.zoom = bound.zoom;
                state.center = bound.center;
            }
            return state;
        });
        this.setState(PathStore.getState());
    },
    _getMapBound: function (points) {
        var min_x = Infinity,
            max_x = -Infinity,
            min_y = Infinity,
            max_y = -Infinity;
        points.map(function (item, i) {
            if (item.A !== undefined) {
                min_x = Math.min(min_x, item.A);
                max_x = Math.max(max_x, item.A);
                min_y = Math.min(min_y, item.F);
                max_y = Math.max(max_y, item.F);
            } else {
                min_x = Math.min(min_x, item[0]);
                max_x = Math.max(max_x, item[0]);
                min_y = Math.min(min_y, item[1]);
                max_y = Math.max(max_y, item[1]);
            }
        });
        var scale = Math.max(max_x - min_x, max_y - min_y);
        var zoom = Math.min((16 - Math.log(scale) / Math.log(2)), 12);
        var center = new LatLng((min_x + max_x) / 2, (min_y + max_y) / 2);
        return {zoom: zoom, center: center};
    },
    _handleCenterChange: function (map) {
        this.setState({
            center: map.getCenter()
        });
    },
    _handleZoomChange: function (map) {
        this.setState({
            zoom: map.getZoom()
        });
    },
    _renderMarker: function (state, i) {
        return (
            <Marker position={this._toPosition(state.location)}
                    key={i}
                    labelContent={state.name}
                />
        );
    },
    _toPosition: function (pos) {
        if (pos.F !== undefined) {
            var res = new LatLng(pos.A, pos.F);
        } else {
            res = new LatLng(Math.max(pos[0], pos[1]), Math.min(pos[0], pos[1]));
        }
        console.log(res);
        return res;
    }
});
export default Path;<|endoftext|>


<commit_before>define(function (require) {
  var text = new Kinetic.Text({
    id: 'click-here-to-start',
    text: 'click here to start',
    fontSize: 90,
    fontFamily: 'Sans-Serif',
    shadowOffset: [1, 1],
    shadowColor: '#ff0',
    shadowBlur: 5,
    shadowOpacity: 1,
    fill: '#fff',
    stroke: '#ff0',
    strokeWidth: 3
  });

  function mousein() { text.setFill('#f00'); }
  function mouseout() { text.setFill('#fff'); }

  function create(scene, callback) {
    text.setY(355);
    text.setX(scene.width / 2 - text.getWidth() / 2);
    text.on('mouseover', mousein);
    text.on('mouseout', mouseout);
    text.on('click', callback);
    return text;
  }

  return create;
});
<commit_msg>added comment about how horrible on(click) is for Kinetic<commit_after>define(function (require) {
  var text = new Kinetic.Text({
    id: 'click-here-to-start',
    text: 'click here to start',
    fontSize: 90,
    fontFamily: 'Sans-Serif',
    shadowOffset: [1, 1],
    shadowColor: '#ff0',
    shadowBlur: 5,
    shadowOpacity: 1,
    fill: '#fff',
    stroke: '#ff0',
    strokeWidth: 3
  });

  function mousein() { text.setFill('#f00'); }
  function mouseout() { text.setFill('#fff'); }

  function create(scene, callback) {
    text.setY(355);
    text.setX(scene.width / 2 - text.getWidth() / 2);
    text.on('mouseover', mousein);
    text.on('mouseout', mouseout);
    text.on('click', callback); // this is horrible and most likely should not be used
    return text;
  }

  return create;
});
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import Actions from '../actions/Action';
import appStore from '../stores/AppStore';
import ReactTypeahead from 'react-typeahead';
import * as $ from 'jquery';

require('styles//Search.less');

class SearchComponent extends React.Component {

  componentWillMount() {
    this.appStoreId = appStore.registerView(() => { this.updateState(); });
    this.updateState();
  }

  componentWillUnmount() {
    appStore.deregisterView(this.appStoreId);
  }

  updateState() {
    this.setState({
      places: appStore.get('venues')
    });
  }

  render() {
    console.log(this.state.places);
    let onSearch = function() {
      //Actions.requestFlickrData(document.getElementById("search-text").value);
      //Actions.request4SquareData(document.getElementById("search-text").value);
      Actions.requestInstaTagData(document.getElementById("search-text").value);
    };
    return (

        {/*

          <input id="search-text" type="text" />
          <button onClick={onSearch}>Search</button>

*/}
          <ReactTypeahead.Typeahead
              name="myTypeahead"
              options={this.state.places}
              maxVisible={15}
              placeholder='Type and select location'
              onKeyUp={ e => { if (e.target.value.length > 3) Actions.request4SquareData(e.target.value); } }
              filterOption={ (input, option) => { /*console.log('filterOption:',input, option);*/ return true; } }
              displayOption={ (option, index) => { /*console.log('displayOption:', option, index);*/ return option.name + '(' + option.stats.checkinsCount + ')'; }}
              onOptionSelected={ o => { console.log(o); Actions.requestInstaGetLocation(o.id); } }
              />

    );
  }
}

SearchComponent.displayName = 'SearchComponent';

// Uncomment properties you need
// SearchComponent.propTypes = {};
// SearchComponent.defaultProps = {};

export default SearchComponent;
<commit_msg>use requestInstaSearch instead requestInstaLocation<commit_after>'use strict';

import React from 'react';
import Actions from '../actions/Action';
import appStore from '../stores/AppStore';
import ReactTypeahead from 'react-typeahead';
import * as $ from 'jquery';

require('styles//Search.less');

class SearchComponent extends React.Component {

  componentWillMount() {
    this.appStoreId = appStore.registerView(() => { this.updateState(); });
    this.updateState();
  }

  componentWillUnmount() {
    appStore.deregisterView(this.appStoreId);
  }

  updateState() {
    this.setState({
      places: appStore.get('venues')
    });
  }

  render() {
    let onSearch = function() {
      //Actions.requestFlickrData(document.getElementById("search-text").value);
      //Actions.request4SquareData(document.getElementById("search-text").value);
      Actions.requestInstaTagData(document.getElementById("search-text").value);
    };
    return (

        {/*

          <input id="search-text" type="text" />
          <button onClick={onSearch}>Search</button>

*/}
          <ReactTypeahead.Typeahead
              name="myTypeahead"
              options={this.state.places}
              maxVisible={15}
              placeholder='Type and select location'
              onKeyUp={ e => { if (e.target.value.length > 3) Actions.request4SquareData(e.target.value); } }
              filterOption={ (input, option) => { /*console.log('filterOption:',input, option);*/ return true; } }
              displayOption={ (option, index) => { /*console.log('displayOption:', option, index);*/ return option.name + '(' + option.stats.checkinsCount + ')'; }}
              onOptionSelected={ o => { Actions.requestInstaSearch({ latitude: o.location.lat, longitude: o.location.lng }); } }
              />

    );
  }
}

SearchComponent.displayName = 'SearchComponent';

// Uncomment properties you need
// SearchComponent.propTypes = {};
// SearchComponent.defaultProps = {};

export default SearchComponent;
<|endoftext|>


<commit_before>import React from 'react';
import {render} from 'react-dom';
import {Route, HashRouter, withRouter} from 'react-router-dom';

require("./../assets/style.css");
import 'bootstrap/dist/css/bootstrap.css';

import AboutPage from './pages/about.page';
import MainPage from './pages/main.page';
import RoutePage from './pages/route.page';
import RouteListPage from './pages/route.list.page';
import RouteMapPage from './pages/route.map.page';
import Header from './components/header';
const RouterHeader = withRouter(Header);

window.React = React;

render((

        <HashRouter>

                <RouterHeader/>
                <Route exact path="/" component={MainPage}></Route>
                <Route exact path="/marsrutai" component={RouteListPage}></Route>
                <Route exact path="/zemelapis" component={RouteMapPage} className="map-box"></Route>
                <Route exact path="/marsrutas/:url" component={RoutePage}></Route>
                <Route exact path="/apie" component={AboutPage}></Route>

        </HashRouter>

), document.getElementById('content'));
<commit_msg>testing rendering 12<commit_after>import React from 'react';
import {render} from 'react-dom';
import {Route, HashRouter, withRouter} from 'react-router-dom';

require("./../assets/style.css");
require('es6-object-assign').polyfill();
import 'bootstrap/dist/css/bootstrap.css';

import AboutPage from './pages/about.page';
import MainPage from './pages/main.page';
import RoutePage from './pages/route.page';
import RouteListPage from './pages/route.list.page';
import RouteMapPage from './pages/route.map.page';
import Header from './components/header';
const RouterHeader = withRouter(Header);

window.React = React;

render((

        <HashRouter>

                <RouterHeader/>
                <Route exact path="/" component={MainPage}></Route>
                <Route exact path="/marsrutai" component={RouteListPage}></Route>
                <Route exact path="/zemelapis" component={RouteMapPage} className="map-box"></Route>
                <Route exact path="/marsrutas/:url" component={RoutePage}></Route>
                <Route exact path="/apie" component={AboutPage}></Route>

        </HashRouter>

), document.getElementById('content'));
<|endoftext|>