<commit_before>eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 m(c,b){4 a=3;a.1a=c;a.Q=c.1Q();a.1f=u J(c);q.p.G.W(a.1f,\'16\',9(){a.2m=3.1H();a.1D(c,b)})}m.l.1D=9(d,b){4 f=3;b=b||{};f.14=m.1t;4 h=d.13;4 i=1;t(4 c 2H h){n(1l d.13.1g(c)===\'2u\'&&1l d.13.1g(c).1j===\'1J\'){4 g=d.13.1g(c).1j;n(g>i){i=g}}}f.H=b.1j||19;f.1C=b.2a;f.v=b.1B||C;4 e;n(1l b.1x===\'1J\'){e=b.1x}15{e=m.1v}f.1u=u q.p.F(-e,e);f.1s=u q.p.F(e,-e);f.27=e;f.L={};f.T={};f.T[f.H]={};f.K={};f.K[f.H]=0;q.p.G.W(d,\'20\',9(){f.12()});q.p.G.W(d,\'1Y\',9(){f.12()});q.p.G.W(d,\'1W\',9(){f.12()});f.I=9(a){a.1n(2F);f.X--};f.O=9(a){n(f.v){a.1n(f.1a);f.X++}};f.1m();f.X=0;f.r=f.1h();q.p.G.1i(f,\'2s\')};m.1t=2q;m.1v=2o;m.1O=2l;m.l.1m=9(){4 a=m.1O;t(4 b=0;b<=3.H;++b){3.T[b]={};3.K[b]=0;3.L[b]=s.2i(a/3.14);a<<=1}};m.l.2g=9(){3.N(3.r,3.I);3.1m()};m.l.w=9(a,c,b){4 d=3.1f.1E(a,c);4 e=u q.p.2c(s.1R((d.x+b.29)/3.14),s.1R((d.y+b.28)/3.14));o e};m.l.1e=9(i,d,j){4 f=3;4 e=i.V();i.1A=d;n(3.1C){q.p.G.W(i,\'1z\',9(a,b,c){f.1y(a,b,c)})}4 h=3.w(e,j,u q.p.F(0,0,0,0));t(4 g=j;g>=d;g--){4 k=3.1d(h.x,h.y,g);k.1w(i);h.x=h.x>>1;h.y=h.y>>1}};m.l.P=9(d){4 b=3.r.A<=d.y&&d.y<=3.r.D;4 e=3.r.B;4 c=e<=d.x&&d.x<=3.r.E;n(!c&&e<0){4 a=3.L[3.r.z];c=e+a<=d.x&&d.x<=a-1}o b&&c};m.l.1y=9(f,b,g){4 c=3.H;4 a=U;4 d=3.w(b,c,u q.p.F(0,0,0,0));4 e=3.w(g,c,u q.p.F(0,0,0,0));1r(c>=0&&(d.x!==e.x||d.y!==e.y)){4 h=3.Y(d.x,d.y,c);n(h){n(3.1c(h,f)){3.1d(e.x,e.y,c).1w(f)}}n(c===3.Q){n(3.P(d)){n(!3.P(e)){3.I(f);a=C}}15{n(3.P(e)){3.O(f);a=C}}}d.x=d.x>>1;d.y=d.y>>1;e.x=e.x>>1;e.y=e.y>>1;--c}n(a){3.M()}};m.l.26=9(d){4 b=3.H;4 a=U;4 e=d.V();4 c=3.w(e,b,u q.p.F(0,0,0,0));1r(b>=0){4 f=3.Y(c.x,c.y,b);n(f){3.1c(f,d)}n(b===3.Q){n(3.P(c)){3.I(d);a=C}}c.x=c.x>>1;c.y=c.y>>1;--b}n(a){3.M()}3.K[d.1A]--};m.l.25=9(b,a,c){4 d=3.1b(c);t(4 i=b.Z-1;i>=0;i--){3.1e(b[i],a,d)}3.K[a]+=b.Z};m.l.1b=9(a){o a||3.H};m.l.24=9(a){4 b=0;t(4 z=0;z<=a;z++){b+=3.K[z]}o b};m.l.23=9(c,e,d){4 b=u q.p.22(c,e);4 f=3.w(b,d,u q.p.F(0,0,0,0));4 g=u q.p.21({1Z:b});4 a=3.Y(f.x,f.y,d);n(a!==1p){t(4 i=0;i<a.Z;i++){n(c===a[i].V().1o()&&e===a[i].V().10()){g=a[i]}}}o g};m.l.1X=9(d,a,b){4 e=3.1b(b);3.1e(d,a,e);4 c=3.w(d.V(),3.Q,u q.p.F(0,0,0,0));n(3.P(c)&&a<=3.r.z&&3.r.z<=e){3.O(d);3.M()}3.K[a]++};9 11(a){3.B=s.R(a[0].x,a[1].x);3.E=s.S(a[0].x,a[1].x);3.A=s.R(a[0].y,a[1].y);3.D=s.S(a[0].y,a[1].y)}11.l.1q=9(a){n(3.E===a.E&&3.D===a.D&&3.B===a.B&&3.A===a.A){o C}15{o U}};11.l.1V=9(a){4 b=3;o(b.B<=a.x&&b.E>=a.x&&b.A<=a.y&&b.D>=a.y)};m.l.1d=9(x,y,z){4 b=3.T[z];n(x<0){x+=3.L[z]}4 c=b[x];n(!c){c=b[x]=[];o(c[y]=[])}4 a=c[y];n(!a){o(c[y]=[])}o a};m.l.Y=9(x,y,z){4 a=3.T[z];n(x<0){x+=3.L[z]}4 b=a[x];o b?b[y]:1p};m.l.1U=9(j,b,c,e){b=s.R(b,3.H);4 i=j.2G();4 f=j.2E();4 d=3.w(i,b,c);4 g=3.w(f,b,e);4 a=3.L[b];n(f.10()<i.10()||g.x<d.x){d.x-=a}n(g.x-d.x+1>=a){d.x=0;g.x=a-1}4 h=u 11([d,g]);h.z=b;o h};m.l.1h=9(){o 3.1U(3.1a.2D(),3.Q,3.1u,3.1s)};m.l.12=9(){3.1T(3,3.1S,0)};m.l.1T=9(b,a,c){o 2C.2B(9(){a.2A(b)},c)};m.l.2z=9(){o 3.v?C:U};m.l.2y=9(){o!3.v};m.l.1B=9(){3.v=C;3.18()};m.l.2x=9(){3.v=U;3.18()};m.l.2w=9(){3.v=!3.v;3.18()};m.l.18=9(){n(3.X>0){3.N(3.r,3.I)}n(3.v){3.N(3.r,3.O)}3.M()};m.l.1S=9(){3.Q=3.1a.1Q();4 a=3.1h();n(a.1q(3.r)&&a.z===3.r.z){o}n(a.z!==3.r.z){3.N(3.r,3.I);n(3.v){3.N(a,3.O)}}15{3.1k(3.r,a,3.1P);n(3.v){3.1k(a,3.r,3.1M)}}3.r=a;3.M()};m.l.M=9(){q.p.G.1i(3,\'1z\',3.r,3.X)};m.l.N=9(b,a){t(4 x=b.B;x<=b.E;x++){t(4 y=b.A;y<=b.D;y++){3.17(x,y,b.z,a)}}};m.l.17=9(x,y,z,a){4 b=3.Y(x,y,z);n(b){t(4 i=b.Z-1;i>=0;i--){a(b[i])}}};m.l.1P=9(x,y,z){3.17(x,y,z,3.I)};m.l.1M=9(x,y,z){3.17(x,y,z,3.O)};m.l.1k=9(c,d,a){4 b=3;b.1I(c,d,9(x,y){a.2p(b,[x,y,c.z])})};m.l.1I=9(j,k,b){4 f=j.B;4 a=j.A;4 d=j.E;4 h=j.D;4 g=k.B;4 c=k.A;4 e=k.E;4 i=k.D;4 x,y;t(x=f;x<=d;x++){t(y=a;y<=h&&y<c;y++){b(x,y)}t(y=s.S(i+1,a);y<=h;y++){b(x,y)}}t(y=s.S(a,c);y<=s.R(h,i);y++){t(x=s.R(d+1,g)-1;x>=f;x--){b(x,y)}t(x=s.S(f,e+1);x<=d;x++){b(x,y)}}};m.l.1c=9(a,c,b){4 d=0;t(4 i=0;i<a.Z;++i){n(a[i]===c||(b&&a[i]===c)){a.2n(i--,1);d++}}o d};9 J(b){3.1n(b);4 d=8;4 c=1<<d;4 a=7;3.1K=b;3.2k=-1;3.2r=3.2j=3.2t=3.2h=-1}J.l=u q.p.2v();J.l.1N=9(a){o(1+a/1L)};J.l.1G=9(b){4 a=s.2f(b*s.1F/1L);o(1-0.5/s.1F*s.2e((1+a)/(1-a)))};J.l.1E=9(a,d){4 c=3.1K;4 b=3.1H().2d(a);4 e={x:~~(0.5+3.1N(a.10())*(2<<(d+6))),y:~~(0.5+3.1G(a.1o())*(2<<(d+6)))};o e};J.l.2b=9(){n(!3.16){3.16=C;q.p.G.1i(3,\'16\')}};',62,168,'|||this|var|||||function||||||||||||prototype|MarkerManager|if|return|maps|google|shownBounds_|Math|for|new|show_|getTilePoint_||||minY|minX|true|maxY|maxX|Size|event|maxZoom_|removeOverlay_|ProjectionHelperOverlay|numMarkers_|gridWidth_|notifyListeners_|processAll_|addOverlay_|isGridPointVisible_|mapZoom_|min|max|grid_|false|getPosition|addListener|shownMarkers_|getGridCellNoCreate_|length|lng|GridBounds|onMapMoveEnd_|mapTypes|tileSize_|else|ready|processCellMarkers_|refresh||map_|getOptMaxZoom_|removeFromArray_|getGridCellCreate_|addMarkerBatch_|projectionHelper_|get|getMapGridBounds_|trigger|maxZoom|rectangleDiff_|typeof|resetManager_|setMap|lat|undefined|equals|while|nePadding_|DEFAULT_TILE_SIZE_|swPadding_|DEFAULT_BORDER_PADDING_|push|borderPadding|onMarkerMoved_|changed|MarkerManager_minZoom|show|trackMarkers_|initialize|LatLngToPixel|PI|LatToY_|getProjection|rectangleDiffCoords_|number|_map|180|addCellMarkers_|LngToX_|MERCATOR_ZOOM_LEVEL_ZERO_RANGE|removeCellMarkers_|getZoom|floor|updateMarkers_|objectSetTimeout_|getGridBounds_|containsPoint|zoom_changed|addMarker|idle|position|dragend|Marker|LatLng|getMarker|getMarkerCount|addMarkers|removeMarker|borderPadding_|height|width|trackMarkers|draw|Point|fromLatLngToDivPixel|log|sin|clearMarkers|_Y1|ceil|_Y0|_zoom|256|projection_|splice|100|apply|1024|_X0|loaded|_X1|object|OverlayView|toggle|hide|isHidden|visible|call|setTimeout|window|getBounds|getNorthEast|null|getSouthWest|in'.split('|'),0,{}))<commit_msg>Update packed version of markermanager<commit_after>eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 m(c,b){4 a=3;a.18=c;a.Q=c.1F();a.1e=u K(c);q.p.H.X(a.1e,\'16\',9(){a.2m=3.1E();a.1B(c,b)})}m.l.1B=9(d,b){4 f=3;b=b||{};f.13=m.1r;4 h=d.1o;4 i=1;t(4 c 2H h){n(h.2A(c)&&h.1N(c).1i===\'1H\'){4 g=d.1o.1N(c).1i;n(g>i){i=g}}}f.F=b.1i||19;f.1O=b.2b;f.v=b.1A||B;4 e;n(27 b.1v===\'1H\'){e=b.1v}14{e=m.1t}f.1s=u q.p.C(-e,e);f.1q=u q.p.C(e,-e);f.26=e;f.L={};f.T={};f.T[f.F]={};f.J={};f.J[f.F]=0;q.p.H.X(d,\'1Z\',9(){f.12()});q.p.H.X(d,\'1X\',9(){f.12()});q.p.H.X(d,\'1V\',9(){f.12()});f.I=9(a){a.1k(2F);f.W--};f.P=9(a){n(f.v){a.1k(f.18);f.W++}};f.1f();f.W=0;f.r=f.1j();q.p.H.1g(f,\'2s\')};m.1r=2q;m.1t=2o;m.1G=2l;m.l.1f=9(){4 a=m.1G;t(4 b=0;b<=3.F;++b){3.T[b]={};3.J[b]=0;3.L[b]=s.2i(a/3.13);a<<=1}};m.l.2g=9(){3.O(3.r,3.I);3.1f()};m.l.w=9(a,c,b){4 d=3.1e.1C(a,c);4 e=u q.p.2c(s.1Q((d.x+b.29)/3.13),s.1Q((d.y+b.28)/3.13));o e};m.l.1d=9(i,d,j){4 f=3;4 e=i.V();i.1y=d;n(3.1O){q.p.H.X(i,\'1x\',9(a,b,c){f.1w(a,b,c)})}4 h=3.w(e,j,u q.p.C(0,0,0,0));t(4 g=j;g>=d;g--){4 k=3.1c(h.x,h.y,g);k.1u(i);h.x=h.x>>1;h.y=h.y>>1}};m.l.N=9(d){4 b=3.r.E<=d.y&&d.y<=3.r.D;4 e=3.r.A;4 c=e<=d.x&&d.x<=3.r.G;n(!c&&e<0){4 a=3.L[3.r.z];c=e+a<=d.x&&d.x<=a-1}o b&&c};m.l.1w=9(f,b,g){4 c=3.F;4 a=U;4 d=3.w(b,c,u q.p.C(0,0,0,0));4 e=3.w(g,c,u q.p.C(0,0,0,0));1p(c>=0&&(d.x!==e.x||d.y!==e.y)){4 h=3.Y(d.x,d.y,c);n(h){n(3.1b(h,f)){3.1c(e.x,e.y,c).1u(f)}}n(c===3.Q){n(3.N(d)){n(!3.N(e)){3.I(f);a=B}}14{n(3.N(e)){3.P(f);a=B}}}d.x=d.x>>1;d.y=d.y>>1;e.x=e.x>>1;e.y=e.y>>1;--c}n(a){3.M()}};m.l.25=9(d){4 b=3.F;4 a=U;4 e=d.V();4 c=3.w(e,b,u q.p.C(0,0,0,0));1p(b>=0){4 f=3.Y(c.x,c.y,b);n(f){3.1b(f,d)}n(b===3.Q){n(3.N(c)){3.I(d);a=B}}c.x=c.x>>1;c.y=c.y>>1;--b}n(a){3.M()}3.J[d.1y]--};m.l.24=9(b,a,c){4 d=3.1a(c);t(4 i=b.Z-1;i>=0;i--){3.1d(b[i],a,d)}3.J[a]+=b.Z};m.l.1a=9(a){o a||3.F};m.l.23=9(a){4 b=0;t(4 z=0;z<=a;z++){b+=3.J[z]}o b};m.l.22=9(c,e,d){4 b=u q.p.21(c,e);4 f=3.w(b,d,u q.p.C(0,0,0,0));4 g=u q.p.20({1Y:b});4 a=3.Y(f.x,f.y,d);n(a!==1m){t(4 i=0;i<a.Z;i++){n(c===a[i].V().1l()&&e===a[i].V().10()){g=a[i]}}}o g};m.l.1W=9(d,a,b){4 e=3.1a(b);3.1d(d,a,e);4 c=3.w(d.V(),3.Q,u q.p.C(0,0,0,0));n(3.N(c)&&a<=3.r.z&&3.r.z<=e){3.P(d);3.M()}3.J[a]++};9 11(a){3.A=s.R(a[0].x,a[1].x);3.G=s.S(a[0].x,a[1].x);3.E=s.R(a[0].y,a[1].y);3.D=s.S(a[0].y,a[1].y)}11.l.1n=9(a){n(3.G===a.G&&3.D===a.D&&3.A===a.A&&3.E===a.E){o B}14{o U}};11.l.1U=9(a){4 b=3;o(b.A<=a.x&&b.G>=a.x&&b.E<=a.y&&b.D>=a.y)};m.l.1c=9(x,y,z){4 b=3.T[z];n(x<0){x+=3.L[z]}4 c=b[x];n(!c){c=b[x]=[];o(c[y]=[])}4 a=c[y];n(!a){o(c[y]=[])}o a};m.l.Y=9(x,y,z){4 a=3.T[z];n(x<0){x+=3.L[z]}4 b=a[x];o b?b[y]:1m};m.l.1S=9(j,b,c,e){b=s.R(b,3.F);4 i=j.2G();4 f=j.2E();4 d=3.w(i,b,c);4 g=3.w(f,b,e);4 a=3.L[b];n(f.10()<i.10()||g.x<d.x){d.x-=a}n(g.x-d.x+1>=a){d.x=0;g.x=a-1}4 h=u 11([d,g]);h.z=b;o h};m.l.1j=9(){o 3.1S(3.18.2D(),3.Q,3.1s,3.1q)};m.l.12=9(){3.1R(3,3.1z,0)};m.l.1R=9(b,a,c){o 2C.2B(9(){a.2z(b)},c)};m.l.2y=9(){o 3.v?B:U};m.l.2x=9(){o!3.v};m.l.1A=9(){3.v=B;3.17()};m.l.2w=9(){3.v=U;3.17()};m.l.2u=9(){3.v=!3.v;3.17()};m.l.17=9(){n(3.W>0){3.O(3.r,3.I)}n(3.v){3.O(3.r,3.P)}3.M()};m.l.1z=9(){3.Q=3.18.1F();4 a=3.1j();n(a.1n(3.r)&&a.z===3.r.z){o}n(a.z!==3.r.z){3.O(3.r,3.I);n(3.v){3.O(a,3.P)}}14{3.1h(3.r,a,3.1M);n(3.v){3.1h(a,3.r,3.1K)}}3.r=a;3.M()};m.l.M=9(){q.p.H.1g(3,\'1x\',3.r,3.W)};m.l.O=9(b,a){t(4 x=b.A;x<=b.G;x++){t(4 y=b.E;y<=b.D;y++){3.15(x,y,b.z,a)}}};m.l.15=9(x,y,z,a){4 b=3.Y(x,y,z);n(b){t(4 i=b.Z-1;i>=0;i--){a(b[i])}}};m.l.1M=9(x,y,z){3.15(x,y,z,3.I)};m.l.1K=9(x,y,z){3.15(x,y,z,3.P)};m.l.1h=9(c,d,a){4 b=3;b.1J(c,d,9(x,y){a.2p(b,[x,y,c.z])})};m.l.1J=9(j,k,b){4 f=j.A;4 a=j.E;4 d=j.G;4 h=j.D;4 g=k.A;4 c=k.E;4 e=k.G;4 i=k.D;4 x,y;t(x=f;x<=d;x++){t(y=a;y<=h&&y<c;y++){b(x,y)}t(y=s.S(i+1,a);y<=h;y++){b(x,y)}}t(y=s.S(a,c);y<=s.R(h,i);y++){t(x=s.R(d+1,g)-1;x>=f;x--){b(x,y)}t(x=s.S(f,e+1);x<=d;x++){b(x,y)}}};m.l.1b=9(a,c,b){4 d=0;t(4 i=0;i<a.Z;++i){n(a[i]===c||(b&&a[i]===c)){a.2n(i--,1);d++}}o d};9 K(b){3.1k(b);4 d=8;4 c=1<<d;4 a=7;3.1I=b;3.2k=-1;3.2r=3.2j=3.2t=3.2h=-1}K.l=u q.p.2v();K.l.1L=9(a){o(1+a/1T)};K.l.1P=9(b){4 a=s.2f(b*s.1D/1T);o(1-0.5/s.1D*s.2e((1+a)/(1-a)))};K.l.1C=9(a,d){4 c=3.1I;4 b=3.1E().2d(a);4 e={x:~~(0.5+3.1L(a.10())*(2<<(d+6))),y:~~(0.5+3.1P(a.1l())*(2<<(d+6)))};o e};K.l.2a=9(){n(!3.16){3.16=B;q.p.H.1g(3,\'16\')}};',62,168,'|||this|var|||||function||||||||||||prototype|MarkerManager|if|return|maps|google|shownBounds_|Math|for|new|show_|getTilePoint_||||minX|true|Size|maxY|minY|maxZoom_|maxX|event|removeOverlay_|numMarkers_|ProjectionHelperOverlay|gridWidth_|notifyListeners_|isGridPointVisible_|processAll_|addOverlay_|mapZoom_|min|max|grid_|false|getPosition|shownMarkers_|addListener|getGridCellNoCreate_|length|lng|GridBounds|onMapMoveEnd_|tileSize_|else|processCellMarkers_|ready|refresh|map_||getOptMaxZoom_|removeFromArray_|getGridCellCreate_|addMarkerBatch_|projectionHelper_|resetManager_|trigger|rectangleDiff_|maxZoom|getMapGridBounds_|setMap|lat|undefined|equals|mapTypes|while|nePadding_|DEFAULT_TILE_SIZE_|swPadding_|DEFAULT_BORDER_PADDING_|push|borderPadding|onMarkerMoved_|changed|MarkerManager_minZoom|updateMarkers_|show|initialize|LatLngToPixel|PI|getProjection|getZoom|MERCATOR_ZOOM_LEVEL_ZERO_RANGE|number|_map|rectangleDiffCoords_|addCellMarkers_|LngToX_|removeCellMarkers_|get|trackMarkers_|LatToY_|floor|objectSetTimeout_|getGridBounds_|180|containsPoint|zoom_changed|addMarker|idle|position|dragend|Marker|LatLng|getMarker|getMarkerCount|addMarkers|removeMarker|borderPadding_|typeof|height|width|draw|trackMarkers|Point|fromLatLngToDivPixel|log|sin|clearMarkers|_Y1|ceil|_Y0|_zoom|256|projection_|splice|100|apply|1024|_X0|loaded|_X1|toggle|OverlayView|hide|isHidden|visible|call|hasOwnProperty|setTimeout|window|getBounds|getNorthEast|null|getSouthWest|in'.split('|'),0,{}))<|endoftext|>


<commit_before>require([
    'website/js/app',
    'website/js/routes',
    'website/js/routes/index_route',
    'website/js/routes/portfolio_route',
    'website/js/routes/blog_route',
    'website/js/routes/stackoverflow_route',
    'website/js/routes/talks_route',
    'website/js/routes/publications_route',
    'website/js/routes/github_route',
    'website/js/routes/twitter_route',
    'website/js/views/index_view',
    'website/js/views/application_view',
    'website/js/views/portfolio_view',
    'website/js/views/blog_view',
    'website/js/views/stackoverflow_view',
    'website/js/views/talks_view',
    'website/js/views/publications_view',
    'website/js/views/github_view',
    'website/js/views/twitter_view',
    'website/js/routes/async_loader',
    'jQuery',
    'Bootstrap',
    'Handlebars',
    'Ember'
], function (
  app,
  routes,
  indexRoute,
  portfolioRoute,
  blogRoute,
  stackoverflowRoute,
  talksRoute,
  publicationsRoute,
  githubRoute,
  twitterRoute,
  indexView,
  applicationView,
  portfolioView,
  blogView,
  stackoverflowView,
  talksView,
  publicationsView,
  githubView,
  twitterView,
  asyncLoader
  ){
    "use strict";

    // pre load feeds
    var f  = function(d){ console.log(d); }
    var e  = function(e){ console.log(e); }
    asyncLoader.getGitHubFeedPromise()(f,e);
    asyncLoader.getSoFeedPromise()(f,e);
    asyncLoader.getTwitterFeedPromise()(f,e);
    asyncLoader.getBlogFeedPromise()(f,e);

    // Configure Routes
    app.Router.map(routes);

    // Configure Routes
    app.IndexRoute = indexRoute;
    app.PortfolioRoute = portfolioRoute;
    app.BlogRoute = blogRoute;
    app.StackoverflowRoute = stackoverflowRoute;
    app.TalksRoute = talksRoute;
    app.PublicationsRoute = publicationsRoute;
    app.GithubRoute = githubRoute;
    app.TwitterRoute = twitterRoute;

    // Configure Views
    app.IndexView = indexView;
    app.ApplicationView = applicationView;
    app.PortfolioView = portfolioView;
    app.BlogView = blogView;
    app.StackoverflowView = stackoverflowView;
    app.TalksView = talksView;
    app.PublicationsView = publicationsView;
    app.GithubView = githubView;
    app.TwitterView = twitterView;

    // We're ready to launch the app!
    app.advanceReadiness();

    $('.loader').hide();
});
<commit_msg>syntax error<commit_after>require([
    'website/js/app',
    'website/js/routes',
    'website/js/routes/index_route',
    'website/js/routes/portfolio_route',
    'website/js/routes/blog_route',
    'website/js/routes/stackoverflow_route',
    'website/js/routes/talks_route',
    'website/js/routes/publications_route',
    'website/js/routes/github_route',
    'website/js/routes/twitter_route',
    'website/js/views/index_view',
    'website/js/views/application_view',
    'website/js/views/portfolio_view',
    'website/js/views/blog_view',
    'website/js/views/stackoverflow_view',
    'website/js/views/talks_view',
    'website/js/views/publications_view',
    'website/js/views/github_view',
    'website/js/views/twitter_view',
    'website/js/routes/async_loader',
    'jQuery',
    'Bootstrap',
    'Handlebars',
    'Ember'
], function (
  app,
  routes,
  indexRoute,
  portfolioRoute,
  blogRoute,
  stackoverflowRoute,
  talksRoute,
  publicationsRoute,
  githubRoute,
  twitterRoute,
  indexView,
  applicationView,
  portfolioView,
  blogView,
  stackoverflowView,
  talksView,
  publicationsView,
  githubView,
  twitterView,
  asyncLoader
  ){
    "use strict";

    // pre load feeds
    var f  = function(d){ console.log(d); }
    var e  = function(e){ console.log(e); }
    var promises = [];
    promises.push(asyncLoader.getGitHubFeedPromise());
    promises.push(asyncLoader.getSoFeedPromise());
    promises.push(asyncLoader.getTwitterFeedPromise());
    promises.push(asyncLoader.getBlogFeedPromise());

    for(var i = 0; i < promises.length; i++) {
      var p = promises[i];
      p(f,e);
    }

    // Configure Routes
    app.Router.map(routes);

    // Configure Routes
    app.IndexRoute = indexRoute;
    app.PortfolioRoute = portfolioRoute;
    app.BlogRoute = blogRoute;
    app.StackoverflowRoute = stackoverflowRoute;
    app.TalksRoute = talksRoute;
    app.PublicationsRoute = publicationsRoute;
    app.GithubRoute = githubRoute;
    app.TwitterRoute = twitterRoute;

    // Configure Views
    app.IndexView = indexView;
    app.ApplicationView = applicationView;
    app.PortfolioView = portfolioView;
    app.BlogView = blogView;
    app.StackoverflowView = stackoverflowView;
    app.TalksView = talksView;
    app.PublicationsView = publicationsView;
    app.GithubView = githubView;
    app.TwitterView = twitterView;

    // We're ready to launch the app!
    app.advanceReadiness();

    $('.loader').hide();
});
<|endoftext|>


<commit_before>import {Aside} from '../../aside';

// TODO figure out if we can make all of these bindings (eg content's transform is bound to
// aside component's `transform` propety
class AsideBaseType {
  constructor(aside: Aside) {
    this.aside = aside;

    // TODO make this a setter
    aside.domElement.classList.add(`type-${aside.type}`);

    //FIXME(ajoslin): have to wait for for bindings to apply in a component
    setTimeout(() => {
      this.aside.content.setIsAside(true);
    })
  }
  setSliding(isSliding) {
    this.aside.noTransitionSetter(isSliding);
  }
  setOpen(isOpen) {
    this.aside.openSetter(isOpen);
  }
  setTransform(transform) {
    this.aside.transformSetter(transform);
  }
}

export class AsideOverlayType extends AsideBaseType {}

export class AsidePushType extends AsideBaseType {
  setSliding(isSliding) {
    super.setSliding(isSliding);
    this.aside.content.noTransitionSetter(isSliding);
  }
  setOpen(isOpen) {
    super.setOpen(isOpen);
    this.aside.content.asideOpenSetter(isOpen, this.aside.side);
  }
  setTransform(transform) {
    super.setTransform(transform);
    this.aside.content.transformSetter(transform);
  }
}

export class AsideRevealType extends AsideBaseType {
  setSliding(isSliding) {
    this.aside.content.noTransitionSetter(isSliding);
  }
  setOpen(isOpen) {
    super.setOpen(isOpen);
    this.aside.content.asideOpenSetter(isOpen, this.aside.side);
  }
  setTransform(transform) {
    this.aside.content.transformSetter(transform);
  }
}
<commit_msg>Update types.js<commit_after>import {Aside} from '../../aside';

// TODO figure out if we can make all of these bindings (eg can we make it so content's transform is bound to
// aside component's `transform` property?)
class AsideBaseType {
  constructor(aside: Aside) {
    this.aside = aside;

    // TODO make this a setter
    aside.domElement.classList.add(`type-${aside.type}`);

    //FIXME(ajoslin): have to wait for for bindings to apply in a component
    setTimeout(() => {
      this.aside.content.setIsAside(true);
    })
  }
  setSliding(isSliding) {
    this.aside.noTransitionSetter(isSliding);
  }
  setOpen(isOpen) {
    this.aside.openSetter(isOpen);
  }
  setTransform(transform) {
    this.aside.transformSetter(transform);
  }
}

export class AsideOverlayType extends AsideBaseType {}

export class AsidePushType extends AsideBaseType {
  setSliding(isSliding) {
    super.setSliding(isSliding);
    this.aside.content.noTransitionSetter(isSliding);
  }
  setOpen(isOpen) {
    super.setOpen(isOpen);
    this.aside.content.asideOpenSetter(isOpen, this.aside.side);
  }
  setTransform(transform) {
    super.setTransform(transform);
    this.aside.content.transformSetter(transform);
  }
}

export class AsideRevealType extends AsideBaseType {
  setSliding(isSliding) {
    this.aside.content.noTransitionSetter(isSliding);
  }
  setOpen(isOpen) {
    super.setOpen(isOpen);
    this.aside.content.asideOpenSetter(isOpen, this.aside.side);
  }
  setTransform(transform) {
    this.aside.content.transformSetter(transform);
  }
}
<|endoftext|>


<commit_before><commit_msg>Initial code<commit_after>/* Copyright (c) 2011 by The Authors.
 * Published under the LGPL 2.1 license.
 * See /license-notice.txt for the full text of the license notice.
 * See /license.txt for the full text of the license.
 */

/**
 * @constructor
 */
jsts.geomgraph.EdgeIntersectionList = function() {

};

<|endoftext|>


<commit_before>'use strict';

/**
 * Handles authorization based on provided permissions/roles.
 * @name permission.permissionDirective
 *
 * Directive accepts single or combined attributes `permission-only` and `permission-except` that checks on
 * DOM rendering if permissions/roles are met. Attributes can be passed either as String, Array or variable from
 * parent scope. Directive also will watch for changes if applied and automatically update the view.
 *
 * @example
 *

 *

 *

 *

 *

 *
 * By default directive will show/hide elements if provided permissions matches.
 * You can override this behaviour by passing `permission-on-authorized` and `permission-on-unauthorized`
 *   attributes that will pass to your function `$element` as argument that you can freely manipulate your DOM
 *   behaviour.
 *
 * Important! Function should be as references - `vm.disableElement` not `vm.disableElement()` to be able to
 *   accept passed $element reference from inside of permissionDirective
 *
 * @example
 *

 *

 *
 * @param $log {Object} Logging service
 * @param $injector {Object} Injector instance object
 * @param PermPermissionMap {permission.permPermissionMap|Function} Map of state access rights
 * @param PermPermissionStrategies {permission.permPermissionStrategies} Set of pre-defined directive behaviours
 *
 * @returns {{
 *   restrict: string,
 *   bindToController: {
 *     sref: string
 *     only: string,
 *     except: string,
 *     onAuthorized: function,
 *     onUnauthorized: function
 *   },
 *   controllerAs: string,
 *   controller: controller
 * }} Directive instance
 */
function PermissionDirective($log, $injector, PermPermissionMap, PermPermissionStrategies) {
  'ngInject';

  return {
    restrict: 'A',
    bindToController: {
      sref: '=?permissionSref',
      only: '=?permissionOnly',
      except: '=?permissionExcept',
      onAuthorized: '&?permissionOnAuthorized',
      onUnauthorized: '&?permissionOnUnauthorized'
    },
    controllerAs: 'permission',
    controller: function ($scope, $element) {
      var permission = this;

      $scope.$watchGroup(['permission.only', 'permission.except', 'sref'],
        function () {
          try {
            if (isSrefStateDefined()) {
              var PermStateAuthorization = $injector.get('PermStateAuthorization');

              PermStateAuthorization
                .authorizeByStateName(permission.sref)
                .then(function () {
                  onAuthorizedAccess();
                })
                .catch(function () {
                  onUnauthorizedAccess();
                });
            } else {
              var PermAuthorization = $injector.get('PermAuthorization');
              var permissionMap = new PermPermissionMap({only: permission.only, except: permission.except});

              PermAuthorization
                .authorizeByPermissionMap(permissionMap)
                .then(function () {
                  onAuthorizedAccess();
                })
                .catch(function () {
                  onUnauthorizedAccess();
                });
            }
          } catch (e) {
            onUnauthorizedAccess();
            $log.error(e.message);
          }
        });

      /**
       * Returns true when permissions should be checked based on state name
       * @private
       *
       * @returns {boolean}
       */
      function isSrefStateDefined() {
        return $injector.has('$state') && permission.sref;
      }

      /**
       * Calls `onAuthorized` function if provided or show element
       * @private
       */
      function onAuthorizedAccess() {
        if (angular.isFunction(permission.onAuthorized)) {
          permission.onAuthorized()($element);
        } else {
          PermPermissionStrategies.showElement($element);
        }
      }

      /**
       * Calls `onUnauthorized` function if provided or hide element
       * @private
       */
      function onUnauthorizedAccess() {
        if (angular.isFunction(permission.onUnauthorized)) {
          permission.onUnauthorized()($element);
        } else {
          PermPermissionStrategies.hideElement($element);
        }
      }
    }
  };
}

angular
  .module('permission')
  .directive('permission', PermissionDirective);
<commit_msg>Update permission.js<commit_after>'use strict';

/**
 * Handles authorization based on provided permissions/roles.
 * @name permission.permissionDirective
 *
 * Directive accepts single or combined attributes `permission-only` and `permission-except` that checks on
 * DOM rendering if permissions/roles are met. Attributes can be passed either as String, Array or variable from
 * parent scope. Directive also will watch for changes if applied and automatically update the view.
 *
 * @example
 *

 *

 *

 *

 *

 *
 * By default directive will show/hide elements if provided permissions matches.
 * You can override this behaviour by passing `permission-on-authorized` and `permission-on-unauthorized`
 *   attributes that will pass to your function `$element` as argument that you can freely manipulate your DOM
 *   behaviour.
 *
 * Important! Function should be as references - `vm.disableElement` not `vm.disableElement()` to be able to
 *   accept passed $element reference from inside of permissionDirective
 *
 * @example
 *

 *

 *
 * @param $log {Object} Logging service
 * @param $injector {Object} Injector instance object
 * @param PermPermissionMap {permission.permPermissionMap|Function} Map of state access rights
 * @param PermPermissionStrategies {permission.permPermissionStrategies} Set of pre-defined directive behaviours
 *
 * @returns {{
 *   restrict: string,
 *   bindToController: {
 *     sref: string
 *     only: string,
 *     except: string,
 *     onAuthorized: function,
 *     onUnauthorized: function
 *   },
 *   controllerAs: string,
 *   controller: controller
 * }} Directive instance
 */
function PermissionDirective($log, $injector, PermPermissionMap, PermPermissionStrategies) {
  'ngInject';

  return {
    restrict: 'A',
    bindToController: {
      sref: '=?permissionSref',
      only: '=?permissionOnly',
      except: '=?permissionExcept',
      onAuthorized: '&?permissionOnAuthorized',
      onUnauthorized: '&?permissionOnUnauthorized'
    },
    controllerAs: 'permission',
    controller: function ($scope, $element) {
      var permission = this;

      $scope.$watchGroup(['permission.only', 'permission.except', 'sref'],
        function () {
          try {
            if (isSrefStateDefined()) {
              var PermStateAuthorization = $injector.get('PermStateAuthorization');

              PermStateAuthorization
                .authorizeByStateName(permission.sref)
                .then(function () {
                  onAuthorizedAccess();
                })
                .catch(function () {
                  onUnauthorizedAccess();
                });
            } else {
              var PermAuthorization = $injector.get('PermAuthorization');
              var permissionMap = new PermPermissionMap({only: permission.only, except: permission.except});

              PermAuthorization
                .authorizeByPermissionMap(permissionMap)
                .then(function () {
                  onAuthorizedAccess();
                })
                .catch(function () {
                  onUnauthorizedAccess();
                });
            }
          } catch (e) {
            onUnauthorizedAccess();
            $log.error(e.message);
          }
        });

      /**
       * Returns true when permissions should be checked based on state name
       * @private
       *
       * @returns {boolean}
       */
      function isSrefStateDefined() {
        return $injector.has('$state') && permission.sref;
      }

      /**
       * Calls `onAuthorized` function if provided or show element
       * @private
       */
      function onAuthorizedAccess() {
        if (angular.isFunction(permission.onAuthorized)) {
          permission.onAuthorized()($element);
        } else {
          PermPermissionStrategies.showElement($element);
        }
      }

      /**
       * Calls `onUnauthorized` function if provided or hide element
       * @private
       */
      function onUnauthorizedAccess() {
        if (angular.isFunction(permission.onUnauthorized)) {
          permission.onUnauthorized()($element);
        } else {
          PermPermissionStrategies.hideElement($element);
        }
      }
    }
  };
}

angular
  .module('permission')
  .directive('permission', PermissionDirective);
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014, D.C.S. LLC. All Rights Reserved. Licensed Software.
 * @ignore
 */

/**
 * A signaling message and the information needed to route it.
 * @author Erin Spiceland <espiceland@digium.com>
 * @class respoke.SignalingMessage
 * @constructor
 * @param {object} params
 * @param {string} [params.endpointId] - If sending, the endpoint ID of the recipient
 * @param {string} [params.connectionId] - If sending, the connection ID of the recipient
 * @param {string} [params.signal] - If sending, a message to send
 * @param {respoke.Endpoint} [params.recipient]
 * @param {string} [params.signalType]
 * @param {string} [params.sessionId] - A globally unique ID to identify this call.
 * @param {string} [params.target] - Either 'call' or 'directConnection', TODO remove the need for this.
 * @param {string} [params.signalId] - A globally unique ID to identify this signal and it's ACK.
 * @param {string} [params.callerId] - Human readable caller ID. Not implemented.
 * @param {RTCSessionDescription} [params.sdp]
 * @param {Array<RTCIceCandidate>} [params.iceCandidates]
 * @param {object} [params.offering] - Object describing the media we're offering to send the remote party in a more
 * usable way than SDP. Not implemented.
 * @param {object} [params.requesting] - Object describing the media we're requesting from the remote party in a more
 * usable way than SDP. Not implemented.
 * @param {string} [params.reason] - Human readable reason for hanging up.
 * @param {string} [params.error] - String indicating that a previous signal was malformed or received in the wrong
 * state. Not implemented.
 * @param {string} [params.status] - "Ringing". Not implemented.
 * @param {object} [params.rawMessage] - If receiving, the parsed JSON we got from the server
 * @private
 * @returns {respoke.SignalingMessage}
 */
module.exports = function (params) {
    "use strict";
    params = params || {};
    var that = {};
    /**
     * Attributes without which we cannot build a signaling message.
     * @memberof! respoke.SignalingMessage
     * @name required
     * @private
     * @type {string}
     */
    var required = ['recipient', 'signalType', 'sessionId', 'target', 'signalId'];
    /**
     * Attributes which we will copy onto the signal if defined.
     * @memberof! respoke.SignalingMessage
     * @name required
     * @private
     * @type {string}
     */
    var allowed = [
        'signalType', 'sessionId', 'callerId', 'sessionDescription', 'iceCandidates', 'offering', 'target', 'signalId',
        'requesting', 'reason', 'error', 'status'
    ];

    /**
     * Parse rawMessage and set attributes required for message delivery.
     * @memberof! respoke.SignalingMessage
     * @method respoke.SignalingMessage.parse
     * @private
     */
    function parse() {
        if (params.rawMessage) {
            try {
                that = JSON.parse(params.rawMessage.signal); // Incoming message
                that.endpointId = params.rawMessage.header.from;
                that.connectionId = params.rawMessage.header.fromConnection;
            } catch (e) {
                throw new Error(e);
            }
        } else {
            required.forEach(function eachAttr(attr) {
                if (params[attr] === 0 || !params[attr]) {
                    throw new Error("Can't build a signaling without " + attr);
                }
            });

            allowed.forEach(function eachAttr(attr) {
                if (params[attr] === 0 || params[attr]) {
                    that[attr] = params[attr];
                }
            });

            that.to = params.recipient.id;
            that.toConnection = params.connectionId;
        }
    }

    parse();
    return that;
}; // End respoke.SignalingMessage
<commit_msg>rename rawMessage.signal to rawMessage.body<commit_after>/**
 * Copyright (c) 2014, D.C.S. LLC. All Rights Reserved. Licensed Software.
 * @ignore
 */

/**
 * A signaling message and the information needed to route it.
 * @author Erin Spiceland <espiceland@digium.com>
 * @class respoke.SignalingMessage
 * @constructor
 * @param {object} params
 * @param {string} [params.endpointId] - If sending, the endpoint ID of the recipient
 * @param {string} [params.connectionId] - If sending, the connection ID of the recipient
 * @param {string} [params.signal] - If sending, a message to send
 * @param {respoke.Endpoint} [params.recipient]
 * @param {string} [params.signalType]
 * @param {string} [params.sessionId] - A globally unique ID to identify this call.
 * @param {string} [params.target] - Either 'call' or 'directConnection', TODO remove the need for this.
 * @param {string} [params.signalId] - A globally unique ID to identify this signal and it's ACK.
 * @param {string} [params.callerId] - Human readable caller ID. Not implemented.
 * @param {RTCSessionDescription} [params.sdp]
 * @param {Array<RTCIceCandidate>} [params.iceCandidates]
 * @param {object} [params.offering] - Object describing the media we're offering to send the remote party in a more
 * usable way than SDP. Not implemented.
 * @param {object} [params.requesting] - Object describing the media we're requesting from the remote party in a more
 * usable way than SDP. Not implemented.
 * @param {string} [params.reason] - Human readable reason for hanging up.
 * @param {string} [params.error] - String indicating that a previous signal was malformed or received in the wrong
 * state. Not implemented.
 * @param {string} [params.status] - "Ringing". Not implemented.
 * @param {object} [params.rawMessage] - If receiving, the parsed JSON we got from the server
 * @private
 * @returns {respoke.SignalingMessage}
 */
module.exports = function (params) {
    "use strict";
    params = params || {};
    var that = {};
    /**
     * Attributes without which we cannot build a signaling message.
     * @memberof! respoke.SignalingMessage
     * @name required
     * @private
     * @type {string}
     */
    var required = ['recipient', 'signalType', 'sessionId', 'target', 'signalId'];
    /**
     * Attributes which we will copy onto the signal if defined.
     * @memberof! respoke.SignalingMessage
     * @name required
     * @private
     * @type {string}
     */
    var allowed = [
        'signalType', 'sessionId', 'callerId', 'sessionDescription', 'iceCandidates', 'offering', 'target', 'signalId',
        'requesting', 'reason', 'error', 'status'
    ];

    /**
     * Parse rawMessage and set attributes required for message delivery.
     * @memberof! respoke.SignalingMessage
     * @method respoke.SignalingMessage.parse
     * @private
     */
    function parse() {
        if (params.rawMessage) {
            try {
                that = JSON.parse(params.rawMessage.body); // Incoming message
                that.endpointId = params.rawMessage.header.from;
                that.connectionId = params.rawMessage.header.fromConnection;
            } catch (e) {
                throw new Error(e);
            }
        } else {
            required.forEach(function eachAttr(attr) {
                if (params[attr] === 0 || !params[attr]) {
                    throw new Error("Can't build a signaling without " + attr);
                }
            });

            allowed.forEach(function eachAttr(attr) {
                if (params[attr] === 0 || params[attr]) {
                    that[attr] = params[attr];
                }
            });

            that.to = params.recipient.id;
            that.toConnection = params.connectionId;
        }
    }

    parse();
    return that;
}; // End respoke.SignalingMessage
<|endoftext|>


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

if(PP.config.enableLogStash)
{
    Ext.define('PP.Logstash_Proxy', {
        extend: 'Ext.data.proxy.Ajax',
        alias: 'proxy.logstash',
        actionMethods: {
            read: 'POST'
        },
        requestQuery: {},
        doRequest: function(operation, callback, scope) {
            var writer  = this.getWriter(),
                request = this.buildRequest(operation);

            if (operation.allowWrite()) {
                request = writer.write(request);
            }

            Ext.apply(request, {
                binary        : this.binary,
                headers       : this.headers,
                timeout       : this.timeout,
                scope         : this,
                jsonData      : this.requestQuery,
                callback      : this.createRequestCallback(request, operation, callback, scope),
                method        : this.getMethod(request),
                disableCaching: false // explicitly set it to false, ServerProxy handles caching
            });

            Ext.Ajax.request(request);

            return request;
        },
    });
    Ext.define('logentry',{
        extend: 'Ext.data.Model',
        // idProperty: 'entity_key',
        fields:[
        { name:'timestamp',mapping:'_source["@timestamp"]'},
        { name: 'type', mapping: '_source["@type"]'},
        { name: 'message', mapping: '_source["@message"]'},
        { name: 'source_host', mapping: '_source["@source_host"]'},
        { name: 'program', mapping: '_source["@fields"].syslog_program[0]'},
        { name: 'facility', mapping: '_source["@fields"].syslog_facility'}
        ],
        remoteSort: false,
        proxy:{
            type: 'logstash',
            startParam: undefined,
            pageParam: undefined,
            limitParam: undefined,
            filterParam: undefined,
            url: PP.config.logstashpath,
            actionMethods: {read:'POST'},
            sortParam:undefined,
            reader:{
                type:'json',
                root:'hits.hits'
            }
        }
    });
}
Ext.define('PP.LogPanel',{
    extend: 'Ext.grid.Panel',
    alias: 'widget.logpanel',
    title: 'Logs',
    system_fqdn:'',
    loaded: false,
    features: [ {
        ftype: 'filters',
        // encode and local configuration options defined previously for easier reuse
        encode: 'encode', // json encode the filter query
        local: 'local',   // defaults to false (remote filtering)

        // Filters are most naturally placed in the column definition, but can also be
        // added here.
        filters: [{
            type: 'boolean',
            dataIndex: 'visible'
        }]
    }],
    listeners: {
        'activate':{
            fn: function(p){
                p.load();
            }
        },
        'boxready':{
            fn: function(p){
                p.load();
            }
        }
    },
    tbar:[
        {
            xtype:'button',
            icon: 'images/refresh.gif',
            text: 'Refresh',
            handler: function(){
                var p=this.up('panel');
                p.loaded=false;
                p.load();
            },
        },
        {
            xtype:'tbfill'
        },
        {
            xtype: 'box',
            autoEl: {
                tag: 'a',
                target: '_blank',
                href: 'http://' + PP.config.logstash_server + '/',
                cn: 'LogStash UI'
            }
        }
    ],
    viewConfig:{
        loadMask:true
    },
    store: new Ext.data.Store({
        model: 'logentry',
        sorters: [{
            property:'timestamp',
            direction: 'DESC'
        }],
        instance: this,
        autoLoad:false
    }),
    columns:[
        {header:'Date',flex:1,dataIndex:'timestamp',sortable:true,filterable:true},
        {header:'Host',flex:1,dataIndex:'source_host',hidden:true,sortable:true,filterable:true},
        {header:'Message',flex:2,dataIndex:'message',sortable:true,filterable:false},
        {header:'Program',flex:1,dataIndex:'program',sortable:true,filterable:true},
        {header:'Facility',flex:1,dataIndex:'facility',sortable:true,filterable:true}
    ],
    load: function(system_fqdn)
    {
        if(system_fqdn)
        {
            if(this.system_fqdn!=system_fqdn)
            {
                this.loaded=false;
            }
            this.system_fqdn=system_fqdn;
        }
        if(!this.loaded && this.isVisible() && this.system_fqdn)
        {
            var logquery=PP.prepquery(this.system_fqdn);
            this.store.getProxy().url='/logstash/logstash-' + Ext.Date.format(new Date(),'Y.m.d') + '/_search';
            this.store.getProxy().requestQuery=logquery;
            this.store.load();
            PP.log('fetched logs with query: ');
            PP.log(logquery);
            this.loaded=true;
        }
    }
});
<commit_msg>fixing not using config logstash path for url construction in load command<commit_after>// Copyright 2011-2013 Proofpoint, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
if(PP.config.enableLogStash)
{
    Ext.define('PP.Logstash_Proxy', {
        extend: 'Ext.data.proxy.Ajax',
        alias: 'proxy.logstash',
        actionMethods: {
            read: 'POST'
        },
        requestQuery: {},
        doRequest: function(operation, callback, scope) {
            var writer  = this.getWriter(),
                request = this.buildRequest(operation);

            if (operation.allowWrite()) {
                request = writer.write(request);
            }

            Ext.apply(request, {
                binary        : this.binary,
                headers       : this.headers,
                timeout       : this.timeout,
                scope         : this,
                jsonData      : this.requestQuery,
                callback      : this.createRequestCallback(request, operation, callback, scope),
                method        : this.getMethod(request),
                disableCaching: false // explicitly set it to false, ServerProxy handles caching
            });

            Ext.Ajax.request(request);

            return request;
        },
    });
    Ext.define('logentry',{
        extend: 'Ext.data.Model',
        // idProperty: 'entity_key',
        fields:[
        { name:'timestamp',mapping:'_source["@timestamp"]'},
        { name: 'type', mapping: '_source["@type"]'},
        { name: 'message', mapping: '_source["@message"]'},
        { name: 'source_host', mapping: '_source["@source_host"]'},
        { name: 'program', mapping: '_source["@fields"].syslog_program[0]'},
        { name: 'facility', mapping: '_source["@fields"].syslog_facility'}
        ],
        remoteSort: false,
        proxy:{
            type: 'logstash',
            startParam: undefined,
            pageParam: undefined,
            limitParam: undefined,
            filterParam: undefined,
            url: PP.config.logstashpath,
            actionMethods: {read:'POST'},
            sortParam:undefined,
            reader:{
                type:'json',
                root:'hits.hits'
            }
        }
    });
    Ext.define('PP.LogPanel',{
        extend: 'Ext.grid.Panel',
        alias: 'widget.logpanel',
        title: 'Logs',
        system_fqdn:'',
        loaded: false,
        features: [ {
            ftype: 'filters',
            // encode and local configuration options defined previously for easier reuse
            encode: 'encode', // json encode the filter query
            local: 'local',   // defaults to false (remote filtering)

            // Filters are most naturally placed in the column definition, but can also be
            // added here.
            filters: [{
                type: 'boolean',
                dataIndex: 'visible'
            }]
        }],
        listeners: {
            'activate':{
                fn: function(p){
                    p.load();
                }
            },
            'boxready':{
                fn: function(p){
                    p.load();
                }
            }
        },
        tbar:[
            {
                xtype:'button',
                icon: 'images/refresh.gif',
                text: 'Refresh',
                handler: function(){
                    var p=this.up('panel');
                    p.loaded=false;
                    p.load();
                },
            },
            {
                xtype:'tbfill'
            },
            {
                xtype: 'box',
                autoEl: {
                    tag: 'a',
                    target: '_blank',
                    href: 'http://' + PP.config.logstash_server + '/',
                    cn: 'LogStash UI'
                }
            }
        ],
        viewConfig:{
            loadMask:true
        },
        store: new Ext.data.Store({
            model: 'logentry',
            sorters: [{
                property:'timestamp',
                direction: 'DESC'
            }],
            instance: this,
            autoLoad:false
        }),
        columns:[
            {header:'Date',flex:1,dataIndex:'timestamp',sortable:true,filterable:true},
            {header:'Host',flex:1,dataIndex:'source_host',hidden:true,sortable:true,filterable:true},
            {header:'Message',flex:2,dataIndex:'message',sortable:true,filterable:false},
            {header:'Program',flex:1,dataIndex:'program',sortable:true,filterable:true},
            {header:'Facility',flex:1,dataIndex:'facility',sortable:true,filterable:true}
        ],
        load: function(system_fqdn)
        {
            if(system_fqdn)
            {
                if(this.system_fqdn!=system_fqdn)
                {
                    this.loaded=false;
                }
                this.system_fqdn=system_fqdn;
            }
            if(!this.loaded && this.isVisible() && this.system_fqdn)
            {
                var logquery=PP.prepquery(this.system_fqdn);
                this.store.getProxy().url=PP.config.logstashpath + 'logstash-' + Ext.Date.format(new Date(),'Y.m.d') + '/_search';
                this.store.getProxy().requestQuery=logquery;
                this.store.load();
                PP.log('fetched logs with query: ');
                PP.log(logquery);
                this.loaded=true;
            }
        },
        prepquery: function(host,days){
            if(days==undefined || days=='')
            {
                days=1;
            }
            var logstashquery={
              "query": {
                "filtered": {
                  "query": {
                    "query_string": {
                      "query": "@source_host:\"m0044556.lab.ppops.net\""
                    }
                  },
                  "filter": {
                    "range": {
                      "@timestamp": {
                        "from": "2013-07-09T11:39:06.040Z",
                        "to": "2013-07-09T17:39:06.041Z"
                      }
                    }
                  }
                }
              },
              "highlight": {
                "fields": {},
                "fragment_size": 2147483647,
                "pre_tags": [
                  "@start-highlight@"
                ],
                "post_tags": [
                  "@end-highlight@"
                ]
              },
              "size": 500,
              "sort": [
                {
                  "@timestamp": {
                    "order": "desc"
                  }
                }
              ]
            };

            logstashquery.query.filtered.query.query_string.query='@source_host:"' + host + '"';
            logstashquery.query.filtered.filter.range['@timestamp'].from=Ext.Date.format(Ext.Date.subtract(new Date(),Ext.Date.DAY,days),'Y-m-d\\TH:i:s') + '.000Z';
            logstashquery.query.filtered.filter.range['@timestamp'].to=Ext.Date.format(new Date(),'Y-m-d\\TH:i:s') + '.000Z';;
            return logstashquery;
        }
    });
}<|endoftext|>


<commit_before>var extend     = require('./extend');
var expiration = require('./expiration');
var keygen     = require('./keygen');
var tryItem    = require('./tryItem');
var migrate    = require('./migrate');

/**
 * @param {Object} localStorage, sessionStorage
 * @param {String} namespace
 * @param {String} semver
 */
module.exports = function storge(storage, namespace, semver) {
    var expire = expiration(storage);
    var gen = keygen(namespace, semver);
    var migration = migrate(storage, gen.space, gen.ver);

    var api = function(name, semver) {
        return storge(storage, name, semver);
    };

    /**
     * Clear data from storage
     */
    var clear = function() {
        getKeys().forEach(function(key) {
            tryItem.remove(storage, key);
        });
        return api;
    };

    /**
     * Get keys from storage
     * @return {Array[String]}
     */
    var getKeys = function() {
        return tryItem.keys(storage)
            .filter(gen.matches);
    };

    /**
     * Get a key at the specified index
     * @param  {Number} index
     * @return {String} key
     */
    var getKey = function(index) {
        var key = tryItem.key(index);
        return key !== undefined ? gen.esc(key) : undefined;
    };

    /**
     * Retrieve item from data
     * @param  {String|Array.<String>} key
     * @return {*}
     */
    var getItem = function(key) {
        // Array is passed, get all values under
        // the keys
        if (Array.isArray(key)) {
            var arr = key.slice(),
                idx = arr.length;
            while (idx--) {
                arr[idx] = tryItem.get(storage, gen.enc(arr[idx]), api.err);
            }
            return arr;
        }

        var genkey = gen.enc(key);
        if (expire.expired(genkey)) {
            removeItem(key);
            return undefined;
        }

        return tryItem.get(storage, genkey, api.err);
    };

    /**
     * Adds to data
     * @param {String|Object} key
     * @param {*} value
     * @param {Object} [opts] for setting the expiration
     */
    var setItem = function(key, value, opts) {
        // Not a string, must be an object,
        // multiple items are being set
        if (typeof key !== 'string') {
            var k;
            for (k in key) {
                setItem(k, key[k], value);
            }
            return api;
        }

        var genkey = gen.enc(key);

        // Expiration
        if (opts) {
            if (opts.ttl !== undefined) {
                expire.set(genkey, opts.ttl);
            }
            if (typeof opts === 'number') {
                expire.set(genkey, opts);
            }
        }

        tryItem.set(storage, genkey, value, api.err);
        return api;
    };

    /**
     * Remove an item from storage by key
     * @param {String} key
     * @returns {*}
     */
    var removeItem = function(key) {
        // Array is passed, remove all values under
        // the keys
        if (Array.isArray(key)) {
            var arr = key.slice(),
                idx = arr.length;
            while (idx--) {
                arr[idx] = tryItem.remove(gen.enc(arr[idx]));
            }
            return arr;
        }

        return tryItem.remove(storage, gen.enc(key), api.err);
    };

    return extend(api, {
        err: function() {},

        clear:      clear,
        keys:       getKeys,
        key:        getKey,
        getItem:    getItem,
        setItem:    setItem,
        removeItem: removeItem,

        /**
         * Proxies
         */
        get: getItem,
        set: setItem,

        /**
         * Dangerous, clears all of the
         * storage, reguardless of namespace
         * and versioning
         */
        flush: function() {
            tryItem.clear();
            return api;
        },

        /**
         * removeItem returns the removed item,
         * this one chains
         * @param {String} key
         * @returns {Storage}
         */
        remove: function(key) {
            removeItem(key);
            return api;
        },

        /**
         * Async methods
         */
        getAsync: function(key) {
            return new Promise(function(resolve) {
                resolve(getItem(key));
            });
        },
        setAsync: function(key, value, opts) {
            return new Promise(function(resolve) {
                setItem(key, value, opts);
                resolve();
            });
        },
        removeAsync: function(key) {
            return new Promise(function(resolve) {
                resolve(removeItem(key));
            });
        },
        clearAsync: function() {
            return new Promise(function(resolve) {
                clear();
                resolve();
            });
        },
        keyAsync: function(index) {
            return new Promise(function(resolve) {
                resolve(getKey(index));
            });
        },
        keysAsync: function() {
            return new Promise(function(resolve) {
                resolve(getKeys());
            });
        },

        /**
         * Migration
         */
        migration: function(config) {
            if (Array.isArray(config)) { config.forEach(migration.add); return api; }
            migration.add(config);
            return api;
        },
        migrate: function() {
            if (!gen.active) { return api; }
            migration.migrate();
            return api;
        },
        deprecate: function() {
            if (!gen.active) { return api; }
            migration.deprecate();
            return api;
        },

        /**
         * Return storage values for JSON serialization
         * @param  {String} [key] return a specific value
         * @return {*|Object}
         */
        toJSON: function(key) {
            if (key !== undefined) {
                return getItem(key);
            }

            // no key, retrieve everything
            return getKeys().reduce(function(memo, key) {
                memo[gen.esc(key)] = tryItem.get(storage, key);
                return memo;
            }, {});
        },

        /**
         * Dangerous, back up all of
         * storage, reguardless of namespace
         * and versioning
         */
        backup: function() {
            return tryItem.keys(storage).reduce(function(memo, key) {
                memo[key] = tryItem.get(storage, key);
                return memo;
            }, {});
        }
    });
};<commit_msg>add reference for minification<commit_after>var extend     = require('./extend');
var expiration = require('./expiration');
var keygen     = require('./keygen');
var tryItem    = require('./tryItem');
var migrate    = require('./migrate');

/**
 * @param {Object} localStorage, sessionStorage
 * @param {String} namespace
 * @param {String} semver
 */
var storge = module.exports = function storge(storage, namespace, semver) {
    var expire = expiration(storage);
    var gen = keygen(namespace, semver);
    var migration = migrate(storage, gen.space, gen.ver);

    var api = function(name, semver) {
        return storge(storage, name, semver);
    };

    /**
     * Clear data from storage
     */
    var clear = function() {
        getKeys().forEach(function(key) {
            tryItem.remove(storage, key);
        });
        return api;
    };

    /**
     * Get keys from storage
     * @return {Array[String]}
     */
    var getKeys = function() {
        return tryItem.keys(storage)
            .filter(gen.matches);
    };

    /**
     * Get a key at the specified index
     * @param  {Number} index
     * @return {String} key
     */
    var getKey = function(index) {
        var key = tryItem.key(index);
        return key !== undefined ? gen.esc(key) : undefined;
    };

    /**
     * Retrieve item from data
     * @param  {String|Array.<String>} key
     * @return {*}
     */
    var getItem = function(key) {
        // Array is passed, get all values under
        // the keys
        if (Array.isArray(key)) {
            var arr = key.slice(),
                idx = arr.length;
            while (idx--) {
                arr[idx] = tryItem.get(storage, gen.enc(arr[idx]), api.err);
            }
            return arr;
        }

        var genkey = gen.enc(key);
        if (expire.expired(genkey)) {
            removeItem(key);
            return undefined;
        }

        return tryItem.get(storage, genkey, api.err);
    };

    /**
     * Adds to data
     * @param {String|Object} key
     * @param {*} value
     * @param {Object} [opts] for setting the expiration
     */
    var setItem = function(key, value, opts) {
        // Not a string, must be an object,
        // multiple items are being set
        if (typeof key !== 'string') {
            var k;
            for (k in key) {
                setItem(k, key[k], value);
            }
            return api;
        }

        var genkey = gen.enc(key);

        // Expiration
        if (opts) {
            if (opts.ttl !== undefined) {
                expire.set(genkey, opts.ttl);
            }
            if (typeof opts === 'number') {
                expire.set(genkey, opts);
            }
        }

        tryItem.set(storage, genkey, value, api.err);
        return api;
    };

    /**
     * Remove an item from storage by key
     * @param {String} key
     * @returns {*}
     */
    var removeItem = function(key) {
        // Array is passed, remove all values under
        // the keys
        if (Array.isArray(key)) {
            var arr = key.slice(),
                idx = arr.length;
            while (idx--) {
                arr[idx] = tryItem.remove(gen.enc(arr[idx]));
            }
            return arr;
        }

        return tryItem.remove(storage, gen.enc(key), api.err);
    };

    return extend(api, {
        err: function() {},

        clear:      clear,
        keys:       getKeys,
        key:        getKey,
        getItem:    getItem,
        setItem:    setItem,
        removeItem: removeItem,

        /**
         * Proxies
         */
        get: getItem,
        set: setItem,

        /**
         * Dangerous, clears all of the
         * storage, reguardless of namespace
         * and versioning
         */
        flush: function() {
            tryItem.clear();
            return api;
        },

        /**
         * removeItem returns the removed item,
         * this one chains
         * @param {String} key
         * @returns {Storage}
         */
        remove: function(key) {
            removeItem(key);
            return api;
        },

        /**
         * Async methods
         */
        getAsync: function(key) {
            return new Promise(function(resolve) {
                resolve(getItem(key));
            });
        },
        setAsync: function(key, value, opts) {
            return new Promise(function(resolve) {
                setItem(key, value, opts);
                resolve();
            });
        },
        removeAsync: function(key) {
            return new Promise(function(resolve) {
                resolve(removeItem(key));
            });
        },
        clearAsync: function() {
            return new Promise(function(resolve) {
                clear();
                resolve();
            });
        },
        keyAsync: function(index) {
            return new Promise(function(resolve) {
                resolve(getKey(index));
            });
        },
        keysAsync: function() {
            return new Promise(function(resolve) {
                resolve(getKeys());
            });
        },

        /**
         * Migration
         */
        migration: function(config) {
            if (Array.isArray(config)) { config.forEach(migration.add); return api; }
            migration.add(config);
            return api;
        },
        migrate: function() {
            if (!gen.active) { return api; }
            migration.migrate();
            return api;
        },
        deprecate: function() {
            if (!gen.active) { return api; }
            migration.deprecate();
            return api;
        },

        /**
         * Return storage values for JSON serialization
         * @param  {String} [key] return a specific value
         * @return {*|Object}
         */
        toJSON: function(key) {
            if (key !== undefined) {
                return getItem(key);
            }

            // no key, retrieve everything
            return getKeys().reduce(function(memo, key) {
                memo[gen.esc(key)] = tryItem.get(storage, key);
                return memo;
            }, {});
        },

        /**
         * Dangerous, back up all of
         * storage, reguardless of namespace
         * and versioning
         */
        backup: function() {
            return tryItem.keys(storage).reduce(function(memo, key) {
                memo[key] = tryItem.get(storage, key);
                return memo;
            }, {});
        }
    });
};<|endoftext|>


<commit_before>'use strict';

module.exports = {
  camelCase: require('./camel-case'),
  colorString: require('./color-string'),
  nestOptions: require('./nest-options'),
  uid: require('./uid'),
  request: require('./request'),
  metadata: require('./metadata'),
  framerate: require('./framerate')
};
<commit_msg>Add normalise language to utils index<commit_after>'use strict';

module.exports = {
  camelCase: require('./camel-case'),
  colorString: require('./color-string'),
  nestOptions: require('./nest-options'),
  uid: require('./uid'),
  request: require('./request'),
  metadata: require('./metadata'),
  framerate: require('./framerate'),
  normalizeLanguage: require('./normalize-language')
};
<|endoftext|>


<commit_before>/**
 * Created by prism on 10/5/14.
 */
<commit_msg>added random password generation<commit_after>/**
 * Created by prism on 10/5/14.
 */
$(document).ready(function() {
    $( "#generate" ).click(function() {
        var length = $('#range').val();
        var charset = "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+";
        var retVal = "";
        for (var i = 0, n = charset.length; i < length; ++i) {
            retVal += charset.charAt(Math.floor(Math.random() * n));
        }
        $('#inputPassword').val(retVal);
    });
});<|endoftext|>


<commit_before>// $Revision$

Ensembl.Panel.Masthead = Ensembl.Panel.extend({
  constructor: function (id) {
    var minWidth    = Ensembl.minWidthEl.width();
    var windowWidth = $(window).width();

    this.longTabs  = false;
    this.moreShown = false;
    this.zIndex    = 10000;

    this.base(id);

    Ensembl.EventManager.register('windowResize', this, this.resize);
  },

  init: function () {
    var panel = this;

    this.base();

    var tabsHolder = $('.tabs_holder', this.el);
    var tabs       = $('.tabs', tabsHolder);
    var tools      = $('.tools_holder', this.el);
    var logo       = $('.logo_holder', this.el);

    this.elLk.shortTabs  = $('li.short_tab', tabs);
    this.elLk.longTabs   = $('li.long_tab', tabs);
    this.elLk.dropdowns  = $('div.dropdown', tabsHolder);
    this.elLk.toolsUl    = $('.tools', tools);
    this.elLk.tools      = $('li', this.elLk.toolsUl);
    this.elLk.toolMore   = $('.more', tools);
    this.elLk.toolMoreUl = $('
').appendTo(this.elLk.toolMore);

    $('.toggle', tabs).bind('click', function () {
      var tab      = $(this).parent();
      var dropdown = panel.elLk.dropdowns.has('ul.' + this.rel);
      var tabWidth, dropdownWidth;

      if (!dropdown.data('positioning')) {
        tabWidth      = tab.outerWidth();
        dropdownWidth = dropdown.outerWidth();

        if (tabWidth > dropdownWidth) {
          dropdown.width(tabWidth - (dropdownWidth - dropdown.width()));
        }

        dropdown.css('left', tab.position().left).data('positioning', 1);
      }

      dropdown.not(':visible').css('zIndex', panel.zIndex++).end().toggle();

      tab      = null;
      dropdown = null;

      return false;
    });

    this.elLk.toolMore.children('a').bind('click', function () {
      panel.elLk.toolMoreUl.html(panel.elLk.toolsOverflow.clone()).toggle();
      panel.moreShown = true;
      return false;
    });

    this.toolsShown = this.elLk.tools.length;

    this.widths = {
      search: $('.search_holder', this.el).outerWidth(true),
      logo:   logo.outerWidth(true) + logo.offset().left,
      more:   this.elLk.toolMore.outerWidth(true)
    };

    this.setWidth('tools');

    this.elLk.longTabs.show();
    this.setWidth('longTabs');
    this.elLk.longTabs.hide();

    this.resize();

    tabsHolder = null;
    tabs       = null;
    tools      = null;
    logo       = null;
  },

  setWidth: function (type) {
    var panel = this;

    this.widths[type] = 0;
    this.widths[type + 'Array'] = [];

    this.elLk[type].each(function () {
      var w = $(this).outerWidth(true);
      panel.widths[type] += w;
      panel.widths[type + 'Array'].unshift(w);
    });
  },

  resize: function () {
    var panel = this;

    var minWidth    = Ensembl.minWidthEl.outerWidth();
    var windowWidth = $(window).width();
    var threshold   = windowWidth < minWidth ? minWidth : windowWidth;
    var longTabs    = this.widths.longTabs < threshold;
    var shortTools  = this.widths.tools > threshold - this.widths.search - this.widths.logo;
    var holderWidth, i, left;

    if (longTabs !== this.longTabs) {
      if (longTabs) {
        this.elLk.shortTabs.hide();
        this.elLk.longTabs.show();
      } else {
        this.elLk.shortTabs.show();
        this.elLk.longTabs.hide();
      }

      this.longTabs = longTabs;
    }

    if (shortTools) {
      holderWidth = threshold - this.widths.search - this.widths.logo - this.widths.more;
      i           = this.widths.toolsArray.length;
      left        = 0;

      while (i--) {
        if (left + this.widths.toolsArray[i] > holderWidth) {
          this.elLk.toolsOverflow = this.elLk.tools.filter(':gt(' + (this.widths.toolsArray.length - i - 2) + ')');
          break;
        }

        left += this.widths.toolsArray[i];
      }

      this.elLk.toolsUl.width(holderWidth);
      this.elLk.toolMore.css('left', left).show();

      if (this.moreShown) {
        this.elLk.toolMoreUl.html(this.elLk.toolsOverflow.clone());
      }
    } else {
      this.elLk.tools.show();
      this.elLk.toolMore.hide();
      this.elLk.toolsUl.width('auto');
    };
  }
});
<commit_msg>tweaks for dropdowns<commit_after>// $Revision$

Ensembl.Panel.Masthead = Ensembl.Panel.extend({
  constructor: function (id) {
    var minWidth    = Ensembl.minWidthEl.width();
    var windowWidth = $(window).width();

    this.longTabs  = false;
    this.moreShown = false;
    this.zIndex    = 1000;

    this.base(id);

    Ensembl.EventManager.register('windowResize', this, this.resize);
  },

  init: function () {
    var panel = this;

    this.base();

    var tabsHolder = $('.tabs_holder', this.el);
    var tabs       = $('.tabs', tabsHolder);
    var tools      = $('.tools_holder', this.el);
    var logo       = $('.logo_holder', this.el);

    this.elLk.shortTabs  = $('li.short_tab', tabs);
    this.elLk.longTabs   = $('li.long_tab', tabs);
    this.elLk.toolsUl    = $('.tools', tools);
    this.elLk.tools      = $('li', this.elLk.toolsUl);
    this.elLk.toolMore   = $('.more', tools);
    this.elLk.toolMoreUl = $('
').appendTo(this.elLk.toolMore);
    this.elLk.dropdowns  = $('div.dropdown', tabsHolder).bind('click', function () {
      $(this).css('zIndex', panel.zIndex++);
    });

    $('.toggle', tabs).bind('click', function () {
      var tab      = $(this).parent();
      var dropdown = panel.elLk.dropdowns.has('ul.' + this.rel);
      var tabWidth, dropdownWidth;

      if (!dropdown.data('positioning')) {
        tabWidth      = tab.outerWidth();
        dropdownWidth = dropdown.outerWidth();

        if (tabWidth > dropdownWidth) {
          dropdown.width(tabWidth - (dropdownWidth - dropdown.width()));
        }

        dropdown.css('left', tab.position().left).data('positioning', 1);
      }

      dropdown.not(':visible').css('zIndex', panel.zIndex++).end().toggle();
      $(this).html(dropdown.is(':visible') ? '▲' : '▼');

      tab      = null;
      dropdown = null;

      return false;
    });

    this.elLk.toolMore.children('a').bind('click', function () {
      panel.elLk.toolMoreUl.html(panel.elLk.toolsOverflow.clone()).toggle();
      panel.moreShown = true;
      return false;
    });

    this.toolsShown = this.elLk.tools.length;

    this.widths = {
      search: $('.search_holder', this.el).outerWidth(true),
      logo:   logo.outerWidth(true) + logo.offset().left,
      more:   this.elLk.toolMore.outerWidth(true)
    };

    this.setWidth('tools');

    this.elLk.longTabs.show();
    this.setWidth('longTabs');
    this.elLk.longTabs.hide();

    this.resize();

    tabsHolder = null;
    tabs       = null;
    tools      = null;
    logo       = null;
  },

  setWidth: function (type) {
    var panel = this;

    this.widths[type] = 0;
    this.widths[type + 'Array'] = [];

    this.elLk[type].each(function () {
      var w = $(this).outerWidth(true);
      panel.widths[type] += w;
      panel.widths[type + 'Array'].unshift(w);
    });
  },

  resize: function () {
    var panel = this;

    var minWidth    = Ensembl.minWidthEl.outerWidth();
    var windowWidth = $(window).width();
    var threshold   = windowWidth < minWidth ? minWidth : windowWidth;
    var longTabs    = this.widths.longTabs < threshold;
    var shortTools  = this.widths.tools > threshold - this.widths.search - this.widths.logo;
    var holderWidth, i, left;

    if (longTabs !== this.longTabs) {
      if (longTabs) {
        this.elLk.shortTabs.hide();
        this.elLk.longTabs.show();
      } else {
        this.elLk.shortTabs.show();
        this.elLk.longTabs.hide();
      }

      this.longTabs = longTabs;
    }

    if (shortTools) {
      holderWidth = threshold - this.widths.search - this.widths.logo - this.widths.more;
      i           = this.widths.toolsArray.length;
      left        = 0;

      while (i--) {
        if (left + this.widths.toolsArray[i] > holderWidth) {
          this.elLk.toolsOverflow = this.elLk.tools.filter(':gt(' + (this.widths.toolsArray.length - i - 2) + ')');
          break;
        }

        left += this.widths.toolsArray[i];
      }

      this.elLk.toolsUl.width(holderWidth);
      this.elLk.toolMore.css('left', left).show();

      if (this.moreShown) {
        this.elLk.toolMoreUl.html(this.elLk.toolsOverflow.clone());
      }
    } else {
      this.elLk.tools.show();
      this.elLk.toolMore.hide();
      this.elLk.toolsUl.width('auto');
    };
  }
});
<|endoftext|>


<commit_before>// Source code repository: https://github.com/frabcus/code-scraper-in-browser-tool/

var connection
var editor
var editorDirty = false
var editorShare
var output
var status = 'nothing' // reflects what status the buttons show: 'running' or 'nothing'
var changing ='' // for starting/stopping states
var state // various things shared with share.js, including group consideration of the running status
var doneLoad = false

// Set up editor whenever we have a good share.js connection
var load_and_wire_up_editor = function() {
  async.parallel( [
    // Wire up shared document on the connection
    function(callback) {
      console.log("sharing doc...")
      // XXX need a better token in here. API key?
      var docName = 'scraperwiki-' + scraperwiki.box + '-doc005'
      connection.open(docName, 'text', function(error, doc) {
        if (error) {
          console.log("sharing doc error", error)
          scraperwiki.alert("Trouble setting up pair editing!", error, true)
          callback(true, null)
        }
        console.log("...shared doc")
        editorShare = doc
        callback(null, doc)
      })
    },
    // Wire up shared state on the connection
    function(callback) {
      console.log("sharing state...")
      // XXX need a better token in here. API key?
      var docName = 'scraperwiki-' + scraperwiki.box + '-state005'
      connection.open(docName, 'json', function(error, doc) {
        if (error) {
          console.log("sharing state error", error)
          scraperwiki.alert("Trouble setting up pair state!", error, true)
          callback(true, null)
        }
        state = doc
        // Start to share status
        if (state.created) {
          console.log("first time this state connection has been used, initialising")
          state.submitOp([{p:[],od:null,oi:{status:'nothing'}}])
        }
        state.on('change', function (op) {
          shared_state_update(op)
        })
        console.log("...shared state")
        callback(null, doc)
      })
    }
  ], function(err, results) {
    if (err) {
      scraperwiki.alert("Gave up setup of pair stuff!", err, true)
      return
    }

    // Load code from file
    console.log("loading...")
    scraperwiki.exec('mkdir -p code && touch code/scraper && cat code/scraper && echo -n swinternalGOTCODEOFSCRAPER', function(data) {
      if (data.indexOf("swinternalGOTCODEOFSCRAPER") == -1) {
        scraperwiki.alert("Trouble loading code!", data, true)
        return
      }
      data = data.replace("swinternalGOTCODEOFSCRAPER", "")

      // If nothing there, set some default content to get people going
      if (data.match(/^\s*$/)) {
        data = "#!/usr/bin/python\n\nimport scraperwiki\n\n"
      }
      console.log("...loaded")

      // Connect editor window to the doc
      editorShare.attach_ace(editor)
      set_editor_mode(data)
      editor.setValue(data) // XXX this overrides what is in filesystem on top of what is in sharej
      editor.moveCursorTo(0, 0)
      editor.focus()
      editor.setReadOnly(false)
      doneLoad = true

      update_dirty(false)
      editor.on('change', function() {
        update_dirty(true)
      })

      poll_output()
    }, handle_exec_error)
  });
}

// Handle error
var handle_exec_error = function(jqXHR, textStatus, errorThrown) {
    console.log("got an error:", errorThrown, jqXHR, textStatus)
    // Handle special case of the browser not being connected to the net
    // http://stackoverflow.com/questions/10026204/dialog-box-if-there-is-no-internet-connection-using-jquery-or-ajax
    if (jqXHR.status == 0) {
      // Wait half a second before error - otherwise they show on page refresh,
      // we only want to show if the browser is disconneted from the network.
      setTimeout(function() {
        clear_alerts()
        scraperwiki.alert("No connection to Internet!", "", false)
      } , 500)
    } else {
      scraperwiki.alert(errorThrown, $(jqXHR.responseText).text(), "error")
    }
}

// Display whether we have unsaved edits
var update_dirty = function(value) {
  clearTimeout(save_code)
  editorDirty = value
  if (editorDirty) {
    // Wait three seconds and then save. If we get another change
    // in those three seconds, reset that timer to avoid excess saves.
    $("#saved").text("Saving...")
    setTimeout(save_code, 3000)
  } else {
    $("#saved").text("All changes saved")
  }
}

// Prevent navigation away if not saved
// XXX this doesn't seem to work for close events in chrome in the frame
$(window).on('beforeunload', function() {
  if (editorDirty) {
    return "You've made changes that haven't been saved yet."
  }
})

// Work out language we're in from the shebang line
var set_editor_mode = function(code) {
  var first = code.split("\n")[0]
  if (first.substr(0,2) != "#!") {
    scraperwiki.alert("Specify language in the first line!", "For example, put #!/usr/bin/ruby, #!/usr/bin/R or #!/usr/bin/python.", false)
    return false
  }
  // Please add more as you need them and send us a pull request!
  if (first.indexOf("python") != -1) {
    editor.getSession().setMode("ace/mode/python")
  } else if (first.indexOf("ruby") != -1) {
    editor.getSession().setMode("ace/mode/ruby")
  } else if (first.indexOf("perl") != -1) {
    editor.getSession().setMode("ace/mode/perl")
  } else if (first.indexOf("node") != -1) {
    editor.getSession().setMode("ace/mode/javascript")
  } else if (first.indexOf("coffee") != -1) {
    editor.getSession().setMode("ace/mode/coffee")
  } else if (first.indexOf("clojure") != -1) {
    editor.getSession().setMode("ace/mode/clojure")
  } else if (first.indexOf("tcc") != -1) {
    editor.getSession().setMode("ace/mode/c_cpp")
  } else if (first.indexOf("R") != -1) {
    editor.getSession().setMode("ace/mode/r")
  } else if (first.indexOf("sh") != -1) {
    editor.getSession().setMode("ace/mode/sh")
  } else {
    editor.getSession().setMode("ace/mode/text")
  }
  return true
}

// Got a new state over ShareJS (from ourselves or remote clients)
var shared_state_update = function(op) {
  console.log("shared_state_update", state.snapshot)

  // Respond to the status change
  var new_status = state.snapshot.status
  if (new_status != status) {
    console.log("status change", status, "===>", new_status)
    if (new_status == "running") {
      poll_output()
    }
    status = new_status
    changing = ""
  }
  update_display_from_status(new_status)
}

// Show status in buttons - we have this as we can call it directly
// to make the run button seem more responsive
var update_display_from_status = function(use_status) {
  $("#run").removeClass("btn-primary").removeClass("btn-danger").removeClass("btn-warning").removeClass("btn-success")
  if (changing == "starting") {
    $("#run").text("Starting...").addClass("btn-warning")
  } else if (changing == "stopping") {
    $("#run").text("Stopping...").addClass("btn-danger")
  } else if (use_status == "running") {
    $("#run").text("Running...").addClass("btn-success")
  } else if (use_status == "nothing") {
    $("#run").text("Run!").addClass("btn-primary")
  }
}

// Show/hide things according to current state
var set_status = function(new_status) {
  if (new_status != "running" && new_status != "nothing") {
    scraperwiki.alert("Unknown new status!", new_status, true)
    return
  }

  // Tell other ShareJS clients the status has changed
  try {
    state.submitOp( {p:['status'],od:status,oi:new_status}) // XXX state.status for od?
  } catch (e) {
    scraperwiki.alert("Error saving to ShareJS!", e, true)
  }
}

// Console get more output
var poll_output = function() {
  scraperwiki.exec("./tool/enrunerate", function(text) {
    console.log("enrunerate:", text, "len:", text.length)
    set_status(text)

    // we poll one last time either way to be sure we get end of output...
    var again = false
    if (text == "running") {
      // ... but if script is still "running" we'll trigger the timer to do it again
      again = true
    }
    scraperwiki.exec("cat logs/out", function(text) {
      // XXX detect no file a better way
      if (text != "cat: logs/out: No such file or directory\n") {
        output.setValue(text)
      }
      output.clearSelection()
      if (again) {
        setTimeout(poll_output, 10)
      }
    }, handle_exec_error)
  }, handle_exec_error)
}

// Clear any errors
var clear_alerts = function() {
  $(".alert").remove()
}

// Save the code - optionally takes text of extra commands to also
// in the same "exec" and a callback to run when done
var save_code = function(callback) {
  clearTimeout(save_code) // stop any already scheduled timed saves
  var code = editor.getValue()
  if (code.length == 0 || code.charAt(code.length - 1) != "\n") {
    code += "\n" // we need a separator \n at the end of the file for the ENDOFSCRAPER heredoc below
  }
  var cmd = "cat >code/scraper.new.$$ <<ENDOFSCRAPER &&\n" + code + "ENDOFSCRAPER\n"
  cmd = cmd + "chmod a+x code/scraper.new.$$ && mv code/scraper.new.$$ code/scraper"
  scraperwiki.exec(cmd, function(text) {
    if (text != "") {
        scraperwiki.alert("Trouble saving code!", text, true)
        return
    }

    // Check actual content against saved - in case there was a change while we executed
    if (editor.getValue() == code) {
      console.log("Saved fine without interference")
      update_dirty(false)
    } else {
      console.log("Ooops, it got dirty while saving")
      update_dirty(true)
    }

    if (callback) {
      callback(text)
    }
  }, handle_exec_error)
}

// When the "documentation" button is pressed
var do_docs = function() {
  window.open("https://scraperwiki.com/docs/", "_blank")
}

// When the "bugs" button is pressed
var do_bugs = function() {
  window.open("https://github.com/frabcus/code-scraper-in-browser-tool/issues", "_blank")
}

// When the "keys" button is pressed
var do_keys = function() {
  window.open("https://github.com/ajaxorg/ace/wiki/Default-Keyboard-Shortcuts", "_blank")
}

// When the "run" button is pressed
var do_run = function() {
  // force a check that we have a shebang (#!) line
  clear_alerts()
  var code = editor.getValue()
  if (!set_editor_mode(code)) {
    return
  }

  // if it is already running, stop instead
  if (status == "running") {
    // make button show what we're doing
    changing = "stopping"
    update_display_from_status(status)

    scraperwiki.exec("./tool/enrunerate stop", function(text) {
      console.log("enrunerate stop:", text)
      // And tell all clients that we're now not running code (if we're not!)
      set_status(text)
    }, handle_exec_error)
    return
  }

  // to make button feel responsibe, temporarily show the wrong status
  // (until next operation makes it right)
  changing = "starting"
  update_display_from_status(status)
  output.setValue("")

  // Save code
  save_code(function (text) {
    // Then run it
    scraperwiki.exec("./tool/enrunerate run", function(text) {
      console.log("enrunerate run:", text)
      // And tell all clients that we're now running code (if we are!)
      set_status(text)
    }, handle_exec_error)
  })
}

// Main entry point
$(document).ready(function() {
  settings = scraperwiki.readSettings()
  $('#apikey').val(settings.source.apikey)

  // Create editor window, read only until it is ready
  editor = ace.edit("editor")
  editor.getSession().setUseSoftTabs(true)
  editor.setTheme("ace/theme/monokai")
  editor.setReadOnly(true)

  // Connect to sharejs server
  console.log("connecting...")
  connection = new sharejs.Connection('http://seagrass.goatchurch.org.uk/sharejs/channel')
  connection.on("error", function(e) {
      console.log("sharejs connection: error")
      clear_alerts()
      scraperwiki.alert("Editor is offline!", e, false)
      doneLoad = false
      editor.setReadOnly(true)
  })
  connection.on("ok", function(e) {
      console.log("sharejs connection: ok")
      clear_alerts()
      load_and_wire_up_editor()
      if (doneLoad) {
        editor.setReadOnly(false)
      }
  })
  console.log("...connected")

  // Create the console output window
  output = ace.edit("output")
  output.setTheme("ace/theme/monokai")
  // ... we use /bin/sh syntax highlighting, the only other at all
  // credible option for such varied output is plain text, which is dull.
  output.getSession().setMode("ace/mode/sh")
  output.setReadOnly(true)

  // Bind all the buttons to do something
  $('#docs').on('click', do_docs)
  $('#bugs').on('click', do_bugs)
  $('#keys').on('click', do_keys)
  $('#run').on('click', do_run)
  $(document).bind('keydown', 'ctrl+r', do_run)
})

<commit_msg>Use clearTimeout right<commit_after>// Source code repository: https://github.com/frabcus/code-scraper-in-browser-tool/

var connection
var editor
var editorDirty = false
var editorShare
var output
var status = 'nothing' // reflects what status the buttons show: 'running' or 'nothing'
var changing ='' // for starting/stopping states
var state // various things shared with share.js, including group consideration of the running status
var doneLoad = false // we've initialised the editor, so can autosave to disk now
var saveTimeout

// Set up editor whenever we have a good share.js connection
var load_and_wire_up_editor = function() {
  async.parallel( [
    // Wire up shared document on the connection
    function(callback) {
      console.log("sharing doc...")
      // XXX need a better token in here. API key?
      var docName = 'scraperwiki-' + scraperwiki.box + '-doc005'
      connection.open(docName, 'text', function(error, doc) {
        if (error) {
          console.log("sharing doc error", error)
          scraperwiki.alert("Trouble setting up pair editing!", error, true)
          callback(true, null)
        }
        console.log("...shared doc")
        editorShare = doc
        callback(null, doc)
      })
    },
    // Wire up shared state on the connection
    function(callback) {
      console.log("sharing state...")
      // XXX need a better token in here. API key?
      var docName = 'scraperwiki-' + scraperwiki.box + '-state005'
      connection.open(docName, 'json', function(error, doc) {
        if (error) {
          console.log("sharing state error", error)
          scraperwiki.alert("Trouble setting up pair state!", error, true)
          callback(true, null)
        }
        state = doc
        // Start to share status
        if (state.created) {
          console.log("first time this state connection has been used, initialising")
          state.submitOp([{p:[],od:null,oi:{status:'nothing'}}])
        }
        state.on('change', function (op) {
          shared_state_update(op)
        })
        console.log("...shared state")
        callback(null, doc)
      })
    }
  ], function(err, results) {
    if (err) {
      scraperwiki.alert("Gave up setup of pair stuff!", err, true)
      return
    }

    // Load code from file
    console.log("loading...")
    scraperwiki.exec('mkdir -p code && touch code/scraper && cat code/scraper && echo -n swinternalGOTCODEOFSCRAPER', function(data) {
      if (data.indexOf("swinternalGOTCODEOFSCRAPER") == -1) {
        scraperwiki.alert("Trouble loading code!", data, true)
        return
      }
      data = data.replace("swinternalGOTCODEOFSCRAPER", "")

      // If nothing there, set some default content to get people going
      if (data.match(/^\s*$/)) {
        data = "#!/usr/bin/python\n\nimport scraperwiki\n\n"
      }
      console.log("...loaded")

      // Connect editor window to the doc
      editorShare.attach_ace(editor)
      set_editor_mode(data)
      editor.setValue(data) // XXX this overrides what is in filesystem on top of what is in sharejs
      editor.moveCursorTo(0, 0)
      editor.focus()
      editor.setReadOnly(false)
      doneLoad = true

      update_dirty(false)

      poll_output()
    }, handle_exec_error)
  });
}

// Handle error
var handle_exec_error = function(jqXHR, textStatus, errorThrown) {
    console.log("got an error:", errorThrown, jqXHR, textStatus)
    // Handle special case of the browser not being connected to the net
    // http://stackoverflow.com/questions/10026204/dialog-box-if-there-is-no-internet-connection-using-jquery-or-ajax
    if (jqXHR.status == 0) {
      // Wait half a second before error - otherwise they show on page refresh,
      // we only want to show if the browser is disconneted from the network.
      setTimeout(function() {
        clear_alerts()
        scraperwiki.alert("No connection to Internet!", "", false)
      } , 500)
    } else {
      scraperwiki.alert(errorThrown, $(jqXHR.responseText).text(), "error")
    }
}

// Display whether we have unsaved edits
var update_dirty = function(value) {
  clearTimeout(saveTimeout)
  editorDirty = value
  if (editorDirty) {
    // Wait three seconds and then save. If we get another change
    // in those three seconds, reset that timer to avoid excess saves.
    $("#saved").text("Saving...")
    //console.log("setTimeout save_code, 3000")
    saveTimeout = setTimeout(save_code, 3000)
  } else {
    $("#saved").text("All changes saved")
  }
}

// Prevent navigation away if not saved
// XXX this doesn't seem to work for close events in chrome in the frame
$(window).on('beforeunload', function() {
  if (editorDirty) {
    return "You've made changes that haven't been saved yet."
  }
})

// Work out language we're in from the shebang line
var set_editor_mode = function(code) {
  var first = code.split("\n")[0]
  if (first.substr(0,2) != "#!") {
    scraperwiki.alert("Specify language in the first line!", "For example, put #!/usr/bin/ruby, #!/usr/bin/R or #!/usr/bin/python.", false)
    return false
  }
  // Please add more as you need them and send us a pull request!
  if (first.indexOf("python") != -1) {
    editor.getSession().setMode("ace/mode/python")
  } else if (first.indexOf("ruby") != -1) {
    editor.getSession().setMode("ace/mode/ruby")
  } else if (first.indexOf("perl") != -1) {
    editor.getSession().setMode("ace/mode/perl")
  } else if (first.indexOf("node") != -1) {
    editor.getSession().setMode("ace/mode/javascript")
  } else if (first.indexOf("coffee") != -1) {
    editor.getSession().setMode("ace/mode/coffee")
  } else if (first.indexOf("clojure") != -1) {
    editor.getSession().setMode("ace/mode/clojure")
  } else if (first.indexOf("tcc") != -1) {
    editor.getSession().setMode("ace/mode/c_cpp")
  } else if (first.indexOf("R") != -1) {
    editor.getSession().setMode("ace/mode/r")
  } else if (first.indexOf("sh") != -1) {
    editor.getSession().setMode("ace/mode/sh")
  } else {
    editor.getSession().setMode("ace/mode/text")
  }
  return true
}

// Got a new state over ShareJS (from ourselves or remote clients)
var shared_state_update = function(op) {
  console.log("shared_state_update", state.snapshot)

  // Respond to the status change
  var new_status = state.snapshot.status
  if (new_status != status) {
    console.log("status change", status, "===>", new_status)
    if (new_status == "running") {
      poll_output()
    }
    status = new_status
    changing = ""
  }
  update_display_from_status(new_status)
}

// Show status in buttons - we have this as we can call it directly
// to make the run button seem more responsive
var update_display_from_status = function(use_status) {
  $("#run").removeClass("btn-primary").removeClass("btn-danger").removeClass("btn-warning").removeClass("btn-success")
  if (changing == "starting") {
    $("#run").text("Starting...").addClass("btn-warning")
  } else if (changing == "stopping") {
    $("#run").text("Stopping...").addClass("btn-danger")
  } else if (use_status == "running") {
    $("#run").text("Running...").addClass("btn-success")
  } else if (use_status == "nothing") {
    $("#run").text("Run!").addClass("btn-primary")
  }
}

// Show/hide things according to current state
var set_status = function(new_status) {
  if (new_status != "running" && new_status != "nothing") {
    scraperwiki.alert("Unknown new status!", new_status, true)
    return
  }

  // Tell other ShareJS clients the status has changed
  try {
    state.submitOp( {p:['status'],od:status,oi:new_status}) // XXX state.status for od?
  } catch (e) {
    scraperwiki.alert("Error saving to ShareJS!", e, true)
  }
}

// Console get more output
var poll_output = function() {
  scraperwiki.exec("./tool/enrunerate", function(text) {
    console.log("enrunerate:", text, "len:", text.length)
    set_status(text)

    // we poll one last time either way to be sure we get end of output...
    var again = false
    if (text == "running") {
      // ... but if script is still "running" we'll trigger the timer to do it again
      again = true
    }
    scraperwiki.exec("cat logs/out", function(text) {
      // XXX detect no file a better way
      if (text != "cat: logs/out: No such file or directory\n") {
        output.setValue(text)
      }
      output.clearSelection()
      if (again) {
        setTimeout(poll_output, 10)
      }
    }, handle_exec_error)
  }, handle_exec_error)
}

// Clear any errors
var clear_alerts = function() {
  $(".alert").remove()
}

// Save the code - optionally takes text of extra commands to also
// in the same "exec" and a callback to run when done
var save_code = function(callback) {
  clearTimeout(saveTimeout) // stop any already scheduled timed saves

  // don't overwrite disk file with blankness
  if (!doneLoad) {
    return
  }

  console.log("save_code...")
  var code = editor.getValue()
  if (code.length == 0 || code.charAt(code.length - 1) != "\n") {
    code += "\n" // we need a separator \n at the end of the file for the ENDOFSCRAPER heredoc below
  }
  var cmd = "cat >code/scraper.new.$$ <<ENDOFSCRAPER &&\n" + code + "ENDOFSCRAPER\n"
  cmd = cmd + "chmod a+x code/scraper.new.$$ && mv code/scraper.new.$$ code/scraper"
  scraperwiki.exec(cmd, function(text) {
    if (text != "") {
        scraperwiki.alert("Trouble saving code!", text, true)
        return
    }

    // Check actual content against saved - in case there was a change while we executed
    if (editor.getValue() == code) {
      console.log("Saved fine without interference")
      update_dirty(false)
    } else {
      console.log("Ooops, it got dirty while saving")
      update_dirty(true)
    }

    if (callback) {
      callback(text)
    }
  }, handle_exec_error)
}

// When the "documentation" button is pressed
var do_docs = function() {
  window.open("https://scraperwiki.com/docs/", "_blank")
}

// When the "bugs" button is pressed
var do_bugs = function() {
  window.open("https://github.com/frabcus/code-scraper-in-browser-tool/issues", "_blank")
}

// When the "keys" button is pressed
var do_keys = function() {
  window.open("https://github.com/ajaxorg/ace/wiki/Default-Keyboard-Shortcuts", "_blank")
}

// When the "run" button is pressed
var do_run = function() {
  // force a check that we have a shebang (#!) line
  clear_alerts()
  var code = editor.getValue()
  if (!set_editor_mode(code)) {
    return
  }

  // if it is already running, stop instead
  if (status == "running") {
    // make button show what we're doing
    changing = "stopping"
    update_display_from_status(status)

    scraperwiki.exec("./tool/enrunerate stop", function(text) {
      console.log("enrunerate stop:", text)
      // And tell all clients that we're now not running code (if we're not!)
      set_status(text)
    }, handle_exec_error)
    return
  }

  // to make button feel responsibe, temporarily show the wrong status
  // (until next operation makes it right)
  changing = "starting"
  update_display_from_status(status)
  output.setValue("")

  // Save code
  save_code(function (text) {
    // Then run it
    scraperwiki.exec("./tool/enrunerate run", function(text) {
      console.log("enrunerate run:", text)
      // And tell all clients that we're now running code (if we are!)
      set_status(text)
    }, handle_exec_error)
  })
}

// Main entry point
$(document).ready(function() {
  settings = scraperwiki.readSettings()
  $('#apikey').val(settings.source.apikey)

  // Create editor window, read only until it is ready
  editor = ace.edit("editor")
  editor.getSession().setUseSoftTabs(true)
  editor.setTheme("ace/theme/monokai")
  editor.setReadOnly(true)
  editor.on('change', function() {
    if (doneLoad) {
      update_dirty(true)
    }
  })

  // Connect to sharejs server
  console.log("connecting...")
  connection = new sharejs.Connection('http://seagrass.goatchurch.org.uk/sharejs/channel')
  connection.on("error", function(e) {
      console.log("sharejs connection: error")
      clear_alerts()
      scraperwiki.alert("Editor is offline!", e, false)
      doneLoad = false
      editor.setReadOnly(true)
  })
  connection.on("ok", function(e) {
      console.log("sharejs connection: ok")
      clear_alerts()
      load_and_wire_up_editor()
      if (doneLoad) {
        editor.setReadOnly(false)
      }
  })
  console.log("...connected")

  // Create the console output window
  output = ace.edit("output")
  output.setTheme("ace/theme/monokai")
  // ... we use /bin/sh syntax highlighting, the only other at all
  // credible option for such varied output is plain text, which is dull.
  output.getSession().setMode("ace/mode/sh")
  output.setReadOnly(true)

  // Bind all the buttons to do something
  $('#docs').on('click', do_docs)
  $('#bugs').on('click', do_bugs)
  $('#keys').on('click', do_keys)
  $('#run').on('click', do_run)
  $(document).bind('keydown', 'ctrl+r', do_run)
})

<|endoftext|>