<commit_before>import DOM from '../dom/DefaultDOMElement'
import isString from '../util/isString'
import _isTextNodeEmpty from './_isTextNodeEmpty'

/*
  Schema drive pretty-printer, that inserts indentation for
  structural elements, and preserves white-spaces for text nodes and inline-elements
*/
export default function prettyPrintXML(xml) {
  let dom
  if (isString(xml)) {
    dom = DOM.parseXML(xml)
  } else {
    dom = xml
  }
  const result = []
  dom.children.forEach((el) => {
    _prettyPrint(result, el, 0)
  })
  return result.join('\n')
}

function _prettyPrint(result, el, level) {
  let indent = new Array(level*2).fill(' ').join('')
  if (el.isElementNode()) {
    const isMixed = _isMixed(el)
    if (isMixed) {
      result.push(indent + el.outerHTML)
    } else {
      let children = el.children
      const tagName = el.tagName
      let tagStr = [`<${tagName}`]
      el.getAttributes().forEach((val, name) => {
        tagStr.push(`${name}="${val}"`)
      })
      if (children.length > 0) {
        result.push(indent + tagStr.join(' ') + '>')
        el.children.forEach((child) => {
          _prettyPrint(result, child, level+1)
        })
        result.push(indent + `</${tagName}>`)
      } else {
        result.push(indent + tagStr.join(' ') + ' />')
      }
    }
  } else {
    result.push(indent + el.outerHTML)
  }
}

function _isMixed(el) {
  const childNodes = el.childNodes
  for (let i = 0; i < childNodes.length; i++) {
    let child = childNodes[i]
    if (child.isTextNode() && !_isTextNodeEmpty(child)) {
      return true
    }
  }
}
<commit_msg>Fix prettyPrintXML to print all nodes.<commit_after>import DOM from '../dom/DefaultDOMElement'
import isString from '../util/isString'
import _isTextNodeEmpty from './_isTextNodeEmpty'

/*
  Schema drive pretty-printer, that inserts indentation for
  structural elements, and preserves white-spaces for text nodes and inline-elements
*/
export default function prettyPrintXML(xml) {
  let dom
  if (isString(xml)) {
    dom = DOM.parseXML(xml)
  } else {
    dom = xml
  }
  const result = []
  dom.childNodes.forEach((el) => {
    _prettyPrint(result, el, 0)
  })
  return result.join('\n')
}

function _prettyPrint(result, el, level) {
  let indent = new Array(level*2).fill(' ').join('')
  if (el.isElementNode()) {
    const isMixed = _isMixed(el)
    if (isMixed) {
      result.push(indent + el.outerHTML)
    } else {
      let children = el.children
      const tagName = el.tagName
      let tagStr = [`<${tagName}`]
      el.getAttributes().forEach((val, name) => {
        tagStr.push(`${name}="${val}"`)
      })
      if (children.length > 0) {
        result.push(indent + tagStr.join(' ') + '>')
        el.children.forEach((child) => {
          _prettyPrint(result, child, level+1)
        })
        result.push(indent + `</${tagName}>`)
      } else {
        result.push(indent + tagStr.join(' ') + ' />')
      }
    }
  } else {
    result.push(indent + el.outerHTML)
  }
}

function _isMixed(el) {
  const childNodes = el.childNodes
  for (let i = 0; i < childNodes.length; i++) {
    let child = childNodes[i]
    if (child.isTextNode() && !_isTextNodeEmpty(child)) {
      return true
    }
  }
}
<|endoftext|>


<commit_before>document.write('
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">            Toggle navigation                                              </button>');
document.write('Code The Change

');
document.write('
');
document.write('
Home
');
document.write('
Partners
');
document.write('
Projects
');
document.write('
Non-Profits
');
document.write('
Create New Project
');
document.write('
              Dropdown

Action

Another action

Something else here

Separated link

One more separated link

');
document.write('<form class="navbar-form navbar-right" role="search">
              <input type="text" class="form-control" placeholder="Search">
            <button type="submit" class="btn btn-default">Submit</button>          </form>

      ');
<commit_msg>Tab that is active is given the active class<commit_after>document.write('');
document.write('');
document.write('
');
document.write('<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">');
document.write('Toggle navigation');
document.write('');
document.write('');
document.write('</button>');
document.write('Code The Change');
document.write('
');

document.write('');
document.write('
');
document.write('
');

var url = document.URL;
var split = url.split("/");
var page = split[split.length - 1];
var pages = ["dashboard.html", "non_profit_partner_profiles.html", "allProjects.html", "projectCreate.html"];
var titles = ["Home", "Partners", "Projects", "Create New Project"];

for(var i = 0; i < 4; i++) {
	document.write('
' + titles[i] + '
');
	//
titles[i]

}

document.write('
');
document.write('Dropdown ');
document.write('
');
document.write('
Action
');
document.write('
Another action
');
document.write('
Something else here
');
document.write('

');
document.write('
Separated link
');
document.write('

');
document.write('
One more separated link
');
document.write('

');

document.write('<form class="navbar-form navbar-right" role="search">');
document.write('
');
document.write('<input type="text" class="form-control" placeholder="Search">
');
document.write('<button type="submit" class="btn btn-default">Submit</button></form>');
document.write('

');
document.write('');
<|endoftext|>


<commit_before>ZBase.registerView((function() {
  var Overview = {};
  var Editor = {};
  var path_parts;

  function renderTableList(source_handler, pane) {
    var ul = pane.querySelector(".zbase_sql_editor_table_list");
    var source_id = "tables";
    var source = source_handler.get(
      source_id,
      "/api/v1/sql_stream?query=" + encodeURIComponent("SHOW TABLES;"));

    source.addEventListener('result', function(e) {
      source_handler.close(source_id);

      var data = JSON.parse(e.data);
      data.results[0].rows.forEach(function(table) {
        var li = document.createElement("li");
        li.innerHTML = table[0];
        ul.appendChild(li);
        li.addEventListener('click', function() {
          renderTableDescriptionModal(source_handler, table[0]);
        }, false);
      });
      pane.querySelector(".sidebar_section .zbase_loader").classList.add("hidden");
      ul.style.display = "block";
    });
  };

  function renderTableDescriptionModal(source_handler, table) {
    var modal = document.querySelector(".zbase_sql_editor_modal.table_descr");
    var loader = modal.querySelector(".zbase_loader");
    var source_id = "table_descr";
    var source = source_handler.get(
      source_id,
      "/api/v1/sql_stream?query=" + encodeURIComponent("DESCRIBE '" + table + "';"));

    modal.querySelector(".zbase_modal_header").innerHTML = table;
    loader.classList.remove("hidden");
    modal.show();

    source.addEventListener('result', function(e) {
      source_handler.close(source_id);
      var result = JSON.parse(e.data).results[0];
      var header = modal.querySelector("thead tr");
      var body = modal.querySelector("tbody");

      header.innerHTML = "";
      result.columns.forEach(function(column) {
        header.innerHTML += "" + column + "</th";
      });

      body.innerHTML = "";
      result.rows.forEach(function(row) {
        var html = "
"
        row.forEach(function(cell) {
          html += "" + cell + "	";
        });
        html += "
";
        body.innerHTML += html;
      });

      loader.classList.add("hidden");
      modal.querySelector(".error_message").classList.add("hidden");
      modal.querySelector(".zbase_table").classList.remove("hidden");
    });

    source.addEventListener("error", function(e) {
      source_handler.close(source_id);
      var error_message = modal.querySelector(".error_message");
      try {
        error_message.innerHTML = JSON.parse(e.data).error;
      } catch (err) {
        error_message.innerHTML = e.data;
      }

      loader.classList.add("hidden");
      modal.querySelector(".zbase_table").classList.add("hidden");
      error_message.classList.remove("hidden");
    });
  };

  /**
    * SQL Editor
    */
  Editor.render = function() {
    var viewport = document.getElementById("zbase_viewport");
    var page = ZBase.getTemplate(
      "sql_editor", "zbase_sql_editor_main_tpl");
    ZBase.util.install_link_handlers(page);

    viewport.innerHTML = "";
    viewport.appendChild(page);

    Editor.validateAndFetchDocument();

    Editor.doc_sync = new DocSync(function() {
      return "content=" + encodeURIComponent(document.querySelector(".zbase_sql_editor_pane fn-codeeditor").getValue()) +
      "&name=" + encodeURIComponent(document.querySelector(".zbase_sql_editor_pane input[name='doc_name']").value)
      },
      "/api/v1/sql_queries/" + Editor.doc_id,
      document.querySelector(".zbase_sql_editor_pane .zbase_sql_editor_infobar")
    );

    Editor.source_handler = new EventSourceHandler();
    renderTableList(
      Editor.source_handler,
      document.querySelector(".zbase_sql_editor_pane"));
  };

  Editor.validateAndFetchDocument = function() {
    Editor.doc_id = path_parts[3];
    // invalid docid
    if (!/^[A-Za-z0-9]+$/.test(Editor.doc_id)) {
      //TODO redirect and display message
      alert("invalid docid");
      return;
    }

    // fetch document
    ZBase.util.httpGet("/api/v1/documents/sql_queries/" + Editor.doc_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        Editor.handleNameEditing(doc.name);
        Editor.setQueryContent(doc.sql_query);
        Editor.observeQueryExecution();

        document.querySelector(".zbase_sql_editor_pane .zbase_loader.fullscreen")
          .classList.add("hidden");
      }
    });
  };

  Editor.setQueryContent = function(query) {
    document.querySelector(".zbase_sql_editor_pane fn-codeeditor").setValue(query);
    if (query != "-- SELECT ... FROM ...;" && query.length > 0) {
      Editor.executeQuery(query);
    }
  };

  Editor.observeQueryExecution = function() {
    var editor = document.querySelector(".zbase_sql_editor_pane fn-codeeditor");
    var exec_btn = document.querySelector(
      ".zbase_sql_editor_pane button[data-action='execute-query']");

    /*document.querySelector("fn-tooltip[data-target='query_exec_btn']").init(
      exec_btn);*/

    exec_btn.addEventListener('click', function() {
      Editor.executeQuery(editor.getValue());
    }, false);

    var cmd_pressed = false;
    editor.addEventListener('keydown', function(e) {
      if (e.keyCode == 17 || e.keyCode == 91) {
        cmd_pressed = true;
      }
    }, false);

    editor.addEventListener('keyup', function(e) {
      if (e.keyCode == 17 || e.keyCode == 91) {
        cmd_pressed = false;
      }
    }, false);

    editor.addEventListener('keydown', function(e) {
      if (e.keyCode == 13 && cmd_pressed) {
        e.preventDefault();
        Editor.executeQuery(editor.getValue());
      }
    }, false);

    var value = editor.getValue();
    editor.addEventListener('keyup', function() {
      var new_value = editor.getValue();
      if (value == new_value) {return;}
      value = new_value;
      /*Editor.doc_sync.cur_version++;
      Editor.doc_sync.documentChanged("content_changed");*/
    }, false);

  };

  Editor.executeQuery = function(query) {
    var id = "query";

    Editor.setResultVisibility("loading");
    Editor.source_handler.close(id);
    var source = Editor.source_handler.get(
      id,
      "/api/v1/sql_stream?query=" + encodeURIComponent(query));

    source.addEventListener('result', function(e) {
      var end = (new Date()).getTime();
      Editor.source_handler.close(id);
      var data = JSON.parse(e.data);
      Editor.renderResults(data.results);
      Editor.setResultVisibility("result");
    });

    source.addEventListener('error', function(e) {
      Editor.source_handler.close(id);
      try {
        document.querySelector('.zbase_sql_editor_pane .error_text').innerHTML = JSON.parse(e.data).error;
      } catch (e) {
        document.querySelector('.zbase_sql_editor_pane .error_text').innerHTML = e.data;
      }
      Editor.setResultVisibility("error");
    });

  };

  Editor.setResultVisibility = function(state) {
    switch (state) {
      case "loading":
        document.querySelector('.zbase_sql_editor_result_pane')
          .classList.add("hidden");
        document.querySelector('.zbase_sql_editor_pane .error_message')
          .classList.add("hidden");
        document.querySelector(".zbase_sql_result_loader")
          .classList.remove("hidden");
        return;

      case "error":
        document.querySelector('.zbase_sql_editor_pane .error_message')
          .classList.remove("hidden");
        document.querySelector(".zbase_sql_result_loader")
          .classList.add("hidden");
        return;

      case "result":
        document.querySelector('.zbase_sql_editor_result_pane')
          .classList.remove("hidden");
        document.querySelector(".zbase_sql_result_loader")
          .classList.add("hidden");
      return;

      default:
        break;
    }
  };

  Editor.renderResultTable = function(rows, columns) {
    var table = document.createElement("table");
    table.className = 'zbase_table';

    innerHTML = "

";
    columns.forEach(function(column) {
      innerHTML += "" + column + "	";
    });

    innerHTML += "

";

    rows.forEach(function(row) {
      innerHTML += "
";
      row.forEach(function(cell) {
        innerHTML += "" + cell + "	";
      });
      innerHTML += "
";
    });

    innerHTML += "
";
    table.innerHTML = innerHTML;
    return table;
  };

  Editor.renderResultChart = function(svg) {
    var elem = document.createElement("div");
    elem.className = "zbase_sql_chart";
    elem.innerHTML = svg;
    return elem;
  };

  Editor.renderResultBar = function(index, multiple_results) {
    var bar = document.createElement("div");
    bar.className = "zbase_result_pane_bar";
    bar.setAttribute('data-active', 'active');
    bar.innerHTML =
      "Result " + (index + 1) + "";

    if (multiple_results) {
      bar.className += " clickable";
      bar.addEventListener('click', function() {
        if (this.hasAttribute('data-active')) {
          this.removeAttribute('data-active');
        } else {
          this.setAttribute('data-active', 'active');
        }
      }, false);
    }

    return bar;
  };

  Editor.renderResults = function(results) {
    var result_pane = document.querySelector(
      ".zbase_sql_editor_pane .zbase_sql_editor_result_pane");

    result_pane.innerHTML = "";
    for (var i = 0; i < results.length; i++) {
      result_pane.appendChild(Editor.renderResultBar(i, results.length > 1));
      var elem;
      switch (results[i].type) {
        case "chart":
          elem = Editor.renderResultChart(results[i].svg);
          break;
        case "table":
          elem = Editor.renderResultTable(results[i].rows, results[i].columns)
          break;
      }
      result_pane.appendChild(elem);
    }
  };

  Editor.handleNameEditing = function(doc_name) {
    var name_elem = document.querySelector(".zbase_sql_editor_pane .pagetitle");
    var modal = document.querySelector(
      ".zbase_sql_editor_pane fn-modal.rename_query");
    var input = modal.querySelector("input");
    var submit_btn = modal.querySelector("button[data-action='submit']");
    name_elem.innerHTML = doc_name;

    name_elem.addEventListener("click", function() {
      input.value = name_elem.innerText;
      modal.show();
      input.focus();
    }, false);

    input.addEventListener('keyup', function() {
      if (input.value.length == 0) {
        submit_btn.classList.add('disabled');
      } else if (update_btn.classList.contains('disabled')) {
        submit_btn.classList.remove("disabled");
      }
    }, false);

    submit_btn.addEventListener('click', function() {
      var name = input.value;
      if (name.length == 0) {
        return;
      }
      name_elem.innerHTML = name;
      modal.close();
      Editor.doc_sync.cur_version++;
      Editor.doc_sync.documentChanged("content_changed");
    }, false);
  };

  /**
    * SQL Editor Overview
    */
  Overview.render = function() {
    var viewport = document.getElementById("zbase_viewport");
    var page = ZBase.getTemplate(
      "sql_editor", "zbase_sql_editor_overview_main_tpl");
    ZBase.util.install_link_handlers(page);

    viewport.innerHTML = "";
    viewport.appendChild(page);

    Overview.source_handler = new EventSourceHandler();
    Overview.load();
    Overview.handleNewQueryButton();
    renderTableList(
      Overview.source_handler,
      document.querySelector(".zbase_sql_editor_overview"));
  };

  Overview.handleNewQueryButton = function() {
    document.querySelector(
      ".zbase_sql_editor button[data-action='new-query']")
      .addEventListener("click", function() {
        ZBase.util.httpPost("/api/v1/documents/sql_queries", "", function(r) {
          var response = JSON.parse(r.response);
          window.location.href = "/a/sql/" + response.uuid;
        });
      });
  };

  Overview.renderTable = function(documents) {
    var tbody = document.querySelector(".zbase_sql_editor_overview tbody");
    documents.forEach(function(doc) {
      var url = "/a/sql/" + doc.uuid;
      var tr = document.createElement("tr");
      tr.innerHTML = "" + doc.name + "	" +
        "" + doc.type + "	—	";
      tbody.appendChild(tr);

      tr.addEventListener("click", function() {
        window.location.href = url;
      });
    });

    document.querySelector(".zbase_sql_editor_overview .zbase_loader.fullscreen")
      .classList.add("hidden");
  };

  Overview.load = function() {
    ZBase.util.httpGet("/api/v1/documents", function(r) {
      if (r.status == 200) {
        var documents = JSON.parse(r.response).documents;
        Overview.renderTable(documents);
      } else {
        //TODO render error message
      }
    });
  };

  var render = function(path) {
    path_parts = path.split("/");
    var view;
    // render view
    if (path_parts.length == 4 && path_parts[3].length > 0) {
      Editor.render();
    } else {
      Overview.render();
    }
  };

  return {
    name: "sql_editor",

    loadView: function(params) {
      render(params.path);
    },
    unloadView: function() {
      if (Editor.source_handler) {
        Editor.source_handler.closeAll();
      } else if (Overview.source_handler) {
        Overview.source_handler.closeAll();
      }
    },
    handleNavigationChange: function(url){
      render(url);
    }
  };

})());
<commit_msg>fixed doc_sync url<commit_after>ZBase.registerView((function() {
  var Overview = {};
  var Editor = {};
  var path_parts;

  function renderTableList(source_handler, pane) {
    var ul = pane.querySelector(".zbase_sql_editor_table_list");
    var source_id = "tables";
    var source = source_handler.get(
      source_id,
      "/api/v1/sql_stream?query=" + encodeURIComponent("SHOW TABLES;"));

    source.addEventListener('result', function(e) {
      source_handler.close(source_id);

      var data = JSON.parse(e.data);
      data.results[0].rows.forEach(function(table) {
        var li = document.createElement("li");
        li.innerHTML = table[0];
        ul.appendChild(li);
        li.addEventListener('click', function() {
          renderTableDescriptionModal(source_handler, table[0]);
        }, false);
      });
      pane.querySelector(".sidebar_section .zbase_loader").classList.add("hidden");
      ul.style.display = "block";
    });
  };

  function renderTableDescriptionModal(source_handler, table) {
    var modal = document.querySelector(".zbase_sql_editor_modal.table_descr");
    var loader = modal.querySelector(".zbase_loader");
    var source_id = "table_descr";
    var source = source_handler.get(
      source_id,
      "/api/v1/sql_stream?query=" + encodeURIComponent("DESCRIBE '" + table + "';"));

    modal.querySelector(".zbase_modal_header").innerHTML = table;
    loader.classList.remove("hidden");
    modal.show();

    source.addEventListener('result', function(e) {
      source_handler.close(source_id);
      var result = JSON.parse(e.data).results[0];
      var header = modal.querySelector("thead tr");
      var body = modal.querySelector("tbody");

      header.innerHTML = "";
      result.columns.forEach(function(column) {
        header.innerHTML += "" + column + "</th";
      });

      body.innerHTML = "";
      result.rows.forEach(function(row) {
        var html = "
"
        row.forEach(function(cell) {
          html += "" + cell + "	";
        });
        html += "
";
        body.innerHTML += html;
      });

      loader.classList.add("hidden");
      modal.querySelector(".error_message").classList.add("hidden");
      modal.querySelector(".zbase_table").classList.remove("hidden");
    });

    source.addEventListener("error", function(e) {
      source_handler.close(source_id);
      var error_message = modal.querySelector(".error_message");
      try {
        error_message.innerHTML = JSON.parse(e.data).error;
      } catch (err) {
        error_message.innerHTML = e.data;
      }

      loader.classList.add("hidden");
      modal.querySelector(".zbase_table").classList.add("hidden");
      error_message.classList.remove("hidden");
    });
  };

  /**
    * SQL Editor
    */
  Editor.render = function() {
    var viewport = document.getElementById("zbase_viewport");
    var page = ZBase.getTemplate(
      "sql_editor", "zbase_sql_editor_main_tpl");
    ZBase.util.install_link_handlers(page);

    viewport.innerHTML = "";
    viewport.appendChild(page);

    Editor.validateAndFetchDocument();

    Editor.doc_sync = new DocSync(function() {
      return "content=" + encodeURIComponent(document.querySelector(".zbase_sql_editor_pane fn-codeeditor").getValue()) +
      "&name=" + encodeURIComponent(document.querySelector(".zbase_sql_editor_pane input[name='doc_name']").value)
      },
      "/api/v1/documents/sql_queries/" + Editor.doc_id,
      document.querySelector(".zbase_sql_editor_pane .zbase_sql_editor_infobar")
    );

    Editor.source_handler = new EventSourceHandler();
    renderTableList(
      Editor.source_handler,
      document.querySelector(".zbase_sql_editor_pane"));
  };

  Editor.validateAndFetchDocument = function() {
    Editor.doc_id = path_parts[3];
    // invalid docid
    if (!/^[A-Za-z0-9]+$/.test(Editor.doc_id)) {
      //TODO redirect and display message
      alert("invalid docid");
      return;
    }

    // fetch document
    ZBase.util.httpGet("/api/v1/documents/sql_queries/" + Editor.doc_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        Editor.handleNameEditing(doc.name);
        Editor.setQueryContent(doc.sql_query);
        Editor.observeQueryExecution();

        document.querySelector(".zbase_sql_editor_pane .zbase_loader.fullscreen")
          .classList.add("hidden");
      }
    });
  };

  Editor.setQueryContent = function(query) {
    document.querySelector(".zbase_sql_editor_pane fn-codeeditor").setValue(query);
    if (query != "-- SELECT ... FROM ...;" && query.length > 0) {
      Editor.executeQuery(query);
    }
  };

  Editor.observeQueryExecution = function() {
    var editor = document.querySelector(".zbase_sql_editor_pane fn-codeeditor");
    var exec_btn = document.querySelector(
      ".zbase_sql_editor_pane button[data-action='execute-query']");

    /*document.querySelector("fn-tooltip[data-target='query_exec_btn']").init(
      exec_btn);*/

    exec_btn.addEventListener('click', function() {
      Editor.executeQuery(editor.getValue());
    }, false);

    var cmd_pressed = false;
    editor.addEventListener('keydown', function(e) {
      if (e.keyCode == 17 || e.keyCode == 91) {
        cmd_pressed = true;
      }
    }, false);

    editor.addEventListener('keyup', function(e) {
      if (e.keyCode == 17 || e.keyCode == 91) {
        cmd_pressed = false;
      }
    }, false);

    editor.addEventListener('keydown', function(e) {
      if (e.keyCode == 13 && cmd_pressed) {
        e.preventDefault();
        Editor.executeQuery(editor.getValue());
      }
    }, false);

    var value = editor.getValue();
    editor.addEventListener('keyup', function() {
      var new_value = editor.getValue();
      if (value == new_value) {return;}
      value = new_value;
      Editor.doc_sync.cur_version++;
      Editor.doc_sync.documentChanged("content_changed");
    }, false);

  };

  Editor.executeQuery = function(query) {
    var id = "query";

    Editor.setResultVisibility("loading");
    Editor.source_handler.close(id);
    var source = Editor.source_handler.get(
      id,
      "/api/v1/sql_stream?query=" + encodeURIComponent(query));

    source.addEventListener('result', function(e) {
      var end = (new Date()).getTime();
      Editor.source_handler.close(id);
      var data = JSON.parse(e.data);
      Editor.renderResults(data.results);
      Editor.setResultVisibility("result");
    });

    source.addEventListener('error', function(e) {
      Editor.source_handler.close(id);
      try {
        document.querySelector('.zbase_sql_editor_pane .error_text').innerHTML = JSON.parse(e.data).error;
      } catch (e) {
        document.querySelector('.zbase_sql_editor_pane .error_text').innerHTML = e.data;
      }
      Editor.setResultVisibility("error");
    });

  };

  Editor.setResultVisibility = function(state) {
    switch (state) {
      case "loading":
        document.querySelector('.zbase_sql_editor_result_pane')
          .classList.add("hidden");
        document.querySelector('.zbase_sql_editor_pane .error_message')
          .classList.add("hidden");
        document.querySelector(".zbase_sql_result_loader")
          .classList.remove("hidden");
        return;

      case "error":
        document.querySelector('.zbase_sql_editor_pane .error_message')
          .classList.remove("hidden");
        document.querySelector(".zbase_sql_result_loader")
          .classList.add("hidden");
        return;

      case "result":
        document.querySelector('.zbase_sql_editor_result_pane')
          .classList.remove("hidden");
        document.querySelector(".zbase_sql_result_loader")
          .classList.add("hidden");
      return;

      default:
        break;
    }
  };

  Editor.renderResultTable = function(rows, columns) {
    var table = document.createElement("table");
    table.className = 'zbase_table';

    innerHTML = "

";
    columns.forEach(function(column) {
      innerHTML += "" + column + "	";
    });

    innerHTML += "

";

    rows.forEach(function(row) {
      innerHTML += "
";
      row.forEach(function(cell) {
        innerHTML += "" + cell + "	";
      });
      innerHTML += "
";
    });

    innerHTML += "
";
    table.innerHTML = innerHTML;
    return table;
  };

  Editor.renderResultChart = function(svg) {
    var elem = document.createElement("div");
    elem.className = "zbase_sql_chart";
    elem.innerHTML = svg;
    return elem;
  };

  Editor.renderResultBar = function(index, multiple_results) {
    var bar = document.createElement("div");
    bar.className = "zbase_result_pane_bar";
    bar.setAttribute('data-active', 'active');
    bar.innerHTML =
      "Result " + (index + 1) + "";

    if (multiple_results) {
      bar.className += " clickable";
      bar.addEventListener('click', function() {
        if (this.hasAttribute('data-active')) {
          this.removeAttribute('data-active');
        } else {
          this.setAttribute('data-active', 'active');
        }
      }, false);
    }

    return bar;
  };

  Editor.renderResults = function(results) {
    var result_pane = document.querySelector(
      ".zbase_sql_editor_pane .zbase_sql_editor_result_pane");

    result_pane.innerHTML = "";
    for (var i = 0; i < results.length; i++) {
      result_pane.appendChild(Editor.renderResultBar(i, results.length > 1));
      var elem;
      switch (results[i].type) {
        case "chart":
          elem = Editor.renderResultChart(results[i].svg);
          break;
        case "table":
          elem = Editor.renderResultTable(results[i].rows, results[i].columns)
          break;
      }
      result_pane.appendChild(elem);
    }
  };

  Editor.handleNameEditing = function(doc_name) {
    var name_elem = document.querySelector(".zbase_sql_editor_pane .pagetitle");
    var modal = document.querySelector(
      ".zbase_sql_editor_pane fn-modal.rename_query");
    var input = modal.querySelector("input");
    var submit_btn = modal.querySelector("button[data-action='submit']");
    name_elem.innerHTML = doc_name;

    name_elem.addEventListener("click", function() {
      input.value = name_elem.innerText;
      modal.show();
      input.focus();
    }, false);

    input.addEventListener('keyup', function() {
      if (input.value.length == 0) {
        submit_btn.classList.add('disabled');
      } else if (submit_btn.classList.contains('disabled')) {
        submit_btn.classList.remove("disabled");
      }
    }, false);

    submit_btn.addEventListener('click', function() {
      var name = input.value;
      if (name.length == 0) {
        return;
      }
      name_elem.innerHTML = name;
      modal.close();
      Editor.doc_sync.cur_version++;
      Editor.doc_sync.documentChanged("content_changed");
    }, false);
  };

  /**
    * SQL Editor Overview
    */
  Overview.render = function() {
    var viewport = document.getElementById("zbase_viewport");
    var page = ZBase.getTemplate(
      "sql_editor", "zbase_sql_editor_overview_main_tpl");
    ZBase.util.install_link_handlers(page);

    viewport.innerHTML = "";
    viewport.appendChild(page);

    Overview.source_handler = new EventSourceHandler();
    Overview.load();
    Overview.handleNewQueryButton();
    renderTableList(
      Overview.source_handler,
      document.querySelector(".zbase_sql_editor_overview"));
  };

  Overview.handleNewQueryButton = function() {
    document.querySelector(
      ".zbase_sql_editor button[data-action='new-query']")
      .addEventListener("click", function() {
        ZBase.util.httpPost("/api/v1/documents/sql_queries", "", function(r) {
          var response = JSON.parse(r.response);
          window.location.href = "/a/sql/" + response.uuid;
        });
      });
  };

  Overview.renderTable = function(documents) {
    var tbody = document.querySelector(".zbase_sql_editor_overview tbody");
    documents.forEach(function(doc) {
      var url = "/a/sql/" + doc.uuid;
      var tr = document.createElement("tr");
      tr.innerHTML = "" + doc.name + "	" +
        "" + doc.type + "	—	";
      tbody.appendChild(tr);

      tr.addEventListener("click", function() {
        window.location.href = url;
      });
    });

    document.querySelector(".zbase_sql_editor_overview .zbase_loader.fullscreen")
      .classList.add("hidden");
  };

  Overview.load = function() {
    ZBase.util.httpGet("/api/v1/documents", function(r) {
      if (r.status == 200) {
        var documents = JSON.parse(r.response).documents;
        Overview.renderTable(documents);
      } else {
        //TODO render error message
      }
    });
  };

  var render = function(path) {
    path_parts = path.split("/");
    var view;
    // render view
    if (path_parts.length == 4 && path_parts[3].length > 0) {
      Editor.render();
    } else {
      Overview.render();
    }
  };

  return {
    name: "sql_editor",

    loadView: function(params) {
      render(params.path);
    },
    unloadView: function() {
      if (Editor.source_handler) {
        Editor.source_handler.closeAll();
      } else if (Overview.source_handler) {
        Overview.source_handler.closeAll();
      }
    },
    handleNavigationChange: function(url){
      render(url);
    }
  };

})());
<|endoftext|>


<commit_before>var Next = function(){
	if ( this === window ) {return new arguments.callee};
	this._signal = new Signal;
	return this;
};

var Signal = function() {
	return ( this === window ) ? ( new arguments.callee ) : this;
};

var _bind = function( func, thisObj ){
	return function() {
		var args = [].slice.call( arguments, 0 );
		func.apply( thisObj, args );
	};
};

Signal.prototype = {
	_storage: {},
	_callbacks: {},
	is: function( sig ) {
		return this._storage.hasOwnProperty( sig );
	},
	touch: function( sig ) {
		if ( this.is( sig ) ) {
			delete this._storage[ sig ];
			return true;
		} else return false;
	},
	send: function( sig ) {
		this._storage[ sig ] = 1;
		if ( this._callbacks[ sig ] ) {
			this.callback( sig );
		}
		return this;
	},
	watch: function( sig, callback ) {
		if( !this._callbacks[ sig ] ) this._callbacks[ sig ] = [];
		this._callbacks[ sig ].push( callback );

		if( this.is ( sig ) ) {
			this.callback( sig );
		}
		return this;
	},
	callback: function( sig ) {
		var self = this;
		for (var i = 0; i < this._callbacks[ sig ].length; i++) {
			this._callbacks[ sig ][ i ].call( self, sig );
		}
		delete this._callbacks[ sig ];
		return this;
	}

};

Next.prototype = {
	_queue: [],
	_queueIndex: 0,
	_lastreturned: null,
	_signal: null,
	next: function( func ) {
		this._queue.push( func );
		return this;
	},
	wait: function() {
		var signalid = Math.random().toString();
		var arglist = [].slice.call( arguments, 0 );
		var addEvDefault = _bind( document.addEventListener, document );
		var removeEvDefault = _bind( document.removeEventListener, document );
		var events = {
			count: {
				successed: 0,
				pending:0
			},
			successed: {},
			pending: {}
		};
		var self = this;
		var _getEventListener = function( ev, removeEvL ) {
			var func = function () {
				if ( events.pending[ ev ] ) {
					events.count.successed++;
					events.count.pending--;
					delete events.pending[ ev ];
					events.successed[ ev ] = arguments;
				}
				removeEvL( ev, func );
				if ( events.count.pending === 0 ) {
					//finally, ...
					//GC
					events = null;
					self._signal.send( signalid );
				}
			};
			return func;
		};

		var ev;
		for ( var i = 0; i < arglist.length; i++ ) {
			if ( typeof arglist[ i ] === "string" ) {
				ev = arglist[ i ];

				addEvDefault( ev, _getEventListener( ev, removeEvDefault ) );

				events.count.pending++;
				events.pending[ ev ] = 1;
			} else if ( arglist[ i ] instanceof Array ) {
				if( arglist[ i ][3] ) {
					if( arglist[ i ][1] ) addEvDefault    = _bind( arglist[ i ][1], arglist[ i ][3] );
					if( arglist[ i ][2] ) removeEvDefault = _bind( arglist[ i ][2], arglist[ i ][3] );
				}
				ev = arglist[ i ][0];

				addEvDefault( ev, _getEventListener( ev, _bind( arglist[ i ][2], arglist[ i ][3] ) ) );

				events.count.pending++;
				events.pending[ ev ] = 1;
			} else {

			}
		}

		self.next( function( eventParam, setterParam, nextstep ) {
			self._signal.watch( signalid, function() { this.touch( signalid ); nextstep(); } );
		});

		return this;
	},
	getListener: function( setterParam ) {
		var self = this;
		var nextstep = function() {
			if ( self._queueIndex < self._queue.length ) {
				var eventParam = arguments;
				self._queueIndex++;
				self._lastreturned = self._queue[ self._queueIndex - 1 ](
					eventParam, setterParam, nextstep, self._lastreturned );
			}
		};

		return nextstep;
	},
	go: function(){
		this.getListener()();
		return this;
	}
};

/* Usage:
	var next = new Next;
	next.next( function( eventParam, setterParam, listener ) {
		//...your codes here.
		setterParam[0] === 1; //true
		listener();
	}).next( function( eventParam, setterParam, listener ) {
		//...your codes here.
		//listener();
	});
	$( sth ).on( 'someev', next.getListener( 1 ) );

	//or watching
 */
<commit_msg>next.js更新<commit_after>/* next.js
	Akiris 2016
	Ver. 1617
	Licensed under the MIT License.
*/

var Next = function(){
	if ( this === window ) {return new arguments.callee};
	this._signal = new Signal;
	return this;
};

var Signal = function() {
	return ( this === window ) ? ( new arguments.callee ) : this;
};

var _bind = function( func, thisObj ){
	return function() {
		var args = [].slice.call( arguments, 0 );
		func.apply( thisObj, args );
	};
};

Signal.prototype = {
	_storage: {},
	_callbacks: {},
	is: function( sig ) {
		return this._storage.hasOwnProperty( sig );
	},
	touch: function( sig ) {
		if ( this.is( sig ) ) {
			delete this._storage[ sig ];
			return true;
		} else return false;
	},
	send: function( sig ) {
		this._storage[ sig ] = 1;
		if ( this._callbacks[ sig ] ) {
			this.callback( sig );
		}
		return this;
	},
	watch: function( sig, callback ) {
		if( !this._callbacks[ sig ] ) this._callbacks[ sig ] = [];
		this._callbacks[ sig ].push( callback );

		if( this.is ( sig ) ) {
			this.callback( sig );
		}
		return this;
	},
	callback: function( sig ) {
		var self = this;
		for (var i = 0; i < this._callbacks[ sig ].length; i++) {
			this._callbacks[ sig ][ i ].call( self, sig );
		}
		delete this._callbacks[ sig ];
		return this;
	}

};

Next.prototype = {
	_queue: [],
	_queueIndex: 0,
	_lastreturned: null,
	_signal: null,
	next: function( func ) {
		this._queue.push( func );
		return this;
	},
	wait: function() {
		var signalid = Math.random().toString();
		var arglist = [].slice.call( arguments, 0 );
		var addEvDefault = _bind( document.addEventListener, document );
		var removeEvDefault = _bind( document.removeEventListener, document );
		var events = {
			count: {
				successed: 0,
				pending:0
			},
			successed: {},
			pending: {}
		};
		var self = this;
		var _getEventListener = function( ev, removeEvL ) {
			var func = function () {
				if ( events.pending[ ev ] ) {
					events.count.successed++;
					events.count.pending--;
					delete events.pending[ ev ];
					events.successed[ ev ] = arguments;
				}
				removeEvL( ev, func );
				if ( events.count.pending === 0 ) {
					//finally, ...
					//GC
					events = null;
					self._signal.send( signalid );
				}
			};
			return func;
		};

		var ev;
		for ( var i = 0; i < arglist.length; i++ ) {
			if ( typeof arglist[ i ] === "string" ) {
				ev = arglist[ i ];

				addEvDefault( ev, _getEventListener( ev, removeEvDefault ) );

				events.count.pending++;
				events.pending[ ev ] = 1;
			} else if ( arglist[ i ] instanceof Array ) {
				if( arglist[ i ][3] ) {
					if( arglist[ i ][1] ) addEvDefault    = _bind( arglist[ i ][1], arglist[ i ][3] );
					if( arglist[ i ][2] ) removeEvDefault = _bind( arglist[ i ][2], arglist[ i ][3] );
				}
				ev = arglist[ i ][0];

				addEvDefault( ev, _getEventListener( ev, _bind( arglist[ i ][2], arglist[ i ][3] ) ) );

				events.count.pending++;
				events.pending[ ev ] = 1;
			} else {

			}
		}

		self.next( function( eventParam, setterParam, nextstep ) {
			self._signal.watch( signalid, function() { this.touch( signalid ); nextstep(); } );
		});

		return this;
	},
	getRunnable: function( setterParam ) {
		var self = this;
		var nextstep = function() {
			if ( self._queueIndex < self._queue.length ) {
				var eventParam = arguments;
				self._queueIndex++;
				self._lastreturned = self._queue[ self._queueIndex - 1 ](
					eventParam, setterParam, nextstep, self._lastreturned );
			}
		};

		return nextstep;
	},
	go: function(){
		this.getRunnable()();
		return this;
	}
};

/* Usage:
	var next = new Next;
	next.next( function( eventParam, setterParam, next ) {
		//...your codes here.
		setterParam[0] === 1; //true
		next();
	}).next( function( eventParam, setterParam, next ) {
		//...your codes here.
		//next();
	});
	$( sth ).on( 'someev', next.getRunnable( 1 ) );

	//or watching
 */
<|endoftext|>


<commit_before>// @flow
import React from "react"
import { connect } from "react-redux"
import type { Dispatch } from "redux"

import Dialog from "../material/Dialog"
import Textfield from "../material/Textfield"
import Textarea from "../material/Textarea"

import { makeEmbedUrl, makeVideoUrl } from "../../lib/urls"
import { formatSecondsToMinutes } from "../../util/util"
import Checkbox from "../material/Checkbox"
import { actions } from "../../actions"
import type { VideoUiState } from "../../flow/videoTypes"

type DialogProps = {
  dispatch: Dispatch,
  videoUi: VideoUiState,
  open: boolean,
  hideDialog: Function,
  videoKey: string
}

class ShareVideoDialog extends React.Component<*, void> {
  props: DialogProps

  onChange = (event: Object) => {
    const { dispatch } = this.props
    dispatch(actions.videoUi.setShareVideoTimeEnabled(event.target.checked))
  }

  render() {
    const { open, hideDialog, videoKey, videoUi } = this.props
    const { shareVideoForm } = videoUi
    const startTime = videoUi.videoTime
    const startParam = shareVideoForm.shareTime ? `?start=${startTime}` : ""
    const videoShareUrl = `${window.location.origin}${makeVideoUrl(
      videoKey
    )}${startParam}`
    const videoEmbedUrl = `${window.location.origin}${makeEmbedUrl(
      videoKey
    )}${startParam}`
    return (
      <Dialog
        title="Share this Video"
        id="share-video-dialog"
        cancelText="Close"
        open={open}
        hideDialog={hideDialog}
        noSubmit={true}
      >

          <Textfield
            readOnly
            label="Video URL"
            id="video-url"
            value={videoShareUrl}
          />
          <Textarea
            readOnly
            label="Embed HTML"
            id="video-embed-code"
            rows="4"
            value={`<iframe src="${videoEmbedUrl}" width="560" height="315" frameborder="0" allowfullscreen></iframe>`}
          />
          <Checkbox
            label={`Start at ${formatSecondsToMinutes(startTime)}`}
            id="start-checkbox"
            value={startTime}
            onChange={this.onChange}
            className="wideLabel"
          />

      </Dialog>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  const { videoUi, collectionUi: { selectedVideoKey } } = state
  const { video } = ownProps

  // The dialog needs a video key passed in as a prop. Depending on the container that includes this dialog,
  // that video key can be retrieved in a couple different ways.
  const videoKey = video ? video.key : selectedVideoKey

  return {
    videoUi:  videoUi,
    videoKey: videoKey
  }
}

export default connect(mapStateToProps)(ShareVideoDialog)
<commit_msg>fix embded video not playing<commit_after>// @flow
import React from "react"
import { connect } from "react-redux"
import type { Dispatch } from "redux"

import Dialog from "../material/Dialog"
import Textfield from "../material/Textfield"
import Textarea from "../material/Textarea"

import { makeEmbedUrl, makeVideoUrl } from "../../lib/urls"
import { formatSecondsToMinutes } from "../../util/util"
import Checkbox from "../material/Checkbox"
import { actions } from "../../actions"
import type { VideoUiState } from "../../flow/videoTypes"

type DialogProps = {
  dispatch: Dispatch,
  videoUi: VideoUiState,
  open: boolean,
  hideDialog: Function,
  videoKey: string
}

class ShareVideoDialog extends React.Component<*, void> {
  props: DialogProps

  onChange = (event: Object) => {
    const { dispatch } = this.props
    dispatch(actions.videoUi.setShareVideoTimeEnabled(event.target.checked))
  }

  render() {
    const { open, hideDialog, videoKey, videoUi } = this.props
    const { shareVideoForm } = videoUi
    const startTime = videoUi.videoTime
    const startParam = shareVideoForm.shareTime ? `?start=${startTime}` : ""
    const videoShareUrl = `${window.location.origin}${makeVideoUrl(
      videoKey
    )}${startParam}`
    const videoEmbedUrl = `${window.location.origin}${makeEmbedUrl(
      videoKey
    )}${startParam}`
    return (
      <Dialog
        title="Share this Video"
        id="share-video-dialog"
        cancelText="Close"
        open={open}
        hideDialog={hideDialog}
        noSubmit={true}
      >

          <Textfield
            readOnly
            label="Video URL"
            id="video-url"
            value={videoShareUrl}
          />
          <Textarea
            readOnly
            label="Embed HTML"
            id="video-embed-code"
            rows="4"
            value={`<iframe src="${videoEmbedUrl}" width="560" height="315" frameborder="0" allow="autoplay" allowfullscreen></iframe>`}
          />
          <Checkbox
            label={`Start at ${formatSecondsToMinutes(startTime)}`}
            id="start-checkbox"
            value={startTime}
            onChange={this.onChange}
            className="wideLabel"
          />

      </Dialog>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  const { videoUi, collectionUi: { selectedVideoKey } } = state
  const { video } = ownProps

  // The dialog needs a video key passed in as a prop. Depending on the container that includes this dialog,
  // that video key can be retrieved in a couple different ways.
  const videoKey = video ? video.key : selectedVideoKey

  return {
    videoUi:  videoUi,
    videoKey: videoKey
  }
}

export default connect(mapStateToProps)(ShareVideoDialog)
<|endoftext|>


<commit_before>'use strict'

var K0 = 0.9996;

var E = 0.00669438;
var E2 = Math.pow(E, 2);
var E3 = Math.pow(E, 3);
var E_P2 = E / (1 - E);

var SQRT_E = Math.sqrt(1 - E);
var _E = (1 - SQRT_E) / (1 + SQRT_E);
var _E2 = Math.pow(_E, 2);
var _E3 = Math.pow(_E, 3);
var _E4 = Math.pow(_E, 4);
var _E5 = Math.pow(_E, 5);

var M1 = 1 - E / 4 - 3 * E2 / 64 - 5 * E3 / 256;
var M2 = 3 * E / 8 + 3 * E2 / 32 + 45 * E3 / 1024;
var M3 = 15 * E2 / 256 + 45 * E3 / 1024;
var M4 = 35 * E3 / 3072;

var P2 = 3 / 2 * _E - 27 / 32 * _E3 + 269 / 512 * _E5;
var P3 = 21 / 16 * _E2 - 55 / 32 * _E4;
var P4 = 151 / 96 * _E3 - 417 / 128 * _E5;
var P5 = 1097 / 512 * _E4;

var R = 6378137;

var ZONE_LETTERS_CONVERSION = {
  '':  84, X:  72, W:  64, V:  56, U:  48, T:  40, S:  32,
  R :  24, Q:  16, P:   8, N:   0, M:  -8, L: -16, K: -24,
  J : -32, H: -40, G: -48, F: -56, E: -64, D: -72, C: -80
};
var ZONE_LETTERS = [
  '',  'X', 'W', 'V', 'U', 'T', 'S',
  'R', 'Q', 'P', 'N', 'M', 'L', 'K',
  'J', 'H', 'G', 'F', 'E', 'D', 'C'
];

export function toLatLon(easting, northing, zoneNum, zoneLetter, northern) {
  zoneLetter = zoneLetter || '';
  northern = !!northern;
  if (!zoneLetter && !northern) {
    throw new Error('either zoneLetter or northern needs to be set');
  } else if (zoneLetter && northern) {
    throw new Error('set either zoneLetter or northern, but not both');
  }

  if (easting < 100000 || 1000000 <= easting) {
    throw new RangeError('easting out of range (must be between 100.000 m and 999.999 m)');
  }
  if (northing < 0 || northing > 10000000) {
    throw new RangeError('northing out of range (must be between 0 m and 10.000.000 m)');
  }
  if (zoneNum < 1 || zoneNum > 60) {
    throw new RangeError('zone number out of range (must be between 1 and 60)');
  }
  if (zoneLetter) {
    zoneLetter = zoneLetter.toUpperCase();
    if (!ZONE_LETTERS_CONVERSION[zoneLetter]) {
      throw new RangeError('zone letter out of range (must be between C and X)');
    }
    northern = ZONE_LETTERS_CONVERSION[zoneLetter];
  }

  var x = easting - 500000;
  var y = northing;

  if (!northern) y -= 1e7;

  var m = y / K0;
  var mu = m / (R * M1);

  var pRad = mu +
             P2 * Math.sin(2 * mu) +
             P3 * Math.sin(4 * mu) +
             P4 * Math.sin(6 * mu) +
             P5 * Math.sin(8 * mu);

  var pSin = Math.sin(pRad);
  var pSin2 = Math.pow(pSin, 2);

  var pCos = Math.cos(pRad);

  var pTan = Math.tan(pRad);
  var pTan2 = Math.pow(pTan, 2);
  var pTan4 = Math.pow(pTan, 4);

  var epSin = 1 - E * pSin2;
  var epSinSqrt = Math.sqrt(epSin);

  var n = R / epSinSqrt;
  var r = (1 - E) / epSin;

  var c = _E * pCos * pCos;
  var c2 = c * c;

  var d = x / (n * K0);
  var d2 = Math.pow(d, 2);
  var d3 = Math.pow(d, 3);
  var d4 = Math.pow(d, 4);
  var d5 = Math.pow(d, 5);
  var d6 = Math.pow(d, 6);

  var latitude = pRad - (pTan / r) *
                 (d2 / 2 -
                  d4 / 24 * (5 + 3 * pTan2 + 10 * c - 4 * c2 - 9 * E_P2)) +
                  d6 / 720 * (61 + 90 * pTan2 + 298 * c + 45 * pTan4 - 252 * E_P2 - 3 * c2);
  var longitude = (d -
                   d3 / 6 * (1 + 2 * pTan2 + c) +
                   d5 / 120 * (5 - 2 * c + 28 * pTan2 - 3 * c2 + 8 * E_P2 + 24 * pTan4)) / pCos;

  return {
    latitude: toDegrees(latitude),
    longitude: toDegrees(longitude) + zoneNumberToCentralLongitude(zoneNum)
  };
}

export function fromLatLon(latitude, longitude, zoneNum) {
  if (latitude > 84 || latitude < -80) {
    throw new RangeError('latitude out of range (must be between 80 deg S and 84 deg N)');
  }
  if (longitude > 180 || longitude < -180) {
    throw new RangeError('longitude out of range (must be between 180 deg W and 180 deg E)');
  }

  var latRad = toRadians(latitude);
  var latSin = Math.sin(latRad);
  var latCos = Math.cos(latRad);

  var latTan = Math.tan(latRad);
  var latTan2 = Math.pow(latTan, 2);
  var latTan4 = Math.pow(latTan, 4);

  if (zoneNum === undefined) {
    zoneNum = latLonToZoneNumber(latitude, longitude);
  }

  var zoneLetter = latitudeToZoneLetter(latitude);

  var lonRad = toRadians(longitude);
  var centralLon = zoneNumberToCentralLongitude(zoneNum);
  var centralLonRad = toRadians(centralLon);

  var n = R / Math.sqrt(1 - E * latSin * latSin);
  var c = E_P2 * latCos * latCos;

  var a = latCos * (lonRad - centralLonRad);
  var a2 = Math.pow(a, 2);
  var a3 = Math.pow(a, 3);
  var a4 = Math.pow(a, 4);
  var a5 = Math.pow(a, 5);
  var a6 = Math.pow(a, 6);

  var m = R * (M1 * latRad -
               M2 * Math.sin(2 * latRad) +
               M3 * Math.sin(4 * latRad) -
               M4 * Math.sin(6 * latRad));
  var easting = K0 * n * (a +
                          a3 / 6 * (1 - latTan2 + c) +
                          a5 / 120 * (5 - 18 * latTan2 + latTan4 + 72 * c - 58 * E_P2)) + 500000;
  var northing = K0 * (m + n * latTan * (a2 / 2 +
                                         a4 / 24 * (5 - latTan2 + 9 * c + 4 * c * c) +
                                         a6 / 720 * (61 - 58 * latTan2 + latTan4 + 600 * c - 330 * E_P2)));
  if (latitude < 0) northing += 1e7;

  return {
    easting: easting,
    northing: northing,
    zoneNum: zoneNum,
    zoneLetter: zoneLetter
  };
}

function latitudeToZoneLetter (latitude) {
  for (var i = 0; i < ZONE_LETTERS.length; i++) {
    var letter = ZONE_LETTERS[i];
    if (latitude >= ZONE_LETTERS_CONVERSION[letter]) return letter;
  }
}

function latLonToZoneNumber (latitude, longitude) {
  if (56 <= latitude && latitude < 64 && 3 <= longitude && longitude < 12) return 32;

  if (72 <= latitude && latitude <= 84 && longitude >= 0) {
    if (longitude <=  9) return 31;
    if (longitude <= 21) return 33;
    if (longitude <= 33) return 35;
    if (longitude <= 42) return 37;
  }

  return ((longitude + 180) / 6 | 0) + 1;
}

function zoneNumberToCentralLongitude (zoneNum) {
  return (zoneNum - 1) * 6 - 180 + 3;
}

function toDegrees (rad) {
  return rad / Math.PI * 180;
}

function toRadians (deg) {
  return deg * Math.PI / 180;
}
<commit_msg>Update from Python upstream<commit_after>'use strict'

var K0 = 0.9996;

var E = 0.00669438;
var E2 = Math.pow(E, 2);
var E3 = Math.pow(E, 3);
var E_P2 = E / (1 - E);

var SQRT_E = Math.sqrt(1 - E);
var _E = (1 - SQRT_E) / (1 + SQRT_E);
var _E2 = Math.pow(_E, 2);
var _E3 = Math.pow(_E, 3);
var _E4 = Math.pow(_E, 4);
var _E5 = Math.pow(_E, 5);

var M1 = 1 - E / 4 - 3 * E2 / 64 - 5 * E3 / 256;
var M2 = 3 * E / 8 + 3 * E2 / 32 + 45 * E3 / 1024;
var M3 = 15 * E2 / 256 + 45 * E3 / 1024;
var M4 = 35 * E3 / 3072;

var P2 = 3 / 2 * _E - 27 / 32 * _E3 + 269 / 512 * _E5;
var P3 = 21 / 16 * _E2 - 55 / 32 * _E4;
var P4 = 151 / 96 * _E3 - 417 / 128 * _E5;
var P5 = 1097 / 512 * _E4;

var R = 6378137;

var ZONE_LETTERS = 'CDEFGHJKLMNPQRSTUVWXX';

export function toLatLon(easting, northing, zoneNum, zoneLetter, northern) {
  if (!zoneLetter && northern === undefined) {
    throw new Error('either zoneLetter or northern needs to be set');
  } else if (zoneLetter && northern !== undefined) {
    throw new Error('set either zoneLetter or northern, but not both');
  }

  if (easting < 100000 || 1000000 <= easting) {
    throw new RangeError('easting out of range (must be between 100.000 m and 999.999 m)');
  }
  if (northing < 0 || northing > 10000000) {
    throw new RangeError('northing out of range (must be between 0 m and 10.000.000 m)');
  }
  if (zoneNum < 1 || zoneNum > 60) {
    throw new RangeError('zone number out of range (must be between 1 and 60)');
  }
  if (zoneLetter) {
    zoneLetter = zoneLetter.toUpperCase();
    if (zoneLetter.length !== 1 || ZONE_LETTERS.indexOf(zoneLetter) === -1) {
      throw new RangeError('zone letter out of range (must be between C and X)');
    }
    northern = zoneLetter >= 'N';
  }

  var x = easting - 500000;
  var y = northing;

  if (!northern) y -= 1e7;

  var m = y / K0;
  var mu = m / (R * M1);

  var pRad = mu +
             P2 * Math.sin(2 * mu) +
             P3 * Math.sin(4 * mu) +
             P4 * Math.sin(6 * mu) +
             P5 * Math.sin(8 * mu);

  var pSin = Math.sin(pRad);
  var pSin2 = Math.pow(pSin, 2);

  var pCos = Math.cos(pRad);

  var pTan = Math.tan(pRad);
  var pTan2 = Math.pow(pTan, 2);
  var pTan4 = Math.pow(pTan, 4);

  var epSin = 1 - E * pSin2;
  var epSinSqrt = Math.sqrt(epSin);

  var n = R / epSinSqrt;
  var r = (1 - E) / epSin;

  var c = _E * pCos * pCos;
  var c2 = c * c;

  var d = x / (n * K0);
  var d2 = Math.pow(d, 2);
  var d3 = Math.pow(d, 3);
  var d4 = Math.pow(d, 4);
  var d5 = Math.pow(d, 5);
  var d6 = Math.pow(d, 6);

  var latitude = pRad - (pTan / r) *
                 (d2 / 2 -
                  d4 / 24 * (5 + 3 * pTan2 + 10 * c - 4 * c2 - 9 * E_P2)) +
                  d6 / 720 * (61 + 90 * pTan2 + 298 * c + 45 * pTan4 - 252 * E_P2 - 3 * c2);
  var longitude = (d -
                   d3 / 6 * (1 + 2 * pTan2 + c) +
                   d5 / 120 * (5 - 2 * c + 28 * pTan2 - 3 * c2 + 8 * E_P2 + 24 * pTan4)) / pCos;

  return {
    latitude: toDegrees(latitude),
    longitude: toDegrees(longitude) + zoneNumberToCentralLongitude(zoneNum)
  };
}

export function fromLatLon(latitude, longitude, forceZoneNum) {
  if (latitude > 84 || latitude < -80) {
    throw new RangeError('latitude out of range (must be between 80 deg S and 84 deg N)');
  }
  if (longitude > 180 || longitude < -180) {
    throw new RangeError('longitude out of range (must be between 180 deg W and 180 deg E)');
  }

  var latRad = toRadians(latitude);
  var latSin = Math.sin(latRad);
  var latCos = Math.cos(latRad);

  var latTan = Math.tan(latRad);
  var latTan2 = Math.pow(latTan, 2);
  var latTan4 = Math.pow(latTan, 4);

  var zoneNum;

  if (forceZoneNum === undefined) {
    zoneNum = latLonToZoneNumber(latitude, longitude);
  } else {
    zoneNum = forceZoneNum;
  }

  var zoneLetter = latitudeToZoneLetter(latitude);

  var lonRad = toRadians(longitude);
  var centralLon = zoneNumberToCentralLongitude(zoneNum);
  var centralLonRad = toRadians(centralLon);

  var n = R / Math.sqrt(1 - E * latSin * latSin);
  var c = E_P2 * latCos * latCos;

  var a = latCos * (lonRad - centralLonRad);
  var a2 = Math.pow(a, 2);
  var a3 = Math.pow(a, 3);
  var a4 = Math.pow(a, 4);
  var a5 = Math.pow(a, 5);
  var a6 = Math.pow(a, 6);

  var m = R * (M1 * latRad -
               M2 * Math.sin(2 * latRad) +
               M3 * Math.sin(4 * latRad) -
               M4 * Math.sin(6 * latRad));
  var easting = K0 * n * (a +
                          a3 / 6 * (1 - latTan2 + c) +
                          a5 / 120 * (5 - 18 * latTan2 + latTan4 + 72 * c - 58 * E_P2)) + 500000;
  var northing = K0 * (m + n * latTan * (a2 / 2 +
                                         a4 / 24 * (5 - latTan2 + 9 * c + 4 * c * c) +
                                         a6 / 720 * (61 - 58 * latTan2 + latTan4 + 600 * c - 330 * E_P2)));
  if (latitude < 0) northing += 1e7;

  return {
    easting: easting,
    northing: northing,
    zoneNum: zoneNum,
    zoneLetter: zoneLetter
  };
}

function latitudeToZoneLetter (latitude) {
  if (-80 <= latitude && latitude <= 84) {
    return ZONE_LETTERS[(latitude + 80) >>> 3];
  } else {
    return null;
  }
}

function latLonToZoneNumber (latitude, longitude) {
  if (56 <= latitude && latitude < 64 && 3 <= longitude && longitude < 12) return 32;

  if (72 <= latitude && latitude <= 84 && longitude >= 0) {
    if (longitude <=  9) return 31;
    if (longitude <= 21) return 33;
    if (longitude <= 33) return 35;
    if (longitude <= 42) return 37;
  }

  return ((longitude + 180) / 6 | 0) + 1;
}

function zoneNumberToCentralLongitude (zoneNum) {
  return (zoneNum - 1) * 6 - 180 + 3;
}

function toDegrees (rad) {
  return rad / Math.PI * 180;
}

function toRadians (deg) {
  return deg * Math.PI / 180;
}
<|endoftext|>


<commit_before>var fs = require('fs')
  , name = 'docs/index.html'
  , rep = {
      'http://documentup.com/stylesheets/screen.css': '/stylesheets/main.css',
      '': '',
      '
': '

Blog

Twitter
'
    };

fs.readFile(name, function (err, buf) {
  if (err) throw err;
  buf = buf.toString();
  for (var k in rep) buf = buf.replace(k, rep[k]);
  fs.writeFile(name, buf);
});<commit_msg>Adding a link to tests in docs<commit_after>var fs = require('fs')
  , name = 'docs/index.html'
  , rep = {
      'http://documentup.com/stylesheets/screen.css': '/stylesheets/main.css',
      '': '',
      '
': '

Blog

Twitter

Tests
'
    };

fs.readFile(name, function (err, buf) {
  if (err) throw err;
  buf = buf.toString();
  for (var k in rep) buf = buf.replace(k, rep[k]);
  fs.writeFile(name, buf);
});<|endoftext|>


<commit_before>angular.module('docs', ['ngRoute', 'templates-docs', 'audioPlayer'])

// Definition of all examples as an hash
.constant('exampleHash', {
  '': {
    displayName: 'Getting Started',
    templateUrl: 'docs.md.tpl.html'
  },
  'progressive-playlist': {
    displayName: 'Progressive Playlist',
    templateUrl: 'examples/progressive-playlist.tpl.html',
    controller: 'ProgressiveController'
  },
  'populate-playlist': {
    displayName: 'Self-populating playlist',
    templateUrl: 'examples/populate-playlist.tpl.html',
    controller: 'PopulateController'
  },
  'swap-playlist': {
    displayName: 'Swap Audio during play',
    templateUrl: 'examples/swap-playlist.tpl.html',
    controller: 'SwapController'
  },
  'interactive-demo': {
    displayName: 'Interactive Demo',
    templateUrl: 'examples/interactive.tpl.html',
    controller: 'InteractiveController'
  },
  'repeat-audio': {
    displayName: 'Using ng-repeat',
    templateUrl: 'examples/repeat-audio.tpl.html',
    controller: 'RepeatController'
  }
})

.config(function ($routeProvider, $locationProvider, exampleHash) {
  var example;
  $routeProvider.when(null, { redirectTo: '/' });
  // For each examples in list, new urls gets created.
  for (example in exampleHash) {
    $routeProvider.when('/' + example, {
      templateUrl: exampleHash[example].templateUrl,
      controller: exampleHash[example].controller
    });
  }

  // Hashbang for searchbot indexing
  $locationProvider.hashPrefix('!');
})

.run(function ($rootScope, $window) {
  // google analitics
  $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
    if (current.$$route.originalPath) {
      $window._gaq.push(['_trackPageview', current.$$route.originalPath]);
    }
  });
})

.controller('BodyController', function ($scope, $route, exampleHash) {
  $scope.route = $route;
  $scope.exampleHash = exampleHash;

  // Utility function to return a boolean value wheter the current route has a certain path
  $scope.currentRoute = function (urlToMatch) {
    if (!urlToMatch) { // in case undefined or null, it returns the displayName of the route
      return (this.route.current) ? exampleHash[this.route.current.$$route.originalPath.substring(1)].displayName : null;
    }
    return (this.route.current) && this.route.current.$$route.originalPath === '/' + urlToMatch;
  };
});
<commit_msg>fix(docs): currentRoute function is more robust now<commit_after>angular.module('docs', ['ngRoute', 'templates-docs', 'audioPlayer'])

// Definition of all examples as an hash
.constant('exampleHash', {
  '': {
    displayName: 'Getting Started',
    templateUrl: 'docs.md.tpl.html'
  },
  'progressive-playlist': {
    displayName: 'Progressive Playlist',
    templateUrl: 'examples/progressive-playlist.tpl.html',
    controller: 'ProgressiveController'
  },
  'populate-playlist': {
    displayName: 'Self-populating playlist',
    templateUrl: 'examples/populate-playlist.tpl.html',
    controller: 'PopulateController'
  },
  'swap-playlist': {
    displayName: 'Swap Audio during play',
    templateUrl: 'examples/swap-playlist.tpl.html',
    controller: 'SwapController'
  },
  'interactive-demo': {
    displayName: 'Interactive Demo',
    templateUrl: 'examples/interactive.tpl.html',
    controller: 'InteractiveController'
  },
  'repeat-audio': {
    displayName: 'Using ng-repeat',
    templateUrl: 'examples/repeat-audio.tpl.html',
    controller: 'RepeatController'
  }
})

.config(function ($routeProvider, $locationProvider, exampleHash) {
  var example;
  $routeProvider.when(null, { redirectTo: '/' });
  // For each examples in list, new urls gets created.
  for (example in exampleHash) {
    $routeProvider.when('/' + example, {
      templateUrl: exampleHash[example].templateUrl,
      controller: exampleHash[example].controller
    });
  }

  // Hashbang for searchbot indexing
  $locationProvider.hashPrefix('!');
})

.run(function ($rootScope, $window) {
  // google analitics
  $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
    if (current.$$route.originalPath) {
      $window._gaq.push(['_trackPageview', current.$$route.originalPath]);
    }
  });
})

.controller('BodyController', function ($scope, $route, exampleHash) {
  $scope.route = $route;
  $scope.exampleHash = exampleHash;

  // Utility function to return a boolean value wheter the current route has a certain path
  $scope.currentRoute = function (urlToMatch) {
    if (urlToMatch === undefined || urlToMatch === null) { // in case undefined or null, it returns the displayName of the route
      return (this.route.current) ? exampleHash[this.route.current.$$route.originalPath.substring(1)].displayName : null;
    }
    return (this.route.current) && this.route.current.$$route.originalPath === '/' + urlToMatch;
  };
});
<|endoftext|>


<commit_before>var extend = require('./utils').extend;
var crypto = require('crypto');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var WebSocketConnection = require('./WebSocketConnection');

var headerValueSplitRegExp = /,\s*/;
var headerParamSplitRegExp = /;\s*/;
var headerSanitizeRegExp = /[\r\n]/g;
var protocolSeparators = [
	"(", ")", "<", ">", "@",
	",", ";", ":", "\\", "\"",
	"/", "[", "]", "?", "=",
	"{", "}", " ", String.fromCharCode(9)
];

var httpStatusDescriptions = {
    100: "Continue",
    101: "Switching Protocols",
    200: "OK",
    201: "Created",
    203: "Non-Authoritative Information",
    204: "No Content",
    205: "Reset Content",
    206: "Partial Content",
    300: "Multiple Choices",
    301: "Moved Permanently",
    302: "Found",
    303: "See Other",
    304: "Not Modified",
    305: "Use Proxy",
    307: "Temporary Redirect",
    400: "Bad Request",
    401: "Unauthorized",
    402: "Payment Required",
    403: "Forbidden",
    404: "Not Found",
    406: "Not Acceptable",
    407: "Proxy Authorization Required",
    408: "Request Timeout",
    409: "Conflict",
    410: "Gone",
    411: "Length Required",
    412: "Precondition Failed",
    413: "Request Entity Too Long",
    414: "Request-URI Too Long",
    415: "Unsupported Media Type",
    416: "Requested Range Not Satisfiable",
    417: "Expectation Failed",
    500: "Internal Server Error",
    501: "Not Implemented",
    502: "Bad Gateway",
    503: "Service Unavailable",
    504: "Gateway Timeout",
    505: "HTTP Version Not Supported"
};

function WebSocketRequest(socket, httpRequest, serverConfig) {
    this.socket = socket;
    this.resource = httpRequest.url;
    this.remoteAddress = socket.remoteAddress;
    this.serverConfig = serverConfig;
};

util.inherits(WebSocketRequest, EventEmitter);

extend(WebSocketRequest.prototype, {
    readHandshake: function(request) {
        if (!request.headers['host']) {
            throw new Error("Client must provide a Host header.");
        }

        this.key = request.headers['sec-websocket-key'];
        if (!this.key) {
            throw new Error("Client must provide a value for Sec-WebSocket-Key.");
        }

        this.origin = request.headers['sec-websocket-origin'];

        this.websocketVersion = request.headers['sec-websocket-version'];
        if (!this.websocketVersion) {
            throw new Error("Client must provide a value for Sec-WebSocket-Version.");
        }
        if (this.websocketVersion !== '8') {
            throw new Error("Unsupported websocket client version.  Client requested version " + this.websocketVersion + ", but we only support version 8.");
        }

        // Protocol is optional.
        var protocolString = request.headers['sec-websocket-protocol'];
        if (protocolString) {
            this.requestedProtocols = protocolString.toLocaleLowerCase().split(headerValueSplitRegExp);
        }
        else {
            this.requestedProtocols = [];
        }

        if (request.headers['x-forwarded-for']) {
            this.remoteAddress = request.headers['x-forwarded-for'].split(', ')[0];
        }

        // Extensions are optional.
        var extensionsString = request.headers['sec-websocket-extensions'];
        this.requestedExtensions = this.parseExtensions(extensionsString);
    },
    parseExtensions: function(extensionsString) {
        if (!extensionsString || extensionsString.length === 0) {
            return [];
        }
        extensions = extensionsString.toLocaleLowerCase().split(headerValueSplitRegExp);
        extensions.forEach(function(extension, index, array) {
            var params = extension.split(headerParamSplitRegExp);
            var extensionName = params[0];
            var extensionParams = params.slice(1);
            extensionParams.forEach(function(rawParam, index, array) {
                var arr = rawParam.split('=');
                var obj = {
                    name: arr[0],
                    value: arr[1]
                };
                array.splice(index, 1, obj);
            });
            var obj = {
                name: extensionName,
                params: extensionParams
            };
            array.splice(index, 1, obj);
        });
        return extensions;
    },
    accept: function(acceptedProtocol, allowedOrigin) {
        // TODO: Handle extensions
        var connection = new WebSocketConnection(this.socket, [], acceptedProtocol, false, this.serverConfig);

        connection.remoteAddress = this.remoteAddress;

        // Create key validation hash
        var sha1 = crypto.createHash('sha1');
        sha1.update(this.key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
        var acceptKey = sha1.digest('base64');

        var response = "HTTP/1.1 101 Switching Protocols\r\n" +
                       "Upgrade: websocket\r\n" +
                       "Connection: Upgrade\r\n" +
                       "Sec-WebSocket-Accept: " + acceptKey + "\r\n";
        if (acceptedProtocol) {
            // validate protocol
			for (var i=0; i < acceptedProtocol.length; i++) {
				var charCode = acceptedProtocol.charCodeAt(i);
				var character = acceptedProtocol.charAt(i);
				if (charCode < 0x21 || charCode > 0x7E || protocolSeparators.indexOf(character) !== -1) {
				    this.reject(500);
					throw new Error("Illegal character '" + String.fromCharCode(character) + "' in subprotocol.");
				}
			}
			if (this.requestedProtocols.indexOf(acceptedProtocol) === -1) {
			    this.reject(500);
			    throw new Error("Specified protocol was not requested by the client.");
			}

            acceptedProtocol = acceptedProtocol.replace(headerSanitizeRegExp, '');
            response += "Sec-WebSocket-Protocol: " + acceptedProtocol + "\r\n";
        }
        if (allowedOrigin) {
            allowedOrigin = allowedOrigin.replace(headerSanitizeRegExp, '');
            response += "Sec-WebSocket-Origin: " + allowedOrigin + "\r\n";
        }
        // TODO: handle negotiated extensions
        // if (negotiatedExtensions) {
        //     response += "Sec-WebSocket-Extensions: " + negotiatedExtensions.join(", ") + "\r\n";
        // }
        response += "\r\n";

        this.socket.write(response, 'ascii');

        this.emit('requestAccepted', connection);

        return connection;
    },
    reject: function(status, reason) {
        if (typeof(status) !== 'number') {
            status = 400;
        }
        var response = "HTTP/1.1 " + status + " " + httpStatusDescriptions[status] + "\r\n" +
                       "Connection: close\r\n";
        if (reason) {
            reason = reason.replace(headerSanitizeRegExp, '');
            response += "X-WebSocket-Reject-Reason: " + reason + "\r\n";
        }
        response += "\r\n";
        this.socket.end(response, 'ascii');

        this.emit('requestRejected', this);
    }
});

module.exports = WebSocketRequest;<commit_msg>Updating handshake error handling to conform to draft-09<commit_after>var extend = require('./utils').extend;
var crypto = require('crypto');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var WebSocketConnection = require('./WebSocketConnection');

var headerValueSplitRegExp = /,\s*/;
var headerParamSplitRegExp = /;\s*/;
var headerSanitizeRegExp = /[\r\n]/g;
var protocolSeparators = [
	"(", ")", "<", ">", "@",
	",", ";", ":", "\\", "\"",
	"/", "[", "]", "?", "=",
	"{", "}", " ", String.fromCharCode(9)
];

var httpStatusDescriptions = {
    100: "Continue",
    101: "Switching Protocols",
    200: "OK",
    201: "Created",
    203: "Non-Authoritative Information",
    204: "No Content",
    205: "Reset Content",
    206: "Partial Content",
    300: "Multiple Choices",
    301: "Moved Permanently",
    302: "Found",
    303: "See Other",
    304: "Not Modified",
    305: "Use Proxy",
    307: "Temporary Redirect",
    400: "Bad Request",
    401: "Unauthorized",
    402: "Payment Required",
    403: "Forbidden",
    404: "Not Found",
    406: "Not Acceptable",
    407: "Proxy Authorization Required",
    408: "Request Timeout",
    409: "Conflict",
    410: "Gone",
    411: "Length Required",
    412: "Precondition Failed",
    413: "Request Entity Too Long",
    414: "Request-URI Too Long",
    415: "Unsupported Media Type",
    416: "Requested Range Not Satisfiable",
    417: "Expectation Failed",
    426: "Upgrade Required",
    500: "Internal Server Error",
    501: "Not Implemented",
    502: "Bad Gateway",
    503: "Service Unavailable",
    504: "Gateway Timeout",
    505: "HTTP Version Not Supported"
};

function WebSocketRequest(socket, httpRequest, serverConfig) {
    this.socket = socket;
    this.resource = httpRequest.url;
    this.remoteAddress = socket.remoteAddress;
    this.serverConfig = serverConfig;
};

util.inherits(WebSocketRequest, EventEmitter);

extend(WebSocketRequest.prototype, {
    readHandshake: function(request) {
        if (!request.headers['host']) {
            throw new Error("Client must provide a Host header.");
        }

        this.key = request.headers['sec-websocket-key'];
        if (!this.key) {
            this.reject(400, "Client must provide a value for Sec-WebSocket-Key.");
            throw new Error("Client must provide a value for Sec-WebSocket-Key.");
        }

        this.origin = request.headers['sec-websocket-origin'];

        this.websocketVersion = request.headers['sec-websocket-version'];
        if (!this.websocketVersion) {
            this.reject(400, "Client must provide a value for Sec-WebSocket-Version.");
            throw new Error("Client must provide a value for Sec-WebSocket-Version.");
        }
        if (this.websocketVersion !== '8') {
            this.reject(426, "Unsupported websocket client version.", {
                "Sec-WebSocket-Version": "8"
            });
            throw new Error("Unsupported websocket client version.  Client requested version " + this.websocketVersion + ", but we only support version 8.");
        }

        // Protocol is optional.
        var protocolString = request.headers['sec-websocket-protocol'];
        if (protocolString) {
            this.requestedProtocols = protocolString.toLocaleLowerCase().split(headerValueSplitRegExp);
        }
        else {
            this.requestedProtocols = [];
        }

        if (request.headers['x-forwarded-for']) {
            this.remoteAddress = request.headers['x-forwarded-for'].split(', ')[0];
        }

        // Extensions are optional.
        var extensionsString = request.headers['sec-websocket-extensions'];
        this.requestedExtensions = this.parseExtensions(extensionsString);
    },
    parseExtensions: function(extensionsString) {
        if (!extensionsString || extensionsString.length === 0) {
            return [];
        }
        extensions = extensionsString.toLocaleLowerCase().split(headerValueSplitRegExp);
        extensions.forEach(function(extension, index, array) {
            var params = extension.split(headerParamSplitRegExp);
            var extensionName = params[0];
            var extensionParams = params.slice(1);
            extensionParams.forEach(function(rawParam, index, array) {
                var arr = rawParam.split('=');
                var obj = {
                    name: arr[0],
                    value: arr[1]
                };
                array.splice(index, 1, obj);
            });
            var obj = {
                name: extensionName,
                params: extensionParams
            };
            array.splice(index, 1, obj);
        });
        return extensions;
    },
    accept: function(acceptedProtocol, allowedOrigin) {
        // TODO: Handle extensions
        var connection = new WebSocketConnection(this.socket, [], acceptedProtocol, false, this.serverConfig);

        connection.remoteAddress = this.remoteAddress;

        // Create key validation hash
        var sha1 = crypto.createHash('sha1');
        sha1.update(this.key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
        var acceptKey = sha1.digest('base64');

        var response = "HTTP/1.1 101 Switching Protocols\r\n" +
                       "Upgrade: websocket\r\n" +
                       "Connection: Upgrade\r\n" +
                       "Sec-WebSocket-Accept: " + acceptKey + "\r\n";
        if (acceptedProtocol) {
            // validate protocol
			for (var i=0; i < acceptedProtocol.length; i++) {
				var charCode = acceptedProtocol.charCodeAt(i);
				var character = acceptedProtocol.charAt(i);
				if (charCode < 0x21 || charCode > 0x7E || protocolSeparators.indexOf(character) !== -1) {
				    this.reject(500);
					throw new Error("Illegal character '" + String.fromCharCode(character) + "' in subprotocol.");
				}
			}
			if (this.requestedProtocols.indexOf(acceptedProtocol) === -1) {
			    this.reject(500);
			    throw new Error("Specified protocol was not requested by the client.");
			}

            acceptedProtocol = acceptedProtocol.replace(headerSanitizeRegExp, '');
            response += "Sec-WebSocket-Protocol: " + acceptedProtocol + "\r\n";
        }
        if (allowedOrigin) {
            allowedOrigin = allowedOrigin.replace(headerSanitizeRegExp, '');
            response += "Sec-WebSocket-Origin: " + allowedOrigin + "\r\n";
        }
        // TODO: handle negotiated extensions
        // if (negotiatedExtensions) {
        //     response += "Sec-WebSocket-Extensions: " + negotiatedExtensions.join(", ") + "\r\n";
        // }
        response += "\r\n";

        this.socket.write(response, 'ascii');

        this.emit('requestAccepted', connection);

        return connection;
    },
    reject: function(status, reason, extraHeaders) {
        if (typeof(status) !== 'number') {
            status = 403;
        }
        var response = "HTTP/1.1 " + status + " " + httpStatusDescriptions[status] + "\r\n" +
                       "Connection: close\r\n";
        if (reason) {
            reason = reason.replace(headerSanitizeRegExp, '');
            response += "X-WebSocket-Reject-Reason: " + reason + "\r\n";
        }

        if (extraHeaders) {
            for (var key in extraHeaders) {
                var sanitizedValue = extraHeaders[key].toString().replace(headerSanitizeRegExp, '');
                var sanitizedKey = key.replace(headerSanitizeRegExp, '');
                response += (key + ": " + sanitizedValue + "\r\n");
            }
        }

        response += "\r\n";
        this.socket.end(response, 'ascii');

        this.emit('requestRejected', this);
    }
});

module.exports = WebSocketRequest;<|endoftext|>


<commit_before>/** @babel */

import {View} from 'atom-space-pen-views'
import {CompositeDisposable} from 'atom'

export default class AboutStatusBar extends View {
  static content () {
    return this.span({type: 'button', class: 'about-release-notes icon icon-squirrel inline-block'})
  }

  constructor () {
    super()

    this.subscriptions = new CompositeDisposable()

    this.on('click', () => {
      atom.workspace.open('atom://about')
    })

    this.subscriptions.add(atom.tooltips.add(this.element, {title: 'An update will be installed the next time Atom is relaunched.

Click the squirrel icon to view release notes.'}))
  }

  detached () {
    this.subscriptions.dispose()
  }
}
<commit_msg>Copy change<commit_after>/** @babel */

import {View} from 'atom-space-pen-views'
import {CompositeDisposable} from 'atom'

export default class AboutStatusBar extends View {
  static content () {
    return this.span({type: 'button', class: 'about-release-notes icon icon-squirrel inline-block'})
  }

  constructor () {
    super()

    this.subscriptions = new CompositeDisposable()

    this.on('click', () => {
      atom.workspace.open('atom://about')
    })

    this.subscriptions.add(atom.tooltips.add(this.element, {title: 'An update will be installed the next time Atom is relaunched.

Click the squirrel icon for more information.'}))
  }

  detached () {
    this.subscriptions.dispose()
  }
}
<|endoftext|>