content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
fix a bug when charge forces are zero
612d23780c6eae7095d0c338edabacf909ab0932
<ide><path>d3.layout.js <ide> d3.layout.force = function() { <ide> node.py -= dy * k; <ide> } <ide> } <add> return !quad.charge; <ide> }; <ide> } <ide> <ide><path>d3.layout.min.js <del>(function(){function bc(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0);return{x:c,y:d,dx:e,dy:f}}function bb(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function ba(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function _(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function $(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function Z(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function Y(a,b){return a.depth-b.depth}function X(a,b){return b.x-a.x}function W(a,b){return a.x-b.x}function V(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=V(c[f],b),a)>0&&(a=d)}return a}function U(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function T(a){return a.children?a.children[0]:a._tree.thread}function S(a,b){return a.parent==b.parent?1:2}function R(a){var b=a.children,c;return b&&(c=b.length)?R(b[c-1]):a}function Q(a){var b=a.children;return b&&b.length?Q(b[0]):a}function P(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function O(a){return 1+d3.max(a,function(a){return a.y})}function N(a,b,c){var d=a.r+c.r,e=b.x-a.x,f=b.y-a.y;if(d&&(e||f)){var g=b.r+c.r,h=Math.sqrt(e*e+f*f),i=Math.max(-1,Math.min(1,(d*d+h*h-g*g)/(2*d*h))),j=Math.acos(i),k=i*(d/=h),l=Math.sin(j)*d;c.x=a.x+k*e+l*f,c.y=a.y+k*f-l*e}else c.x=a.x+d,c.y=a.y}function M(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)M(e[f],b,c,d)}}function L(a){var b=a.children;b&&b.length?(b.forEach(L),a.r=I(b)):a.r=Math.sqrt(a.value)}function K(a){delete a._pack_next,delete a._pack_prev}function J(a){a._pack_next=a._pack_prev=a}function I(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(J),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],N(g,h,i),l(i),F(g,i),g._pack_prev=i,F(i,h),h=g._pack_next;for(var m=3;m<f;m++){N(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(H(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(H(k,i)){p<o&&(n=-1,j=k);break}n==0?(F(g,i),h=i,l(i)):n>0?(G(g,j),h=j,m--):(G(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(K);return s}function H(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function G(a,b){a._pack_next=b,b._pack_prev=a}function F(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function E(a,b){return a.value-b.value}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a,b){return b.value-a.value}function A(a){return a.value}function z(a){return a.children}function y(a,b){a.sort=d3.rebind(a,b.sort),a.children=d3.rebind(a,b.children),a.links=C,a.value=d3.rebind(a,b.value),a.nodes=function(b){D=!0;return(a.nodes=a)(b)};return a}function x(a){return[d3.min(a),d3.max(a)]}function w(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function v(a,b){return w(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function u(a,b){return a+b[1]}function t(a){return a.reduce(u,0)}function s(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function p(a,b,c){a.y0=b,a.y=c}function o(a){return a.y}function n(a){return a.x}function m(a){return 1}function l(a){return 20}function k(a,b,c){var d=0,e=0;a.charge=0;if(!a.leaf){var f=a.nodes,g=f.length,h=-1,i;while(++h<g){i=f[h];if(i==null)continue;k(i,b,c),a.charge+=i.charge,d+=i.charge*i.cx,e+=i.charge*i.cy}}if(a.point){a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5);var j=b*c[a.point.index];a.charge+=a.pointCharge=j,d+=j*a.point.x,e+=j*a.point.y}a.cx=d/a.charge,a.cy=e/a.charge}function j(){f.px+=d3.event.dx,f.py+=d3.event.dy,e.resume()}function i(){j(),f.fixed&=1,e=f=null}function h(a){a!==f&&(a.fixed&=1)}function g(a){a.fixed|=2}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;b.push(a);return b}function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function k(){b.sort(function(a,b){return i(a.target.value,b.target.value)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push(v.value<w.value?{source:w,target:v}:{source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function C(b){g(f=b),e=a}function B(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(r){k(e=d3.geom.quadtree(v),n,z),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(A(g))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);b.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function A(a){return function(b,c,d,e,f){if(b.point!==a){var g=b.cx-a.x,h=b.cy-a.y,i=1/Math.sqrt(g*g+h*h);if((e-c)*i<t){var j=b.charge*i*i;a.px-=g*j,a.py-=h*j;return!0}if(b.point&&isFinite(i)){var j=b.pointCharge*i*i;a.px-=g*j,a.py-=h*j}}}}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y,z;a.on=function(c,d){b[c].add(d);return a},a.nodes=function(b){if(!arguments.length)return v;v=b;return a},a.links=function(b){if(!arguments.length)return w;w=b;return a},a.size=function(b){if(!arguments.length)return c;c=b;return a},a.linkDistance=function(b){if(!arguments.length)return p;p=d3.functor(b);return a},a.distance=a.linkDistance,a.linkStrength=function(b){if(!arguments.length)return q;q=d3.functor(b);return a},a.friction=function(b){if(!arguments.length)return o;o=b;return a},a.charge=function(b){if(!arguments.length)return r;r=typeof b=="function"?b:+b;return a},a.gravity=function(b){if(!arguments.length)return s;s=b;return a},a.theta=function(b){if(!arguments.length)return t;t=b;return a},a.start=function(){function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);z=[];if(typeof r=="function")for(b=0;b<e;++b)z[b]=+r.call(this,v[b],b);else for(b=0;b<e;++b)z[b]=r;return a.resume()},a.resume=function(){n=.1,d3.timer(B);return a},a.stop=function(){n=0;return a},a.drag=function(){d||(d=d3.behavior.drag().on("dragstart",C).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)};return a};var e,f;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.size=function(a){if(!arguments.length)return b;b=a;return e};return y(e,a)},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{data:f[a],value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=q["default"],c=r.zero,d=p,e=n,f=o;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:q[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:r[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var q={"inside-out":function(a){var b=a.length,c,d,e=a.map(s),f=a.map(t),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},r={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=x,d=v;e.value=function(a){if(!arguments.length)return b;b=a;return e},e.range=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.bins=function(a){if(!arguments.length)return d;d=typeof a=="number"?function(b){return w(b,a)}:d3.functor(a);return e},e.frequency=function(b){if(!arguments.length)return a;a=!!b;return e};return e},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d&&(i=d.length)){var h=-1,i,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,D?a:a.data,b)||0);c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k=D?f:{data:f};k.depth=h,i.push(k);if(j&&(m=j.length)){var l=-1,m,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}var a=B,b=z,c=A;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g};var D=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,L(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);M(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy().sort(E),b=[1,1];c.size=function(a){if(!arguments.length)return b;b=a;return c};return y(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;Z(g,function(a){var c=a.children;c&&c.length?(a.x=P(c),a.y=O(c)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=Q(g),m=R(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=U(g),e=T(e),g&&e)h=T(h),f=U(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(_(ba(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!U(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!T(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;$(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];Z(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=V(g,X),l=V(g,W),m=V(g,Y),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.treemap=function(){function n(b){var d=g||a(b),e=d[0];e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d);return d}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=j?d.dy:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=j?b(k.area/j):0;k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=j?d.dx:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=j?b(k.area/j):0;k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}c*=c,b*=b;return c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function k(a){if(!!a.children){var b=e(a),c=a.children.slice(),d,f=[];i(c,b.dx*b.dy/a.value),f.area=0;while(d=c.pop())f.push(d),f.area+=d.area,d.z!=null&&(m(f,d.z?b.dx:b.dy,b,!c.length),f.length=f.area=0);a.children.forEach(k)}}function j(a){if(!!a.children){var b=e(a),c=[],d=a.children.slice(),f,g=Infinity,h,k=Math.min(b.dx,b.dy),n;i(d,b.dx*b.dy/a.value),c.area=0;while((n=d.length)>0)c.push(f=d[n-1]),c.area+=f.area,(h=l(c,k))<=g?(d.pop(),g=h):(c.area-=c.pop().area,m(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,g=Infinity);c.length&&(m(c,k,b,!0),c.length=c.area=0),a.children.forEach(j)}}function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bb,f=!1,g,h=.5*(1+Math.sqrt(5));n.size=function(a){if(!arguments.length)return c;c=a;return n},n.padding=function(a){function c(b){return bc(b,a)}function b(b){var c=a.call(n,b,b.depth);return c==null?bb(b):bc(b,typeof c=="number"?[c,c,c,c]:c)}if(!arguments.length)return d;var f;e=(d=a)==null?bb:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c;return n},n.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return n},n.sticky=function(a){if(!arguments.length)return f;f=a,g=null;return n},n.ratio=function(a){if(!arguments.length)return h;h=a;return n};return y(n,a)}})() <ide>\ No newline at end of file <add>(function(){function bc(a,b){var c=a.x+b[3],d=a.y+b[0],e=a.dx-b[1]-b[3],f=a.dy-b[0]-b[2];e<0&&(c+=e/2,e=0),f<0&&(d+=f/2,f=0);return{x:c,y:d,dx:e,dy:f}}function bb(a){return{x:a.x,y:a.y,dx:a.dx,dy:a.dy}}function ba(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function _(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function $(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function Z(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function Y(a,b){return a.depth-b.depth}function X(a,b){return b.x-a.x}function W(a,b){return a.x-b.x}function V(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=V(c[f],b),a)>0&&(a=d)}return a}function U(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function T(a){return a.children?a.children[0]:a._tree.thread}function S(a,b){return a.parent==b.parent?1:2}function R(a){var b=a.children,c;return b&&(c=b.length)?R(b[c-1]):a}function Q(a){var b=a.children;return b&&b.length?Q(b[0]):a}function P(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function O(a){return 1+d3.max(a,function(a){return a.y})}function N(a,b,c){var d=a.r+c.r,e=b.x-a.x,f=b.y-a.y;if(d&&(e||f)){var g=b.r+c.r,h=Math.sqrt(e*e+f*f),i=Math.max(-1,Math.min(1,(d*d+h*h-g*g)/(2*d*h))),j=Math.acos(i),k=i*(d/=h),l=Math.sin(j)*d;c.x=a.x+k*e+l*f,c.y=a.y+k*f-l*e}else c.x=a.x+d,c.y=a.y}function M(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)M(e[f],b,c,d)}}function L(a){var b=a.children;b&&b.length?(b.forEach(L),a.r=I(b)):a.r=Math.sqrt(a.value)}function K(a){delete a._pack_next,delete a._pack_prev}function J(a){a._pack_next=a._pack_prev=a}function I(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(J),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],N(g,h,i),l(i),F(g,i),g._pack_prev=i,F(i,h),h=g._pack_next;for(var m=3;m<f;m++){N(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(H(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(H(k,i)){p<o&&(n=-1,j=k);break}n==0?(F(g,i),h=i,l(i)):n>0?(G(g,j),h=j,m--):(G(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(K);return s}function H(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function G(a,b){a._pack_next=b,b._pack_prev=a}function F(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function E(a,b){return a.value-b.value}function C(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function B(a,b){return b.value-a.value}function A(a){return a.value}function z(a){return a.children}function y(a,b){a.sort=d3.rebind(a,b.sort),a.children=d3.rebind(a,b.children),a.links=C,a.value=d3.rebind(a,b.value),a.nodes=function(b){D=!0;return(a.nodes=a)(b)};return a}function x(a){return[d3.min(a),d3.max(a)]}function w(a,b){var c=-1,d=+a[0],e=(a[1]-d)/b,f=[];while(++c<=b)f[c]=e*c+d;return f}function v(a,b){return w(a,Math.ceil(Math.log(b.length)/Math.LN2+1))}function u(a,b){return a+b[1]}function t(a){return a.reduce(u,0)}function s(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function p(a,b,c){a.y0=b,a.y=c}function o(a){return a.y}function n(a){return a.x}function m(a){return 1}function l(a){return 20}function k(a,b,c){var d=0,e=0;a.charge=0;if(!a.leaf){var f=a.nodes,g=f.length,h=-1,i;while(++h<g){i=f[h];if(i==null)continue;k(i,b,c),a.charge+=i.charge,d+=i.charge*i.cx,e+=i.charge*i.cy}}if(a.point){a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5);var j=b*c[a.point.index];a.charge+=a.pointCharge=j,d+=j*a.point.x,e+=j*a.point.y}a.cx=d/a.charge,a.cy=e/a.charge}function j(){f.px+=d3.event.dx,f.py+=d3.event.dy,e.resume()}function i(){j(),f.fixed&=1,e=f=null}function h(a){a!==f&&(a.fixed&=1)}function g(a){a.fixed|=2}function c(a,c){if(a===c)return a;var d=b(a),e=b(c),f=d.pop(),g=e.pop(),h=null;while(f===g)h=f,f=d.pop(),g=e.pop();return h}function b(a){var b=[],c=a.parent;while(c!=null)b.push(a),a=c,c=c.parent;b.push(a);return b}function a(a){var b=a.source,d=a.target,e=c(b,d),f=[b];while(b!==e)b=b.parent,f.push(b);var g=f.length;while(d!==e)f.splice(g,0,d),d=d.parent;return f}d3.layout={},d3.layout.bundle=function(){return function(b){var c=[],d=-1,e=b.length;while(++d<e)c.push(a(b[d]));return c}},d3.layout.chord=function(){function k(){b.sort(function(a,b){return i(a.target.value,b.target.value)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push(v.value<w.value?{source:w,target:v}:{source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function C(b){g(f=b),e=a}function B(){var a=v.length,d=w.length,e,f,g,h,i,j,l,m,p;for(f=0;f<d;++f){g=w[f],h=g.source,i=g.target,m=i.x-h.x,p=i.y-h.y;if(j=m*m+p*p)j=n*y[f]*((j=Math.sqrt(j))-x[f])/j,m*=j,p*=j,i.x-=m*(l=h.weight/(i.weight+h.weight)),i.y-=p*l,h.x+=m*(l=1-l),h.y+=p*l}if(l=n*s){m=c[0]/2,p=c[1]/2,f=-1;if(l)while(++f<a)g=v[f],g.x+=(m-g.x)*l,g.y+=(p-g.y)*l}if(r){k(e=d3.geom.quadtree(v),n,z),f=-1;while(++f<a)(g=v[f]).fixed||e.visit(A(g))}f=-1;while(++f<a)g=v[f],g.fixed?(g.x=g.px,g.y=g.py):(g.x-=(g.px-(g.px=g.x))*o,g.y-=(g.py-(g.py=g.y))*o);b.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function A(a){return function(b,c,d,e,f){if(b.point!==a){var g=b.cx-a.x,h=b.cy-a.y,i=1/Math.sqrt(g*g+h*h);if((e-c)*i<t){var j=b.charge*i*i;a.px-=g*j,a.py-=h*j;return!0}if(b.point&&isFinite(i)){var j=b.pointCharge*i*i;a.px-=g*j,a.py-=h*j}}return!b.charge}}var a={},b=d3.dispatch("tick"),c=[1,1],d,n,o=.9,p=l,q=m,r=-30,s=.1,t=.8,u,v=[],w=[],x,y,z;a.on=function(c,d){b[c].add(d);return a},a.nodes=function(b){if(!arguments.length)return v;v=b;return a},a.links=function(b){if(!arguments.length)return w;w=b;return a},a.size=function(b){if(!arguments.length)return c;c=b;return a},a.linkDistance=function(b){if(!arguments.length)return p;p=d3.functor(b);return a},a.distance=a.linkDistance,a.linkStrength=function(b){if(!arguments.length)return q;q=d3.functor(b);return a},a.friction=function(b){if(!arguments.length)return o;o=b;return a},a.charge=function(b){if(!arguments.length)return r;r=typeof b=="function"?b:+b;return a},a.gravity=function(b){if(!arguments.length)return s;s=b;return a},a.theta=function(b){if(!arguments.length)return t;t=b;return a},a.start=function(){function l(){if(!i){i=[];for(d=0;d<e;++d)i[d]=[];for(d=0;d<f;++d){var a=w[d];i[a.source.index].push(a.target),i[a.target.index].push(a.source)}}return i[b]}function k(a,c){var d=l(b),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][a]))return g;return Math.random()*c}var b,d,e=v.length,f=w.length,g=c[0],h=c[1],i,j;for(b=0;b<e;++b)(j=v[b]).index=b,j.weight=0;x=[],y=[];for(b=0;b<f;++b)j=w[b],typeof j.source=="number"&&(j.source=v[j.source]),typeof j.target=="number"&&(j.target=v[j.target]),x[b]=p.call(this,j,b),y[b]=q.call(this,j,b),++j.source.weight,++j.target.weight;for(b=0;b<e;++b)j=v[b],isNaN(j.x)&&(j.x=k("x",g)),isNaN(j.y)&&(j.y=k("y",h)),isNaN(j.px)&&(j.px=j.x),isNaN(j.py)&&(j.py=j.y);z=[];if(typeof r=="function")for(b=0;b<e;++b)z[b]=+r.call(this,v[b],b);else for(b=0;b<e;++b)z[b]=r;return a.resume()},a.resume=function(){n=.1,d3.timer(B);return a},a.stop=function(){n=0;return a},a.drag=function(){d||(d=d3.behavior.drag().on("dragstart",C).on("drag",j).on("dragend",i)),this.on("mouseover.force",g).on("mouseout.force",h).call(d)};return a};var e,f;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d=a.value?d/a.value:0;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.size=function(a){if(!arguments.length)return b;b=a;return e};return y(e,a)},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{data:f[a],value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=q["default"],c=r.zero,d=p,e=n,f=o;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:q[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:r[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var q={"inside-out":function(a){var b=a.length,c,d,e=a.map(s),f=a.map(t),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},r={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.histogram=function(){function e(e,f){var g=[],h=e.map(b,this),i=c.call(this,h,f),j=d.call(this,i,h,f),k,f=-1,l=h.length,m=j.length-1,n=a?1:1/l,o;while(++f<m)k=g[f]=[],k.dx=j[f+1]-(k.x=j[f]),k.y=0;f=-1;while(++f<l)o=h[f],o>=i[0]&&o<=i[1]&&(k=g[d3.bisect(j,o,1,m)-1],k.y+=n,k.push(e[f]));return g}var a=!0,b=Number,c=x,d=v;e.value=function(a){if(!arguments.length)return b;b=a;return e},e.range=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.bins=function(a){if(!arguments.length)return d;d=typeof a=="number"?function(b){return w(b,a)}:d3.functor(a);return e},e.frequency=function(b){if(!arguments.length)return a;a=!!b;return e};return e},d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d&&(i=d.length)){var h=-1,i,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=+c.call(g,D?a:a.data,b)||0);c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k=D?f:{data:f};k.depth=h,i.push(k);if(j&&(m=j.length)){var l=-1,m,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=+c.call(g,f,h)||0);return k}var a=B,b=z,c=A;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g};var D=!1;d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,L(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);M(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy().sort(E),b=[1,1];c.size=function(a){if(!arguments.length)return b;b=a;return c};return y(c,a)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;Z(g,function(a){var c=a.children;c&&c.length?(a.x=P(c),a.y=O(c)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=Q(g),m=R(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=U(g),e=T(e),g&&e)h=T(h),f=U(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(_(ba(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!U(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!T(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d&&(f=d.length)){var f,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;$(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];Z(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=V(g,X),l=V(g,W),m=V(g,Y),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth||1;Z(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=S,c=[1,1];d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return y(d,a)},d3.layout.treemap=function(){function n(b){var d=g||a(b),e=d[0];e.x=0,e.y=0,e.dx=c[0],e.dy=c[1],g&&a.revalue(e),i([e],e.dx*e.dy/e.value),(g?k:j)(e),f&&(g=d);return d}function m(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=j?d.dy:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=j?b(k.area/j):0;k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=j?d.dx:0;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=j?b(k.area/j):0;k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function l(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,i=a.length;while(++g<i){if(!(d=a[g].area))continue;d<f&&(f=d),d>e&&(e=d)}c*=c,b*=b;return c?Math.max(b*e*h/c,c/(b*f*h)):Infinity}function k(a){if(!!a.children){var b=e(a),c=a.children.slice(),d,f=[];i(c,b.dx*b.dy/a.value),f.area=0;while(d=c.pop())f.push(d),f.area+=d.area,d.z!=null&&(m(f,d.z?b.dx:b.dy,b,!c.length),f.length=f.area=0);a.children.forEach(k)}}function j(a){if(!!a.children){var b=e(a),c=[],d=a.children.slice(),f,g=Infinity,h,k=Math.min(b.dx,b.dy),n;i(d,b.dx*b.dy/a.value),c.area=0;while((n=d.length)>0)c.push(f=d[n-1]),c.area+=f.area,(h=l(c,k))<=g?(d.pop(),g=h):(c.area-=c.pop().area,m(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,g=Infinity);c.length&&(m(c,k,b,!0),c.length=c.area=0),a.children.forEach(j)}}function i(a,b){var c=-1,d=a.length,e,f;while(++c<d)f=(e=a[c]).value*(b<0?0:b),e.area=isNaN(f)||f<=0?0:f}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=null,e=bb,f=!1,g,h=.5*(1+Math.sqrt(5));n.size=function(a){if(!arguments.length)return c;c=a;return n},n.padding=function(a){function c(b){return bc(b,a)}function b(b){var c=a.call(n,b,b.depth);return c==null?bb(b):bc(b,typeof c=="number"?[c,c,c,c]:c)}if(!arguments.length)return d;var f;e=(d=a)==null?bb:(f=typeof a)==="function"?b:f==="number"?(a=[a,a,a,a],c):c;return n},n.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return n},n.sticky=function(a){if(!arguments.length)return f;f=a,g=null;return n},n.ratio=function(a){if(!arguments.length)return h;h=a;return n};return y(n,a)}})() <ide>\ No newline at end of file <ide><path>src/layout/force.js <ide> d3.layout.force = function() { <ide> node.py -= dy * k; <ide> } <ide> } <add> return !quad.charge; <ide> }; <ide> } <ide>
3
Java
Java
add classpath checks to jacksonmodulesruntimehints
0973348bde86f705f4a5d0218e23fcd54d3091be
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/JacksonModulesRuntimeHints.java <ide> import org.springframework.aot.hint.RuntimeHints; <ide> import org.springframework.aot.hint.RuntimeHintsRegistrar; <ide> import org.springframework.aot.hint.TypeReference; <add>import org.springframework.util.ClassUtils; <ide> <ide> /** <ide> * {@link RuntimeHintsRegistrar} implementation that registers reflection entries <ide> class JacksonModulesRuntimeHints implements RuntimeHintsRegistrar { <ide> @Override <ide> public void registerHints(RuntimeHints hints, ClassLoader classLoader) { <ide> ReflectionHints reflectionHints = hints.reflection(); <del> registerType(reflectionHints, "com.fasterxml.jackson.datatype.jdk8.Jdk8Module"); <del> registerType(reflectionHints, "com.fasterxml.jackson.datatype.jsr310.JavaTimeModule"); <del> registerType(reflectionHints, "com.fasterxml.jackson.module.kotlin.KotlinModule"); <add> registerType(reflectionHints, "com.fasterxml.jackson.datatype.jdk8.Jdk8Module", classLoader); <add> registerType(reflectionHints, "com.fasterxml.jackson.datatype.jsr310.JavaTimeModule", classLoader); <add> registerType(reflectionHints, "com.fasterxml.jackson.module.kotlin.KotlinModule", classLoader); <ide> } <ide> <del> private void registerType(ReflectionHints reflectionHints, String className) { <del> reflectionHints.registerType(TypeReference.of(className), <del> builder -> builder.onReachableType(TypeReference.of(Jackson2ObjectMapperBuilder.class)) <del> .withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)); <add> private void registerType(ReflectionHints reflectionHints, String className, ClassLoader classLoader) { <add> if (ClassUtils.isPresent(className, classLoader)) { <add> reflectionHints.registerType(TypeReference.of(className), <add> builder -> builder.onReachableType(TypeReference.of(Jackson2ObjectMapperBuilder.class)) <add> .withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)); <add> } <ide> } <ide> }
1
PHP
PHP
add skeleton methods for schema\collection
52c7064096a0274f86cac798372b04cabddbf68d
<ide><path>lib/Cake/Database/Schema/Collection.php <add><?php <add>/** <add> * PHP Version 5.4 <add> * <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since CakePHP(tm) v 3.0.0 <add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <add> */ <add>namespace Cake\Database\Schema; <add> <add>use Cake\Database\Connection; <add>use Cake\Error; <add> <add>/** <add> * Represents a database schema collection <add> * <add> * Used to access information about the tables, <add> * and other data in a database. <add> */ <add>class Collection { <add> <add> protected $_connection; <add> <add>/** <add> * Constructor. <add> * <add> * @param Cake\Database\Connection $connection <add> */ <add> public function __construct(Connection $connection) { <add> $this->_connection = $connection; <add> } <add> <add>/** <add> * Get the list of tables in the connection's database. <add> * <add> * @return array A list of table names. <add> */ <add> public function listTables() { <add> } <add> <add>/** <add> * Get the column metadata for a table. <add> * <add> * <add> * @param string $name The name of the table to describe <add> * @return Cake\Schema\Table object with column metdata. <add> * @see Collection::fullDescribe() <add> */ <add> public function describe($name) { <add> } <add> <add>/** <add> * Get column & index metadata for a table. <add> * <add> * @param string $name The name of the table to describe <add> * @return Cake\Schema\Table object for table <add> * @see Collection::describe() <add> */ <add> public function fullDescribe($table) { <add> } <add> <add>} <ide><path>lib/Cake/Test/TestCase/Database/Schema/CollectionTest.php <add><?php <add>/** <add> * PHP Version 5.4 <add> * <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since CakePHP(tm) v 3.0.0 <add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <add> */ <add>namespace Cake\Test\TestCase\Database\Schema; <add> <add>use Cake\Database\Schema\Table; <add>use Cake\Database\Schema\Collection; <add>use Cake\TestSuite\TestCase; <add> <add>/** <add> * Test case for Collection <add> */ <add>class CollectionTest extends TestCase { <add> <add>/** <add> * Test getting table listings. <add> * <add> * @return void <add> */ <add> public function testListTables() { <add> } <add> <add>/** <add> * Test getting simple descriptions for tables. <add> * <add> * @return void <add> */ <add> public function testDescribe() { <add> } <add> <add>/** <add> * @expectedException Cake\Error\Exception <add> * @return void <add> */ <add> public function testDescribeIncorrectTable() { <add> } <add> <add>}
2
Javascript
Javascript
use isurlinstance instead of instanceof
d24eecd7d73959872058ea5cee5cd83a9825fa13
<ide><path>lib/internal/modules/cjs/loader.js <ide> const { <ide> maybeCacheSourceMap, <ide> rekeySourceMap <ide> } = require('internal/source_map/source_map_cache'); <del>const { pathToFileURL, fileURLToPath, URL } = require('internal/url'); <add>const { pathToFileURL, fileURLToPath, isURLInstance } = require('internal/url'); <ide> const { deprecate } = require('internal/util'); <ide> const vm = require('vm'); <ide> const assert = require('internal/assert'); <ide> const createRequireError = 'must be a file URL object, file URL string, or ' + <ide> function createRequire(filename) { <ide> let filepath; <ide> <del> if (filename instanceof URL || <add> if (isURLInstance(filename) || <ide> (typeof filename === 'string' && !path.isAbsolute(filename))) { <ide> try { <ide> filepath = fileURLToPath(filename);
1
Python
Python
add get_blobs_list method to wasbhook
0bf330ba8681c417fd5a10b3ba01c75600dc5f2e
<ide><path>airflow/providers/microsoft/azure/hooks/wasb.py <ide> def check_for_prefix(self, container_name, prefix, **kwargs): <ide> num_results=1, **kwargs) <ide> return len(list(matches)) > 0 <ide> <add> def get_blobs_list(self, container_name: str, prefix: str, **kwargs): <add> """ <add> Return a list of blobs from path defined in prefix param <add> <add> :param container_name: Name of the container. <add> :type container_name: str <add> :param prefix: Prefix of the blob. <add> :type prefix: str <add> :param kwargs: Optional keyword arguments that <add> `BlockBlobService.list_blobs()` takes (num_results, include, <add> delimiter, marker, timeout) <add> :type kwargs: object <add> :return: List of blobs. <add> :rtype: list(azure.storage.common.models.ListGenerator) <add> """ <add> return self.connection.list_blobs(container_name, prefix, **kwargs) <add> <ide> def load_file(self, file_path, container_name, blob_name, **kwargs): <ide> """ <ide> Upload a file to Azure Blob Storage. <ide><path>tests/providers/microsoft/azure/hooks/test_wasb.py <ide> def test_delete_multiple_nonexisting_blobs_fails(self, mock_service): <ide> is_prefix=True, ignore_if_missing=False <ide> ) <ide> self.assertIsInstance(context.exception, AirflowException) <add> <add> @mock.patch('airflow.providers.microsoft.azure.hooks.wasb.BlockBlobService', <add> autospec=True) <add> def test_get_blobs_list(self, mock_service): <add> mock_instance = mock_service.return_value <add> hook = WasbHook(wasb_conn_id='wasb_test_sas_token') <add> hook.get_blobs_list('container', 'prefix', num_results=1, timeout=3) <add> mock_instance.list_blobs.assert_called_once_with( <add> 'container', 'prefix', num_results=1, timeout=3 <add> )
2
Ruby
Ruby
improve scope docs
c6372d604952a8eef16ce73a06814aa143b94779
<ide><path>activerecord/lib/active_record/named_scope.rb <ide> module NamedScope <ide> extend ActiveSupport::Concern <ide> <ide> module ClassMethods <del> # Returns a relation if invoked without any arguments. <add> # Returns an anonymous scope. <ide> # <ide> # posts = Post.scoped <ide> # posts.size # Fires "select count(*) from posts" and returns the count <ide> # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects <ide> # <del> # Returns an anonymous named scope if any options are supplied. <del> # <del> # shirts = Shirt.scoped(:conditions => {:color => 'red'}) <del> # shirts = shirts.scoped(:include => :washing_instructions) <add> # fruits = Fruit.scoped <add> # fruits = fruits.where(:colour => 'red') if options[:red_only] <add> # fruits = fruits.limit(10) if limited? <ide> # <ide> # Anonymous \scopes tend to be useful when procedurally generating complex queries, where passing <ide> # intermediate values (scopes) around as first-class objects is convenient. <ide> def scopes <ide> end <ide> <ide> # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query, <del> # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>. <add> # such as <tt>where(:color => :red).select('shirts.*').includes(:washing_instructions)</tt>. <ide> # <ide> # class Shirt < ActiveRecord::Base <del> # scope :red, :conditions => {:color => 'red'} <del> # scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true] <add> # scope :red, where(:color => 'red') <add> # scope :dry_clean_only, joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) <ide> # end <ide> # <ide> # The above calls to <tt>scope</tt> define class methods Shirt.red and Shirt.dry_clean_only. Shirt.red, <del> # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>. <add> # in effect, represents the query <tt>Shirt.where(:color => 'red')</tt>. <ide> # <ide> # Unlike <tt>Shirt.find(...)</tt>, however, the object returned by Shirt.red is not an Array; it resembles the association object <del> # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>, <del> # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just <del> # as with the association objects, named \scopes act like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>, <del> # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really was an Array. <add> # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>, <add> # <tt>Shirt.red.where(:size => 'small')</tt>. Also, just as with the association objects, named \scopes act like an Array, <add> # implementing Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> <add> # all behave as if Shirt.red really was an Array. <ide> # <ide> # These named \scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only. <ide> # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments <ide> def scopes <ide> # Named \scopes can also be procedural: <ide> # <ide> # class Shirt < ActiveRecord::Base <del> # scope :colored, lambda { |color| <del> # { :conditions => { :color => color } } <del> # } <add> # scope :colored, lambda {|color| where(:color => color) } <ide> # end <ide> # <ide> # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts. <ide> # <ide> # Named \scopes can also have extensions, just as with <tt>has_many</tt> declarations: <ide> # <ide> # class Shirt < ActiveRecord::Base <del> # scope :red, :conditions => {:color => 'red'} do <add> # scope :red, where(:color => 'red') do <ide> # def dom_id <ide> # 'red_shirts' <ide> # end <ide> # end <ide> # end <del> # <del> # <del> # For testing complex named \scopes, you can examine the scoping options using the <del> # <tt>proxy_options</tt> method on the proxy itself. <del> # <del> # class Shirt < ActiveRecord::Base <del> # scope :colored, lambda { |color| <del> # { :conditions => { :color => color } } <del> # } <del> # end <del> # <del> # expected_options = { :conditions => { :colored => 'red' } } <del> # assert_equal expected_options, Shirt.colored('red').proxy_options <ide> def scope(name, scope_options = {}, &block) <ide> name = name.to_sym <ide>
1
Mixed
Ruby
fix querycache nil dup
e220fda3e5a497f4b971cf1bb59b2020059634bf
<ide><path>activerecord/CHANGELOG.md <add>* Notifications see frozen SQL string. <add> <add> Fixes #23774 <add> <add> *Richard Monette* <add> <add>* RuntimeErrors are no longer translated to ActiveRecord::StatementInvalid. <add> <add> *Richard Monette* <add> <ide> * Change the schema cache format to use YAML instead of Marshal. <ide> <ide> *Kir Shatrov* <ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def initialize <ide> def to_sql(arel, binds = []) <ide> if arel.respond_to?(:ast) <ide> collected = visitor.accept(arel.ast, collector) <del> collected.compile(binds, self) <add> collected.compile(binds, self).freeze <ide> else <del> arel <add> arel.dup.freeze <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = <ide> <ide> def translate_exception(exception, message) <ide> # override in derived class <del> ActiveRecord::StatementInvalid.new(message) <add> case exception <add> when RuntimeError <add> exception <add> else <add> ActiveRecord::StatementInvalid.new(message) <add> end <ide> end <ide> <ide> def without_prepared_statement?(binds) <ide><path>activerecord/test/cases/adapter_test.rb <ide> def test_select_methods_passing_a_relation <ide> <ide> unless current_adapter?(:PostgreSQLAdapter) <ide> def test_log_invalid_encoding <del> error = assert_raise ActiveRecord::StatementInvalid do <add> error = assert_raises RuntimeError do <ide> @connection.send :log, "SELECT 'ы' FROM DUAL" do <ide> raise "ы".force_encoding(Encoding::ASCII_8BIT) <ide> end <ide> end <ide> <del> assert_not_nil error.cause <add> assert_not_nil error.message <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/query_cache_test.rb <ide> def test_cache_does_not_raise_exceptions <ide> ActiveSupport::Notifications.unsubscribe subscriber <ide> end <ide> <add> def test_query_cache_does_not_allow_sql_key_mutation <add> subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |_, _, _, _, payload| <add> payload[:sql].downcase! <add> end <add> <add> assert_raises RuntimeError do <add> ActiveRecord::Base.cache do <add> assert_queries(1) { Task.find(1); Task.find(1) } <add> end <add> end <add> ensure <add> ActiveSupport::Notifications.unsubscribe subscriber <add> end <add> <ide> def test_cache_is_flat <ide> Task.cache do <ide> assert_queries(1) { Topic.find(1); Topic.find(1); }
5
Javascript
Javascript
add google and github merge strategies
dfeb12d6ce086bd2cffd8333caf6a8b4b20f9825
<ide><path>config/passport.js <ide> passport.use(new FacebookStrategy(secrets.facebook, function (req, accessToken, <ide> existingUser.tokens = _.union(existingUser.tokens, req.user.tokens); <ide> existingUser.save(function(err) { <ide> User.remove({ _id: req.user.id }, function(err) { <del> req.flash('info', { msg: 'Your account has been merged with an existing one that belongs to you' }); <del> return done(null, existingUser); <add> req.flash('info', { msg: 'Your accounts have been merged' }); <add> return done(err, existingUser); <ide> }); <ide> }); <ide> } else { <ide> passport.use(new FacebookStrategy(secrets.facebook, function (req, accessToken, <ide> } <ide> })); <ide> <add>/** <add> * Sign in with GitHub. <add> * <add> * Possible authentication states: <add> * <add> * 1. User is logged in. <add> * a. Already signed in with GitHub before. (MERGE ACCOUNTS, EXISTING ACCOUNT HAS PRECEDENCE) <add> * b. First time signing in with GitHub. (ADD GITHUB ID TO EXISTING USER) <add> * 2. User is not logged in. <add> * a. Already signed with GitHub before. (LOGIN) <add> * b. First time signing in with GitHub. (CREATE ACCOUNT) <add> */ <add> <ide> passport.use(new GitHubStrategy(secrets.github, function(req, accessToken, refreshToken, profile, done) { <ide> if (req.user) { <del> User.findById(req.user.id, function(err, user) { <del> user.github = profile.id; <del> user.tokens.push({ kind: 'github', accessToken: accessToken }); <del> user.profile.name = user.profile.name || profile.displayName; <del> user.profile.picture = user.profile.picture || profile._json.avatar_url; <del> user.profile.location = user.profile.location || profile._json.location; <del> user.profile.website = user.profile.website || profile._json.blog; <del> user.save(function(err) { <del> done(err, user); <del> }); <add> User.findOne({ $or: [{ github: profile.id }, { email: profile.email }] }, function(err, existingUser) { <add> if (existingUser) { <add> existingUser.facebook = existingUser.facebook || req.user.facebook; <add> existingUser.google = existingUser.google || req.user.google; <add> existingUser.twitter = existingUser.twitter || req.user.twitter; <add> existingUser.email = existingUser.email || req.user.email; <add> existingUser.password = existingUser.password || req.user.password; <add> existingUser.profile = existingUser.profile || req.user.profile; <add> existingUser.tokens = _.union(existingUser.tokens, req.user.tokens); <add> existingUser.save(function(err) { <add> User.remove({ _id: req.user.id }, function(err) { <add> req.flash('info', { msg: 'Your accounts have been merged' }); <add> return done(err, existingUser); <add> }); <add> }); <add> } else { <add> User.findById(req.user.id, function(err, user) { <add> user.github = profile.id; <add> user.tokens.push({ kind: 'github', accessToken: accessToken }); <add> user.profile.name = user.profile.name || profile.displayName; <add> user.profile.picture = user.profile.picture || profile._json.avatar_url; <add> user.profile.location = user.profile.location || profile._json.location; <add> user.profile.website = user.profile.website || profile._json.blog; <add> user.save(function(err) { <add> done(err, user); <add> }); <add> }); <add> } <ide> }); <ide> } else { <ide> User.findOne({ github: profile.id }, function(err, existingUser) { <ide> passport.use(new TwitterStrategy(secrets.twitter, function(req, accessToken, tok <ide> } <ide> })); <ide> <add>/** <add> * Sign in with Google. <add> * <add> * Possible authentication states: <add> * <add> * 1. User is logged in. <add> * a. Already signed in with Google before. (MERGE ACCOUNTS, EXISTING ACCOUNT HAS PRECEDENCE) <add> * b. First time signing in with Google. (ADD GOOGLE ID TO EXISTING USER) <add> * 2. User is not logged in. <add> * a. Already signed with GitHub before. (LOGIN) <add> * b. First time signing in with Google. (CREATE ACCOUNT) <add> */ <add> <ide> passport.use(new GoogleStrategy(secrets.google, function(req, accessToken, refreshToken, profile, done) { <ide> if (req.user) { <del> User.findById(req.user.id, function(err, user) { <del> user.google = profile.id; <del> user.tokens.push({ kind: 'google', accessToken: accessToken }); <del> user.profile.name = user.profile.name || profile.displayName; <del> user.profile.gender = user.profile.gender || profile._json.gender; <del> user.profile.picture = user.profile.picture || profile._json.picture; <del> user.save(function(err) { <del> done(err, user); <del> }); <add> <add> User.findOne({ $or: [{ google: profile.id }, { email: profile.email }] }, function(err, existingUser) { <add> if (existingUser) { <add> existingUser.facebook = existingUser.facebook || req.user.facebook; <add> existingUser.github = existingUser.github || req.user.github; <add> existingUser.twitter = existingUser.twitter || req.user.twitter; <add> existingUser.email = existingUser.email || req.user.email; <add> existingUser.password = existingUser.password || req.user.password; <add> existingUser.profile = existingUser.profile || req.user.profile; <add> existingUser.tokens = _.union(existingUser.tokens, req.user.tokens); <add> existingUser.save(function(err) { <add> User.remove({ _id: req.user.id }, function(err) { <add> req.flash('info', { msg: 'Your accounts have been merged' }); <add> return done(err, existingUser); <add> }); <add> }); <add> } else { <add> User.findById(req.user.id, function(err, user) { <add> user.google = profile.id; <add> user.tokens.push({ kind: 'google', accessToken: accessToken }); <add> user.profile.name = user.profile.name || profile.displayName; <add> user.profile.gender = user.profile.gender || profile._json.gender; <add> user.profile.picture = user.profile.picture || profile._json.picture; <add> user.save(function(err) { <add> done(err, user); <add> }); <add> }); <add> } <ide> }); <ide> } else { <ide> User.findOne({ google: profile.id }, function(err, existingUser) {
1
Go
Go
fix start/restart of detached container
4ca7d4f0c1490845cbf04220a408f67c006af248
<ide><path>daemon/container_operations.go <ide> func (daemon *Daemon) allocateNetwork(container *container.Container) error { <ide> } <ide> } <ide> <add> // If the container is not to be connected to any network, <add> // create its network sandbox now if not present <add> if len(networks) == 0 { <add> if nil == daemon.getNetworkSandbox(container) { <add> options, err := daemon.buildSandboxOptions(container) <add> if err != nil { <add> return err <add> } <add> sb, err := daemon.netController.NewSandbox(container.ID, options...) <add> if err != nil { <add> return err <add> } <add> container.UpdateSandboxNetworkSettings(sb) <add> defer func() { <add> if err != nil { <add> sb.Delete() <add> } <add> }() <add> } <add> <add> } <add> <ide> if err := container.WriteHostConfig(); err != nil { <ide> return err <ide> } <ide><path>integration-cli/docker_cli_restart_test.go <ide> func (s *DockerSuite) TestRestartWithVolumes(c *check.C) { <ide> c.Assert(source, checker.Equals, sourceAfterRestart) <ide> } <ide> <add>func (s *DockerSuite) TestRestartDisconnectedContainer(c *check.C) { <add> testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace, NotArm) <add> <add> // Run a container on the default bridge network <add> out, _ := dockerCmd(c, "run", "-d", "--name", "c0", "busybox", "top") <add> cleanedContainerID := strings.TrimSpace(out) <add> c.Assert(waitRun(cleanedContainerID), checker.IsNil) <add> <add> // Disconnect the container from the network <add> out, err := dockerCmd(c, "network", "disconnect", "bridge", "c0") <add> c.Assert(err, check.NotNil, check.Commentf(out)) <add> <add> // Restart the container <add> dockerCmd(c, "restart", "c0") <add> c.Assert(err, check.NotNil, check.Commentf(out)) <add>} <add> <ide> func (s *DockerSuite) TestRestartPolicyNO(c *check.C) { <ide> out, _ := dockerCmd(c, "create", "--restart=no", "busybox") <ide>
2
Javascript
Javascript
fix ssr of styled-components
64aa4454ace64c2982f53374334834c9f47bb491
<ide><path>examples/with-styled-components/pages/_document.js <ide> import styleSheet from 'styled-components/lib/models/StyleSheet' <ide> <ide> export default class MyDocument extends Document { <ide> static async getInitialProps ({ renderPage }) { <del> styleSheet.flush() <ide> const page = renderPage() <ide> const style = styleSheet.rules().map(rule => rule.cssText).join('\n') <ide> return { ...page, style }
1
Java
Java
fix failing test
acd6b9df06ac24045576cb9ae5736f5fe24a29d2
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/TomcatWebSocketClient.java <ide> package org.springframework.web.reactive.socket.client; <ide> <ide> import javax.websocket.Session; <add>import javax.websocket.WebSocketContainer; <ide> <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.adapter.StandardWebSocketSession; <ide> public class TomcatWebSocketClient extends StandardWebSocketClient { <ide> <ide> <add> public TomcatWebSocketClient() { <add> } <add> <add> public TomcatWebSocketClient(WebSocketContainer webSocketContainer) { <add> super(webSocketContainer); <add> } <add> <add> <ide> @Override <ide> protected StandardWebSocketSession createWebSocketSession(Session session, <ide> HandshakeInfo info, MonoProcessor<Void> completion) { <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/socket/AbstractWebSocketIntegrationTests.java <ide> import java.net.URI; <ide> import java.net.URISyntaxException; <ide> <add>import org.apache.tomcat.websocket.WsContainerProvider; <add>import org.apache.tomcat.websocket.WsWebSocketContainer; <ide> import org.apache.tomcat.websocket.server.WsContextListener; <ide> import org.junit.After; <ide> import org.junit.Before; <ide> public abstract class AbstractWebSocketIntegrationTests { <ide> public static Object[][] arguments() throws IOException { <ide> <ide> Flux<? extends WebSocketClient> clients = Flux.concat( <del> Flux.just(new TomcatWebSocketClient()).repeat(5), <add> Flux.just(new TomcatWebSocketClient(new WsWebSocketContainer())).repeat(5), <ide> Flux.just(new JettyWebSocketClient()).repeat(5), <ide> Flux.just(new ReactorNettyWebSocketClient()).repeat(5), <ide> Flux.just(new RxNettyWebSocketClient()).repeat(5),
2
Go
Go
add "src" alias for `--secret`
950658bbb63480de254a166bdeaef1fc8b8fe644
<ide><path>opts/secret.go <ide> func (o *SecretOpt) Set(value string) error { <ide> <ide> value := parts[1] <ide> switch key { <del> case "source": <add> case "source", "src": <ide> options.Source = value <ide> case "target": <ide> tDir, _ := filepath.Split(value) <ide><path>opts/secret_test.go <ide> func TestSecretOptionsSourceTarget(t *testing.T) { <ide> assert.Equal(t, req.Target, "testing") <ide> } <ide> <add>func TestSecretOptionsShorthand(t *testing.T) { <add> var opt SecretOpt <add> <add> testCase := "src=foo,target=testing" <add> assert.NilError(t, opt.Set(testCase)) <add> <add> reqs := opt.Value() <add> assert.Equal(t, len(reqs), 1) <add> req := reqs[0] <add> assert.Equal(t, req.Source, "foo") <add>} <add> <ide> func TestSecretOptionsCustomUidGid(t *testing.T) { <ide> var opt SecretOpt <ide>
2
PHP
PHP
use table helper from symfony 2.3
9db66a6b4b7a08b635b0b2638b5e14859e6dafea
<ide><path>src/Illuminate/Foundation/Console/RoutesCommand.php <ide> <ide> class RoutesCommand extends Command { <ide> <del> /** <add> /** <ide> * The console command name. <ide> * <ide> * @var string <ide> protected function getRouteInformation($name, Route $route) <ide> */ <ide> protected function displayRoutes(array $routes) <ide> { <del> $widths = $this->getCellWidths($routes); <del> <del> $this->displayHeadings($widths); <del> <del> foreach($routes as $route) <del> { <del> $this->displayRoute($route, $widths); <del> } <del> } <del> <del> /** <del> * Display the route table headings. <del> * <del> * @param array $widths <del> * @return void <del> */ <del> protected function displayHeadings(array $widths) <del> { <del> extract($widths); <del> <del> $this->comment(str_pad('URI', $uris).str_pad('Name', $names).str_pad('Action', $actions)); <del> } <del> <del> /** <del> * Display a route in the route table. <del> * <del> * @param array $route <del> * @param array $widths <del> * @return void <del> */ <del> protected function displayRoute(array $route, array $widths) <del> { <del> extract($widths); <del> <del> $this->info( <del> str_pad($route['uri'], $uris).str_pad($route['name'], $names).str_pad($route['action'], $actions) <del> ); <del> } <add> $table = $this->getHelperSet()->get('table'); <ide> <del> /** <del> * Get the correct cell spacing per column. <del> * <del> * @param array $routes <del> * @return array <del> */ <del> protected function getCellWidths($routes, $padding = 10) <del> { <del> $widths = array(); <del> <del> foreach($this->getColumns($routes) as $key => $column) <del> { <del> $widths[$key] = max(array_map('strlen', $column)) + $padding; <del> } <del> <del> return $widths; <del> } <del> <del> /** <del> * Get the columns for the route table. <del> * <del> * @param array $routes <del> * @return array <del> */ <del> protected function getColumns(array $routes) <del> { <del> $columns = array(); <del> <del> foreach (array('uris', 'actions', 'names') as $key) <del> { <del> $columns[$key] = array_pluck($routes, str_singular($key)); <del> } <add> $table->setHeaders(array('URI', 'Name', 'Action'))->setRows($routes); <ide> <del> return $columns; <add> $table->render($this->getOutput()); <ide> } <ide> <ide> /**
1
Javascript
Javascript
fix error in widgetannotation
c889e4e679519f108fd61c7848406a5517241236
<ide><path>src/core/annotation.js <ide> var WidgetAnnotation = (function WidgetAnnotationClosure() { <ide> var name = namedItem.get('T'); <ide> if (name) { <ide> fieldName.unshift(stringToPDFString(name)); <del> } else { <add> } else if (parent && ref) { <ide> // The field name is absent, that means more than one field <ide> // with the same name may exist. Replacing the empty name <ide> // with the '`' plus index in the parent's 'Kids' array.
1
Javascript
Javascript
support decimal stepsize
637c2176ecad70b674ffe8802bde070136785a45
<ide><path>src/core/core.helpers.js <ide> module.exports = function() { <ide> helpers.toDegrees = function(radians) { <ide> return radians * (180 / Math.PI); <ide> }; <add> <add> /** <add> * Returns the number of decimal places <add> * i.e. the number of digits after the decimal point, of the value of this Number. <add> * @param {Number} x - A number. <add> * @returns {Number} The number of decimal places. <add> */ <add> helpers.decimalPlaces = function(x) { <add> if (!helpers.isFinite(x)) { <add> return; <add> } <add> var e = 1; <add> var p = 0; <add> while (Math.round(x * e) / e !== x) { <add> e *= 10; <add> p++; <add> } <add> return p; <add> }; <add> <ide> // Gets the angle from vertical upright to the point about a centre. <ide> helpers.getAngleFromPoint = function(centrePoint, anglePoint) { <ide> var distanceFromXCenter = anglePoint.x - centrePoint.x; <ide><path>src/scales/scale.linearbase.js <ide> function generateTicks(generationOptions, dataRange) { <ide> // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks <ide> // for details. <ide> <del> var factor; <del> var precision; <del> var spacing; <add> var stepSize = generationOptions.stepSize; <add> var min = generationOptions.min; <add> var max = generationOptions.max; <add> var spacing, precision, factor, niceRange, niceMin, niceMax, numSpaces; <ide> <del> if (generationOptions.stepSize && generationOptions.stepSize > 0) { <del> spacing = generationOptions.stepSize; <add> if (stepSize && stepSize > 0) { <add> spacing = stepSize; <ide> } else { <del> var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false); <add> niceRange = helpers.niceNum(dataRange.max - dataRange.min, false); <ide> spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true); <ide> <ide> precision = generationOptions.precision; <del> if (precision !== undefined) { <add> if (!helpers.isNullOrUndef(precision)) { <ide> // If the user specified a precision, round to that number of decimal places <ide> factor = Math.pow(10, precision); <ide> spacing = Math.ceil(spacing * factor) / factor; <ide> } <ide> } <del> var niceMin = Math.floor(dataRange.min / spacing) * spacing; <del> var niceMax = Math.ceil(dataRange.max / spacing) * spacing; <add> // If a precision is not specified, calculate factor based on spacing <add> if (!factor) { <add> factor = Math.pow(10, helpers.decimalPlaces(spacing)); <add> } <add> niceMin = Math.floor(dataRange.min / spacing) * spacing; <add> niceMax = Math.ceil(dataRange.max / spacing) * spacing; <ide> <ide> // If min, max and stepSize is set and they make an evenly spaced scale use it. <del> if (!helpers.isNullOrUndef(generationOptions.min) && !helpers.isNullOrUndef(generationOptions.max) && generationOptions.stepSize) { <add> if (!helpers.isNullOrUndef(min) && !helpers.isNullOrUndef(max) && stepSize) { <ide> // If very close to our whole number, use it. <del> if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) { <del> niceMin = generationOptions.min; <del> niceMax = generationOptions.max; <add> if (helpers.almostWhole((max - min) / stepSize, spacing / 1000)) { <add> niceMin = min; <add> niceMax = max; <ide> } <ide> } <ide> <del> var numSpaces = (niceMax - niceMin) / spacing; <add> numSpaces = (niceMax - niceMin) / spacing; <ide> // If very close to our rounded value, use it. <ide> if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { <ide> numSpaces = Math.round(numSpaces); <ide> } else { <ide> numSpaces = Math.ceil(numSpaces); <ide> } <ide> <del> precision = 1; <del> if (spacing < 1) { <del> precision = Math.pow(10, 1 - Math.floor(helpers.log10(spacing))); <del> niceMin = Math.round(niceMin * precision) / precision; <del> niceMax = Math.round(niceMax * precision) / precision; <del> } <del> ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin); <add> niceMin = Math.round(niceMin * factor) / factor; <add> niceMax = Math.round(niceMax * factor) / factor; <add> ticks.push(helpers.isNullOrUndef(min) ? niceMin : min); <ide> for (var j = 1; j < numSpaces; ++j) { <del> ticks.push(Math.round((niceMin + j * spacing) * precision) / precision); <add> ticks.push(Math.round((niceMin + j * spacing) * factor) / factor); <ide> } <del> ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax); <add> ticks.push(helpers.isNullOrUndef(max) ? niceMax : max); <ide> <ide> return ticks; <ide> } <ide><path>test/specs/core.helpers.tests.js <ide> describe('Core helper tests', function() { <ide> expect(helpers.toDegrees(Math.PI * 3 / 2)).toBe(270); <ide> }); <ide> <add> it('should get the correct number of decimal places', function() { <add> expect(helpers.decimalPlaces(100)).toBe(0); <add> expect(helpers.decimalPlaces(1)).toBe(0); <add> expect(helpers.decimalPlaces(0)).toBe(0); <add> expect(helpers.decimalPlaces(0.01)).toBe(2); <add> expect(helpers.decimalPlaces(-0.01)).toBe(2); <add> expect(helpers.decimalPlaces('1')).toBe(undefined); <add> expect(helpers.decimalPlaces('')).toBe(undefined); <add> expect(helpers.decimalPlaces(undefined)).toBe(undefined); <add> }); <add> <ide> it('should get an angle from a point', function() { <ide> var center = { <ide> x: 0, <ide><path>test/specs/scale.linear.tests.js <ide> describe('Linear Scale', function() { <ide> expect(chart.scales.yScale0.ticks).toEqual(['11', '9', '7', '5', '3', '1']); <ide> }); <ide> <add> it('Should create decimal steps if stepSize is a decimal number', function() { <add> var chart = window.acquireChart({ <add> type: 'bar', <add> data: { <add> datasets: [{ <add> yAxisID: 'yScale0', <add> data: [10, 3, 6, 8, 3, 1] <add> }], <add> labels: ['a', 'b', 'c', 'd', 'e', 'f'] <add> }, <add> options: { <add> scales: { <add> yAxes: [{ <add> id: 'yScale0', <add> type: 'linear', <add> ticks: { <add> stepSize: 2.5 <add> } <add> }] <add> } <add> } <add> }); <add> <add> expect(chart.scales.yScale0).not.toEqual(undefined); // must construct <add> expect(chart.scales.yScale0.min).toBe(0); <add> expect(chart.scales.yScale0.max).toBe(10); <add> expect(chart.scales.yScale0.ticks).toEqual(['10', '7.5', '5', '2.5', '0']); <add> }); <add> <ide> describe('precision', function() { <ide> it('Should create integer steps if precision is 0', function() { <ide> var chart = window.acquireChart({
4
Java
Java
add more perf counters
caaf7fd417e974d32bfaf8a8bd35e7a6e5b99f3d
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/PerformanceCounter.java <ide> import java.util.Map; <ide> <ide> public interface PerformanceCounter { <del> public Map<String,Double> getPerformanceCounters(); <add> public Map<String, Long> getPerformanceCounters(); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java <ide> */ <ide> package com.facebook.react.uimanager; <ide> <add>import android.os.SystemClock; <ide> import com.facebook.common.logging.FLog; <ide> import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.react.animation.Animation; <ide> import com.facebook.yoga.YogaDirection; <ide> import java.util.Arrays; <ide> import java.util.List; <add>import java.util.Map; <ide> import javax.annotation.Nullable; <ide> <ide> /** <ide> public class UIImplementation { <ide> private final ReactApplicationContext mReactContext; <ide> protected final EventDispatcher mEventDispatcher; <ide> <del> private double mLayoutCount = 0.0; <del> private double mLayoutTimer = 0.0; <add> private long mLastCalculateLayoutTime = 0; <ide> <ide> public UIImplementation( <ide> ReactApplicationContext reactContext, <ide> public void updateNodeSize( <ide> } <ide> } <ide> <del> public double getLayoutCount() { <del> return mLayoutCount; <add> public void profileNextBatch() { <add> mOperationsQueue.profileNextBatch(); <ide> } <ide> <del> public double getLayoutTimer() { <del> return mLayoutTimer; <add> public Map<String, Long> getProfiledBatchPerfCounters() { <add> return mOperationsQueue.getProfiledBatchPerfCounters(); <ide> } <ide> <ide> /** <ide> public void dispatchViewUpdates(int batchId) { <ide> "UIImplementation.dispatchViewUpdates") <ide> .arg("batchId", batchId) <ide> .flush(); <add> final long commitStartTime = SystemClock.uptimeMillis(); <ide> try { <ide> updateViewHierarchy(); <ide> mNativeViewHierarchyOptimizer.onBatchComplete(); <del> mOperationsQueue.dispatchViewUpdates(batchId); <add> mOperationsQueue.dispatchViewUpdates(batchId, commitStartTime, mLastCalculateLayoutTime); <ide> } finally { <ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> protected void calculateRootLayout(ReactShadowNode cssRoot) { <ide> SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "cssRoot.calculateLayout") <ide> .arg("rootTag", cssRoot.getReactTag()) <ide> .flush(); <del> double startTime = (double) System.nanoTime(); <add> long startTime = SystemClock.uptimeMillis(); <ide> try { <ide> cssRoot.calculateLayout(); <ide> } finally { <ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <del> mLayoutTimer = mLayoutTimer + ((double)System.nanoTime() - startTime) / 1000000.0; <del> mLayoutCount = mLayoutCount + 1; <add> mLastCalculateLayoutTime = SystemClock.uptimeMillis() - startTime; <ide> } <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java <ide> import com.facebook.react.uimanager.events.EventDispatcher; <ide> import com.facebook.systrace.Systrace; <ide> import com.facebook.systrace.SystraceMessage; <del>import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> import javax.annotation.Nullable; <ide> private static Map<String, Object> createConstants( <ide> } <ide> } <ide> <del> public Map<String,Double> getPerformanceCounters() { <del> Map<String,Double> perfMap = new HashMap<>(); <del> perfMap.put("LayoutCount", mUIImplementation.getLayoutCount()); <del> perfMap.put("LayoutTimer", mUIImplementation.getLayoutTimer()); <del> return perfMap; <add> @Override <add> public Map<String, Long> getPerformanceCounters() { <add> return mUIImplementation.getProfiledBatchPerfCounters(); <ide> } <ide> <ide> /** <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java <ide> <ide> package com.facebook.react.uimanager; <ide> <del>import javax.annotation.Nullable; <del>import javax.annotation.concurrent.GuardedBy; <del> <del>import java.util.ArrayDeque; <del>import java.util.ArrayList; <del> <add>import android.os.SystemClock; <ide> import com.facebook.common.logging.FLog; <ide> import com.facebook.react.animation.Animation; <ide> import com.facebook.react.animation.AnimationRegistry; <ide> import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener; <ide> import com.facebook.systrace.Systrace; <ide> import com.facebook.systrace.SystraceMessage; <add>import java.util.ArrayDeque; <add>import java.util.ArrayList; <add>import java.util.HashMap; <add>import java.util.Map; <add>import javax.annotation.Nullable; <add>import javax.annotation.concurrent.GuardedBy; <ide> <ide> /** <ide> * This class acts as a buffer for command executed on {@link NativeViewHierarchyManager} or on <ide> public void execute() { <ide> private @Nullable NotThreadSafeViewHierarchyUpdateDebugListener mViewHierarchyUpdateDebugListener; <ide> private boolean mIsDispatchUIFrameCallbackEnqueued = false; <ide> private boolean mIsInIllegalUIState = false; <add> private boolean mIsProfilingNextBatch = false; <add> private long mNonBatchedExecutionTotalTime; <add> private long mProfiledBatchCommitStartTime; <add> private long mProfiledBatchLayoutTime; <add> private long mProfiledBatchDispatchViewUpdatesTime; <add> private long mProfiledBatchRunStartTime; <add> private long mProfiledBatchBatchedExecutionTime; <add> private long mProfiledBatchNonBatchedExecutionTime; <ide> <ide> public UIViewOperationQueue( <ide> ReactApplicationContext reactContext, <ide> public void setViewHierarchyUpdateDebugListener( <ide> mViewHierarchyUpdateDebugListener = listener; <ide> } <ide> <add> public void profileNextBatch() { <add> mIsProfilingNextBatch = true; <add> mProfiledBatchCommitStartTime = 0; <add> } <add> <add> public Map<String, Long> getProfiledBatchPerfCounters() { <add> Map<String, Long> perfMap = new HashMap<>(); <add> perfMap.put("CommitStartTime", mProfiledBatchCommitStartTime); <add> perfMap.put("LayoutTime", mProfiledBatchLayoutTime); <add> perfMap.put("DispatchViewUpdatesTime", mProfiledBatchDispatchViewUpdatesTime); <add> perfMap.put("RunStartTime", mProfiledBatchRunStartTime); <add> perfMap.put("BatchedExecutionTime", mProfiledBatchBatchedExecutionTime); <add> perfMap.put("NonBatchedExecutionTime", mProfiledBatchNonBatchedExecutionTime); <add> return perfMap; <add> } <add> <ide> public boolean isEmpty() { <ide> return mOperations.isEmpty(); <ide> } <ide> public void enqueueUIBlock(UIBlock block) { <ide> mOperations.add(new UIBlockOperation(block)); <ide> } <ide> <del> /* package */ void dispatchViewUpdates(final int batchId) { <add> /* package */ void dispatchViewUpdates( <add> final int batchId, final long commitStartTime, final long layoutTime) { <ide> SystraceMessage.beginSection( <ide> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <ide> "UIViewOperationQueue.dispatchViewUpdates") <ide> .arg("batchId", batchId) <ide> .flush(); <ide> try { <add> final long dispatchViewUpdatesTime = SystemClock.uptimeMillis(); <add> <ide> // Store the current operation queues to dispatch and create new empty ones to continue <ide> // receiving new operations <ide> final ArrayList<UIOperation> batchedOperations; <ide> public void enqueueUIBlock(UIBlock block) { <ide> mViewHierarchyUpdateDebugListener.onViewHierarchyUpdateEnqueued(); <ide> } <ide> <del> Runnable runOperations = new Runnable() { <del> @Override <del> public void run() { <del> SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "DispatchUI") <del> .arg("BatchId", batchId) <del> .flush(); <del> try { <del> // All nonBatchedOperations should be executed before regular operations as <del> // regular operations may depend on them <del> if (nonBatchedOperations != null) { <del> for (UIOperation op : nonBatchedOperations) { <del> op.execute(); <del> } <del> } <del> <del> if (batchedOperations != null) { <del> for (UIOperation op : batchedOperations) { <del> op.execute(); <add> Runnable runOperations = <add> new Runnable() { <add> @Override <add> public void run() { <add> SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "DispatchUI") <add> .arg("BatchId", batchId) <add> .flush(); <add> try { <add> long runStartTime = SystemClock.uptimeMillis(); <add> <add> // All nonBatchedOperations should be executed before regular operations as <add> // regular operations may depend on them <add> if (nonBatchedOperations != null) { <add> for (UIOperation op : nonBatchedOperations) { <add> op.execute(); <add> } <add> } <add> <add> if (batchedOperations != null) { <add> for (UIOperation op : batchedOperations) { <add> op.execute(); <add> } <add> } <add> <add> if (mIsProfilingNextBatch && mProfiledBatchCommitStartTime == 0) { <add> mProfiledBatchCommitStartTime = commitStartTime; <add> mProfiledBatchLayoutTime = layoutTime; <add> mProfiledBatchDispatchViewUpdatesTime = dispatchViewUpdatesTime; <add> mProfiledBatchRunStartTime = runStartTime; <add> <add> Systrace.beginAsyncSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "delayBeforeDispatchViewUpdates", <add> 0, <add> mProfiledBatchCommitStartTime * 1000000); <add> Systrace.endAsyncSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "delayBeforeDispatchViewUpdates", <add> 0, <add> mProfiledBatchDispatchViewUpdatesTime * 1000000); <add> Systrace.beginAsyncSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "delayBeforeBatchRunStart", <add> 0, <add> mProfiledBatchDispatchViewUpdatesTime * 1000000); <add> Systrace.endAsyncSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "delayBeforeBatchRunStart", <add> 0, <add> mProfiledBatchRunStartTime * 1000000); <add> } <add> <add> // Clear layout animation, as animation only apply to current UI operations batch. <add> mNativeViewHierarchyManager.clearLayoutAnimation(); <add> <add> if (mViewHierarchyUpdateDebugListener != null) { <add> mViewHierarchyUpdateDebugListener.onViewHierarchyUpdateFinished(); <add> } <add> } catch (Exception e) { <add> mIsInIllegalUIState = true; <add> throw e; <add> } finally { <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> } <del> <del> // Clear layout animation, as animation only apply to current UI operations batch. <del> mNativeViewHierarchyManager.clearLayoutAnimation(); <del> <del> if (mViewHierarchyUpdateDebugListener != null) { <del> mViewHierarchyUpdateDebugListener.onViewHierarchyUpdateFinished(); <del> } <del> } catch (Exception e) { <del> mIsInIllegalUIState = true; <del> throw e; <del> } finally { <del> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <del> } <del> } <del> }; <add> }; <ide> <ide> SystraceMessage.beginSection( <ide> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <ide> public void runGuarded() { <ide> flushPendingBatches(); <ide> } <ide> <del> private void flushPendingBatches() { <add> private boolean flushPendingBatches() { <ide> if (mIsInIllegalUIState) { <ide> FLog.w( <ide> ReactConstants.TAG, <ide> "Not flushing pending UI operations because of previously thrown Exception"); <del> return; <add> return false; <ide> } <ide> <ide> final ArrayList<Runnable> runnables; <ide> private void flushPendingBatches() { <ide> } <ide> } <ide> <del> if (runnables != null) { <del> for (Runnable runnable : runnables) { <del> runnable.run(); <del> } <add> if (runnables == null) { <add> return false; <ide> } <add> <add> for (Runnable runnable : runnables) { <add> runnable.run(); <add> } <add> return true; <ide> } <ide> <ide> /** <ide> public void doFrameGuarded(long frameTimeNanos) { <ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> <del> flushPendingBatches(); <add> final long flushPendingBatchesStartTime = SystemClock.uptimeMillis(); <add> if (flushPendingBatches()) { <add> if (mIsProfilingNextBatch) { <add> mProfiledBatchBatchedExecutionTime = <add> SystemClock.uptimeMillis() - flushPendingBatchesStartTime; <add> mProfiledBatchNonBatchedExecutionTime = mNonBatchedExecutionTotalTime; <add> mIsProfilingNextBatch = false; <add> <add> Systrace.beginAsyncSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "batchedExecutionTime", <add> 0, <add> flushPendingBatchesStartTime * 1000000); <add> Systrace.endAsyncSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "batchedExecutionTime", 0); <add> } <add> mNonBatchedExecutionTotalTime = 0; <add> } <ide> <ide> ReactChoreographer.getInstance().postFrameCallback( <ide> ReactChoreographer.CallbackType.DISPATCH_UI, this); <ide> private void dispatchPendingNonBatchedOperations(long frameTimeNanos) { <ide> } <ide> <ide> try { <add> long nonBatchedExecutionStartTime = SystemClock.uptimeMillis(); <ide> nextOperation.execute(); <add> mNonBatchedExecutionTotalTime += <add> SystemClock.uptimeMillis() - nonBatchedExecutionStartTime; <ide> } catch (Exception e) { <ide> mIsInIllegalUIState = true; <ide> throw e; <ide><path>ReactAndroid/src/main/java/com/facebook/systrace/Systrace.java <ide> public static void beginAsyncSection( <ide> final int cookie) { <ide> } <ide> <add> public static void beginAsyncSection( <add> long tag, final String sectionName, final int cookie, final long startNanos) {} <add> <ide> public static void endAsyncSection( <ide> long tag, <ide> final String sectionName, <ide> final int cookie) { <ide> } <ide> <add> public static void endAsyncSection( <add> long tag, final String sectionName, final int cookie, final long endNanos) {} <add> <ide> public static void traceCounter( <ide> long tag, <ide> final String counterName,
5
Javascript
Javascript
remove prefixed concurrent apis from www build
7cec15155ac2bb9d8c61dc8ab1951c6226c5cd3b
<ide><path>packages/react-dom/src/client/ReactDOMFB.js <ide> Object.assign( <ide> }, <ide> ); <ide> <del>// TODO: These are temporary until we update the callers downstream. <del>ReactDOM.unstable_createRoot = ReactDOM.createRoot; <del>ReactDOM.unstable_createSyncRoot = ReactDOM.createSyncRoot; <del>ReactDOM.unstable_interactiveUpdates = (fn, a, b, c) => { <del> ReactDOM.unstable_flushDiscreteUpdates(); <del> return ReactDOM.unstable_discreteUpdates(fn, a, b, c); <del>}; <del> <ide> export default ReactDOM;
1
Ruby
Ruby
add empty line
d0e83d39a028babe1a1509ea4d198c9b9d5be6ba
<ide><path>Library/Homebrew/cask/installer.rb <ide> def install <ide> print caveats <ide> fetch <ide> uninstall_existing_cask if reinstall? <add> <ide> backup if force? && @cask.staged_path.exist? && @cask.metadata_versioned_path.exist? <ide> <ide> oh1 "Installing Cask #{Formatter.identifier(@cask)}"
1
Text
Text
introspect vs inspect
a56339d0db94e5d5b85a2bfe02ec49ac51af0073
<ide><path>docs/introduction/ThreePrinciples.md <ide> Redux can be described in three fundamental principles: <ide> <ide> **The [state](../Glossary.md#state) of your whole application is stored in an object tree within a single [store](../Glossary.md#store).** <ide> <del>This makes it easy to create universal apps, as the state from your server can be serialized and hydrated into the client with no extra coding effort. A single state tree also makes it easier to debug or introspect an application; it also enables you to persist your app's state in development, for a faster development cycle. Some functionality which has been traditionally difficult to implement - Undo/Redo, for example - can suddenly become trivial to implement, if all of your state is stored in a single tree. <add>This makes it easy to create universal apps, as the state from your server can be serialized and hydrated into the client with no extra coding effort. A single state tree also makes it easier to debug or inspect an application; it also enables you to persist your app's state in development, for a faster development cycle. Some functionality which has been traditionally difficult to implement - Undo/Redo, for example - can suddenly become trivial to implement, if all of your state is stored in a single tree. <ide> <ide> ```js <ide> console.log(store.getState())
1
PHP
PHP
fix more failing tests
a703f6158cfd77501ee2fe2b9e782b11f3aa9231
<ide><path>lib/Cake/Console/Command/AclShell.php <ide> public function startup() { <ide> <ide> $class = Configure::read('Acl.classname'); <ide> $className = App::classname($class, 'Controller/Component/Acl'); <del> if (!in_array($class, array('DbAcl', 'DB_ACL')) && !is_subclass_of($className, 'Cake\Controller\Component\Acl\DbAcl')) { <add> if ( <add> $class !== 'Cake\Controller\Component\Acl\DbAcl' && <add> !is_subclass_of($className, 'Cake\Controller\Component\Acl\DbAcl') <add> ) { <ide> $out = "--------------------------------------------------\n"; <ide> $out .= __d('cake_console', 'Error: Your current Cake configuration is set to an ACL implementation other than DB.') . "\n"; <ide> $out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n"; <ide><path>lib/Cake/Test/TestCase/Console/ShellTest.php <ide> <?php <ide> /** <del> * ShellTest file <del> * <del> * Test Case for Shell <del> * <del> * PHP 5 <del> * <ide> * CakePHP : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. <ide> * <ide> * <ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. <ide> * @link http://cakephp.org CakePHP Project <del> * @package Cake.Test.Case.Console.Command <ide> * @since CakePHP v 1.2.0.7726 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <ide> namespace Cake\Test\TestCase\Console; <add> <ide> use Cake\Console\Shell; <ide> use Cake\Core\App; <ide> use Cake\Core\Plugin; <ide> public function testFileAndConsoleLogging() { <ide> unlink(LOGS . 'error.log'); <ide> $this->assertFalse(file_exists(LOGS . 'error.log')); <ide> <del> // both file and console logging <del> require_once CORE_TEST_CASES . DS . 'Log/Engine/ConsoleLogTest.php'; <del> $mock = $this->getMock('ConsoleLog', array('write'), array( <del> array('types' => 'error'), <del> )); <del> TestCakeLog::config('console', array( <del> 'engine' => 'ConsoleLog', <del> 'stream' => 'php://stderr', <del> )); <del> TestCakeLog::replace('console', $mock); <add> $mock = $this->getMock( <add> 'Cake\Log\Engine\ConsoleLog', <add> ['write'], <add> [['types' => 'error']] <add> ); <add> Log::engine('console', $mock); <ide> $mock->expects($this->once()) <ide> ->method('write') <ide> ->with('error', $this->Shell->testMessage); <ide> public function testProtectedUseLogger() { <ide> Log::drop('stdout'); <ide> Log::drop('stderr'); <ide> $this->Shell->useLogger(true); <del> $this->assertNotEmpty(Log::stream('stdout')); <del> $this->assertNotEmpty(Log::stream('stderr')); <add> $this->assertNotEmpty(Log::engine('stdout')); <add> $this->assertNotEmpty(Log::engine('stderr')); <ide> $this->Shell->useLogger(false); <del> $this->assertFalse(Log::stream('stdout')); <del> $this->assertFalse(Log::stream('stderr')); <add> $this->assertFalse(Log::engine('stdout')); <add> $this->assertFalse(Log::engine('stderr')); <ide> } <ide> <ide> /**
2
Javascript
Javascript
replace passive effect context with boolean
c0ed0a2468d8f4fdecc42e5fe36ef5a4d1dcb68b
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.js <ide> const { <ide> <ide> type ExecutionContext = number; <ide> <del>const NoContext = /* */ 0b0000000; <del>const BatchedContext = /* */ 0b0000001; <del>const EventContext = /* */ 0b0000010; <del>const DiscreteEventContext = /* */ 0b0000100; <del>const LegacyUnbatchedContext = /* */ 0b0001000; <del>const RenderContext = /* */ 0b0010000; <del>const CommitContext = /* */ 0b0100000; <del>const PassiveEffectContext = /* */ 0b1000000; <add>const NoContext = /* */ 0b000000; <add>const BatchedContext = /* */ 0b000001; <add>const EventContext = /* */ 0b000010; <add>const DiscreteEventContext = /* */ 0b000100; <add>const LegacyUnbatchedContext = /* */ 0b001000; <add>const RenderContext = /* */ 0b010000; <add>const CommitContext = /* */ 0b100000; <ide> <ide> type RootExitStatus = 0 | 1 | 2 | 3 | 4 | 5; <ide> const RootIncomplete = 0; <ide> let spawnedWorkDuringRender: null | Array<ExpirationTime> = null; <ide> // receive the same expiration time. Otherwise we get tearing. <ide> let currentEventTime: ExpirationTime = NoWork; <ide> <add>// Dev only flag that tracks if passive effects are currently being flushed. <add>// We warn about state updates for unmounted components differently in this case. <add>let isFlushingPassiveEffects = false; <add> <ide> export function getWorkInProgressRoot(): FiberRoot | null { <ide> return workInProgressRoot; <ide> } <ide> function flushPassiveEffectsImpl() { <ide> return false; <ide> } <ide> <add> if (__DEV__) { <add> isFlushingPassiveEffects = true; <add> } <add> <ide> const root = rootWithPendingPassiveEffects; <ide> const expirationTime = pendingPassiveEffectsExpirationTime; <ide> rootWithPendingPassiveEffects = null; <ide> function flushPassiveEffectsImpl() { <ide> ); <ide> const prevExecutionContext = executionContext; <ide> executionContext |= CommitContext; <del> executionContext |= PassiveEffectContext; <ide> const prevInteractions = pushInteractions(root); <ide> <ide> if (runAllPassiveEffectDestroysBeforeCreates) { <ide> function flushPassiveEffectsImpl() { <ide> nestedPassiveUpdateCount = <ide> rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1; <ide> <add> if (__DEV__) { <add> isFlushingPassiveEffects = false; <add> } <add> <ide> return true; <ide> } <ide> <ide> function warnAboutUpdateOnUnmountedFiberInDEV(fiber) { <ide> } <ide> <ide> // If we are currently flushing passive effects, change the warning text. <del> if ((executionContext & PassiveEffectContext) !== NoContext) { <add> if (isFlushingPassiveEffects) { <ide> console.error( <ide> "Can't perform a React state update from within a useEffect cleanup function. " + <ide> 'To fix, move state updates to the useEffect() body in %s.%s',
1
Ruby
Ruby
avoid postgresql and mysql tests warnings
4b4a548a60236ccfb68c91f53386459bcb1751ab
<ide><path>activerecord/test/cases/active_schema_test_mysql.rb <ide> class ActiveSchemaTest < ActiveRecord::TestCase <ide> def setup <ide> ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do <ide> alias_method :execute_without_stub, :execute <add> remove_method :execute <ide> def execute(sql, name = nil) return sql end <ide> end <ide> end <ide> def test_drop_table_with_specific_database <ide> assert_equal "DROP TABLE `otherdb`.`people`", drop_table('otherdb.people') <ide> end <ide> <del> def test_add_timestamps <add> def test_add_timestamps <ide> with_real_execute do <ide> begin <ide> ActiveRecord::Base.connection.create_table :delete_me do |t| <ide> def test_add_timestamps <ide> end <ide> end <ide> end <del> <del> def test_remove_timestamps <add> <add> def test_remove_timestamps <ide> with_real_execute do <ide> begin <ide> ActiveRecord::Base.connection.create_table :delete_me do |t| <ide> def with_real_execute <ide> ensure <ide> #before finishing, we restore the alias to the mock-up method <ide> ActiveRecord::ConnectionAdapters::MysqlAdapter.class_eval do <add> remove_method :execute <ide> alias_method :execute, :execute_with_stub <ide> end <ide> end <ide><path>activerecord/test/cases/active_schema_test_postgresql.rb <ide> class PostgresqlActiveSchemaTest < Test::Unit::TestCase <ide> def setup <ide> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do <ide> alias_method :real_execute, :execute <add> remove_method :execute <ide> def execute(sql, name = nil) sql end <ide> end <ide> end
2
PHP
PHP
add stringable class
acbbf272214e65f176a2b6a407201ff51729f787
<ide><path>src/Illuminate/Support/Str.php <ide> class Str <ide> */ <ide> protected static $uuidFactory; <ide> <add> /** <add> * Get a new stringable object from the given string. <add> * <add> * @param string $string <add> * @return \Illuminate\Support\Stringable <add> */ <add> public static function of($string) <add> { <add> return new Stringable($string); <add> } <add> <ide> /** <ide> * Return the remainder of a string after the first occurrence of a given value. <ide> * <ide><path>src/Illuminate/Support/Stringable.php <add><?php <add> <add>namespace Illuminate\Support; <add> <add>use Closure; <add>use Illuminate\Support\Str; <add>use Illuminate\Support\Traits\Macroable; <add> <add>class Stringable <add>{ <add> use Macroable; <add> <add> /** <add> * The underlying string value. <add> * <add> * @var string <add> */ <add> protected $value; <add> <add> /** <add> * Create a new instance of the class. <add> * <add> * @param string $value <add> * @return void <add> */ <add> public function __construct($value) <add> { <add> $this->value = (string) $value; <add> } <add> <add> /** <add> * The cache of snake-cased words. <add> * <add> * @var array <add> */ <add> protected static $snakeCache = []; <add> <add> /** <add> * The cache of camel-cased words. <add> * <add> * @var array <add> */ <add> protected static $camelCache = []; <add> <add> /** <add> * The cache of studly-cased words. <add> * <add> * @var array <add> */ <add> protected static $studlyCache = []; <add> <add> /** <add> * The callback that should be used to generate UUIDs. <add> * <add> * @var callable <add> */ <add> protected static $uuidFactory; <add> <add> /** <add> * Return the remainder of a string after the first occurrence of a given value. <add> * <add> * @param string $search <add> * @return static <add> */ <add> public function after($search) <add> { <add> return new static(Str::after($this->value, $search)); <add> } <add> <add> /** <add> * Return the remainder of a string after the last occurrence of a given value. <add> * <add> * @param string $search <add> * @return static <add> */ <add> public function afterLast($search) <add> { <add> return new static(Str::afterLast($this->value, $search)); <add> } <add> <add> /** <add> * Append the given values to the string. <add> * <add> * @param dynamic $values <add> * @return static <add> */ <add> public function append(...$values) <add> { <add> return new static($this->value.implode('', $values)); <add> } <add> <add> /** <add> * Transliterate a UTF-8 value to ASCII. <add> * <add> * @param string $language <add> * @return static <add> */ <add> public function ascii($language = 'en') <add> { <add> return new static(Str::ascii($this->value, $language)); <add> } <add> <add> /** <add> * Get the portion of a string before the first occurrence of a given value. <add> * <add> * @param string $search <add> * @return static <add> */ <add> public function before($search) <add> { <add> return new static(Str::before($this->value, $search)); <add> } <add> <add> /** <add> * Get the portion of a string before the last occurrence of a given value. <add> * <add> * @param string $search <add> * @return static <add> */ <add> public function beforeLast($search) <add> { <add> return new static(Str::beforeLast($this->value, $search)); <add> } <add> <add> /** <add> * Convert a value to camel case. <add> * <add> * @return static <add> */ <add> public function camel() <add> { <add> return new static(Str::camel($this->value)); <add> } <add> <add> /** <add> * Determine if a given string contains a given substring. <add> * <add> * @param string|array $needles <add> * @return bool <add> */ <add> public function contains($haystack, $needles) <add> { <add> return Str::contains($this->value, $needles); <add> } <add> <add> /** <add> * Determine if a given string contains all array values. <add> * <add> * @param array $needles <add> * @return bool <add> */ <add> public function containsAll(array $needles) <add> { <add> return Str::containsAll($this->value, $needles); <add> } <add> <add> /** <add> * Determine if a given string ends with a given substring. <add> * <add> * @param string|array $needles <add> * @return bool <add> */ <add> public function endsWith($needles) <add> { <add> return Str::endsWith($this->value, $needles); <add> } <add> <add> /** <add> * Determine if the string is an exact match with the given value. <add> * <add> * @param string $value <add> * @return bool <add> */ <add> public function exactly($value) <add> { <add> return $this->value === $value; <add> } <add> <add> /** <add> * Explode the string into an array. <add> * <add> * @param string $delimiter <add> * @param int $limit <add> * @return array <add> */ <add> public function explode($delimiter, $limit = PHP_INT_MAX) <add> { <add> return explode($delimiter, $this->value, $limit); <add> } <add> <add> /** <add> * Cap a string with a single instance of a given value. <add> * <add> * @param string $cap <add> * @return static <add> */ <add> public function finish($cap) <add> { <add> return new static(Str::finish($this->value, $cap)); <add> } <add> <add> /** <add> * Determine if a given string matches a given pattern. <add> * <add> * @param string|array $pattern <add> * @return bool <add> */ <add> public function is($pattern) <add> { <add> return Str::is($pattern, $this->value); <add> } <add> <add> /** <add> * Determine if a given string is 7 bit ASCII. <add> * <add> * @return bool <add> */ <add> public function isAscii() <add> { <add> return Str::isAscii($this->value); <add> } <add> <add> /** <add> * Determine if the given string is empty. <add> * <add> * @return bool <add> */ <add> public function isEmpty() <add> { <add> return empty($this->value); <add> } <add> <add> /** <add> * Convert a string to kebab case. <add> * <add> * @return static <add> */ <add> public function kebab() <add> { <add> return new static(Str::kebab($this->value)); <add> } <add> <add> /** <add> * Return the length of the given string. <add> * <add> * @param string $encoding <add> * @return int <add> */ <add> public function length($encoding = null) <add> { <add> return Str::length($this->value, $encoding); <add> } <add> <add> /** <add> * Limit the number of characters in a string. <add> * <add> * @param int $limit <add> * @param string $end <add> * @return static <add> */ <add> public function limit($limit = 100, $end = '...') <add> { <add> return new static(Str::limit($this->value, $limit, $end)); <add> } <add> <add> /** <add> * Convert the given string to lower-case. <add> * <add> * @return static <add> */ <add> public function lower() <add> { <add> return new static(Str::lower($this->value)); <add> } <add> <add> /** <add> * Limit the number of words in a string. <add> * <add> * @param int $words <add> * @param string $end <add> * @return static <add> */ <add> public function words($words = 100, $end = '...') <add> { <add> return new static(Str::words($this->value, $words, $end)); <add> } <add> <add> /** <add> * Parse a Class@method style callback into class and method. <add> * <add> * @param string|null $default <add> * @return array <add> */ <add> public function parseCallback($default = null) <add> { <add> return Str::parseCallback($this->value); <add> } <add> <add> /** <add> * Get the plural form of an English word. <add> * <add> * @param int $count <add> * @return static <add> */ <add> public function plural($count = 2) <add> { <add> return new static(Str::plural($this->value, $count)); <add> } <add> <add> /** <add> * Pluralize the last word of an English, studly caps case string. <add> * <add> * @param int $count <add> * @return static <add> */ <add> public function pluralStudly($count = 2) <add> { <add> return new static(Str::pluralStudly($this->value, $count)); <add> } <add> <add> /** <add> * Prepend the given values to the string. <add> * <add> * @param dynamic $values <add> * @return static <add> */ <add> public function prepend(...$values) <add> { <add> return new static(implode('', $values).$this->value); <add> } <add> <add> /** <add> * Replace a given value in the string sequentially with an array. <add> * <add> * @param string $search <add> * @param array $replace <add> * @return static <add> */ <add> public function replaceArray($search, array $replace) <add> { <add> return new static(Str::replaceArray($search, $replace, $this->value)); <add> } <add> <add> /** <add> * Replace the first occurrence of a given value in the string. <add> * <add> * @param string $search <add> * @param string $replace <add> * @return static <add> */ <add> public function replaceFirst($search, $replace) <add> { <add> return new static(Str::replaceFirst($search, $replace, $this->value)); <add> } <add> <add> /** <add> * Replace the last occurrence of a given value in the string. <add> * <add> * @param string $search <add> * @param string $replace <add> * @return static <add> */ <add> public function replaceLast($search, $replace) <add> { <add> return new static(Str::replaceLast($search, $replace, $this->value)); <add> } <add> <add> /** <add> * Replace the patterns matching the given regular expression. <add> * <add> * @param string $pattern <add> * @param \Closure|string $replace <add> * @param int $limit <add> * @return static <add> */ <add> public function replaceMatches($pattern, $replace, $limit = -1) <add> { <add> if ($replace instanceof Closure) { <add> return new static(preg_replace_callback($pattern, $replace, $this->value, $limit)); <add> } else { <add> return new static(preg_replace($pattern, $replace, $this->value, $limit)); <add> } <add> } <add> <add> /** <add> * Begin a string with a single instance of a given value. <add> * <add> * @param string $prefix <add> * @return static <add> */ <add> public function start($prefix) <add> { <add> return new static(Str::start($this->value, $prefix)); <add> } <add> <add> /** <add> * Convert the given string to upper-case. <add> * <add> * @return static <add> */ <add> public function upper() <add> { <add> return new static(Str::upper($this->value)); <add> } <add> <add> /** <add> * Convert the given string to title case. <add> * <add> * @return static <add> */ <add> public function title() <add> { <add> return new static(Str::title($this->value)); <add> } <add> <add> /** <add> * Get the singular form of an English word. <add> * <add> * @return static <add> */ <add> public function singular() <add> { <add> return new static(Str::singular($this->value)); <add> } <add> <add> /** <add> * Generate a URL friendly "slug" from a given string. <add> * <add> * @param string $separator <add> * @param string|null $language <add> * @return static <add> */ <add> public function slug($separator = '-', $language = 'en') <add> { <add> return new static(Str::slug($this->value, $separator, $language)); <add> } <add> <add> /** <add> * Convert a string to snake case. <add> * <add> * @param string $delimiter <add> * @return static <add> */ <add> public function snake($delimiter = '_') <add> { <add> return new static(Str::snake($this->value, $delimiter)); <add> } <add> <add> /** <add> * Determine if a given string starts with a given substring. <add> * <add> * @param string|array $needles <add> * @return bool <add> */ <add> public function startsWith($needles) <add> { <add> return Str::startsWith($this->value, $needles); <add> } <add> <add> /** <add> * Convert a value to studly caps case. <add> * <add> * @return static <add> */ <add> public function studly() <add> { <add> return new static(Str::studly($this->value)); <add> } <add> <add> /** <add> * Returns the portion of string specified by the start and length parameters. <add> * <add> * @param int $start <add> * @param int|null $length <add> * @return static <add> */ <add> public function substr($start, $length = null) <add> { <add> return new static(Str::substr($this->value, $start, $length)); <add> } <add> <add> /** <add> * Trim the string of the given characeters. <add> * <add> * @param string $characters <add> * @return static <add> */ <add> public function trim($characters = null) <add> { <add> return new static(trim($this->value, $characters)); <add> } <add> <add> /** <add> * Make a string's first character uppercase. <add> * <add> * @return static <add> */ <add> public function ucfirst() <add> { <add> return new static(Str::ucfirst($this->value)); <add> } <add> <add> /** <add> * Proxy dynamic properties onto methods. <add> * <add> * @param string $key <add> * @return mixed <add> */ <add> public function __get($key) <add> { <add> return $this->{$key}(); <add> } <add> <add> /** <add> * Get the raw string value. <add> * <add> * @return string <add> */ <add> public function __toString() <add> { <add> return (string) $this->value; <add> } <add>}
2
Python
Python
make a base init in featureextractionmixin
2199608ca686fa9773b782ac251e085bfe3163f4
<ide><path>src/transformers/feature_extraction_sequence_utils.py <ide> def __init__(self, feature_size: int, sampling_rate: int, padding_value: float, <ide> self.padding_side = kwargs.pop("padding_side", "right") <ide> self.return_attention_mask = kwargs.pop("return_attention_mask", True) <ide> <del> # Additional attributes without default values <del> for key, value in kwargs.items(): <del> try: <del> setattr(self, key, value) <del> except AttributeError as err: <del> logger.error(f"Can't set {key} with value {value} for {self}") <del> raise err <add> super().__init__(**kwargs) <ide> <ide> def pad( <ide> self, <ide><path>src/transformers/feature_extraction_utils.py <ide> class FeatureExtractionMixin: <ide> extractors. <ide> """ <ide> <add> def __init__(self, **kwargs): <add> """Set elements of `kwargs` as attributes.""" <add> # Additional attributes without default values <add> for key, value in kwargs.items(): <add> try: <add> setattr(self, key, value) <add> except AttributeError as err: <add> logger.error(f"Can't set {key} with value {value} for {self}") <add> raise err <add> <ide> @classmethod <ide> def from_pretrained( <ide> cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
2
Java
Java
remove unused method
45a9b9f99221341e134dfa141876614459976b23
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewGroupManager.java <ide> public void removeAllViews(T parent) { <ide> public boolean needsCustomLayoutForChildren() { <ide> return false; <ide> } <del> <del> /** <del> * Returns whether or not this View type should promote its grandchildren as Views. This is an <del> * optimization for Scrollable containers when using Nodes, where instead of having one ViewGroup <del> * containing a large number of draw commands (and thus being more expensive in the case of an <del> * invalidate or re-draw), we split them up into several draw commands. <del> */ <del> public boolean shouldPromoteGrandchildren() { <del> return false; <del> } <ide> }
1
Javascript
Javascript
add initial atom.exe wrapper
42ab14c2cb59c46bcac0ed8dcd1a185dde17764b
<ide><path>resources/win/atom.js <add>var spawn = require('child_process').spawn; <add> <add>var options = { <add> detached: true, <add> stdio: 'ignore' <add>} <add>spawn("C:\\Users\\kevin\\AppData\\Local\\atom\\app-0.156.0\\atom.exe", [], options);
1
PHP
PHP
fix inflection for words ending in media
bd87400131a90c92731a043e309f9033448b2b22
<ide><path>lib/Cake/Test/Case/Utility/InflectorTest.php <ide> public function testInflectingSingulars() { <ide> $this->assertEqual(Inflector::singularize('Aliases'), 'Alias'); <ide> $this->assertEqual(Inflector::singularize('Alias'), 'Alias'); <ide> $this->assertEqual(Inflector::singularize('Media'), 'Media'); <add> $this->assertEqual(Inflector::singularize('NodeMedia'), 'NodeMedia'); <ide> $this->assertEqual(Inflector::singularize('alumni'), 'alumnus'); <ide> $this->assertEqual(Inflector::singularize('bacilli'), 'bacillus'); <ide> $this->assertEqual(Inflector::singularize('cacti'), 'cactus'); <ide> public function testInflectingPlurals() { <ide> $this->assertEqual(Inflector::pluralize('Alias'), 'Aliases'); <ide> $this->assertEqual(Inflector::pluralize('Aliases'), 'Aliases'); <ide> $this->assertEqual(Inflector::pluralize('Media'), 'Media'); <add> $this->assertEqual(Inflector::pluralize('NodeMedia'), 'NodeMedia'); <ide> $this->assertEqual(Inflector::pluralize('alumnus'), 'alumni'); <ide> $this->assertEqual(Inflector::pluralize('bacillus'), 'bacilli'); <ide> $this->assertEqual(Inflector::pluralize('cactus'), 'cacti'); <ide><path>lib/Cake/Utility/Inflector.php <ide> class Inflector { <ide> 'debris', 'diabetes', 'djinn', 'eland', 'elk', 'equipment', 'Faroese', 'flounder', <ide> 'Foochowese', 'gallows', 'Genevese', 'Genoese', 'Gilbertese', 'graffiti', <ide> 'headquarters', 'herpes', 'hijinks', 'Hottentotese', 'information', 'innings', <del> 'jackanapes', 'Kiplingese', 'Kongoese', 'Lucchese', 'mackerel', 'Maltese', 'media', <add> 'jackanapes', 'Kiplingese', 'Kongoese', 'Lucchese', 'mackerel', 'Maltese', '.*?media', <ide> 'mews', 'moose', 'mumps', 'Nankingese', 'news', 'nexus', 'Niasese', <ide> 'Pekingese', 'Piedmontese', 'pincers', 'Pistoiese', 'pliers', 'Portuguese', <ide> 'proceedings', 'rabies', 'rice', 'rhinoceros', 'salmon', 'Sarawakese', 'scissors', <ide> 'sea[- ]bass', 'series', 'Shavese', 'shears', 'siemens', 'species', 'swine', 'testes', <del> 'trousers', 'trout','tuna', 'Vermontese', 'Wenchowese', 'whiting', 'wildebeest', <add> 'trousers', 'trout', 'tuna', 'Vermontese', 'Wenchowese', 'whiting', 'wildebeest', <ide> 'Yengeese' <ide> ); <ide>
2
Python
Python
add tests for english norm exceptions
d77c2cc8bb9d9e3c73cb30e3bd766d73f7308865
<ide><path>spacy/tests/lang/en/test_exceptions.py <ide> def test_en_tokenizer_handles_times(en_tokenizer, text): <ide> tokens = en_tokenizer(text) <ide> assert len(tokens) == 2 <ide> assert tokens[1].lemma_ in ["a.m.", "p.m."] <add> <add> <add>@pytest.mark.parametrize('text,norms', [("I'm", ["i", "am"]), ("shan't", ["shall", "not"])]) <add>def test_en_tokenizer_norm_exceptions(en_tokenizer, text, norms): <add> tokens = en_tokenizer(text) <add> assert [token.norm_ for token in tokens] == norms <add> <add> <add>@pytest.mark.xfail <add>@pytest.mark.parametrize('text,norm', [("radicalised", "radicalized"), ("cuz", "because")]) <add>def test_en_lex_attrs_norm_exceptions(en_tokenizer, text, norm): <add> tokens = en_tokenizer(text) <add> assert tokens[0].norm_ == norm
1
Go
Go
add string method
0d9f1e344a629e5abcd6a385952d22d19555f125
<ide><path>pkg/version/version.go <ide> func (v Version) compareTo(other Version) int { <ide> return 0 <ide> } <ide> <add>// String returns the version string <add>func (v Version) String() string { <add> return string(v) <add>} <add> <ide> // LessThan checks if a version is less than another <ide> func (v Version) LessThan(other Version) bool { <ide> return v.compareTo(other) == -1
1
Ruby
Ruby
clarify description of --api option
f0b087efb06da36b557948b0f9fe99596f440164
<ide><path>railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb <ide> class ScaffoldGenerator < ResourceGenerator # :nodoc: <ide> remove_hook_for :resource_controller <ide> remove_class_option :actions <ide> <del> class_option :api, type: :boolean <add> class_option :api, type: :boolean, <add> desc: "Generate API-only controller and tests, with no view templates" <ide> class_option :resource_route, type: :boolean <ide> <ide> hook_for :scaffold_controller, required: true
1
Python
Python
fix code friendly
35357167cf7dce05446b6bc1ea484370dd725ba6
<ide><path>celery/backends/elasticsearch.py <ide> def __init__(self, url=None, *args, **kwargs): <ide> <ide> self.es_retry_on_timeout = ( <ide> _get('elasticsearch_retry_on_timeout') or self.es_retry_on_timeout <del> ) <add> ) <ide> <ide> es_timeout = _get('elasticsearch_timeout') <ide> if es_timeout is not None: <ide> def _get_server(self): <ide> retry_on_timeout=self.es_retry_on_timeout, <ide> max_retries=self.es_max_retries, <ide> timeout=self.es_timeout <del> ) <add> ) <ide> <ide> @property <ide> def server(self):
1
Python
Python
set version to v2.2.0
b5c775dd42276530b48a1670095fdb476d123e47
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "2.2.0.dev15" <add>__version__ = "2.2.0" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) in Python" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion" <ide> __email__ = "contact@explosion.ai" <ide> __license__ = "MIT" <del>__release__ = False <add>__release__ = True <ide> <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Python
Python
improve error messaging for asr pipeline.
463226e2ee372ae48f473cd9f93917839f0901ff
<ide><path>src/transformers/pipelines/automatic_speech_recognition.py <ide> def preprocess(self, inputs, chunk_length_s=0, stride_length_s=None): <ide> raise ValueError("We expect a single channel audio input for AutomaticSpeechRecognitionPipeline") <ide> <ide> if chunk_length_s: <add> if self.type not in {"ctc", "ctc_with_lm"}: <add> raise ValueError( <add> "`chunk_length_s` is only valid for CTC models, use other chunking options for other models" <add> ) <ide> if stride_length_s is None: <ide> stride_length_s = chunk_length_s / 6 <ide> <ide> def preprocess(self, inputs, chunk_length_s=0, stride_length_s=None): <ide> stride_left = int(round(stride_length_s[0] * self.feature_extractor.sampling_rate / align_to) * align_to) <ide> stride_right = int(round(stride_length_s[1] * self.feature_extractor.sampling_rate / align_to) * align_to) <ide> <del> if self.type not in {"ctc", "ctc_with_lm"}: <del> raise ValueError( <del> "`chunk_length_s` is only valid for CTC models, use other chunking options for other models" <del> ) <ide> if chunk_len < stride_left + stride_right: <ide> raise ValueError("Chunk length must be superior to stride length") <ide> <ide><path>tests/pipelines/test_pipelines_automatic_speech_recognition.py <ide> def run_pipeline_test(self, speech_recognizer, examples): <ide> }, <ide> ) <ide> else: <add> # Non CTC models cannot use chunk_length <add> with self.assertRaises(ValueError) as v: <add> outputs = speech_recognizer(audio, chunk_length_s=10) <add> self.assertEqual(v.exception, "") <add> <ide> # Non CTC models cannot use return_timestamps <del> with self.assertRaises(ValueError): <add> with self.assertRaises(ValueError) as v: <ide> outputs = speech_recognizer(audio, return_timestamps="char") <add> self.assertEqual(v.exception, "") <ide> <ide> @require_torch <ide> @slow <ide> def test_small_model_pt(self): <ide> waveform = np.tile(np.arange(1000, dtype=np.float32), 34) <ide> output = speech_recognizer(waveform) <ide> self.assertEqual(output, {"text": "(Applaudissements)"}) <add> with self.assertRaises(ValueError) as v: <add> _ = speech_recognizer(waveform, chunk_length_s=10) <add> self.assertEqual( <add> str(v.exception), <add> "`chunk_length_s` is only valid for CTC models, use other chunking options for other models", <add> ) <add> <add> # Non CTC models cannot use return_timestamps <add> with self.assertRaises(ValueError) as v: <add> _ = speech_recognizer(waveform, return_timestamps="char") <add> self.assertEqual(str(v.exception), "We cannot return_timestamps yet on non-ctc models !") <ide> <ide> @require_torch <ide> def test_small_model_pt_seq2seq(self):
2
Python
Python
convert tests/jobs/test_base_job.py to pytest
c3af681edf5988d9f9b2aa58c3eb7c97b2f91ca3
<ide><path>tests/jobs/test_base_job.py <ide> # <ide> <ide> import datetime <del>import unittest <ide> <ide> from mock import Mock, patch <add>from pytest import raises <ide> from sqlalchemy.exc import OperationalError <ide> <ide> from airflow.executors.sequential_executor import SequentialExecutor <ide> from tests.test_utils.config import conf_vars <ide> <ide> <del>class TestBaseJob(unittest.TestCase): <del> class TestJob(BaseJob): <del> __mapper_args__ = { <del> 'polymorphic_identity': 'TestJob' <del> } <add>class MockJob(BaseJob): <add> __mapper_args__ = { <add> 'polymorphic_identity': 'MockJob' <add> } <ide> <del> def __init__(self, func, **kwargs): <del> self.func = func <del> super().__init__(**kwargs) <add> def __init__(self, func, **kwargs): <add> self.func = func <add> super().__init__(**kwargs) <ide> <del> def _execute(self): <del> return self.func() <add> def _execute(self): <add> return self.func() <ide> <add> <add>class TestBaseJob: <ide> def test_state_success(self): <del> job = self.TestJob(lambda: True) <add> job = MockJob(lambda: True) <ide> job.run() <ide> <del> self.assertEqual(job.state, State.SUCCESS) <del> self.assertIsNotNone(job.end_date) <add> assert job.state == State.SUCCESS <add> assert job.end_date is not None <ide> <ide> def test_state_sysexit(self): <ide> import sys <del> job = self.TestJob(lambda: sys.exit(0)) <add> job = MockJob(lambda: sys.exit(0)) <ide> job.run() <ide> <del> self.assertEqual(job.state, State.SUCCESS) <del> self.assertIsNotNone(job.end_date) <add> assert job.state == State.SUCCESS <add> assert job.end_date is not None <ide> <ide> def test_state_failed(self): <ide> def abort(): <ide> raise RuntimeError("fail") <ide> <del> job = self.TestJob(abort) <del> with self.assertRaises(RuntimeError): <add> job = MockJob(abort) <add> with raises(RuntimeError): <ide> job.run() <ide> <del> self.assertEqual(job.state, State.FAILED) <del> self.assertIsNotNone(job.end_date) <add> assert job.state == State.FAILED <add> assert job.end_date is not None <ide> <ide> def test_most_recent_job(self): <del> <ide> with create_session() as session: <del> old_job = self.TestJob(None, heartrate=10) <add> old_job = MockJob(None, heartrate=10) <ide> old_job.latest_heartbeat = old_job.latest_heartbeat - datetime.timedelta(seconds=20) <del> job = self.TestJob(None, heartrate=10) <add> job = MockJob(None, heartrate=10) <ide> session.add(job) <ide> session.add(old_job) <ide> session.flush() <ide> <del> self.assertEqual( <del> self.TestJob.most_recent_job(session=session), <del> job <del> ) <add> assert MockJob.most_recent_job(session=session) == job <ide> <ide> session.rollback() <ide> <ide> def test_is_alive(self): <del> job = self.TestJob(None, heartrate=10, state=State.RUNNING) <del> self.assertTrue(job.is_alive()) <add> job = MockJob(None, heartrate=10, state=State.RUNNING) <add> assert job.is_alive() is True <ide> <ide> job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=20) <del> self.assertTrue(job.is_alive()) <add> assert job.is_alive() is True <ide> <ide> job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=21) <del> self.assertFalse(job.is_alive()) <add> assert job.is_alive() is False <ide> <ide> # test because .seconds was used before instead of total_seconds <ide> # internal repr of datetime is (days, seconds) <ide> job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(days=1) <del> self.assertFalse(job.is_alive()) <add> assert job.is_alive() is False <ide> <ide> job.state = State.SUCCESS <ide> job.latest_heartbeat = timezone.utcnow() - datetime.timedelta(seconds=10) <del> self.assertFalse(job.is_alive(), "Completed jobs even with recent heartbeat should not be alive") <add> assert job.is_alive() is False, "Completed jobs even with recent heartbeat should not be alive" <ide> <ide> @patch('airflow.jobs.base_job.create_session') <ide> def test_heartbeat_failed(self, mock_create_session): <ide> def test_heartbeat_failed(self, mock_create_session): <ide> mock_session = Mock(spec_set=session, name="MockSession") <ide> mock_create_session.return_value.__enter__.return_value = mock_session <ide> <del> job = self.TestJob(None, heartrate=10, state=State.RUNNING) <add> job = MockJob(None, heartrate=10, state=State.RUNNING) <ide> job.latest_heartbeat = when <ide> <ide> mock_session.commit.side_effect = OperationalError("Force fail", {}, None) <ide> <ide> job.heartbeat() <ide> <del> self.assertEqual(job.latest_heartbeat, when, "attribute not updated when heartbeat fails") <add> assert job.latest_heartbeat == when, "attribute not updated when heartbeat fails" <ide> <ide> @conf_vars({('scheduler', 'max_tis_per_query'): '100'}) <ide> @patch('airflow.jobs.base_job.ExecutorLoader.get_default_executor') <ide> def test_essential_attr(self, mock_getuser, mock_hostname, mock_default_executor <ide> mock_getuser.return_value = "testuser" <ide> mock_default_executor.return_value = mock_sequential_executor <ide> <del> test_job = self.TestJob(None, heartrate=10, dag_id="example_dag", state=State.RUNNING) <del> self.assertEqual(test_job.executor_class, "SequentialExecutor") <del> self.assertEqual(test_job.heartrate, 10) <del> self.assertEqual(test_job.dag_id, "example_dag") <del> self.assertEqual(test_job.hostname, "test_hostname") <del> self.assertEqual(test_job.max_tis_per_query, 100) <del> self.assertEqual(test_job.unixname, "testuser") <del> self.assertEqual(test_job.state, "running") <del> self.assertEqual(test_job.executor, mock_sequential_executor) <add> test_job = MockJob(None, heartrate=10, dag_id="example_dag", state=State.RUNNING) <add> assert test_job.executor_class == "SequentialExecutor" <add> assert test_job.heartrate == 10 <add> assert test_job.dag_id == "example_dag" <add> assert test_job.hostname == "test_hostname" <add> assert test_job.max_tis_per_query == 100 <add> assert test_job.unixname == "testuser" <add> assert test_job.state == "running" <add> assert test_job.executor == mock_sequential_executor
1
Python
Python
throw valueerror for mirror downloads
361b6df36a93521008c95f32505d8be304adcccf
<ide><path>src/transformers/file_utils.py <ide> def hf_bucket_url( <ide> filename = f"{subfolder}/{filename}" <ide> <ide> if mirror: <del> logger.warning( <del> "Deprecated: The mirroring is deprecated." <del> "Tuna and BFSU mirrors are no longer available." <del> "We will soon provide a self-hosted alternative." <del> ) <add> if mirror in ["tuna", "bfsu"]: <add> raise ValueError("The Tuna and BFSU mirrors are no longer available. Try removing the mirror argument.") <ide> legacy_format = "/" not in model_id <ide> if legacy_format: <ide> return f"{mirror}/{model_id}-{filename}"
1
Ruby
Ruby
convert `brew help` test to spec
c37dbb79b669fc0c4088415d7269a6618f1ccb3c
<ide><path>Library/Homebrew/test/cmd/help_spec.rb <add>describe "brew", :integration_test do <add> it "prints help when no argument is given" do <add> expect { brew } <add> .to output(/Example usage:\n/).to_stderr <add> .and be_a_failure <add> end <add> <add> describe "help" do <add> it "prints help" do <add> expect { brew "help" } <add> .to output(/Example usage:\n/).to_stdout <add> .and be_a_success <add> end <add> <add> it "prints help for a documented Ruby command" do <add> expect { brew "help", "cat" } <add> .to output(/^brew cat/).to_stdout <add> .and be_a_success <add> end <add> <add> it "prints help for a documented shell command" do <add> expect { brew "help", "update" } <add> .to output(/^brew update/).to_stdout <add> .and be_a_success <add> end <add> <add> it "prints help for a documented Ruby developer command" do <add> expect { brew "help", "update-test" } <add> .to output(/^brew update-test/).to_stdout <add> .and be_a_success <add> end <add> <add> it "fails when given an unknown command" do <add> expect { brew "help", "command-that-does-not-exist" } <add> .to output(/Unknown command: command-that-does-not-exist/).to_stderr <add> .and be_a_failure <add> end <add> end <add> <add> describe "cat" do <add> it "prints help when no argument is given" do <add> expect { brew "cat" } <add> .to output(/^brew cat/).to_stderr <add> .and be_a_failure <add> end <add> end <add>end <ide><path>Library/Homebrew/test/help_test.rb <del>require "testing_env" <del> <del>class IntegrationCommandTestHelp < IntegrationCommandTestCase <del> def test_help <del> assert_match "Example usage:\n", <del> cmd_fail # Generic help (empty argument list). <del> assert_match "Unknown command: command-that-does-not-exist", <del> cmd_fail("help", "command-that-does-not-exist") <del> assert_match(/^brew cat /, <del> cmd_fail("cat")) # Missing formula argument triggers help. <del> <del> assert_match "Example usage:\n", <del> cmd("help") # Generic help. <del> assert_match(/^brew cat /, <del> cmd("help", "cat")) # Internal command (documented, Ruby). <del> assert_match(/^brew update /, <del> cmd("help", "update")) # Internal command (documented, Shell). <del> assert_match(/^brew update-test /, <del> cmd("help", "update-test")) # Internal developer command (documented, Ruby). <del> end <del>end
2
Ruby
Ruby
add test case to channelgeneratortest
4ee80f25ce9790c6eaedb2da27d0f25b397aa93d
<ide><path>railties/test/generators/channel_generator_test.rb <ide> def test_channel_on_revoke <ide> assert_file "app/channels/application_cable/connection.rb" <ide> assert_file "app/assets/javascripts/cable.js" <ide> end <add> <add> def test_channel_suffix_is_not_duplicated <add> run_generator ["chat_channel"] <add> <add> assert_no_file "app/channels/chat_channel_channel.rb" <add> assert_file "app/channels/chat_channel.rb" <add> <add> assert_no_file "app/assets/javascripts/channels/chat_channel.js" <add> assert_file "app/assets/javascripts/channels/chat.js" <add> end <ide> end
1
Python
Python
fix tf-slim urls
decf35bcec7d6b147d338c5a49cd40047b634d97
<ide><path>keras/applications/inception_resnet_v2.py <ide> <ide> Model naming and structure follows TF-slim implementation (which has some additional <ide> layers and different number of filters from the original arXiv paper): <del>https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py <add>https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_resnet_v2.py <ide> <ide> Pre-trained ImageNet weights are also converted from TF-slim, which can be found in: <del>https://github.com/tensorflow/models/tree/master/slim#pre-trained-models <add>https://github.com/tensorflow/models/tree/master/research/slim#pre-trained-models <ide> <ide> # Reference <ide> - [Inception-v4, Inception-ResNet and the Impact of
1
Python
Python
fix segfault in ctypeslib with obj being collected
cec59cc17025352a4159172dbe5077e30eee01a1
<ide><path>numpy/ctypeslib.py <ide> def as_ctypes(obj): <ide> raise TypeError("readonly arrays unsupported") <ide> tp = _ctype_ndarray(_typecodes[ai["typestr"]], ai["shape"]) <ide> result = tp.from_address(addr) <del> result.__keep = ai <add> result.__keep = obj <ide> return result <ide><path>numpy/tests/test_ctypeslib.py <ide> <ide> import sys <ide> import pytest <add>import weakref <ide> <ide> import numpy as np <ide> from numpy.ctypeslib import ndpointer, load_library, as_array <ide> def test_reference_cycles(self): <ide> b = np.ctypeslib.as_array(newpnt, (N,)) <ide> # now delete both, which should cleanup both objects <ide> del newpnt, b <add> <add> def test_segmentation_fault(self): <add> arr = np.zeros((224, 224, 3)) <add> c_arr = np.ctypeslib.as_ctypes(arr) <add> arr_ref = weakref.ref(arr) <add> del arr <add> <add> # check the reference wasn't cleaned up <add> assert_(arr_ref() is not None) <add> <add> # check we avoid the segfault <add> c_arr[0][0][0]
2
Ruby
Ruby
add comments, tweak argument handling
74a2c3a5092c3d0556a5e3a8b07c8e2e92b93c1c
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def brew_update <ide> <ide> travis_pr = ENV["TRAVIS_PULL_REQUEST"] && ENV["TRAVIS_PULL_REQUEST"] != "false" <ide> <del> # Use Jenkins environment variables if present. <del> if no_args? && ENV["GIT_PREVIOUS_COMMIT"] && ENV["GIT_COMMIT"] \ <del> && !ENV["ghprbPullLink"] <del> diff_start_sha1 = shorten_revision ENV["GIT_PREVIOUS_COMMIT"] <del> diff_end_sha1 = shorten_revision ENV["GIT_COMMIT"] <del> elsif ENV["TRAVIS_COMMIT_RANGE"] <del> diff_start_sha1, diff_end_sha1 = ENV["TRAVIS_COMMIT_RANGE"].split "..." <del> diff_end_sha1 = ENV["TRAVIS_COMMIT"] if travis_pr <del> elsif ENV["ghprbPullLink"] <del> # Handle Jenkins pull request builder plugin. <add> # Use Jenkins GitHub Pull Request Builder plugin variables for <add> # pull request jobs. <add> if ENV["ghprbPullLink"] <ide> @url = ENV["ghprbPullLink"] <ide> @hash = nil <ide> test "git", "checkout", "origin/master" <add> # Use Travis CI pull-request variables for pull request jobs. <ide> elsif travis_pr <ide> @url = "https://github.com/#{ENV["TRAVIS_REPO_SLUG"]}/pull/#{ENV["TRAVIS_PULL_REQUEST"]}" <ide> @hash = nil <del> elsif @hash <del> diff_start_sha1 = current_sha1 <del> brew_update <del> diff_end_sha1 = current_sha1 <ide> end <ide> <add> # Use Jenkins Git plugin variables for master branch jobs. <add> if ENV["GIT_PREVIOUS_COMMIT"] && ENV["GIT_COMMIT"] <add> diff_start_sha1 = ENV["GIT_PREVIOUS_COMMIT"] <add> diff_end_sha1 = ENV["GIT_COMMIT"] <add> # Use Travis CI Git variables for master or branch jobs. <add> elsif ENV["TRAVIS_COMMIT_RANGE"] <add> diff_start_sha1, diff_end_sha1 = ENV["TRAVIS_COMMIT_RANGE"].split "..." <add> # Otherwise just use the current SHA-1 (which may be overriden later) <add> else <add> diff_end_sha1 = diff_start_sha1 = current_sha1 <add> end <add> <add> # Handle no arguments being passed on the command-line e.g. `brew test-bot`. <ide> if no_args? <ide> if diff_start_sha1 == diff_end_sha1 || \ <ide> single_commit?(diff_start_sha1, diff_end_sha1) <ide> @name = diff_end_sha1 <ide> else <ide> @name = "#{diff_start_sha1}-#{diff_end_sha1}" <ide> end <add> # Handle formulae arguments being passed on the command-line e.g. `brew test-bot wget fish`. <add> elsif @formulae && @formulae.any? <add> @name = "#{@formulae.first}-#{diff_end_sha1}" <add> # Handle a hash being passed on the command-line e.g. `brew test-bot 1a2b3c`. <ide> elsif @hash <ide> test "git", "checkout", @hash <ide> diff_start_sha1 = "#{@hash}^" <ide> diff_end_sha1 = @hash <ide> @name = @hash <del> elsif ENV["TRAVIS_PULL_REQUEST"] && ENV["TRAVIS_PULL_REQUEST"] != "false" <del> @short_url = @url.gsub("https://github.com/", "") <del> @name = "#{@short_url}-#{diff_end_sha1}" <del> # TODO: in future this may need to use `brew pull` to push the right commit. <add> # Handle a URL being passed on the command-line or through Jenkins/Travis <add> # environment variables e.g. <add> # `brew test-bot https://github.com/Homebrew/homebrew/pull/44293`. <ide> elsif @url <del> diff_start_sha1 = current_sha1 <del> test "brew", "pull", "--clean", @url <del> diff_end_sha1 = current_sha1 <add> # TODO: in future Travis CI may need to also use `brew pull` to e.g. push <add> # the right commit to BrewTestBot. <add> unless travis_pr <add> diff_start_sha1 = current_sha1 <add> test "brew", "pull", "--clean", @url <add> diff_end_sha1 = current_sha1 <add> end <ide> @short_url = @url.gsub("https://github.com/", "") <ide> if @short_url.include? "/commit/" <ide> # 7 characters should be enough for a commit (not 40). <ide> def brew_update <ide> @name = "#{@short_url}-#{diff_end_sha1}" <ide> end <ide> else <del> diff_start_sha1 = diff_end_sha1 = current_sha1 <del> @name = "#{@formulae.first}-#{diff_end_sha1}" <add> raise "Cannot set @name: invalid command-line arguments!" <ide> end <ide> <ide> if ENV["TRAVIS"]
1
Javascript
Javascript
remove reference to non-existent parameter
1924cf221695f4abcf2e73e26b93c113571118ac
<ide><path>src/Angular.js <ide> function baseExtend(dst, objs, deep) { <ide> * <ide> * @param {Object} dst Destination object. <ide> * @param {...Object} src Source object(s). <del> * @param {boolean=} deep if the last parameter is set to `true`, objects are recursively merged <del> * (deep copy). Defaults to `false`. <ide> * @returns {Object} Reference to `dst`. <ide> */ <ide> function extend(dst) {
1
Python
Python
unskip tests with 1.x
296d0d3fc8efd5f165c10a71a9e1235b5889bb90
<ide><path>official/transformer/v2/transformer_main_test.py <ide> def tearDown(self): <ide> def _assert_exists(self, filepath): <ide> self.assertTrue(os.path.exists(filepath)) <ide> <del> def test_train(self): <add> def test_train_no_dist_strat(self): <ide> t = tm.TransformerTask(FLAGS) <ide> t.train() <ide> <del> @unittest.skipUnless(keras_utils.is_v2_0(), 'TF 2.0 only test.') <ide> def test_train_static_batch(self): <add> FLAGS.distribution_strategy = 'one_device' <ide> FLAGS.static_batch = True <ide> t = tm.TransformerTask(FLAGS) <ide> t.train() <ide> <ide> @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') <del> @unittest.skipUnless(keras_utils.is_v2_0(), 'TF 2.0 only test.') <ide> def test_train_1_gpu_with_dist_strat(self): <ide> FLAGS.distribution_strategy = 'one_device' <ide> t = tm.TransformerTask(FLAGS) <ide> t.train() <ide> <ide> @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') <del> @unittest.skipUnless(keras_utils.is_v2_0(), 'TF 2.0 only test.') <ide> def test_train_2_gpu(self): <ide> if context.num_gpus() < 2: <ide> self.skipTest( <ide> def test_train_2_gpu(self): <ide> t.train() <ide> <ide> @unittest.skipUnless(tf.test.is_built_with_cuda(), 'requires GPU') <del> @unittest.skipUnless(keras_utils.is_v2_0(), 'TF 2.0 only test.') <ide> def test_train_2_gpu_fp16(self): <ide> if context.num_gpus() < 2: <ide> self.skipTest(
1
Ruby
Ruby
add missing require for `strip_heredoc`
6fe9cc80fccaa553e1bd611a7247ba1320895071
<ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb <ide> require "rack/session/abstract/id" <ide> require "action_controller/metal/exceptions" <ide> require "active_support/security_utils" <add>require "active_support/core_ext/string/strip" <ide> <ide> module ActionController #:nodoc: <ide> class InvalidAuthenticityToken < ActionControllerError #:nodoc:
1
Go
Go
fix cache with onbuild
f1ade82d82e6436971c6b7d08eb1da57ed9ba756
<ide><path>builder/dockerfile/evaluator.go <ide> func (b *Builder) dispatch(options dispatchOptions) (*dispatchState, error) { <ide> buildsFailed.WithValues(metricsUnknownInstructionError).Inc() <ide> return nil, fmt.Errorf("unknown instruction: %s", upperCasedCmd) <ide> } <del> if err := f(newDispatchRequestFromOptions(options, b, args)); err != nil { <del> return nil, err <del> } <ide> options.state.updateRunConfig() <del> return options.state, nil <add> err = f(newDispatchRequestFromOptions(options, b, args)) <add> return options.state, err <ide> } <ide> <ide> type dispatchOptions struct { <ide><path>integration-cli/docker_api_attach_test.go <ide> func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) { <ide> <ide> // regression gh14320 <ide> func (s *DockerSuite) TestPostContainersAttachContainerNotFound(c *check.C) { <del> client, err := request.NewClient(daemonHost()) <add> client, err := request.NewHTTPClient(daemonHost()) <ide> c.Assert(err, checker.IsNil) <ide> req, err := request.New(daemonHost(), "/containers/doesnotexist/attach", request.Method(http.MethodPost)) <ide> resp, err := client.Do(req) <ide><path>integration-cli/docker_api_build_test.go <ide> package main <ide> import ( <ide> "archive/tar" <ide> "bytes" <add> "encoding/json" <ide> "io/ioutil" <ide> "net/http" <ide> "regexp" <ide> import ( <ide> "github.com/docker/docker/integration-cli/request" <ide> "github.com/docker/docker/pkg/testutil" <ide> "github.com/go-check/check" <add> "github.com/stretchr/testify/assert" <add> "github.com/stretchr/testify/require" <add> "golang.org/x/net/context" <ide> ) <ide> <ide> func (s *DockerSuite) TestBuildAPIDockerFileRemote(c *check.C) { <ide> func (s *DockerSuite) TestBuildOnBuildWithCopy(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(string(out), checker.Contains, "Successfully built") <ide> } <add> <add>func (s *DockerSuite) TestBuildOnBuildCache(c *check.C) { <add> build := func(dockerfile string) []byte { <add> ctx := fakecontext.New(c, "", <add> fakecontext.WithDockerfile(dockerfile), <add> ) <add> defer ctx.Close() <add> <add> res, body, err := request.Post( <add> "/build", <add> request.RawContent(ctx.AsTarReader(c)), <add> request.ContentType("application/x-tar")) <add> require.NoError(c, err) <add> assert.Equal(c, http.StatusOK, res.StatusCode) <add> <add> out, err := testutil.ReadBody(body) <add> require.NoError(c, err) <add> assert.Contains(c, string(out), "Successfully built") <add> return out <add> } <add> <add> dockerfile := ` <add> FROM ` + minimalBaseImage() + ` as onbuildbase <add> ENV something=bar <add> ONBUILD ENV foo=bar <add> ` <add> build(dockerfile) <add> <add> dockerfile += "FROM onbuildbase" <add> out := build(dockerfile) <add> <add> imageIDs := getImageIDsFromBuild(c, out) <add> assert.Len(c, imageIDs, 2) <add> parentID, childID := imageIDs[0], imageIDs[1] <add> <add> client, err := request.NewClient() <add> require.NoError(c, err) <add> <add> // check parentID is correct <add> image, _, err := client.ImageInspectWithRaw(context.Background(), childID) <add> require.NoError(c, err) <add> assert.Equal(c, parentID, image.Parent) <add>} <add> <add>type buildLine struct { <add> Stream string <add> Aux struct { <add> ID string <add> } <add>} <add> <add>func getImageIDsFromBuild(c *check.C, output []byte) []string { <add> ids := []string{} <add> for _, line := range bytes.Split(output, []byte("\n")) { <add> if len(line) == 0 { <add> continue <add> } <add> entry := buildLine{} <add> require.NoError(c, json.Unmarshal(line, &entry)) <add> if entry.Aux.ID != "" { <add> ids = append(ids, entry.Aux.ID) <add> } <add> } <add> return ids <add>} <ide><path>integration-cli/request/request.go <ide> func DoOnHost(host, endpoint string, modifiers ...func(*http.Request) error) (*h <ide> if err != nil { <ide> return nil, nil, err <ide> } <del> client, err := NewClient(host) <add> client, err := NewHTTPClient(host) <ide> if err != nil { <ide> return nil, nil, err <ide> } <ide> func New(host, endpoint string, modifiers ...func(*http.Request) error) (*http.R <ide> return req, nil <ide> } <ide> <del>// NewClient creates an http client for the specific host <del>func NewClient(host string) (*http.Client, error) { <add>// NewHTTPClient creates an http client for the specific host <add>func NewHTTPClient(host string) (*http.Client, error) { <ide> // FIXME(vdemeester) 10*time.Second timeout of SockRequest… ? <ide> proto, addr, _, err := dclient.ParseHost(host) <ide> if err != nil { <ide> func NewClient(host string) (*http.Client, error) { <ide> }, err <ide> } <ide> <add>// NewClient returns a new Docker API client <add>func NewClient() (dclient.APIClient, error) { <add> host := DaemonHost() <add> httpClient, err := NewHTTPClient(host) <add> if err != nil { <add> return nil, err <add> } <add> return dclient.NewClient(host, "", httpClient, nil) <add>} <add> <ide> // FIXME(vdemeester) httputil.ClientConn is deprecated, use http.Client instead (closer to actual client) <ide> // Deprecated: Use New instead of NewRequestClient <ide> // Deprecated: use request.Do (or Get, Delete, Post) instead
4
Go
Go
return prune data when context canceled
87b4dc2002d50e245f432bbd97e9dee2db25cf96
<ide><path>api/server/backend/build/backend.go <ide> func (b *Backend) Build(ctx context.Context, config backend.BuildConfig) (string <ide> <ide> // PruneCache removes all cached build sources <ide> func (b *Backend) PruneCache(ctx context.Context) (*types.BuildCachePruneReport, error) { <del> size, err := b.fsCache.Prune() <add> size, err := b.fsCache.Prune(ctx) <ide> if err != nil { <ide> return nil, errors.Wrap(err, "failed to prune build cache") <ide> } <ide><path>builder/fscache/fscache.go <ide> func (fsc *FSCache) DiskUsage() (int64, error) { <ide> } <ide> <ide> // Prune allows manually cleaning up the cache <del>func (fsc *FSCache) Prune() (uint64, error) { <del> return fsc.store.Prune() <add>func (fsc *FSCache) Prune(ctx context.Context) (uint64, error) { <add> return fsc.store.Prune(ctx) <ide> } <ide> <ide> // Close stops the gc and closes the persistent db <ide> func (s *fsCacheStore) DiskUsage() (int64, error) { <ide> } <ide> <ide> // Prune allows manually cleaning up the cache <del>func (s *fsCacheStore) Prune() (uint64, error) { <add>func (s *fsCacheStore) Prune(ctx context.Context) (uint64, error) { <ide> s.mu.Lock() <ide> defer s.mu.Unlock() <ide> var size uint64 <ide> <ide> for id, snap := range s.sources { <add> select { <add> case <-ctx.Done(): <add> logrus.Debugf("Cache prune operation cancelled, pruned size: %d", size) <add> // when the context is cancelled, only return current size and nil <add> return size, nil <add> default: <add> } <ide> if len(snap.refs) == 0 { <ide> ss, err := snap.getSize() <ide> if err != nil { <ide><path>builder/fscache/fscache_test.go <ide> func TestFSCache(t *testing.T) { <ide> assert.Equal(t, s, int64(8)) <ide> <ide> // prune deletes everything <del> released, err := fscache.Prune() <add> released, err := fscache.Prune(context.TODO()) <ide> assert.Nil(t, err) <ide> assert.Equal(t, released, uint64(8)) <ide> <ide><path>daemon/prune.go <ide> func (daemon *Daemon) ContainersPrune(ctx context.Context, pruneFilters filters. <ide> for _, c := range allContainers { <ide> select { <ide> case <-ctx.Done(): <del> logrus.Warnf("ContainersPrune operation cancelled: %#v", *rep) <del> return rep, ctx.Err() <add> logrus.Debugf("ContainersPrune operation cancelled: %#v", *rep) <add> return rep, nil <ide> default: <ide> } <ide> <ide> func (daemon *Daemon) VolumesPrune(ctx context.Context, pruneFilters filters.Arg <ide> pruneVols := func(v volume.Volume) error { <ide> select { <ide> case <-ctx.Done(): <del> logrus.Warnf("VolumesPrune operation cancelled: %#v", *rep) <add> logrus.Debugf("VolumesPrune operation cancelled: %#v", *rep) <ide> return ctx.Err() <ide> default: <ide> } <ide> func (daemon *Daemon) VolumesPrune(ctx context.Context, pruneFilters filters.Arg <ide> } <ide> <ide> err = daemon.traverseLocalVolumes(pruneVols) <add> if err == context.Canceled { <add> return rep, nil <add> } <ide> <ide> return rep, err <ide> } <ide> deleteImagesLoop: <ide> } <ide> <ide> if canceled { <del> logrus.Warnf("ImagesPrune operation cancelled: %#v", *rep) <del> return nil, ctx.Err() <add> logrus.Debugf("ImagesPrune operation cancelled: %#v", *rep) <ide> } <ide> <ide> return rep, nil <ide> func (daemon *Daemon) localNetworksPrune(ctx context.Context, pruneFilters filte <ide> l := func(nw libnetwork.Network) bool { <ide> select { <ide> case <-ctx.Done(): <add> // context cancelled <ide> return true <ide> default: <ide> } <ide> func (daemon *Daemon) clusterNetworksPrune(ctx context.Context, pruneFilters fil <ide> for _, nw := range networks { <ide> select { <ide> case <-ctx.Done(): <del> return rep, ctx.Err() <add> return rep, nil <ide> default: <ide> if nw.Ingress { <ide> // Routing-mesh network removal has to be explicitly invoked by user <ide> func (daemon *Daemon) NetworksPrune(ctx context.Context, pruneFilters filters.Ar <ide> <ide> select { <ide> case <-ctx.Done(): <del> logrus.Warnf("NetworksPrune operation cancelled: %#v", *rep) <del> return nil, ctx.Err() <add> logrus.Debugf("NetworksPrune operation cancelled: %#v", *rep) <add> return rep, nil <ide> default: <ide> } <ide>
4
Python
Python
fix a regression in paramikosshclient.run method
0c4869c0561384fbc0623d162360c27b781847de
<ide><path>libcloud/test/compute/test_deployment.py <ide> def test_script_deployment(self): <ide> self.assertEqual(self.node, sd2.run(node=self.node, <ide> client=MockClient(hostname='localhost'))) <ide> <add> def test_script_deployment_relative_path(self): <add> client = Mock() <add> client.put.return_value = '/home/ubuntu/relative.sh' <add> client.run.return_value = ('', '', 0) <add> <add> sd = ScriptDeployment(script='echo "foo"', name='relative.sh') <add> sd.run(self.node, client) <add> <add> client.run.assert_called_once_with('/home/ubuntu/relative.sh') <add> <add> def test_script_deployment_absolute_path(self): <add> client = Mock() <add> client.put.return_value = '/home/ubuntu/relative.sh' <add> client.run.return_value = ('', '', 0) <add> <add> sd = ScriptDeployment(script='echo "foo"', name='/root/relative.sh') <add> sd.run(self.node, client) <add> <add> client.run.assert_called_once_with('/root/relative.sh') <add> <ide> def test_script_deployment_and_sshkey_deployment_argument_types(self): <ide> class FileObject(object): <ide> def __init__(self, name): <ide><path>libcloud/test/compute/test_ssh_client.py <ide> def test_basic_usage_absolute_path(self): <ide> <ide> mock.close() <ide> <del> def _disabled_test_run_script_with_relative_path(self): <del> """ <del> Execute script with relative path. <del> """ <del> mock = self.ssh_cli <del> <del> # Define behaviour then ask for 'current directory' <del> mock.client.open_sftp().getcwd.return_value = '/home/ubuntu/' <del> <del> # Script without full path <del> sd = 'random_script.sh' <del> <del> # Without assertions because they are the same than the previous <del> # 'test_basic_usage' method <del> mock.connect() <del> <del> mock_cli = mock.client # The actual mocked object: SSHClient <del> <del> mock.put(sd, chmod=600) <del> # Make assertions over 'put' method <del> mock_cli.open_sftp().file.assert_called_once_with('random_script.sh', <del> mode='w') <del> mock_cli.open_sftp().file().chmod.assert_called_once_with(600) <del> <del> mock.run(sd) <del> # Make assertions over the 'run' method <del> mock_cli.open_sftp().chdir.assert_called_with(".") <del> mock_cli.open_sftp().getcwd.assert_called_once() <del> full_sd = '/home/ubuntu/random_script.sh' <del> mock_cli.get_transport().open_session().exec_command \ <del> .assert_called_once_with(full_sd) <del> <del> mock.close() <del> <ide> def test_delete_script(self): <ide> """ <ide> Provide a basic test with 'delete' action.
2
Go
Go
add synchronization to count and list
2d21996eec8d3e6100f19fa0d0fa7adad25285ca
<ide><path>daemon/volumes.go <ide> func (s *volumeStore) Decrement(v volume.Volume) { <ide> <ide> // Count returns the usage count of the passed in volume <ide> func (s *volumeStore) Count(v volume.Volume) int { <add> s.mu.Lock() <add> defer s.mu.Unlock() <ide> vc, exists := s.vols[v.Name()] <ide> if !exists { <ide> return 0 <ide> func (s *volumeStore) Count(v volume.Volume) int { <ide> <ide> // List returns all the available volumes <ide> func (s *volumeStore) List() []volume.Volume { <add> s.mu.Lock() <add> defer s.mu.Unlock() <ide> var ls []volume.Volume <ide> for _, vc := range s.vols { <ide> ls = append(ls, vc.Volume)
1
PHP
PHP
fix path for loading config files from plugin
4eae13f01a97f3c9a8d75b486a6f019da271823f
<ide><path>src/Configure/Engine/IniConfig.php <ide> public function dump($key, $data) { <ide> /** <ide> * Converts a value into the ini equivalent <ide> * <del> * @param mixed $val Value to export. <add> * @param mixed $value Value to export. <ide> * @return string String value for ini file. <ide> */ <ide> protected function _value($value) { <ide> protected function _getFilePath($key) { <ide> } <ide> <ide> if ($plugin) { <del> $file = App::pluginPath($plugin) . 'Config' . DS . $key; <add> $file = App::pluginPath($plugin) . 'src' . DS . 'Config' . DS . $key; <ide> } else { <ide> $file = $this->_path . $key; <ide> } <ide><path>src/Configure/Engine/PhpConfig.php <ide> protected function _getFilePath($key) { <ide> $key .= '.php'; <ide> <ide> if ($plugin) { <del> $file = App::pluginPath($plugin) . 'Config' . DS . $key; <add> $file = App::pluginPath($plugin) . 'src' . DS . 'Config' . DS . $key; <ide> } else { <ide> $file = $this->_path . $key; <ide> }
2
Python
Python
fix google dlp example and improve ops idempotency
5ae82a56dab599de44f1be7027cecc4ef86f7bb6
<ide><path>airflow/providers/google/cloud/example_dags/example_dlp.py <ide> ) <ide> INSPECT_CONFIG = InspectConfig(info_types=[{"name": "PHONE_NUMBER"}, {"name": "US_TOLLFREE_PHONE_NUMBER"}]) <ide> INSPECT_TEMPLATE = InspectTemplate(inspect_config=INSPECT_CONFIG) <add>OUTPUT_BUCKET = os.environ.get("DLP_OUTPUT_BUCKET", "gs://test-dlp-airflow") <add>OUTPUT_FILENAME = "test.txt" <ide> <add>OBJECT_GCS_URI = os.path.join(OUTPUT_BUCKET, "tmp") <add>OBJECT_GCS_OUTPUT_URI = os.path.join(OUTPUT_BUCKET, "tmp", OUTPUT_FILENAME) <ide> <ide> with models.DAG( <ide> "example_gcp_dlp", <ide> schedule_interval=None, # Override to match your needs <ide> start_date=days_ago(1), <ide> tags=['example'], <del>) as dag: <add>) as dag1: <ide> # [START howto_operator_dlp_create_inspect_template] <ide> create_template = CloudDLPCreateInspectTemplateOperator( <ide> project_id=GCP_PROJECT, <ide> inspect_template=INSPECT_TEMPLATE, <ide> template_id=TEMPLATE_ID, <ide> task_id="create_template", <ide> do_xcom_push=True, <del> dag=dag, <ide> ) <ide> # [END howto_operator_dlp_create_inspect_template] <ide> <ide> project_id=GCP_PROJECT, <ide> item=ITEM, <ide> inspect_template_name="{{ task_instance.xcom_pull('create_template', key='return_value')['name'] }}", <del> dag=dag, <ide> ) <ide> # [END howto_operator_dlp_use_inspect_template] <ide> <ide> # [START howto_operator_dlp_delete_inspect_template] <ide> delete_template = CloudDLPDeleteInspectTemplateOperator( <del> task_id="delete_template", template_id=TEMPLATE_ID, project_id=GCP_PROJECT, dag=dag, <add> task_id="delete_template", template_id=TEMPLATE_ID, project_id=GCP_PROJECT, <ide> ) <ide> # [END howto_operator_dlp_delete_inspect_template] <ide> <ide> create_template >> inspect_content >> delete_template <ide> <del> <del>CUSTOM_INFO_TYPES = [{"info_type": {"name": "C_MRN"}, "regex": {"pattern": "[1-9]{3}-[1-9]{1}-[1-9]{5}"},}] <ide> CUSTOM_INFO_TYPE_ID = "custom_info_type" <del>UPDATE_CUSTOM_INFO_TYPE = [ <del> {"info_type": {"name": "C_MRN"}, "regex": {"pattern": "[a-z]{3}-[a-z]{1}-[a-z]{5}"},} <del>] <add>CUSTOM_INFO_TYPES = { <add> "large_custom_dictionary": { <add> "output_path": {"path": OBJECT_GCS_OUTPUT_URI}, <add> "cloud_storage_file_set": {"url": OBJECT_GCS_URI + "/"}, <add> } <add>} <add>UPDATE_CUSTOM_INFO_TYPE = { <add> "large_custom_dictionary": { <add> "output_path": {"path": OBJECT_GCS_OUTPUT_URI}, <add> "cloud_storage_file_set": {"url": OBJECT_GCS_URI + "/"}, <add> } <add>} <ide> <ide> with models.DAG( <ide> "example_gcp_dlp_info_types", <ide> schedule_interval=None, <ide> start_date=days_ago(1), <ide> tags=["example", "dlp", "info-types"], <del>) as dag: <add>) as dag2: <ide> # [START howto_operator_dlp_create_info_type] <ide> create_info_type = CloudDLPCreateStoredInfoTypeOperator( <ide> project_id=GCP_PROJECT, <ide> config=CUSTOM_INFO_TYPES, <ide> stored_info_type_id=CUSTOM_INFO_TYPE_ID, <del> dag=dag, <ide> task_id="create_info_type", <ide> ) <ide> # [END howto_operator_dlp_create_info_type] <ide> project_id=GCP_PROJECT, <ide> stored_info_type_id=CUSTOM_INFO_TYPE_ID, <ide> config=UPDATE_CUSTOM_INFO_TYPE, <del> dag=dag, <ide> task_id="update_info_type", <ide> ) <ide> # [END howto_operator_dlp_update_info_type] <ide> # [START howto_operator_dlp_delete_info_type] <ide> delete_info_type = CloudDLPDeleteStoredInfoTypeOperator( <del> project_id=GCP_PROJECT, stored_info_type_id=CUSTOM_INFO_TYPE_ID, dag=dag, task_id="delete_info_type", <add> project_id=GCP_PROJECT, stored_info_type_id=CUSTOM_INFO_TYPE_ID, task_id="delete_info_type", <ide> ) <ide> # [END howto_operator_dlp_delete_info_type] <ide> create_info_type >> update_info_type >> delete_info_type <ide> <del>SCHEDULE = {"recurrence_period_duration": {"seconds": 60 * 60 * 24}} <del>JOB = { <del> "inspect_config": INSPECT_CONFIG, <del>} <del> <ide> JOB_TRIGGER = { <del> "inspect_job": JOB, <del> "triggers": [{"schedule": SCHEDULE}], <add> "inspect_job": { <add> "storage_config": { <add> "datastore_options": {"partition_id": {"project_id": GCP_PROJECT}, "kind": {"name": "test"}} <add> } <add> }, <add> "triggers": [{"schedule": {"recurrence_period_duration": {"seconds": 60 * 60 * 24}}}], <ide> "status": "HEALTHY", <ide> } <ide> <ide> TRIGGER_ID = "example_trigger" <ide> <ide> with models.DAG( <del> "example_gcp_dlp_job", schedule_interval=None, start_date=days_ago(1), tags=["example", "dlp_job"], <del>) as dag: # [START howto_operator_dlp_create_job_trigger] <add> "example_gcp_dlp_job", schedule_interval=None, start_date=days_ago(1), tags=["example", "dlp_job"] <add>) as dag3: # [START howto_operator_dlp_create_job_trigger] <ide> create_trigger = CloudDLPCreateJobTriggerOperator( <ide> project_id=GCP_PROJECT, <ide> job_trigger=JOB_TRIGGER, <ide> trigger_id=TRIGGER_ID, <del> dag=dag, <ide> task_id="create_trigger", <ide> ) <ide> # [END howto_operator_dlp_create_job_trigger] <del> UPDATED_SCHEDULE = {"recurrence_period_duration": {"seconds": 2 * 60 * 60 * 24}} <ide> <del> JOB_TRIGGER["triggers"] = [{"schedule": UPDATED_SCHEDULE}] <add> JOB_TRIGGER["triggers"] = [{"schedule": {"recurrence_period_duration": {"seconds": 2 * 60 * 60 * 24}}}] <ide> <ide> # [START howto_operator_dlp_update_job_trigger] <ide> update_trigger = CloudDLPUpdateJobTriggerOperator( <ide> project_id=GCP_PROJECT, <ide> job_trigger_id=TRIGGER_ID, <ide> job_trigger=JOB_TRIGGER, <del> dag=dag, <ide> task_id="update_info_type", <ide> ) <ide> # [END howto_operator_dlp_update_job_trigger] <ide> # [START howto_operator_dlp_delete_job_trigger] <ide> delete_trigger = CloudDLPDeleteJobTriggerOperator( <del> project_id=GCP_PROJECT, job_trigger_id=TRIGGER_ID, dag=dag, task_id="delete_info_type", <add> project_id=GCP_PROJECT, job_trigger_id=TRIGGER_ID, task_id="delete_info_type" <ide> ) <ide> # [END howto_operator_dlp_delete_job_trigger] <ide> create_trigger >> update_trigger >> delete_trigger <add> <ide><path>airflow/providers/google/cloud/operators/dlp.py <ide> def execute(self, context): <ide> timeout=self.timeout, <ide> metadata=self.metadata, <ide> ) <del> except AlreadyExists: <add> except InvalidArgument as e: <add> if "already in use" not in e.message: <add> raise <ide> trigger = hook.get_job_trigger( <ide> project_id=self.project_id, <ide> job_trigger_id=self.trigger_id, <ide> def execute(self, context): <ide> timeout=self.timeout, <ide> metadata=self.metadata, <ide> ) <del> except AlreadyExists: <add> except InvalidArgument as e: <add> if "already exists" not in e.message: <add> raise <ide> info = hook.get_stored_info_type( <ide> organization_id=self.organization_id, <ide> project_id=self.project_id, <ide><path>tests/providers/google/cloud/operators/test_dlp_system.py <ide> <ide> from tests.providers.google.cloud.utils.gcp_authenticator import GCP_DLP_KEY <ide> from tests.test_utils.gcp_system_helpers import CLOUD_DAG_FOLDER, GoogleSystemTest, provide_gcp_context <add>from airflow.providers.google.cloud.example_dags.example_dlp import OUTPUT_BUCKET, OUTPUT_FILENAME <add> <add> <add>@pytest.fixture(scope="class") <add>def helper(): <add> GoogleSystemTest.create_gcs_bucket(OUTPUT_BUCKET) <add> GoogleSystemTest.upload_content_to_gcs("aaaa\nbbbb", OUTPUT_BUCKET, f"tmp/{OUTPUT_FILENAME}") <add> yield <add> GoogleSystemTest.delete_gcs_bucket(OUTPUT_BUCKET) <ide> <ide> <ide> @pytest.mark.backend("mysql", "postgres") <add>@pytest.mark.usefixtures("helper") <ide> @pytest.mark.credential_file(GCP_DLP_KEY) <ide> class GcpDLPExampleDagsSystemTest(GoogleSystemTest): <ide> @provide_gcp_context(GCP_DLP_KEY) <del> def test_run_example_dag_function(self): <add> def test_run_example_dag(self): <ide> self.run_dag('example_gcp_dlp', CLOUD_DAG_FOLDER) <add> <add> @provide_gcp_context(GCP_DLP_KEY) <add> def test_run_example_info_types(self): <add> self.run_dag('example_gcp_dlp_info_types', CLOUD_DAG_FOLDER) <add> <add> @provide_gcp_context(GCP_DLP_KEY) <add> def test_run_example_dlp_job(self): <add> self.run_dag('example_gcp_dlp_job', CLOUD_DAG_FOLDER)
3
Javascript
Javascript
add snapshot tests for sticky headers
f37fc6705a42263c120f915298faa7c0b4fb35b8
<ide><path>Libraries/Lists/SectionList.js <ide> const MetroListView = require('MetroListView'); <ide> const Platform = require('Platform'); <ide> const React = require('React'); <add>const ScrollView = require('ScrollView'); <ide> const VirtualizedSectionList = require('VirtualizedSectionList'); <ide> <ide> import type {ViewToken} from 'ViewabilityHelper'; <ide> type OptionalProps<SectionT: SectionBase<any>> = { <ide> legacyImplementation?: ?boolean, <ide> }; <ide> <del>type Props<SectionT> = RequiredProps<SectionT> & <add>export type Props<SectionT> = RequiredProps<SectionT> & <ide> OptionalProps<SectionT> & <ide> VirtualizedSectionListProps<SectionT>; <ide> <ide> class SectionList<SectionT: SectionBase<any>> extends React.PureComponent< <ide> /** <ide> * Provides a handle to the underlying scroll responder. <ide> */ <del> getScrollResponder() { <add> getScrollResponder(): ?ScrollView { <ide> const listRef = this._wrapperListRef && this._wrapperListRef.getListRef(); <ide> if (listRef) { <ide> return listRef.getScrollResponder();
1
Python
Python
add initial version of theano/tensorflow backends
cda6a998ef55121223489364fb340e7ea74ffc4c
<ide><path>keras/backend/__init__.py <add>from __future__ import absolute_import <add> <add>_BACKEND = 'theano' <add> <add>if _BACKEND == 'theano': <add> from .theano_backend import * <add>elif _BACKEND == 'tensorflow': <add> from .tensorflow_backend import * <add>else: <add> raise Exception('Unknown backend: ' + str(backend)) <ide><path>keras/backend/common.py <add>import numpy as np <add> <add># the type of float to use throughout the session. <add>_FLOATX = 'float32' <add>_EPSILON = 10e-8 <add> <add> <add>def floatx(): <add> return _FLOATX <add> <add> <add>def set_floatx(floatx): <add> ''' <add> ''' <add> global _FLOATX <add> if floatx not in {'float32', 'float64'}: <add> raise Exception('Unknown floatx type: ' + str(floatx)) <add> _FLOATX = floatx <add> <add> <add>def cast_to_floatx(x): <add> '''Cast a Numpy array to floatx. <add> ''' <add> return np.asarray(x, dtype=_FLOATX) <ide><path>keras/backend/tensorflow_backend.py <add>import tensorflow as tf <add>import numpy as np <add>from .common import _FLOATX, _EPSILON <add> <add># INTERNAL UTILS <add> <add>_SESSION = None <add> <add> <add>def _get_session(): <add> global _SESSION <add> if _SESSION is None: <add> _SESSION = tf.Session('') <add> return _SESSION <add> <add> <add>def _set_session(session): <add> global _SESSION <add> _SESSION = session <add> <add> <add># VARIABLE MANIPULATION <add> <add>def variable(value, dtype=_FLOATX, name=None): <add> v = tf.Variable(np.asarray(value, dtype=dtype), name=name) <add> _get_session().run(v.initializer) <add> return v <add> <add> <add>def shape(x): <add> return x.get_shape() <add> <add> <add>def eval(x): <add> '''Run a graph. <add> ''' <add> return x.eval(session=_get_session()) <add> <add> <add>def zeros(shape, dtype=_FLOATX, name=None): <add> return variable(np.zeros(shape), dtype, name) <add> <add> <add>def ones(shape, dtype=_FLOATX, name=None): <add> return variable(np.ones(shape), dtype, name) <add> <add> <add>def placeholder(shape=None, ndim=None, dtype=_FLOATX, name=None): <add> return tf.placeholder(dtype, shape=shape, name=name) <add> <add> <add># LINEAR ALGEBRA <add> <add>def dot(x, y): <add> return tf.matmul(x, y) <add> <add> <add>def transpose(x): <add> return tf.transpose(x) <add> <add> <add># ELEMENT-WISE OPERATIONS <add> <add>def max(x, axis=None, keepdims=False): <add> return tf.reduce_max(x, reduction_indices=axis, keep_dims=keepdims) <add> <add> <add>def min(x, axis=None, keepdims=False): <add> return tf.reduce_min(x, reduction_indices=axis, keep_dims=keepdims) <add> <add> <add>def sum(x, axis=None, keepdims=False): <add> '''Sum of the values in a tensor, alongside the specified axis. <add> ''' <add> return tf.reduce_sum(x, reduction_indices=axis, keep_dims=keepdims) <add> <add> <add>def mean(x, axis=None, keepdims=False): <add> return tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims) <add> <add> <add>def any(x, axis=None, keepdims=False): <add> '''Bitwise reduction (logical OR). <add> <add> Return array of int8 (0s and 1s). <add> ''' <add> x = tf.cast(x, tf.bool) <add> x = tf.reduce_any(x, reduction_indices=axis, keep_dims=keepdims) <add> return tf.cast(x, tf.int8) <add> <add> <add>def argmax(x, axis=-1): <add> axis = axis % len(x.get_shape()) <add> return tf.argmax(x, axis) <add> <add> <add>def argmin(x, axis=-1): <add> axis = axis % len(x.get_shape()) <add> return tf.argmin(x, axis) <add> <add> <add>def square(x): <add> return tf.square(x) <add> <add> <add>def abs(x): <add> return tf.abs(x) <add> <add> <add>def sqrt(x): <add> x = tf.clip_by_value(x, _EPSILON, np.inf) <add> return tf.sqrt(x) <add> <add> <add>def exp(x): <add> return tf.exp(x) <add> <add> <add>def log(x): <add> return tf.log(x) <add> <add> <add>def round(x): <add> return tf.round(x) <add> <add> <add>def clip(x, min_value, max_value): <add> if max_value < min_value: <add> max_value = min_value <add> return tf.clip_by_value(x, min_value, max_value) <add> <add> <add>def equal(x, y): <add> return tf.equal(x, y) <add> <add> <add>def maximum(x, y): <add> return tf.maximum(x, y) <add> <add> <add>def minimum(x, y): <add> return tf.maximum(x, y) <add> <add> <add># SHAPE OPERATIONS <add> <add>def concatenate(tensors, axis=-1): <add> axis = axis % len(tensors[0].get_shape()) <add> return tf.concat(axis, tensors) <add> <add> <add>def reshape(x, shape): <add> return tf.reshape(x, shape) <add> <add> <add>def permute_dimensions(x, pattern): <add> '''Transpose dimensions. <add> <add> pattern should be a tuple or list of <add> dimension indices, e.g. [0, 2, 1]. <add> ''' <add> return tf.transpose(x, perm=pattern) <add> <add> <add>def repeat(x, n, axis=-1): <add> tiling_pattern = [1 for _ in range(len(x.get_shape()))] <add> tiling_pattern[axis] = n <add> return tf.tile(x, tiling_pattern) <add> <add> <add>def flatten(x): <add> x = tf.reshape(x, [-1, np.prod(x.get_shape()[1:].as_list())]) <add> return x <add> <add> <add># VALUE MANIPULATION <add> <add>def get_value(x): <add> '''Technically the same as eval() for TF. <add> ''' <add> return x.eval(session=_get_session()) <add> <add> <add>def set_value(x, value): <add> tf.assign(x, value).op.run(session=_get_session()) <add> <add> <add># GRAPH MANIPULATION <add> <add>class Function(object): <add> <add> def __init__(self, inputs, outputs, updates=[]): <add> self.inputs = list(inputs) <add> self.outputs = list(outputs) <add> with tf.control_dependencies(self.outputs): <add> self.updates = [tf.assign(p, new_p) for (p, new_p) in updates] <add> <add> def __call__(self, inputs): <add> names = [v.name for v in self.inputs] <add> feed_dict = dict(zip(names, inputs)) <add> session = _get_session() <add> updated = session.run(self.outputs + self.updates, feed_dict=feed_dict) <add> return updated[:len(self.outputs)] <add> <add> <add>def function(inputs, outputs, updates=[]): <add> return Function(inputs, outputs, updates=updates) <add> <add> <add>def gradients(loss, variables): <add> return tf.gradients(loss, variables) <add> <add> <add># CONTROL FLOW <add> <add>def rnn(step_function, inputs, initial_states, go_backwards=False): <add> '''TODO <add> ''' <add> pass <add> <add> <add>def switch(condition, then_expression, else_expression): <add> '''condition: scalar tensor. <add> ''' <add> return tf.control_flow_ops.cond(condition, <add> lambda: then_expression, <add> lambda: else_expression) <add> <add> <add># NN OPERATIONS <add> <add>def relu(x, alpha=0., max_value=None): <add> '''ReLU. <add> <add> alpha: slope of negative section. <add> ''' <add> negative_part = tf.nn.relu(-x) <add> x = tf.nn.relu(x) <add> if max_value is not None: <add> x = tf.clip_by_value(x, 0., max_value) <add> x -= alpha * negative_part <add> return x <add> <add> <add>def softmax(x): <add> return tf.nn.softmax(x) <add> <add> <add>def softplus(x): <add> return tf.nn.softplus(x) <add> <add> <add>def categorical_crossentropy(output, target, from_logits=False): <add> '''Note: tf.nn.softmax_cross_entropy_with_logits <add> expects logits, Keras expects probabilities. <add> ''' <add> if not from_logits: <add> # scale preds so that the class probas of each sample sum to 1 <add> output /= tf.reduce_sum(output, <add> reduction_indices=len(output.get_shape())-1, <add> keep_dims=True) <add> # manual computation of crossentropy <add> output = tf.clip_by_value(output, _EPSILON, 1.-_EPSILON) <add> return - tf.reduce_sum(target * tf.log(output), <add> reduction_indices=len(output.get_shape())-1) <add> else: <add> return tf.nn.softmax_cross_entropy_with_logits(output, target) <add> <add> <add>def binary_crossentropy(output, target, from_logits=False): <add> '''Note: tf.nn.sigmoid_cross_entropy_with_logits <add> expects logits, Keras expects probabilities. <add> ''' <add> if not from_logits: <add> # transform back to logits <add> output = tf.clip_by_value(output, _EPSILON, 1.-_EPSILON) <add> output = tf.log(output / (1 - output)) <add> return tf.nn.sigmoid_cross_entropy_with_logits(output, target) <add> <add> <add>def sigmoid(x): <add> return tf.nn.sigmoid(x) <add> <add> <add>def hard_sigmoid(x): <add> x = (0.2 * x) + 0.5 <add> x = tf.clip_by_value(x, 0., 1.) <add> return x <add> <add> <add>def tanh(x): <add> return tf.nn.tanh(x) <add> <add> <add>def dropout(x, level, seed=None): <add> retain_prob = 1. - level <add> if seed is None: <add> seed = np.random.randint(10e6) <add> # the dummy 1. works around a TF bug <add> # (float32_ref vs. float32 incomptability) <add> return tf.nn.dropout(x * 1., retain_prob, seed=seed) <add> <add> <add># CONVOLUTIONS <add> <add> <add>def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th'): <add> ''' <add> Run on cuDNN if available. <add> border_mode: string, "same" or "valid". <add> dim_ordering: whether to use Theano or TensorFlow dimension ordering <add> in inputs/kernels/ouputs. <add> ''' <add> if border_mode == 'same': <add> padding = 'SAME' <add> elif border_mode == 'valid': <add> padding = 'VALID' <add> else: <add> raise Exception('Invalid border mode: ' + str(border_mode)) <add> <add> strides = (1,) + strides + (1,) <add> <add> if dim_ordering == 'th': <add> # TF uses the last dimension as channel dimension, <add> # instead of the 2nd one. <add> # TH input shape: (samples, input_depth, rows, cols) <add> # TF input shape: (samples, rows, cols, input_depth) <add> # TH kernel shape: (depth, input_depth, rows, cols) <add> # TF kernel shape: (rows, cols, input_depth, depth) <add> x = tf.transpose(x, (0, 2, 3, 1)) <add> kernel = tf.transpose(kernel, (2, 3, 1, 0)) <add> x = tf.nn.conv2d(x, kernel, strides, padding=padding) <add> x = tf.transpose(x, (0, 3, 1, 2)) <add> elif dim_ordering == 'tf': <add> x = tf.nn.conv2d(x, kernel, strides, padding=padding) <add> else: <add> raise Exception('Unknown dim_ordering: ' + str(dim_ordering)) <add> return x <add> <add> <add>def maxpool2d(x, pool_size, strides=(1, 1), border_mode='valid', dim_ordering='th'): <add> ''' <add> pool_size: tuple of 2 integers. <add> strides: tuple of 2 integers. <add> border_mode: one of "valid", "same". <add> dim_ordering: one of "th", "tf". <add> ''' <add> if border_mode == 'same': <add> padding = 'SAME' <add> elif border_mode == 'valid': <add> padding = 'VALID' <add> else: <add> raise Exception('Invalid border mode: ' + str(border_mode)) <add> <add> strides = (1,) + strides + (1,) <add> pool_size = (1,) + pool_size + (1,) <add> <add> if dim_ordering == 'th': <add> # TF uses the last dimension as channel dimension, instead of the 2nd one. <add> # TH input shape: (samples, input_depth, rows, cols) <add> # TF input shape: (samples, rows, cols, input_depth) <add> # TH kernel shape: (depth, input_depth, rows, cols) <add> # TF kernel shape: (rows, cols, input_depth, depth) <add> x = tf.transpose(x, (0, 2, 3, 1)) <add> x = tf.nn.max_pool(x, pool_size, strides, padding=padding) <add> x = tf.transpose(x, (0, 3, 1, 2)) <add> elif dim_ordering == 'tf': <add> x = tf.nn.max_pool(x, pool_size, strides, padding=padding) <add> else: <add> raise Exception('Unknown dim_ordering: ' + str(dim_ordering)) <add> return x <add> <add> <add># RANDOMNESS <add> <add>def random_normal(shape, mean=0.0, std=1.0, dtype=_FLOATX, seed=None): <add> if seed is None: <add> seed = np.random.randint(10e6) <add> return tf.random_normal(shape, mean=mean, stddev=std, <add> dtype=dtype, seed=seed) <add> <add> <add>def random_uniform(shape, low=0.0, high=1.0, dtype=_FLOATX, seed=None): <add> if seed is None: <add> seed = np.random.randint(10e6) <add> return tf.random_uniform(shape, minval=low, maxval=high, <add> dtype=dtype, seed=seed) <ide><path>keras/backend/theano_backend.py <add>import theano <add>from theano import tensor as T <add>from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams <add>from theano.tensor.signal import downsample <add>import numpy as np <add>from .common import _FLOATX, _EPSILON <add> <add> <add># INTERNAL UTILS <add> <add>def _on_gpu(): <add> '''Returns whether the session is set to <add> run on GPU or not (i.e. on CPU). <add> ''' <add> return theano.config.device[:3] == 'gpu' <add> <add> <add>if _on_gpu(): <add> '''Import cuDNN only if running on GPU: <add> not having Cuda install should not <add> prevent from running the present code. <add> ''' <add> from theano.sandbox.cuda import dnn <add> <add> <add># VARIABLE MANIPULATION <add> <add>def variable(value, dtype=_FLOATX, name=None): <add> '''Instantiate a tensor variable. <add> ''' <add> return theano.shared(np.asarray(value, dtype=dtype), name=name) <add> <add> <add>def shape(x): <add> '''Return the shape of a tensor. <add> <add> Warning: type returned will be different for <add> Theano backend (Theano tensor type) and TF backend (TF TensorShape). <add> ''' <add> return x.shape <add> <add> <add>def eval(x): <add> '''Run a graph. <add> ''' <add> return x.eval() <add> <add> <add>def zeros(shape, dtype=_FLOATX, name=None): <add> '''Instantiate an all-zeros variable. <add> ''' <add> return variable(np.zeros(shape), dtype, name) <add> <add> <add>def ones(shape, dtype=_FLOATX, name=None): <add> '''Instantiate an all-ones variable. <add> ''' <add> return variable(np.ones(shape), dtype, name) <add> <add> <add>def placeholder(shape=None, ndim=None, dtype=_FLOATX, name=None): <add> '''Instantiate an input data placeholder variable. <add> ''' <add> if shape is None and ndim is None: <add> raise Exception('Specify either a shape or ndim value.') <add> if shape is not None: <add> ndim = len(shape) <add> if ndim == 0: <add> return T.scalar(name=name, dtype=dtype) <add> elif ndim == 1: <add> return T.vector(name=name, dtype=dtype) <add> elif ndim == 2: <add> return T.matrix(name=name, dtype=dtype) <add> elif ndim == 3: <add> return T.tensor3(name=name, dtype=dtype) <add> elif ndim == 4: <add> return T.tensor4(name=name, dtype=dtype) <add> else: <add> raise Exception('ndim too large: ' + str(ndim)) <add> <add> <add># LINEAR ALGEBRA <add> <add>''' <add>Assumed overridden: <add>+, -, /, *, +=, -=, *=, /= <add>''' <add> <add> <add>def dot(x, y): <add> return T.dot(x, y) <add> <add> <add>def transpose(x): <add> return T.transpose(x) <add> <add> <add># ELEMENT-WISE OPERATIONS <add> <add>def max(x, axis=None, keepdims=False): <add> return T.max(x, axis=axis, keepdims=keepdims) <add> <add> <add>def min(x, axis=None, keepdims=False): <add> return T.min(x, axis=axis, keepdims=keepdims) <add> <add> <add>def sum(x, axis=None, keepdims=False): <add> '''Sum of the values in a tensor, alongside the specified axis. <add> ''' <add> return T.sum(x, axis=axis, keepdims=keepdims) <add> <add> <add>def mean(x, axis=None, keepdims=False): <add> return T.mean(x, axis=axis, keepdims=keepdims) <add> <add> <add>def any(x, axis=None, keepdims=False): <add> '''Bitwise reduction (logical OR). <add> ''' <add> return T.any(x, axis=axis, keepdims=keepdims) <add> <add> <add>def argmax(x, axis=-1): <add> return T.argmax(x, axis=axis, keepdims=False) <add> <add> <add>def argmin(x, axis=-1): <add> return T.argmin(x, axis=axis, keepdims=False) <add> <add> <add>def square(x): <add> return T.sqr(x) <add> <add> <add>def abs(x): <add> return T.abs_(x) <add> <add> <add>def sqrt(x): <add> x = T.clip(x, _EPSILON, np.inf) <add> return T.sqrt(x) <add> <add> <add>def exp(x): <add> return T.exp(x) <add> <add> <add>def log(x): <add> return T.log(x) <add> <add> <add>def round(x): <add> return T.round(x) <add> <add> <add>def clip(x, min_value, max_value): <add> if max_value < min_value: <add> max_value = min_value <add> return T.clip(x, min_value, max_value) <add> <add> <add>def equal(x, y): <add> return T.eq(x, y) <add> <add> <add>def maximum(x, y): <add> return T.maximum(x, y) <add> <add> <add>def minimum(x, y): <add> return T.maximum(x, y) <add> <add> <add># SHAPE OPERATIONS <add> <add>def concatenate(tensors, axis=-1): <add> return T.concatenate(tensors, axis=axis) <add> <add> <add>def reshape(x, shape): <add> return T.reshape(x, shape) <add> <add> <add>def permute_dimensions(x, pattern): <add> '''Transpose dimensions. <add> <add> pattern should be a tuple or list of <add> dimension indices, e.g. [0, 2, 1]. <add> ''' <add> pattern = tuple(pattern) <add> return x.dimshuffle(pattern) <add> <add> <add>def repeat(x, n, axis=-1): <add> return T.extra_ops.repeat(x, n, axis=axis) <add> <add> <add>def flatten(x): <add> x = T.reshape(x, (x.shape[0], T.prod(x.shape) // x.shape[0])) <add> return x <add> <add> <add># VALUE MANIPULATION <add> <add>def get_value(x): <add> if not hasattr(x, 'get_value'): <add> raise Exception("'get_value() can only be called on a variable. " + <add> "If you have an expression instead, use eval().") <add> return x.get_value() <add> <add> <add>def set_value(x, value): <add> x.set_value(np.asarray(value, dtype=x.dtype)) <add> <add> <add># GRAPH MANIPULATION <add> <add>class Function(object): <add> <add> def __init__(self, inputs, outputs, updates=[], **kwargs): <add> self.function = theano.function(inputs, outputs, updates=updates, <add> allow_input_downcast=True, **kwargs) <add> <add> def __call__(self, inputs): <add> if len(inputs) == 1: <add> inputs = inputs[0] # Theano is pretty dumb there tbh <add> return self.function(inputs) <add> <add> <add>def function(inputs, outputs, updates=[]): <add> return Function(inputs, outputs, updates=updates) <add> <add> <add>def gradients(loss, variables): <add> return T.grad(loss, variables) <add> <add> <add># CONTROL FLOW <add> <add>def rnn(step_function, inputs, initial_states, go_backwards=False): <add> '''TODO <add> <add> Wrapper for scan <add> ''' <add> pass <add> <add> <add>def switch(condition, then_expression, else_expression): <add> '''condition: scalar tensor. <add> ''' <add> return T.switch(condition, then_expression, else_expression) <add> <add> <add># NN OPERATIONS <add> <add>def relu(x, alpha=0., max_value=None): <add> x = T.nnet.relu(x, alpha) <add> if max_value is not None: <add> x = T.minimum(x, max_value) <add> return x <add> <add> <add>def softmax(x): <add> return T.nnet.softmax(x) <add> <add> <add>def softplus(x): <add> return T.nnet.softplus(x) <add> <add> <add>def categorical_crossentropy(output, target, from_logits=False): <add> if from_logits: <add> output = T.nnet.softmax(output) <add> else: <add> # scale preds so that the class probas of each sample sum to 1 <add> output /= output.sum(axis=-1, keepdims=True) <add> # avoid numerical instability with _EPSILON clipping <add> output = T.clip(output, _EPSILON, 1.0 - _EPSILON) <add> return T.nnet.categorical_crossentropy(output, target) <add> <add> <add>def binary_crossentropy(output, target, from_logits=False): <add> if from_logits: <add> output = T.nnet.sigmoid(output) <add> # avoid numerical instability with _EPSILON clipping <add> output = T.clip(output, _EPSILON, 1.0 - _EPSILON) <add> return T.nnet.binary_crossentropy(output, target) <add> <add> <add>def sigmoid(x): <add> return T.nnet.sigmoid(x) <add> <add> <add>def hard_sigmoid(x): <add> return T.nnet.hard_sigmoid(x) <add> <add> <add>def tanh(x): <add> return T.tanh(x) <add> <add> <add>def dropout(x, level, seed=None): <add> if level < 0. or level >= 1: <add> raise Exception('Dropout level must be in interval [0, 1[.') <add> if seed is None: <add> seed = np.random.randint(10e6) <add> rng = RandomStreams(seed=seed) <add> retain_prob = 1. - level <add> x *= rng.binomial(x.shape, p=retain_prob, dtype=x.dtype) <add> x /= retain_prob <add> return x <add> <add> <add># CONVOLUTIONS <add> <add> <add>def conv2d(x, kernel, strides=(1, 1), border_mode='valid', dim_ordering='th'): <add> ''' <add> Run on cuDNN if available. <add> border_mode: string, "same" or "valid". <add> ''' <add> if dim_ordering not in {'th', 'tf'}: <add> raise Exception('Unknown dim_ordering ' + str(dim_ordering)) <add> <add> if dim_ordering == 'tf': <add> # TF uses the last dimension as channel dimension, <add> # instead of the 2nd one. <add> # TH input shape: (samples, input_depth, rows, cols) <add> # TF input shape: (samples, rows, cols, input_depth) <add> # TH kernel shape: (depth, input_depth, rows, cols) <add> # TF kernel shape: (rows, cols, input_depth, depth) <add> x = x.dimshuffle((0, 3, 1, 2)) <add> kernel = kernel.dimshuffle((3, 2, 0, 1)) <add> <add> if _on_gpu() and dnn.dnn_available(): <add> if border_mode == 'same': <add> assert(strides == (1, 1)) <add> pad_x = (kernel.shape[2] - strides[0]) // 2 <add> pad_y = (kernel.shape[3] - strides[1]) // 2 <add> conv_out = dnn.dnn_conv(img=x, <add> kerns=kernel, <add> border_mode=(pad_x, pad_y)) <add> else: <add> conv_out = dnn.dnn_conv(img=x, <add> kerns=kernel, <add> border_mode=border_mode, <add> subsample=strides) <add> else: <add> if border_mode == 'same': <add> th_border_mode = 'full' <add> assert(strides == (1, 1)) <add> elif border_mode == 'valid': <add> th_border_mode = 'valid' <add> else: <add> raise Exception('Border mode not supported: ' + str(border_mode)) <add> <add> conv_out = T.nnet.conv.conv2d(x, kernel, <add> border_mode=th_border_mode, <add> subsample=strides) <add> if border_mode == 'same': <add> shift_x = (kernel.shape[2] - 1) // 2 <add> shift_y = (kernel.shape[3] - 1) // 2 <add> conv_out = conv_out[:, :, <add> shift_x:x.shape[2] + shift_x, <add> shift_y:x.shape[3] + shift_y] <add> if dim_ordering == 'tf': <add> conv_out = conv_out.dimshuffle((0, 2, 3, 1)) <add> return conv_out <add> <add> <add>def maxpool2d(x, pool_size, strides=(1, 1), border_mode='valid', dim_ordering='th'): <add> if border_mode == 'same': <add> # TODO: add implementation for border_mode="same" <add> raise Exception('border_mode="same" not supported with Theano.') <add> elif border_mode == 'valid': <add> ignore_border = True <add> padding = (0, 0) <add> else: <add> raise Exception('Invalid border mode: ' + str(border_mode)) <add> <add> if dim_ordering not in {'th', 'tf'}: <add> raise Exception('Unknown dim_ordering ' + str(dim_ordering)) <add> <add> if dim_ordering == 'tf': <add> x = x.dimshuffle((0, 3, 1, 2)) <add> <add> pool_out = downsample.max_pool_2d(x, <add> ds=pool_size, <add> st=strides, <add> ignore_border=ignore_border, <add> padding=padding, <add> mode='average_exc_pad') <add> if dim_ordering == 'tf': <add> pool_out = pool_out.dimshuffle((0, 2, 3, 1)) <add> return pool_out <add> <add> <add># RANDOMNESS <add> <add>def random_normal(shape, mean=0.0, std=1.0, dtype=_FLOATX, seed=None): <add> if seed is None: <add> seed = np.random.randint(10e6) <add> rng = RandomStreams(seed=seed) <add> return rng.normal(size=shape, avg=mean, std=std, dtype=dtype) <add> <add> <add>def random_uniform(shape, low=0.0, high=1.0, dtype=_FLOATX, seed=None): <add> if seed is None: <add> seed = np.random.randint(10e6) <add> rng = RandomStreams(seed=seed) <add> return rng.uniform(shape, low=low, high=high, dtype=dtype) <add> <add> <add> <add>''' <add>more TODO: <add> <add>shape_padright/left <add>tensordot <add>batched_tensordot <add> <add>addbroadcast -> remove usage? <add>unbroadcast -> remove usage? <add> <add>embedding: make sure that [] operator works for TF <add>''' <ide><path>tests/auto/keras/backend/test_backends.py <add>import unittest <add>from numpy.testing import assert_allclose <add>import numpy as np <add> <add>np.random.seed(1337) <add> <add>from keras.backend import theano_backend as KTH <add>from keras.backend import tensorflow_backend as KTF <add> <add> <add>def check_single_tensor_operation(function_name, input_shape, **kwargs): <add> val = np.random.random(input_shape) - 0.5 <add> xth = KTH.variable(val) <add> xtf = KTF.variable(val) <add> <add> zth = KTH.eval(getattr(KTH, function_name)(xth, **kwargs)) <add> ztf = KTF.eval(getattr(KTF, function_name)(xtf, **kwargs)) <add> <add> assert zth.shape == ztf.shape <add> assert_allclose(zth, ztf, atol=1e-06) <add> <add> <add>def check_two_tensor_operation(function_name, x_input_shape, <add> y_input_shape, **kwargs): <add> xval = np.random.random(x_input_shape) - 0.5 <add> xth = KTH.variable(xval) <add> xtf = KTF.variable(xval) <add> <add> yval = np.random.random(y_input_shape) - 0.5 <add> yth = KTH.variable(yval) <add> ytf = KTF.variable(yval) <add> <add> zth = KTH.eval(getattr(KTH, function_name)(xth, yth, **kwargs)) <add> ztf = KTF.eval(getattr(KTF, function_name)(xtf, ytf, **kwargs)) <add> <add> assert zth.shape == ztf.shape <add> assert_allclose(zth, ztf, atol=1e-06) <add> <add> <add>class TestBackend(unittest.TestCase): <add> <add> def test_linear_operations(self): <add> check_two_tensor_operation('dot', (4, 2), (2, 4)) <add> check_single_tensor_operation('transpose', (4, 2)) <add> <add> def test_shape_operations(self): <add> # concatenate <add> xval = np.random.random((4, 3)) <add> xth = KTH.variable(xval) <add> xtf = KTF.variable(xval) <add> yval = np.random.random((4, 2)) <add> yth = KTH.variable(yval) <add> ytf = KTF.variable(yval) <add> zth = KTH.eval(KTH.concatenate([xth, yth], axis=-1)) <add> ztf = KTF.eval(KTF.concatenate([xtf, ytf], axis=-1)) <add> assert zth.shape == ztf.shape <add> assert_allclose(zth, ztf, atol=1e-06) <add> <add> check_single_tensor_operation('reshape', (4, 2), shape=(8, 1)) <add> check_single_tensor_operation('permute_dimensions', (4, 2, 3), <add> pattern=(2, 0, 1)) <add> check_single_tensor_operation('repeat', (4, 1), n=3) <add> check_single_tensor_operation('flatten', (4, 1)) <add> <add> def test_value_manipulation(self): <add> val = np.random.random((4, 2)) <add> xth = KTH.variable(val) <add> xtf = KTF.variable(val) <add> <add> valth = KTH.get_value(xth) <add> valtf = KTF.get_value(xtf) <add> assert valtf.shape == valth.shape <add> assert_allclose(valth, valtf, atol=1e-06) <add> <add> val = np.random.random((4, 2)) <add> KTH.set_value(xth, val) <add> KTF.set_value(xtf, val) <add> <add> valth = KTH.get_value(xth) <add> valtf = KTF.get_value(xtf) <add> assert valtf.shape == valth.shape <add> assert_allclose(valth, valtf, atol=1e-06) <add> <add> def test_elementwise_operations(self): <add> check_single_tensor_operation('max', (4, 2)) <add> check_single_tensor_operation('max', (4, 2), axis=1, keepdims=True) <add> <add> check_single_tensor_operation('min', (4, 2)) <add> check_single_tensor_operation('min', (4, 2), axis=1, keepdims=True) <add> <add> check_single_tensor_operation('mean', (4, 2)) <add> check_single_tensor_operation('mean', (4, 2), axis=1, keepdims=True) <add> <add> # does not work yet, wait for bool <-> int casting in TF (coming soon) <add> # check_single_tensor_operation('any', (4, 2)) <add> # check_single_tensor_operation('any', (4, 2), axis=1, keepdims=True) <add> <add> check_single_tensor_operation('argmax', (4, 2)) <add> check_single_tensor_operation('argmax', (4, 2), axis=1) <add> <add> check_single_tensor_operation('argmin', (4, 2)) <add> check_single_tensor_operation('argmin', (4, 2), axis=1) <add> <add> check_single_tensor_operation('square', (4, 2)) <add> check_single_tensor_operation('abs', (4, 2)) <add> check_single_tensor_operation('sqrt', (4, 2)) <add> check_single_tensor_operation('exp', (4, 2)) <add> check_single_tensor_operation('log', (4, 2)) <add> check_single_tensor_operation('round', (4, 2)) <add> check_single_tensor_operation('clip', (4, 2), min_value=0.4, <add> max_value=0.6) <add> <add> # two-tensor ops <add> check_two_tensor_operation('equal', (4, 2), (4, 2)) <add> check_two_tensor_operation('maximum', (4, 2), (4, 2)) <add> check_two_tensor_operation('minimum', (4, 2), (4, 2)) <add> <add> def test_gradient(self): <add> val = np.random.random((4, 2)) <add> xth = KTH.variable(val) <add> xtf = KTF.variable(val) <add> <add> expth = xth * KTH.exp(xth) <add> exptf = xtf * KTF.exp(xtf) <add> lossth = KTH.sum(expth) <add> losstf = KTF.sum(exptf) <add> <add> gradth = KTH.gradients(lossth, [expth]) <add> gradtf = KTF.gradients(losstf, [exptf]) <add> <add> zth = KTH.eval(gradth[0]) <add> ztf = KTF.eval(gradtf[0]) <add> assert zth.shape == ztf.shape <add> assert_allclose(zth, ztf, atol=1e-06) <add> <add> def test_function(self): <add> val = np.random.random((4, 2)) <add> input_val = np.random.random((4, 2)) <add> <add> xth = KTH.variable(val) <add> xtf = KTF.variable(val) <add> yth = KTH.placeholder(ndim=2) <add> ytf = KTF.placeholder(ndim=2) <add> <add> exp_th = KTH.square(xth) + yth <add> exp_tf = KTF.square(xtf) + ytf <add> <add> update_th = xth * 2 <add> update_tf = xtf * 2 <add> fth = KTH.function([yth], [exp_th], updates=[(xth, update_th)]) <add> ftf = KTF.function([ytf], [exp_tf], updates=[(xtf, update_tf)]) <add> <add> function_outputs_th = fth([input_val])[0] <add> function_outputs_tf = ftf([input_val])[0] <add> assert function_outputs_th.shape == function_outputs_tf.shape <add> assert_allclose(function_outputs_th, function_outputs_tf, atol=1e-06) <add> <add> new_val_th = KTH.get_value(xth) <add> new_val_tf = KTF.get_value(xtf) <add> assert new_val_th.shape == new_val_tf.shape <add> assert_allclose(new_val_th, new_val_tf, atol=1e-06) <add> <add> def test_rnn(self): <add> pass <add> <add> def test_switch(self): <add> val = np.random.random() <add> xth = KTH.variable(val) <add> xth = KTH.switch(xth >= 0.5, xth * 0.1, xth * 0.2) <add> <add> xtf = KTF.variable(val) <add> xtf = KTF.switch(xtf >= 0.5, xtf * 0.1, xtf * 0.2) <add> <add> zth = KTH.eval(xth) <add> ztf = KTF.eval(xtf) <add> <add> assert zth.shape == ztf.shape <add> assert_allclose(zth, ztf, atol=1e-06) <add> <add> def test_nn_operations(self): <add> check_single_tensor_operation('relu', (4, 2), alpha=0.1, max_value=0.5) <add> check_single_tensor_operation('softmax', (4, 10)) <add> check_single_tensor_operation('softplus', (4, 10)) <add> <add> check_single_tensor_operation('sigmoid', (4, 2)) <add> check_single_tensor_operation('hard_sigmoid', (4, 2)) <add> check_single_tensor_operation('tanh', (4, 2)) <add> <add> # dropout <add> val = np.random.random((20, 20)) <add> xth = KTH.variable(val) <add> xtf = KTF.variable(val) <add> zth = KTH.eval(KTH.dropout(xth, level=0.2)) <add> ztf = KTF.eval(KTF.dropout(xtf, level=0.2)) <add> assert zth.shape == ztf.shape <add> # dropout patterns are different, only check mean <add> assert np.abs(zth.mean() - ztf.mean()) < 0.05 <add> <add> check_two_tensor_operation('binary_crossentropy', (4, 2), (4, 2), from_logits=True) <add> check_two_tensor_operation('categorical_crossentropy', (4, 2), (4, 2), from_logits=True) <add> check_two_tensor_operation('binary_crossentropy', (4, 2), (4, 2), from_logits=False) <add> <add> check_two_tensor_operation('categorical_crossentropy', (4, 2), (4, 2), from_logits=False) <add> <add> # def test_conv2d(self): <add> # '''conv2d works "properly" with Theano and TF but outputs different <add> # values in each case. Cause unclear (input / kernel shape format?) <add> # ''' <add> # # TH kernel shape: (depth, input_depth, rows, cols) <add> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 2, 2), <add> # strides=(1, 1), border_mode='valid') <add> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 2, 2), <add> # strides=(1, 1), border_mode='same') <add> <add> # # TF kernel shape: (rows, cols, input_depth, depth) <add> # check_two_tensor_operation('conv2d', (5, 10, 12, 3), (2, 2, 3, 4), <add> # strides=(1, 1), border_mode='valid', dim_ordering='tf') <add> # check_two_tensor_operation('conv2d', (5, 10, 12, 3), (2, 2, 3, 4), <add> # strides=(1, 1), border_mode='same', dim_ordering='tf') <add> <add> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 3, 3), <add> # strides=(1, 1), border_mode='valid') <add> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 3, 3), <add> # strides=(1, 1), border_mode='same') <add> <add> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 3, 3), <add> # strides=(2, 2), border_mode='valid') <add> <add> # def test_maxpool2d(self): <add> # '''maxpool2d works "properly" with Theano and TF but outputs different <add> # values in each case. Cause unclear (input shape format?) <add> # ''' <add> # check_single_tensor_operation('maxpool2d', (5, 3, 10, 12), pool_size=(2, 2), <add> # strides=(1, 1), border_mode='valid') <add> <add> # check_single_tensor_operation('maxpool2d', (5, 3, 9, 11), pool_size=(2, 2), <add> # strides=(1, 1), border_mode='valid') <add> <add> # check_single_tensor_operation('maxpool2d', (5, 3, 9, 11), pool_size=(2, 3), <add> # strides=(1, 1), border_mode='valid') <add> <add> def test_random_normal(self): <add> mean = 0. <add> std = 1. <add> rand = KTF.get_value(KTF.random_normal((1000, 1000), mean=mean, std=std)) <add> assert(rand.shape == (1000, 1000)) <add> assert(np.abs(np.mean(rand) - mean) < 0.01) <add> assert(np.abs(np.std(rand) - std) < 0.01) <add> <add> rand = KTF.get_value(KTF.random_normal((1000, 1000), mean=mean, std=std)) <add> assert(rand.shape == (1000, 1000)) <add> assert(np.abs(np.mean(rand) - mean) < 0.01) <add> assert(np.abs(np.std(rand) - std) < 0.01) <add> <add> def test_random_uniform(self): <add> mean = 0. <add> std = 1. <add> rand = KTF.get_value(KTF.random_normal((1000, 1000), mean=mean, std=std)) <add> assert(rand.shape == (1000, 1000)) <add> assert(np.abs(np.mean(rand) - mean) < 0.01) <add> assert(np.abs(np.std(rand) - std) < 0.01) <add> <add> rand = KTF.get_value(KTF.random_normal((1000, 1000), mean=mean, std=std)) <add> assert(rand.shape == (1000, 1000)) <add> assert(np.abs(np.mean(rand) - mean) < 0.01) <add> assert(np.abs(np.std(rand) - std) < 0.01) <add> <add> <add>if __name__ == '__main__': <add> unittest.main()
5
Go
Go
make getpidsforcontainer() a driver call
335bc39c9a5abfdbd07914ae1b8667a9d8590a6e
<ide><path>execdriver/chroot/driver.go <ide> func (d *driver) Info(id string) execdriver.Info { <ide> func (d *driver) Name() string { <ide> return fmt.Sprintf("%s-%s", DriverName, Version) <ide> } <add> <add>func (d *driver) GetPidsForContainer(id string) ([]int, error) { <add> return nil, fmt.Errorf("Not supported") <add>} <ide><path>execdriver/driver.go <ide> type Info interface { <ide> type Driver interface { <ide> Run(c *Command, startCallback StartCallback) (int, error) // Run executes the process and blocks until the process exits and returns the exit code <ide> Kill(c *Command, sig int) error <del> Restore(c *Command) error // Wait and try to re-attach on an out of process command <del> Name() string // Driver name <del> Info(id string) Info // "temporary" hack (until we move state from core to plugins) <add> Restore(c *Command) error // Wait and try to re-attach on an out of process command <add> Name() string // Driver name <add> Info(id string) Info // "temporary" hack (until we move state from core to plugins) <add> GetPidsForContainer(id string) ([]int, error) // Returns a list of pids for the given container. <ide> } <ide> <ide> // Network settings of the container <ide><path>execdriver/lxc/driver.go <ide> package lxc <ide> import ( <ide> "fmt" <ide> "github.com/dotcloud/docker/execdriver" <add> "github.com/dotcloud/docker/pkg/cgroups" <ide> "github.com/dotcloud/docker/utils" <ide> "io/ioutil" <ide> "log" <ide> "os" <ide> "os/exec" <ide> "path" <add> "path/filepath" <ide> "strconv" <ide> "strings" <ide> "syscall" <ide> func (d *driver) Info(id string) execdriver.Info { <ide> } <ide> } <ide> <add>func (d *driver) GetPidsForContainer(id string) ([]int, error) { <add> pids := []int{} <add> <add> // memory is chosen randomly, any cgroup used by docker works <add> subsystem := "memory" <add> <add> cgroupRoot, err := cgroups.FindCgroupMountpoint(subsystem) <add> if err != nil { <add> return pids, err <add> } <add> <add> cgroupDir, err := cgroups.GetThisCgroupDir(subsystem) <add> if err != nil { <add> return pids, err <add> } <add> <add> filename := filepath.Join(cgroupRoot, cgroupDir, id, "tasks") <add> if _, err := os.Stat(filename); os.IsNotExist(err) { <add> // With more recent lxc versions use, cgroup will be in lxc/ <add> filename = filepath.Join(cgroupRoot, cgroupDir, "lxc", id, "tasks") <add> } <add> <add> output, err := ioutil.ReadFile(filename) <add> if err != nil { <add> return pids, err <add> } <add> for _, p := range strings.Split(string(output), "\n") { <add> if len(p) == 0 { <add> continue <add> } <add> pid, err := strconv.Atoi(p) <add> if err != nil { <add> return pids, fmt.Errorf("Invalid pid '%s': %s", p, err) <add> } <add> pids = append(pids, pid) <add> } <add> return pids, nil <add>} <add> <ide> func linkLxcStart(root string) error { <ide> sourcePath, err := exec.LookPath("lxc-start") <ide> if err != nil { <ide><path>pkg/cgroups/cgroups.go <ide> import ( <ide> "fmt" <ide> "github.com/dotcloud/docker/pkg/mount" <ide> "io" <del> "io/ioutil" <ide> "os" <del> "path/filepath" <del> "strconv" <ide> "strings" <ide> ) <ide> <ide> func FindCgroupMountpoint(subsystem string) (string, error) { <ide> } <ide> <ide> // Returns the relative path to the cgroup docker is running in. <del>func getThisCgroupDir(subsystem string) (string, error) { <add>func GetThisCgroupDir(subsystem string) (string, error) { <ide> f, err := os.Open("/proc/self/cgroup") <ide> if err != nil { <ide> return "", err <ide> func parseCgroupFile(subsystem string, r io.Reader) (string, error) { <ide> } <ide> return "", fmt.Errorf("cgroup '%s' not found in /proc/self/cgroup", subsystem) <ide> } <del> <del>// Returns a list of pids for the given container. <del>func GetPidsForContainer(id string) ([]int, error) { <del> pids := []int{} <del> <del> // memory is chosen randomly, any cgroup used by docker works <del> subsystem := "memory" <del> <del> cgroupRoot, err := FindCgroupMountpoint(subsystem) <del> if err != nil { <del> return pids, err <del> } <del> <del> cgroupDir, err := getThisCgroupDir(subsystem) <del> if err != nil { <del> return pids, err <del> } <del> <del> filename := filepath.Join(cgroupRoot, cgroupDir, id, "tasks") <del> if _, err := os.Stat(filename); os.IsNotExist(err) { <del> // With more recent lxc versions use, cgroup will be in lxc/ <del> filename = filepath.Join(cgroupRoot, cgroupDir, "lxc", id, "tasks") <del> } <del> <del> output, err := ioutil.ReadFile(filename) <del> if err != nil { <del> return pids, err <del> } <del> for _, p := range strings.Split(string(output), "\n") { <del> if len(p) == 0 { <del> continue <del> } <del> pid, err := strconv.Atoi(p) <del> if err != nil { <del> return pids, fmt.Errorf("Invalid pid '%s': %s", p, err) <del> } <del> pids = append(pids, pid) <del> } <del> return pids, nil <del>} <ide><path>server.go <ide> import ( <ide> "github.com/dotcloud/docker/archive" <ide> "github.com/dotcloud/docker/auth" <ide> "github.com/dotcloud/docker/engine" <del> "github.com/dotcloud/docker/pkg/cgroups" <ide> "github.com/dotcloud/docker/pkg/graphdb" <ide> "github.com/dotcloud/docker/registry" <ide> "github.com/dotcloud/docker/utils" <ide> func (srv *Server) ContainerTop(job *engine.Job) engine.Status { <ide> job.Errorf("Container %s is not running", name) <ide> return engine.StatusErr <ide> } <del> pids, err := cgroups.GetPidsForContainer(container.ID) <add> pids, err := srv.runtime.execDriver.GetPidsForContainer(container.ID) <ide> if err != nil { <ide> job.Error(err) <ide> return engine.StatusErr
5
Javascript
Javascript
add getshaderprecisionformat polyfill
2ba3e37476013604b660b5da0f7af05aead04f76
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> } <ide> <add> if ( _gl.getShaderPrecisionFormat === undefined ) { <add> <add> _gl.getShaderPrecisionFormat = function () { <add> <add> return { <add> 'rangeMin': 1, <add> 'rangeMax': 1, <add> 'precision': 1 <add> }; <add> <add> } <add> <add> } <add> <ide> var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters ); <ide> <ide> var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
1
Java
Java
add responder strategies to rsocketstrategies
91b040d0bf05c857c022a263b3c076a3020c3875
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/reactive/MessageMappingMessageHandler.java <ide> public class MessageMappingMessageHandler extends AbstractMethodMessageHandler<C <ide> @Nullable <ide> private Validator validator; <ide> <add> @Nullable <ide> private RouteMatcher routeMatcher; <ide> <ide> private ConversionService conversionService = new DefaultFormattingConversionService(); <ide> public class MessageMappingMessageHandler extends AbstractMethodMessageHandler<C <ide> <ide> <ide> public MessageMappingMessageHandler() { <del> AntPathMatcher pathMatcher = new AntPathMatcher(); <del> pathMatcher.setPathSeparator("."); <del> this.routeMatcher = new SimpleRouteMatcher(pathMatcher); <ide> setHandlerPredicate(type -> AnnotatedElementUtils.hasAnnotation(type, Controller.class)); <ide> } <ide> <ide> public void setRouteMatcher(RouteMatcher routeMatcher) { <ide> <ide> /** <ide> * Return the {@code RouteMatcher} used to map messages to handlers. <add> * May be {@code null} before component is initialized. <ide> */ <add> @Nullable <ide> public RouteMatcher getRouteMatcher() { <ide> return this.routeMatcher; <ide> } <ide> protected List<? extends HandlerMethodArgumentResolver> initArgumentResolvers() <ide> resolvers.add(new PayloadMethodArgumentResolver( <ide> getDecoders(), this.validator, getReactiveAdapterRegistry(), true)); <ide> <add> if (this.routeMatcher == null) { <add> AntPathMatcher pathMatcher = new AntPathMatcher(); <add> pathMatcher.setPathSeparator("."); <add> this.routeMatcher = new SimpleRouteMatcher(pathMatcher); <add> } <add> <ide> return resolvers; <ide> } <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketStrategies.java <ide> import org.springframework.core.io.buffer.DataBufferFactory; <ide> import org.springframework.core.io.buffer.NettyDataBufferFactory; <ide> import org.springframework.lang.Nullable; <add>import org.springframework.util.AntPathMatcher; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.MimeTypeUtils; <add>import org.springframework.util.RouteMatcher; <add>import org.springframework.util.SimpleRouteMatcher; <ide> <ide> /** <ide> * Default, package-private {@link RSocketStrategies} implementation. <ide> final class DefaultRSocketStrategies implements RSocketStrategies { <ide> <ide> private final List<Decoder<?>> decoders; <ide> <del> private final ReactiveAdapterRegistry adapterRegistry; <add> private final RouteMatcher routeMatcher; <add> <add> private final MetadataExtractor metadataExtractor; <ide> <ide> private final DataBufferFactory bufferFactory; <ide> <add> private final ReactiveAdapterRegistry adapterRegistry; <add> <ide> <ide> private DefaultRSocketStrategies(List<Encoder<?>> encoders, List<Decoder<?>> decoders, <del> ReactiveAdapterRegistry adapterRegistry, DataBufferFactory bufferFactory) { <add> RouteMatcher routeMatcher, MetadataExtractor metadataExtractor, <add> DataBufferFactory bufferFactory, ReactiveAdapterRegistry adapterRegistry) { <ide> <ide> this.encoders = Collections.unmodifiableList(encoders); <ide> this.decoders = Collections.unmodifiableList(decoders); <del> this.adapterRegistry = adapterRegistry; <add> this.routeMatcher = routeMatcher; <add> this.metadataExtractor = metadataExtractor; <ide> this.bufferFactory = bufferFactory; <add> this.adapterRegistry = adapterRegistry; <ide> } <ide> <ide> <ide> public List<Decoder<?>> decoders() { <ide> } <ide> <ide> @Override <del> public ReactiveAdapterRegistry reactiveAdapterRegistry() { <del> return this.adapterRegistry; <add> public RouteMatcher routeMatcher() { <add> return this.routeMatcher; <add> } <add> <add> @Override <add> public MetadataExtractor metadataExtractor() { <add> return this.metadataExtractor; <ide> } <ide> <ide> @Override <ide> public DataBufferFactory dataBufferFactory() { <ide> return this.bufferFactory; <ide> } <ide> <add> @Override <add> public ReactiveAdapterRegistry reactiveAdapterRegistry() { <add> return this.adapterRegistry; <add> } <add> <ide> <ide> /** <ide> * Default RSocketStrategies.Builder implementation. <ide> static class DefaultRSocketStrategiesBuilder implements RSocketStrategies.Builde <ide> <ide> private final List<Decoder<?>> decoders = new ArrayList<>(); <ide> <add> @Nullable <add> private RouteMatcher routeMatcher; <add> <add> @Nullable <add> private MetadataExtractor metadataExtractor; <add> <ide> private ReactiveAdapterRegistry adapterRegistry = ReactiveAdapterRegistry.getSharedInstance(); <ide> <ide> @Nullable <ide> public Builder decoders(Consumer<List<Decoder<?>>> consumer) { <ide> return this; <ide> } <ide> <add> @Override <add> public Builder routeMatcher(RouteMatcher routeMatcher) { <add> this.routeMatcher = routeMatcher; <add> return this; <add> } <add> <add> @Override <add> public Builder metadataExtractor(MetadataExtractor metadataExtractor) { <add> this.metadataExtractor = metadataExtractor; <add> return this; <add> } <add> <ide> @Override <ide> public Builder reactiveAdapterStrategy(ReactiveAdapterRegistry registry) { <ide> Assert.notNull(registry, "ReactiveAdapterRegistry is required"); <ide> public Builder dataBufferFactory(DataBufferFactory bufferFactory) { <ide> @Override <ide> public RSocketStrategies build() { <ide> return new DefaultRSocketStrategies( <del> this.encoders, this.decoders, this.adapterRegistry, initBufferFactory()); <add> this.encoders, this.decoders, <add> this.routeMatcher != null ? this.routeMatcher : initRouteMatcher(), <add> this.metadataExtractor != null ? this.metadataExtractor : initMetadataExtractor(), <add> this.bufferFactory != null ? this.bufferFactory : initBufferFactory(), <add> this.adapterRegistry); <add> } <add> <add> private RouteMatcher initRouteMatcher() { <add> AntPathMatcher pathMatcher = new AntPathMatcher(); <add> pathMatcher.setPathSeparator("."); <add> return new SimpleRouteMatcher(pathMatcher); <add> } <add> <add> private MetadataExtractor initMetadataExtractor() { <add> DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(); <add> extractor.metadataToExtract(MimeTypeUtils.TEXT_PLAIN, String.class, MetadataExtractor.ROUTE_KEY); <add> return extractor; <ide> } <ide> <ide> private DataBufferFactory initBufferFactory() { <del> return this.bufferFactory != null ? this.bufferFactory : <del> new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT); <add> return new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT); <ide> } <ide> } <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketStrategies.java <ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory; <ide> import org.springframework.core.io.buffer.NettyDataBufferFactory; <ide> import org.springframework.lang.Nullable; <add>import org.springframework.util.AntPathMatcher; <ide> import org.springframework.util.MimeType; <add>import org.springframework.util.RouteMatcher; <add>import org.springframework.util.SimpleRouteMatcher; <ide> <ide> /** <ide> * Access to strategies for use by RSocket requester and responder components. <ide> default <T> Decoder<T> decoder(ResolvableType elementType, @Nullable MimeType mi <ide> } <ide> <ide> /** <del> * Return the configured <del> * {@link Builder#reactiveAdapterStrategy(ReactiveAdapterRegistry) reactiveAdapterRegistry}. <add> * Return the configured {@link Builder#routeMatcher(RouteMatcher)}. <ide> */ <del> ReactiveAdapterRegistry reactiveAdapterRegistry(); <add> RouteMatcher routeMatcher(); <add> <add> /** <add> * Return the configured {@link Builder#metadataExtractor(MetadataExtractor)}. <add> */ <add> MetadataExtractor metadataExtractor(); <ide> <ide> /** <ide> * Return the configured <ide> * {@link Builder#dataBufferFactory(DataBufferFactory) dataBufferFactory}. <ide> */ <ide> DataBufferFactory dataBufferFactory(); <ide> <add> /** <add> * Return the configured <add> * {@link Builder#reactiveAdapterStrategy(ReactiveAdapterRegistry) reactiveAdapterRegistry}. <add> */ <add> ReactiveAdapterRegistry reactiveAdapterRegistry(); <add> <ide> <ide> /** <ide> * Return a builder to build a new {@code RSocketStrategies} instance. <ide> interface Builder { <ide> */ <ide> Builder decoders(Consumer<List<Decoder<?>>> consumer); <ide> <add> /** <add> * Configure a {@code RouteMatcher} for matching routes to message <add> * handlers based on route patterns. This option is applicable to <add> * client or server responders. <add> * <p>By default, {@link SimpleRouteMatcher} is used, backed by <add> * {@link AntPathMatcher} with "." as separator. For better <add> * efficiency consider using the {@code PathPatternRouteMatcher} from <add> * {@code spring-web} instead. <add> */ <add> Builder routeMatcher(RouteMatcher routeMatcher); <add> <add> /** <add> * Configure a {@link MetadataExtractor} to extract the route along with <add> * other metadata. This option is applicable to client or server <add> * responders. <add> * <p>By default this is {@link DefaultMetadataExtractor} extracting a <add> * route from {@code "message/x.rsocket.routing.v0"} or <add> * {@code "text/plain"} metadata entries. <add> */ <add> Builder metadataExtractor(MetadataExtractor metadataExtractor); <add> <ide> /** <ide> * Configure the registry for reactive type support. This can be used to <ide> * to adapt to, and/or determine the semantics of a given <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/annotation/support/AnnotationClientResponderConfigurer.java <ide> import org.springframework.beans.BeanUtils; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.messaging.rsocket.ClientRSocketFactoryConfigurer; <del>import org.springframework.messaging.rsocket.MetadataExtractor; <ide> import org.springframework.messaging.rsocket.RSocketStrategies; <ide> import org.springframework.util.Assert; <del>import org.springframework.util.RouteMatcher; <ide> <ide> /** <ide> * {@link ClientRSocketFactoryConfigurer} to configure and plug in a responder <ide> public final class AnnotationClientResponderConfigurer implements ClientRSocketF <ide> <ide> private final List<Object> handlers = new ArrayList<>(); <ide> <del> @Nullable <del> private RouteMatcher routeMatcher; <del> <del> @Nullable <del> private MetadataExtractor extractor; <del> <ide> @Nullable <ide> private RSocketStrategies strategies; <ide> <ide> private AnnotationClientResponderConfigurer(List<Object> handlers) { <ide> } <ide> <ide> <del> /** <del> * Configure the {@link RouteMatcher} to use. This is used to set <del> * {@link RSocketMessageHandler#setRouteMatcher(RouteMatcher)}. <del> */ <del> public AnnotationClientResponderConfigurer routeMatcher(RouteMatcher routeMatcher) { <del> this.routeMatcher = routeMatcher; <del> return this; <del> } <del> <del> /** <del> * Configure the {@link MetadataExtractor} to use. This is used to set <del> * {@link RSocketMessageHandler#setMetadataExtractor(MetadataExtractor)}. <del> */ <del> public AnnotationClientResponderConfigurer metadataExtractor(MetadataExtractor extractor) { <del> this.extractor = extractor; <del> return this; <del> } <del> <ide> /** <ide> * Configure handlers to detect {@code @MessasgeMapping} handler methods on. <ide> * This is used to set {@link RSocketMessageHandler#setHandlers(List)}. <ide> public void configure(RSocketFactory.ClientRSocketFactory factory) { <ide> Assert.notEmpty(this.handlers, "No handlers"); <ide> RSocketMessageHandler messageHandler = new RSocketMessageHandler(); <ide> messageHandler.setHandlers(this.handlers); <del> if (this.routeMatcher != null) { <del> messageHandler.setRouteMatcher(this.routeMatcher); <del> } <del> if (this.extractor != null) { <del> messageHandler.setMetadataExtractor(this.extractor); <del> } <ide> messageHandler.setRSocketStrategies(this.strategies); <ide> messageHandler.afterPropertiesSet(); <ide> factory.acceptor(messageHandler.clientResponder()); <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/annotation/support/RSocketMessageHandler.java <ide> public List<? extends Encoder<?>> getEncoders() { <ide> /** <ide> * Provide configuration in the form of {@link RSocketStrategies} instance <ide> * which can also be re-used to initialize a client-side <del> * {@link RSocketRequester}. When this property is set, it also sets <del> * {@link #setDecoders(List) decoders}, {@link #setEncoders(List) encoders}, <del> * and {@link #setReactiveAdapterRegistry(ReactiveAdapterRegistry) <del> * reactiveAdapterRegistry}. <add> * {@link RSocketRequester}. <add> * <p>When this is set, in turn it sets the following: <add> * <ul> <add> * <li>{@link #setDecoders(List)} <add> * <li>{@link #setEncoders(List)} <add> * <li>{@link #setRouteMatcher(RouteMatcher)} <add> * <li>{@link #setMetadataExtractor(MetadataExtractor)} <add> * <li>{@link #setReactiveAdapterRegistry(ReactiveAdapterRegistry)} <add> * </ul> <add> * <p>By default if this is not set, it is initialized from the above. <ide> */ <ide> public void setRSocketStrategies(@Nullable RSocketStrategies rsocketStrategies) { <ide> this.rsocketStrategies = rsocketStrategies; <ide> public RSocketStrategies getRSocketStrategies() { <ide> } <ide> <ide> /** <del> * Configure a {@link MetadataExtractor} to extract the route and possibly <del> * other metadata from the first payload of incoming requests. <del> * <p>By default this is a {@link DefaultMetadataExtractor} with the <del> * configured {@link RSocketStrategies} (and decoders), extracting a route <del> * from {@code "message/x.rsocket.routing.v0"} or {@code "text/plain"} <del> * metadata entries. <add> * Configure a {@link MetadataExtractor} to extract the route along with <add> * other metadata. <add> * <p>By default this is {@link DefaultMetadataExtractor} extracting a <add> * route from {@code "message/x.rsocket.routing.v0"} or {@code "text/plain"}. <ide> * @param extractor the extractor to use <ide> */ <ide> public void setMetadataExtractor(MetadataExtractor extractor) { <ide> public MimeType getDefaultMetadataMimeType() { <ide> <ide> @Override <ide> public void afterPropertiesSet() { <add> <add> getArgumentResolverConfigurer().addCustomResolver(new RSocketRequesterMethodArgumentResolver()); <add> super.afterPropertiesSet(); <add> <add> if (getMetadataExtractor() == null) { <add> DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(); <add> extractor.metadataToExtract(MimeTypeUtils.TEXT_PLAIN, String.class, MetadataExtractor.ROUTE_KEY); <add> setMetadataExtractor(extractor); <add> } <add> <ide> if (this.rsocketStrategies == null) { <ide> this.rsocketStrategies = RSocketStrategies.builder() <ide> .decoder(getDecoders().toArray(new Decoder<?>[0])) <ide> .encoder(getEncoders().toArray(new Encoder<?>[0])) <add> .routeMatcher(getRouteMatcher()) <add> .metadataExtractor(getMetadataExtractor()) <ide> .reactiveAdapterStrategy(getReactiveAdapterRegistry()) <ide> .build(); <ide> } <del> if (this.metadataExtractor == null) { <del> DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(); <del> extractor.metadataToExtract(MimeTypeUtils.TEXT_PLAIN, String.class, MetadataExtractor.ROUTE_KEY); <del> this.metadataExtractor = extractor; <del> } <del> getArgumentResolverConfigurer().addCustomResolver(new RSocketRequesterMethodArgumentResolver()); <del> super.afterPropertiesSet(); <ide> } <ide> <ide> @Override
5
PHP
PHP
remove extra space
bd5bbb64802afa975b124917f5918f6421bae3e0
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function isLocale($locale) <ide> public function registerCoreContainerAliases() <ide> { <ide> foreach ([ <del> 'app' => [self::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class, \Psr\Container\ContainerInterface::class], <add> 'app' => [self::class, \Illuminate\Contracts\Container\Container::class, \Illuminate\Contracts\Foundation\Application::class, \Psr\Container\ContainerInterface::class], <ide> 'auth' => [\Illuminate\Auth\AuthManager::class, \Illuminate\Contracts\Auth\Factory::class], <ide> 'auth.driver' => [\Illuminate\Contracts\Auth\Guard::class], <ide> 'blade.compiler' => [\Illuminate\View\Compilers\BladeCompiler::class],
1
Go
Go
fix tests with old cmd function
e201d5bcd46a3dcb70dd6b6e23ee375e4b5b5f40
<ide><path>integration-cli/docker_cli_create_test.go <ide> func TestCreateEchoStdout(t *testing.T) { <ide> <ide> func TestCreateVolumesCreated(t *testing.T) { <ide> name := "test_create_volume" <del> cmd(t, "create", "--name", name, "-v", "/foo", "busybox") <add> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "--name", name, "-v", "/foo", "busybox")); err != nil { <add> t.Fatal(out, err) <add> } <ide> dir, err := inspectFieldMap(name, "Volumes", "/foo") <ide> if err != nil { <ide> t.Fatalf("Error getting volume host path: %q", err)
1
Ruby
Ruby
fix spelling [ci skip]
d4f2c3adb3cd9a0fbf68f2f132eed5a75a7d3ea0
<ide><path>actionview/lib/action_view/helpers/number_helper.rb <ide> def number_to_currency(number, options = {}) <ide> # (defaults to current locale). <ide> # * <tt>:precision</tt> - Sets the precision of the number <ide> # (defaults to 3). <del> # * <tt>:significant</tt> - If +true+, precision will be the # <del> # of significant_digits. If +false+, the # of fractional <add> # * <tt>:significant</tt> - If +true+, precision will be the number <add> # of significant_digits. If +false+, the number of fractional <ide> # digits (defaults to +false+). <ide> # * <tt>:separator</tt> - Sets the separator between the <ide> # fractional and integer digits (defaults to "."). <ide> def number_with_delimiter(number, options = {}) <ide> # (defaults to current locale). <ide> # * <tt>:precision</tt> - Sets the precision of the number <ide> # (defaults to 3). <del> # * <tt>:significant</tt> - If +true+, precision will be the # <del> # of significant_digits. If +false+, the # of fractional <add> # * <tt>:significant</tt> - If +true+, precision will be the number <add> # of significant_digits. If +false+, the number of fractional <ide> # digits (defaults to +false+). <ide> # * <tt>:separator</tt> - Sets the separator between the <ide> # fractional and integer digits (defaults to "."). <ide> def number_with_precision(number, options = {}) <ide> # (defaults to current locale). <ide> # * <tt>:precision</tt> - Sets the precision of the number <ide> # (defaults to 3). <del> # * <tt>:significant</tt> - If +true+, precision will be the # <del> # of significant_digits. If +false+, the # of fractional <add> # * <tt>:significant</tt> - If +true+, precision will be the number <add> # of significant_digits. If +false+, the number of fractional <ide> # digits (defaults to +true+) <ide> # * <tt>:separator</tt> - Sets the separator between the <ide> # fractional and integer digits (defaults to "."). <ide> def number_to_human_size(number, options = {}) <ide> # (defaults to current locale). <ide> # * <tt>:precision</tt> - Sets the precision of the number <ide> # (defaults to 3). <del> # * <tt>:significant</tt> - If +true+, precision will be the # <del> # of significant_digits. If +false+, the # of fractional <add> # * <tt>:significant</tt> - If +true+, precision will be the number <add> # of significant_digits. If +false+, the number of fractional <ide> # digits (defaults to +true+) <ide> # * <tt>:separator</tt> - Sets the separator between the <ide> # fractional and integer digits (defaults to "."). <ide><path>activesupport/lib/active_support/number_helper.rb <ide> def number_to_currency(number, options = {}) <ide> # (defaults to current locale). <ide> # * <tt>:precision</tt> - Sets the precision of the number <ide> # (defaults to 3). Keeps the number's precision if nil. <del> # * <tt>:significant</tt> - If +true+, precision will be the # <del> # of significant_digits. If +false+, the # of fractional <add> # * <tt>:significant</tt> - If +true+, precision will be the number <add> # of significant_digits. If +false+, the number of fractional <ide> # digits (defaults to +false+). <ide> # * <tt>:separator</tt> - Sets the separator between the <ide> # fractional and integer digits (defaults to "."). <ide> def number_to_delimited(number, options = {}) <ide> # (defaults to current locale). <ide> # * <tt>:precision</tt> - Sets the precision of the number <ide> # (defaults to 3). Keeps the number's precision if nil. <del> # * <tt>:significant</tt> - If +true+, precision will be the # <del> # of significant_digits. If +false+, the # of fractional <add> # * <tt>:significant</tt> - If +true+, precision will be the number <add> # of significant_digits. If +false+, the number of fractional <ide> # digits (defaults to +false+). <ide> # * <tt>:separator</tt> - Sets the separator between the <ide> # fractional and integer digits (defaults to "."). <ide> def number_to_rounded(number, options = {}) <ide> # (defaults to current locale). <ide> # * <tt>:precision</tt> - Sets the precision of the number <ide> # (defaults to 3). <del> # * <tt>:significant</tt> - If +true+, precision will be the # <del> # of significant_digits. If +false+, the # of fractional <add> # * <tt>:significant</tt> - If +true+, precision will be the number <add> # of significant_digits. If +false+, the number of fractional <ide> # digits (defaults to +true+) <ide> # * <tt>:separator</tt> - Sets the separator between the <ide> # fractional and integer digits (defaults to "."). <ide> def number_to_human_size(number, options = {}) <ide> # (defaults to current locale). <ide> # * <tt>:precision</tt> - Sets the precision of the number <ide> # (defaults to 3). <del> # * <tt>:significant</tt> - If +true+, precision will be the # <del> # of significant_digits. If +false+, the # of fractional <add> # * <tt>:significant</tt> - If +true+, precision will be the number <add> # of significant_digits. If +false+, the number of fractional <ide> # digits (defaults to +true+) <ide> # * <tt>:separator</tt> - Sets the separator between the <ide> # fractional and integer digits (defaults to ".").
2
Text
Text
update ssh demo to ubuntu 14.04
98f57d1c392eab7df30fa3179c8e0f99a418e772
<ide><path>docs/sources/examples/running_ssh_service.md <ide> quick access to a test container. <ide> # <ide> # VERSION 0.0.1 <ide> <del> FROM ubuntu:12.04 <add> FROM ubuntu:14.04 <ide> MAINTAINER Thatcher R. Peskens "thatcher@dotcloud.com" <ide> <ide> RUN apt-get update && apt-get install -y openssh-server <ide> RUN mkdir /var/run/sshd <del> RUN echo 'root:screencast' |chpasswd <add> RUN echo 'root:screencast' | chpasswd <add> RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config <ide> <ide> EXPOSE 22 <del> CMD ["/usr/sbin/sshd", "-D"] <add> CMD ["/usr/sbin/sshd", "-D"] <ide> <ide> Build the image using: <ide> <ide> the container's port 22 is mapped to: <ide> $ sudo docker port test_sshd 22 <ide> 0.0.0.0:49154 <ide> <del>And now you can ssh to port `49154` on the Docker daemon's host IP <del>address (`ip address` or `ifconfig` can tell you that): <add>And now you can ssh as `root` on the container's IP address (you can find it <add>with `docker inspect`) or on port `49154` of the Docker daemon's host IP address <add>(`ip address` or `ifconfig` can tell you that): <ide> <ide> $ ssh root@192.168.1.2 -p 49154 <ide> # The password is ``screencast``.
1
Javascript
Javascript
add jsdoc to os module functions
d97787fccc18ec8023c7571a38c0e13f3837df4f
<ide><path>lib/os.js <ide> const { <ide> const getHomeDirectory = getCheckedFunction(_getHomeDirectory); <ide> const getHostname = getCheckedFunction(_getHostname); <ide> const getInterfaceAddresses = getCheckedFunction(_getInterfaceAddresses); <add>/** <add> * @returns {string} <add> */ <ide> const getOSRelease = () => release; <add>/** <add> * @returns {string} <add> */ <ide> const getOSType = () => type; <add>/** <add> * @returns {string} <add> */ <ide> const getOSVersion = () => version; <ide> <ide> getFreeMem[SymbolToPrimitive] = () => getFreeMem(); <ide> const kEndianness = isBigEndian ? 'BE' : 'LE'; <ide> <ide> const avgValues = new Float64Array(3); <ide> <add>/** <add> * @returns {[number, number, number]} <add> */ <ide> function loadavg() { <ide> getLoadAvg(avgValues); <ide> return [avgValues[0], avgValues[1], avgValues[2]]; <ide> } <ide> <add>/** <add> * Returns an array of objects containing information about each <add> * logical CPU core. <add> * <add> * @returns {Array<{ <add> * model: string <add> * speed: number <add> * times: { <add> * user: number <add> * nice: number <add> * sys: number <add> * idle: number <add> * irq: number <add> * } <add> * }>} <add> */ <ide> function cpus() { <ide> // [] is a bugfix for a regression introduced in 51cea61 <ide> const data = getCPUs() || []; <ide> function cpus() { <ide> return result; <ide> } <ide> <add>/** <add> * @returns {string} <add> */ <ide> function arch() { <ide> return process.arch; <ide> } <ide> arch[SymbolToPrimitive] = () => process.arch; <ide> <add>/** <add> * @returns {string} <add> */ <ide> function platform() { <ide> return process.platform; <ide> } <ide> platform[SymbolToPrimitive] = () => process.platform; <ide> <add>/** <add> * @returns {string} <add> */ <ide> function tmpdir() { <ide> var path; <ide> if (isWindows) { <ide> function tmpdir() { <ide> } <ide> tmpdir[SymbolToPrimitive] = () => tmpdir(); <ide> <add>/** <add> * @returns {'BE' | 'LE'} <add> */ <ide> function endianness() { <ide> return kEndianness; <ide> } <ide> function getCIDR(address, netmask, family) { <ide> return `${address}/${ones}`; <ide> } <ide> <add>/** <add> * @returns {Record<string, Array<{ <add> * address: string <add> * netmask: string <add> * family: 'IPv4' | 'IPv6' <add> * mac: string <add> * internal: boolean <add> * scopeid: number <add> * cidr: string | null <add> * }>>} <add> */ <ide> function networkInterfaces() { <ide> const data = getInterfaceAddresses(); <ide> const result = {}; <ide> function networkInterfaces() { <ide> return result; <ide> } <ide> <add>/** <add> * @param {number} pid <add> * @param {number} priority <add> * @returns {void} <add> */ <ide> function setPriority(pid, priority) { <ide> if (priority === undefined) { <ide> priority = pid; <ide> function setPriority(pid, priority) { <ide> throw new ERR_SYSTEM_ERROR(ctx); <ide> } <ide> <add>/** <add> * @param {number} pid <add> * @returns {number} <add> */ <ide> function getPriority(pid) { <ide> if (pid === undefined) <ide> pid = 0; <ide> function getPriority(pid) { <ide> return priority; <ide> } <ide> <add>/** <add> * @param {{ encoding?: string }} options If `encoding` is set to `'buffer'`, <add> * the `username`, `shell`, and `homedir` values will be `Buffer` instances. <add> * Default: `'utf8'` <add> * @returns {{ <add> * uid: number <add> * gid: number <add> * username: string <add> * homedir: string <add> * shell: string | null <add> * }} <add> */ <ide> function userInfo(options) { <ide> if (typeof options !== 'object') <ide> options = null;
1
Python
Python
fix str into int to match definition
df4594a9dadca89482b69ec9a388456114a81491
<ide><path>src/transformers/tokenization_xlm.py <ide> "xlm-mlm-en-2048": {"do_lowercase_and_remove_accent": True}, <ide> "xlm-mlm-ende-1024": { <ide> "do_lowercase_and_remove_accent": True, <del> "id2lang": {"0": "de", "1": "en"}, <add> "id2lang": {0: "de", 1: "en"}, <ide> "lang2id": {"de": 0, "en": 1}, <ide> }, <ide> "xlm-mlm-enfr-1024": { <ide> "do_lowercase_and_remove_accent": True, <del> "id2lang": {"0": "en", "1": "fr"}, <add> "id2lang": {0: "en", 1: "fr"}, <ide> "lang2id": {"en": 0, "fr": 1}, <ide> }, <ide> "xlm-mlm-enro-1024": { <ide> "do_lowercase_and_remove_accent": True, <del> "id2lang": {"0": "en", "1": "ro"}, <add> "id2lang": {0: "en", 1: "ro"}, <ide> "lang2id": {"en": 0, "ro": 1}, <ide> }, <ide> "xlm-mlm-tlm-xnli15-1024": { <ide> "do_lowercase_and_remove_accent": True, <ide> "id2lang": { <del> "0": "ar", <del> "1": "bg", <del> "2": "de", <del> "3": "el", <del> "4": "en", <del> "5": "es", <del> "6": "fr", <del> "7": "hi", <del> "8": "ru", <del> "9": "sw", <del> "10": "th", <del> "11": "tr", <del> "12": "ur", <del> "13": "vi", <del> "14": "zh", <add> 0: "ar", <add> 1: "bg", <add> 2: "de", <add> 3: "el", <add> 4: "en", <add> 5: "es", <add> 6: "fr", <add> 7: "hi", <add> 8: "ru", <add> 9: "sw", <add> 10: "th", <add> 11: "tr", <add> 12: "ur", <add> 13: "vi", <add> 14: "zh", <ide> }, <ide> "lang2id": { <ide> "ar": 0, <ide> "xlm-mlm-xnli15-1024": { <ide> "do_lowercase_and_remove_accent": True, <ide> "id2lang": { <del> "0": "ar", <del> "1": "bg", <del> "2": "de", <del> "3": "el", <del> "4": "en", <del> "5": "es", <del> "6": "fr", <del> "7": "hi", <del> "8": "ru", <del> "9": "sw", <del> "10": "th", <del> "11": "tr", <del> "12": "ur", <del> "13": "vi", <del> "14": "zh", <add> 0: "ar", <add> 1: "bg", <add> 2: "de", <add> 3: "el", <add> 4: "en", <add> 5: "es", <add> 6: "fr", <add> 7: "hi", <add> 8: "ru", <add> 9: "sw", <add> 10: "th", <add> 11: "tr", <add> 12: "ur", <add> 13: "vi", <add> 14: "zh", <ide> }, <ide> "lang2id": { <ide> "ar": 0, <ide> }, <ide> "xlm-clm-enfr-1024": { <ide> "do_lowercase_and_remove_accent": True, <del> "id2lang": {"0": "en", "1": "fr"}, <add> "id2lang": {0: "en", 1: "fr"}, <ide> "lang2id": {"en": 0, "fr": 1}, <ide> }, <ide> "xlm-clm-ende-1024": { <ide> "do_lowercase_and_remove_accent": True, <del> "id2lang": {"0": "de", "1": "en"}, <add> "id2lang": {0: "de", 1: "en"}, <ide> "lang2id": {"de": 0, "en": 1}, <ide> }, <ide> "xlm-mlm-17-1280": { <ide> "do_lowercase_and_remove_accent": False, <ide> "id2lang": { <del> "0": "ar", <del> "1": "de", <del> "2": "en", <del> "3": "es", <del> "4": "fr", <del> "5": "hi", <del> "6": "it", <del> "7": "ja", <del> "8": "ko", <del> "9": "nl", <del> "10": "pl", <del> "11": "pt", <del> "12": "ru", <del> "13": "sv", <del> "14": "tr", <del> "15": "vi", <del> "16": "zh", <add> 0: "ar", <add> 1: "de", <add> 2: "en", <add> 3: "es", <add> 4: "fr", <add> 5: "hi", <add> 6: "it", <add> 7: "ja", <add> 8: "ko", <add> 9: "nl", <add> 10: "pl", <add> 11: "pt", <add> 12: "ru", <add> 13: "sv", <add> 14: "tr", <add> 15: "vi", <add> 16: "zh", <ide> }, <ide> "lang2id": { <ide> "ar": 0, <ide> "xlm-mlm-100-1280": { <ide> "do_lowercase_and_remove_accent": False, <ide> "id2lang": { <del> "0": "af", <del> "1": "als", <del> "2": "am", <del> "3": "an", <del> "4": "ang", <del> "5": "ar", <del> "6": "arz", <del> "7": "ast", <del> "8": "az", <del> "9": "bar", <del> "10": "be", <del> "11": "bg", <del> "12": "bn", <del> "13": "br", <del> "14": "bs", <del> "15": "ca", <del> "16": "ceb", <del> "17": "ckb", <del> "18": "cs", <del> "19": "cy", <del> "20": "da", <del> "21": "de", <del> "22": "el", <del> "23": "en", <del> "24": "eo", <del> "25": "es", <del> "26": "et", <del> "27": "eu", <del> "28": "fa", <del> "29": "fi", <del> "30": "fr", <del> "31": "fy", <del> "32": "ga", <del> "33": "gan", <del> "34": "gl", <del> "35": "gu", <del> "36": "he", <del> "37": "hi", <del> "38": "hr", <del> "39": "hu", <del> "40": "hy", <del> "41": "ia", <del> "42": "id", <del> "43": "is", <del> "44": "it", <del> "45": "ja", <del> "46": "jv", <del> "47": "ka", <del> "48": "kk", <del> "49": "kn", <del> "50": "ko", <del> "51": "ku", <del> "52": "la", <del> "53": "lb", <del> "54": "lt", <del> "55": "lv", <del> "56": "mk", <del> "57": "ml", <del> "58": "mn", <del> "59": "mr", <del> "60": "ms", <del> "61": "my", <del> "62": "nds", <del> "63": "ne", <del> "64": "nl", <del> "65": "nn", <del> "66": "no", <del> "67": "oc", <del> "68": "pl", <del> "69": "pt", <del> "70": "ro", <del> "71": "ru", <del> "72": "scn", <del> "73": "sco", <del> "74": "sh", <del> "75": "si", <del> "76": "simple", <del> "77": "sk", <del> "78": "sl", <del> "79": "sq", <del> "80": "sr", <del> "81": "sv", <del> "82": "sw", <del> "83": "ta", <del> "84": "te", <del> "85": "th", <del> "86": "tl", <del> "87": "tr", <del> "88": "tt", <del> "89": "uk", <del> "90": "ur", <del> "91": "uz", <del> "92": "vi", <del> "93": "war", <del> "94": "wuu", <del> "95": "yi", <del> "96": "zh", <del> "97": "zh_classical", <del> "98": "zh_min_nan", <del> "99": "zh_yue", <add> 0: "af", <add> 1: "als", <add> 2: "am", <add> 3: "an", <add> 4: "ang", <add> 5: "ar", <add> 6: "arz", <add> 7: "ast", <add> 8: "az", <add> 9: "bar", <add> 10: "be", <add> 11: "bg", <add> 12: "bn", <add> 13: "br", <add> 14: "bs", <add> 15: "ca", <add> 16: "ceb", <add> 17: "ckb", <add> 18: "cs", <add> 19: "cy", <add> 20: "da", <add> 21: "de", <add> 22: "el", <add> 23: "en", <add> 24: "eo", <add> 25: "es", <add> 26: "et", <add> 27: "eu", <add> 28: "fa", <add> 29: "fi", <add> 30: "fr", <add> 31: "fy", <add> 32: "ga", <add> 33: "gan", <add> 34: "gl", <add> 35: "gu", <add> 36: "he", <add> 37: "hi", <add> 38: "hr", <add> 39: "hu", <add> 40: "hy", <add> 41: "ia", <add> 42: "id", <add> 43: "is", <add> 44: "it", <add> 45: "ja", <add> 46: "jv", <add> 47: "ka", <add> 48: "kk", <add> 49: "kn", <add> 50: "ko", <add> 51: "ku", <add> 52: "la", <add> 53: "lb", <add> 54: "lt", <add> 55: "lv", <add> 56: "mk", <add> 57: "ml", <add> 58: "mn", <add> 59: "mr", <add> 60: "ms", <add> 61: "my", <add> 62: "nds", <add> 63: "ne", <add> 64: "nl", <add> 65: "nn", <add> 66: "no", <add> 67: "oc", <add> 68: "pl", <add> 69: "pt", <add> 70: "ro", <add> 71: "ru", <add> 72: "scn", <add> 73: "sco", <add> 74: "sh", <add> 75: "si", <add> 76: "simple", <add> 77: "sk", <add> 78: "sl", <add> 79: "sq", <add> 80: "sr", <add> 81: "sv", <add> 82: "sw", <add> 83: "ta", <add> 84: "te", <add> 85: "th", <add> 86: "tl", <add> 87: "tr", <add> 88: "tt", <add> 89: "uk", <add> 90: "ur", <add> 91: "uz", <add> 92: "vi", <add> 93: "war", <add> 94: "wuu", <add> 95: "yi", <add> 96: "zh", <add> 97: "zh_classical", <add> 98: "zh_min_nan", <add> 99: "zh_yue", <ide> }, <ide> "lang2id": { <ide> "af": 0,
1
Javascript
Javascript
remove superfluous 'new'
60e26668b3c73b9163d9fb1ae6a7951c6acbc889
<ide><path>lib/child_process.js <ide> var Pipe; <ide> function createPipe(ipc) { <ide> // Lazy load <ide> if (!Pipe) { <del> Pipe = new process.binding('pipe_wrap').Pipe; <add> Pipe = process.binding('pipe_wrap').Pipe; <ide> } <ide> <ide> return new Pipe(ipc);
1
Text
Text
add silverwind as collaborator
92c1ad97c066fe6f0bd04943962c3fb568016a7e
<ide><path>README.md <ide> information about the governance of the io.js project, see <ide> * **Robert Kowalski** ([@robertkowalski](https://github.com/robertkowalski)) &lt;rok@kowalski.gd&gt; <ide> * **Julian Duque** ([@julianduque](https://github.com/julianduque)) &lt;julianduquej@gmail.com&gt; <ide> * **Johan Bergström** ([@jbergstroem](https://github.com/jbergstroem)) &lt;bugs@bergstroem.nu&gt; <add>* **Roman Reiss** ([@silverwind](https://github.com/silverwind)) &lt;me@silverwind.io&gt; <ide> <ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in <ide> maintaining the io.js project.
1
Javascript
Javascript
show falsy names as anonymous for dep0097
9dca43e7093525d07db32ef6995f4e498da96006
<ide><path>lib/domain.js <ide> function emitMakeCallbackDeprecation({ target, method }) { <ide> 'Using a domain property in MakeCallback is deprecated. Use the ' + <ide> 'async_context variant of MakeCallback or the AsyncResource class ' + <ide> 'instead. ' + <del> `(Triggered by calling ${method?.name ?? '<anonymous>'} ` + <add> `(Triggered by calling ${method?.name || '<anonymous>'} ` + <ide> `on ${target?.constructor?.name}.)`, <ide> 'DeprecationWarning', 'DEP0097'); <ide> sendMakeCallbackDeprecation = true; <ide><path>test/parallel/test-domain-dep0097.js <add>'use strict'; <add>const common = require('../common'); <add> <add>common.skipIfInspectorDisabled(); <add> <add>const assert = require('assert'); <add>const domain = require('domain'); <add>const inspector = require('inspector'); <add> <add>process.on('warning', common.mustCall((warning) => { <add> assert.strictEqual(warning.code, 'DEP0097'); <add> assert.match(warning.message, /Triggered by calling <anonymous> on process/); <add>})); <add> <add>domain.create().run(() => { <add> inspector.open(); <add>});
2
Go
Go
fix warning in build
ee814055673ca1d5981a4e9e4788a4199fd2f456
<ide><path>runtime.go <ide> func (runtime *Runtime) Create(config *Config, name string) (*Container, []strin <ide> return nil, nil, err <ide> } <ide> <del> if img.Config != nil { <del> if err := MergeConfig(config, img.Config); err != nil { <del> return nil, nil, err <add> checkDeprecatedExpose := func(config *Config) bool { <add> if config != nil { <add> if config.PortSpecs != nil { <add> for _, p := range config.PortSpecs { <add> if strings.Contains(p, ":") { <add> return true <add> } <add> } <add> } <ide> } <add> return false <ide> } <add> <ide> warnings := []string{} <del> if config.PortSpecs != nil { <del> for _, p := range config.PortSpecs { <del> if strings.Contains(p, ":") { <del> warnings = append(warnings, "The mapping to public ports on your host has been deprecated. Use -p to publish the ports.") <del> break <del> } <add> if checkDeprecatedExpose(img.Config) || checkDeprecatedExpose(config) { <add> warnings = append(warnings, "The mapping to public ports on your host has been deprecated. Use -p to publish the ports.") <add> } <add> <add> if img.Config != nil { <add> if err := MergeConfig(config, img.Config); err != nil { <add> return nil, nil, err <ide> } <ide> } <ide>
1
Java
Java
fix jaxb2typescanner to scan for @xmlregistry
4f871d444864d001a049e7817a84f1c59c70016f
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/jaxb/ClassPathJaxb2TypeScanner.java <ide> import java.io.IOException; <ide> import java.util.ArrayList; <ide> import java.util.List; <add> <ide> import javax.xml.bind.annotation.XmlEnum; <add>import javax.xml.bind.annotation.XmlRegistry; <ide> import javax.xml.bind.annotation.XmlRootElement; <ide> import javax.xml.bind.annotation.XmlSeeAlso; <ide> import javax.xml.bind.annotation.XmlType; <ide> * @author Arjen Poutsma <ide> * @author Juergen Hoeller <ide> * @author David Harrigan <add> * @author Biju Kunjummen <ide> * @since 3.1.1 <ide> * @see #scanPackages() <ide> */ <ide> class ClassPathJaxb2TypeScanner { <ide> private static final String RESOURCE_PATTERN = "/**/*.class"; <ide> <ide> private static final TypeFilter[] JAXB2_TYPE_FILTERS = new TypeFilter[] { <del> new AnnotationTypeFilter(XmlRootElement.class, false), new AnnotationTypeFilter(XmlType.class, false), <del> new AnnotationTypeFilter(XmlSeeAlso.class, false), new AnnotationTypeFilter(XmlEnum.class, false)}; <add> new AnnotationTypeFilter(XmlRootElement.class, false), <add> new AnnotationTypeFilter(XmlType.class, false), <add> new AnnotationTypeFilter(XmlSeeAlso.class, false), <add> new AnnotationTypeFilter(XmlEnum.class, false), <add> new AnnotationTypeFilter(XmlRegistry.class, false)}; <ide> <ide> <ide> private final ResourcePatternResolver resourcePatternResolver; <ide><path>spring-oxm/src/test/java/org/springframework/oxm/jaxb/Airplane.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.oxm.jaxb; <add> <add>import javax.xml.bind.annotation.XmlRootElement; <add> <add>@XmlRootElement <add>public class Airplane { <add> <add> private String name; <add> <add> <add> public String getName() { <add> return name; <add> } <add> <add> public void setName(String name) { <add> this.name = name; <add> } <add> <add>} <ide><path>spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java <ide> import org.xml.sax.ContentHandler; <ide> import org.xml.sax.Locator; <ide> <del>import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; <add> <ide> import static org.junit.Assert.*; <add>import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; <ide> import static org.mockito.BDDMockito.*; <ide> <add>/** <add> * @author Arjen Poutsma <add> * @author Biju Kunjummen <add> */ <ide> public class Jaxb2MarshallerTests extends AbstractMarshallerTests { <ide> <ide> private static final String CONTEXT_PATH = "org.springframework.oxm.jaxb.test"; <ide> public void marshalAttachments() throws Exception { <ide> verify(mimeContainer, times(3)).addAttachment(isA(String.class), isA(DataHandler.class)); <ide> } <ide> <add> @Test <add> public void marshalAWrappedObjectHoldingAnXmlElementDeclElement() throws Exception { <add> // SPR-10714 <add> marshaller = new Jaxb2Marshaller(); <add> marshaller.setPackagesToScan(new String[] { "org.springframework.oxm.jaxb" }); <add> marshaller.afterPropertiesSet(); <add> Airplane airplane = new Airplane(); <add> airplane.setName("test"); <add> StringWriter writer = new StringWriter(); <add> Result result = new StreamResult(writer); <add> marshaller.marshal(airplane, result); <add> assertXMLEqual("Marshalling should use root Element", <add> writer.toString(), "<airplane><name>test</name></airplane>"); <add> } <add> <ide> @XmlRootElement <ide> @SuppressWarnings("unused") <ide> public static class DummyRootElement { <ide><path>spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <ide> <add>/** <add> * @author Arjen Poutsma <add> * @author Biju Kunjummen <add> */ <ide> public class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTests { <ide> <ide> private static final String INPUT_STRING = "<tns:flights xmlns:tns=\"http://samples.springframework.org/flight\">" + <ide> protected void testFlight(Object o) { <ide> <ide> @Test <ide> @Override <add> @SuppressWarnings("unchecked") <ide> public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception { <ide> XMLInputFactory inputFactory = XMLInputFactory.newInstance(); <ide> XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING)); <ide> public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception { <ide> testFlight(flight); <ide> } <ide> <add> @Test <add> @SuppressWarnings("unchecked") <add> public void unmarshalAnXmlReferingToAWrappedXmlElementDecl() throws Exception { <add> // SPR-10714 <add> unmarshaller = new Jaxb2Marshaller(); <add> unmarshaller.setPackagesToScan(new String[] { "org.springframework.oxm.jaxb" }); <add> unmarshaller.afterPropertiesSet(); <add> Source source = new StreamSource(new StringReader( <add> "<brand-airplane><name>test</name></brand-airplane>")); <add> JAXBElement<Airplane> airplane = (JAXBElement<Airplane>) unmarshaller.unmarshal(source); <add> assertEquals("Unmarshalling via explicit @XmlRegistry tag should return correct type", <add> "test", airplane.getValue().getName()); <add> } <ide> <ide> } <ide><path>spring-oxm/src/test/java/org/springframework/oxm/jaxb/XmlRegObjectFactory.java <add> <add>package org.springframework.oxm.jaxb; <add> <add>import javax.xml.bind.JAXBElement; <add>import javax.xml.bind.annotation.XmlElementDecl; <add>import javax.xml.bind.annotation.XmlRegistry; <add>import javax.xml.namespace.QName; <add> <add>@XmlRegistry <add>public class XmlRegObjectFactory { <add> <add> @XmlElementDecl(name = "brand-airplane") <add> public JAXBElement<Airplane> createAirplane(Airplane airplane) { <add> return new JAXBElement<Airplane>(new QName("brand-airplane"), Airplane.class, null, airplane); <add> } <add>} <ide>\ No newline at end of file
5
Text
Text
add two taps, update ci info
2020f382cb6cc51d58f7cf6c2895361129f11b5a
<ide><path>docs/Brew-Test-Bot.md <ide> `brew test-bot` is the name for the automated review and testing system funded <ide> by [our Kickstarter in 2013](https://www.kickstarter.com/projects/homebrew/brew-test-bot). <ide> <del>It comprises four Mac Minis running in a data centre in England which host <add>It comprises four Mac Minis and three Xserves running in two data centres which host <ide> [a Jenkins instance at https://jenkins.brew.sh](https://jenkins.brew.sh) and run the <ide> [`brew-test-bot.rb`](https://github.com/Homebrew/homebrew-test-bot/blob/master/cmd/brew-test-bot.rb) <ide> Ruby script to perform automated testing of commits to the master branch, pull <ide> A passed build looks like this: <ide> On failed or passed builds you can click the "Details" link to view the result <ide> in Jenkins. <ide> <del>When you click this you'll see the results. <del> <ide> A passed build looks like this: <ide> <ide> ![Passed Jenkins Build](img/docs/brew-test-bot-passed-jenkins.png) <ide><path>docs/Interesting-Taps-and-Forks.md <ide> You can be added as a maintainer for one of the Homebrew organization taps and a <ide> <ide> * [brewsci/science](https://github.com/brewsci/homebrew-science): Software tailored to scientific endeavours. <ide> <add>* [davidchall/hep](https://github.com/davidchall/homebrew-hep): High energy physics formulae. <add> <add>* [lifepillar/appleii](https://github.com/lifepillar/homebrew-appleii): Formulae for vintage Apple emulation. <add> <ide> ## Interesting forks <ide> <del>* [mistydemeo/tigerbrew](https://github.com/mistydemeo/tigerbrew): Experimental Tiger PowerPC version <add>* [mistydemeo/tigerbrew](https://github.com/mistydemeo/tigerbrew): Experimental Tiger PowerPC version. <ide> <del>* [Linuxbrew/brew](https://github.com/Linuxbrew/brew): Experimental Linux version <add>* [Linuxbrew/brew](https://github.com/Linuxbrew/brew): Experimental Linux version. <ide> <ide> ## Technical details <ide>
2
PHP
PHP
improve doc blocks for ide understanding
35f70ad2c9843b1c42afba072615ce9141d3bf45
<ide><path>src/Auth/BaseAuthenticate.php <ide> <ide> /** <ide> * Base Authentication class with common methods and properties. <add> * <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> abstract class BaseAuthenticate implements EventListenerInterface <ide> { <ide><path>src/Auth/BaseAuthorize.php <ide> * Abstract base authorization adapter for AuthComponent. <ide> * <ide> * @see \Cake\Controller\Component\AuthComponent::$authenticate <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> abstract class BaseAuthorize <ide> { <ide><path>src/Auth/Storage/SessionStorage.php <ide> <ide> /** <ide> * Session based persistent storage for authenticated user record. <add> * <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> class SessionStorage implements StorageInterface <ide> { <ide><path>src/Cache/CacheEngine.php <ide> <ide> /** <ide> * Storage engine for CakePHP caching <add> * <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> abstract class CacheEngine <ide> { <ide><path>src/Controller/Component.php <ide> * <ide> * @link https://book.cakephp.org/3.0/en/controllers/components.html <ide> * @see \Cake\Controller\Controller::$components <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> class Component implements EventListenerInterface <ide> { <ide><path>src/Datasource/QueryInterface.php <ide> interface QueryInterface <ide> * <ide> * @param string $field The field to alias <ide> * @param string|null $alias the alias used to prefix the field <del> * @return array <add> * @return string <ide> */ <ide> public function aliasField($field, $alias = null); <ide> <ide> public function aliasField($field, $alias = null); <ide> * <ide> * @param array $fields The fields to alias <ide> * @param string|null $defaultAlias The default alias <del> * @return array <add> * @return string[] <ide> */ <ide> public function aliasFields($fields, $defaultAlias = null); <ide> <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php <ide> * <ide> * Traps exceptions and converts them into HTML or content-type appropriate <ide> * error pages using the CakePHP ExceptionRenderer. <add> * <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> class ErrorHandlerMiddleware <ide> { <ide><path>src/Http/Client.php <ide> * specify which authentication strategy you want to use. <ide> * CakePHP comes with built-in support for basic authentication. <ide> * <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> class Client <ide> { <ide><path>src/Log/Engine/BaseLog.php <ide> <ide> /** <ide> * Base log engine class. <add> * <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> abstract class BaseLog extends AbstractLogger <ide> { <ide><path>src/Mailer/AbstractTransport.php <ide> <ide> /** <ide> * Abstract transport for sending email <add> * <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> abstract class AbstractTransport <ide> { <ide><path>src/Network/Socket.php <ide> * CakePHP network socket connection class. <ide> * <ide> * Core base class for network communication. <add> * <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> class Socket <ide> { <ide><path>src/ORM/Association.php <ide> protected function _formatAssociationResults($query, $surrogate, $options) <ide> $extracted = new ResultSetDecorator($callable($extracted)); <ide> } <ide> <add> /* @var \Cake\Collection\CollectionInterface $results */ <ide> return $results->insert($property, $extracted); <ide> }, Query::PREPEND); <ide> } <ide><path>src/ORM/Behavior.php <ide> * <ide> * @see \Cake\ORM\Table::addBehavior() <ide> * @see \Cake\Event\EventManager <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> class Behavior implements EventListenerInterface <ide> { <ide><path>src/ORM/Behavior/TranslateBehavior.php <ide> public function beforeFind(Event $event, Query $query, $options) <ide> } <ide> <ide> $conditions = function ($field, $locale, $query, $select) { <del> return function ($q) use ($field, $locale, $query, $select) { <del> $q->where([$q->repository()->aliasField('locale') => $locale]); <add> return function ($query) use ($field, $locale, $query, $select) { <add> /* @var \Cake\Datasource\QueryInterface $query */ <add> $query->where([$query->repository()->aliasField('locale') => $locale]); <ide> <add> /* @var \Cake\ORM\Query $query */ <ide> if ($query->isAutoFieldsEnabled() || <ide> in_array($field, $select, true) || <ide> in_array($this->_table->aliasField($field), $select, true) <ide> ) { <del> $q->select(['id', 'content']); <add> $query->select(['id', 'content']); <ide> } <ide> <del> return $q; <add> return $query; <ide> }; <ide> }; <ide> <ide> public function buildMarshalMap($marshaller, $map, $options) <ide> <ide> return [ <ide> '_translations' => function ($value, $entity) use ($marshaller, $options) { <add> /* @var \Cake\Datasource\EntityInterface $entity */ <ide> $translations = $entity->get('_translations'); <ide> foreach ($this->_config['fields'] as $field) { <ide> $options['validate'] = $this->_config['validator']; <ide> $errors = []; <ide> if (!is_array($value)) { <del> return; <add> return null; <ide> } <ide> foreach ($value as $language => $fields) { <ide> if (!isset($translations[$language])) { <ide> public function findTranslations(Query $query, array $options) <ide> $targetAlias = $this->_translationTable->getAlias(); <ide> <ide> return $query <del> ->contain([$targetAlias => function ($q) use ($locales, $targetAlias) { <add> ->contain([$targetAlias => function ($query) use ($locales, $targetAlias) { <ide> if ($locales) { <del> $q->where(["$targetAlias.locale IN" => $locales]); <add> /* @var \Cake\Datasource\QueryInterface $query */ <add> $query->where(["$targetAlias.locale IN" => $locales]); <ide> } <ide> <del> return $q; <add> return $query; <ide> }]) <ide> ->formatResults([$this, 'groupTranslations'], $query::PREPEND); <ide> } <ide> protected function _rowMapper($results, $locale) <ide> <ide> $row['_locale'] = $locale; <ide> if ($hydrated) { <add> /** @var \Cake\Datasource\EntityInterface $row */ <ide> $row->clean(); <ide> } <ide> <ide><path>src/ORM/Table.php <ide> public function findList(Query $query, array $options) <ide> ); <ide> <ide> return $query->formatResults(function ($results) use ($options) { <add> /* @var \Cake\Collection\CollectionInterface $results */ <ide> return $results->combine( <ide> $options['keyField'], <ide> $options['valueField'], <ide> public function findThreaded(Query $query, array $options) <ide> $options = $this->_setFieldMatchers($options, ['keyField', 'parentField']); <ide> <ide> return $query->formatResults(function ($results) use ($options) { <add> /* @var \Cake\Collection\CollectionInterface $results */ <ide> return $results->nest($options['keyField'], $options['parentField'], $options['nestingKey']); <ide> }); <ide> } <ide><path>src/Routing/DispatcherFilter.php <ide> * <ide> * When using the `for` or `when` matchers, conditions will be re-checked on the before and after <ide> * callback as the conditions could change during the dispatch cycle. <add> * <add> * @mixin \Cake\Core\InstanceConfigTrait <ide> */ <ide> class DispatcherFilter implements EventListenerInterface <ide> {
16
Javascript
Javascript
use createelement and innerhtml
16b3af3762bcf3b430c677de3eebff25236f3cac
<ide><path>packages/ember-views/lib/system/render_buffer.js <ide> Ember._RenderBuffer.prototype = <ide> of this buffer <ide> */ <ide> element: function() { <del> return Ember.$(this.string())[0]; <add> var element = document.createElement(this.elementTag), <add> id = this.elementId, <add> classes = this.elementClasses, <add> attrs = this.elementAttributes, <add> style = this.elementStyle, <add> styleBuffer = '', prop; <add> <add> if (id) { element.setAttribute('id', id); } <add> if (classes) { element.setAttribute('class', classes.toDOM()); } <add> <add> if (style) { <add> for (prop in style) { <add> if (style.hasOwnProperty(prop)) { <add> styleBuffer += (prop + ':' + style[prop] + ';'); <add> } <add> } <add> <add> element.setAttribute('style', styleBuffer); <add> } <add> <add> if (attrs) { <add> for (prop in attrs) { <add> if (attrs.hasOwnProperty(prop)) { <add> element.setAttribute(prop, attrs[prop]); <add> } <add> } <add> } <add> <add> this.elementTag = ''; // hack to avoid creating an innerString function <add> element.innerHTML = this.string(); <add> return element; <ide> }, <ide> <ide> /** <ide> Generates the HTML content for this buffer. <ide> <ide> @method string <del> @return {String} The generated HTMl <add> @return {String} The generated HTML <ide> */ <ide> string: function() { <ide> var content = [];
1
Text
Text
remove outdated timeout.unref content
a7164fdd1a27c30f425d96f6a9392da5418751ee
<ide><path>doc/api/timers.md <ide> to remain active. If there is no other activity keeping the event loop running, <ide> the process may exit before the `Timeout` object's callback is invoked. Calling <ide> `timeout.unref()` multiple times will have no effect. <ide> <del>Calling `timeout.unref()` creates an internal timer that will wake the Node.js <del>event loop. Creating too many of these can adversely impact performance <del>of the Node.js application. <del> <ide> ### `timeout[Symbol.toPrimitive]()` <ide> <ide> <!-- YAML
1
Go
Go
fix inspectexecid test
c5c98c31a184837c7f5b1f43d8ef18a676a8bf30
<ide><path>integration-cli/docker_cli_exec_test.go <ide> func (s *DockerSuite) TestInspectExecID(c *check.C) { <ide> if out != "[]" && out != "<no value>" { <ide> break <ide> } <del> if i == tries { <add> if i+1 == tries { <ide> c.Fatalf("ExecIDs should not be empty, got: %s", out) <ide> } <ide> time.Sleep(1 * time.Second)
1
PHP
PHP
add table truncation for sqlite + mysql
416d340331aa70a33873070adcf81128a8127b2a
<ide><path>lib/Cake/Database/Schema/MysqlSchema.php <ide> public function extraSchemaColumns() { <ide> ]; <ide> } <ide> <add>/** <add> * Generate the SQL to truncate a table. <add> * <add> * @param Cake\Database\Schema\Table $table Table instance <add> * @return array TRUNCATE TABLE sql <add> */ <add> public function truncateTableSql(Table $table) { <add> return [sprintf("TRUNCATE TABLE `%s`", $table->name())]; <add> } <add> <ide> /** <ide> * Generate the SQL to drop a table. <ide> * <ide><path>lib/Cake/Database/Schema/SqliteSchema.php <ide> public function dropTableSql(Table $table) { <ide> return [sprintf('DROP TABLE "%s"', $table->name())]; <ide> } <ide> <add>/** <add> * Generate the SQL to truncate a table. <add> * <add> * @param Cake\Database\Schema\Table $table Table instance <add> * @return array SQL statements to drop truncate a table. <add> */ <add> public function truncateTableSql(Table $table) { <add> $name = $table->name(); <add> return [ <add> sprintf('DELETE FROM sqlite_sequence WHERE name="%s"', $name), <add> sprintf('DELETE FROM "%s"', $name) <add> ]; <add> } <add> <ide> } <ide><path>lib/Cake/Database/Schema/Table.php <ide> public function dropSql(Connection $connection) { <ide> */ <ide> public function truncateSql(Connection $connection) { <ide> $dialect = $connection->driver()->schemaDialect(); <del> return $dialect->truncateSql($this); <add> return $dialect->truncateTableSql($this); <ide> } <ide> <ide> } <ide><path>lib/Cake/Test/TestCase/Database/Schema/MysqlSchemaTest.php <ide> public function testDropSql() { <ide> <ide> /** <ide> * Test truncateSql() <add> * <add> * @return void <ide> */ <ide> public function testTruncateSql() { <add> $driver = $this->_getMockedDriver(); <add> $connection = $this->getMock('Cake\Database\Connection', array(), array(), '', false); <add> $connection->expects($this->any())->method('driver') <add> ->will($this->returnValue($driver)); <add> <add> $table = new Table('articles'); <add> $result = $table->truncateSql($connection); <add> $this->assertCount(1, $result); <add> $this->assertEquals('TRUNCATE TABLE `articles`', $result[0]); <ide> } <ide> <ide> /** <ide><path>lib/Cake/Test/TestCase/Database/Schema/SqliteSchemaTest.php <ide> public function testDropSql() { <ide> $this->assertEquals('DROP TABLE "articles"', $result[0]); <ide> } <ide> <add>/** <add> * Test truncateSql() <add> * <add> * @return void <add> */ <add> public function testTruncateSql() { <add> $driver = $this->_getMockedDriver(); <add> $connection = $this->getMock('Cake\Database\Connection', array(), array(), '', false); <add> $connection->expects($this->any())->method('driver') <add> ->will($this->returnValue($driver)); <add> <add> $table = new Table('articles'); <add> $result = $table->truncateSql($connection); <add> $this->assertCount(2, $result); <add> $this->assertEquals('DELETE FROM sqlite_sequence WHERE name="articles"', $result[0]); <add> $this->assertEquals('DELETE FROM "articles"', $result[1]); <add> } <add> <ide> /** <ide> * Get a schema instance with a mocked driver/pdo instances <ide> *
5
Java
Java
provide xml assertions in webtestclient
2734f01067fb231ee3fd3d6dd100e0ae6ed6ed0b
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClient.java <ide> import java.util.concurrent.atomic.AtomicLong; <ide> import java.util.function.Consumer; <ide> import java.util.function.Function; <add>import javax.xml.xpath.XPathExpressionException; <ide> <ide> import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.Flux; <ide> import org.springframework.http.client.reactive.ClientHttpRequest; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.test.util.JsonExpectationsHelper; <add>import org.springframework.test.util.XmlExpectationsHelper; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.MimeType; <ide> import org.springframework.util.MultiValueMap; <ide> public BodyContentSpec json(String json) { <ide> return this; <ide> } <ide> <add> @Override <add> public BodyContentSpec xml(String expectedXml) { <add> this.result.assertWithDiagnostics(() -> { <add> try { <add> new XmlExpectationsHelper().assertXmlEqual(expectedXml, getBodyAsString()); <add> } <add> catch (Exception ex) { <add> throw new AssertionError("XML parsing error", ex); <add> } <add> }); <add> return this; <add> } <add> <ide> @Override <ide> public JsonPathAssertions jsonPath(String expression, Object... args) { <ide> return new JsonPathAssertions(this, getBodyAsString(), expression, args); <ide> } <ide> <add> @Override <add> public XpathAssertions xpath(String expression, Map<String, String> namespaces, Object... args) { <add> try { <add> return new XpathAssertions(this, expression, namespaces, args); <add> } <add> catch (XPathExpressionException ex) { <add> throw new AssertionError("XML parsing error", ex); <add> } <add> } <add> <ide> private String getBodyAsString() { <ide> byte[] body = this.result.getResponseBody(); <ide> if (body == null || body.length == 0) { <ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/WebTestClient.java <ide> interface BodyContentSpec { <ide> */ <ide> BodyContentSpec json(String expectedJson); <ide> <add> /** <add> * Parse the expected and actual response content as XML and perform a <add> * comparison verifying the same structure. <add> * @param expectedXml the expected JSON content. <add> * @since 5.1 <add> */ <add> BodyContentSpec xml(String expectedXml); <add> <ide> /** <ide> * Access to response body assertions using a <ide> * <a href="https://github.com/jayway/JsonPath">JsonPath</a> expression <ide> interface BodyContentSpec { <ide> */ <ide> JsonPathAssertions jsonPath(String expression, Object... args); <ide> <add> /** <add> * Access to response body assertions using an XPath expression to inspect a specific <add> * subset of the body. <add> * <p>The XPath expression can be a parameterized string using <add> * formatting specifiers as defined in {@link String#format}. <add> * @param expression The XPath expression <add> * @param args arguments to parameterize the expression <add> * @see #xpath(String, Map, Object...) <add> * @since 5.1 <add> */ <add> default XpathAssertions xpath(String expression, Object... args){ <add> return xpath(expression, null, args); <add> } <add> <add> /** <add> * Access to response body assertions with specific namespaces using an XPath <add> * expression to inspect a specific subset of the body. <add> * <p>The XPath expression can be a parameterized string using <add> * formatting specifiers as defined in {@link String#format}. <add> * @param expression The XPath expression <add> * @param namespaces The namespaces <add> * @param args arguments to parameterize the expression <add> * @since 5.1 <add> */ <add> XpathAssertions xpath(String expression, Map<String, String> namespaces, Object... args); <add> <ide> /** <ide> * Assert the response body content with the given {@link Consumer}. <ide> * @param consumer the consumer for the response body; the input <ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/XpathAssertions.java <add>/* <add> * Copyright 2002-2018 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.test.web.reactive.server; <add> <add>import java.nio.charset.StandardCharsets; <add>import java.util.Map; <add>import java.util.Optional; <add>import javax.xml.xpath.XPathExpressionException; <add> <add>import org.hamcrest.Matcher; <add>import org.w3c.dom.Node; <add> <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.lang.Nullable; <add>import org.springframework.test.util.XpathExpectationsHelper; <add>import org.springframework.util.MimeType; <add> <add>/** <add> * XPath assertions for a {@link WebTestClient}. <add> * <add> * @author Eric Deandrea <add> * @since 5.1 <add> */ <add>public class XpathAssertions { <add> <add> private final WebTestClient.BodyContentSpec bodySpec; <add> <add> private final XpathExpectationsHelper xpathHelper; <add> <add> XpathAssertions(WebTestClient.BodyContentSpec spec, String expression, @Nullable Map<String, String> namespaces, Object... args) throws XPathExpressionException { <add> this.bodySpec = spec; <add> this.xpathHelper = new XpathExpectationsHelper(expression, namespaces, args); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper#assertString(byte[], String, String)} <add> */ <add> public WebTestClient.BodyContentSpec isEqualTo(String expectedValue) { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.assertString(getResponseBody(), getDefinedEncoding(), expectedValue)); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper#assertNumber(byte[], String, Double)} <add> */ <add> public WebTestClient.BodyContentSpec isEqualTo(Double expectedValue) { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.assertNumber(getResponseBody(), getDefinedEncoding(), expectedValue)); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper#assertBoolean(byte[], String, boolean)} <add> */ <add> public WebTestClient.BodyContentSpec isEqualTo(boolean expectedValue) { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.assertBoolean(getResponseBody(), getDefinedEncoding(), expectedValue)); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper#exists(byte[], String)} <add> */ <add> public WebTestClient.BodyContentSpec exists() { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.exists(getResponseBody(), getDefinedEncoding())); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper#doesNotExist(byte[], String)} <add> */ <add> public WebTestClient.BodyContentSpec doesNotExist() { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.doesNotExist(getResponseBody(), getDefinedEncoding())); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper[#assertNodeCount(byte[], String, int)} <add> */ <add> public WebTestClient.BodyContentSpec nodeCount(int expectedCount) { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.assertNodeCount(getResponseBody(), getDefinedEncoding(), expectedCount)); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper#assertNodeCount(byte[], String, Matcher)} <add> */ <add> public WebTestClient.BodyContentSpec nodeCount(Matcher<Integer> matcher) { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.assertNodeCount(getResponseBody(), getDefinedEncoding(), matcher)); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper#assertNode(byte[], String, Matcher)} <add> */ <add> public WebTestClient.BodyContentSpec nodeMatches(Matcher<? super Node> matcher) { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.assertNode(getResponseBody(), getDefinedEncoding(), matcher)); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper#assertString(byte[], String, Matcher)} <add> */ <add> public WebTestClient.BodyContentSpec matchesString(Matcher<? super String> matcher) { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.assertString(getResponseBody(), getDefinedEncoding(), matcher)); <add> } <add> <add> /** <add> * Applies {@link XpathExpectationsHelper#assertNumber(byte[], String, Matcher)} <add> */ <add> public WebTestClient.BodyContentSpec matchesNumber(Matcher<? super Double> matcher) { <add> return performXmlAssertionAndHandleError(() -> this.xpathHelper.assertNumber(getResponseBody(), getDefinedEncoding(), matcher)); <add> } <add> <add> private WebTestClient.BodyContentSpec performXmlAssertionAndHandleError(AssertionThrowingRunnable assertion) { <add> assertion.run(); <add> return this.bodySpec; <add> } <add> <add> private byte[] getResponseBody() { <add> return getResult().getResponseBody(); <add> } <add> <add> private EntityExchangeResult<byte[]> getResult() { <add> return this.bodySpec.returnResult(); <add> } <add> <add> private String getDefinedEncoding() { <add> return Optional.ofNullable(getResult()) <add> .map(EntityExchangeResult::getResponseHeaders) <add> .map(HttpHeaders::getContentType) <add> .map(MimeType::getCharset) <add> .orElse(StandardCharsets.UTF_8) <add> .name(); <add> } <add> <add> /** <add> * Lets us be able to use lambda expressions that could throw checked exceptions, since <add> * {@link XpathExpectationsHelper} throws {@link Exception} on its methods. <add> */ <add> @FunctionalInterface <add> private interface AssertionThrowingRunnable extends Runnable { <add> void runThrows() throws Exception; <add> <add> @Override <add> default void run() { <add> try { <add> runThrows(); <add> } <add> catch (Exception ex) { <add> throw new AssertionError("XML parsing error", ex); <add> } <add> } <add> } <add>} <ide>\ No newline at end of file <ide><path>spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/XmlContentTests.java <add>/* <add> * Copyright 2002-2018 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.test.web.reactive.server.samples; <add> <add>import java.net.URI; <add>import java.util.ArrayList; <add>import java.util.Arrays; <add>import java.util.List; <add> <add>import javax.validation.constraints.NotNull; <add>import javax.xml.bind.annotation.XmlAccessType; <add>import javax.xml.bind.annotation.XmlAccessorType; <add>import javax.xml.bind.annotation.XmlElement; <add>import javax.xml.bind.annotation.XmlElementWrapper; <add>import javax.xml.bind.annotation.XmlRootElement; <add> <add>import org.hamcrest.Matchers; <add>import org.junit.Test; <add>import reactor.core.publisher.Flux; <add>import reactor.core.publisher.Mono; <add> <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.http.MediaType; <add>import org.springframework.http.ResponseEntity; <add>import org.springframework.test.web.reactive.server.WebTestClient; <add>import org.springframework.util.ObjectUtils; <add>import org.springframework.web.bind.annotation.GetMapping; <add>import org.springframework.web.bind.annotation.PathVariable; <add>import org.springframework.web.bind.annotation.PostMapping; <add>import org.springframework.web.bind.annotation.RequestBody; <add>import org.springframework.web.bind.annotation.RequestMapping; <add>import org.springframework.web.bind.annotation.RestController; <add> <add>/** <add> * Samples of tests using {@link WebTestClient} with serialized XML content. <add> * <add> * @author Eric Deandrea <add> * @since 5.1 <add> */ <add>public class XmlContentTests { <add> <add> private static final String PEOPLE_XML = <add> "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" <add> + "<people><people>" <add> + "<person><name>Jane</name></person>" <add> + "<person><name>Jason</name></person>" <add> + "<person><name>John</name></person>" <add> + "</people></people>"; <add> <add> private final WebTestClient client = WebTestClient.bindToController(new PersonController()).build(); <add> <add> @Test <add> public void xmlContent() { <add> this.client.get().uri("/persons") <add> .accept(MediaType.APPLICATION_XML) <add> .exchange() <add> .expectStatus().isOk() <add> .expectBody().xml(PEOPLE_XML); <add> } <add> <add> @Test <add> public void xpathIsEqualTo() { <add> this.client.get().uri("/persons") <add> .accept(MediaType.APPLICATION_XML) <add> .exchange() <add> .expectStatus().isOk() <add> .expectBody() <add> .xpath("/").exists() <add> .xpath("/people").exists() <add> .xpath("/people/people").exists() <add> .xpath("/people/people/person").exists() <add> .xpath("/people/people/person").nodeCount(3) <add> .xpath("/people/people/person[1]/name").isEqualTo("Jane") <add> .xpath("/people/people/person[2]/name").isEqualTo("Jason") <add> .xpath("/people/people/person[3]/name").isEqualTo("John"); <add> } <add> <add> @Test <add> public void xpathMatches() { <add> this.client.get().uri("/persons") <add> .accept(MediaType.APPLICATION_XML) <add> .exchange() <add> .expectStatus().isOk() <add> .expectBody() <add> .xpath("/").exists() <add> .xpath("/people").exists() <add> .xpath("/people/people").exists() <add> .xpath("/people/people/person").exists() <add> .xpath("/people/people/person").nodeCount(3) <add> .xpath("//person/name").matchesString(Matchers.startsWith("J")); <add> } <add> <add> @Test <add> public void xpathContainsSubstringViaRegex() { <add> this.client.get().uri("/persons/John") <add> .accept(MediaType.APPLICATION_XML) <add> .exchange() <add> .expectStatus().isOk() <add> .expectBody() <add> .xpath("//name[contains(text(), 'oh')]").exists(); <add> } <add> <add> @Test <add> public void postXmlContent() { <add> this.client.post().uri("/persons") <add> .contentType(MediaType.APPLICATION_XML) <add> .syncBody("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><person><name>John</name></person>") <add> .exchange() <add> .expectStatus().isCreated() <add> .expectHeader().valueEquals(HttpHeaders.LOCATION, "/persons/John") <add> .expectBody().isEmpty(); <add> } <add> <add> @XmlRootElement <add> private static class Person { <add> <add> @NotNull <add> private String name; <add> <add> public Person() { <add> } <add> <add> public Person(String name) { <add> this.name = name; <add> } <add> <add> public String getName() { <add> return this.name; <add> } <add> <add> public void setName(String name) { <add> this.name = name; <add> } <add> <add> public Person name(String name) { <add> setName(name); <add> return this; <add> } <add> <add> @Override <add> public boolean equals(Object other) { <add> if (this == other) { <add> return true; <add> } <add> if (!(other instanceof Person)) { <add> return false; <add> } <add> Person otherPerson = (Person) other; <add> return ObjectUtils.nullSafeEquals(this.name, otherPerson.name); <add> } <add> <add> @Override <add> public int hashCode() { <add> return Person.class.hashCode(); <add> } <add> <add> @Override <add> public String toString() { <add> return "Person [name=" + this.name + "]"; <add> } <add> } <add> <add> @SuppressWarnings("unused") <add> @XmlRootElement(name="people") <add> @XmlAccessorType(XmlAccessType.FIELD) <add> private static class PeopleWrapper { <add> <add> @XmlElementWrapper(name="people") <add> @XmlElement(name="person") <add> private final List<Person> people = new ArrayList<>(); <add> <add> public PeopleWrapper() { <add> } <add> <add> public PeopleWrapper(List<Person> people) { <add> this.people.addAll(people); <add> } <add> <add> public PeopleWrapper(Person... people) { <add> this.people.addAll(Arrays.asList(people)); <add> } <add> <add> public List<Person> getPeople() { <add> return this.people; <add> } <add> } <add> <add> @RestController <add> @RequestMapping("/persons") <add> static class PersonController { <add> <add> @GetMapping(produces = MediaType.APPLICATION_XML_VALUE) <add> Mono<PeopleWrapper> getPersons() { <add> return Mono.just(new PeopleWrapper(new Person("Jane"), new Person("Jason"), new Person("John"))); <add> } <add> <add> @GetMapping(path = "/{name}", produces = MediaType.APPLICATION_XML_VALUE) <add> Mono<Person> getPerson(@PathVariable String name) { <add> return Mono.just(new Person(name)); <add> } <add> <add> @PostMapping(consumes = MediaType.APPLICATION_XML_VALUE) <add> Mono<ResponseEntity<Object>> savePeople(@RequestBody Flux<Person> person) { <add> return person <add> .map(Person::getName) <add> .map(name -> String.format("/persons/%s", name)) <add> .map(URI::create) <add> .map(ResponseEntity::created) <add> .map(ResponseEntity.BodyBuilder::build) <add> .next(); <add> } <add> } <add> <add>} <ide>\ No newline at end of file
4
Javascript
Javascript
rename some allegories
682f9b4709f0d7e634568209ce3adfe18e345774
<ide><path>test/internet/test-dgram-broadcast-multi-process.js <ide> if (process.argv[2] !== 'child') { <ide> TIMEOUT); <ide> console.error('[PARENT] Fail'); <ide> <del> killChildren(workers); <add> killSubprocesses(workers); <ide> <ide> process.exit(1); <ide> }, TIMEOUT); <ide> if (process.argv[2] !== 'child') { <ide> console.error('[PARENT] All workers have died.'); <ide> console.error('[PARENT] Fail'); <ide> <del> killChildren(workers); <add> killSubprocesses(workers); <ide> <ide> process.exit(1); <ide> } <ide> if (process.argv[2] !== 'child') { <ide> <ide> clearTimeout(timer); <ide> console.error('[PARENT] Success'); <del> killChildren(workers); <add> killSubprocesses(workers); <ide> } <ide> } <ide> }); <ide> if (process.argv[2] !== 'child') { <ide> ); <ide> }; <ide> <del> function killChildren(children) { <del> Object.keys(children).forEach(function(key) { <del> const child = children[key]; <del> child.kill(); <add> function killSubprocesses(subprocesses) { <add> Object.keys(subprocesses).forEach(function(key) { <add> const subprocess = subprocesses[key]; <add> subprocess.kill(); <ide> }); <ide> } <ide> } <ide><path>test/internet/test-dgram-multicast-multi-process.js <ide> function launchChildProcess() { <ide> <ide> clearTimeout(timer); <ide> console.error('[PARENT] Success'); <del> killChildren(workers); <add> killSubprocesses(workers); <ide> } <ide> } <ide> }); <ide> } <ide> <del>function killChildren(children) { <del> Object.keys(children).forEach(function(key) { <del> const child = children[key]; <del> child.kill(); <add>function killSubprocesses(subprocesses) { <add> Object.keys(subprocesses).forEach(function(key) { <add> const subprocess = subprocesses[key]; <add> subprocess.kill(); <ide> }); <ide> } <ide> <ide> if (process.argv[2] !== 'child') { <ide> TIMEOUT); <ide> console.error('[PARENT] Fail'); <ide> <del> killChildren(workers); <add> killSubprocesses(workers); <ide> <ide> process.exit(1); <ide> }, TIMEOUT); <ide><path>test/internet/test-dgram-multicast-set-interface-lo.js <ide> if (process.argv[2] !== 'child') { <ide> TIMEOUT); <ide> console.error('[PARENT] Skip'); <ide> <del> killChildren(workers); <add> killSubprocesses(workers); <ide> common.skip('Check filter policy'); <ide> <ide> process.exit(1); <ide> if (process.argv[2] !== 'child') { <ide> console.error('[PARENT] All workers have died.'); <ide> console.error('[PARENT] Fail'); <ide> <del> killChildren(workers); <add> killSubprocesses(workers); <ide> <ide> process.exit(1); <ide> } <ide> if (process.argv[2] !== 'child') { <ide> <ide> clearTimeout(timer); <ide> console.error('[PARENT] Success'); <del> killChildren(workers); <add> killSubprocesses(workers); <ide> } <ide> } <ide> }); <ide> if (process.argv[2] !== 'child') { <ide> ); <ide> }; <ide> <del> function killChildren(children) { <del> for (const i in children) <del> children[i].kill(); <add> function killSubprocesses(subprocesses) { <add> for (const i in subprocesses) <add> subprocesses[i].kill(); <ide> } <ide> } <ide> <ide><path>test/parallel/test-child-process-fork-net.js <ide> if (process.argv[2] === 'child') { <ide> while (j--) { <ide> const client = net.connect(this.address().port, '127.0.0.1'); <ide> client.on('error', function() { <del> // This can happen if we kill the child too early. <add> // This can happen if we kill the subprocess too early. <ide> // The client should still get a close event afterwards. <ide> console.error('[m] CLIENT: error event'); <ide> }); <ide><path>test/parallel/test-listen-fd-detached-inherit.js <ide> function test() { <ide> function next() { <ide> console.error('output from parent = %s', json); <ide> const child = JSON.parse(json); <del> // now make sure that we can request to the child, then kill it. <add> // now make sure that we can request to the subprocess, then kill it. <ide> http.get({ <ide> server: 'localhost', <ide> port: child.port, <ide> function test() { <ide> s += c.toString(); <ide> }); <ide> res.on('end', function() { <del> // kill the child before we start doing asserts. <add> // kill the subprocess before we start doing asserts. <ide> // it's really annoying when tests leave orphans! <ide> process.kill(child.pid, 'SIGKILL'); <ide> try { <ide><path>test/parallel/test-listen-fd-detached.js <ide> function test() { <ide> function next() { <ide> console.error('output from parent = %s', json); <ide> const child = JSON.parse(json); <del> // now make sure that we can request to the child, then kill it. <add> // now make sure that we can request to the subprocess, then kill it. <ide> http.get({ <ide> server: 'localhost', <ide> port: child.port, <ide> function test() { <ide> s += c.toString(); <ide> }); <ide> res.on('end', function() { <del> // kill the child before we start doing asserts. <add> // kill the subprocess before we start doing asserts. <ide> // it's really annoying when tests leave orphans! <ide> process.kill(child.pid, 'SIGKILL'); <ide> try { <ide><path>test/parallel/test-listen-fd-server.js <ide> process.on('exit', function() { <ide> // concurrency in HTTP servers! Use the cluster module, or if you want <ide> // a more low-level approach, use child process IPC manually. <ide> test(function(child, port) { <del> // now make sure that we can request to the child, then kill it. <add> // now make sure that we can request to the subprocess, then kill it. <ide> http.get({ <ide> server: 'localhost', <ide> port: port, <ide><path>test/sequential/test-child-process-fork-getconnections.js <ide> if (process.argv[2] === 'child') { <ide> const child = fork(process.argv[1], ['child']); <ide> <ide> child.on('exit', function(code, signal) { <del> if (!childKilled) <del> throw new Error('child died unexpectedly!'); <add> if (!subprocessKilled) <add> throw new Error('subprocess died unexpectedly!'); <ide> }); <ide> <ide> const server = net.createServer(); <ide> if (process.argv[2] === 'child') { <ide> } <ide> }); <ide> <del> let childKilled = false; <add> let subprocessKilled = false; <ide> function closeSockets(i) { <ide> if (i === count) { <del> childKilled = true; <add> subprocessKilled = true; <ide> server.close(); <ide> child.kill(); <ide> return;
8
Go
Go
add interface for untar
14692d0d417378efc3456ddb810eae5646652bda
<ide><path>pkg/archive/archive.go <ide> type ( <ide> NoLchown bool <ide> Name string <ide> } <add> <add> // Archiver allows the reuse of most utility functions of this package <add> // with a pluggable Untar function. <add> Archiver struct { <add> Untar func(io.Reader, string, *TarOptions) error <add> } <ide> ) <ide> <ide> var ( <ide> ErrNotImplemented = errors.New("Function not implemented") <add> defaultArchiver = &Archiver{Untar} <ide> ) <ide> <ide> const ( <ide> loop: <ide> return nil <ide> } <ide> <del>// TarUntar is a convenience function which calls Tar and Untar, with <del>// the output of one piped into the other. If either Tar or Untar fails, <del>// TarUntar aborts and returns the error. <del>func TarUntar(src string, dst string) error { <add>func (archiver *Archiver) TarUntar(src, dst string) error { <ide> log.Debugf("TarUntar(%s %s)", src, dst) <ide> archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) <ide> if err != nil { <ide> return err <ide> } <ide> defer archive.Close() <del> return Untar(archive, dst, nil) <add> return archiver.Untar(archive, dst, nil) <ide> } <ide> <del>// UntarPath is a convenience function which looks for an archive <del>// at filesystem path `src`, and unpacks it at `dst`. <del>func UntarPath(src, dst string) error { <add>// TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. <add>// If either Tar or Untar fails, TarUntar aborts and returns the error. <add>func TarUntar(src, dst string) error { <add> return defaultArchiver.TarUntar(src, dst) <add>} <add> <add>func (archiver *Archiver) UntarPath(src, dst string) error { <ide> archive, err := os.Open(src) <ide> if err != nil { <ide> return err <ide> } <ide> defer archive.Close() <del> if err := Untar(archive, dst, nil); err != nil { <add> if err := archiver.Untar(archive, dst, nil); err != nil { <ide> return err <ide> } <ide> return nil <ide> } <ide> <del>// CopyWithTar creates a tar archive of filesystem path `src`, and <del>// unpacks it at filesystem path `dst`. <del>// The archive is streamed directly with fixed buffering and no <del>// intermediary disk IO. <del>// <del>func CopyWithTar(src, dst string) error { <add>// UntarPath is a convenience function which looks for an archive <add>// at filesystem path `src`, and unpacks it at `dst`. <add>func UntarPath(src, dst string) error { <add> return defaultArchiver.UntarPath(src, dst) <add>} <add> <add>func (archiver *Archiver) CopyWithTar(src, dst string) error { <ide> srcSt, err := os.Stat(src) <ide> if err != nil { <ide> return err <ide> } <ide> if !srcSt.IsDir() { <del> return CopyFileWithTar(src, dst) <add> return archiver.CopyFileWithTar(src, dst) <ide> } <ide> // Create dst, copy src's content into it <ide> log.Debugf("Creating dest directory: %s", dst) <ide> if err := os.MkdirAll(dst, 0755); err != nil && !os.IsExist(err) { <ide> return err <ide> } <ide> log.Debugf("Calling TarUntar(%s, %s)", src, dst) <del> return TarUntar(src, dst) <add> return archiver.TarUntar(src, dst) <ide> } <ide> <del>// CopyFileWithTar emulates the behavior of the 'cp' command-line <del>// for a single file. It copies a regular file from path `src` to <del>// path `dst`, and preserves all its metadata. <del>// <del>// If `dst` ends with a trailing slash '/', the final destination path <del>// will be `dst/base(src)`. <del>func CopyFileWithTar(src, dst string) (err error) { <add>// CopyWithTar creates a tar archive of filesystem path `src`, and <add>// unpacks it at filesystem path `dst`. <add>// The archive is streamed directly with fixed buffering and no <add>// intermediary disk IO. <add>func CopyWithTar(src, dst string) error { <add> return defaultArchiver.CopyWithTar(src, dst) <add>} <add> <add>func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { <ide> log.Debugf("CopyFileWithTar(%s, %s)", src, dst) <ide> srcSt, err := os.Stat(src) <ide> if err != nil { <ide> func CopyFileWithTar(src, dst string) (err error) { <ide> err = er <ide> } <ide> }() <del> return Untar(r, filepath.Dir(dst), nil) <add> return archiver.Untar(r, filepath.Dir(dst), nil) <add>} <add> <add>// CopyFileWithTar emulates the behavior of the 'cp' command-line <add>// for a single file. It copies a regular file from path `src` to <add>// path `dst`, and preserves all its metadata. <add>// <add>// If `dst` ends with a trailing slash '/', the final destination path <add>// will be `dst/base(src)`. <add>func CopyFileWithTar(src, dst string) (err error) { <add> return defaultArchiver.CopyFileWithTar(src, dst) <ide> } <ide> <ide> // CmdStream executes a command, and returns its stdout as a stream.
1
Ruby
Ruby
add gcab 1.3 to whitelist
9fc495125dd730319014983903cbcdb3db5c746e
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_specs <ide> pygtkglext 1.1.0 <ide> gtk-mac-integration 2.1.3 <ide> gtk-doc 1.31 <add> gcab 1.3 <ide> ].each_slice(2).to_a.map do |formula, version| <ide> [formula, version.split(".")[0..1].join(".")] <ide> end
1
Text
Text
modify invalid url in plugins_network.md
fc7c235f84f76d5d64f25bc802486ecbe87f8b95
<ide><path>docs/extend/plugins_network.md <ide> referring to that network will be sent to the plugin, <ide> ## Write a network plugin <ide> <ide> Network plugins implement the [Docker plugin <del>API](https://docs.docker.com/extend/plugin_api/) and the network plugin protocol <add>API](plugin_api.md) and the network plugin protocol <ide> <ide> ## Network plugin protocol <ide>
1
Java
Java
fix memory leak in newthreadscheduler recursion
b1d9c1cb62517f7cf3cbb64ac2c9bc2fd55d4f50
<ide><path>rxjava-core/src/main/java/rx/schedulers/NewThreadScheduler.java <ide> import rx.Scheduler; <ide> import rx.Subscription; <ide> import rx.subscriptions.CompositeSubscription; <add>import rx.subscriptions.MultipleAssignmentSubscription; <ide> import rx.subscriptions.Subscriptions; <add>import rx.util.functions.Action0; <ide> import rx.util.functions.Func2; <ide> <ide> /** <ide> private NewThreadScheduler() { <ide> <ide> private static class EventLoopScheduler extends Scheduler { <ide> private final ExecutorService executor; <add> private final MultipleAssignmentSubscription childSubscription = new MultipleAssignmentSubscription(); <ide> <ide> private EventLoopScheduler() { <ide> executor = Executors.newFixedThreadPool(1, new ThreadFactory() { <ide> public Thread newThread(Runnable r) { <ide> <ide> @Override <ide> public <T> Subscription schedule(T state, Func2<? super Scheduler, ? super T, ? extends Subscription> action) { <add> CompositeSubscription s = new CompositeSubscription(); <ide> final DiscardableAction<T> discardableAction = new DiscardableAction<T>(state, action); <del> // all subscriptions that may need to be unsubscribed <del> final CompositeSubscription subscription = new CompositeSubscription(discardableAction); <del> <add> s.add(discardableAction); <add> <ide> final Scheduler _scheduler = this; <del> subscription.add(Subscriptions.from(executor.submit(new Runnable() { <add> s.add(Subscriptions.from(executor.submit(new Runnable() { <ide> <ide> @Override <ide> public void run() { <del> Subscription s = discardableAction.call(_scheduler); <del> subscription.add(s); <add> discardableAction.call(_scheduler); <ide> } <ide> }))); <del> <del> return subscription; <add> <add> // replace the EventLoopScheduler child subscription with this one <add> childSubscription.set(s); <add> /* <add> * If `schedule` is run concurrently instead of recursively then we'd lose subscriptions as the `childSubscription` <add> * only remembers the last one scheduled. However, the parent subscription will shutdown the entire EventLoopScheduler <add> * and the ExecutorService which will terminate all outstanding tasks so this childSubscription is actually somewhat <add> * superfluous for stopping and cleanup ... though childSubscription does ensure exactness as can be seen by <add> * the `testUnSubscribeForScheduler()` unit test which fails if the `childSubscription` does not exist. <add> */ <add> <add> return childSubscription; <ide> } <ide> <ide> @Override <ide> public void run() { <ide> return subscription; <ide> } <ide> <add> private void shutdownNow() { <add> executor.shutdownNow(); <add> } <add> <ide> } <ide> <ide> @Override <ide> public <T> Subscription schedule(T state, Func2<? super Scheduler, ? super T, ? extends Subscription> action) { <del> EventLoopScheduler s = new EventLoopScheduler(); <del> return s.schedule(state, action); <add> final EventLoopScheduler s = new EventLoopScheduler(); <add> CompositeSubscription cs = new CompositeSubscription(); <add> cs.add(s.schedule(state, action)); <add> cs.add(Subscriptions.create(new Action0() { <add> <add> @Override <add> public void call() { <add> // shutdown the executor, all tasks queued to run and clean up resources <add> s.shutdownNow(); <add> } <add> })); <add> return cs; <ide> } <ide> <ide> @Override
1
Text
Text
drop the www
e52fd3925cde274041fab49bc86d52f6e9ded5a7
<ide><path>docs/converting-a-text-mate-theme.md <ide> __Syntax Theme__ dropdown menu to enable your new theme. <ide> <ide> :bulb: Consider using `apm publish` to publish this theme to [atom.io][atomio]. <ide> <del>[atomio]: https://www.atom.io <add>[atomio]: https://atom.io <ide> [CSS]: http://en.wikipedia.org/wiki/Cascading_Style_Sheets <ide> [LESS]: http://lesscss.org <ide> [plist]: http://en.wikipedia.org/wiki/Property_list
1
Python
Python
add large model config
0b2f46fa9e7ceab69ea5f1bbe7e850bbbb26f6cc
<ide><path>tests/test_modeling_t5.py <ide> def __init__( <ide> self.scope = None <ide> self.is_training = is_training <ide> <add> def get_large_model_config(self): <add> return T5Config.from_pretrained("t5-base") <add> <ide> def prepare_config_and_inputs(self): <ide> input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) <ide>
1
Javascript
Javascript
support #each foo in this and #with this as bar
96768564fcd17e36d367a79e9f2eca076a4d37eb
<ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> EmberHandlebars.registerHelper('with', function(context, options) { <ide> // together. When we implement that functionality, we should use it here. <ide> var contextKey = Ember.$.expando + Ember.guidFor(this); <ide> options.data.keywords[contextKey] = this; <del> Ember.bind(options.data.keywords, keywordName, contextKey + '.' + path); <add> <add> // if the path is '' ("this"), just bind directly to the current context <add> var contextPath = path ? contextKey + '.' + path : contextKey; <add> Ember.bind(options.data.keywords, keywordName, contextPath); <ide> } <ide> <ide> return bind.call(this, path, options.fn, true, function(result) { <ide><path>packages/ember-handlebars/lib/helpers/each.js <ide> Ember.Handlebars.registerHelper('each', function(path, options) { <ide> <ide> options = arguments[3]; <ide> path = arguments[2]; <add> if (path === '') { path = "this"; } <ide> <ide> options.hash.keyword = keywordName; <ide> } else { <ide><path>packages/ember-handlebars/tests/helpers/each_test.js <ide> if (Ember.VIEW_PRESERVES_CONTEXT) { <ide> equal(view.$().text(), "My Cool Each Test 1My Cool Each Test 2"); <ide> }); <ide> <add> test("#each accepts 'this' as the right hand side", function() { <add> view = Ember.View.create({ <add> template: templateFor("{{#each item in this}}{{view.title}} {{item.name}}{{/each}}"), <add> title: "My Cool Each Test", <add> controller: Ember.A([{ name: 1 }, { name: 2 }]) <add> }); <add> <add> append(view); <add> <add> equal(view.$().text(), "My Cool Each Test 1My Cool Each Test 2"); <add> }); <add> <ide> } <ide><path>packages/ember-handlebars/tests/helpers/with_test.js <ide> test("it should support #with Foo.bar as qux", function() { <ide> <ide> equal(view.$().text(), "updated", "should update"); <ide> }); <add> <add>module("Handlebars {{#with this as foo}}"); <add> <add>test("it should support #with this as qux", function() { <add> var view = Ember.View.create({ <add> template: Ember.Handlebars.compile("{{#with this as person}}{{person.name}}{{/with}}"), <add> controller: Ember.Object.create({ name: "Los Pivots" }) <add> }); <add> <add> appendView(view); <add> equal(view.$().text(), "Los Pivots", "should be properly scoped"); <add> <add> Ember.run(function() { <add> Ember.setPath(view, 'controller.name', "l'Pivots"); <add> }); <add> <add> equal(view.$().text(), "l'Pivots", "should update"); <add>}); <add>
4
Python
Python
fix runtests.py overriding
bd03c464c3d4b70b6a5d3061f8f015787a0095a4
<ide><path>runtests.py <ide> def main(argv): <ide> site_dir, site_dir_noarch = build_project(args) <ide> sys.path.insert(0, site_dir) <ide> sys.path.insert(0, site_dir_noarch) <del> os.environ['PYTHONPATH'] = site_dir + os.pathsep + site_dir_noarch <add> os.environ['PYTHONPATH'] = \ <add> os.pathsep.join(( <add> site_dir, <add> site_dir_noarch, <add> os.environ.get('PYTHONPATH', '') <add> )) <ide> else: <ide> _temp = __import__(PROJECT_MODULE) <ide> site_dir = os.path.sep.join(_temp.__file__.split(os.path.sep)[:-2]) <ide> def build_project(args): <ide> os.makedirs(site_dir) <ide> if not os.path.exists(site_dir_noarch): <ide> os.makedirs(site_dir_noarch) <del> env['PYTHONPATH'] = site_dir + os.pathsep + site_dir_noarch <add> env['PYTHONPATH'] = \ <add> os.pathsep.join((site_dir, site_dir_noarch, env.get('PYTHONPATH', ''))) <ide> <ide> log_filename = os.path.join(ROOT_DIR, 'build.log') <ide>
1
Javascript
Javascript
remove message from asserts
721f6df7053ae783bd6b1f58d47474df523f2d0c
<ide><path>test/parallel/test-cluster-worker-init.js <ide> if (cluster.isMaster) { <ide> const worker = cluster.fork(); <ide> <ide> worker.on('message', common.mustCall((message) => { <del> assert.strictEqual(message, true, 'did not receive expected message'); <add> assert.strictEqual(message, true); <ide> const w = worker.disconnect(); <del> assert.strictEqual(worker, w, 'did not return a reference'); <add> assert.strictEqual(worker, w); <ide> })); <ide> <ide> worker.on('online', () => {
1
Javascript
Javascript
fix race write() before and after connect()
63431796f4cdeb726cf8a4fe91806702cf09619c
<ide><path>lib/net.js <ide> function afterConnect(status, handle, req, readable, writable) { <ide> handle.readStart(); <ide> } <ide> <del> self.emit('connect'); <del> <ide> if (self._connectQueue) { <ide> debug('Drain the connect queue'); <ide> for (var i = 0; i < self._connectQueue.length; i++) { <ide> function afterConnect(status, handle, req, readable, writable) { <ide> self._connectQueueCleanUp(); <ide> } <ide> <add> self.emit('connect'); <add> <ide> if (self._flags & FLAG_SHUTDOWNQUED) { <ide> // end called before connected - call end now with no data <ide> self._flags &= ~FLAG_SHUTDOWNQUED; <ide><path>test/simple/test-net-write-connect-write.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <add> <add>var received = ''; <add> <add>var server = net.createServer(function(socket) { <add> socket.pipe(socket); <add>}).listen(common.PORT, function() { <add> var conn = net.connect(common.PORT); <add> conn.setEncoding('utf8'); <add> conn.write('before'); <add> conn.on('connect', function() { <add> conn.write('after'); <add> }); <add> conn.on('data', function(buf) { <add> received += buf; <add> conn.end(); <add> }); <add> conn.on('end', function() { <add> server.close(); <add> }); <add>}); <add> <add>process.on('exit', function() { <add> assert.equal(received, 'before' + 'after'); <add>});
2
Text
Text
clarify description for finders keepers
0b700b5f78c0ab170e696027947561e33018d221
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers.english.md <ide> forumTopicId: 16016 <ide> <ide> ## Description <ide> <section id='description'> <del>Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument). If no element passes the test, return undefined. <add> <add> <add>Create a function that looks through an array `arr` and returns the first element in it that passes a 'truth test'. This means that given an element `x`, the 'truth test' is passed if `func(x)` is `true`. If no element passes the test, return `undefined`. <ide> </section> <ide> <ide> ## Instructions
1
Java
Java
update todo for spr-13280
aae0bd2fb43092bd3e1bc5c3296265e760b4fc43
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java <ide> private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) { <ide> <ide> // Consider scoping <ide> ScopedProxyMode proxyMode = ScopedProxyMode.NO; <del> // TODO Determine why type is hard coded to org.springframework.context.annotation.Scope, <add> // TODO [SPR-13280] Determine why type is hard coded to org.springframework.context.annotation.Scope, <ide> // since AnnotationScopeMetadataResolver supports a custom scope annotation type. <ide> AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class); <ide> if (attributes != null) {
1
Javascript
Javascript
remove unnecessary '#'
4f340e6c73032af032d068ebd5bf7cce95d96732
<ide><path>packages/ember-runtime/lib/system/core_object.js <ide> CoreObject.PrototypeMixin = Mixin.create({ <ide> } <ide> }); <ide> teacher = App.Teacher.create() <del> teacher.toString(); // #=> "<App.Teacher:ember1026:Tom Dale>" <add> teacher.toString(); //=> "<App.Teacher:ember1026:Tom Dale>" <ide> <ide> @method toString <ide> @return {String} string representation
1
Mixed
Javascript
fix devtools typos and grammar
21a851e03507e77bf51b410c36e4d32d6e5bf728
<ide><path>packages/react-client/src/__tests__/ReactFlight-test.js <ide> describe('ReactFlight', () => { <ide> }); <ide> <ide> // @gate enableServerContext <del> it('propagates ServerContext and cleansup providers in flight', async () => { <add> it('propagates ServerContext and cleans up the providers in flight', async () => { <ide> const ServerContext = React.createServerContext( <ide> 'ServerContext', <ide> 'default', <ide> describe('ReactFlight', () => { <ide> }); <ide> <ide> // @gate enableServerContext <del> it('takes ServerContext from client for refetching usecases', async () => { <add> it('takes ServerContext from the client for refetching use cases', async () => { <ide> const ServerContext = React.createServerContext( <ide> 'ServerContext', <ide> 'default', <ide><path>packages/react-devtools-core/src/editor.js <ide> function guessEditor(): Array<string> { <ide> } <ide> } <ide> <del> // Last resort, use old skool env vars <add> // Last resort, use old-school env vars <ide> if (process.env.VISUAL) { <ide> return [process.env.VISUAL]; <ide> } else if (process.env.EDITOR) { <ide><path>packages/react-devtools/OVERVIEW.md <ide> The React DevTools extension consists of multiple pieces: <ide> * The **frontend** portion is the extension you see (the Components tree, the Profiler, etc.). <ide> * The **backend** portion is invisible. It runs in the same context as React itself. When React commits changes to e.g. the DOM, the backend is responsible for notifying the frontend by sending a message through the **bridge** (an abstraction around e.g. `postMessage`). <ide> <del>One of the largest performance bottlenecks of the old React DevTools was the amount of bridge traffic. Each time React commits an update, the backend sends every fiber that changed across the bridge, resulting in a lot of (JSON) serialization. The primary goal for the DevTools rewrite was to reduce this traffic. Instead of sending everything across the bridge, **the backend should only send the minimum amount required to render the Components tree**. The frontend can request more information (e.g. an element's props) on demand, only as needed. <add>One of the largest performance bottlenecks of the old React DevTools was the amount of bridge traffic. Each time React commits an update, the backend sends every fiber that changed across the bridge, resulting in a lot of (JSON) serialization. The primary goal for the DevTools rewrite was to reduce this traffic. Instead of sending everything across the bridge, **the backend should only send the minimum amount required to render the Components tree**. The frontend can request more information (e.g. an element's props) on-demand, only as needed. <ide> <ide> The old DevTools also rendered the entire application tree in the form of a large DOM structure of nested nodes. A secondary goal of the rewrite was to avoid rendering unnecessary nodes by using a windowing library (specifically [react-window](https://github.com/bvaughn/react-window)). <ide> <ide> The string table is encoded right after the first two numbers. <ide> <ide> It consists of: <ide> <del>1. the total length of next items that belong to string table <add>1. the total length of the next items that belong to the string table <ide> 2. for each string in a table: <ide> * encoded size <ide> * a list of its UTF encoded codepoints <ide> For example: <ide> <ide> #### Updating tree base duration <ide> <del>While profiling is in progress, we send an extra operation any time a fiber is added or a updated in a way that affects its tree base duration. This information is needed by the Profiler UI in order to render the "snapshot" and "ranked" chart views. <add>While profiling is in progress, we send an extra operation any time a fiber is added or updated in a way that affects its tree base duration. This information is needed by the Profiler UI in order to render the "snapshot" and "ranked" chart views. <ide> <ide> 1. tree base duration constant (`4`) <ide> 1. fiber id <ide> We only send the serialized messages as part of the `inspectElement` event. <ide> <ide> #### Removing a root <ide> <del>Special case of unmounting an entire root (include its descendants). This specialized message replaces what would otherwise be a series of remove-node operations. It is currently only used in one case: updating component filters. The primary motivation for this is actually to preserve fiber ids for components that are re-added to the tree after the updated filters have been applied. This preserves mappings between the Fiber (id) and things like error and warning logs. <add>A special case of unmounting an entire root (including its descendants). This specialized message replaces what would otherwise be a series of remove-node operations. It is currently only used in one case: updating component filters. The primary motivation for this is actually to preserve fiber ids for components that are re-added to the tree after the updated filters have been applied. This preserves mappings between the Fiber (id) and things like error and warning logs. <ide> <ide> ```js <ide> [ <ide> The frontend stores its information about the tree in a map of id to objects wit <ide> <ide> <sup>1</sup> The `depth` value determines how much padding/indentation to use for the element when rendering it in the Components panel. (This preserves the appearance of a nested tree, even though the view is a flat list.) <ide> <del><sup>2</sup> The `weight` of an element is the number of elements (including itself) below it in the tree. We cache this property so that we can quickly determine the total number of Components as well as to find the Nth element within that set. (This enables us to use windowing.) This value needs to be adjusted each time elements are added or removed from the tree, but we amortize this over time to avoid any big performance hits when rendering the tree. <add><sup>2</sup> The `weight` of an element is the number of elements (including itself) below it in the tree. We cache this property so that we can quickly determine the total number of Components as well as find the Nth element within that set. (This enables us to use windowing.) This value needs to be adjusted each time elements are added or removed from the tree, but we amortize this over time to avoid any big performance hits when rendering the tree. <ide> <ide> #### Finding the element at index N <ide> <ide> while (index !== currentWeight) { <ide> <ide> When an element is mounted in the tree, DevTools sends a minimal amount of information about it across the bridge. This information includes its display name, type, and key- but does _not_ include things like props or state. (These values are often expensive to serialize and change frequently, which would add a significant amount of load to the bridge.) <ide> <del>Instead DevTools lazily requests additional information about an element only when it is selected in the "Components" tab. At that point, the frontend requests this information by sending a special "_inspectElement_" message containing the id of the element being inspected. The backend then responds with an "_inspectedElement_" message containing the additional details. <add>Instead, DevTools lazily requests additional information about an element only when it is selected in the "Components" tab. At that point, the frontend requests this information by sending a special "_inspectElement_" message containing the id of the element being inspected. The backend then responds with an "_inspectedElement_" message containing the additional details. <ide> <ide> ### Polling strategy <ide> <del>Elements can update frequently, especially in response to things like scrolling events. Since props and state can be large, we avoid sending this information across the bridge every time the selected element is updated. Instead, the frontend polls the backend for updates about once a second. The backend tracks when the element was last "inspected" and sends a special no-op response if it has not re-rendered since then. <add>Elements can update frequently, especially in response to things like scrolling events. Since props and state can be large, we avoid sending this information across the bridge every time the selected element is updated. Instead, the frontend polls the backend for updates about once a second. The backend tracks when the element was last "inspected" and sends a special no-op response if it has not been re-rendered since then. <ide> <ide> ### Deeply nested properties <ide> <del>Even when dealing with a single component, serializing deeply nested properties can be expensive. Because of this, DevTools uses a technique referred to as "dehydration" to only send a shallow copy of the data on initial inspection. DevTools then fills in the missing data on demand as a user expands nested objects or arrays. Filled in paths are remembered (for the currently inspected element) so they are not "dehydrated" again as part of a polling update. <add>Even when dealing with a single component, serializing deeply nested properties can be expensive. Because of this, DevTools uses a technique referred to as "dehydration" to only send a shallow copy of the data on initial inspection. DevTools then fills in the missing data on-demand as a user expands nested objects or arrays. Filled in paths are remembered (for the currently inspected element) so they are not "dehydrated" again as part of a polling update. <ide> <ide> ### Inspecting hooks <ide> <ide> Hooks present a unique challenge for the DevTools because of the concept of _custom_ hooks. (A custom hook is essentially any function that calls at least one of the built-in hooks. By convention custom hooks also have names that begin with "use".) <ide> <del>So how does DevTools identify custom functions called from within third party components? It does this by temporarily overriding React's built-in hooks and shallow rendering the component in question. Whenever one of the (overridden) built-in hooks are called, it parses the call stack to spot potential custom hooks (functions between the component itself and the built-in hook). This approach enables it to build a tree structure describing all of the calls to both the built-in _and_ custom hooks, along with the values passed to those hooks. (If you're interested in learning more about this, [here is the source code](https://github.com/facebook/react/blob/main/packages/react-debug-tools/src/ReactDebugHooks.js).) <add>So how does DevTools identify custom functions called from within third-party components? It does this by temporarily overriding React's built-in hooks and shallow rendering the component in question. Whenever one of the (overridden) built-in hooks are called, it parses the call stack to spot potential custom hooks (functions between the component itself and the built-in hook). This approach enables it to build a tree structure describing all of the calls to both the built-in _and_ custom hooks, along with the values passed to those hooks. (If you're interested in learning more about this, [here is the source code](https://github.com/facebook/react/blob/main/packages/react-debug-tools/src/ReactDebugHooks.js).) <ide> <ide> > **Note**: DevTools obtains hooks info by re-rendering a component. <ide> > Breakpoints will be invoked during this additional (shallow) render, <ide> To mitigate the performance impact of re-rendering a component, DevTools does th <ide> * Only function components that use _at least one hook_ are rendered. (Props and state can be analyzed without rendering.) <ide> * Rendering is always shallow. <ide> * Rendering is throttled to occur, at most, once per second. <del>* Rendering is skipped if the component has not updated since the last time its properties were inspected. <add>* Rendering is skipped if the component has been not updated since the last time its properties were inspected. <ide> <ide> ## Profiler <ide> <ide> When profiling begins, the backend records the base durations of each fiber curr <ide> * Which elements were rendered during that commit <ide> * Which props and state changed (if enabled in profiler settings) <ide> <del>This information will eventually be required by the frontend in order to render its profiling graphs, but it will not be sent across the bridge until profiling has completed (to minimize the performance impact of profiling). <add>This information will eventually be required by the frontend in order to render its profiling graphs, but it will not be sent across the bridge until profiling has been completed (to minimize the performance impact of profiling). <ide> <ide> ### Timeline profiler <ide> <ide> Timeline profiling data can come from one of two places: <ide> <ide> ### Combining profiling data <ide> <del>Once profiling is finished, the frontend requests profiling data from the backend one renderer at a time by sending a "_getProfilingData_" message. The backend responds with a "_profilingData_" message that contains per-root commit timing and duration information. The frontend then combines this information with its own snapshots to form a complete picture of the profiling session. Using this data, charts and graphs are lazily computed (and incrementally cached) on demand, based on which commits and views are selected in the Profiler UI. <add>Once profiling is finished, the frontend requests profiling data from the backend one renderer at a time by sending a "_getProfilingData_" message. The backend responds with a "_profilingData_" message that contains per-root commit timing and duration information. The frontend then combines this information with its own snapshots to form a complete picture of the profiling session. Using this data, charts and graphs are lazily computed (and incrementally cached) on-demand, based on which commits and views are selected in the Profiler UI. <ide> <ide> ### Importing/exporting data <ide>
3
PHP
PHP
fix redirecttoaction method
bdff3a702892ff84008599a3e4502ed0abbdf62f
<ide><path>src/Illuminate/Routing/ResponseFactory.php <ide> public function redirectToRoute($route, $parameters = array(), $status = 302, $h <ide> */ <ide> public function redirectToAction($action, $parameters = array(), $status = 302, $headers = array()) <ide> { <del> return $this->redirector->action($route, $parameters, $status, $headers); <add> return $this->redirector->action($action, $parameters, $status, $headers); <ide> } <ide> <ide> /**
1
Javascript
Javascript
add head/tail to file
2573dc0b22e4b5841b3bf0c4d317873856eb0ab0
<ide><path>common/app/routes/challenges/redux/reducer.js <ide> import { createPoly } from '../../../../utils/polyvinyl'; <ide> <ide> import types from './types'; <ide> import { BONFIRE, HTML, JS } from '../../../utils/challengeTypes'; <del>import { buildSeed, createTests, getPath } from '../utils'; <add>import { arrayToString, buildSeed, createTests, getPath } from '../utils'; <ide> <ide> const initialState = { <ide> challenge: '', <ide> const filesReducer = handleActions( <ide> ...state, <ide> [path]: createPoly({ <ide> path, <del> contents: buildSeed(challenge) <add> contents: buildSeed(challenge), <add> head: arrayToString(challenge.head), <add> tail: arrayToString(challenge.tail) <ide> }) <ide> }; <ide> } <ide><path>common/app/routes/challenges/utils.js <ide> export function decodeFccfaaAttr(value) { <ide> ); <ide> } <ide> <del>export function arrayToNewLineString(seedData = []) { <add>export function arrayToString(seedData = ['']) { <ide> seedData = Array.isArray(seedData) ? seedData : [seedData]; <ide> return seedData.reduce((seed, line) => '' + seed + line + '\n', '\n'); <ide> } <ide> <ide> export function buildSeed({ challengeSeed = [] } = {}) { <ide> return compose( <ide> decodeSafeTags, <del> arrayToNewLineString <add> arrayToString <ide> )(challengeSeed); <ide> } <ide> <ide><path>common/utils/polyvinyl.js <ide> import invariant from 'invariant'; <ide> // contents: String, <ide> // history?: [...String], <ide> // }) => PolyVinyl, throws <del>export function createPoly({ path, contents, history } = {}) { <add>export function createPoly({ path, contents, history, ...rest } = {}) { <ide> invariant( <ide> typeof path === 'string', <ide> 'path must be a string but got %s', <ide> export function createPoly({ path, contents, history } = {}) { <ide> ); <ide> <ide> return { <add> ...rest, <ide> history: Array.isArray(history) ? history : [ path ], <ide> path: path, <ide> contents: contents,
3
Ruby
Ruby
add `installer` spec
05cb6cda088d740e2cfa204da2ba36a68f503afc
<ide><path>Library/Homebrew/test/cask/artifact/installer_spec.rb <add>describe Hbc::Artifact::Installer, :cask do <add> let(:staged_path) { mktmpdir } <add> let(:cask) { instance_double("Cask", staged_path: staged_path, config: nil) } <add> subject(:installer) { described_class.new(cask, **args) } <add> let(:command) { Hbc::SystemCommand } <add> <add> let(:args) { {} } <add> <add> describe "#install_phase" do <add> context "when given a manual installer" do <add> let(:args) { { manual: "installer" } } <add> <add> it "shows a message prompting to run the installer manually" do <add> expect { <add> installer.install_phase(command: command) <add> }.to output(%r{run the installer at\s+'#{staged_path}/installer'}).to_stdout <add> end <add> end <add> <add> context "when given a script installer" do <add> let(:executable) { staged_path/"executable" } <add> let(:args) { { script: { executable: "executable" } } } <add> <add> before(:each) do <add> FileUtils.touch executable <add> end <add> <add> it "looks for the executable in HOMEBREW_PREFIX" do <add> expect(command).to receive(:run!).with( <add> executable, <add> a_hash_including( <add> env: { "PATH" => PATH.new("#{HOMEBREW_PREFIX}/bin", "#{HOMEBREW_PREFIX}/sbin", ENV["PATH"]) }, <add> ), <add> ) <add> <add> installer.install_phase(command: command) <add> end <add> end <add> end <add>end
1
Javascript
Javascript
fix incorrect substraction
cf8ae64f8a7438ff1f71dce5fc1ff067bc212a22
<ide><path>lib/Template.js <ide> class Template { <ide> return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); <ide> <ide> // upper case <del> n -= DELTA_A_TO_Z; <del> if (n < DELTA_A_TO_Z) <del> return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); <add> if (n < DELTA_A_TO_Z * 2) { <add> return String.fromCharCode( <add> START_UPPERCASE_ALPHABET_CODE + n - DELTA_A_TO_Z <add> ); <add> } <ide> <ide> // use multiple letters <ide> return (
1
PHP
PHP
fix failing test
3ff051f54f7750db43cf76edd158194f20715b71
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testRequestContentTypes() <ide> $this->assertEquals('json', $this->RequestHandler->requestedWith()); <ide> <ide> $this->request->env('REQUEST_METHOD', 'POST'); <del> $this->request->env('CONTENT_TYPE', ''); <del> $this->request->env('HTTP_CONTENT_TYPE', 'application/json'); <add> $this->request->env('CONTENT_TYPE', 'application/json'); <ide> <ide> $result = $this->RequestHandler->requestedWith(['json', 'xml']); <ide> $this->assertEquals('json', $result);
1
PHP
PHP
remove unneded annotations
159c4b0d620cccb4f0b2fc7fdbf7147d13045b36
<ide><path>src/Database/Query.php <ide> public function set($key, $value = null, $types = []) <ide> if (!is_string($types)) { <ide> $types = null; <ide> } <del> /** @psalm-suppress PossiblyInvalidArgument */ <ide> $this->_parts['set']->eq($key, $value, $types); <ide> <ide> return $this; <ide> protected function _conjugate(string $part, $append, $conjunction, array $types) <ide> } <ide> <ide> if ($append instanceof Closure) { <del> /** @psalm-suppress PossiblyInvalidFunctionCall */ <ide> $append = $append($this->newExpr(), $this); <ide> } <ide>
1
Javascript
Javascript
delay unlink in test-regress-gh-4027.js
f1c890afb05274880df0f1ce4084607c03b194bf
<ide><path>test/sequential/test-regress-GH-4027.js <ide> common.refreshTmpDir(); <ide> <ide> const filename = path.join(common.tmpDir, 'watched'); <ide> fs.writeFileSync(filename, 'quis custodiet ipsos custodes'); <del>setTimeout(fs.unlinkSync, 100, filename); <ide> <ide> fs.watchFile(filename, { interval: 50 }, common.mustCall(function(curr, prev) { <ide> assert.strictEqual(prev.nlink, 1); <ide> assert.strictEqual(curr.nlink, 0); <ide> fs.unwatchFile(filename); <ide> })); <add> <add>setTimeout(fs.unlinkSync, common.platformTimeout(300), filename);
1
Ruby
Ruby
add create_fixtures method for tests
5fe543b6294df44d0e7670b78347564874a2f5e2
<ide><path>activerecord/test/cases/helper.rb <ide> class ActiveSupport::TestCase <ide> self.fixture_path = FIXTURES_ROOT <ide> self.use_instantiated_fixtures = false <ide> self.use_transactional_fixtures = true <add> <add> def create_fixtures(*table_names, &block) <add> Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block) <add> end <ide> end
1
Text
Text
create git rm
0ebc2eed5b4de6078d4bc4f6857066ad91df7f1c
<ide><path>guide/english/git/git-rm/index.md <add>--- <add>title: git rm <add>--- <add>## git rm <add> The git rm command removes, or deletes files from a working git tree and git index. See <a href='https://git-scm.com/docs/git-rm' target='_blank' rel='nofollow'>Git documentation</a> for comprehensive details of the git -rm command. <add> The git rm command will remove a file from everywhere within the git tree as there is no option for removing a file from only the working directory. <add> <add> ### git rm --cached -r . <add> The wildcard "." in place of the filename position in the command <strong>git rm --cached -r .</strong> removes all files from the staging area in a recursive fashion, hence the "-r" option. The <strong>--cached</strong> option in essence protects working tree files regardless of whether modifications have been applied. <add> <add> ### git rm -n <add> To determine which files would be affected by the git rm command, place the <strong>-n</strong> option in the command. Executing the command will indicate the files that would be removed had the <strong>-n</strong> option not been present. <add>
1
PHP
PHP
shorten long exception message
8c8ff5fac7d5830f075c00c27a3812dd2a4b4817
<ide><path>laravel/ioc.php <ide> public static function resolve($name, $parameters = array()) <ide> <ide> if ( ! static::registered($name)) <ide> { <del> throw new \OutOfBoundsException("Error resolving [$name]. No resolver has been registered in the container."); <add> throw new \OutOfBoundsException("Error resolving [$name]. No resolver has been registered."); <ide> } <ide> <ide> $object = call_user_func(static::$registry[$name]['resolver'], $parameters); <ide> public static function resolve($name, $parameters = array()) <ide> * loaded since there isn't any reason to load the container <ide> * configuration until the class is first requested. <ide> */ <del>IoC::bootstrap(); <add>IoC::bootstrap(); <ide>\ No newline at end of file
1
Text
Text
add possessive case to react
6b7383072a61dfc3b4bb58a295bf72b8800a59cd
<ide><path>docs/Network.md <ide> permalink: docs/network.html <ide> next: timers <ide> --- <ide> <del>One of React Native goals is to be a playground where we can experiment with different architectures and crazy ideas. Since browsers are not flexible enough, we had no choice but to reimplement the entire stack. In the places that we did not intend to change, we tried to be as faithful as possible to the browser APIs. The networking stack is a great example. <add>One of React Native's goals is to be a playground where we can experiment with different architectures and crazy ideas. Since browsers are not flexible enough, we had no choice but to reimplement the entire stack. In the places that we did not intend to change, we tried to be as faithful as possible to the browser APIs. The networking stack is a great example. <ide> <ide> ## XMLHttpRequest <ide>
1
Javascript
Javascript
upgrade systemplugin to es6
e3d5c681156e76166e265f0e7c5b5d48c3f9c413
<ide><path>lib/dependencies/SystemPlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <del>var ConstDependency = require("./ConstDependency"); <del>var ParserHelpers = require("../ParserHelpers"); <add>"use strict"; <ide> <del>function SystemPlugin(options) { <del> this.options = options; <del>} <del>module.exports = SystemPlugin; <add>const ConstDependency = require("./ConstDependency"); <add>const ParserHelpers = require("../ParserHelpers"); <add> <add>class SystemPlugin { <add> constructor(options) { <add> this.options = options; <add> } <add> <add> apply(compiler) { <add> compiler.plugin("compilation", (compilation, params) => { <add> params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { <add> <add> if(typeof parserOptions.system !== "undefined" && !parserOptions.system) <add> return; <ide> <del>SystemPlugin.prototype.apply = function(compiler) { <del> compiler.plugin("compilation", function(compilation, params) { <del> params.normalModuleFactory.plugin("parser", function(parser, parserOptions) { <del> <del> if(typeof parserOptions.system !== "undefined" && !parserOptions.system) <del> return; <del> <del> function setNotSupported(name) { <del> parser.plugin("evaluate typeof " + name, ParserHelpers.evaluateToString("undefined")); <del> parser.plugin("expression " + name, <del> ParserHelpers.expressionIsUnsupported(name + " is not supported by webpack.") <del> ); <del> } <del> <del> parser.plugin("typeof System", ParserHelpers.toConstantDependency("object")); <del> parser.plugin("evaluate typeof System", ParserHelpers.evaluateToString("object")); <del> <del> parser.plugin("typeof System.import", ParserHelpers.toConstantDependency("function")); <del> parser.plugin("evaluate typeof System.import", ParserHelpers.evaluateToString("function")); <del> <del> setNotSupported("System.set"); <del> setNotSupported("System.get"); <del> setNotSupported("System.register"); <del> parser.plugin("expression System", function(expr) { <del> var dep = new ConstDependency("{}", expr.range); <del> dep.loc = expr.loc; <del> this.state.current.addDependency(dep); <del> return true; <add> function setNotSupported(name) { <add> parser.plugin("evaluate typeof " + name, ParserHelpers.evaluateToString("undefined")); <add> parser.plugin("expression " + name, <add> ParserHelpers.expressionIsUnsupported(name + " is not supported by webpack.") <add> ); <add> } <add> <add> parser.plugin("typeof System", ParserHelpers.toConstantDependency("object")); <add> parser.plugin("evaluate typeof System", ParserHelpers.evaluateToString("object")); <add> <add> parser.plugin("typeof System.import", ParserHelpers.toConstantDependency("function")); <add> parser.plugin("evaluate typeof System.import", ParserHelpers.evaluateToString("function")); <add> <add> setNotSupported("System.set"); <add> setNotSupported("System.get"); <add> setNotSupported("System.register"); <add> parser.plugin("expression System", (expr) => { <add> const dep = new ConstDependency("{}", expr.range); <add> dep.loc = expr.loc; <add> parser.state.current.addDependency(dep); <add> return true; <add> }); <ide> }); <ide> }); <del> }); <del>}; <add> } <add>} <add>module.exports = SystemPlugin;
1
Ruby
Ruby
remove unnecessary require statements
06806f860d12aa5a4cfd077b67cae62071755864
<ide><path>Library/Homebrew/bottles.rb <ide> require "tab" <del>require "os/mac" <ide> require "extend/ARGV" <ide> <ide> def built_as_bottle?(f) <ide><path>Library/Homebrew/extend/ENV/std.rb <ide> require "hardware" <del>require "os/mac" <ide> require "extend/ENV/shared" <ide> <ide> # @deprecated <ide><path>Library/Homebrew/extend/ENV/super.rb <del>require "os/mac" <ide> require "extend/ENV/shared" <ide> <ide> # ### Why `superenv`? <ide><path>Library/Homebrew/utils.rb <ide> require "pathname" <ide> require "exceptions" <del>require "os/mac" <ide> require "utils/json" <ide> require "utils/inreplace" <ide> require "utils/popen"
4