Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

refactor rserve.js out of rclient.js

  • Loading branch information...
commit 4de8ffc4d266fa5ae3cd2a3f7dc6886005ec14b4 1 parent 479bb72
Carlos Scheidegger authored
View
5 htdocs/js/Makefile
@@ -6,12 +6,9 @@ rcloud_bundle.js: \
chart.js \
facet_chart.js \
websockets.js \
+ rserve.js \
rclient.js \
buffer.js \
- parse.js \
- peg_parser.js \
- objs.js \
- Rsrv.js \
rcloud.js \
notebook/_begin.js \
notebook/cell/_begin.js \
View
10 htdocs/js/parse.js
@@ -111,7 +111,7 @@ function reader(m)
l -= attr_result[1];
}
if (handlers[t] === undefined) {
- throw "Unimplemented " + t;
+ throw ["Unimplemented " + t, -1];
} else {
var result = handlers[t].call(this, attributes, l);
return [result[0], total_read + result[1]];
@@ -134,7 +134,7 @@ function reader(m)
for (var i=0; i<lst.length; i+=2) {
var value = lst[i], tag = lst[i+1];
if (tag.type !== "symbol")
- throw "Unexpected type " + tag.type + " as tag for tagged_list";
+ throw ["Unexpected type " + tag.type + " as tag for tagged_list", -1];
result[tag.value] = value;
}
return Robj.tagged_list(result, attributes);
@@ -177,12 +177,12 @@ function parse(msg)
var header = new Int32Array(msg, 0, 4);
if (header[0] !== Rsrv.RESP_OK && header[0] !== Rsrv.OOB_SEND) {
var status_code = header[0] >> 24;
- throw("ERROR FROM R SERVER: " + (Rsrv.status_codes[status_code] ||
+ throw ["ERROR FROM R SERVER: " + (Rsrv.status_codes[status_code] ||
status_code)
+ " " + header[0] + " " + header[1] + " " + header[2] + " " + header[3]
+ " " + msg.byteLength
- + " " + msg
- ); // not too helpful, but better than undefined
+ + " " + msg,
+ status_code];
}
var payload = my_ArrayBufferView(msg, 16, msg.byteLength - 16);
View
189 htdocs/js/rclient.js
@@ -14,104 +14,68 @@ function escape_r_literal_string(s) {
// return "\"" + s.replace(/"/g, "\\\"") + "\"";
}
-RClient = {
- create: function(opts) {
- var host = opts.host;
- var onconnect = opts.on_connect;
+function NoCallbackError() {
+ this.name = "NoCallbackError";
+}
- var socket = new WebSocket(host);
+NoCallbackError.prototype = Object.create(Error);
+NoCallbackError.prototype.constructor = NoCallbackError;
- var _debug = true;
- var _capturing_answers = false;
- var _capturing_callback = undefined;
- var _received_handshake = false;
+function no_callback() { throw new NoCallbackError(); }
- var result;
- var command_counter = 0;
-
- socket.binaryType = 'arraybuffer';
-
- function hand_shake(msg)
- {
- msg = msg.data;
- if (msg.substr(0,4) !== 'Rsrv') {
- result.post_error("server is not an RServe instance");
- } else if (msg.substr(4, 4) !== '0103') {
- result.post_error("sorry, rclient only speaks the 0103 version of the R server protocol");
- } else if (msg.substr(8, 4) !== 'QAP1') {
- result.post_error("sorry, rclient only speaks QAP1");
- } else {
- _received_handshake = true;
- result.running = true;
- // FIXME: there should be a better way to handle this ...
- // FIXME: can we use r_funcall? r_funcall does
- // not support named parameters (for now)
- var cookies = $.cookies.get();
- result.login(cookies.token);
- result.send("rcloud.support::session.init(username=" + escape_r_literal_string(rcloud.username()) + ")");
- onconnect && onconnect.call(result);
- }
+RClient = {
+ create: function(opts) {
+
+ function on_connect() {
+ result.running = true;
+ result.send("rcloud.support::session.init(username=" + escape_r_literal_string(rcloud.username()) + ")");
+ opts.on_connect && opts.on_connect.call(result);
}
- socket.onmessage = function(msg) {
- var v = null;
- if (_capturing_answers) {
- try {
- v = parse(msg.data);
- if (v !== null)
- v = result.eval(v);
- _capturing_callback(v);
- } catch (e) {
- _capturing_answers = false;
- _capturing_callback = undefined;
- throw e;
- }
+ function on_error(msg, status_code) {
+ if (status_code === 65) {
+ // Authentication failed.
+ result.post_error("Authentication failed. Login first!");
+ result.post_error(msg);
+
} else {
- if (!_received_handshake) {
- hand_shake(msg);
- return;
- }
- if (typeof msg.data === 'string')
- result.post_response(msg.data);
- else {
- v = parse(msg.data);
- if (v !== null)
- result.eval(v);
- }
+ result.post_error(msg);
}
- };
+ }
- socket.onclose = function(msg) {
+ function on_close(msg) {
result.post_response("Socket was closed. Goodbye!");
+ result.running = false;
};
+ var token = $.cookies.get().token;
+ var rserve = Rserve.create({
+ host: opts.host,
+ on_connect: on_connect,
+ on_error: on_error,
+ on_close: on_close,
+ login: token + "\n" + token
+ });
+
+ var _debug = true;
+ var _capturing_answers = false;
+ var _capturing_callback = undefined;
+
+ var result;
+ var command_counter = 0;
result = {
handlers: {
"eval": function(v) {
if (v.value.length === 3) {
var command_id = v.value[2].value[0];
- var cb = this.result_handlers[command_id];
- // if there's a callback attached, call it.
- // otherwise, display it.
- if (cb) {
- cb(command_id, v.value[1]);
- } else {
- result.display_response(v.value[1]);
- }
+ result.display_response(v.value[1]);
}
return v.value[1];
},
"markdown.eval": function(v) {
if (v.value.length === 3) {
var command_id = v.value[2].value[0];
- var cb = this.result_handlers[command_id];
- // if there's a callback attached, call it.
- // otherwise, display it.
- if (cb) {
- cb(command_id, v.value[1]);
- } else {
- result.display_markdown_response(v.value[1]);
- }
+ result.display_markdown_response(v.value[1]);
}
return v.value[1];
},
@@ -207,7 +171,7 @@ RClient = {
try {
this.display_response(parse(msg));
} catch (e) {
- this.post_error("Uncaught exception: " + e);
+ this.post_error("Uncaught exception: " + e.message + " - " + e.status_code);
}
}
},
@@ -233,6 +197,7 @@ RClient = {
//////////////////////////////////////////////////////////////////
post_error: function (msg) {
+ debugger;
var d = $("<div class='error-message'></div>").html(msg);
$("#output").append(d);
window.scrollTo(0, document.body.scrollHeight);
@@ -290,67 +255,45 @@ RClient = {
this.send(command);
},
- login: function(token) {
- var command = token + '\n' + token;
- var buffer = new ArrayBuffer(command.length + 21);
- var view = new EndianAwareDataView(buffer);
- view.setInt32(0, 1);
- view.setInt32(4, 5 + command.length);
- view.setInt32(8, 0);
- view.setInt32(12, 0);
- view.setInt32(16, 4 + ((1 + command.length) << 8));
- for (var i=0; i<command.length; ++i) {
- view.setUint8(20 + i, command.charCodeAt(i));
- }
- view.setUint8(buffer.byteLength - 1, 0);
- socket.send(buffer);
- },
-
- send: function(command, wrap) {
- if (!result.running) {
- alert("Init failed, cannot communicate with R process");
- return;
- }
- if (!_.isUndefined(wrap)) command = wrap(command)[0];
- var buffer = new ArrayBuffer(command.length + 21);
- var view = new EndianAwareDataView(buffer);
- view.setInt32(0, 3);
- view.setInt32(4, 5 + command.length);
- view.setInt32(8, 0);
- view.setInt32(12, 0);
- view.setInt32(16, 4 + ((1 + command.length) << 8));
- for (var i=0; i<command.length; ++i) {
- view.setUint8(20 + i, command.charCodeAt(i));
- }
- view.setUint8(buffer.byteLength - 1, 0);
-
- socket.send(buffer);
- },
-
record_cell_execution: function(cell_model) {
var json_rep = JSON.stringify(cell_model.json());
var call = this.r_funcall("rcloud.record.cell.execution",
rcloud.username(), json_rep);
- this.send(call);
+ rserve.eval(call);
+ },
+
+ send: function(command, wrap) {
+ this.send_and_callback(command, no_callback, wrap);
},
send_and_callback: function(command, callback, wrap) {
+ var that = this;
if (_.isUndefined(callback))
- callback = _.identity;
+ callback = no_callback;
var t;
if (wrap) {
t = wrap(command);
} else {
t = this.wrap_command(command, true);
}
- var command_id = t[1];
command = t[0];
- var that = this;
- this.result_handlers[command_id] = function(id, data) {
- delete that.result_handlers[id];
- callback(data);
- };
- this.send(command);
+ if (_debug)
+ console.log(command);
+ function unwrap(v) {
+ if (_debug) {
+ debugger;
+ console.log(v);
+ }
+ try {
+ callback(v.value.value[1]);
+ } catch (e) {
+ if (e.constructor === NoCallbackError) {
+ debugger;
+ that.handlers[v.value.value[0].value[0]](v.value);
+ }
+ }
+ }
+ rserve.eval(command, unwrap);
},
// FIXME this needs hardening
View
2,756 htdocs/js/rcloud_bundle.js
1,121 additions, 1,635 deletions not shown
View
4 htdocs/js/rcloud_bundle.min.js
@@ -1,3 +1,3 @@
// bare-bones d3 charting facilities
-function pprint_array_as_div(a){function c(){var a=document.createElement("table"),b=document.createElement("tr");a.appendChild(b);var c=this.attributes.value.dim.value,d=this.value,e=this;d3.select(b).selectAll("td").data(_.range(c[1]+1)).enter().append("td").text(function(a){return a===0?"":"[,"+a+"]"}),d3.select(a).selectAll("tr-data").data(_.range(c[0])).enter().append("tr").selectAll("td").data(function(a){return _.map(_.range(c[1]+1),function(b){return[a,b]})}).enter().append("td").text(function(a){var b=a[0],f=a[1];if(f===0)return"["+(b+1)+",]";var g=d[(f-1)*c[0]+b];return e.attributes&&e.attributes.value.levels?e.attributes.value.levels.value[g-1]:g});return a}function b(){var b=$("<div class='obj'></div>"),c=$("<div class='string-value'></div>"),d=this.value,e,f=this;a=a||function(a){return a};var g;this.attributes&&this.attributes.value.names?g=function(b){return f.attributes.value.names.value[b]+": "+a(String(d[b]))}:this.attributes&&this.attributes.value.levels?g=function(a){return f.attributes.value.levels.value[d[a]-1]}:g=function(b){return a(String(d[b]))};if(d.length===0)e="[]";else if(d.length===1)e=g(0);else if(d.length<=10){e="["+g(0);for(var h=1;h<d.length;++h)e=e+", "+g(h);e=e+"]"}else{e="["+g(0);for(var h=1;h<5;++h)e=e+", "+g(h);e=e+", ... ";for(h=d.length-5;h<d.length;++h)e=e+", "+g(h);e=e+"]"}c.html(e),b.append(c);return b}return function(){return this.attributes&&this.attributes.value.dim?c.call(this):b.call(this)}}function make_basic(a,b){return function(c,d){function e(){this.type=a,this.value=c,this.attributes=d}e.prototype=b||{html_element:function(){return $("<div class='obj'></div>").append($("<div class='key'></div>").html(a))}};return new e}}function parse_payload(a){var b=a.read_int(),c=Rsrv.par_parse(b),d=c[0],e=c[1];if(d===Rsrv.DT_INT)return{type:"int",value:a.read_int()};if(d===Rsrv.DT_STRING)return{type:"string",value:a.read_string(e)};if(d===Rsrv.DT_BYTESTREAM)return{type:"stream",value:a.read_stream(e)};if(d===Rsrv.DT_SEXP){c=a.read_sexp();var f=c[0],g=c[1];return{type:"sexp",value:f}}throw"Bad type for parse? "+d+" "+e}function parse(a){var b=new Int32Array(a,0,4);if(b[0]!==Rsrv.RESP_OK&&b[0]!==Rsrv.OOB_SEND){var c=b[0]>>24;throw"ERROR FROM R SERVER: "+(Rsrv.status_codes[c]||c)+" "+b[0]+" "+b[1]+" "+b[2]+" "+b[3]+" "+a.byteLength+" "+a}var d=my_ArrayBufferView(a,16,a.byteLength-16);if(d.length===0)return null;var e=parse_payload(reader(d));return e}function reader(a){function i(a,b){return d(function(c,d){return b(a.call(g,d),c)})}function h(a,b){return e(a,function(a){return d(function(c,d){return b(a,c)},0)})}function f(a){return function(b,c){var d=[],e=c;while(c>0){var f=a.call(g,b,c);d.push(f[0]),c-=f[1]}return[d,e]}}function e(a,b){return function(c,d){var e=a.call(g,c,d),f=b(e[0])(c,d-e[1]);return[f[0],e[1]+f[1]]}}function d(a,b){return function(c,d){return[a.call(g,c,d),b||d]}}var b={},c,g={offset:0,data_view:a.make(EndianAwareDataView),msg:a,read_int:function(){var a=this.offset;this.offset+=4;return this.data_view.getInt32(a)},read_string:function(a){var b="";while(a--){var c=this.data_view.getInt8(this.offset++);c&&(b=b+String.fromCharCode(c))}return b},read_stream:function(a){var b=this.offset;this.offset+=a;return this.msg.view(b,a)},read_int_vector:function(a){var b=this.offset;this.offset+=a;return this.msg.make(Int32Array,b,a)},read_double_vector:function(a){var b=this.offset;this.offset+=a;return this.msg.make(Float64Array,b,a)},read_null:d(function(a,b){return Robj.null(a)}),read_string_array:function(a,b){var c=this.read_stream(b).make(Uint8Array),d=[],e="";for(var f=0;f<c.length;++f)c[f]===0?(d.push(e),e=""):e=e+String.fromCharCode(c[f]);return[Robj.string_array(d,a),b]},read_bool_array:function(a,b){var c=this.read_int(),d=this.read_stream(b-4),e=d.make(Uint8Array),f=[];for(var g=0;g<c;++g)f[g]=!!e[g];return[Robj.bool_array(f,a),b]},read_sexp:function(){var a=this.read_int(),c=Rsrv.par_parse(a),d=c[0],e=c[1],f=4,g=undefined;if(d&Rsrv.XT_HAS_ATTR){d=d&~Rsrv.XT_HAS_ATTR;var h=this.read_sexp();g=h[0],f+=h[1],e-=h[1]}if(b[d]===undefined)throw"Unimplemented "+d;var i=b[d].call(this,g,e);return[i[0],f+i[1]]}};g.read_clos=e(g.read_sexp,function(a){return e(g.read_sexp,function(b){return d(function(c,d){return Robj.clos(a,b,c)},0)})}),g.read_list=f(g.read_sexp),g.read_list_tag=e(g.read_list,function(a){return d(function(b,c){var d={};for(var e=0;e<a.length;e+=2){var f=a[e],g=a[e+1];if(g.type!=="symbol")throw"Unexpected type "+g.type+" as tag for tagged_list";d[g.value]=f}return Robj.tagged_list(d,b)},0)}),g.read_vector=h(g.read_list,Robj.vector),g.read_list_no_tag=h(g.read_list,Robj.list),g.read_lang_no_tag=h(g.read_list,Robj.lang),g.read_vector_exp=h(g.read_list,Robj.vector_exp),g.read_symname=i(g.read_string,Robj.symbol),g.read_int_array=i(g.read_int_vector,Robj.int_array),g.read_double_array=i(g.read_double_vector,Robj.double_array),b[Rsrv.XT_NULL]=g.read_null,b[Rsrv.XT_VECTOR]=g.read_vector,b[Rsrv.XT_CLOS]=g.read_clos,b[Rsrv.XT_SYMNAME]=g.read_symname,b[Rsrv.XT_LIST_NOTAG]=g.read_list_no_tag,b[Rsrv.XT_LIST_TAG]=g.read_list_tag,b[Rsrv.XT_LANG_NOTAG]=g.read_lang_no_tag,b[Rsrv.XT_VECTOR_EXP]=g.read_vector_exp,b[Rsrv.XT_ARRAY_INT]=g.read_int_array,b[Rsrv.XT_ARRAY_DOUBLE]=g.read_double_array,b[Rsrv.XT_ARRAY_STR]=g.read_string_array,b[Rsrv.XT_ARRAY_BOOL]=g.read_bool_array;return g}(function(){function g(a){return typeof a=="function"?a:function(a){return function(){return a}}(a)}function e(a,b){if(_.isUndefined(c[b])){var e=new Uint8Array(a.data().length);d[b]=e,c[b]=[a]}else c[b].push(a)}function b(a,b,c){var d=a.slice((c||b)+1||a.length);a.length=b<0?a.length+b:b;return a.push.apply(a,d)}function a(a,b){return"translate("+a+","+b+")"}Chart={};var c={},d={};Chart.get_selections=function(a){return d[this.group_id]},Chart.set_selections=function(a,b){for(var e=0;e<b.length;e++)d[a][e]=b[e];_.each(c[a],function(a){_.each(a.views,function(a){a.selection_changed()})})},Chart.data_model=function(a,b){var f=a.length,g={views:{},group_id:b,data:function(){return a},selection:function(){return d[this.group_id]},register_view:function(a){this.views[a._view_index]=a},deregister_view:function(a){delete this.views[a._view_index]},notify:function(){_.each(c[this.group_id],function(a){_.each(a.views,function(a){a.selection_changed()})})},clear_brushes:function(a){_.each(c[this.group_id],function(b){_.each(b.views,function(b){b._view_index!==a._view_index&&(console.log("clearing brush on view",b._view_index,b,a),b.clear_brush())})})}};e(g,b);return g};var f=0;Chart.scatterplot=function(b){function J(){v.empty()&&F(y)}function I(a){var c=v.extent(),d=h.selection();y.each(function(a){var e=i[a],f=c[0][0]<=b.x(e)&&b.x(e)<=c[1][0]&&c[0][1]<=b.y(e)&&b.y(e)<=c[1][1];d[a]=f}),h.notify()}function H(a){h.clear_brushes(s)}function G(c){c.attr("d",d3.svg.symbol().type("circle")).attr("size",5).attr("transform",function(c){c=i[c];return a(p(b.x(c)),q(b.y(c)))}).style("stroke-width",function(a){return s.opts.stroke_width(i[a])})}function F(){var a=h.selection();z.attr("display",function(b){return a[b]?null:"none"})}b=_.defaults(b,{width:400,height:400,padding:20,n_xticks:10,n_yticks:10,stroke:"white",stroke_width:"1.5px",fill:"black",stroke_opacity:1,fill_opacity:1}),b.stroke=g(b.stroke),b.stroke_opacity=g(b.stroke_opacity),b.stroke_width=g(b.stroke_width),b.fill=g(b.fill),b.fill_opacity=g(b.fill_opacity);var c=b.width,d=b.height,e=b.padding,h=b.data,i=h.data(),j=_.map(i,b.x),k=_.map(i,b.y),l=_.min(j),m=_.max(j),n=_.min(k),o=_.max(k),p=d3.scale.linear().domain([l,m]).range([0,c]),q=d3.scale.linear().domain([n,o]).range([d,0]),r=$("<div></div>")[0],s={_view_index:++f,opts:b,plot:r,clear_brush:function(){u.call(v.clear())},selection_changed:function(){F()},deleted:function(){h.deregister_view(this)}};h.register_view(s);var t=d3.select(r).append("svg").attr("width",c+2*e).attr("height",d+2*e),u=t.append("g").attr("transform",a(e,e)),v=d3.svg.brush().on("brushstart",H).on("brush",I).on("brushend",J);u.append("rect").attr("width",c).attr("height",d).attr("fill","#eee");var w=u.selectAll("g.x").data(p.ticks(b.n_xticks)).enter().append("g").attr("class","x");w.append("line").attr("x1",p).attr("x2",p).attr("y1",0).attr("y2",d),w.append("text").attr("x",p).attr("y",d+3).attr("dy",".71em").attr("text-anchor","middle").attr("class","rule-text").text(p.tickFormat(b.n_xticks));var x=u.selectAll("g.y").data(q.ticks(b.n_yticks)).enter().append("g").attr("class","x");x.append("line").attr("x1",0).attr("x2",c).attr("y1",q).attr("y2",q),x.append("text").attr("x",-3).attr("y",q).attr("dy",".35em").attr("text-anchor","end").attr("class","rule-text").text(q.tickFormat(b.n_yticks));var y=u.selectAll("path.dot").data(_.range(i.length)).enter().append("path"),z=u.selectAll("pathasdkf.dot").data(_.range(i.length)).enter().append("path"),A=function(a){return i[a]};y.style("fill",_.compose(b.fill,A)).style("stroke",_.compose(b.stroke,A)).style("fill-opacity",_.compose(b.fill_opacity,A)).style("stroke-opacity",_.compose(b.stroke_opacity,A)),u.call(v.x(p).y(q));var B=function(){return"red"},C=function(){return"red"},D=function(){return 1},E=function(){return 1};z.style("fill",_.compose(B,A)).style("stroke",_.compose(C,A)).style("fill-opacity",_.compose(D,A)).style("stroke-opacity",_.compose(E,A)),t.on("keydown",function(a){console.log(a)}),G(y),G(z),F();return s},Chart.histogram=function(a){a=_.defaults(a,{width:400,height:400,padding:20,n_bins:10,stroke:"white",stroke_width:"1.5px",fill:"black",stroke_opacity:1,fill_opacity:1}),a.stroke=g(a.stroke),a.stroke_opacity=g(a.stroke_opacity),a.stroke_width=g(a.stroke_width),a.fill=g(a.fill),a.fill_opacity=g(a.fill_opacity);var b=a.width,c=a.height,d=a.padding,e=a.data,h=e.data(),i=_.map(h,a.x),j=_.min(i),k=_.max(i),l=$("<div></div>")[0],m=d3.scale.linear().domain([j,k]).range([0,b]),n=d3.layout.histogram().range([j,k]).bins(a.n_bins),o=n(a.x),p={_view_index:++f,opts:a,plot:l,clear_brush:function(){vis.call(brush.clear())},selection_changed:function(){update_selection()},deleted:function(){e.deregister_view(this)}}}})(),FacetChart={},FacetChart.facet_tour_plot=function(a){function l(a){var b=[],c=[],d=0,e=0;for(var f=0;f<a;++f)b[f]=Math.random()*2-1,c[f]=Math.random()*2-1,d+=b[f]*b[f],e+=c[f]*c[f];d=Math.sqrt(d),e=Math.sqrt(e);if(d===0||e===0)return l(a);var g=0;for(f=0;f<a;++f)b[f]/=d,c[f]/=e,g+=b[f]*c[f];var h=0;for(f=0;f<a;++f)c[f]=c[f]-g*b[f],h+=c[f]*c[f];h=Math.sqrt(h);if(h===0)return l(a);for(f=0;f<a;++f)c[f]/=h;return[b,c]}function k(){Facet.set_context(m),f=j();var a=10,b=2.5,c=1;g=[],h=[];var d,i,k=[],l=Shade.vec(0,0),n=Shade.vec(0,0),o=Shade.vec(0,0);for(var p=0;p<f.columns.length;++p){var q=f[f.columns[p]];g.push(Shade.parameter("float")),h.push(Shade.parameter("float"));var r=Shade.vec(g[p],h[p]);d=_.min(q.array),i=_.max(q.array),k=(i+d)/2,l=l.add(r.mul(q)),n=n.add(r.mul(k)),o=o.add(r.mul(k-d).abs())}var s=Shade.color("red");e=Facet.Marks.scatterplot({elements:f[f.columns[0]].numItems,xy:l,xy_scale:Shade.Utils.linear(n.sub(o),n.add(o),Shade.vec(0,0),Shade.vec(1,1)),fill_color:s,stroke_color:Shade.mix(Shade.color("black"),s,.5),stroke_width:b,point_diameter:a})}function j(){var b={},c=[];for(var d=0;d<a.value.length;++d)b["dim_"+d]=Facet.attribute_buffer({vertex_array:a.value[d].value,item_size:1,keep_array:!0}),c.push("dim_"+d);b.columns=c;return b}function i(){m.viewport(0,0,m.viewportWidth,m.viewportHeight),m.clearDepth(1),m.clearColor(0,0,0,0),m.clear(m.COLOR_BUFFER_BIT|m.DEPTH_BUFFER_BIT),e.draw()}var b=600,c=600,d=$("<canvas width='"+b+"' height='"+c+"'></canvas>")[0],e,f,g,h,m=Facet.init(d,{clearColor:[1,1,1,1]});k();var n=l(f.columns.length),o=l(f.columns.length),p=(new Date).getTime(),q=1,r=function(){var a=((new Date).getTime()-p)/1e3,b=a/3;b-=Math.floor(b),b<q&&(n=o,o=l(4)),q=b;for(var c=0;c<f.columns.length;++c)g[c].set(b*o[0][c]+(1-b)*n[0][c]),h[c].set(b*o[1][c]+(1-b)*n[1][c]);window.requestAnimFrame(r,d),i()};r();return d},FacetChart.facet_osm_plot=function(a,b,c,d,e){var f=$("<canvas width='"+d+"' height='"+e+"'></canvas>")[0],g=Facet.init(f,{clearColor:[1,1,1,1],mousedown:function(a){var b=j.mousedown(a);return b},mousemove:function(a){var b=j.mousemove(a);return b},mouseup:function(a){var b=j.mouseup(a);return b}}),h=Shade.parameter("float",3),i=Shade.Camera.perspective({look_at:[Shade.vec(0,0,6),Shade.vec(0,0,-1),Shade.vec(0,1,0)],field_of_view_y:Shade.div(20,h)}),j=Facet.Marks.globe({view_proj:i,zoom:h});a=Facet.attribute_buffer({vertex_array:a,item_size:1}),b=Facet.attribute_buffer({vertex_array:b,item_size:1}),console.log(c),c.length===3?c=Shade.vec(c[0],c[1],c[2],1):c.length>1&&(c=Shade.vec(Facet.attribute_buffer({vertex_array:c,item_size:3}),1));var k=Facet.model({type:"points",lats:a,lons:b}),l=Facet.bake(k,{color:c,point_size:2,position:j.lat_lon_position(k.lats.radians(),k.lons.radians())});Facet.Scene.add(j),Facet.Scene.add(l);return f},function(a){if(a.WebSocket===undefined)if(a.MozWebSocket)a.WebSocket=a.MozWebSocket;else throw"WebSocket support not found"}(this),function(){function a(a){return'"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}RClient={create:function(b){function l(b){b=b.data;if(b.substr(0,4)!=="Rsrv")j.post_error("server is not an RServe instance");else if(b.substr(4,4)!=="0103")j.post_error("sorry, rclient only speaks the 0103 version of the R server protocol");else if(b.substr(8,4)!=="QAP1")j.post_error("sorry, rclient only speaks QAP1");else{i=!0,j.running=!0;var c=$.cookies.get();j.login(c.token),j.send("rcloud.support::session.init(username="+a(rcloud.username())+")"),d&&d.call(j)}}var c=b.host,d=b.on_connect,e=new WebSocket(c),f=!0,g=!1,h=undefined,i=!1,j,k=0;e.binaryType="arraybuffer",e.onmessage=function(a){var b=null;if(g)try{b=parse(a.data),b!==null&&(b=j.eval(b)),h(b)}catch(c){g=!1,h=undefined;throw c}else{if(!i){l(a);return}typeof a.data=="string"?j.post_response(a.data):(b=parse(a.data),b!==null&&j.eval(b))}},e.onclose=function(a){j.post_response("Socket was closed. Goodbye!")},j={handlers:{eval:function(a){if(a.value.length===3){var b=a.value[2].value[0],c=this.result_handlers[b];c?c(b,a.value[1]):j.display_response(a.value[1])}return a.value[1]},"markdown.eval":function(a){if(a.value.length===3){var b=a.value[2].value[0],c=this.result_handlers[b];c?c(b,a.value[1]):j.display_markdown_response(a.value[1])}return a.value[1]},browsePath:function(a){$.ajax({url:"http://127.0.0.1:8080"+a.value[1].value}).done(function(a){var b=/[\s\S]*<body>([\s\S]*)<\/body>/g.exec(a)[1];$("#help-output").html(b)})},"img.url.update":function(a){return a.value[1]},"img.url.final":function(a){return a.value[1]},"dev.new":function(a){return""},"dev.close":function(a){return""},internal_cmd:function(a){return""},"boot.failure":function(a){j.running=!1}},running:!1,result_handlers:{},eval:function(a){var b=this;if(a.type!=="sexp")return this.post_error("Bad protocol, should always be sexp.");a=a.value;if(a.type==="string_array")return this.post_error(a.value[0]);if(a.type==="null")return null;if(a.type!=="vector")return this.post_error("Protocol error, unexpected value of type "+a.type);if(a.value[0].type!=="string_array"||a.value[0].value.length!==1){console.log("Protocol error?! ",a.value[0]);return undefined}var c=a.value[0].value[0],d=this.handlers;if(d[c]===undefined)return this.post_error("Unknown command "+c);if(c=="img.url.update"||c=="img.url.final"){var e=window.devImgIndex;e||(window.devImgIndex=e=1),c=="img.url.final"&&window.devImgIndex++;var f=document.getElementById("dimg"+e);f?f.innerHTML="<img src="+a.value[1].value[0]+">":this.post_div("<div id=dimg"+e+"><img src="+a.value[1].value[0]+"></div>")}return d[c].call(this,a)},register_handler:function(a,b){this.handlers[a]=b},post_sent_command:function(a){var b=$('<pre class="r-sent-command"></pre>').html("> "+a);$("#output").append(b)},post_debug_message:function(a){var b=new Uint8Array(a),c=Array.prototype.join.call(b,",");this.post_response(c)},post_div:function(a){return shell.post_div(a)},post_binary_response:function(a){if(f)this.post_debug_message(a),this.display_response(parse(a));else try{this.display_response(parse(a))}catch(b){this.post_error("Uncaught exception: "+b)}},display_response:function(a){a&&$("#output").append(a.html_element()),window.scrollTo(0,document.body.scrollHeight)},display_markdown_response:function(a){a&&($("#output").append($("<div></div>").html(a.value[0])).find("pre code").each(function(a,b){hljs.highlightBlock(b)}),MathJax.Hub.Queue(["Typeset",MathJax.Hub]))},post_error:function(a){var b=$("<div class='error-message'></div>").html(a);$("#output").append(b),window.scrollTo(0,document.body.scrollHeight)},post_response:function(a){var b=$("<pre></pre>").html(a);$("#output").append(b),window.scrollTo(0,document.body.scrollHeight)},capture_answers:function(a,b){function d(d){c.push(d),a--,a===0&&(g=!1,h=undefined,b(c))}if(g)throw"Still waiting for previous answers...";g=!0;var c=[];h=d},wrap_command:function(a,b){var c=k++;b===undefined&&(b=!1);return["rcloud.support::session.eval({"+a+"}, "+c+", "+(b?"TRUE":"FALSE")+")",c]},markdown_wrap_command:function(b,c){var d=k++;return["rcloud.support::session.markdown.eval({markdownToHTML(text=paste(knit(text="+a(b+"\n")+'), collapse="\\n"), fragment=TRUE)}, '+d+", "+(c?"TRUE":"FALSE")+")",d]},log:function(a){a='rcloud.support::session.log("'+rcloud.username()+'", "'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'")',this.send(a)},login:function(a){var b=a+"\n"+a,c=new ArrayBuffer(b.length+21),d=new EndianAwareDataView(c);d.setInt32(0,1),d.setInt32(4,5+b.length),d.setInt32(8,0),d.setInt32(12,0),d.setInt32(16,4+(1+b.length<<8));for(var f=0;f<b.length;++f)d.setUint8(20+f,b.charCodeAt(f));d.setUint8(c.byteLength-1,0),e.send(c)},send:function(a,b){if(!j.running)alert("Init failed, cannot communicate with R process");else{_.isUndefined(b)||(a=b(a)[0]);var c=new ArrayBuffer(a.length+21),d=new EndianAwareDataView(c);d.setInt32(0,3),d.setInt32(4,5+a.length),d.setInt32(8,0),d.setInt32(12,0),d.setInt32(16,4+(1+a.length<<8));for(var f=0;f<a.length;++f)d.setUint8(20+f,a.charCodeAt(f));d.setUint8(c.byteLength-1,0),e.send(c)}},record_cell_execution:function(a){var b=JSON.stringify(a.json()),c=this.r_funcall("rcloud.record.cell.execution",rcloud.username(),b);this.send(c)},send_and_callback:function(a,b,c){_.isUndefined(b)&&(b=_.identity);var d;c?d=c(a):d=this.wrap_command(a,!0);var e=d[1];a=d[0];var f=this;this.result_handlers[e]=function(a,c){delete f.result_handlers[a],b(c)},this.send(a)},r_funcall:function(b){var c=[b,"("];for(var d=1;d<arguments.length;++d){var e=typeof arguments[d];e==="string"?c.push(a(arguments[d])):c.push(String(arguments[d])),d<arguments.length-1&&c.push(",")}c.push(")");var f=c.join("");return f}};return j}}}(),function(a){var b;(function(){var a=new ArrayBuffer(4),c=new Uint8Array(a),d=new Uint32Array(a);c[0]=1;if(d[0]===1)b=!0;else if(d[0]===16777216)b=!1;else throw"we're bizarro endian, refusing to continue"})();var c=["Int32","Int16","Uint32","Uint16","Float32","Float64"],d=["setInt32","setInt16","setUint32","setUint16","setFloat32","setFloat64"],e=["getInt32","getInt16","getUint32","getUint16","getFloat32","getFloat64"];if(!a.DataView){console.log("polyfilling DataView");var f={};for(var g=0;g<c.length;++g){var h=this[c[g]+"Array"],i=h.BYTES_PER_ELEMENT,j=new ArrayBuffer(i),k=new h(j),l=new Uint8Array(j);f[c[g]]=function(a,b){return function(c,d,e,f){a[0]=f;for(var g=0;g<d;++g)c[e+g]=b[g]}}(k,l)}function m(a,c,d){this.buffer=a,this.byteOffset=_.isUndefined(c)?0:c,this.byteLength=_.isUndefined(d)?a.byteLength:d,this.view=new jDataView(a,c,d,b),this.byte_array=new Uint8Array(a)}var n={};m.prototype=n;for(g=0;g<c.length;++g){var o="get"+c[g];n[o]=function(a){return function(b){return this.view[a](b)}}(o);var p="set"+c[g],i=this[c[g]+"Array"].BYTES_PER_ELEMENT;n[p]=function(a,b){return function(c,d){console.log(b),console.log(f),f[b](this.byte_array,a,c,d)}}(i,c[g])}n.setUint8=function(a,b){this.byte_array[a]=b},n.setInt8=function(a,b){b<0&&(b+=256),this.byte_array[a]=b},n.getInt8=function(a){return this.view.GetInt8(a)},n.getUint8=function(a){this.byte_array[a]},a.DataView=m}a.EndianAwareDataView=function(){function g(a,b,c){b===undefined?this.view=new DataView(a):this.view=new DataView(a,b,c)}var a={setInt8:function(a,b){return this.view.setInt8(a,b)},setUint8:function(a,b){return this.view.setUint8(a,b)},getInt8:function(a){return this.view.getInt8(a)},getUint8:function(a){return this.view.getUint8(a)}},c=["setInt32","setInt16","setUint32","setUint16","setFloat32","setFloat64"],d=["getInt32","getInt16","getUint32","getUint16","getFloat32","getFloat64"];for(var e=0;e<c.length;++e){var f=c[e];a[f]=function(a){return function(c,d){return this.view[a](c,d,b)}}(f)}for(e=0;e<d.length;++e){var f=d[e];a[f]=function(a){return function(c){return this.view[a](c,b)}}(f)}g.prototype=a;return g}(),a.my_ArrayBufferView=function(a,b,c){b=_.isUndefined(b)?0:b,c=_.isUndefined(c)?a.byteLength:c;return{buffer:a,offset:b,length:c,make:function(a,b,c){b=_.isUndefined(b)?0:b,c=_.isUndefined(c)?this.length:c;var d=a.BYTES_PER_ELEMENT||1,e=c/d;if((this.offset+b)%d!=0){var f=new DataView(this.buffer,this.offset+b,c),g=new ArrayBuffer(c),h=new DataView(g);for(var i=0;i<c;++i)h.setUint8(i,f.getUint8(i));return new a(g)}return new a(this.buffer,this.offset+b,e)},view:function(a,b){return my_ArrayBufferView(this.buffer,this.offset+a,b)}}}}(this),parser=function(){var a={parse:function(a,b){function s(){var b=1,c=1,d=!1;for(var e=0;e<f;e++){var g=a.charAt(e);g==="\n"?(d||b++,c=1,d=!1):g==="\r"|g==="\u2028"||g==="\u2029"?(b++,c=1,d=!0):(c++,d=!1)}return{line:b,column:c}}function r(){function b(a){a.sort();var b=null,c=[];for(var d=0;d<a.length;d++)a[d]!==b&&(c.push(a[d]),b=a[d]);switch(c.length){case 0:return"end of input";case 1:return c[0];default:return c.slice(0,c.length-1).join(", ")+" or "+c[c.length-1]}}var c=b(g),e=Math.max(d,f),h=e<a.length?k(a.charAt(e)):"end of input";return"Expected "+c+" but "+h+" found."}function q(){var b="parameter@"+d,c=h[b];if(c){d=c.nextPos;return c.result}var f=d,g=d;if(a.substr(d,2)==="{{"){var i="{{";d+=2}else{var i=null;e&&l('"{{"')}if(i!==null){if(a.substr(d).match(/^[A-Za-z0-9_.+\/*\-"'[\]()!@#$%^&*;:<>,\\|]/)!==null){var j=a.charAt(d);d++}else{var j=null;e&&l("[A-Za-z0-9_.+\\/*\\-\"'[\\]()!@#$%^&*;:<>,\\\\|]")}if(j!==null){var k=[];while(j!==null){k.push(j);if(a.substr(d).match(/^[A-Za-z0-9_.+\/*\-"'[\]()!@#$%^&*;:<>,\\|]/)!==null){var j=a.charAt(d);d++}else{var j=null;e&&l("[A-Za-z0-9_.+\\/*\\-\"'[\\]()!@#$%^&*;:<>,\\\\|]")}}}else var k=null;if(k!==null){if(a.substr(d,2)==="}}"){var m="}}";d+=2}else{var m=null;e&&l('"}}"')}if(m!==null)var n=[i,k,m];else{var n=null;d=g}}else{var n=null;d=g}}else{var n=null;d=g}var o=n!==null?function(a){return a.join("")}(n[1]):null;if(o!==null)var p=o;else{var p=null;d=f}h[b]={nextPos:d,result:p};return p}function p(){var a="paramlist@"+d,b=h[a];if(b){d=b.nextPos;return b.result}var c=d,e=d,f=q();if(f!==null){var g=m();if(g!==null){var i=p();if(i!==null)var j=[f,g,i];else{var j=null;d=e}}else{var j=null;d=e}}else{var j=null;d=e}var k=j!==null?function(a,b){var c=[a];for(var d=0;d<b.length;++d)c.push(b[d]);return c}(j[0],j[2]):null;if(k!==null)var l=k;else{var l=null;d=c}if(l!==null)var n=l;else{var o=d,r=q(),s=r!==null?function(a){return[a]}(r):null;if(s!==null)var t=s;else{var t=null;d=o}if(t!==null)var n=t;else var n=null}h[a]={nextPos:d,result:n};return n}function o(){var b="identifier@"+d,c=h[b];if(c){d=c.nextPos;return c.result}var f=d,g=d;if(a.substr(d).match(/^[A-Za-z_]/)!==null){var i=a.charAt(d);d++}else{var i=null;e&&l("[A-Za-z_]")}if(i!==null){if(a.substr(d).match(/^[A-Za-z0-9_]/)!==null){var j=a.charAt(d);d++}else{var j=null;e&&l("[A-Za-z0-9_]")}if(j!==null){var k=[];while(j!==null){k.push(j);if(a.substr(d).match(/^[A-Za-z0-9_]/)!==null){var j=a.charAt(d);d++}else{var j=null;e&&l("[A-Za-z0-9_]")}}}else var k=null;if(k!==null)var m=[i,k];else{var m=null;d=g}}else{var m=null;d=g}var n=m!==null?function(a,b){return a+b.join("")}(m[0],m[1]):null;if(n!==null)var o=n;else{var o=null;d=f}h[b]={nextPos:d,result:o};return o}function n(){var b="command@"+d,c=h[b];if(c){d=c.nextPos;return c.result}var f=d,g=d;if(a.substr(d,1)==="@"){var i="@";d+=1}else{var i=null;e&&l('"@"')}if(i!==null){var j=o();if(j!==null){var k=m();if(k!==null){var n=p();if(n!==null)var q=[i,j,k,n];else{var q=null;d=g}}else{var q=null;d=g}}else{var q=null;d=g}}else{var q=null;d=g}var r=q!==null?function(a,b){return{id:a,ps:b}}(q[1],q[3]):null;if(r!==null)var s=r;else{var s=null;d=f}if(s!==null)var t=s;else{var u=d,v=d;if(a.substr(d,1)==="@"){var w="@";d+=1}else{var w=null;e&&l('"@"')}if(w!==null){var x=o();if(x!==null)var y=[w,x];else{var y=null;d=v}}else{var y=null;d=v}var z=y!==null?function(a){return{id:a,ps:[]}}(y[1]):null;if(z!==null)var A=z;else{var A=null;d=u}if(A!==null)var t=A;else var t=null}h[b]={nextPos:d,result:t};return t}function m(){var b="whitespace@"+d,c=h[b];if(c){d=c.nextPos;return c.result}if(a.substr(d).match(/^[ \n\r]/)!==null){var f=a.charAt(d);d++}else{var f=null;e&&l("[ \t\\n\\r]")}if(f!==null){var g=[];while(f!==null){g.push(f);if(a.substr(d).match(/^[ \n\r]/)!==null){var f=a.charAt(d);d++}else{var f=null;e&&l("[ \t\\n\\r]")}}}else var g=null;h[b]={nextPos:d,result:g};return g}function l(a){d<f||(d>f&&(f=d,g=[]),g.push(a))}function k(a){return'"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/[\x80-\uFFFF]/g,j)+'"'}function j(a){var b=a.charCodeAt(0);if(b<=255)var c="x",d=2;else var c="u",d=4;return"\\"+c+i(b.toString(16).toUpperCase(),"0",d)}function i(a,b,c){var d=a,e=c-a.length;for(var f=0;f<e;f++)d=b+d;return d}var c={command:n,identifier:o,parameter:q,paramlist:p,whitespace:m};if(b!==undefined){if(c[b]===undefined)throw new Error("Invalid rule name: "+k(b)+".")}else b="command";var d=0,e=!0,f=0,g=[],h={},t=c[b]();if(t===null||d!==a.length){var u=s();throw new this.SyntaxError(r(),u.line,u.column)}return t},toSource:function(){return this._source}};a.SyntaxError=function(a,b,c){this.name="SyntaxError",this.message=a,this.line=b,this.column=c},a.SyntaxError.prototype=Error.prototype;return a}(),Robj={"null":function(a){return{type:"null",value:null,attributes:a,html_element:function(){return $("<div class='obj'><div class='key'>null</div></div>")}}},clos:function(a,b,c){return{type:"clos",value:{formals:a,body:b},attributes:c,html_element:function(){var a=$("<div class='obj'></div>"),b=$("<div></div>");b.append($("<div class='key'>formals:</div>")),b.append(this.value.formals.html_element()),a.append(b),b=$("<div></div>"),b.append($("<div class='key'>body:</div>")),b.append(this.value.body.html_element()),a.append(b);return a}}},vector:make_basic("vector",{html_element:function(){var a=$("<div class='obj'></div>");if(!this.attributes)for(var b=0;b<this.value.length;++b)a.append(this.value[b].html_element());else{var c=_.map(this.value,function(a){return a.value.length}),d=this.attributes.value.names.value;if(_.all(c,function(a){return a===c[0]})){var e=document.createElement("table"),f=document.createElement("tr"),g=this.value;e.appendChild(f),d3.select(f).selectAll("th").data(_.range(c.length)).enter().append("th").text(function(a){return d[a]});var h;c[0]<11?h=_.range(c[0]):(h=[0,1,2,3,4,5],h.push.apply(h,_.range(c[0]-5,c[0]))),d3.select(e).selectAll("tr-data").data(h).enter().append("tr").selectAll("td").data(function(a){return _.map(_.range(c.length),function(b){return[a,b]})}).enter().append("td").text(function(a,b){var d=a[0],e=a[1];if(c[0]>=11&&d===5)return"...";var f=g[e].value[d];return g[e].attributes?g[e].attributes.value.levels.value[f-1]:f}),a.append(e)}else{var i=$("<div></div>");for(var b=0;b<this.value.length;++b)i.append($("<span class='key'></span>").append(d[b]+": ")),i.append(this.value[b].html_element());a.append(i)}}return a}}),symbol:make_basic("symbol"),list:make_basic("list"),lang:make_basic("lang"),tagged_list:make_basic("tagged_list"),tagged_lang:make_basic("tagged_lang"),vector_exp:make_basic("vector_exp"),int_array:make_basic("int_array",{html_element:pprint_array_as_div()}),double_array:make_basic("double_array",{html_element:pprint_array_as_div()}),string_array:make_basic("string_array",{html_element:pprint_array_as_div(function(a){var b,c,d=a.length,e='"';for(c=0;c<d;c+=1){b=a.charAt(c);if(b>=" "){if(b==="\\"||b==='"')e+="\\";e+=b}else switch(b){case"\b":e+="\\b";break;case"\f":e+="\\f";break;case"\n":e+="\\n";break;case"\r":e+="\\r";break;case"\t":e+="\\t";break;default:b=b.charCodeAt(),e+="\\u00"+Math.floor(b/16).toString(16)+(b%16).toString(16)}}return e+'"'})}),bool_array:make_basic("bool_array",{html_element:pprint_array_as_div()})},Rsrv={PAR_TYPE:function(a){return a&255},PAR_LEN:function(a){return a>>8},PAR_LENGTH:function(a){return a>>8},par_parse:function(a){return[Rsrv.PAR_TYPE(a),Rsrv.PAR_LEN(a)]},SET_PAR:function(a,b){return(b&16777215)<<8|a&255},CMD_STAT:function(a){return a>>24&127},SET_STAT:function(a,b){return a|(b&127)<<24},CMD_RESP:65536,RESP_OK:65537,RESP_ERR:65538,OOB_SEND:200704,ERR_auth_failed:65,ERR_conn_broken:66,ERR_inv_cmd:67,ERR_inv_par:68,ERR_Rerror:69,ERR_IOerror:70,ERR_notOpen:71,ERR_accessDenied:72,ERR_unsupportedCmd:73,ERR_unknownCmd:74,ERR_data_overflow:75,ERR_object_too_big:76,ERR_out_of_mem:77,ERR_ctrl_closed:78,ERR_session_busy:80,ERR_detach_failed:81,CMD_long:1,CMD_voidEval:2,CMD_eval:3,CMD_shutdown:4,CMD_openFile:16,CMD_createFile:17,CMD_closeFile:18,CMD_readFile:19,CMD_writeFile:20,CMD_removeFile:21,CMD_setSEXP:32,CMD_assignSEXP:129,CMD_detachSession:48,CMD_detachedVoidEval:49,CMD_attachSession:50,CMD_ctrl:64,CMD_ctrlEval:66,CMD_ctrlSource:69,CMD_ctrlShutdown:68,CMD_setBufferSize:129,CMD_setEncoding:130,CMD_SPECIAL_MASK:240,CMD_serEval:245,CMD_serAssign:246,CMD_serEEval:247,DT_INT:1,DT_CHAR:2,DT_DOUBLE:3,DT_STRING:4,DT_BYTESTREAM:5,DT_SEXP:10,DT_ARRAY:11,DT_LARGE:64,XT_NULL:0,XT_INT:1,XT_DOUBLE:2,XT_STR:3,XT_LANG:4,XT_SYM:5,XT_BOOL:6,XT_S4:7,XT_VECTOR:16,XT_LIST:17,XT_CLOS:18,XT_SYMNAME:19,XT_LIST_NOTAG:20,XT_LIST_TAG:21,XT_LANG_NOTAG:22,XT_LANG_TAG:23,XT_VECTOR_EXP:26,XT_VECTOR_STR:27,XT_ARRAY_INT:32,XT_ARRAY_DOUBLE:33,XT_ARRAY_STR:34,XT_ARRAY_BOOL_UA:35,XT_ARRAY_BOOL:36,XT_RAW:37,XT_ARRAY_CPLX:38,XT_UNKNOWN:48,XT_LARGE:64,XT_HAS_ATTR:128,BOOL_TRUE:1,BOOL_FALSE:0,BOOL_NA:2,GET_XT:function(a){return a&63},GET_DT:function(a){return a&63},HAS_ATTR:function(a){return(a&Rsrv.XT_HAS_ATTR)>0},IS_LARGE:function(a){return(a&Rsrv.XT_LARGE)>0},itop:function(a){return a},ptoi:function(a){return a},dtop:function(a){return a},ptod:function(a){return a},fixdcpy:function(){throw"unimplemented"},status_codes:{65:"ERR_auth_failed",66:"ERR_conn_broken",67:"ERR_inv_cmd",68:"ERR_inv_par",69:"ERR_Rerror",70:"ERR_IOerror",71:"ERR_notOpen",72:"ERR_accessDenied",73:"ERR_unsupportedCmd",74:"ERR_unknownCmd",75:"ERR_data_overflow",76:"ERR_object_too_big",77:"ERR_out_of_mem",78:"ERR_ctrl_closed",80:"ERR_session_busy",81:"ERR_detach_failed"}},rcloud={},rcloud.init_client_side_data=function(){var a=this;rcloud.get_user_filenames(function(b){a.user_filenames=b.value;var c=b.value,d=d3.select("#internals-user-files");d.append("h3").text("User files"),d.append("ul").selectAll("li").data(c).enter().append("li").text(function(a){return a})}),rclient.send_and_callback("rcloud.prefix.uuid()",function(b){a.wplot_uuid=b.value[0]})},rcloud.username=function(){return $.cookies.get("user")},rcloud.get_user_filenames=function(a){_.isUndefined(a)&&(a=_.identity),rclient.send_and_callback(rclient.r_funcall("rcloud.list.initial.filenames",this.username()),a)},rcloud.search=function(a,b){var c=this;_.isUndefined(b)&&(b=_.identity),rclient.send_and_callback(rclient.r_funcall("rcloud.search",a),b)},rcloud.get_all_user_filenames=function(a){var b=this;_.isUndefined(a)&&(a=_.identity),rclient.send_and_callback(rclient.r_funcall("rcloud.list.all.initial.filenames"),a)},rcloud.load_user_file=function(a,b,c){rclient.send_and_callback(rclient.r_funcall("rcloud.load.user.file",a,b),c)},rcloud.save_to_user_file=function(a,b,c,d){rclient.send_and_callback(rclient.r_funcall("rcloud.save.to.user.file",a,b,c),d)},rcloud.create_user_file=function(a,b){rclient.send_and_callback(rclient.r_funcall("rcloud.create.user.file",rcloud.username(),a),b)},rcloud.resolve_deferred_result=function(a,b){var c=rclient.r_funcall("rcloud.fetch.deferred.result",a);rclient.send_and_callback(c,b)},Notebook={},Notebook.Cell={},function(){function c(b){function k(){v.html("Computing..."),h(),y.show_result(),b.controller.execute()}function j(a){a.addClass("button-disabled")}function i(a){a.removeClass("button-disabled")}function h(){b.content($(u).val())}var c=$("<div class='notebook-cell'></div>"),d=$("<span class='fontawesome-button'><i class='icon-edit'></i></span>").tooltip({
-title:"source"}),e=$("<span class='fontawesome-button'><i class='icon-picture'></i></span>").tooltip({title:"result"}),f=$("<span class='fontawesome-button'><i class='icon-resize-small'></i></span>").tooltip({title:"hide"}),g=$("<span class='fontawesome-button'><i class='icon-trash'></i></span>").tooltip({title:"remove"});d.click(function(a){$(a.currentTarget).hasClass("button-disabled")||y.show_source()}),e.click(function(a){$(a.currentTarget).hasClass("button-disabled")||y.show_result()}),f.click(function(a){$(a.currentTarget).hasClass("button-disabled")||y.hide_all()}),g.click(function(a){$(a.currentTarget).hasClass("button-disabled")||(b.parent_model.controller.remove_cell(b),$(".tooltip").remove())});var l=$("<div style='position:relative; float: right; z-index:10000'></div>"),m=$("<div style='margin:0.5em;'></div>"),n=$("<div style='margin:0.5em;'></div>");m.append(d),m.append(e),m.append(f),m.append(g),l.append(m),n.hide(),l.append(n),c.append(l);var o=$("<div></div>"),p=$("<div style='clear:both;'></div>");c.append(o),c.append(p);var q=$('<div style="position: relative; width:100%;"></div>'),r=$('<div style="position: absolute; right:-0.5em; top:-0.5em"></div>'),s=a("icon-plus-sign","insert cell");o.append(r),r.append(s),s.click(function(a){var b=c.index(),d=b;shell.insert_markdown_cell_before(d)});var t=$('<div style="width:100%; margin-left: 0.5em; margin-top: 0.5em"></div>');o.append(q),q.append(t);var u=$('<input type="text" style="width:88%"/>');t.append(u),u.keypress(function(a){if(a.which===13){k(),a.preventDefault();return!1}return!0});var v=$('<div class="r-result-div"></div>');o.append(v);var w=$("<span></span>");o.append(w);var x,y={content_updated:function(){u.val(b.content())},self_removed:function(){c.remove()},result_updated:function(a){v.hide(),v.html(a.value[0]),v.slideDown(150);var b=rcloud.wplot_uuid;o.find("pre code").contents().filter(function(){return this.nodeValue.indexOf(b)!==-1}).parent().parent().each(function(){var a=this.childNodes[0].childNodes[0].data.substr(8,73).split("|"),b=this;rcloud.resolve_deferred_result(a[1],function(a){$(b).replaceWith(function(){return shell.handle(a.value[0].value[0],a)})})}),o.find("pre code").each(function(a,b){hljs.highlightBlock(b)}),_.isUndefined(MathJax)||MathJax.Hub.Queue(["Typeset",MathJax.Hub]),this.show_result(),w[0].scrollIntoView()},hide_buttons:function(){l.css("display","none"),r.css("display","none")},show_buttons:function(){l.css("display",null),r.css("display",null)},show_source:function(){c.css({height:""}),j(d),i(e),i(f),i(g),n.show(),q.show(),v.hide(),u.focus(),x="source"},show_result:function(){c.css({height:""}),i(d),j(e),i(f),i(g),n.hide(),q.hide(),v.slideDown(150,function(){w[0].scrollIntoView()}),x="result"},hide_all:function(){c.css({height:""}),i(d),i(e),j(f),i(g),n.hide(),x==="result"?v.slideUp(150):q.slideUp(150)},remove_self:function(){b.parent_model.remove_cell(b),c.remove()},div:function(){return c},update_model:function(){h()},focus:function(){u.focus()}};y.show_result(),y.content_updated();return y}function b(b){function l(){z.html("Computing..."),i(),C.show_result(),b.controller.execute()}function k(a){a.addClass("button-disabled")}function j(a){a.removeClass("button-disabled")}function i(){b.content(v.getSession().getValue())}var c=$("<div class='notebook-cell'></div>"),d=a("icon-edit","source"),e=a("icon-picture","result"),f=a("icon-resize-small","hide"),g=a("icon-trash","remove"),h=a("icon-repeat","run");d.click(function(a){$(a.currentTarget).hasClass("button-disabled")||C.show_source()}),e.click(function(a){$(a.currentTarget).hasClass("button-disabled")||C.show_result()}),f.click(function(a){$(a.currentTarget).hasClass("button-disabled")||C.hide_all()}),g.click(function(a){$(a.currentTarget).hasClass("button-disabled")||(b.parent_model.controller.remove_cell(b),$(".tooltip").remove())}),h.click(function(a){l()});var m=$("<div style='position:relative; float: right; z-index:10000'></div>"),n=$("<div style='margin:0.5em;'></div>"),o=$("<div style='margin:0.5em;'></div>");n.append(d),n.append(e),n.append(f),n.append(g),m.append(n),o.append(h),o.hide(),m.append(o),c.append(m);var p=$("<div></div>"),q=$("<div style='clear:both;'></div>");c.append(p),c.append(q);var r=$('<div style="position: relative; width:100%; height:100%"></div>'),s=$('<div style="position: absolute; right:-0.5em; top:-0.5em"></div>'),t=a("icon-plus-sign","insert cell");p.append(s),s.append(t),t.click(function(a){var b=c.index(),d=b;shell.insert_markdown_cell_before(d)});var u=$('<div style="width:100%; height:100%"></div>');p.append(r),r.append(u);var v=ace.edit(u[0]),w=require("mode/rmarkdown").Mode,x=v.getSession(),y=x.doc;v.getSession().setMode(new w(!1,y,x)),v.setTheme("ace/theme/chrome"),v.getSession().setUseWrapMode(!0),v.resize(),v.commands.addCommand({name:"sendToR",bindKey:{win:"Ctrl-Return",mac:"Command-Return",sender:"editor"},exec:function(a,b,c){l()}});var z=$('<div class="r-result-div"><span style="opacity:0.5">Not evaluated</span></div>');p.append(z);var A=$("<span></span>");p.append(A);var B,C={content_updated:function(){v.getSession().setValue(b.content())},self_removed:function(){c.remove()},result_updated:function(a){z.hide(),z.html(a.value[0]),z.slideDown(150);var b=rcloud.wplot_uuid;p.find("pre code").contents().filter(function(){return this.nodeValue.indexOf(b)!==-1}).parent().parent().each(function(){var a=this.childNodes[0].childNodes[0].data.substr(8,73).split("|"),b=this;rcloud.resolve_deferred_result(a[1],function(a){$(b).replaceWith(function(){return shell.handle(a.value[0].value[0],a)})})}),p.find("pre code").each(function(a,b){hljs.highlightBlock(b)}),_.isUndefined(MathJax)||MathJax.Hub.Queue(["Typeset",MathJax.Hub]),this.show_result(),A[0].scrollIntoView()},hide_buttons:function(){m.css("display","none"),s.css("display","none")},show_buttons:function(){m.css("display",null),s.css("display",null)},show_source:function(){c.css({height:"70%"}),k(d),j(e),j(f),j(g),o.show(),r.show(),z.hide(),v.resize(),v.focus(),B="source"},show_result:function(){c.css({height:""}),j(d),k(e),j(f),j(g),o.hide(),r.hide(),z.slideDown(150,function(){A[0].scrollIntoView()}),B="result"},hide_all:function(){c.css({height:""}),j(d),j(e),k(f),j(g),o.hide(),B==="result"?z.slideUp(150):r.slideUp(150)},remove_self:function(){b.parent_model.remove_cell(b),c.remove()},div:function(){return c},update_model:function(){i()},focus:function(){v.focus()}};C.show_result(),C.content_updated();return C}function a(a,b){return $("<span class='fontawesome-button'><i class='"+a+"'></i></span>").tooltip({title:b,delay:{show:250,hide:0}})}var d={markdown:b,interactive:c};Notebook.Cell.create_html_view=function(a){return d[a.type()](a)}}(),Notebook.Cell.create_model=function(a,b){function d(){_.each(c.views,function(a){a.content_updated()})}var c={views:[],type:function(){return b},content:function(b){_.isUndefined(b)||(a=b,d());return a},json:function(){return{content:a,type:b}}};return c},Notebook.Cell.create_controller=function(a){var b={execute:function(){function d(b){_.each(a.views,function(a){a.result_updated(b)})}var b=this,c=a.type();rclient.record_cell_execution(a);if(c==="markdown"){var e=rclient.markdown_wrap_command(a.content());rclient.send_and_callback(e,d,_.identity)}else if(c==="interactive"){var e=rclient.markdown_wrap_command("```{r}\n"+a.content()+"\n```\n");rclient.send_and_callback(e,d,_.identity)}else alert("Can only do markdown or interactive for now!")}};return b},Notebook.create_html_view=function(a,b){var c={model:a,sub_views:[],cell_appended:function(a){var c=Notebook.Cell.create_html_view(a);a.views.push(c),b.append(c.div()),this.sub_views.push(c);return c},cell_inserted:function(a,c){var d=Notebook.Cell.create_html_view(a);a.views.push(d),b.append(d.div()),$(d.div()).insertBefore(b.children()[c]),this.sub_views.splice(c,0,d),d.show_source();return d},cell_removed:function(a,b){_.each(a.views,function(a){a.self_removed()}),this.sub_views.splice(b,1)},update_model:function(){_.each(this.sub_views,function(a){a.update_model()})}};a.views.push(c);return c},Notebook.create_model=function(){return{notebook:[],views:[],clear:function(){while(this.notebook.length)this.remove_cell(this.notebook[this.notebook.length-1])},append_cell:function(a){a.parent_model=this,this.notebook.push(a),_.each(this.views,function(b){b.cell_appended(a)})},insert_cell:function(a,b){a.parent_model=this,this.notebook.splice(b,0,a),_.each(this.views,function(c){c.cell_inserted(a,b)})},json:function(){return _.map(this.notebook,function(a){return a.json()})},remove_cell:function(a){var b=this.notebook.indexOf(a);if(b===-1)throw"cell_model not in notebook model?!";_.each(this.views,function(c){c.cell_removed(a,b)}),this.notebook.splice(b,1)}}},Notebook.create_controller=function(a){var b={append_cell:function(b,c){var d=Notebook.Cell.create_model(b,c),e=Notebook.Cell.create_controller(d);d.controller=e,a.append_cell(d);return e},insert_cell:function(b,c,d){var e=Notebook.Cell.create_model(b,c),f=Notebook.Cell.create_controller(e);e.controller=f,a.insert_cell(e,d);return f},remove_cell:function(b){a.remove_cell(b)},clear:function(){a.clear()},load_from_file:function(a,b,c){var d=this;rcloud.load_user_file(a,b,function(a){var b=JSON.parse(a.value.join("\n"));d.clear(),_.each(b,function(a){var b=d.append_cell(a.content,a.type)}),c()})},save_file:function(b,c,d){var e=this,f=JSON.stringify(a.json());rcloud.load_user_file(b,c,function(a){a=a.value.join("\n"),f!==a?rcloud.save_to_user_file(b,c,f,function(){d&&d()}):d&&d()})},run_all:function(){_.each(a.notebook,function(a){a.controller.execute()})}};a.controller=b;return b}
+(function(){function g(a){return typeof a=="function"?a:function(a){return function(){return a}}(a)}function e(a,b){if(_.isUndefined(c[b])){var e=new Uint8Array(a.data().length);d[b]=e,c[b]=[a]}else c[b].push(a)}function b(a,b,c){var d=a.slice((c||b)+1||a.length);a.length=b<0?a.length+b:b;return a.push.apply(a,d)}function a(a,b){return"translate("+a+","+b+")"}Chart={};var c={},d={};Chart.get_selections=function(a){return d[this.group_id]},Chart.set_selections=function(a,b){for(var e=0;e<b.length;e++)d[a][e]=b[e];_.each(c[a],function(a){_.each(a.views,function(a){a.selection_changed()})})},Chart.data_model=function(a,b){var f=a.length,g={views:{},group_id:b,data:function(){return a},selection:function(){return d[this.group_id]},register_view:function(a){this.views[a._view_index]=a},deregister_view:function(a){delete this.views[a._view_index]},notify:function(){_.each(c[this.group_id],function(a){_.each(a.views,function(a){a.selection_changed()})})},clear_brushes:function(a){_.each(c[this.group_id],function(b){_.each(b.views,function(b){b._view_index!==a._view_index&&(console.log("clearing brush on view",b._view_index,b,a),b.clear_brush())})})}};e(g,b);return g};var f=0;Chart.scatterplot=function(b){function J(){v.empty()&&F(y)}function I(a){var c=v.extent(),d=h.selection();y.each(function(a){var e=i[a],f=c[0][0]<=b.x(e)&&b.x(e)<=c[1][0]&&c[0][1]<=b.y(e)&&b.y(e)<=c[1][1];d[a]=f}),h.notify()}function H(a){h.clear_brushes(s)}function G(c){c.attr("d",d3.svg.symbol().type("circle")).attr("size",5).attr("transform",function(c){c=i[c];return a(p(b.x(c)),q(b.y(c)))}).style("stroke-width",function(a){return s.opts.stroke_width(i[a])})}function F(){var a=h.selection();z.attr("display",function(b){return a[b]?null:"none"})}b=_.defaults(b,{width:400,height:400,padding:20,n_xticks:10,n_yticks:10,stroke:"white",stroke_width:"1.5px",fill:"black",stroke_opacity:1,fill_opacity:1}),b.stroke=g(b.stroke),b.stroke_opacity=g(b.stroke_opacity),b.stroke_width=g(b.stroke_width),b.fill=g(b.fill),b.fill_opacity=g(b.fill_opacity);var c=b.width,d=b.height,e=b.padding,h=b.data,i=h.data(),j=_.map(i,b.x),k=_.map(i,b.y),l=_.min(j),m=_.max(j),n=_.min(k),o=_.max(k),p=d3.scale.linear().domain([l,m]).range([0,c]),q=d3.scale.linear().domain([n,o]).range([d,0]),r=$("<div></div>")[0],s={_view_index:++f,opts:b,plot:r,clear_brush:function(){u.call(v.clear())},selection_changed:function(){F()},deleted:function(){h.deregister_view(this)}};h.register_view(s);var t=d3.select(r).append("svg").attr("width",c+2*e).attr("height",d+2*e),u=t.append("g").attr("transform",a(e,e)),v=d3.svg.brush().on("brushstart",H).on("brush",I).on("brushend",J);u.append("rect").attr("width",c).attr("height",d).attr("fill","#eee");var w=u.selectAll("g.x").data(p.ticks(b.n_xticks)).enter().append("g").attr("class","x");w.append("line").attr("x1",p).attr("x2",p).attr("y1",0).attr("y2",d),w.append("text").attr("x",p).attr("y",d+3).attr("dy",".71em").attr("text-anchor","middle").attr("class","rule-text").text(p.tickFormat(b.n_xticks));var x=u.selectAll("g.y").data(q.ticks(b.n_yticks)).enter().append("g").attr("class","x");x.append("line").attr("x1",0).attr("x2",c).attr("y1",q).attr("y2",q),x.append("text").attr("x",-3).attr("y",q).attr("dy",".35em").attr("text-anchor","end").attr("class","rule-text").text(q.tickFormat(b.n_yticks));var y=u.selectAll("path.dot").data(_.range(i.length)).enter().append("path"),z=u.selectAll("pathasdkf.dot").data(_.range(i.length)).enter().append("path"),A=function(a){return i[a]};y.style("fill",_.compose(b.fill,A)).style("stroke",_.compose(b.stroke,A)).style("fill-opacity",_.compose(b.fill_opacity,A)).style("stroke-opacity",_.compose(b.stroke_opacity,A)),u.call(v.x(p).y(q));var B=function(){return"red"},C=function(){return"red"},D=function(){return 1},E=function(){return 1};z.style("fill",_.compose(B,A)).style("stroke",_.compose(C,A)).style("fill-opacity",_.compose(D,A)).style("stroke-opacity",_.compose(E,A)),t.on("keydown",function(a){console.log(a)}),G(y),G(z),F();return s},Chart.histogram=function(a){a=_.defaults(a,{width:400,height:400,padding:20,n_bins:10,stroke:"white",stroke_width:"1.5px",fill:"black",stroke_opacity:1,fill_opacity:1}),a.stroke=g(a.stroke),a.stroke_opacity=g(a.stroke_opacity),a.stroke_width=g(a.stroke_width),a.fill=g(a.fill),a.fill_opacity=g(a.fill_opacity);var b=a.width,c=a.height,d=a.padding,e=a.data,h=e.data(),i=_.map(h,a.x),j=_.min(i),k=_.max(i),l=$("<div></div>")[0],m=d3.scale.linear().domain([j,k]).range([0,b]),n=d3.layout.histogram().range([j,k]).bins(a.n_bins),o=n(a.x),p={_view_index:++f,opts:a,plot:l,clear_brush:function(){vis.call(brush.clear())},selection_changed:function(){update_selection()},deleted:function(){e.deregister_view(this)}}}})(),FacetChart={},FacetChart.facet_tour_plot=function(a){function l(a){var b=[],c=[],d=0,e=0;for(var f=0;f<a;++f)b[f]=Math.random()*2-1,c[f]=Math.random()*2-1,d+=b[f]*b[f],e+=c[f]*c[f];d=Math.sqrt(d),e=Math.sqrt(e);if(d===0||e===0)return l(a);var g=0;for(f=0;f<a;++f)b[f]/=d,c[f]/=e,g+=b[f]*c[f];var h=0;for(f=0;f<a;++f)c[f]=c[f]-g*b[f],h+=c[f]*c[f];h=Math.sqrt(h);if(h===0)return l(a);for(f=0;f<a;++f)c[f]/=h;return[b,c]}function k(){Facet.set_context(m),f=j();var a=10,b=2.5,c=1;g=[],h=[];var d,i,k=[],l=Shade.vec(0,0),n=Shade.vec(0,0),o=Shade.vec(0,0);for(var p=0;p<f.columns.length;++p){var q=f[f.columns[p]];g.push(Shade.parameter("float")),h.push(Shade.parameter("float"));var r=Shade.vec(g[p],h[p]);d=_.min(q.array),i=_.max(q.array),k=(i+d)/2,l=l.add(r.mul(q)),n=n.add(r.mul(k)),o=o.add(r.mul(k-d).abs())}var s=Shade.color("red");e=Facet.Marks.scatterplot({elements:f[f.columns[0]].numItems,xy:l,xy_scale:Shade.Utils.linear(n.sub(o),n.add(o),Shade.vec(0,0),Shade.vec(1,1)),fill_color:s,stroke_color:Shade.mix(Shade.color("black"),s,.5),stroke_width:b,point_diameter:a})}function j(){var b={},c=[];for(var d=0;d<a.value.length;++d)b["dim_"+d]=Facet.attribute_buffer({vertex_array:a.value[d].value,item_size:1,keep_array:!0}),c.push("dim_"+d);b.columns=c;return b}function i(){m.viewport(0,0,m.viewportWidth,m.viewportHeight),m.clearDepth(1),m.clearColor(0,0,0,0),m.clear(m.COLOR_BUFFER_BIT|m.DEPTH_BUFFER_BIT),e.draw()}var b=600,c=600,d=$("<canvas width='"+b+"' height='"+c+"'></canvas>")[0],e,f,g,h,m=Facet.init(d,{clearColor:[1,1,1,1]});k();var n=l(f.columns.length),o=l(f.columns.length),p=(new Date).getTime(),q=1,r=function(){var a=((new Date).getTime()-p)/1e3,b=a/3;b-=Math.floor(b),b<q&&(n=o,o=l(4)),q=b;for(var c=0;c<f.columns.length;++c)g[c].set(b*o[0][c]+(1-b)*n[0][c]),h[c].set(b*o[1][c]+(1-b)*n[1][c]);window.requestAnimFrame(r,d),i()};r();return d},FacetChart.facet_osm_plot=function(a,b,c,d,e){var f=$("<canvas width='"+d+"' height='"+e+"'></canvas>")[0],g=Facet.init(f,{clearColor:[1,1,1,1],mousedown:function(a){var b=j.mousedown(a);return b},mousemove:function(a){var b=j.mousemove(a);return b},mouseup:function(a){var b=j.mouseup(a);return b}}),h=Shade.parameter("float",3),i=Shade.Camera.perspective({look_at:[Shade.vec(0,0,6),Shade.vec(0,0,-1),Shade.vec(0,1,0)],field_of_view_y:Shade.div(20,h)}),j=Facet.Marks.globe({view_proj:i,zoom:h});a=Facet.attribute_buffer({vertex_array:a,item_size:1}),b=Facet.attribute_buffer({vertex_array:b,item_size:1}),console.log(c),c.length===3?c=Shade.vec(c[0],c[1],c[2],1):c.length>1&&(c=Shade.vec(Facet.attribute_buffer({vertex_array:c,item_size:3}),1));var k=Facet.model({type:"points",lats:a,lons:b}),l=Facet.bake(k,{color:c,point_size:2,position:j.lat_lon_position(k.lats.radians(),k.lons.radians())});Facet.Scene.add(j),Facet.Scene.add(l);return f},function(a){if(a.WebSocket===undefined)if(a.MozWebSocket)a.WebSocket=a.MozWebSocket;else throw"WebSocket support not found"}(this),function(){function g(a){function c(){var a=document.createElement("table"),b=document.createElement("tr");a.appendChild(b);var c=this.attributes.value.dim.value,d=this.value,e=this;d3.select(b).selectAll("td").data(_.range(c[1]+1)).enter().append("td").text(function(a){return a===0?"":"[,"+a+"]"}),d3.select(a).selectAll("tr-data").data(_.range(c[0])).enter().append("tr").selectAll("td").data(function(a){return _.map(_.range(c[1]+1),function(b){return[a,b]})}).enter().append("td").text(function(a){var b=a[0],f=a[1];if(f===0)return"["+(b+1)+",]";var g=d[(f-1)*c[0]+b];return e.attributes&&e.attributes.value.levels?e.attributes.value.levels.value[g-1]:g});return a}function b(){var b=$("<div class='obj'></div>"),c=$("<div class='string-value'></div>"),d=this.value,e,f=this;a=a||function(a){return a};var g;this.attributes&&this.attributes.value.names?g=function(b){return f.attributes.value.names.value[b]+": "+a(String(d[b]))}:this.attributes&&this.attributes.value.levels?g=function(a){return f.attributes.value.levels.value[d[a]-1]}:g=function(b){return a(String(d[b]))};if(d.length===0)e="[]";else if(d.length===1)e=g(0);else if(d.length<=10){e="["+g(0);for(var h=1;h<d.length;++h)e=e+", "+g(h);e=e+"]"}else{e="["+g(0);for(var h=1;h<5;++h)e=e+", "+g(h);e=e+", ... ";for(h=d.length-5;h<d.length;++h)e=e+", "+g(h);e=e+"]"}c.html(e),b.append(c);return b}return function(){return this.attributes&&this.attributes.value.dim?c.call(this):b.call(this)}}function f(a,b){return function(c,d){function e(){this.type=a,this.value=c,this.attributes=d}e.prototype=b||{html_element:function(){return $("<div class='obj'></div>").append($("<div class='key'></div>").html(a))}};return new e}}function e(c){var d=c.read_int(),e=b.par_parse(d),f=e[0],g=e[1];if(f===b.DT_INT)return{type:"int",value:c.read_int()};if(f===b.DT_STRING)return{type:"string",value:c.read_string(g)};if(f===b.DT_BYTESTREAM)return{type:"stream",value:c.read_stream(g)};if(f===b.DT_SEXP){e=c.read_sexp();var h=e[0],i=e[1];return{type:"sexp",value:h}}throw new a("Bad type for parse? "+f+" "+g,-1)}function d(d){var f=new Int32Array(d,0,4);if(f[0]!==b.RESP_OK&&f[0]!==b.OOB_SEND){var g=f[0]>>24;throw new a("ERROR FROM R SERVER: "+(b.status_codes[g]||g)+" "+f[0]+" "+f[1]+" "+f[2]+" "+f[3]+" "+d.byteLength+" "+d,g)}var h=my_ArrayBufferView(d,16,d.byteLength-16);if(h.length===0)return null;var i=e(c(h));return[i,f[0]]}function c(c){function k(a,b){return f(function(c,d){return b(a.call(i,d),c)})}function j(a,b){return g(a,function(a){return f(function(c,d){return b(a,c)},0)})}function h(a){return function(b,c){var d=[],e=c;while(c>0){var f=a.call(i,b,c);d.push(f[0]),c-=f[1]}return[d,e]}}function g(a,b){return function(c,d){var e=a.call(i,c,d),f=b(e[0])(c,d-e[1]);return[f[0],e[1]+f[1]]}}function f(a,b){return function(c,d){return[a.call(i,c,d),b||d]}}var d={},e,i={offset:0,data_view:c.make(EndianAwareDataView),msg:c,read_int:function(){var a=this.offset;this.offset+=4;return this.data_view.getInt32(a)},read_string:function(a){var b="";while(a--){var c=this.data_view.getInt8(this.offset++);c&&(b=b+String.fromCharCode(c))}return b},read_stream:function(a){var b=this.offset;this.offset+=a;return this.msg.view(b,a)},read_int_vector:function(a){var b=this.offset;this.offset+=a;return this.msg.make(Int32Array,b,a)},read_double_vector:function(a){var b=this.offset;this.offset+=a;return this.msg.make(Float64Array,b,a)},read_null:f(function(a,b){return Robj.null(a)}),read_string_array:function(a,b){var c=this.read_stream(b).make(Uint8Array),d=[],e="";for(var f=0;f<c.length;++f)c[f]===0?(d.push(e),e=""):e=e+String.fromCharCode(c[f]);return[Robj.string_array(d,a),b]},read_bool_array:function(a,b){var c=this.read_int(),d=this.read_stream(b-4),e=d.make(Uint8Array),f=[];for(var g=0;g<c;++g)f[g]=!!e[g];return[Robj.bool_array(f,a),b]},read_sexp:function(){var c=this.read_int(),e=b.par_parse(c),f=e[0],g=e[1],h=4,i=undefined;if(f&b.XT_HAS_ATTR){f=f&~b.XT_HAS_ATTR;var j=this.read_sexp();i=j[0],h+=j[1],g-=j[1]}if(d[f]===undefined)throw new a("Unimplemented "+f,-1);var k=d[f].call(this,i,g);return[k[0],h+k[1]]}};i.read_clos=g(i.read_sexp,function(a){return g(i.read_sexp,function(b){return f(function(c,d){return Robj.clos(a,b,c)},0)})}),i.read_list=h(i.read_sexp),i.read_list_tag=g(i.read_list,function(b){return f(function(c,d){var e={};for(var f=0;f<b.length;f+=2){var g=b[f],h=b[f+1];if(h.type!=="symbol")throw new a("Unexpected type "+h.type+" as tag for tagged_list",-1);e[h.value]=g}return Robj.tagged_list(e,c)},0)}),i.read_vector=j(i.read_list,Robj.vector),i.read_list_no_tag=j(i.read_list,Robj.list),i.read_lang_no_tag=j(i.read_list,Robj.lang),i.read_vector_exp=j(i.read_list,Robj.vector_exp),i.read_symname=k(i.read_string,Robj.symbol),i.read_int_array=k(i.read_int_vector,Robj.int_array),i.read_double_array=k(i.read_double_vector,Robj.double_array),d[b.XT_NULL]=i.read_null,d[b.XT_VECTOR]=i.read_vector,d[b.XT_CLOS]=i.read_clos,d[b.XT_SYMNAME]=i.read_symname,d[b.XT_LIST_NOTAG]=i.read_list_no_tag,d[b.XT_LIST_TAG]=i.read_list_tag,d[b.XT_LANG_NOTAG]=i.read_lang_no_tag,d[b.XT_VECTOR_EXP]=i.read_vector_exp,d[b.XT_ARRAY_INT]=i.read_int_array,d[b.XT_ARRAY_DOUBLE]=i.read_double_array,d[b.XT_ARRAY_STR]=i.read_string_array,d[b.XT_ARRAY_BOOL]=i.read_bool_array;return i}function a(a,b){this.name="RserveError",this.message=a,this.status_code=b}a.prototype=Object.create(Error),a.prototype.constructor=a;var b={PAR_TYPE:function(a){return a&255},PAR_LEN:function(a){return a>>8},PAR_LENGTH:function(a){return a>>8},par_parse:function(a){return[b.PAR_TYPE(a),b.PAR_LEN(a)]},SET_PAR:function(a,b){return(b&16777215)<<8|a&255},CMD_STAT:function(a){return a>>24&127},SET_STAT:function(a,b){return a|(b&127)<<24},CMD_RESP:65536,RESP_OK:65537,RESP_ERR:65538,OOB_SEND:200704,ERR_auth_failed:65,ERR_conn_broken:66,ERR_inv_cmd:67,ERR_inv_par:68,ERR_Rerror:69,ERR_IOerror:70,ERR_notOpen:71,ERR_accessDenied:72,ERR_unsupportedCmd:73,ERR_unknownCmd:74,ERR_data_overflow:75,ERR_object_too_big:76,ERR_out_of_mem:77,ERR_ctrl_closed:78,ERR_session_busy:80,ERR_detach_failed:81,CMD_long:1,CMD_voidEval:2,CMD_eval:3,CMD_shutdown:4,CMD_openFile:16,CMD_createFile:17,CMD_closeFile:18,CMD_readFile:19,CMD_writeFile:20,CMD_removeFile:21,CMD_setSEXP:32,CMD_assignSEXP:129,CMD_detachSession:48,CMD_detachedVoidEval:49,CMD_attachSession:50,CMD_ctrl:64,CMD_ctrlEval:66,CMD_ctrlSource:69,CMD_ctrlShutdown:68,CMD_setBufferSize:129,CMD_setEncoding:130,CMD_SPECIAL_MASK:240,CMD_serEval:245,CMD_serAssign:246,CMD_serEEval:247,DT_INT:1,DT_CHAR:2,DT_DOUBLE:3,DT_STRING:4,DT_BYTESTREAM:5,DT_SEXP:10,DT_ARRAY:11,DT_LARGE:64,XT_NULL:0,XT_INT:1,XT_DOUBLE:2,XT_STR:3,XT_LANG:4,XT_SYM:5,XT_BOOL:6,XT_S4:7,XT_VECTOR:16,XT_LIST:17,XT_CLOS:18,XT_SYMNAME:19,XT_LIST_NOTAG:20,XT_LIST_TAG:21,XT_LANG_NOTAG:22,XT_LANG_TAG:23,XT_VECTOR_EXP:26,XT_VECTOR_STR:27,XT_ARRAY_INT:32,XT_ARRAY_DOUBLE:33,XT_ARRAY_STR:34,XT_ARRAY_BOOL_UA:35,XT_ARRAY_BOOL:36,XT_RAW:37,XT_ARRAY_CPLX:38,XT_UNKNOWN:48,XT_LARGE:64,XT_HAS_ATTR:128,BOOL_TRUE:1,BOOL_FALSE:0,BOOL_NA:2,GET_XT:function(a){return a&63},GET_DT:function(a){return a&63},HAS_ATTR:function(a){return(a&b.XT_HAS_ATTR)>0},IS_LARGE:function(a){return(a&b.XT_LARGE)>0},itop:function(a){return a},ptoi:function(a){return a},dtop:function(a){return a},ptod:function(a){return a},fixdcpy:function(){throw new a("unimplemented",-1)},status_codes:{65:"ERR_auth_failed",66:"ERR_conn_broken",67:"ERR_inv_cmd",68:"ERR_inv_par",69:"ERR_Rerror",70:"ERR_IOerror",71:"ERR_notOpen",72:"ERR_accessDenied",73:"ERR_unsupportedCmd",74:"ERR_unknownCmd",75:"ERR_data_overflow",76:"ERR_object_too_big",77:"ERR_out_of_mem",78:"ERR_ctrl_closed",80:"ERR_session_busy",81:"ERR_detach_failed"}};Robj={"null":function(a){return{type:"null",value:null,attributes:a,html_element:function(){return $("<div class='obj'><div class='key'>null</div></div>")}}},clos:function(a,b,c){return{type:"clos",value:{formals:a,body:b},attributes:c,html_element:function(){var a=$("<div class='obj'></div>"),b=$("<div></div>");b.append($("<div class='key'>formals:</div>")),b.append(this.value.formals.html_element()),a.append(b),b=$("<div></div>"),b.append($("<div class='key'>body:</div>")),b.append(this.value.body.html_element()),a.append(b);return a}}},vector:f("vector",{html_element:function(){var a=$("<div class='obj'></div>");if(!this.attributes)for(var b=0;b<this.value.length;++b)a.append(this.value[b].html_element());else{var c=_.map(this.value,function(a){return a.value.length}),d=this.attributes.value.names.value;if(_.all(c,function(a){return a===c[0]})){var e=document.createElement("table"),f=document.createElement("tr"),g=this.value;e.appendChild(f),d3.select(f).selectAll("th").data(_.range(c.length)).enter().append("th").text(function(a){return d[a]});var h;c[0]<11?h=_.range(c[0]):(h=[0,1,2,3,4,5],h.push.apply(h,_.range(c[0]-5,c[0]))),d3.select(e).selectAll("tr-data").data(h).enter().append("tr").selectAll("td").data(function(a){return _.map(_.range(c.length),function(b){return[a,b]})}).enter().append("td").text(function(a,b){var d=a[0],e=a[1];if(c[0]>=11&&d===5)return"...";var f=g[e].value[d];return g[e].attributes?g[e].attributes.value.levels.value[f-1]:f}),a.append(e)}else{var i=$("<div></div>");for(var b=0;b<this.value.length;++b)i.append($("<span class='key'></span>").append(d[b]+": ")),i.append(this.value[b].html_element());a.append(i)}}return a}}),symbol:f("symbol"),list:f("list"),lang:f("lang"),tagged_list:f("tagged_list"),tagged_lang:f("tagged_lang"),vector_exp:f("vector_exp"),int_array:f("int_array",{html_element:g()}),double_array:f("double_array",{html_element:g()}),string_array:f("string_array",{html_element:g(function(a){var b,c,d=a.length,e='"';for(c=0;c<d;c+=1){b=a.charAt(c);if(b>=" "){if(b==="\\"||b==='"')e+="\\";e+=b}else switch(b){case"\b":e+="\\b";break;case"\f":e+="\\f";break;case"\n":e+="\\n";break;case"\r":e+="\\r";break;case"\t":e+="\\t";break;default:b=b.charCodeAt(),e+="\\u00"+Math.floor(b/16).toString(16)+(b%16).toString(16)}}return e+'"'})}),bool_array:f("bool_array",{html_element:g()})},Rserve={create:function(c){function m(a){a=a.data,a.substr(0,4)!=="Rsrv"?h("server is not an RServe instance",-1):a.substr(4,4)!=="0103"?h("sorry, rserve only speaks the 0103 version of the R server protocol",-1):a.substr(8,4)!=="QAP1"?h("sorry, rserve only speaks QAP1",-1):(i=!0,c.login&&k.login(c.login),k.running=!0,f&&f.call(k))}var e=c.host,f=c.on_connect,g=new WebSocket(e),h=c.on_error||function(b){throw new a(b,-1)};g.binaryType="arraybuffer";var i=!1,j=[],k,l=0;g.onclose=function(a){k.running=!1,c.on_close&&c.on_close(a)},g.onmessage=function(e){if(!i)m(e);else if(typeof e.data=="string")c.on_raw_string&&c.on_raw_string(e.data);else{var f;try{f=d(e.data)}catch(g){h(g.message,g.status_code);return}if(f===null)return;var k=f[1];f=f[0];switch(k){case b.RESP_OK:var l=j.shift();l(f);break;case b.OOB_SEND:c.on_data&&c.on_data(f);break;default:throw new a("Internal Error, parse returned unexpected type "+k,-1)}}},k={close:function(){g.close()},login:function(a){var b=a,c=new ArrayBuffer(b.length+21),d=new EndianAwareDataView(c);d.setInt32(0,1),d.setInt32(4,5+b.length),d.setInt32(8,0),d.setInt32(12,0),d.setInt32(16,4+(1+b.length<<8));for(var e=0;e<b.length;++e)d.setUint8(20+e,b.charCodeAt(e));d.setUint8(c.byteLength-1,0),g.send(c)},eval:function(a,b){b=b||function(){},j.push(b);var c=new ArrayBuffer(a.length+21),d=new EndianAwareDataView(c);d.setInt32(0,3),d.setInt32(4,5+a.length),d.setInt32(8,0),d.setInt32(12,0),d.setInt32(16,4+(1+a.length<<8));for(var e=0;e<a.length;++e)d.setUint8(20+e,a.charCodeAt(e));d.setUint8(c.byteLength-1,0),g.send(c)}};return k}}}(),function(){function c(){throw new b}function b(){this.name="NoCallbackError"}function a(a){return'"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}b.prototype=Object.create(Error),b.prototype.constructor=b,RClient={create:function(d){function g(a){m.post_response("Socket was closed. Goodbye!"),m.running=!1}function f(a,b){b===65?(m.post_error("Authentication failed. Login first!"),m.post_error(a)):m.post_error(a)}function e(){m.running=!0,m.send("rcloud.support::session.init(username="+a(rcloud.username())+")"),d.on_connect&&d.on_connect.call(m)}var h=$.cookies.get().token,i=Rserve.create({host:d.host,on_connect:e,on_error:f,on_close:g,login:h+"\n"+h}),j=!0,k=!1,l=undefined,m,n=0;m={handlers:{eval:function(a){if(a.value.length===3){var b=a.value[2].value[0];m.display_response(a.value[1])}return a.value[1]},"markdown.eval":function(a){if(a.value.length===3){var b=a.value[2].value[0];m.display_markdown_response(a.value[1])}return a.value[1]},browsePath:function(a){$.ajax({url:"http://127.0.0.1:8080"+a.value[1].value}).done(function(a){var b=/[\s\S]*<body>([\s\S]*)<\/body>/g.exec(a)[1];$("#help-output").html(b)})},"img.url.update":function(a){return a.value[1]},"img.url.final":function(a){return a.value[1]},"dev.new":function(a){return""},"dev.close":function(a){return""},internal_cmd:function(a){return""},"boot.failure":function(a){m.running=!1}},running:!1,result_handlers:{},eval:function(a){var b=this;if(a.type!=="sexp")return this.post_error("Bad protocol, should always be sexp.");a=a.value;if(a.type==="string_array")return this.post_error(a.value[0]);if(a.type==="null")return null;if(a.type!=="vector")return this.post_error("Protocol error, unexpected value of type "+a.type);if(a.value[0].type!=="string_array"||a.value[0].value.length!==1){console.log("Protocol error?! ",a.value[0]);return undefined}var c=a.value[0].value[0],d=this.handlers;if(d[c]===undefined)return this.post_error("Unknown command "+c);if(c=="img.url.update"||c=="img.url.final"){var e=window.devImgIndex;e||(window.devImgIndex=e=1),c=="img.url.final"&&window.devImgIndex++;var f=document.getElementById("dimg"+e);f?f.innerHTML="<img src="+a.value[1].value[0]+">":this.post_div("<div id=dimg"+e+"><img src="+a.value[1].value[0]+"></div>")}return d[c].call(this,a)},register_handler:function(a,b){this.handlers[a]=b},post_sent_command:function(a){var b=$('<pre class="r-sent-command"></pre>').html("> "+a);$("#output").append(b)},post_debug_message:function(a){var b=new Uint8Array(a),c=Array.prototype.join.call(b,",");this.post_response(c)},post_div:function(a){return shell.post_div(a)},post_binary_response:function(a){if(j)this.post_debug_message(a),this.display_response(parse(a));else try{this.display_response(parse(a))}catch(b){this.post_error("Uncaught exception: "+b.message+" - "+b.status_code)}},display_response:function(a){a&&$("#output").append(a.html_element()),window.scrollTo(0,document.body.scrollHeight)},display_markdown_response:function(a){a&&($("#output").append($("<div></div>").html(a.value[0])).find("pre code").each(function(a,b){hljs.highlightBlock(b)}),MathJax.Hub.Queue(["Typeset",MathJax.Hub]))},post_error:function(a){debugger;var b=$("<div class='error-message'></div>").html(a);$("#output").append(b),window.scrollTo(0,document.body.scrollHeight)},post_response:function(a){var b=$("<pre></pre>").html(a);$("#output").append(b),window.scrollTo(0,document.body.scrollHeight)},capture_answers:function(a,b){function d(d){c.push(d),a--,a===0&&(k=!1,l=undefined,b(c))}if(k)throw"Still waiting for previous answers...";k=!0;var c=[];l=d},wrap_command:function(a,b){var c=n++;b===undefined&&(b=!1);return["rcloud.support::session.eval({"+a+"}, "+c+", "+(b?"TRUE":"FALSE")+")",c]},markdown_wrap_command:function(b,c){var d=n++;return["rcloud.support::session.markdown.eval({markdownToHTML(text=paste(knit(text="+a(b+"\n")+'), collapse="\\n"), fragment=TRUE)}, '+d+", "+(c?"TRUE":"FALSE")+")",d]},log:function(a){a='rcloud.support::session.log("'+rcloud.username()+'", "'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'")',this.send(a)},record_cell_execution:function(a){var b=JSON.stringify(a.json()),c=this.r_funcall("rcloud.record.cell.execution",rcloud.username(),b);i.eval(c)},send:function(a,b){this.send_and_callback(a,c,b)},send_and_callback:function(a,d,e){function h(a){j&&(debugger,console.log(a));try{d(a.value.value[1])}catch(c){c.constructor===b&&(debugger,f.handlers[a.value.value[0].value[0]](a.value))}}var f=this;_.isUndefined(d)&&(d=c);var g;e?g=e(a):g=this.wrap_command(a,!0),a=g[0],j&&console.log(a),i.eval(a,h)},r_funcall:function(b){var c=[b,"("];for(var d=1;d<arguments.length;++d){var e=typeof arguments[d];e==="string"?c.push(a(arguments[d])):c.push(String(arguments[d])),d<arguments.length-1&&c.push(",")}c.push(")");var f=c.join("");return f}};return m}}}(),function(a){var b;(function(){var a=new ArrayBuffer(4),c=new Uint8Array(a),d=new Uint32Array(a);c[0]=1;if(d[0]===1)b=!0;else if(d[0]===16777216)b=!1;else throw"we're bizarro endian, refusing to continue"})();var c=["Int32","Int16","Uint32","Uint16","Float32","Float64"],d=["setInt32","setInt16","setUint32","setUint16","setFloat32","setFloat64"],e=["getInt32","getInt16","getUint32","getUint16","getFloat32","getFloat64"];if(!a.DataView){console.log("polyfilling DataView");var f={};for(var g=0;g<c.length;++g){var h=this[c[g]+"Array"],i=h.BYTES_PER_ELEMENT,j=new ArrayBuffer(i),k=new h(j),l=new Uint8Array(j);f[c[g]]=function(a,b){return function(c,d,e,f){a[0]=f;for(var g=0;g<d;++g)c[e+g]=b[g]}}(k,l)}function m(a,c,d){this.buffer=a,this.byteOffset=_.isUndefined(c)?0:c,this.byteLength=_.isUndefined(d)?a.byteLength:d,this.view=new jDataView(a,c,d,b),this.byte_array=new Uint8Array(a)}var n={};m.prototype=n;for(g=0;g<c.length;++g){var o="get"+c[g];n[o]=function(a){return function(b){return this.view[a](b)}}(o);var p="set"+c[g],i=this[c[g]+"Array"].BYTES_PER_ELEMENT;n[p]=function(a,b){return function(c,d){console.log(b),console.log(f),f[b](this.byte_array,a,c,d)}}(i,c[g])}n.setUint8=function(a,b){this.byte_array[a]=b},n.setInt8=function(a,b){b<0&&(b+=256),this.byte_array[a]=b},n.getInt8=function(a){return this.view.GetInt8(a)},n.getUint8=function(a){this.byte_array[a]},a.DataView=m}a.EndianAwareDataView=function(){function g(a,b,c){b===undefined?this.view=new DataView(a):this.view=new DataView(a,b,c)}var a={setInt8:function(a,b){return this.view.setInt8(a,b)},setUint8:function(a,b){return this.view.setUint8(a,b)},getInt8:function(a){return this.view.getInt8(a)},getUint8:function(a){return this.view.getUint8(a)}},c=["setInt32","setInt16","setUint32","setUint16","setFloat32","setFloat64"],d=["getInt32","getInt16","getUint32","getUint16","getFloat32","getFloat64"];for(var e=0;e<c.length;++e){var f=c[e];a[f]=function(a){return function(c,d){return this.view[a](c,d,b)}}(f)}for(e=0;e<d.length;++e){var f=d[e];a[f]=function(a){return function(c){return this.view[a](c,b)}}(f)}g.prototype=a;return g}(),a.my_ArrayBufferView=function(a,b,c){b=_.isUndefined(b)?0:b,c=_.isUndefined(c)?a.byteLength:c;return{buffer:a,offset:b,length:c,make:function(a,b,c){b=_.isUndefined(b)?0:b,c=_.isUndefined(c)?this.length:c;var d=a.BYTES_PER_ELEMENT||1,e=c/d;if((this.offset+b)%d!=0){var f=new DataView(this.buffer,this.offset+b,c),g=new ArrayBuffer(c),h=new DataView(g);for(var i=0;i<c;++i)h.setUint8(i,f.getUint8(i));return new a(g)}return new a(this.buffer,this.offset+b,e)},view:function(a,b){return my_ArrayBufferView(this.buffer,this.offset+a,b)}}}}(this),rcloud={},rcloud.init_client_side_data=function(){var a=this;rcloud.get_user_filenames(function(b){a.user_filenames=b.value;var c=b.value,d=d3.select("#internals-user-files");d.append("h3").text("User files"),d.append("ul").selectAll("li").data(c).enter().append("li").text(function(a){return a})}),rclient.send_and_callback("rcloud.prefix.uuid()",function(b){a.wplot_uuid=b.value[0]})},rcloud.username=function(){return $.cookies.get("user")},rcloud.get_user_filenames=function(a){_.isUndefined(a)&&(a=_.identity),rclient.send_and_callback(rclient.r_funcall("rcloud.list.initial.filenames",this.username()),a)},rcloud.search=function(a,b){var c=this;_.isUndefined(b)&&(b=_.identity),rclient.send_and_callback(rclient.r_funcall("rcloud.search",a),b)},rcloud.get_all_user_filenames=function(a){var b=this;_.isUndefined(a)&&(a=_.identity),rclient.send_and_callback(rclient.r_funcall("rcloud.list.all.initial.filenames"),a)},rcloud.load_user_file=function(a,b,c){rclient.send_and_callback(rclient.r_funcall("rcloud.load.user.file",a,b),c)},rcloud.save_to_user_file=function(a,b,c,d){rclient.send_and_callback(rclient.r_funcall("rcloud.save.to.user.file",a,b,c),d)},rcloud.create_user_file=function(a,b){rclient.send_and_callback(rclient.r_funcall("rcloud.create.user.file",rcloud.username(),a),b)},rcloud.resolve_deferred_result=function(a,b){var c=rclient.r_funcall("rcloud.fetch.deferred.result",a);rclient.send_and_callback(c,b)},Notebook={},Notebook.Cell={},function(){function c(b){function k(){v.html("Computing..."),h(),y.show_result(),b.controller.execute()}function j(a){a.addClass("button-disabled")}function i(a){a.removeClass("button-disabled")}function h(){b.content($(u).val())}var c=$("<div class='notebook-cell'></div>"),d=$("<span class='fontawesome-button'><i class='icon-edit'></i></span>").tooltip({title:"source"}),e=$("<span class='fontawesome-button'><i class='icon-picture'></i></span>").tooltip({title:"result"}),f=$("<span class='fontawesome-button'><i class='icon-resize-small'></i></span>").tooltip({title:"hide"}),g=$("<span class='fontawesome-button'><i class='icon-trash'></i></span>").tooltip({title:"remove"});d.click(function(a){$(a.currentTarget).hasClass("button-disabled")||y.show_source()}),e.click(function(a){$(a.currentTarget).hasClass("button-disabled")||y.show_result()}),f.click(function(a){$(a.currentTarget).hasClass("button-disabled")||y.hide_all()}),g.click(function(a){$(a.currentTarget).hasClass("button-disabled")||(b.parent_model.controller.remove_cell(b),$(".tooltip").remove())});var l=$("<div style='position:relative; float: right; z-index:10000'></div>"),m=$("<div style='margin:0.5em;'></div>"),n=$("<div style='margin:0.5em;'></div>");m.append(d),m.append(e),m.append(f),m.append(g),l.append(m),n.hide(),l.append(n),c.append(l);var o=$("<div></div>"),p=$("<div style='clear:both;'></div>");c.append(o),c.append(p);var q=$('<div style="position: relative; width:100%;"></div>'),r=$('<div style="position: absolute; right:-0.5em; top:-0.5em"></div>'),s=a("icon-plus-sign","insert cell");o.append(r),r.append(s),s.click(function(a){var b=c.index(),d=b;shell.insert_markdown_cell_before(d)});var t=$('<div style="width:100%; margin-left: 0.5em; margin-top: 0.5em"></div>');o.append(q),q.append(t);var u=$('<input type="text" style="width:88%"/>');t.append(u),u.keypress(function(a){if(a.which===13){k(),a.preventDefault();return!1}return!0});var v=$('<div class="r-result-div"></div>');o.append(v);var w=$("<span></span>");o.append(w);var x,y={content_updated:function(){u.val(b.content())},self_removed:function(){c.remove()},result_updated:function(a){v.hide(),v.html(a.value[0]),v.slideDown(150);var b=rcloud.wplot_uuid;o.find("pre code").contents().filter(function(){return this.nodeValue.indexOf(b)!==-1}).parent().parent().each(function(){var a=this.childNodes[0].childNodes[0].data.substr(8,73).split("|"),b=this;rcloud.resolve_deferred_result(a[1],function(a){$(b).replaceWith(function(){return shell.handle(a.value[0].value[0],a)})})}),o.find("pre code").each(function(a,b){hljs.highlightBlock(b)}),_.isUndefined(MathJax)||MathJax.Hub.Queue(["Typeset",MathJax.Hub]),this.show_result(),w[0].scrollIntoView()},hide_buttons:function(){l.css("display","none"),r.css("display","none")},show_buttons:function(){l.css("display",null),r.css("display",null)},show_source:function(){c.css({height:""}),j(d),i(e),i(f),i(g),n.show(),q.show(),v.hide(),u.focus(),x="source"},show_result:function(){c.css({height:""}),i(d),j(e),i(f),i(g),n.hide(),q.hide(),v.slideDown(150,function(){w[0].scrollIntoView()}),x="result"},hide_all:function(){c.css({height:""}),i(d),i(e),j(f),i(g),n.hide(),x==="result"?v.slideUp(150):q.slideUp(150)},remove_self:function(){b.parent_model.remove_cell(b),c.remove()},div:function(){return c},update_model:function(){h()},focus:function(){u.focus()}};y.show_result(),y.content_updated();return y}function b(b){function l(){z.html("Computing..."),i(),C.show_result(),b.controller.execute()}function k(a){a.addClass("button-disabled")}function j(a){a.removeClass("button-disabled")}function i(){b.content(v.getSession().getValue())}var c=$("<div class='notebook-cell'></div>"),d=a("icon-edit","source"),e=a("icon-picture","result"),f=a("icon-resize-small","hide"),g=a("icon-trash","remove"),h=a("icon-repeat","run");d.click(function(a){$(a.currentTarget).hasClass("button-disabled")||C.show_source()}),e.click(function(a){$(a.currentTarget).hasClass("button-disabled")||C.show_result()}),f.click(function(a){$(a.currentTarget).hasClass("button-disabled")||C.hide_all()}),g.click(function(a){$(a.currentTarget).hasClass("button-disabled")||(b.parent_model.controller.remove_cell(b),$(".tooltip").remove())}),h.click(function(a){l()});var m=$("<div style='position:relative; float: right; z-index:10000'></div>"),n=$("<div style='margin:0.5em;'></div>"),o=$("<div style='margin:0.5em;'></div>");n.append(d),n.append(e),n.append(f),n.append(g),m.append(n),o.append(h),o.hide(),m.append(o),c.append(m);var p=$("<div></div>"),q=$("<div style='clear:both;'></div>"
+);c.append(p),c.append(q);var r=$('<div style="position: relative; width:100%; height:100%"></div>'),s=$('<div style="position: absolute; right:-0.5em; top:-0.5em"></div>'),t=a("icon-plus-sign","insert cell");p.append(s),s.append(t),t.click(function(a){var b=c.index(),d=b;shell.insert_markdown_cell_before(d)});var u=$('<div style="width:100%; height:100%"></div>');p.append(r),r.append(u);var v=ace.edit(u[0]),w=require("mode/rmarkdown").Mode,x=v.getSession(),y=x.doc;v.getSession().setMode(new w(!1,y,x)),v.setTheme("ace/theme/chrome"),v.getSession().setUseWrapMode(!0),v.resize(),v.commands.addCommand({name:"sendToR",bindKey:{win:"Ctrl-Return",mac:"Command-Return",sender:"editor"},exec:function(a,b,c){l()}});var z=$('<div class="r-result-div"><span style="opacity:0.5">Not evaluated</span></div>');p.append(z);var A=$("<span></span>");p.append(A);var B,C={content_updated:function(){v.getSession().setValue(b.content())},self_removed:function(){c.remove()},result_updated:function(a){z.hide(),z.html(a.value[0]),z.slideDown(150);var b=rcloud.wplot_uuid;p.find("pre code").contents().filter(function(){return this.nodeValue.indexOf(b)!==-1}).parent().parent().each(function(){var a=this.childNodes[0].childNodes[0].data.substr(8,73).split("|"),b=this;rcloud.resolve_deferred_result(a[1],function(a){$(b).replaceWith(function(){return shell.handle(a.value[0].value[0],a)})})}),p.find("pre code").each(function(a,b){hljs.highlightBlock(b)}),_.isUndefined(MathJax)||MathJax.Hub.Queue(["Typeset",MathJax.Hub]),this.show_result(),A[0].scrollIntoView()},hide_buttons:function(){m.css("display","none"),s.css("display","none")},show_buttons:function(){m.css("display",null),s.css("display",null)},show_source:function(){c.css({height:"70%"}),k(d),j(e),j(f),j(g),o.show(),r.show(),z.hide(),v.resize(),v.focus(),B="source"},show_result:function(){c.css({height:""}),j(d),k(e),j(f),j(g),o.hide(),r.hide(),z.slideDown(150,function(){A[0].scrollIntoView()}),B="result"},hide_all:function(){c.css({height:""}),j(d),j(e),k(f),j(g),o.hide(),B==="result"?z.slideUp(150):r.slideUp(150)},remove_self:function(){b.parent_model.remove_cell(b),c.remove()},div:function(){return c},update_model:function(){i()},focus:function(){v.focus()}};C.show_result(),C.content_updated();return C}function a(a,b){return $("<span class='fontawesome-button'><i class='"+a+"'></i></span>").tooltip({title:b,delay:{show:250,hide:0}})}var d={markdown:b,interactive:c};Notebook.Cell.create_html_view=function(a){return d[a.type()](a)}}(),Notebook.Cell.create_model=function(a,b){function d(){_.each(c.views,function(a){a.content_updated()})}var c={views:[],type:function(){return b},content:function(b){_.isUndefined(b)||(a=b,d());return a},json:function(){return{content:a,type:b}}};return c},Notebook.Cell.create_controller=function(a){var b={execute:function(){function d(b){_.each(a.views,function(a){a.result_updated(b)})}var b=this,c=a.type();rclient.record_cell_execution(a);if(c==="markdown"){var e=rclient.markdown_wrap_command(a.content());rclient.send_and_callback(e,d,_.identity)}else if(c==="interactive"){var e=rclient.markdown_wrap_command("```{r}\n"+a.content()+"\n```\n");rclient.send_and_callback(e,d,_.identity)}else alert("Can only do markdown or interactive for now!")}};return b},Notebook.create_html_view=function(a,b){var c={model:a,sub_views:[],cell_appended:function(a){var c=Notebook.Cell.create_html_view(a);a.views.push(c),b.append(c.div()),this.sub_views.push(c);return c},cell_inserted:function(a,c){var d=Notebook.Cell.create_html_view(a);a.views.push(d),b.append(d.div()),$(d.div()).insertBefore(b.children()[c]),this.sub_views.splice(c,0,d),d.show_source();return d},cell_removed:function(a,b){_.each(a.views,function(a){a.self_removed()}),this.sub_views.splice(b,1)},update_model:function(){_.each(this.sub_views,function(a){a.update_model()})}};a.views.push(c);return c},Notebook.create_model=function(){return{notebook:[],views:[],clear:function(){while(this.notebook.length)this.remove_cell(this.notebook[this.notebook.length-1])},append_cell:function(a){a.parent_model=this,this.notebook.push(a),_.each(this.views,function(b){b.cell_appended(a)})},insert_cell:function(a,b){a.parent_model=this,this.notebook.splice(b,0,a),_.each(this.views,function(c){c.cell_inserted(a,b)})},json:function(){return _.map(this.notebook,function(a){return a.json()})},remove_cell:function(a){var b=this.notebook.indexOf(a);if(b===-1)throw"cell_model not in notebook model?!";_.each(this.views,function(c){c.cell_removed(a,b)}),this.notebook.splice(b,1)}}},Notebook.create_controller=function(a){var b={append_cell:function(b,c){var d=Notebook.Cell.create_model(b,c),e=Notebook.Cell.create_controller(d);d.controller=e,a.append_cell(d);return e},insert_cell:function(b,c,d){var e=Notebook.Cell.create_model(b,c),f=Notebook.Cell.create_controller(e);e.controller=f,a.insert_cell(e,d);return f},remove_cell:function(b){a.remove_cell(b)},clear:function(){a.clear()},load_from_file:function(a,b,c){var d=this;rcloud.load_user_file(a,b,function(a){var b=JSON.parse(a.value.join("\n"));d.clear(),_.each(b,function(a){var b=d.append_cell(a.content,a.type)}),c()})},save_file:function(b,c,d){var e=this,f=JSON.stringify(a.json());rcloud.load_user_file(b,c,function(a){a=a.value.join("\n"),f!==a?rcloud.save_to_user_file(b,c,f,function(){d&&d()}):d&&d()})},run_all:function(){_.each(a.notebook,function(a){a.controller.execute()})}};a.controller=b;return b}
View
748 htdocs/js/rserve.js
@@ -0,0 +1,748 @@
+/*
+
+ RServe is a low-level communication layer between Javascript and a
+ running RServe process on the other side, via Websockets.
+
+ */
+
+(function() {
+
+function RserveError(message, status_code) {
+ this.name = "RserveError";
+ this.message = message;
+ this.status_code = status_code;
+}
+
+RserveError.prototype = Object.create(Error);
+RserveError.prototype.constructor = RserveError;
+
+var Rsrv = {
+ PAR_TYPE: function(x) { return x & 255; },
+ PAR_LEN: function(x) { return x >> 8; },
+ PAR_LENGTH: function(x) { return x >> 8; },
+ par_parse: function(x) { return [Rsrv.PAR_TYPE(x), Rsrv.PAR_LEN(x)]; },
+ SET_PAR: function(ty, len) { return ((len & 0xffffff) << 8 | (ty & 255)); },
+ CMD_STAT: function(x) { return (x >> 24) & 127; },
+ SET_STAT: function(x, s) { return x | ((s & 127) << 24); },
+
+ CMD_RESP : 0x10000,
+ RESP_OK : 0x10000 | 0x0001,
+ RESP_ERR : 0x10000 | 0x0002,
+ OOB_SEND : 0x30000 | 0x1000,
+ ERR_auth_failed : 0x41,
+ ERR_conn_broken : 0x42,
+ ERR_inv_cmd : 0x43,
+ ERR_inv_par : 0x44,
+ ERR_Rerror : 0x45,
+ ERR_IOerror : 0x46,
+ ERR_notOpen : 0x47,
+ ERR_accessDenied : 0x48,
+ ERR_unsupportedCmd : 0x49,
+ ERR_unknownCmd : 0x4a,
+ ERR_data_overflow : 0x4b,
+ ERR_object_too_big : 0x4c,
+ ERR_out_of_mem : 0x4d,
+ ERR_ctrl_closed : 0x4e,
+ ERR_session_busy : 0x50,
+ ERR_detach_failed : 0x51,
+
+ CMD_long : 0x001,
+ CMD_voidEval : 0x002,
+ CMD_eval : 0x003,
+ CMD_shutdown : 0x004,
+ CMD_openFile : 0x010,
+ CMD_createFile : 0x011,
+ CMD_closeFile : 0x012,
+ CMD_readFile : 0x013,
+ CMD_writeFile : 0x014,
+ CMD_removeFile : 0x015,
+ CMD_setSEXP : 0x020,
+ CMD_assignSEXP : 0201,
+ CMD_detachSession : 0x030,
+ CMD_detachedVoidEval : 0x031,
+ CMD_attachSession : 0x032,
+ CMD_ctrl : 0x40,
+ CMD_ctrlEval : 0x42,
+ CMD_ctrlSource : 0x45,
+ CMD_ctrlShutdown : 0x44,
+ CMD_setBufferSize : 0x081,
+ CMD_setEncoding : 0x082,
+ CMD_SPECIAL_MASK : 0xf0,
+ CMD_serEval : 0xf5,
+ CMD_serAssign : 0xf6,
+ CMD_serEEval : 0xf7,
+
+
+ DT_INT : 1,
+ DT_CHAR : 2,
+ DT_DOUBLE : 3,
+ DT_STRING : 4,
+ DT_BYTESTREAM : 5,
+ DT_SEXP : 10,
+ DT_ARRAY : 11,
+ DT_LARGE : 64,
+
+ XT_NULL : 0,
+ XT_INT : 1,
+ XT_DOUBLE : 2,
+ XT_STR : 3,
+ XT_LANG : 4,
+ XT_SYM : 5,
+ XT_BOOL : 6,
+ XT_S4 : 7,
+ XT_VECTOR : 16,
+ XT_LIST : 17,
+ XT_CLOS : 18,
+ XT_SYMNAME : 19,
+ XT_LIST_NOTAG : 20,
+ XT_LIST_TAG : 21,
+ XT_LANG_NOTAG : 22,
+ XT_LANG_TAG : 23,
+ XT_VECTOR_EXP : 26,
+ XT_VECTOR_STR : 27,
+ XT_ARRAY_INT : 32,
+ XT_ARRAY_DOUBLE : 33,
+ XT_ARRAY_STR : 34,
+ XT_ARRAY_BOOL_UA : 35,
+ XT_ARRAY_BOOL : 36,
+ XT_RAW : 37,
+ XT_ARRAY_CPLX : 38,
+ XT_UNKNOWN : 48,
+ XT_LARGE : 64,
+ XT_HAS_ATTR : 128,
+
+ BOOL_TRUE : 1,
+ BOOL_FALSE : 0,
+ BOOL_NA : 2,
+
+ GET_XT: function(x) { return x & 63; },
+ GET_DT: function(x) { return x & 63; },
+ HAS_ATTR: function(x) { return (x & Rsrv.XT_HAS_ATTR) > 0; },
+ IS_LARGE: function(x) { return (x & Rsrv.XT_LARGE) > 0; },
+
+ // # FIXME A WHOLE LOT OF MACROS HERE WHICH ARE PROBABLY IMPORTANT
+ // ##############################################################################
+
+ itop: function(x) { return x; },
+ ptoi: function(x) { return x; },
+ dtop: function(x) { return x; },
+ ptod: function(x) { return x; },
+
+ fixdcpy: function() { throw new RserveError("unimplemented", -1); },
+
+ status_codes: {
+ 0x41 : "ERR_auth_failed" ,
+ 0x42 : "ERR_conn_broken" ,
+ 0x43 : "ERR_inv_cmd" ,
+ 0x44 : "ERR_inv_par" ,
+ 0x45 : "ERR_Rerror" ,
+ 0x46 : "ERR_IOerror" ,
+ 0x47 : "ERR_notOpen" ,
+ 0x48 : "ERR_accessDenied" ,
+ 0x49 : "ERR_unsupportedCmd",
+ 0x4a : "ERR_unknownCmd" ,
+ 0x4b : "ERR_data_overflow" ,
+ 0x4c : "ERR_object_too_big",
+ 0x4d : "ERR_out_of_mem" ,
+ 0x4e : "ERR_ctrl_closed" ,
+ 0x50 : "ERR_session_busy" ,
+ 0x51 : "ERR_detach_failed"
+ }
+};
+
+function reader(m)
+{
+ var handlers = {};
+ var _;
+
+ function lift(f, amount) {
+ return function(attributes, length) {
+ return [f.call(that, attributes, length), amount || length];
+ };
+ }
+
+ function bind(m, f) {
+ return function(attributes, length) {
+ var t = m.call(that, attributes, length);
+ var t2 = f(t[0])(attributes, length - t[1]);
+ return [t2[0], t[1] + t2[1]];
+ };
+ }
+
+ function unfold(f) {
+ return function(attributes, length) {
+ var result = [];
+ var old_length = length;
+ while (length > 0) {
+ var t = f.call(that, attributes, length);
+ result.push(t[0]);
+ length -= t[1];
+ }
+ return [result, old_length];
+ };
+ }
+
+ var that = {
+ offset: 0,
+ data_view: m.make(EndianAwareDataView),
+ msg: m,
+
+ //////////////////////////////////////////////////////////////////////
+
+ read_int: function() {
+ var old_offset = this.offset;
+ this.offset += 4;
+ return this.data_view.getInt32(old_offset);
+ },
+ read_string: function(length) {
+ // FIXME SLOW
+ var result = "";
+ while (length--) {
+ var c = this.data_view.getInt8(this.offset++);
+ if (c) result = result + String.fromCharCode(c);
+ }
+ return result;
+ },
+ read_stream: function(length) {
+ var old_offset = this.offset;
+ this.offset += length;
+ return this.msg.view(old_offset, length);
+ },
+ read_int_vector: function(length) {
+ var old_offset = this.offset;
+ this.offset += length;
+ return this.msg.make(Int32Array, old_offset, length);
+ },
+ read_double_vector: function(length) {
+ var old_offset = this.offset;
+ this.offset += length;
+ return this.msg.make(Float64Array, old_offset, length);
+ },
+
+ //////////////////////////////////////////////////////////////////////
+
+ read_null: lift(function(a, l) { return Robj.null(a); }),
+
+ //////////////////////////////////////////////////////////////////////
+ // and these return full R objects as well.
+
+ read_string_array: function(attributes, length) {
+ var a = this.read_stream(length).make(Uint8Array);
+ var result = [];
+ var current_str = "";
+ for (var i=0; i<a.length; ++i)
+ if (a[i] === 0) {
+ result.push(current_str);
+ current_str = "";
+ } else {
+ current_str = current_str + String.fromCharCode(a[i]);
+ }
+ return [Robj.string_array(result, attributes), length];
+ },
+ read_bool_array: function(attributes, length) {
+ var l2 = this.read_int();
+ var s = this.read_stream(length-4);
+ var a = s.make(Uint8Array); // new Uint8Array(s, 0, l2);
+ var result = [];
+ for (var i=0; i<l2; ++i)
+ result[i] = !!a[i];
+ return [Robj.bool_array(result, attributes), length];
+ },
+
+ read_sexp: function() {
+ var d = this.read_int();
+ var _ = Rsrv.par_parse(d);
+ var t = _[0], l = _[1];
+ var total_read = 4;
+ var attributes = undefined;
+ if (t & Rsrv.XT_HAS_ATTR) {
+ t = t & ~Rsrv.XT_HAS_ATTR;
+ var attr_result = this.read_sexp();
+ attributes = attr_result[0];
+ total_read += attr_result[1];
+ l -= attr_result[1];
+ }
+ if (handlers[t] === undefined) {
+ throw new RserveError("Unimplemented " + t, -1);
+ } else {
+ var result = handlers[t].call(this, attributes, l);
+ return [result[0], total_read + result[1]];
+ }
+ }
+ };
+
+ that.read_clos = bind(that.read_sexp, function(formals) {
+ return bind(that.read_sexp, function(body) {
+ return lift(function(a, l) {
+ return Robj.clos(formals, body, a);
+ }, 0);
+ } );
+ });
+
+ that.read_list = unfold(that.read_sexp);
+ that.read_list_tag = bind(that.read_list, function(lst) {
+ return lift(function(attributes, length) {
+ var result = {};
+ for (var i=0; i<lst.length; i+=2) {
+ var value = lst[i], tag = lst[i+1];
+ if (tag.type !== "symbol")
+ throw new RserveError("Unexpected type " + tag.type + " as tag for tagged_list", -1);
+ result[tag.value] = value;
+ }
+ return Robj.tagged_list(result, attributes);
+ }, 0);
+ });
+
+ function xf(f, g) { return bind(f, function(t) {
+ return lift(function(a, l) { return g(t, a); }, 0);
+ }); }
+ that.read_vector = xf(that.read_list, Robj.vector);
+ that.read_list_no_tag = xf(that.read_list, Robj.list);
+ that.read_lang_no_tag = xf(that.read_list, Robj.lang);
+ that.read_vector_exp = xf(that.read_list, Robj.vector_exp);
+
+ function sl(f, g) { return lift(function(a, l) {
+ return g(f.call(that, l), a);
+ }); }
+ that.read_symname = sl(that.read_string, Robj.symbol);
+ that.read_int_array = sl(that.read_int_vector, Robj.int_array);
+ that.read_double_array = sl(that.read_double_vector, Robj.double_array);
+
+ handlers[Rsrv.XT_NULL] = that.read_null;
+ handlers[Rsrv.XT_VECTOR] = that.read_vector;
+ handlers[Rsrv.XT_CLOS] = that.read_clos;
+ handlers[Rsrv.XT_SYMNAME] = that.read_symname;
+ handlers[Rsrv.XT_LIST_NOTAG] = that.read_list_no_tag;
+ handlers[Rsrv.XT_LIST_TAG] = that.read_list_tag;
+ handlers[Rsrv.XT_LANG_NOTAG] = that.read_lang_no_tag;
+ handlers[Rsrv.XT_VECTOR_EXP] = that.read_vector_exp;
+ handlers[Rsrv.XT_ARRAY_INT] = that.read_int_array;
+ handlers[Rsrv.XT_ARRAY_DOUBLE] = that.read_double_array;
+ handlers[Rsrv.XT_ARRAY_STR] = that.read_string_array;
+ handlers[Rsrv.XT_ARRAY_BOOL] = that.read_bool_array;
+
+ return that;
+}
+
+function parse(msg)
+{
+ var header = new Int32Array(msg, 0, 4);
+ if (header[0] !== Rsrv.RESP_OK && header[0] !== Rsrv.OOB_SEND) {
+ var status_code = header[0] >> 24;
+ throw new RserveError("ERROR FROM R SERVER: " + (Rsrv.status_codes[status_code] ||
+ status_code)
+ + " " + header[0] + " " + header[1] + " " + header[2] + " " + header[3]
+ + " " + msg.byteLength
+ + " " + msg, status_code);
+ }
+
+ var payload = my_ArrayBufferView(msg, 16, msg.byteLength - 16);
+ if (payload.length === 0)
+ return null;
+ var result = parse_payload(reader(payload));
+ return [result, header[0]];
+}
+
+function parse_payload(reader)
+{
+ var d = reader.read_int();
+ var _ = Rsrv.par_parse(d);
+ var t = _[0], l = _[1];
+ if (t === Rsrv.DT_INT) {
+ return { type: "int", value: reader.read_int() };
+ } else if (t === Rsrv.DT_STRING) {
+ return { type: "string", value: reader.read_string(l) };
+ } else if (t === Rsrv.DT_BYTESTREAM) { // NB this returns a my_ArrayBufferView()
+ return { type: "stream", value: reader.read_stream(l) };
+ } else if (t === Rsrv.DT_SEXP) {
+ _ = reader.read_sexp();
+ var sexp = _[0], l2 = _[1];
+ return { type: "sexp", value: sexp };
+ } else
+ throw new RserveError("Bad type for parse? " + t + " " + l, -1);
+}
+
+function make_basic(type, proto) {
+ return function(v, attrs) {
+ function r_object() {
+ this.type = type;
+ this.value = v;
+ this.attributes = attrs;
+ }
+ r_object.prototype = proto || {
+ html_element: function() {
+ return $("<div class='obj'></div>").append($("<div class='key'></div>").html(type));
+ }
+ };
+ return new r_object();
+ };
+}
+
+function pprint_array_as_div(formatter) {
+ function plain_array() {
+ var result = $("<div class='obj'></div>");
+ var div = $("<div class='string-value'></div>");
+ var v = this.value;
+ var s;
+ var that = this;
+ formatter = formatter || function(v) { return v; };
+ var element;
+ if (this.attributes && this.attributes.value.names) {
+ element = function(i) {
+ return that.attributes.value.names.value[i] + ": " + formatter(String(v[i]));
+ };
+ } else if (this.attributes && this.attributes.value.levels) {
+ element = function(i) {
+ return that.attributes.value.levels.value[v[i]-1];
+ };
+ } else {
+ element = function(i) {
+ return formatter(String(v[i]));
+ };
+ }
+
+ if (v.length === 0) {
+ s = "[]";
+ } else if (v.length === 1) {
+ s = element(0);
+ } else if (v.length <= 10) {
+ s = "[" + element(0);
+ for (var i=1; i<v.length; ++i) {
+ s = s + ", " + element(i);
+ }
+ s = s + "]";
+ } else {
+ s = "[" + element(0);
+ for (var i=1; i<5; ++i) {
+ s = s + ", " + element(i);
+ }
+ s = s + ", ... ";
+ for (i=v.length-5; i<v.length; ++i)
+ s = s + ", " + element(i);
+ s = s + "]";
+ }
+ div.html(s);
+ result.append(div);
+ return result;
+ }
+ function matrix() {
+ var result = document.createElement("table");
+ var header = document.createElement("tr");
+ result.appendChild(header);
+ var dims = this.attributes.value.dim.value;
+ var values = this.value;
+ var that = this;
+ d3.select(header)
+ .selectAll("td")
+ .data(_.range(dims[1]+1))
+ .enter().append("td").text(function(i) {
+ if (i === 0) return "";
+ return "[," + i + "]";
+ });
+ d3.select(result)
+ .selectAll("tr-data")
+ .data(_.range(dims[0]))
+ .enter().append("tr")
+ .selectAll("td")
+ .data(function(i) { return _.map(_.range(dims[1]+1),
+ function(j) {
+ return [i,j];
+ });
+ })
+ .enter()
+ .append("td")
+ .text(function(d) {
+ var row = d[0], col = d[1];
+ if (col === 0) {
+ return "[" + (row+1) + ",]";
+ };
+ var v = values[(col-1) * dims[0] + row];
+ if (that.attributes &&
+ that.attributes.value.levels) {
+ return that.attributes.value.levels.value[v-1];
+ } else {
+ return v;
+ }
+ });
+ return result;
+ }
+
+ return function() {
+ if (this.attributes &&
+ this.attributes.value.dim) {
+ return matrix.call(this);
+ } else
+ return plain_array.call(this);
+
+ };
+}
+
+Robj = {
+ "null": function(attributes) {
+ return {
+ type: "null",
+ value: null,
+ attributes: attributes,
+ html_element: function() {
+ return $("<div class='obj'><div class='key'>null</div></div>");
+ }
+ };
+ },
+
+ clos: function(formals, body, attributes) {
+ return {
+ type: "clos",
+ value: { formals: formals,
+ body: body },
+ attributes: attributes,
+ html_element: function() {
+ var div = $("<div class='obj'></div>");
+ var pair = $("<div></div>");
+ pair.append($("<div class='key'>formals:</div>"));
+ pair.append(this.value.formals.html_element());
+ div.append(pair);
+ pair = $("<div></div>");
+ pair.append($("<div class='key'>body:</div>"));
+ pair.append(this.value.body.html_element());
+ div.append(pair);
+ return div;
+ }
+ };
+ },
+
+ vector: make_basic("vector", {
+ html_element: function () {
+ var div = $("<div class='obj'></div>");
+ if (!this.attributes) {
+ for (var i=0; i<this.value.length; ++i) {
+ div.append(this.value[i].html_element());
+ }
+ } else {
+ var lengths = _.map(this.value, function(v) { return v.value.length; });
+ var names = this.attributes.value.names.value;
+ if (_.all(lengths, function(i) { return i === lengths[0]; })) {
+ // it's a dataframe
+ var result = document.createElement("table");
+ var th = document.createElement("tr");
+ var values = this.value;
+ result.appendChild(th);
+ d3.select(th)
+ .selectAll("th")
+ .data(_.range(lengths.length))
+ .enter().append("th").text(function(i) {
+ return names[i];
+ });
+ var rows;
+ // rows = _.range(lengths[0]);
+ if (lengths[0] < 11) {
+ rows = _.range(lengths[0]);
+ } else {
+ rows = [0,1,2,3,4,5];
+ rows.push.apply(rows, _.range(lengths[0] - 5, lengths[0]));
+ }
+ d3.select(result)
+ .selectAll("tr-data")
+ .data(rows)
+ .enter().append("tr")
+ .selectAll("td")
+ .data(function(i) { return _.map(_.range(lengths.length),
+ function(j) {
+ return [i,j];
+ });
+ })
+ .enter()
+ .append("td")
+ .text(function(d, i) {
+ var row = d[0], col = d[1];
+ if (lengths[0] >= 11 && row === 5)
+ return "...";
+ var v = values[col].value[row];
+ if (values[col].attributes) {
+ return values[col].attributes.value.levels.value[v-1];
+ } else {
+ return v;
+ }
+ });
+ div.append(result);
+ } else {
+ var pair = $("<div></div>");
+ for (var i=0; i<this.value.length; ++i) {
+ pair.append($("<span class='key'></span>").append(names[i] + ": "));
+ pair.append(this.value[i].html_element());
+ }
+ div.append(pair);
+ }
+ }
+ return div;
+ }
+ }),
+ symbol: make_basic("symbol"),
+ list: make_basic("list"),
+ lang: make_basic("lang"),
+ tagged_list: make_basic("tagged_list"),
+ tagged_lang: make_basic("tagged_lang"),
+ vector_exp: make_basic("vector_exp"),
+ int_array: make_basic("int_array", {
+ html_element: pprint_array_as_div()
+ }),
+ double_array: make_basic("double_array", {
+ html_element: pprint_array_as_div()
+ }),
+ string_array: make_basic("string_array", {
+ // from http://javascript.crockford.com/remedial.html
+ html_element: pprint_array_as_div(function (s) {
+ var c, i, l = s.length, o = '"';
+ for (i = 0; i < l; i += 1) {
+ c = s.charAt(i);
+ if (c >= ' ') {
+ if (c === '\\' || c === '"') {
+ o += '\\';
+ }
+ o += c;
+ } else {
+ switch (c) {
+ case '\b':
+ o += '\\b';
+ break;
+ case '\f':
+ o += '\\f';
+ break;
+ case '\n':
+ o += '\\n';
+ break;
+ case '\r':
+ o += '\\r';
+ break;
+ case '\t':
+ o += '\\t';
+ break;
+ default:
+ c = c.charCodeAt();
+ o += '\\u00' + Math.floor(c / 16).toString(16) +
+ (c % 16).toString(16);
+ }
+ }
+ }
+ return o + '"';
+ })
+ }),
+ bool_array: make_basic("bool_array", {
+ html_element: pprint_array_as_div()
+ })
+};
+
+Rserve = {
+ create: function(opts) {
+ var host = opts.host;
+ var onconnect = opts.on_connect;
+ var socket = new WebSocket(host);
+ var handle_error = opts.on_error || function(error) { throw new RserveError(error, -1); };
+ socket.binaryType = 'arraybuffer';
+
+ var received_handshake = false;
+ var value_callbacks = [];
+
+ var result;
+ var command_counter = 0;
+
+ function hand_shake(msg)
+ {
+ msg = msg.data;
+ if (msg.substr(0,4) !== 'Rsrv') {
+ handle_error("server is not an RServe instance", -1);
+ } else if (msg.substr(4, 4) !== '0103') {
+ handle_error("sorry, rserve only speaks the 0103 version of the R server protocol", -1);
+ } else if (msg.substr(8, 4) !== 'QAP1') {
+ handle_error("sorry, rserve only speaks QAP1", -1);
+ } else {
+ received_handshake = true;
+ if (opts.login)
+ result.login(opts.login);
+ result.running = true;
+ onconnect && onconnect.call(result);
+ }
+ }
+
+ socket.onclose = function(msg) {
+ result.running = false;
+ opts.on_close && opts.on_close(msg);
+ };
+
+ socket.onmessage = function(msg) {
+ if (!received_handshake) {
+ hand_shake(msg);
+ return;
+ }
+ if (typeof msg.data === 'string')
+ opts.on_raw_string && opts.on_raw_string(msg.data);
+ else {
+ var v;
+ try {
+ v = parse(msg.data);
+ } catch (e) {
+ handle_error(e.message, e.status_code);
+ return;
+ }
+
+ if (v === null) {
+ // there's no data, but there's no error either: ignore the message
+ return;
+ }
+ var type = v[1];
+ v = v[0];
+ switch (type) {
+ case Rsrv.RESP_OK:
+ var value_callback = value_callbacks.shift();
+ value_callback(v);
+ break;
+ case Rsrv.OOB_SEND:
+ opts.on_data && opts.on_data(v);
+ break;
+ default:
+ throw new RserveError("Internal Error, parse returned unexpected type " + type, -1);
+ }
+ }
+ };
+
+ result = {
+ close: function() {
+ socket.close();
+ },
+
+ login: function(auth_string) {
+ var command = auth_string;
+ var buffer = new ArrayBuffer(command.length + 21);
+ var view = new EndianAwareDataView(buffer);
+ view.setInt32(0, 1);
+ view.setInt32(4, 5 + command.length);
+ view.setInt32(8, 0);
+ view.setInt32(12, 0);
+ view.setInt32(16, 4 + ((1 + command.length) << 8));
+ for (var i=0; i<command.length; ++i) {
+ view.setUint8(20 + i, command.charCodeAt(i));
+ }
+ view.setUint8(buffer.byteLength - 1, 0);
+ socket.send(buffer);
+ },
+ eval: function(command, k) {
+ k = k || function() {};
+ value_callbacks.push(k);
+ var buffer = new ArrayBuffer(command.length + 21);
+ var view = new EndianAwareDataView(buffer);
+ view.setInt32(0, 3);
+ view.setInt32(4, 5 + command.length);
+ view.setInt32(8, 0);
+ view.setInt32(12, 0);
+ view.setInt32(16, 4 + ((1 + command.length) << 8));
+ for (var i=0; i<command.length; ++i) {
+ view.setUint8(20 + i, command.charCodeAt(i));
+ }
+ view.setUint8(buffer.byteLength - 1, 0);
+ socket.send(buffer);
+ }
+ };
+ return result;
+ }
+};
+
+})();
View
75 htdocs/main.js
@@ -35,49 +35,50 @@ function main_init() {
rclient = RClient.create({
host: "ws://"+location.hostname+":8081/",
on_connect: function() {
- $("#new-md-cell-button").click(function() {
- shell.terminal.disable();
- shell.new_markdown_cell("", "markdown");
- var vs = shell.notebook.view.sub_views;
- vs[vs.length-1].show_source();
- });
- $("#share-notebook").click(function() {
- shell.serialize_state(function() {
- window.location="share.html?user=" + shell.user + "&filename=" + shell.filename;
+ $("#new-md-cell-button").click(function() {
+ shell.terminal.disable();
+ shell.new_markdown_cell("", "markdown");
+ var vs = shell.notebook.view.sub_views;
+ vs[vs.length-1].show_source();
});
- });
- $("#rcloud-logout").click(function() {
- $.cookies.set('user', null);
- $.cookies.set('sessid', null);
- window.location.href = '/login.html';
- });
- $(".collapse").collapse();
- $("#input-text-search").click(function() {
- shell.terminal.disable();
- });
- rcloud.init_client_side_data();
- var that = this;
- var shell_objtypes = ["scatterplot", "iframe", "facet_osm_plot", "facet_tour_plot"];
- for (var i=0; i<shell_objtypes.length; ++i) {
- (function(objtype) {
- that.register_handler(objtype, function(data) {
- var div = shell.handle(objtype, data);
- shell.post_div(div);
- // shell.handle(objtype, data);
+ $("#share-notebook").click(function() {
+ shell.serialize_state(function() {
+ window.location="share.html?user=" + shell.user + "&filename=" + shell.filename;
});
- })(shell_objtypes[i]);
- }
+ });
+ $("#rcloud-logout").click(function() {
+ $.cookies.set('user', null);
+ $.cookies.set('sessid', null);
+ window.location.href = '/login.html';
+ });
+ $(".collapse").collapse();
+ $("#input-text-search").click(function() {
+ shell.terminal.disable();
+ });
+ rcloud.init_client_side_data();
+ var that = this;
+ var shell_objtypes = ["scatterplot", "iframe", "facet_osm_plot", "facet_tour_plot"];
+ for (var i=0; i<shell_objtypes.length; ++i) {
+ (function(objtype) {
+ that.register_handler(objtype, function(data) {
+ var div = shell.handle(objtype, data);
+ shell.post_div(div);
+ // shell.handle(objtype, data);
+ });
+ })(shell_objtypes[i]);
+ }
- editor.init();
+ editor.init();
- if (location.search.length > 0) {
- function getURLParameter(name) {
- return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
+ if (location.search.length > 0) {
+ function getURLParameter(name) {
+ return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
+ }
+ editor.load_file(getURLParameter("user"), getURLParameter("filename"));
+ $("#tabs").tabs("select", "#tabs-2");
}
- editor.load_file(getURLParameter("user"), getURLParameter("filename"));
- $("#tabs").tabs("select", "#tabs-2");
}
- }});
+ });
}
window.onload = main_init;
View
3  todo.org
@@ -8,6 +8,5 @@
** saved cells could contain an image of the output! (if we save the HTML content before sending, we can display it on search results...)
*** But what about wplot, wgeoplot, etc?
* BUGS
-** Create directory when new user logs in
** wplot negative signs are broken
-
+** Check state sent to github and back during authentication
Please sign in to comment.
Something went wrong with that request. Please try again.