<commit_before>/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */(function() {'use strict';var l=this;function p(b,e){var a=b.split("."),c=l;!(a[0]in c)&&c.execScript&&c.execScript("var "+a[0]);for(var d;a.length&&(d=a.shift());)!a.length&&void 0!==e?c[d]=e:c=c[d]?c[d]:c[d]={}};var q="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array&&"undefined"!==typeof DataView;function t(b){var e=b.length,a=0,c=Number.POSITIVE_INFINITY,d,f,g,h,k,m,r,n,s,J;for(n=0;n<e;++n)b[n]>a&&(a=b[n]),b[n]<c&&(c=b[n]);d=1<<a;f=new (q?Uint32Array:Array)(d);g=1;h=0;for(k=2;g<=a;){for(n=0;n<e;++n)if(b[n]===g){m=0;r=h;for(s=0;s<g;++s)m=m<<1|r&1,r>>=1;J=g<<16|n;for(s=m;s<d;s+=k)f[s]=J;++h}++g;h<<=1;k<<=1}return[f,a,c]};function u(b,e){this.g=[];this.h=32768;this.c=this.f=this.d=this.k=0;this.input=q?new Uint8Array(b):b;this.l=!1;this.i=v;this.q=!1;if(e||!(e={}))e.index&&(this.d=e.index),e.bufferSize&&(this.h=e.bufferSize),e.bufferType&&(this.i=e.bufferType),e.resize&&(this.q=e.resize);switch(this.i){case w:this.a=32768;this.b=new (q?Uint8Array:Array)(32768+this.h+258);break;case v:this.a=0;this.b=new (q?Uint8Array:Array)(this.h);this.e=this.v;this.m=this.s;this.j=this.t;break;default:throw Error("invalid inflate mode");
}}var w=0,v=1;
u.prototype.u=function(){for(;!this.l;){var b=x(this,3);b&1&&(this.l=!0);b>>>=1;switch(b){case 0:var e=this.input,a=this.d,c=this.b,d=this.a,f=e.length,g=void 0,h=void 0,k=c.length,m=void 0;this.c=this.f=0;if(a+1>=f)throw Error("invalid uncompressed block header: LEN");g=e[a++]|e[a++]<<8;if(a+1>=f)throw Error("invalid uncompressed block header: NLEN");h=e[a++]|e[a++]<<8;if(g===~h)throw Error("invalid uncompressed block header: length verify");if(a+g>e.length)throw Error("input buffer is broken");switch(this.i){case w:for(;d+
g>c.length;){m=k-d;g-=m;if(q)c.set(e.subarray(a,a+m),d),d+=m,a+=m;else for(;m--;)c[d++]=e[a++];this.a=d;c=this.e();d=this.a}break;case v:for(;d+g>c.length;)c=this.e({o:2});break;default:throw Error("invalid inflate mode");}if(q)c.set(e.subarray(a,a+g),d),d+=g,a+=g;else for(;g--;)c[d++]=e[a++];this.d=a;this.a=d;this.b=c;break;case 1:this.j(y,z);break;case 2:A(this);break;default:throw Error("unknown BTYPE: "+b);}}return this.m()};
var B=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],C=q?new Uint16Array(B):B,D=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],E=q?new Uint16Array(D):D,F=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],G=q?new Uint8Array(F):F,H=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],I=q?new Uint16Array(H):H,K=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,
13],L=q?new Uint8Array(K):K,M=new (q?Uint8Array:Array)(288),N,O;N=0;for(O=M.length;N<O;++N)M[N]=143>=N?8:255>=N?9:279>=N?7:8;var y=t(M),P=new (q?Uint8Array:Array)(30),Q,R;Q=0;for(R=P.length;Q<R;++Q)P[Q]=5;var z=t(P);function x(b,e){for(var a=b.f,c=b.c,d=b.input,f=b.d,g=d.length,h;c<e;){if(f>=g)throw Error("input buffer is broken");a|=d[f++]<<c;c+=8}h=a&(1<<e)-1;b.f=a>>>e;b.c=c-e;b.d=f;return h}
function S(b,e){for(var a=b.f,c=b.c,d=b.input,f=b.d,g=d.length,h=e[0],k=e[1],m,r;c<k&&!(f>=g);)a|=d[f++]<<c,c+=8;m=h[a&(1<<k)-1];r=m>>>16;b.f=a>>r;b.c=c-r;b.d=f;return m&65535}
function A(b){function e(a,b,c){var e,d=this.p,f,g;for(g=0;g<a;)switch(e=S(this,b),e){case 16:for(f=3+x(this,2);f--;)c[g++]=d;break;case 17:for(f=3+x(this,3);f--;)c[g++]=0;d=0;break;case 18:for(f=11+x(this,7);f--;)c[g++]=0;d=0;break;default:d=c[g++]=e}this.p=d;return c}var a=x(b,5)+257,c=x(b,5)+1,d=x(b,4)+4,f=new (q?Uint8Array:Array)(C.length),g,h,k,m;for(m=0;m<d;++m)f[C[m]]=x(b,3);if(!q){m=d;for(d=f.length;m<d;++m)f[C[m]]=0}g=t(f);h=new (q?Uint8Array:Array)(a);k=new (q?Uint8Array:Array)(c);b.p=0;
b.j(t(e.call(b,a,g,h)),t(e.call(b,c,g,k)))}u.prototype.j=function(b,e){var a=this.b,c=this.a;this.n=b;for(var d=a.length-258,f,g,h,k;256!==(f=S(this,b));)if(256>f)c>=d&&(this.a=c,a=this.e(),c=this.a),a[c++]=f;else{g=f-257;k=E[g];0<G[g]&&(k+=x(this,G[g]));f=S(this,e);h=I[f];0<L[f]&&(h+=x(this,L[f]));c>=d&&(this.a=c,a=this.e(),c=this.a);for(;k--;)a[c]=a[c++-h]}for(;8<=this.c;)this.c-=8,this.d--;this.a=c};
u.prototype.t=function(b,e){var a=this.b,c=this.a;this.n=b;for(var d=a.length,f,g,h,k;256!==(f=S(this,b));)if(256>f)c>=d&&(a=this.e(),d=a.length),a[c++]=f;else{g=f-257;k=E[g];0<G[g]&&(k+=x(this,G[g]));f=S(this,e);h=I[f];0<L[f]&&(h+=x(this,L[f]));c+k>d&&(a=this.e(),d=a.length);for(;k--;)a[c]=a[c++-h]}for(;8<=this.c;)this.c-=8,this.d--;this.a=c};
u.prototype.e=function(){var b=new (q?Uint8Array:Array)(this.a-32768),e=this.a-32768,a,c,d=this.b;if(q)b.set(d.subarray(32768,b.length));else{a=0;for(c=b.length;a<c;++a)b[a]=d[a+32768]}this.g.push(b);this.k+=b.length;if(q)d.set(d.subarray(e,e+32768));else for(a=0;32768>a;++a)d[a]=d[e+a];this.a=32768;return d};
u.prototype.v=function(b){var e,a=this.input.length/this.d+1|0,c,d,f,g=this.input,h=this.b;b&&("number"===typeof b.o&&(a=b.o),"number"===typeof b.r&&(a+=b.r));2>a?(c=(g.length-this.d)/this.n[2],f=258*(c/2)|0,d=f<h.length?h.length+f:h.length<<1):d=h.length*a;q?(e=new Uint8Array(d),e.set(h)):e=h;return this.b=e};
u.prototype.m=function(){var b=0,e=this.b,a=this.g,c,d=new (q?Uint8Array:Array)(this.k+(this.a-32768)),f,g,h,k;if(0===a.length)return q?this.b.subarray(32768,this.a):this.b.slice(32768,this.a);f=0;for(g=a.length;f<g;++f){c=a[f];h=0;for(k=c.length;h<k;++h)d[b++]=c[h]}f=32768;for(g=this.a;f<g;++f)d[b++]=e[f];this.g=[];return this.buffer=d};
u.prototype.s=function(){var b,e=this.a;q?this.q?(b=new Uint8Array(e),b.set(this.b.subarray(0,e))):b=this.b.subarray(0,e):(this.b.length>e&&(this.b.length=e),b=this.b);return this.buffer=b};p("Zlib.RawInflate",u);p("Zlib.RawInflate.prototype.decompress",u.prototype.u);var T={ADAPTIVE:v,BLOCK:w},U,V,W,X;if(Object.keys)U=Object.keys(T);else for(V in U=[],W=0,T)U[W++]=V;W=0;for(X=U.length;W<X;++W)V=U[W],p("Zlib.RawInflate.BufferType."+V,T[V]);}).call(this); //@ sourceMappingURL=rawinflate.min.js.map
<commit_msg>rawinflate库在ios打包失败的问题<commit_after>/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */(function() {var l=this;
    function p(b, e) {
        var a = b.split("."),c = l;
        for(var i=0; i<a.length; i++){
            var item = a[i];
            if(!c[item]){
                c[item] = {};
            }
            if(i==a.length-1){
                c[item] = e;
            }
            c = c[item];
        }
    };

    var q="undefined"!==typeof Uint8Array&&"undefined"!==typeof Uint16Array&&"undefined"!==typeof Uint32Array&&"undefined"!==typeof DataView;function t(b){var e=b.length,a=0,c=Number.POSITIVE_INFINITY,d,f,g,h,k,m,r,n,s,J;for(n=0;n<e;++n)b[n]>a&&(a=b[n]),b[n]<c&&(c=b[n]);d=1<<a;f=new (q?Uint32Array:Array)(d);g=1;h=0;for(k=2;g<=a;){for(n=0;n<e;++n)if(b[n]===g){m=0;r=h;for(s=0;s<g;++s)m=m<<1|r&1,r>>=1;J=g<<16|n;for(s=m;s<d;s+=k)f[s]=J;++h}++g;h<<=1;k<<=1}return[f,a,c]};function u(b,e){this.g=[];this.h=32768;this.c=this.f=this.d=this.k=0;this.input=q?new Uint8Array(b):b;this.l=!1;this.i=v;this.q=!1;if(e||!(e={}))e.index&&(this.d=e.index),e.bufferSize&&(this.h=e.bufferSize),e.bufferType&&(this.i=e.bufferType),e.resize&&(this.q=e.resize);switch(this.i){case w:this.a=32768;this.b=new (q?Uint8Array:Array)(32768+this.h+258);break;case v:this.a=0;this.b=new (q?Uint8Array:Array)(this.h);this.e=this.v;this.m=this.s;this.j=this.t;break;default:throw Error("invalid inflate mode");
    }}var w=0,v=1;
    u.prototype.u=function(){for(;!this.l;){var b=x(this,3);b&1&&(this.l=!0);b>>>=1;switch(b){case 0:var e=this.input,a=this.d,c=this.b,d=this.a,f=e.length,g=void 0,h=void 0,k=c.length,m=void 0;this.c=this.f=0;if(a+1>=f)throw Error("invalid uncompressed block header: LEN");g=e[a++]|e[a++]<<8;if(a+1>=f)throw Error("invalid uncompressed block header: NLEN");h=e[a++]|e[a++]<<8;if(g===~h)throw Error("invalid uncompressed block header: length verify");if(a+g>e.length)throw Error("input buffer is broken");switch(this.i){case w:for(;d+
                                                                                g>c.length;){m=k-d;g-=m;if(q)c.set(e.subarray(a,a+m),d),d+=m,a+=m;else for(;m--;)c[d++]=e[a++];this.a=d;c=this.e();d=this.a}break;case v:for(;d+g>c.length;)c=this.e({o:2});break;default:throw Error("invalid inflate mode");}if(q)c.set(e.subarray(a,a+g),d),d+=g,a+=g;else for(;g--;)c[d++]=e[a++];this.d=a;this.a=d;this.b=c;break;case 1:this.j(y,z);break;case 2:A(this);break;default:throw Error("unknown BTYPE: "+b);}}return this.m()};
    var B=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],C=q?new Uint16Array(B):B,D=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],E=q?new Uint16Array(D):D,F=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],G=q?new Uint8Array(F):F,H=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],I=q?new Uint16Array(H):H,K=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,
        13],L=q?new Uint8Array(K):K,M=new (q?Uint8Array:Array)(288),N,O;N=0;for(O=M.length;N<O;++N)M[N]=143>=N?8:255>=N?9:279>=N?7:8;var y=t(M),P=new (q?Uint8Array:Array)(30),Q,R;Q=0;for(R=P.length;Q<R;++Q)P[Q]=5;var z=t(P);function x(b,e){for(var a=b.f,c=b.c,d=b.input,f=b.d,g=d.length,h;c<e;){if(f>=g)throw Error("input buffer is broken");a|=d[f++]<<c;c+=8}h=a&(1<<e)-1;b.f=a>>>e;b.c=c-e;b.d=f;return h}
    function S(b,e){for(var a=b.f,c=b.c,d=b.input,f=b.d,g=d.length,h=e[0],k=e[1],m,r;c<k&&!(f>=g);)a|=d[f++]<<c,c+=8;m=h[a&(1<<k)-1];r=m>>>16;b.f=a>>r;b.c=c-r;b.d=f;return m&65535}
    function A(b){function e(a,b,c){var e,d=this.p,f,g;for(g=0;g<a;)switch(e=S(this,b),e){case 16:for(f=3+x(this,2);f--;)c[g++]=d;break;case 17:for(f=3+x(this,3);f--;)c[g++]=0;d=0;break;case 18:for(f=11+x(this,7);f--;)c[g++]=0;d=0;break;default:d=c[g++]=e}this.p=d;return c}var a=x(b,5)+257,c=x(b,5)+1,d=x(b,4)+4,f=new (q?Uint8Array:Array)(C.length),g,h,k,m;for(m=0;m<d;++m)f[C[m]]=x(b,3);if(!q){m=d;for(d=f.length;m<d;++m)f[C[m]]=0}g=t(f);h=new (q?Uint8Array:Array)(a);k=new (q?Uint8Array:Array)(c);b.p=0;
        b.j(t(e.call(b,a,g,h)),t(e.call(b,c,g,k)))}u.prototype.j=function(b,e){var a=this.b,c=this.a;this.n=b;for(var d=a.length-258,f,g,h,k;256!==(f=S(this,b));)if(256>f)c>=d&&(this.a=c,a=this.e(),c=this.a),a[c++]=f;else{g=f-257;k=E[g];0<G[g]&&(k+=x(this,G[g]));f=S(this,e);h=I[f];0<L[f]&&(h+=x(this,L[f]));c>=d&&(this.a=c,a=this.e(),c=this.a);for(;k--;)a[c]=a[c++-h]}for(;8<=this.c;)this.c-=8,this.d--;this.a=c};
    u.prototype.t=function(b,e){var a=this.b,c=this.a;this.n=b;for(var d=a.length,f,g,h,k;256!==(f=S(this,b));)if(256>f)c>=d&&(a=this.e(),d=a.length),a[c++]=f;else{g=f-257;k=E[g];0<G[g]&&(k+=x(this,G[g]));f=S(this,e);h=I[f];0<L[f]&&(h+=x(this,L[f]));c+k>d&&(a=this.e(),d=a.length);for(;k--;)a[c]=a[c++-h]}for(;8<=this.c;)this.c-=8,this.d--;this.a=c};
    u.prototype.e=function(){var b=new (q?Uint8Array:Array)(this.a-32768),e=this.a-32768,a,c,d=this.b;if(q)b.set(d.subarray(32768,b.length));else{a=0;for(c=b.length;a<c;++a)b[a]=d[a+32768]}this.g.push(b);this.k+=b.length;if(q)d.set(d.subarray(e,e+32768));else for(a=0;32768>a;++a)d[a]=d[e+a];this.a=32768;return d};
    u.prototype.v=function(b){var e,a=this.input.length/this.d+1|0,c,d,f,g=this.input,h=this.b;b&&("number"===typeof b.o&&(a=b.o),"number"===typeof b.r&&(a+=b.r));2>a?(c=(g.length-this.d)/this.n[2],f=258*(c/2)|0,d=f<h.length?h.length+f:h.length<<1):d=h.length*a;q?(e=new Uint8Array(d),e.set(h)):e=h;return this.b=e};
    u.prototype.m=function(){var b=0,e=this.b,a=this.g,c,d=new (q?Uint8Array:Array)(this.k+(this.a-32768)),f,g,h,k;if(0===a.length)return q?this.b.subarray(32768,this.a):this.b.slice(32768,this.a);f=0;for(g=a.length;f<g;++f){c=a[f];h=0;for(k=c.length;h<k;++h)d[b++]=c[h]}f=32768;for(g=this.a;f<g;++f)d[b++]=e[f];this.g=[];return this.buffer=d};
    u.prototype.s=function(){var b,e=this.a;q?this.q?(b=new Uint8Array(e),b.set(this.b.subarray(0,e))):b=this.b.subarray(0,e):(this.b.length>e&&(this.b.length=e),b=this.b);return this.buffer=b};p("Zlib.RawInflate",u);p("Zlib.RawInflate.prototype.decompress",u.prototype.u);var T={ADAPTIVE:v,BLOCK:w},U,V,W,X;if(Object.keys)U=Object.keys(T);else for(V in U=[],W=0,T)U[W++]=V;W=0;for(X=U.length;W<X;++W)V=U[W],p("Zlib.RawInflate.BufferType."+V,T[V]);}).call(this); //@ sourceMappingURL=rawinflate.min.js.map

<|endoftext|>


<commit_before>/* global Firebase angular */
(function() {
  'use strict';
//Start of PoLoginController
angular.module('dolmen')
.controller('PoLoginController', function(){
  var ref = new Firebase('https://dolmen.firebaseio.com');
   var self = this;
   self.login = function() {
     ref.authWithOAuthPopup('google', function(error){
       if (error) {
         console.log("Awesomeness!!!", error);
       }
       else {
         //Totally not getting here EVAH'
       }
     });
   };
   self.logout = function() {
     ref.unauth();
     console.log("And you are out! Bammm!")
   };
});//End of PoLoginController
})();//end of IIFE

//---------- TWO ---------------
  // var services = angular.module('dolmen.', ['firebase']);
  // services.controller('PoLoginController', function($scope){
  //   // TODO: Move code from `index.services.js:authServices` in here...
  //
  //   var firebase = new firebase("https://dolmen.firebaseapp.com");
  //   this.email = 0;
  //   var self = this;
  //   this.email = function(){
  //     firebase.authWithOAuthPopup('google', function(error, authData){
  //       // console.log(whaaaaa???);
  //       $scope.$apply(function(){
  //         self.email = authData.google.email;
  //       });
  //     });
  //   };
  //   this.setUser = function(){
  //     return self.email !== 0;
  //   };
  //   });
  //   angular.module('dolmen').constant('FIREBASE_URL', 'http://dolmen.firebaseapp.com');
  // })();
  //
  //
  //

//---------- ONE -----------
  //   authServices = {};
  //
  //   var ref = new Firebase( 'https://dolmen.firebaseio.com' );
  //   authServices.authObj = $firebaseAuth( ref );
  //
  //   authServices.login = function()
  //   {
  //     authServices.authObj.$authWithOAuthPopup( 'google')
  //       .then(function(ref){
  //         $state.go('po_dash');
  //       })
  //       .catch( function( err ){
  //         console.log( err );
  //       });
  //   };
<commit_msg>removing unused code<commit_after>/* global Firebase angular */
(function() {
  'use strict';
//Start of PoLoginController
angular.module('dolmen')
.controller('PoLoginController', function(){
  var ref = new Firebase('https://dolmen.firebaseio.com');
   var self = this;
   self.login = function() {
     ref.authWithOAuthPopup('google', function(error){
       if (error) {
         console.log("Awesomeness!!!", error);
       }
       else {
         //Totally not getting here EVAH'
       }
      //  .then(function(){
      //    $location.path('/dashboard');
      //  });
     });
   };
   self.logout = function() {
     ref.unauth();
     console.log("And you are out! Bammm!");
   };
});//End of PoLoginController
})();//end of IIFE

//---------- TWO ---------------
  // var services = angular.module('dolmen.', ['firebase']);
  // services.controller('PoLoginController', function($scope){
  //   // TODO: Move code from `index.services.js:authServices` in here...
  //
  //   var firebase = new firebase("https://dolmen.firebaseapp.com");
  //   this.email = 0;
  //   var self = this;
  //   this.email = function(){
  //     firebase.authWithOAuthPopup('google', function(error, authData){
  //       // console.log(whaaaaa???);
  //       $scope.$apply(function(){
  //         self.email = authData.google.email;
  //       });
  //     });
  //   };
  //   this.setUser = function(){
  //     return self.email !== 0;
  //   };
  //   });
  //   angular.module('dolmen').constant('FIREBASE_URL', 'http://dolmen.firebaseapp.com');
  // })();
  //
  //
  //

//---------- ONE -----------
  //   authServices = {};
  //
  //   var ref = new Firebase( 'https://dolmen.firebaseio.com' );
  //   authServices.authObj = $firebaseAuth( ref );
  //
  //   authServices.login = function()
  //   {
  //     authServices.authObj.$authWithOAuthPopup( 'google')
  //       .then(function(ref){
  //         $state.go('po_dash');
  //       })
  //       .catch( function( err ){
  //         console.log( err );
  //       });
  //   };
<|endoftext|>


<commit_before>var post_top_url = "http://" + window.location.host + "/api/v1/friendposts/?" + timeline_js_parameter_top_post_polling;
var post_bottom_url = "/api/v1/friendposts/";
var comment_offsets = new Object();
var isBottominit = 0;

// post create
$("#form_post").submit(function(event) {
    alert("@");
    var feedback_api = "/api/v1/post/";
    var group =  $("select[name=group]").val()? $("select[name=group]").val() : "";
    var open_scope = $("select[name=open_scope]").val();
    switch (open_scope) {
        case "public":
            open_scope = 0;
            break;
        case "private":
            open_scope = 1;
            break;
        default:
            open_scope = 0;
            break;
    }
    if (group != "" && open_scope == 1){
        alert("비공개 그룹글은 지원하지 않습니다.\n"+group+"\n"+open_scope);
        return false;
    }
    var data = JSON.stringify({
        "post": $("input[name=post]").val(),
        "group": group,
        "open_scope": open_scope
    });
    console.log(data);
    $.ajax({
        url: feedback_api,
        type: "POST",
        contentType: "application/json",
        data: data,
        dataType: "json",
        statusCode: {
            201: function(data) {
                /*post로 생성 후 생성한 json response*/
                console.log("post submit response");
                console.log(data);
                PostTopPolling();
                $("input[name=post]").val("");
            }
        }
    });
    return false;
});

// comment create
$(document).on("submit", "#form_comment",function(event) {
        var feedback_api = "/api/v1/comment/";
        var post_key = $(this).find("input[name=post_key]").val();
        var data = JSON.stringify({
            "comment": $(this).find("input[name=comment]").val(),
            "post_key": post_key
        });
        console.log(data);
        $.ajax({
            url: feedback_api,
            type: "POST",
            contentType: "application/json",
            data: data,
            dataType: "json",
            context: this,
            statusCode: {
                201: function(data) {
                    console.log("post submit response");
                    console.log(data);
                    pollComment(data.post_key);
                    $("input[name=comment]").val("");
                    var comment_count = $("#commentList"+post_key+" li").size();
                    $(this).parent().siblings("header").find(".p_comment").html("댓글/ "+comment_count+"");
                }
            }
        });
        return false;
});

// polling post
function PostTopPolling() {
    $.ajax({
        url: post_top_url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log("TOP POLL POST  url:" + post_top_url);
            console.log(data)
            if(data.objects.length != 0)
            {
                $("#post_public_template").tmpl(data.objects).prependTo("#timeline_posts");
                timeRefresh();
                post_top_url = data.meta.previous;
                console.log("1 previous url:  " + post_top_url);
                if(!data.meta.previous)
                    post_top_url = "http://" + window.location.host + "/api/v1/friendposts/?limit=1&id__gt=" + data.objects[0].id + "&" + timeline_js_parameter_top_post_polling;
                console.log("2 previous url:  " + post_top_url);
                if(isBottominit==0) {
                    post_bottom_url = (!data.meta.next) ? null : data.meta.next + "&id__lte=" + data.objects[0].id;
                    console.log("1 next url:  " + post_bottom_url);
                    isBottominit = 1;
                }
            }
        }
        });
}

// when screen on top, call PostTopPolling
$(document).ready(function() {
    PostTopPolling();
    setTimeout(function(){$("#timeline_posts").waypoint(function(){postBottom();}, { offset: 'bottom-in-view' });}, 1000);
    setTimeout(function(){$("#p_timeline").waypoint(function(){PostTopPolling()}, { offset: '0' });}, 5000);

    // dynamic timeago(Korean)
    $.timeago.settings.strings = {
        suffixAgo: "전",
        suffixFromNow: "후",
        seconds: "1분 이내",
        minute: "1분",
        minutes: "%d분",
        hour: "1시간",
        hours: "%d시간",
        day: "하루",
        days: "%d일",
        month: "한 달",
        months: "%d달",
        year: "1년",
        years: "%d년",
        wordSeparator: " "
    };

    setTimeout(function(){timeRefresh();console.log("timeago called");}, 2000);
});

function postBottom() {
    if(!post_bottom_url)
        return;
    $.ajax({
        url: post_bottom_url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log("BOTTOM POLL POST   url:" + post_bottom_url);
            console.log(data);
            if(data.objects.length != 0)
            {
                $("#post_public_template").tmpl(data.objects).appendTo("#timeline_posts");
                post_bottom_url = data.meta.next;
                console.log("2 next url:  "+post_bottom_url);
                timeRefresh();
            }
        }
        });
}
// polling comment
function pollComment(post_id) {
    if(!post_id)
        return;

    var feedback_api = "/api/v1/comment/?post=" + post_id; // api inner parameter ?limit=20&offset=0"

    if(comment_offsets[post_id]){
        feedback_api = "/api/v1/comment/?post=" + post_id + "&limit=30&id__gt=" + comment_offsets[post_id];
        // feedback_api = "/api/v1/comment/?post=" + post_id + "&limit=30&offset=" + comment_offsets[post_id];
    }

    console.log("Polling comment url :  " + feedback_api);
    $.ajax({
        url: feedback_api,
        type: "GET",
        dataType: "json",
        success: function(data) {
            if(data.objects.length != 0)
            {
                console.log(data);
                $("#comment_template").tmpl(data.objects.reverse()).appendTo("#commentList" + post_id);
                comment_offsets[post_id] = data.objects[data.objects.length - 1].id;
                console.log("댓글 폴링한 마지막 오프셋 :"+comment_offsets[post_id]);
            }
        }
        });
}

// comment toggle
$(document).on("click", ".p_responses", function(){
        $(this).parent().children("section").toggle();
        var resp = $(this).toggleClass("opened");

        // comment polling on post focused
        if (resp && resp.context.className.search("opened") != -1){
            var tag_id = $(this).siblings(".p_comment").children(".p_commentList").attr("id");
            if (!tag_id)
                return false;
            var postid = tag_id.replace("commentList", "");

            pollComment(postid);
        }
        return false;
});

// emotion click
$(document).on("click", ".form_emotion :submit", function(event){
        var feedback_api = "/api/v1/postemotions/"
        var data = JSON.stringify({
            "emotion": $(this).attr('tag'),
            "post_key": $(this).siblings("input[name=post_key]").val()
        });
        console.log(data);
        $.ajax({
            url: feedback_api,
            type: "POST",
            contentType: "application/json",
            data: data,
            dataType: "json",
            statusCode: {
                201: function(data) {
                    console.log("post emotion submit response");
                    console.log(data);
                }
            }
        });
        return false;
});

function timeRefresh() {
    $("abbr.timeago").timeago();
}

// TODO - Post crate using open scope<commit_msg>댓글 time ago 적용, 작성시 글, 댓글 의 시간 업데이트<commit_after>var post_top_url = "http://" + window.location.host + "/api/v1/friendposts/?" + timeline_js_parameter_top_post_polling;
var post_bottom_url = "/api/v1/friendposts/";
var comment_offsets = new Object();
var isBottominit = 0;

// post create
$("#form_post").submit(function(event) {
    alert("@");
    var feedback_api = "/api/v1/post/";
    var group =  $("select[name=group]").val()? $("select[name=group]").val() : "";
    var open_scope = $("select[name=open_scope]").val();
    switch (open_scope) {
        case "public":
            open_scope = 0;
            break;
        case "private":
            open_scope = 1;
            break;
        default:
            open_scope = 0;
            break;
    }
    if (group != "" && open_scope == 1){
        alert("비공개 그룹글은 지원하지 않습니다.\n"+group+"\n"+open_scope);
        return false;
    }
    var data = JSON.stringify({
        "post": $("input[name=post]").val(),
        "group": group,
        "open_scope": open_scope
    });
    console.log(data);
    $.ajax({
        url: feedback_api,
        type: "POST",
        contentType: "application/json",
        data: data,
        dataType: "json",
        statusCode: {
            201: function(data) {
                /*post로 생성 후 생성한 json response*/
                console.log("post submit response");
                console.log(data);
                PostTopPolling();
                $("input[name=post]").val("");
            }
        }
    });
    return false;
});

// comment create
$(document).on("submit", "#form_comment",function(event) {
        var feedback_api = "/api/v1/comment/";
        var post_key = $(this).find("input[name=post_key]").val();
        var data = JSON.stringify({
            "comment": $(this).find("input[name=comment]").val(),
            "post_key": post_key
        });
        console.log(data);
        $.ajax({
            url: feedback_api,
            type: "POST",
            contentType: "application/json",
            data: data,
            dataType: "json",
            context: this,
            statusCode: {
                201: function(data) {
                    console.log("post submit response");
                    console.log(data);
                    pollComment(data.post_key);
                    $("input[name=comment]").val("");
                    var comment_count = $("#commentList"+post_key+" li").size();
                    $(this).parent().siblings("header").find(".p_comment").html("댓글/ "+comment_count+"");
                }
            }
        });
        return false;
});

// polling post
function PostTopPolling() {
    $.ajax({
        url: post_top_url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log("TOP POLL POST  url:" + post_top_url);
            console.log(data)
            if(data.objects.length != 0)
            {
                $("#post_public_template").tmpl(data.objects).prependTo("#timeline_posts");
                timeRefresh();
                post_top_url = data.meta.previous;
                console.log("1 previous url:  " + post_top_url);
                if(!data.meta.previous)
                    post_top_url = "http://" + window.location.host + "/api/v1/friendposts/?limit=1&id__gt=" + data.objects[0].id + "&" + timeline_js_parameter_top_post_polling;
                console.log("2 previous url:  " + post_top_url);
                if(isBottominit==0) {
                    post_bottom_url = (!data.meta.next) ? null : data.meta.next + "&id__lte=" + data.objects[0].id;
                    console.log("1 next url:  " + post_bottom_url);
                    isBottominit = 1;
                }
            }
        }
        });
}

// when screen on top, call PostTopPolling
$(document).ready(function() {
    PostTopPolling();
    setTimeout(function(){$("#timeline_posts").waypoint(function(){postBottom();}, { offset: 'bottom-in-view' });}, 1000);
    setTimeout(function(){$("#p_timeline").waypoint(function(){PostTopPolling()}, { offset: '0' });}, 5000);

    // dynamic timeago(Korean)
    $.timeago.settings.strings = {
        suffixAgo: "전",
        suffixFromNow: "후",
        seconds: "1분 이내",
        minute: "1분",
        minutes: "%d분",
        hour: "1시간",
        hours: "%d시간",
        day: "하루",
        days: "%d일",
        month: "한 달",
        months: "%d달",
        year: "1년",
        years: "%d년",
        wordSeparator: " "
    };

    setTimeout(function(){timeRefresh();console.log("timeago called");}, 2000);
});

function postBottom() {
    if(!post_bottom_url)
        return;
    $.ajax({
        url: post_bottom_url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            console.log("BOTTOM POLL POST   url:" + post_bottom_url);
            console.log(data);
            if(data.objects.length != 0)
            {
                $("#post_public_template").tmpl(data.objects).appendTo("#timeline_posts");
                post_bottom_url = data.meta.next;
                console.log("2 next url:  "+post_bottom_url);
                timeRefresh();
            }
        }
        });
}
// polling comment
function pollComment(post_id) {
    if(!post_id)
        return;

    var feedback_api = "/api/v1/comment/?post=" + post_id; // api inner parameter ?limit=20&offset=0"

    if(comment_offsets[post_id]){
        feedback_api = "/api/v1/comment/?post=" + post_id + "&limit=30&id__gt=" + comment_offsets[post_id];
        // feedback_api = "/api/v1/comment/?post=" + post_id + "&limit=30&offset=" + comment_offsets[post_id];
    }

    console.log("Polling comment url :  " + feedback_api);
    $.ajax({
        url: feedback_api,
        type: "GET",
        dataType: "json",
        success: function(data) {
            if(data.objects.length != 0)
            {
                console.log(data);
                $("#comment_template").tmpl(data.objects.reverse()).appendTo("#commentList" + post_id);
                timeRefresh();
                comment_offsets[post_id] = data.objects[data.objects.length - 1].id;
                console.log("댓글 폴링한 마지막 오프셋 :"+comment_offsets[post_id]);
            }
        }
        });
}

// comment toggle
$(document).on("click", ".p_responses", function(){
        $(this).parent().children("section").toggle();
        var resp = $(this).toggleClass("opened");

        // comment polling on post focused
        if (resp && resp.context.className.search("opened") != -1){
            var tag_id = $(this).siblings(".p_comment").children(".p_commentList").attr("id");
            if (!tag_id)
                return false;
            var postid = tag_id.replace("commentList", "");

            pollComment(postid);
        }
        return false;
});

// emotion click
$(document).on("click", ".form_emotion :submit", function(event){
        var feedback_api = "/api/v1/postemotions/"
        var data = JSON.stringify({
            "emotion": $(this).attr('tag'),
            "post_key": $(this).siblings("input[name=post_key]").val()
        });
        console.log(data);
        $.ajax({
            url: feedback_api,
            type: "POST",
            contentType: "application/json",
            data: data,
            dataType: "json",
            statusCode: {
                201: function(data) {
                    console.log("post emotion submit response");
                    console.log(data);
                }
            }
        });
        return false;
});

function timeRefresh() {
    $("abbr.timeago").timeago();
}

// TODO - Post crate using open scope<|endoftext|>


<commit_before>/**
 * Service to display status in all app views
 */
angular.module('lcaApp.status.service', ['angularSpinner', 'ui.bootstrap.alert'])
    .constant("SPINNER_KEY", "spinner-lca")
    .factory('StatusService', [ 'usSpinnerService', 'SPINNER_KEY', '$rootScope',
        function (usSpinnerService, SPINNER_KEY, $rootScope) {
            var svc = { };

            svc.startWaiting = function () {
                $rootScope.alert = null;
                usSpinnerService.spin(SPINNER_KEY);
            };

            svc.stopWaiting = function () {
                usSpinnerService.stop(SPINNER_KEY);
            };

            svc.handleFailure = function (errMsg) {
                svc.stopWaiting();
                $rootScope.alert = { type: "danger", msg: errMsg };
            };

            svc.handleSuccess = function (infoMsg) {
                    svc.stopWaiting();
                    $rootScope.alert = null;
                    if (infoMsg) {
                        $rootScope.alert = { type: "success", msg: infoMsg };
                    }
            };

            return svc;
    }]);
<commit_msg>Vis: Extract error from httpResponse (#148)<commit_after>/**
 * Service to display status in all app views
 */
angular.module('lcaApp.status.service', ['angularSpinner', 'ui.bootstrap.alert'])
    .constant("SPINNER_KEY", "spinner-lca")
    .factory('StatusService', [ 'usSpinnerService', 'SPINNER_KEY', '$rootScope',
        function (usSpinnerService, SPINNER_KEY, $rootScope) {
            var svc = { };

            svc.startWaiting = function () {
                $rootScope.alert = null;
                usSpinnerService.spin(SPINNER_KEY);
            };

            svc.stopWaiting = function () {
                usSpinnerService.stop(SPINNER_KEY);
            };

            /**
             * Stop waiting and display error.
             * @param {string | {}} err     httpResponse for failed request or error message
             */
            svc.handleFailure = function (err) {
                var errMsg = "";
                svc.stopWaiting();
                if (typeof(err) === "string") {
                    errMsg = err;
                } else {
                    if (err.hasOwnProperty("status")) {
                        if (err["status"] == 409) {
                            errMsg = "Web API request conflicts with another request that is in progress.\n";
                        }
                    }
                    if (err.hasOwnProperty("data")) {
                        errMsg += err["data"]
                    }
                }
                $rootScope.alert = { type: "danger", msg: errMsg };
            };

            svc.handleSuccess = function (infoMsg) {
                    svc.stopWaiting();
                    $rootScope.alert = null;
                    if (infoMsg) {
                        $rootScope.alert = { type: "success", msg: infoMsg };
                    }
            };

            return svc;
    }]);
<|endoftext|>


<commit_before>/* Base phone module for Odoo
   Copyright (C) 2013-2018 Akretion France
   @author: Alexis de Lattre <alexis.delattre@akretion.com>
   License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). */

odoo.define("base_phone.updatedphone_widget", function (require) {
    "use strict";

    var core = require("web.core");
    var FieldPhone = require("web.basic_fields").FieldPhone;
    var _t = core._t;

    FieldPhone.include({
        /* Always enable phone link tel:, not only on small screens  */
        _canCall: function () {
            return true;
        },
        showDialButton: function () {
            // Must be inherited by ipbx specific modules
            // and set to true
            return false;
        },

        _renderReadonly: function () {
            // Create a link to trigger action on server
            // this link will be after the
            this._super();

            if (!this.showDialButton()) {
                return;
            }
            var self = this;

            // Create our link
            var dial = $(
                '
☎ Dial
'
            );

            // Add a parent element
            // it's not possible to append to $el directly
            // because $el don't have any parent yet
            var parent = $("
");
            parent.append([this.$el[0], " ", dial]);

            // Replace this.$el by our new container
            this.$el = parent;

            var phone_num = this.value;
            /* eslint-disable no-unused-vars */
            dial.click(function (evt) {
                self.click2dial(phone_num);
            });
            /* eslint-enable no-unused-vars */
        },
        click2dial: function (phone_num) {
            var self = this;
            this.do_notify(
                _.str.sprintf(_t("Click2dial to %s"), phone_num),
                _t("Unhook your ringing phone"),
                false
            );
            var params = {
                phone_number: phone_num,
                click2dial_model: this.model,
                click2dial_id: this.res_id,
            };
            return this._rpc({
                model: "phone.common",
                context: params,
                method: "click2dial",
                args: [phone_num],
            }).then(
                /* eslint-disable no-unused-vars */
                function (r) {
                    console.log("successfull", r);
                    if (r === false) {
                        self.do_warn("Click2dial failed");
                    } else if (typeof r === "object") {
                        self.do_notify(
                            _t("Click2dial successfull"),
                            _.str.sprintf(_t("Number dialed: %s"), r.dialed_number),
                            false
                        );
                        if (r.action_model) {
                            var action = {
                                name: r.action_name,
                                type: "ir.actions.act_window",
                                res_model: r.action_model,
                                view_mode: "form",
                                views: [[false, "form"]],
                                target: "new",
                                context: params,
                            };
                            return self.do_action(action);
                        }
                    }
                },
                function (r) {
                    console.log("on error");
                    self.do_warn("Click2dial failed");
                }
                /* eslint-enable no-unused-vars */
            );
        },
    });

    return {
        FieldPhone: FieldPhone,
    };
});
<commit_msg>[FIX] We have to stay on the same page after clicking on the link<commit_after>/* Base phone module for Odoo
   Copyright (C) 2013-2018 Akretion France
   @author: Alexis de Lattre <alexis.delattre@akretion.com>
   License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). */

odoo.define("base_phone.updatedphone_widget", function (require) {
    "use strict";

    var core = require("web.core");
    var FieldPhone = require("web.basic_fields").FieldPhone;
    var _t = core._t;

    FieldPhone.include({
        /* Always enable phone link tel:, not only on small screens  */
        _canCall: function () {
            return true;
        },
        showDialButton: function () {
            // Must be inherited by ipbx specific modules
            // and set to true
            return false;
        },

        _renderReadonly: function () {
            // Create a link to trigger action on server
            // this link will be after the
            this._super();

            if (!this.showDialButton()) {
                return;
            }
            var self = this;

            // Create our link
            var dial = $(
                '
☎ Dial
'
            );

            // Add a parent element
            // it's not possible to append to $el directly
            // because $el don't have any parent yet
            var parent = $("
");
            parent.append([this.$el[0], " ", dial]);

            // Replace this.$el by our new container
            this.$el = parent;

            var phone_num = this.value;
            /* eslint-disable no-unused-vars */
            dial.click(function (evt) {
                self.click2dial(phone_num);
            });
            /* eslint-enable no-unused-vars */
        },
        click2dial: function (phone_num) {
            var self = this;
            this.do_notify(
                _.str.sprintf(_t("Click2dial to %s"), phone_num),
                _t("Unhook your ringing phone"),
                false
            );
            var params = {
                phone_number: phone_num,
                click2dial_model: this.model,
                click2dial_id: this.res_id,
            };
            return this._rpc({
                model: "phone.common",
                context: params,
                method: "click2dial",
                args: [phone_num],
            }).then(
                /* eslint-disable no-unused-vars */
                function (r) {
                    console.log("successfull", r);
                    if (r === false) {
                        self.do_warn("Click2dial failed");
                    } else if (typeof r === "object") {
                        self.do_notify(
                            _t("Click2dial successfull"),
                            _.str.sprintf(_t("Number dialed: %s"), r.dialed_number),
                            false
                        );
                        if (r.action_model) {
                            var action = {
                                name: r.action_name,
                                type: "ir.actions.act_window",
                                res_model: r.action_model,
                                view_mode: "form",
                                views: [[false, "form"]],
                                target: "new",
                                context: params,
                            };
                            return self.do_action(action);
                        }
                    }
                },
                function (r) {
                    console.log("on error");
                    self.do_warn("Click2dial failed");
                }
                /* eslint-enable no-unused-vars */
            );
        },
    });

    return {
        FieldPhone: FieldPhone,
    };
});
<|endoftext|>


<commit_before>/**
 * @class GeoExt.plugins.PrintPageField
 *
 * A plugin for `Ext.form.Field` components which provides synchronization
 *  with a {@link GeoExt.data.PrintPage}. The field name has to match the
 *  respective property of the printPage (e.g. `scale`, `rotation`).
 *
 * A form with a combo box for the scale and text fields for rotation and a
 *  page title. The page title is a custom parameter of the print module's
 *  page configuration:
 *
 *      @example
 *      var printPage = Ext.create('GeoExt.data.PrintPage'{
 *          printProvider: Ext.create('GeoExt.data.PrintProvider', {
 *              capabilities: printCapabilities
 *          })
 *      });
 *      Ext.create('Ext.form.FormPanel', {
 *          renderTo: "form",
 *          width: 200,
 *          height: 300,
 *          items: [{
 *              xtype: "combo",
 *              displayField: "name",
 *              store: printPage.scales, // printPage.scale
 *              name: "scale",
 *              fieldLabel: "Scale",
 *              typeAhead: true,
 *              mode: "local",
 *              forceSelection: true,
 *              triggerAction: "all",
 *              selectOnFocus: true,
 *              plugins: new GeoExt.plugins.PrintPageField({
 *                  printPage: printPage
 *              })
 *          }, {
 *              xtype: "textfield",
 *              name: "rotation", // printPage.rotation
 *              fieldLabel: "Rotation",
 *              plugins: new GeoExt.plugins.PrintPageField({
 *                  printPage: printPage
 *              })
 *          }, {
 *              xtype: "textfield",
 *              name: "mapTitle", // printPage.customParams["mapTitle"]
 *              fieldLabel: "Map Title",
 *              plugins: new GeoExt.plugins.PrintPageField({
 *                  printPage: printPage
 *              })
 *          }]
 *      });
 *
 */
Ext.define('GeoExt.plugins.PrintPageField', {
    extend : 'Ext.util.Observable',
    requires: ['GeoExt.data.PrintPage'],
    alias : 'widget.gx_printpagefield',
    alternateClassName : 'GeoExt.PrintPageField',

    /**
     * @cfg {GeoExt.data.PrintPage} printPage
     * The print page to synchronize with.
     */

    /**
     * @private
     * @property {GeoExt.data.PrintPage} printPage
     * The print page to synchronize with.
     *  Read-only.
     */
    printPage: null,

    /**
     * @private
     * @property {Ext.form.Field} target
     * This plugin's target field.
     */
    target: null,

    /**
     * @private
     */
    constructor: function(config) {
        this.initialConfig = config;
        Ext.apply(this, config);

        this.callParent(arguments);
    },

    /**
     * @private
     * @param {Ext.form.Field} target The component that this plugin
     *  extends.
     * @param {Object} target
     */
    init: function(target) {
        this.target = target;
        var onCfg = {
            "beforedestroy": this.onBeforeDestroy,
            scope: this
        };
        var eventName = target instanceof Ext.form.ComboBox ?
                            "select" : target instanceof Ext.form.Checkbox ?
                                "check" : "valid";
        onCfg[eventName] = this.onFieldChange;
        target.on(onCfg);
        this.printPage.on({
            "change": this.onPageChange,
            scope: this
        });
        this.printPage.printProvider.on({
            "layoutchange": this.onLayoutChange,
            scope: this
        });
        this.setValue(this.printPage);
    },

    /**
     * Handler for the target field's "valid" or "select" event.
     *
     * @private
     * @param {Ext.form.Field} field
     * @param {Ext.data.Record} record Optional.
     */
    onFieldChange: function(field, record) {
        var printProvider = this.printPage.printProvider;
        var value = field.getValue();
        this._updating = true;
        if(field.store === printProvider.scales || field.name === "scale") {
            this.printPage.setScale(record);
        } else if(field.name == "rotation") {
            !isNaN(value) && this.printPage.setRotation(value);
        } else {
            this.printPage.customParams[field.name] = value;
        }
        delete this._updating;
    },

    /**
     * Handler for the "change" event for the page this plugin is configured
     *  with.
     *
     * @private
     * @param {GeoExt.data.PrintPage} printPage
     */
    onPageChange: function(printPage) {
        if(!this._updating) {
            this.setValue(printPage);
        }
    },

    /**
     * Handler for the "layoutchange" event of the printProvider.
     *
     * @private
     * @param {GeoExt.data.PrintProvider} printProvider
     * @param {Ext.Record} layout
     *
     */
    onLayoutChange: function(printProvider, layout) {
        var t = this.target;
        t.name == "rotation" && t.setDisabled(!layout.get("rotation"));
    },

    /**
     * Sets the value in the target field.
     *
     * @private
     * @param {GeoExt.data.PrintPage} printPage
     */
    setValue: function(printPage) {
        var t = this.target;
        t.suspendEvents();
        if(t.store === printPage.printProvider.scales || t.name === "scale") {
            if(printPage.scale) {
                t.setValue(printPage.scale.get(t.displayField));
            }
        } else if(t.name == "rotation") {
            t.setValue(printPage.rotation);
        }
        t.resumeEvents();
    },

    /**
     * @private
     */
    onBeforeDestroy: function() {
        this.target.un("beforedestroy", this.onBeforeDestroy, this);
        this.target.un("select", this.onFieldChange, this);
        this.target.un("valid", this.onFieldChange, this);
        this.printPage.un("change", this.onPageChange, this);
        this.printPage.printProvider.un("layoutchange", this.onLayoutChange,
            this);
    }
});<commit_msg>Ported logic of PrintPageField to ExtJS 4 needs.<commit_after>/**
 * @class GeoExt.plugins.PrintPageField
 *
 * A plugin for `Ext.form.Field` components which provides synchronization
 *  with a {@link GeoExt.data.PrintPage}. The field name has to match the
 *  respective property of the printPage (e.g. `scale`, `rotation`).
 *
 * A form with a combo box for the scale and text fields for rotation and a
 *  page title. The page title is a custom parameter of the print module's
 *  page configuration:
 *
 *      @example
 *      var printPage = Ext.create('GeoExt.data.PrintPage'{
 *          printProvider: Ext.create('GeoExt.data.PrintProvider', {
 *              capabilities: printCapabilities
 *          })
 *      });
 *      Ext.create('Ext.form.FormPanel', {
 *          renderTo: "form",
 *          width: 200,
 *          height: 300,
 *          items: [{
 *              xtype: "combo",
 *              displayField: "name",
 *              store: printPage.scales, // printPage.scale
 *              name: "scale",
 *              fieldLabel: "Scale",
 *              typeAhead: true,
 *              mode: "local",
 *              forceSelection: true,
 *              triggerAction: "all",
 *              selectOnFocus: true,
 *              plugins: new GeoExt.plugins.PrintPageField({
 *                  printPage: printPage
 *              })
 *          }, {
 *              xtype: "textfield",
 *              name: "rotation", // printPage.rotation
 *              fieldLabel: "Rotation",
 *              plugins: new GeoExt.plugins.PrintPageField({
 *                  printPage: printPage
 *              })
 *          }, {
 *              xtype: "textfield",
 *              name: "mapTitle", // printPage.customParams["mapTitle"]
 *              fieldLabel: "Map Title",
 *              plugins: new GeoExt.plugins.PrintPageField({
 *                  printPage: printPage
 *              })
 *          }]
 *      });
 *
 */
Ext.define('GeoExt.plugins.PrintPageField', {
    extend : 'Ext.util.Observable',
    requires: ['GeoExt.data.PrintPage', 'Ext.form.field.ComboBox', 'Ext.form.field.Checkbox'],
    alias : 'widget.gx_printpagefield',
    alternateClassName : 'GeoExt.PrintPageField',

    /**
     * @cfg {GeoExt.data.PrintPage} printPage
     * The print page to synchronize with.
     */

    /**
     * @private
     * @property {GeoExt.data.PrintPage} printPage
     * The print page to synchronize with.
     *  Read-only.
     */
    printPage: null,

    /**
     * @private
     * @property {Ext.form.Field} target
     * This plugin's target field.
     */
    target: null,

    /**
     * @private
     */
    constructor: function(config) {
        this.initialConfig = config;
        Ext.apply(this, config);

        this.callParent(arguments);
    },

    /**
     * @private
     * @param {Ext.form.Field} target The component that this plugin
     *  extends.
     * @param {Object} target
     */
    init: function(target) {

        this.target = target;
        var onCfg = {
            "beforedestroy": this.onBeforeDestroy,
            scope: this
        };

        // the old 'check' event of 3.x is gone, only 'change' is supported
        var eventName = target instanceof Ext.form.ComboBox ?
                            "select" : target instanceof Ext.form.Checkbox ?
                                "change" : "valid";
        onCfg[eventName] = this.onFieldChange;
        target.on(onCfg);
        this.printPage.on({
            "change": this.onPageChange,
            scope: this
        });
        this.printPage.printProvider.on({
            "layoutchange": this.onLayoutChange,
            scope: this
        });
        this.setValue(this.printPage);
    },

    /**
     * Handler for the target field's "valid" or "select" event.
     *
     * @private
     * @param {Ext.form.Field} field
     * @param {Ext.data.Record[]} records Optional.
     */
    onFieldChange: function(field, records) {

    	var record;
    	if (Ext.isArray(records)) {
			record = records[0];
		} else {
			record = records;
		}

        var printProvider = this.printPage.printProvider;
        var value = field.getValue();
        this._updating = true;
        if(field.store === printProvider.scales || field.name === "scale") {
            this.printPage.setScale(record);
        } else if(field.name == "rotation") {
            !isNaN(value) && this.printPage.setRotation(value);
        } else {
            this.printPage.customParams[field.name] = value;
        }
        delete this._updating;
    },

    /**
     * Handler for the "change" event for the page this plugin is configured
     *  with.
     *
     * @private
     * @param {GeoExt.data.PrintPage} printPage
     */
    onPageChange: function(printPage) {
        if(!this._updating) {
            this.setValue(printPage);
        }
    },

    /**
     * Handler for the "layoutchange" event of the printProvider.
     *
     * @private
     * @param {GeoExt.data.PrintProvider} printProvider
     * @param {Ext.Record} layout
     *
     */
    onLayoutChange: function(printProvider, layout) {
        var t = this.target;
        t.name == "rotation" && t.setDisabled(!layout.get("rotation"));
    },

    /**
     * Sets the value in the target field.
     *
     * @private
     * @param {GeoExt.data.PrintPage} printPage
     */
    setValue: function(printPage) {
        var t = this.target;
        t.suspendEvents();
        if(t.store === printPage.printProvider.scales || t.name === "scale") {
            if(printPage.scale) {
                t.setValue(printPage.scale.get(t.displayField));
            }
        } else if(t.name == "rotation") {
            t.setValue(printPage.rotation);
        }
        t.resumeEvents();
    },

    /**
     * @private
     */
    onBeforeDestroy: function() {
        this.target.un("beforedestroy", this.onBeforeDestroy, this);
        this.target.un("select", this.onFieldChange, this);
        this.target.un("valid", this.onFieldChange, this);
        this.printPage.un("change", this.onPageChange, this);
        this.printPage.printProvider.un("layoutchange", this.onLayoutChange,
            this);
    }
});<|endoftext|>


<commit_before>var bot = require('nodemw');
// pass configuration object
var client = new bot({
  server: 'en.wikipedia.org',  // host name of MediaWiki-powered site
  path: '/w',                  // path to api.php script
  debug: false                // is more verbose when set to true
});

// get the object being the first key/value entry of a given object
var getFirstItem = function(object) {
  for(var key in object);
  return object[key];
};

function getLinks(title, callback) {
  query = {
    action: 'query',
    prop: 'links',
    titles: title,
    pllimit:5000
  };

  function makeCall() {
    client.api.call(query,
      function(data, info, next) {
        for(var i in getFirstItem(data.pages).links)
        {
          callback(getFirstItem(data.pages).links[i]);
        }

      }
    );
  }

  makeCall();
}

function getSubCategories(prefix,callback){
	if(typeof prefix === 'function') {
				callback = prefix;
			}
			client.api.call({
				action: 'query',
				cmnamespace:'14|0',
				list: 'categorymembers',
				cmtitle:prefix,
				cmlimit: 500
			}, function(data){
				callback && callback(data && data.categorymembers || []);
			})
}
function getInternalLinks(title,callback){
		client.api.call({
					action: 'query',
					prop: 'links',
					titles: title,
					ellimit: 5000

				}, function(data) {
					callback && callback((data && getFirstItem(data.pages).links) || []);
			});
}

/*
 get first Paragraph
 require the txtjs module
 */

function getFirstParagraph(title,callback){
	var txtwiki=require('./txtwiki');
	client.getArticle(title,function(data){
		callback(txtwiki.parseWikitext(data.substring(0,data.indexOf("\n\n"))));
	});
}

//import  pages and cat within 7 level
	var pageCount=0;
	var catCount=0;
	var existingCategories = {};
	var fs=require('fs');
function writeAllPagesAndCat(catagory,level,callback){
	getSubCategories(catagory,function(data){
		for(var i in data){
			if(data[i].ns===0){
				/*
				this is the article in this catagory
				write article into the article.txt,format: articleTitle,catagory
				article might be in the different catagory
                */
              fs.appendFile("article.txt",data[i].title+","+catagory+"\n",function(){});
               pageCount++;
			}else{
				/* this is the catagory
				 write catagory into the catagory.txt,format: catagory,parentCatagory
				*/
               // check if we already has the catogory, check in the txt files
               if(!existingCategories[data[i].title]){
               	  // add it into the exsistingCategories
               	  existingCategories[data[i].title]=true;
                  fs.appendFile("catagory.txt",data[i].title+","+catagory+"\n",function(){});
                  // get it's subcatagories
                  if(level<7){
                  	writeAllPagesAndCat(data[i].title,level+1,callback);
                  }

                  catCount++;
               }
			}
		}
		callback(level,catagory);
	})
}

/*
import all the datas
writeAllPagesAndCat('Category:Computer_science',1,function(level,catagory){
	console.log(level,catagory,pageCount,catCount);
});
*/
// read the file and save it into the other new files

var lazy=require('lazy');
// read all the txt and convert it with title,
new lazy(fs.createReadStream('article.txt'))
	.lines
	.forEach(function(line){
		var array=line.toString().split(',');
		var title=array[0].replace(" ","_");
		var catagory=array[1].replace("Category:","");
		var url="http://en.wikipedia.org/wiki/"+title;
		//console.log(title,url,catagory);
	})

<commit_msg>fix the bug of the get first paragraph<commit_after>var bot = require('nodemw');
// pass configuration object
var client = new bot({
  server: 'en.wikipedia.org',  // host name of MediaWiki-powered site
  path: '/w',                  // path to api.php script
  debug: false                // is more verbose when set to true
});

// get the object being the first key/value entry of a given object
var getFirstItem = function(object) {
  for(var key in object);
  return object[key];
};

function getLinks(title, callback) {
  query = {
    action: 'query',
    prop: 'links',
    titles: title,
    pllimit:5000
  };

  function makeCall() {
    client.api.call(query,
      function(data, info, next) {
        for(var i in getFirstItem(data.pages).links)
        {
          callback(getFirstItem(data.pages).links[i]);
        }

      }
    );
  }

  makeCall();
}

function getSubCategories(prefix,callback){
	if(typeof prefix === 'function') {
				callback = prefix;
			}
			client.api.call({
				action: 'query',
				cmnamespace:'14|0',
				list: 'categorymembers',
				cmtitle:prefix,
				cmlimit: 500
			}, function(data){
				callback && callback(data && data.categorymembers || []);
			})
}
function getInternalLinks(title,callback){
		client.api.call({
					action: 'query',
					prop: 'links',
					titles: title,
					pllimit: 5000

				}, function(data) {
					callback && callback((data && getFirstItem(data.pages).links) || []);
			});
}

//import  pages and cat within 7 level
	var pageCount=0;
	var catCount=0;
	var existingCategories = {};
	var fs=require('fs');
function writeAllPagesAndCat(catagory,level,callback){
	getSubCategories(catagory,function(data){
		for(var i in data){
			if(data[i].ns===0){
				/*
				this is the article in this catagory
				write article into the article.txt,format: articleTitle,catagory
				article might be in the different catagory
                */
              fs.appendFile("article.txt",data[i].title+","+catagory+"\n",function(){});
               pageCount++;
			}else{
				/* this is the catagory
				 write catagory into the catagory.txt,format: catagory,parentCatagory
				*/
               // check if we already has the catogory, check in the txt files
               if(!existingCategories[data[i].title]){
               	  // add it into the exsistingCategories
               	  existingCategories[data[i].title]=true;
                  fs.appendFile("catagory.txt",data[i].title+","+catagory+"\n",function(){});
                  // get it's subcatagories
                  if(level<7){
                  	writeAllPagesAndCat(data[i].title,level+1,callback);
                  }

                  catCount++;
               }
			}
		}
		callback(level,catagory);
	})
}

/*
import all the datas
writeAllPagesAndCat('Category:Computer_science',1,function(level,catagory){
	console.log(level,catagory,pageCount,catCount);
});
*/
// read the file and save it into the other new files
/*
var lazy=require('lazy');
// read all the txt and convert it with title,
new lazy(fs.createReadStream('article.txt'))
	.lines
	.forEach(function(line){
		var array=line.toString().split(',');
		var title=array[0].replace(" ","_");
		var catagory=array[1].replace("Category:","");
		var url="http://en.wikipedia.org/wiki/"+title;
		//console.log(title,url,catagory);
	})
*/

function calculateStrength(startingNode,endingnode,callback)  {
   var connected=0;
	getInternalLinks(startingNode,function(datas){

        getInternalLinks(endingnode,function(endNodeDatas){
           var titles=[];
           for(var i in endNodeDatas){
               titles[i]=endNodeDatas[i].title;
           }

            for(var i=0;i<datas.length;i++){
		       	 if(titles.indexOf(datas[i].title)!=-1){
                   connected++ ;

		       	 }
		    }
		      callback(connected/datas.length,connected,connected/endNodeDatas.length);
        })

    });
}

function getFirstParagraph(title,callback){

	client.api.call({
		action: 'parse',
		page:title,
		prop: 'text',
		},function(data){
		var regex = /<p>.+<\/p>/;
		match = regex.exec(data.text['*']);
         callback(match[0]);
	})
}
getFirstParagraph("Python (programming language)",console.log);

<|endoftext|>


<commit_before>var QUERY_TRANSFORMS = {
  'BLUE': 'class="l"',
  'ORANGE': 'class="h"',
  'RED': '',
  'YELLOW': 'class="o"',
  'GRAY': '',
  'RED1': '',
  'RED2': '<a',
  'RED3': '	',
  'UNMAINTAINED' : '<span class="unmaintained"'
};

window.body_ready = function() {
  var url_parts = window.location.href.split('?');
  if (url_parts[1]) {
    var query_parts = url_parts[1].split('&');
    $.each(query_parts, function(i, query_part) {
      key_val = query_part.split('=');
      key_val[1] = decodeURIComponent(key_val[1]);
      switch(key_val[0]) {
        case 'q': window.queries = key_val[1]; break;
        case 's': window.sort = key_val[1]; break;
        case 'r': window.reverse = key_val[1]; break;
      }
    });
  }
};

window.age_threshold_green = moment.duration(30, 'minutes');
window.age_threshold_yellow = moment.duration(1, 'days');

window.body_ready_with_age = function(age) {
  // Do age stuff
  $(document).ready(function() {
    $('.age p').replaceWith("
Page was generated:
" + age.humanize() + " ago
");
    if (age < window.age_threshold_green) {
      $('.age p').css('color', '#3c763d');
      $('.age').css('background-color', '#dff0d8');
      $('.age').css('border-color', '#d6e9c6');
    } else if (age < window.age_threshold_yellow) {
      $('.age p').css('color', '#8a6d3b');
      $('.age').css('background-color', '#fcf8e3');
      $('.age').css('border-color', '#faebcc');
    } else {
      $('.age p').css('color', '#a94442');
      $('.age').css('background-color', '#f2dede');
      $('.age').css('border-color', '#ebccd1');
    }
  });
  // Call normal "body_ready"
  return window.body_ready();
};

/* Counterpart to nth-child selectors—returns the number of the child that this
 * node is. eg, how many siblings preceed it. Do note that nth-child is 1-based,
 * while this function is zero based. */
function child_num(node) {
  return $.inArray(node, $(node).parent().children());
}

window.tbody_ready = function() {
  var table = $('table');

  // Populate the input box in the form.
  if (window.queries) {
    $('.search form input').val(window.queries.replace("+", " "));
  }

  // Hook up the event handler which fires when the input is changed.
  $('.search form input').on('input', function() {
    queries = $(this).val();
    window.filter_timeout && clearTimeout(window.filter_timeout);
    window.filter_timeout = setTimeout(function() {
      window.queries = queries;
      filter_table();
    }, 250);
  });

  // Disable submitting the form (eg, with an enter press).
  $('.search form').on('submit', function() { return false; });

  // Hook up click handlers to the keyword shortcuts.
  $('.search a').on('click', function(e) {
    e.preventDefault();
    var url_parts = $(this).attr('href').split('?');
    if (url_parts[1]) {
      var query_parts = url_parts[1].split('&');
      $.each(query_parts, function(i, query_part) {
        key_val = query_part.split('=');
        key_val[1] = decodeURIComponent(key_val[1]);
        if (key_val[0] == 'q') {
          window.queries = key_val[1];
        }
      });
    }
    $('.search form input').val(window.queries);
    filter_table();
  });

  // This mouseover handler wires up the tooltip and CI url in a JIT manner
  // when the mouse hovers on a version square. Critically important is that
  // there's only instance of this handler: on the tbody.
  // This is the "live" event pattern.
  $('tbody', table).on('mouseover', 'tr td:nth-child(n+' + (window.META_COLUMNS + 1) + ') a', function(e) {
    var a = $(this);
    var tr = a.closest('tr');
    var repo_num = child_num(this);
    var ver = a.text();
    if (!ver) {
      // If not included, then it's the same as the "latest", grab from that cell.
      ver = $('td:nth-child(' + window.VERSION_COLUMN + ')', tr).text();
      if (a.hasClass('m') || a.hasClass('i')) {
        // Unless this square is "missing" or "intentionally missing", in which case, it's None.
        ver = "None";
      }
    }
    a.attr('title', repos[repo_num] + ': ' + ver);
    if (repo_num === 0) {
      target_index = child_num(a.closest('td')[0]) - window.META_COLUMNS;
      if (window.job_url_templates.length > target_index) {
        var job_url = window.job_url_templates[target_index];
        var pkg_name_converted = $('td div', tr).text().split(' ')[0];
        if (!a.hasClass('i') && !a.hasClass('obs') ) {
          a.attr('href', job_url.replace('{pkg}', pkg_name_converted));
        }
      }
    }
  });

  /* CSS makes the original header in the document invisible. We create a clone of that
   * to be the "real" header, with the dimensions copied to the clone, and the clone alternatiing
   * between being position: absolute and position: fixed, depending on the scroll of the page. */
  var orig_header = $('thead', table);
  var header = orig_header.clone();
  header.addClass('floating').hide();
  $('table').prepend(header);
  // Insert spacer divs into the floating header to that it matches the
  // dimensions of the original table.
  $('th', header).each(function() {
    $(this).append($('

'));
  });
  $(window).on('resize', function() {
    // Resize the spacers to make the floating version match the original.
    $('th', header).each(function(i, el) {
      $('.spacer', this).css('width', $('tr th:nth-child(' + (i+1) + ')', orig_header).width());
    });
    header.show();
  });

  // This is an awkward race condition. The "better way" here would be to have the tfoot contain
  // dummy elements which lock the size of the table. Then the resize event could be triggered
  // immediately.
  setTimeout(function() {
    $(window).trigger('resize');
  }, 0);

  // When the page scrolls, check whether the header should be fixed or floating.
  var last_left = null;
  $(window).on('scroll', function() {
    if ($(window).scrollTop() > table.position().top) {
      // Fixed thead
      header.addClass('fixed');
      var left = window.scrollX;
      left = Math.max(left, 0);
      left = Math.min(left, Math.max(0, table.width() - document.documentElement.clientWidth));
      if (left != last_left) {
        header.css('left', -left);
        last_left = left;
      }
    } else {
      // Floating thead
      header.removeClass('fixed');
    }
  });

  // Hook up sort logic on click to table headers.
  $('th:nth-child(-n+' + window.META_COLUMNS + ')', header).on('click', function() {
    var sort = child_num(this) + 1;
    if (window.sort == sort) {
      window.reverse = window.reverse ? 0 : 1;
    } else {
      window.sort = sort;
      delete window.reverse;
    }
    filter_table();
  });

  /* If there is a load-time query string which will trigger an immediate
   * filter, hide the in-progress loading of the table. Deliberately do this
   * after the header cloning dingus above, so that the header dimensions are
   * correct. */
  if (window.queries || window.sort) {
    $('tbody').css('visibility', 'hidden');
    setTimeout(function() {
      $('tbody').css('visibility', 'visible');
      if (!$('tbody').data('body_done')) {
        $('tbody').hide();
      }
    }, 0);
  }
};

window.body_done = function() {
  if (window.queries || window.sort) {
    filter_table();
  } else {
    var count = $('tbody tr').length;
    $("#search-count").text("showing " + count + " of " + count + " total");
  }
  $('tbody').show();
  $('tbody').data('body_done', true);
};

function scan_rows() {
  // TODO: Potentially could make the initial load/search more responsive by having this
  // go in chunks, with timeouts in between.
  window.rows = [];
  $('table tbody tr').each(function() {
    // Add lowercased version of name (which is the last meta column) for faster case-insensitive search.
    var name_td = $('td:nth-child(' + window.META_COLUMNS + ')', this);
    if (name_td.text() && name_td.text().length > 0) {
      name_td.append(' ' + name_td.text().toLowerCase() + '');
    }
    var row_info = [$(this).html()];
    for (var i = 1; i <= window.META_COLUMNS; i++) {
      var td = $("td:nth-child(" + i + ")", this);
      var sort_text = td.text();
      if (sort_text === '') sort_text = td.html();
      row_info.push(sort_text);
    }
    window.rows.push(row_info);
  });
  console.log("Total rows found: " + window.rows.length);
}

function filter_table() {
  // One time setup, to build up the array of row contents combined with sortable fields.
  if (!window.rows) { scan_rows(); }

  // If query provided, copy only the matching rows to the result set.
  // It not, just use the original. It gets mangled when sorting, but that's okay.
  var result_rows;
  if (window.queries) {
    var queries = window.queries.split("+");
    queries = $.map(queries, function(q) {
      // Disregard short terms.
      if (q.length < 3) return null;

      // Transform "magic" queries as necessary.
      return QUERY_TRANSFORMS[q] || q;
    });

    if (window.previous_queries && window.previous_queries.toString() == queries.toString() &&
        window.previous_sort == window.sort &&
        window.previous_reverse == window.reverse) {
      console.log("No change, skipping rebuilding table.");
      return;
    } else {
      window.previous_queries = queries;
      window.previous_sort = window.sort;
      window.previous_reverse = window.reverse;
    }

    if (queries.length > 0) {
      console.log("Filtering for queries:", queries);
      result_rows = $.map(window.rows, function(row) {
        for (var i = 0; i < queries.length; i++) {
          var is_known_query = false;
          for (var q in QUERY_TRANSFORMS) {
            if (RegExp("^("+QUERY_TRANSFORMS[q]+")$").test(queries[i])) {
              is_known_query = true;
              break;
            }
          }
          if (is_known_query) {
            // search in full row html
            if (row[0].indexOf(queries[i]) == -1) return null;
          } else {
            // search in plain text of each column
            match = false;
            for (var j = 1; j < row.length; j++) {
              if (row[j] && row[j].indexOf(queries[i]) != -1) {
                match = true;
                break;
              }
            }
            if (!match) return null;
          }
        }
        return [row];
      });
    } else {
      console.log("No query terms, returning whole set.");
      result_rows = window.rows;
    }
  } else {
    console.log("No query, returning whole set.");
    result_rows = window.rows;
  }

  console.log("Result rows found: " + result_rows.length);
  $("#search-count").text("showing " + result_rows.length + " of " + rows.length + " total");

  if (window.sort) {
    var sort = parseInt(window.sort);
    var order = 1;
    if (window.reverse == 1) order = -1;
    // temporary store index of each row
    for (var i = 0; i < result_rows.length; ++i) {
      result_rows[i].push(i);
    }
    result_rows.sort(function(a, b) {
      var val1 = a[sort];
      var val2 = b[sort];

      // Convert strings to floats if appropriate
      var val1_float = parseFloat(val1);
      var val2_float = parseFloat(val2);
      if (val1 == val1_float) val1 = val1_float;
      if (val2 == val2_float) val2 = val2_float;

      if (val1 > val2) return order;
      if (val1 < val2) return -order;

      // emulate stable sorting by considering the previous index of each row
      val1 = a[a.length - 1];
      val2 = b[b.length - 1];
      if (val1 > val2) return 1;
      if (val1 < val2) return -1;
      return 0;  // this should never be the case
    });
    // remove temporary index from each row
    for (var i = 0; i < result_rows.length; ++i) {
      result_rows[i].pop();
    }
  }

  var result_rows_plain = $.map(result_rows, function(row) { return row[0]; });

  // It's still a nasty rendering pause as the browser crunches through this. A possible
  // future optimization would be to have multiple tbody elements, chunk up the resulting
  // rows, and load them in in batches, separated by zero timeouts.
  $('table tbody').html("

" + result_rows_plain.join("

") + "
");

  if (window.history && window.history.replaceState) {
    var qs = [];
    if (window.queries) qs.push("q=" + encodeURIComponent(window.queries));
    if (window.sort) qs.push("s=" + encodeURIComponent(window.sort));
    if (window.reverse) qs.push("r=" + encodeURIComponent(window.reverse));
    var url = document.location.origin + document.location.pathname;
    if (qs.length > 0) {
      url += "?" + qs.join("&");
    }
    try {
      window.history.replaceState({}, document.title, url);
    } catch (e) {
      // ignore potential SecurityError when using file:// url
      console.log("Attempted to change URL to: " + url);
    }
  }
}

<commit_msg>support OR syntax (#436)<commit_after>var QUERY_TRANSFORMS = {
  'BLUE': 'class="l"',
  'ORANGE': 'class="h"',
  'RED': '',
  'YELLOW': 'class="o"',
  'GRAY': '',
  'RED1': '',
  'RED2': '<a',
  'RED3': '	',
  'UNMAINTAINED' : '<span class="unmaintained"'
};

window.body_ready = function() {
  var url_parts = window.location.href.split('?');
  if (url_parts[1]) {
    var query_parts = url_parts[1].split('&');
    $.each(query_parts, function(i, query_part) {
      key_val = query_part.split('=');
      key_val[1] = decodeURIComponent(key_val[1]);
      switch(key_val[0]) {
        case 'q': window.queries = key_val[1]; break;
        case 's': window.sort = key_val[1]; break;
        case 'r': window.reverse = key_val[1]; break;
      }
    });
  }
};

window.age_threshold_green = moment.duration(30, 'minutes');
window.age_threshold_yellow = moment.duration(1, 'days');

window.body_ready_with_age = function(age) {
  // Do age stuff
  $(document).ready(function() {
    $('.age p').replaceWith("
Page was generated:
" + age.humanize() + " ago
");
    if (age < window.age_threshold_green) {
      $('.age p').css('color', '#3c763d');
      $('.age').css('background-color', '#dff0d8');
      $('.age').css('border-color', '#d6e9c6');
    } else if (age < window.age_threshold_yellow) {
      $('.age p').css('color', '#8a6d3b');
      $('.age').css('background-color', '#fcf8e3');
      $('.age').css('border-color', '#faebcc');
    } else {
      $('.age p').css('color', '#a94442');
      $('.age').css('background-color', '#f2dede');
      $('.age').css('border-color', '#ebccd1');
    }
  });
  // Call normal "body_ready"
  return window.body_ready();
};

/* Counterpart to nth-child selectors—returns the number of the child that this
 * node is. eg, how many siblings preceed it. Do note that nth-child is 1-based,
 * while this function is zero based. */
function child_num(node) {
  return $.inArray(node, $(node).parent().children());
}

window.tbody_ready = function() {
  var table = $('table');

  // Populate the input box in the form.
  if (window.queries) {
    $('.search form input').val(window.queries.replace("+", " "));
  }

  // Hook up the event handler which fires when the input is changed.
  $('.search form input').on('input', function() {
    queries = $(this).val();
    window.filter_timeout && clearTimeout(window.filter_timeout);
    window.filter_timeout = setTimeout(function() {
      window.queries = queries;
      filter_table();
    }, 250);
  });

  // Disable submitting the form (eg, with an enter press).
  $('.search form').on('submit', function() { return false; });

  // Hook up click handlers to the keyword shortcuts.
  $('.search a').on('click', function(e) {
    e.preventDefault();
    var url_parts = $(this).attr('href').split('?');
    if (url_parts[1]) {
      var query_parts = url_parts[1].split('&');
      $.each(query_parts, function(i, query_part) {
        key_val = query_part.split('=');
        key_val[1] = decodeURIComponent(key_val[1]);
        if (key_val[0] == 'q') {
          window.queries = key_val[1];
        }
      });
    }
    $('.search form input').val(window.queries);
    filter_table();
  });

  // This mouseover handler wires up the tooltip and CI url in a JIT manner
  // when the mouse hovers on a version square. Critically important is that
  // there's only instance of this handler: on the tbody.
  // This is the "live" event pattern.
  $('tbody', table).on('mouseover', 'tr td:nth-child(n+' + (window.META_COLUMNS + 1) + ') a', function(e) {
    var a = $(this);
    var tr = a.closest('tr');
    var repo_num = child_num(this);
    var ver = a.text();
    if (!ver) {
      // If not included, then it's the same as the "latest", grab from that cell.
      ver = $('td:nth-child(' + window.VERSION_COLUMN + ')', tr).text();
      if (a.hasClass('m') || a.hasClass('i')) {
        // Unless this square is "missing" or "intentionally missing", in which case, it's None.
        ver = "None";
      }
    }
    a.attr('title', repos[repo_num] + ': ' + ver);
    if (repo_num === 0) {
      target_index = child_num(a.closest('td')[0]) - window.META_COLUMNS;
      if (window.job_url_templates.length > target_index) {
        var job_url = window.job_url_templates[target_index];
        var pkg_name_converted = $('td div', tr).text().split(' ')[0];
        if (!a.hasClass('i') && !a.hasClass('obs') ) {
          a.attr('href', job_url.replace('{pkg}', pkg_name_converted));
        }
      }
    }
  });

  /* CSS makes the original header in the document invisible. We create a clone of that
   * to be the "real" header, with the dimensions copied to the clone, and the clone alternatiing
   * between being position: absolute and position: fixed, depending on the scroll of the page. */
  var orig_header = $('thead', table);
  var header = orig_header.clone();
  header.addClass('floating').hide();
  $('table').prepend(header);
  // Insert spacer divs into the floating header to that it matches the
  // dimensions of the original table.
  $('th', header).each(function() {
    $(this).append($('

'));
  });
  $(window).on('resize', function() {
    // Resize the spacers to make the floating version match the original.
    $('th', header).each(function(i, el) {
      $('.spacer', this).css('width', $('tr th:nth-child(' + (i+1) + ')', orig_header).width());
    });
    header.show();
  });

  // This is an awkward race condition. The "better way" here would be to have the tfoot contain
  // dummy elements which lock the size of the table. Then the resize event could be triggered
  // immediately.
  setTimeout(function() {
    $(window).trigger('resize');
  }, 0);

  // When the page scrolls, check whether the header should be fixed or floating.
  var last_left = null;
  $(window).on('scroll', function() {
    if ($(window).scrollTop() > table.position().top) {
      // Fixed thead
      header.addClass('fixed');
      var left = window.scrollX;
      left = Math.max(left, 0);
      left = Math.min(left, Math.max(0, table.width() - document.documentElement.clientWidth));
      if (left != last_left) {
        header.css('left', -left);
        last_left = left;
      }
    } else {
      // Floating thead
      header.removeClass('fixed');
    }
  });

  // Hook up sort logic on click to table headers.
  $('th:nth-child(-n+' + window.META_COLUMNS + ')', header).on('click', function() {
    var sort = child_num(this) + 1;
    if (window.sort == sort) {
      window.reverse = window.reverse ? 0 : 1;
    } else {
      window.sort = sort;
      delete window.reverse;
    }
    filter_table();
  });

  /* If there is a load-time query string which will trigger an immediate
   * filter, hide the in-progress loading of the table. Deliberately do this
   * after the header cloning dingus above, so that the header dimensions are
   * correct. */
  if (window.queries || window.sort) {
    $('tbody').css('visibility', 'hidden');
    setTimeout(function() {
      $('tbody').css('visibility', 'visible');
      if (!$('tbody').data('body_done')) {
        $('tbody').hide();
      }
    }, 0);
  }
};

window.body_done = function() {
  if (window.queries || window.sort) {
    filter_table();
  } else {
    var count = $('tbody tr').length;
    $("#search-count").text("showing " + count + " of " + count + " total");
  }
  $('tbody').show();
  $('tbody').data('body_done', true);
};

function scan_rows() {
  // TODO: Potentially could make the initial load/search more responsive by having this
  // go in chunks, with timeouts in between.
  window.rows = [];
  $('table tbody tr').each(function() {
    // Add lowercased version of name (which is the last meta column) for faster case-insensitive search.
    var name_td = $('td:nth-child(' + window.META_COLUMNS + ')', this);
    if (name_td.text() && name_td.text().length > 0) {
      name_td.append(' ' + name_td.text().toLowerCase() + '');
    }
    var row_info = [$(this).html()];
    for (var i = 1; i <= window.META_COLUMNS; i++) {
      var td = $("td:nth-child(" + i + ")", this);
      var sort_text = td.text();
      if (sort_text === '') sort_text = td.html();
      row_info.push(sort_text);
    }
    window.rows.push(row_info);
  });
  console.log("Total rows found: " + window.rows.length);
}

function filter_table() {
  // One time setup, to build up the array of row contents combined with sortable fields.
  if (!window.rows) { scan_rows(); }

  // If query provided, copy only the matching rows to the result set.
  // It not, just use the original. It gets mangled when sorting, but that's okay.
  var result_rows;
  if (window.queries) {
    var queries = window.queries.split("+");
    queries = $.map(queries, function(q) {
      // Disregard short terms.
      if (q.length < 3) return null;

      // Transform "magic" queries as necessary.
      return QUERY_TRANSFORMS[q] || q;
    });

    if (window.previous_queries && window.previous_queries.toString() == queries.toString() &&
        window.previous_sort == window.sort &&
        window.previous_reverse == window.reverse) {
      console.log("No change, skipping rebuilding table.");
      return;
    } else {
      window.previous_queries = queries;
      window.previous_sort = window.sort;
      window.previous_reverse = window.reverse;
    }

    if (queries.length > 0) {
      console.log("Filtering for queries:", queries);
      result_rows = $.map(window.rows, function(row) {
        for (var i = 0; i < queries.length; i++) {
          var is_known_query = false;
          for (var q in QUERY_TRANSFORMS) {
            // need to escape RegExp characters, for example |
            if (RegExp("^("+escape(QUERY_TRANSFORMS[q])+")$").test(escape(queries[i]))) {
              is_known_query = true;
              break;
            }
          }
          if (is_known_query) {
            // search in full row html
            if (! RegExp(queries[i]).test(row[0])) return null;
          } else {
            // search in plain text of each column
            match = false;
            for (var j = 1; j < row.length; j++) {
              if (row[j] && RegExp(queries[i]).test(row[j])) {
                match = true;
                break;
              }
            }
            if (!match) return null;
          }
        }
        return [row];
      });
    } else {
      console.log("No query terms, returning whole set.");
      result_rows = window.rows;
    }
  } else {
    console.log("No query, returning whole set.");
    result_rows = window.rows;
  }

  console.log("Result rows found: " + result_rows.length);
  $("#search-count").text("showing " + result_rows.length + " of " + rows.length + " total");

  if (window.sort) {
    var sort = parseInt(window.sort);
    var order = 1;
    if (window.reverse == 1) order = -1;
    // temporary store index of each row
    for (var i = 0; i < result_rows.length; ++i) {
      result_rows[i].push(i);
    }
    result_rows.sort(function(a, b) {
      var val1 = a[sort];
      var val2 = b[sort];

      // Convert strings to floats if appropriate
      var val1_float = parseFloat(val1);
      var val2_float = parseFloat(val2);
      if (val1 == val1_float) val1 = val1_float;
      if (val2 == val2_float) val2 = val2_float;

      if (val1 > val2) return order;
      if (val1 < val2) return -order;

      // emulate stable sorting by considering the previous index of each row
      val1 = a[a.length - 1];
      val2 = b[b.length - 1];
      if (val1 > val2) return 1;
      if (val1 < val2) return -1;
      return 0;  // this should never be the case
    });
    // remove temporary index from each row
    for (var i = 0; i < result_rows.length; ++i) {
      result_rows[i].pop();
    }
  }

  var result_rows_plain = $.map(result_rows, function(row) { return row[0]; });

  // It's still a nasty rendering pause as the browser crunches through this. A possible
  // future optimization would be to have multiple tbody elements, chunk up the resulting
  // rows, and load them in in batches, separated by zero timeouts.
  $('table tbody').html("

" + result_rows_plain.join("

") + "
");

  if (window.history && window.history.replaceState) {
    var qs = [];
    if (window.queries) qs.push("q=" + encodeURIComponent(window.queries));
    if (window.sort) qs.push("s=" + encodeURIComponent(window.sort));
    if (window.reverse) qs.push("r=" + encodeURIComponent(window.reverse));
    var url = document.location.origin + document.location.pathname;
    if (qs.length > 0) {
      url += "?" + qs.join("&");
    }
    try {
      window.history.replaceState({}, document.title, url);
    } catch (e) {
      // ignore potential SecurityError when using file:// url
      console.log("Attempted to change URL to: " + url);
    }
  }
}

<|endoftext|>