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
initialize tweens immediately
936963e357d7d2e3e5b4f14f935276c4501ea54e
<ide><path>d3.js <ide> function d3_transform_transition(nodes) { <ide> <ide> // Bind the active transition to the node. <ide> function bind(interval) { <del> var s = d3_transform_stack; <ide> for (i = 0; i < m; ++i) { <ide> (o = nodes[i]).node.interval = interval; <ide> } <del> try { <del> d3.time = 0; <del> d3_transform_stack = stack; <del> d3_transform_transition_bind(actions, nodes); <del> } finally { <del> delete d3.time; <del> d3_transform_stack = s; <del> } <add> } <add> <add> // Compute the tween values. <add> try { <add> d3.time = 0; <add> d3_transform_transition_bind(actions, nodes); <add> } finally { <add> delete d3.time; <ide> } <ide> <ide> function tickOne() { <ide><path>d3.min.js <del>if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(D){function z(){}z.prototype=D;return new z}; <del>(function(D){function z(a){return function(f){return 1-a(1-f)}}function O(a){return function(f){return 0.5*(f<0.5?a(2*f):2-a(2-2*f))}}function V(a){return a}function E(a){return function(f){return Math.pow(f,a)}}function W(a){return 1-Math.cos(a*Math.PI/2)}function X(a){return a?Math.pow(2,10*(a-1))-0.0010:0}function Y(a){return 1-Math.sqrt(1-a*a)}function Z(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+0.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+0.9375:7.5625*(a-=2.625/2.75)*a+0.984375} <del>function F(a){var f,d,g,e,b;if(e=/([a-z]+)\((.*)\)/i.exec(a)){b=e[2].split(",");switch(e[1]){case "hsl":return P(parseFloat(b[0]),parseFloat(b[1])/100,parseFloat(b[2])/100);case "rgb":return{r:G(b[0]),g:G(b[1]),b:G(b[2])}}}if(e=v[a])return e;if(a==null)return v.black;if(a.charAt(0)=="#"){if(a.length==4){f=a.charAt(1);f+=f;d=a.charAt(2);d+=d;g=a.charAt(3);g+=g}else if(a.length==7){f=a.substring(1,3);d=a.substring(3,5);g=a.substring(5,7)}f=parseInt(f,16);d=parseInt(d,16);g=parseInt(g,16)}return{r:f, <del>g:d,b:g}}function P(a,f,d){function g(c){if(c>360)c-=360;else if(c<0)c+=360;if(c<60)return e+(b-e)*c/60;if(c<180)return b;if(c<240)return e+(b-e)*(240-c)/60;return e}var e,b;a%=360;if(a<0)a+=360;f=f<0?0:f>1?1:f;d=d<0?0:d>1?1:d;b=d<=0.5?d*(1+f):d+f-d*f;e=2*d-b;return{r:Math.round(g(a+120)*255),g:Math.round(g(a)*255),b:Math.round(g(a-120)*255)}}function G(a){var f=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(f*2.55):f}function Q(){function a(g,e){var b=Object.create(f);b.pop=g;b.data=function(c){var h, <add>if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(C){function z(){}z.prototype=C;return new z}; <add>(function(C){function z(a){return function(f){return 1-a(1-f)}}function O(a){return function(f){return 0.5*(f<0.5?a(2*f):2-a(2-2*f))}}function V(a){return a}function D(a){return function(f){return Math.pow(f,a)}}function W(a){return 1-Math.cos(a*Math.PI/2)}function X(a){return a?Math.pow(2,10*(a-1))-0.0010:0}function Y(a){return 1-Math.sqrt(1-a*a)}function Z(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+0.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+0.9375:7.5625*(a-=2.625/2.75)*a+0.984375} <add>function E(a){var f,d,g,e,b;if(e=/([a-z]+)\((.*)\)/i.exec(a)){b=e[2].split(",");switch(e[1]){case "hsl":return P(parseFloat(b[0]),parseFloat(b[1])/100,parseFloat(b[2])/100);case "rgb":return{r:F(b[0]),g:F(b[1]),b:F(b[2])}}}if(e=v[a])return e;if(a==null)return v.black;if(a.charAt(0)=="#"){if(a.length==4){f=a.charAt(1);f+=f;d=a.charAt(2);d+=d;g=a.charAt(3);g+=g}else if(a.length==7){f=a.substring(1,3);d=a.substring(3,5);g=a.substring(5,7)}f=parseInt(f,16);d=parseInt(d,16);g=parseInt(g,16)}return{r:f, <add>g:d,b:g}}function P(a,f,d){function g(c){if(c>360)c-=360;else if(c<0)c+=360;if(c<60)return e+(b-e)*c/60;if(c<180)return b;if(c<240)return e+(b-e)*(240-c)/60;return e}var e,b;a%=360;if(a<0)a+=360;f=f<0?0:f>1?1:f;d=d<0?0:d>1?1:d;b=d<=0.5?d*(1+f):d+f-d*f;e=2*d-b;return{r:Math.round(g(a+120)*255),g:Math.round(g(a)*255),b:Math.round(g(a-120)*255)}}function F(a){var f=parseFloat(a);return a.charAt(a.length-1)=="%"?Math.round(f*2.55):f}function Q(){function a(g,e){var b=Object.create(f);b.pop=g;b.data=function(c){var h, <ide> i={impl:R,bind:$,value:c,actions:[],enterActions:[],exitActions:[]};e.push(i);h=a(b,i.actions);h.enter=a(b,i.enterActions);h.exit=a(b,i.exitActions);h.key=function(l,n){i.key={name:A.qualify(l),value:n};return h};return h};b.attr=function(c,h){e.push({impl:aa,bind:ba,name:A.qualify(c),value:h});return b};b.style=function(c,h,i){e.push({impl:ca,bind:da,name:c,value:h,priority:arguments.length<3?null:i});return b};b.append=function(c,h){var i={impl:ea,name:A.qualify(c),value:h,actions:[]};e.push(i); <del>return a(b,i.actions)};b.remove=function(c){e.push({impl:fa,selector:c});return b};b.text=function(c){e.push({impl:ga,value:c});return b};b.on=function(c){c={impl:ha,type:c,actions:[]};e.push(c);return a(b,c.actions)};b.bind=function(c,h){e.push({impl:ia,type:c,listener:h});return b};b.filter=function(c){c={impl:S,bind:S,filter:c,actions:[]};e.push(c);return a(b,c.actions)};b.select=function(c){c={impl:H,bind:ja,selector:c,actions:[]};e.push(c);return a(b,c.actions)};b.selectAll=function(c){c={impl:I, <del>bind:ka,selector:c,actions:[]};e.push(c);return a(b,c.actions)};b.transition=function(){var c,h={impl:la,actions:[],endActions:[],ease:k.ease("cubic-in-out"),delay:0,duration:250};e.push(h);c=a(b,h.actions);c.end=a(b,h.endActions);c.ease=function(i){h.ease=typeof i=="string"?k.ease(i):i;return c};c.delay=function(i){h.delay=i;return c};c.duration=function(i){h.duration=i;return c};return c};return b}var f={},d=[];f.select=function(g){g={impl:H,selector:g,actions:[]};d.push(g);return a(f,g.actions)}; <del>f.selectAll=function(g){g={impl:I,selector:g,actions:[]};d.push(g);return a(f,g.actions)};f.apply=function(){j.unshift(null);u(d,[{node:document,index:0}]);j.shift();return f};return f}function u(a,f){var d=a.length,g;for(g=0;g<d;++g)a[g].impl(f,u)}function ea(a,f){var d=a.length,g=this.name,e=[],b,c,h;if(g.local)for(b=0;b<d;++b){e.push(h=Object.create(c=a[b]));h.node=(h.parent=c).node.appendChild(document.createElementNS(g.space,g.local))}else for(b=0;b<d;++b){e.push(h=Object.create(c=a[b]));h.node= <add>return a(b,i.actions)};b.remove=function(c){e.push({impl:fa,selector:c});return b};b.text=function(c){e.push({impl:ga,value:c});return b};b.on=function(c){c={impl:ha,type:c,actions:[]};e.push(c);return a(b,c.actions)};b.bind=function(c,h){e.push({impl:ia,type:c,listener:h});return b};b.filter=function(c){c={impl:S,bind:S,filter:c,actions:[]};e.push(c);return a(b,c.actions)};b.select=function(c){c={impl:G,bind:ja,selector:c,actions:[]};e.push(c);return a(b,c.actions)};b.selectAll=function(c){c={impl:H, <add>bind:ka,selector:c,actions:[]};e.push(c);return a(b,c.actions)};b.transition=function(){var c,h={impl:la,actions:[],endActions:[],ease:k.ease("cubic-in-out"),delay:0,duration:250};e.push(h);c=a(b,h.actions);c.end=a(b,h.endActions);c.ease=function(i){h.ease=typeof i=="string"?k.ease(i):i;return c};c.delay=function(i){h.delay=i;return c};c.duration=function(i){h.duration=i;return c};return c};return b}var f={},d=[];f.select=function(g){g={impl:G,selector:g,actions:[]};d.push(g);return a(f,g.actions)}; <add>f.selectAll=function(g){g={impl:H,selector:g,actions:[]};d.push(g);return a(f,g.actions)};f.apply=function(){j.unshift(null);t(d,[{node:document,index:0}]);j.shift();return f};return f}function t(a,f){var d=a.length,g;for(g=0;g<d;++g)a[g].impl(f,t)}function ea(a,f){var d=a.length,g=this.name,e=[],b,c,h;if(g.local)for(b=0;b<d;++b){e.push(h=Object.create(c=a[b]));h.node=(h.parent=c).node.appendChild(document.createElementNS(g.space,g.local))}else for(b=0;b<d;++b){e.push(h=Object.create(c=a[b]));h.node= <ide> (h.parent=c).node.appendChild(document.createElement(g))}f(this.actions,e)}function aa(a){var f=a.length,d=this.name,g=this.value,e,b,c;if(d.local)if(g==null)for(e=0;e<f;++e)a[e].node.removeAttributeNS(d.space,d.local);else if(typeof g=="function")for(e=0;e<f;++e){j[0]=(b=a[e]).data;c=g.apply(b,j);c==null?b.node.removeAttributeNS(d.space,d.local):b.node.setAttributeNS(d.space,d.local,c)}else for(e=0;e<f;++e)a[e].node.setAttributeNS(d.space,d.local,g);else if(g==null)for(e=0;e<f;++e)a[e].node.removeAttribute(d); <ide> else if(typeof g=="function")for(e=0;e<f;++e){j[0]=(b=a[e]).data;c=g.apply(b,j);c==null?b.node.removeAttribute(d):b.node.setAttribute(d,c)}else for(e=0;e<f;++e)a[e].node.setAttribute(d,g)}function ba(a){var f=a.length,d=this.name,g=this.bound||(this.bound=this.value),e="attr."+(d.local?d.space+":"+d.local:d),b,c;if(g&&g.bind){if(d.local)for(b=0;b<f;++b){(c=a[b]).value=c.node.getAttributeNS(d.space,d.local);c.name=d.space+":"+d.local;j[0]=c.data;c[e]=g.bind.apply(c,j);delete c.value;delete c.name}else for(b= <ide> 0;b<f;++b){(c=a[b]).value=c.node.getAttribute(d);c.name=d;j[0]=c.data;c[e]=g.bind.apply(c,j);delete c.value;delete c.name}this.value=function(){return this[e].apply(this,arguments)}}}function ia(a){function f(i,l){return function(n){var o=j;try{k.event=n;h[0]=l;e.apply(i,j=h)}finally{delete k.event;j=o}}}var d=a.length,g="on"+this.type,e=this.listener,b=0,c,h=j.slice();if(e)for(;b<d;++b){c=a[b];c.node[g]=f(c,c.data)}else for(;b<d;++b)a[b].node[g]=null}function R(a,f){var d=this.value,g=a.length,e, <del>b=this.key,c,h,i,l,n=[],o=[],w=[],p,s,m;if(typeof d=="function"){c=j.shift();d=d.apply(null,j);j.unshift(c)}e=d.length;if(b){c=b.name;h=b.value;p={};s={};m={};if(c.local)for(b=0;b<g;++b){if(l=a[b].node){i=l.getAttributeNS(c.space,c.local);if(i!=null)p[i]=l}}else for(b=0;b<g;++b)if(l=a[b].node){i=l.getAttribute(c);if(i!=null)p[i]=l}for(b=0;b<e;++b){j[0]=c=d[b];i=h.apply(null,j);if(i!=null){s[i]=c;m[i]=b}}for(i in s){c=s[i];b=m[i];(l=p[i])?o.push({node:l,data:c,key:i,index:b}):n.push({node:a.parent.node, <del>data:c,key:i,index:b})}for(i in p)i in s||w.push({node:p[i]})}else{i=e<g?e:g;for(b=0;b<i;++b){(l=a[b]).data=d[b];if(l.node)o.push(l);else{l.node=l.parent.node;n.push(l)}}for(i=b;i<e;++i)n.push({node:a.parent.node,data:d[i],index:i});for(i=b;i<g;++i)w.push(a[i])}f(this.enterActions,n);f(this.actions,o);f(this.exitActions,w)}function $(a,f){var d=a.length,g=this.bound||(this.bound=this.value),e,b,c;if(g&&g.bind){e=[];for(b=0;b<d;++b){j[0]=(c=a[b]).data;c.value=c.data;c.data_=g.bind.apply(c,j);delete c.value}this.value= <del>function(){j.unshift(null);for(b=0;b<d;++b){j[0]=(c=a[b]).data;e[b]=c.data_.apply(c,j)}j.shift();return e}}else R.call(this,a,f)}function fa(a){var f=a.length,d=this.selector,g,e,b,c,h;if(d==null)for(e=0;e<f;++e){h=a[e].node;h.parentNode.removeChild(h)}else for(e=0;e<f;++e){g=a[e].node.querySelectorAll(d);b=0;for(c=g.length;b<c;b++){h=g[b];h.parentNode.removeChild(h)}}}function ha(a){function f(l){return function(n){var o=j;try{j=i;k.event=n;for(c=0;c<g;++c)d[c].impl(l,u)}finally{delete k.event;j= <del>o}}}var d=this.actions,g=d.length,e=a.length,b="on"+this.type,c=0,h,i=j.slice();if(g)for(;c<e;++c){h=a[c];h.node[b]=f([h])}else for(;c<e;++c)a[c].node[b]=null}function S(a,f){var d=[],g=a.length,e=this.filter,b,c;for(b=0;b<g;++b){j[0]=(c=a[b]).data;e.apply(c,j)&&d.push(c)}f(this.actions,d)}function H(a,f){var d=[],g=a.length,e=this.selector,b,c,h,i;for(b=0;b<g;++b){i=(c=a[b]).node.querySelector(e);d.push(h=Object.create(c));h.parent=c;h.node=i}f(this.actions,d)}function ja(a,f){var d=this;H.call(this, <del>a,function(g,e){f(g,e);d.impl=function(b,c){c(g,e)}})}function I(a,f){var d=a.length,g=this.selector,e,b;j.unshift(null);for(e=0;e<d;++e){j[1]=(b=a[e]).data;if(b.node){var c=f,h=this.actions,i=b.node.querySelectorAll(g),l=[],n=0,o=i.length;for(l.parent=b;n<o;n++)l.push({node:i[n],index:n});c(h,l)}}j.shift()}function ka(a,f){var d=a.length,g,e;I.call(this,a,function(b,c){f(b,c.parent.selectAll=c)});this.impl=function(b,c){j.unshift(null);g=0;for(d=b.length;g<d;++g){j[1]=(e=b[g]).data;c(this.actions, <add>b=this.key,c,h,i,l,n=[],o=[],w=[],p,r,m;if(typeof d=="function"){c=j.shift();d=d.apply(null,j);j.unshift(c)}e=d.length;if(b){c=b.name;h=b.value;p={};r={};m={};if(c.local)for(b=0;b<g;++b){if(l=a[b].node){i=l.getAttributeNS(c.space,c.local);if(i!=null)p[i]=l}}else for(b=0;b<g;++b)if(l=a[b].node){i=l.getAttribute(c);if(i!=null)p[i]=l}for(b=0;b<e;++b){j[0]=c=d[b];i=h.apply(null,j);if(i!=null){r[i]=c;m[i]=b}}for(i in r){c=r[i];b=m[i];(l=p[i])?o.push({node:l,data:c,key:i,index:b}):n.push({node:a.parent.node, <add>data:c,key:i,index:b})}for(i in p)i in r||w.push({node:p[i]})}else{i=e<g?e:g;for(b=0;b<i;++b){(l=a[b]).data=d[b];if(l.node)o.push(l);else{l.node=l.parent.node;n.push(l)}}for(i=b;i<e;++i)n.push({node:a.parent.node,data:d[i],index:i});for(i=b;i<g;++i)w.push(a[i])}f(this.enterActions,n);f(this.actions,o);f(this.exitActions,w)}function $(a,f){var d=a.length,g=this.bound||(this.bound=this.value),e,b,c;if(g&&g.bind){e=[];for(b=0;b<d;++b){j[0]=(c=a[b]).data;c.value=c.data;c.data_=g.bind.apply(c,j);delete c.value}this.value= <add>function(){j.unshift(null);for(b=0;b<d;++b){j[0]=(c=a[b]).data;e[b]=c.data_.apply(c,j)}j.shift();return e}}else R.call(this,a,f)}function fa(a){var f=a.length,d=this.selector,g,e,b,c,h;if(d==null)for(e=0;e<f;++e){h=a[e].node;h.parentNode.removeChild(h)}else for(e=0;e<f;++e){g=a[e].node.querySelectorAll(d);b=0;for(c=g.length;b<c;b++){h=g[b];h.parentNode.removeChild(h)}}}function ha(a){function f(l){return function(n){var o=j;try{j=i;k.event=n;for(c=0;c<g;++c)d[c].impl(l,t)}finally{delete k.event;j= <add>o}}}var d=this.actions,g=d.length,e=a.length,b="on"+this.type,c=0,h,i=j.slice();if(g)for(;c<e;++c){h=a[c];h.node[b]=f([h])}else for(;c<e;++c)a[c].node[b]=null}function S(a,f){var d=[],g=a.length,e=this.filter,b,c;for(b=0;b<g;++b){j[0]=(c=a[b]).data;e.apply(c,j)&&d.push(c)}f(this.actions,d)}function G(a,f){var d=[],g=a.length,e=this.selector,b,c,h,i;for(b=0;b<g;++b){i=(c=a[b]).node.querySelector(e);d.push(h=Object.create(c));h.parent=c;h.node=i}f(this.actions,d)}function ja(a,f){var d=this;G.call(this, <add>a,function(g,e){f(g,e);d.impl=function(b,c){c(g,e)}})}function H(a,f){var d=a.length,g=this.selector,e,b;j.unshift(null);for(e=0;e<d;++e){j[1]=(b=a[e]).data;if(b.node){var c=f,h=this.actions,i=b.node.querySelectorAll(g),l=[],n=0,o=i.length;for(l.parent=b;n<o;n++)l.push({node:i[n],index:n});c(h,l)}}j.shift()}function ka(a,f){var d=a.length,g,e;H.call(this,a,function(b,c){f(b,c.parent.selectAll=c)});this.impl=function(b,c){j.unshift(null);g=0;for(d=b.length;g<d;++g){j[1]=(e=b[g]).data;c(this.actions, <ide> e.selectAll)}j.shift()}}function ca(a){var f=a.length,d=this.name,g=this.value,e=this.priority,b,c,h;if(g==null)for(b=0;b<f;++b)a[b].node.style.removeProperty(d);else if(typeof g=="function")for(b=0;b<f;++b){c=a[b];j[0]=c.data;h=g.apply(c,j);h==null?c.node.style.removeProperty(d):c.node.style.setProperty(d,h,e)}else for(b=0;b<f;++b)a[b].node.style.setProperty(d,g,e)}function da(a){var f=a.length,d=this.name,g=this.bound||(this.bound=this.value),e="style."+d,b,c;if(g&&g.bind){for(b=0;b<f;++b){(c=a[b]).value= <ide> c.node.style.getPropertyValue(d);c.name=d;j[0]=c.data;c[e]=g.bind.apply(c,j);delete c.value;delete c.name}this.value=function(){return this[e].apply(this,arguments)}}}function ga(a){var f=a.length,d=this.value,g,e,b;if(typeof d=="function")for(g=0;g<f;++g){e=a[g];j[0]=e.data;b=d.apply(e,j);for(e=e.node;e.lastChild;)e.removeChild(e.lastChild);e.appendChild(document.createTextNode(b))}else for(g=0;g<f;++g){for(e=a[g].node;e.lastChild;)e.removeChild(e.lastChild);e.appendChild(document.createTextNode(d))}} <del>function la(a){function f(x){var q=j;for(m=0;m<s;++m)(r=a[m]).node.interval=x;try{k.time=0;j=B;T(e,a)}finally{delete k.time;j=q}}function d(){var x=j,q=a.filter(function(ma){return ma.node.interval==o}),C=q.length,J=Date.now(),y,U=true;try{j=B;for(m=0;m<C;++m){r=q[m];y=(J-c-r.delay)/l;if(!(y<0)){if(y>1)y=1;else U=false;k.time=n(y);for(t=0;t<w;++t)e[t].impl([r],u);if(y==1){for(t=0;t<p;++t)b[t].impl([r],u);r.delay=Infinity}}}}finally{delete k.time;j=x}U&&clearInterval(o)}function g(){var x=j,q=(Date.now()- <del>c-h)/l,C=a.filter(function(J){return J.node.interval==o});try{j=B;k.time=n(q<0?0:q>1?1:q);for(m=0;m<w;++m)e[m].impl(C,u)}finally{delete k.time;j=x}if(q>=1){clearInterval(o);try{j=B;for(m=0;m<p;++m)b[m].impl(C,u)}finally{j=x}}}var e=this.actions,b=this.endActions,c=Date.now(),h=this.delay,i=Infinity,l=this.duration,n=this.ease,o,w=e.length,p=b.length,s=a.length,m,t,r,K,B=j.slice();if(typeof h=="function"){for(m=0;m<s;++m){j[0]=(r=a[m]).data;K=r.delay=h.apply(r,j);if(K<i)i=K}setTimeout(function(){f(o= <del>setInterval(d,24))},i)}else setTimeout(function(){f(o=setInterval(g,24))},h)}function T(a,f){var d=a.length,g,e;for(e=0;e<d;++e){g=a[e];g.bind&&g.bind(f,T)}}var k=D.d3={};k.version="0.0.0";k.range=function(a,f,d){if(arguments.length==1){f=a;a=0}if(d==null)d=1;if((f-a)/d==Infinity)throw Error("infinite range");var g=[],e=-1,b;if(d<0)for(;(b=a+d*++e)>f;)g.push(b);else for(;(b=a+d*++e)<f;)g.push(b);return g};var A={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink", <add>function la(a){function f(x){for(m=0;m<r;++m)(q=a[m]).node.interval=x}function d(){var x=j,u=a.filter(function(ma){return ma.node.interval==o}),B=u.length,I=Date.now(),y,T=true;try{j=J;for(m=0;m<B;++m){q=u[m];y=(I-c-q.delay)/l;if(!(y<0)){if(y>1)y=1;else T=false;k.time=n(y);for(s=0;s<w;++s)e[s].impl([q],t);if(y==1){for(s=0;s<p;++s)b[s].impl([q],t);q.delay=Infinity}}}}finally{delete k.time;j=x}T&&clearInterval(o)}function g(){var x=j,u=(Date.now()-c-h)/l,B=a.filter(function(I){return I.node.interval== <add>o});try{j=J;k.time=n(u<0?0:u>1?1:u);for(m=0;m<w;++m)e[m].impl(B,t)}finally{delete k.time;j=x}if(u>=1){clearInterval(o);try{j=J;for(m=0;m<p;++m)b[m].impl(B,t)}finally{j=x}}}var e=this.actions,b=this.endActions,c=Date.now(),h=this.delay,i=Infinity,l=this.duration,n=this.ease,o,w=e.length,p=b.length,r=a.length,m,s,q,K,J=j.slice();if(typeof h=="function"){for(m=0;m<r;++m){j[0]=(q=a[m]).data;K=q.delay=h.apply(q,j);if(K<i)i=K}setTimeout(function(){f(o=setInterval(d,24))},i)}else setTimeout(function(){f(o= <add>setInterval(g,24))},h);try{k.time=0;U(e,a)}finally{delete k.time}}function U(a,f){var d=a.length,g,e;for(e=0;e<d;++e){g=a[e];g.bind&&g.bind(f,U)}}var k=C.d3={};k.version="0.0.0";k.range=function(a,f,d){if(arguments.length==1){f=a;a=0}if(d==null)d=1;if((f-a)/d==Infinity)throw Error("infinite range");var g=[],e=-1,b;if(d<0)for(;(b=a+d*++e)>f;)g.push(b);else for(;(b=a+d*++e)<f;)g.push(b);return g};var A={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink", <ide> xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},resolve:function(a){return A.prefix[a]||null},qualify:function(a){var f=a.indexOf(":");return f<0?a:{space:A.prefix[a.substring(0,f)],local:a.substring(f+1)}}};k.dispatch=function(a){var f={};a.on=function(d,g){for(var e=f[d]||(f[d]=[]),b=0;b<e.length;b++)if(e[b].handler==g)return a;e.push({handler:g,on:true});return a};a.off=function(d,g){var e=f[d];if(e)for(var b=0;b<e.length;b++){var c=e[b];if(c.handler==g){c.on= <del>false;e.splice(b,1);break}}return a};a.dispatch=function(d){var g=f[d.type];if(g){g=g.slice();for(var e=0;e<g.length;e++){var b=g[e];b.on&&b.handler.call(a,d)}}};return a};var na=E(2),oa=E(3),pa={linear:function(){return V},poly:E,quad:function(){return na},cubic:function(){return oa},sin:function(){return W},exp:function(){return X},circle:function(){return Y},elastic:function(a,f){var d;if(arguments.length<2)f=0.45;if(arguments.length<1){a=1;d=f/4}else d=f/(2*Math.PI)*Math.asin(1/a);return function(g){return 1+ <add>false;e.splice(b,1);break}}return a};a.dispatch=function(d){var g=f[d.type];if(g){g=g.slice();for(var e=0;e<g.length;e++){var b=g[e];b.on&&b.handler.call(a,d)}}};return a};var na=D(2),oa=D(3),pa={linear:function(){return V},poly:D,quad:function(){return na},cubic:function(){return oa},sin:function(){return W},exp:function(){return X},circle:function(){return Y},elastic:function(a,f){var d;if(arguments.length<2)f=0.45;if(arguments.length<1){a=1;d=f/4}else d=f/(2*Math.PI)*Math.asin(1/a);return function(g){return 1+ <ide> a*Math.pow(2,10*-g)*Math.sin(-(g+d)*2*Math.PI/f)}},back:function(a){a||(a=1.70158);return function(f){return f*f*((a+1)*f-a)}},bounce:function(){return Z}},qa={"in":function(a){return a},out:z,"in-out":O,"out-int":function(a){return O(z(a))}};k.ease=function(a){var f=a.indexOf("-"),d=f>=0?a.substring(0,f):a;f=f>=0?a.substring(f+1):"in";return qa[f](pa[d].apply(null,Array.prototype.slice.call(arguments,1)))};k.interpolate=function(a,f){if(typeof f=="number")return k.interpolateNumber(+a,f);if(typeof f== <ide> "string")return f in v||/^(#|rgb\(|hsl\()/.test(f)?k.interpolateRgb(String(a),f):k.interpolateString(String(a),f);if(f instanceof Array)return k.interpolateArray(a,f);return k.interpolateObject(a,f)};k.interpolateNumber=function(a,f){f-=a;return function(d){return a+f*d}};k.interpolateString=function(a,f){var d,g,e=0,b=[],c=[],h,i;for(g=0;d=L.exec(f);++g){d.index&&b.push(f.substring(e,d.index));c.push({i:b.length,x:d[0]});b.push(null);e=L.lastIndex}e<f.length&&b.push(f.substring(e));g=0;for(h=c.length;(d= <ide> L.exec(a))&&g<h;++g){i=c[g];if(i.x==d[0]){if(i.i)if(b[i.i+1]==null){b[i.i-1]+=i.x;b.splice(i.i,1);for(d=g+1;d<h;++d)c[d].i--}else{b[i.i-1]+=i.x+b[i.i+1];b.splice(i.i,2);for(d=g+1;d<h;++d)c[d].i-=2}else if(b[i.i+1]==null)b[i.i]=i.x;else{b[i.i]=i.x+b[i.i+1];b.splice(i.i+1,1);for(d=g+1;d<h;++d)c[d].i--}c.splice(g,1);h--;g--}else i.x=k.interpolateNumber(parseFloat(d[0]),parseFloat(i.x))}for(;g<h;){i=c.pop();if(b[i.i+1]==null)b[i.i]=i.x;else{b[i.i]=i.x+b[i.i+1];b.splice(i.i+1,1)}h--}if(b.length==1)return b[0]== <del>null?c[0].x:function(){return f};return function(l){for(g=0;g<h;++g)b[(i=c[g]).i]=i.x(l);return b.join("")}};k.interpolateRgb=function(a,f){a=F(a);f=F(f);var d=a.r,g=a.g,e=a.b,b=f.r-d,c=f.g-g,h=f.b-e;return function(i){return"rgb("+Math.round(d+b*i)+","+Math.round(g+c*i)+","+Math.round(e+h*i)+")"}};k.interpolateArray=function(a,f){var d=[],g=[],e=a.length,b=f.length,c=Math.min(a.length,f.length),h;for(h=0;h<c;++h)d.push(k.interpolate(a[h],f[h]));for(;h<e;++h)g[h]=a[h];for(;h<b;++h)g[h]=f[h];return function(i){for(h= <add>null?c[0].x:function(){return f};return function(l){for(g=0;g<h;++g)b[(i=c[g]).i]=i.x(l);return b.join("")}};k.interpolateRgb=function(a,f){a=E(a);f=E(f);var d=a.r,g=a.g,e=a.b,b=f.r-d,c=f.g-g,h=f.b-e;return function(i){return"rgb("+Math.round(d+b*i)+","+Math.round(g+c*i)+","+Math.round(e+h*i)+")"}};k.interpolateArray=function(a,f){var d=[],g=[],e=a.length,b=f.length,c=Math.min(a.length,f.length),h;for(h=0;h<c;++h)d.push(k.interpolate(a[h],f[h]));for(;h<e;++h)g[h]=a[h];for(;h<b;++h)g[h]=f[h];return function(i){for(h= <ide> 0;h<c;++h)g[h]=d[h](i);return g}};k.interpolateObject=function(a,f){var d={},g={},e;for(e in a)if(e in f)d[e]=(e in M||/\bcolor\b/.test(e)?k.interpolateRgb:k.interpolate)(a[e],f[e]);else g[e]=a[e];for(e in f)e in a||(g[e]=f[e]);return function(b){for(e in d)g[e]=d[e](b);return g}};var L=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,M={background:1,fill:1,stroke:1};k.tween=function(a){return{bind:typeof a=="function"?function(){var f=this.value,d=this.name,g=a.apply(this,arguments),e=(d in M|| <ide> /\bcolor\b/.test(d)?k.interpolateRgb:k.interpolate)(f,g);return function(){return e(k.time)}}:function(){var f=this.value,d=this.name,g=(d in M||/\bcolor\b/.test(d)?k.interpolateRgb:k.interpolate)(f,a);return function(){return g(k.time)}}}};var v={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0", <ide> chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1", <ide> darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00", <ide> lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3", <ide> mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9", <ide> peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee", <del>wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},N;for(N in v)v[N]=F(v[N]);k.hsl=function(a,f,d){a=P(a,f,d);return"rgb("+a.r+","+a.g+","+a.b+")"};k.linear=function(){function a(h){return c((h-f)*b)}var f=0,d=1,g=0,e=1,b=1/(d-f),c=k.interpolate(g,e);a.invert=function(h){return(h-g)/b+f};a.domain=function(h){if(!arguments.length)return[f,d];f=h[0];d=h[1];b=1/(d-f);return a};a.range=function(h){if(!arguments.length)return[g,e];g=h[0];e=h[1];c=k.interpolate(g, <add>wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},N;for(N in v)v[N]=E(v[N]);k.hsl=function(a,f,d){a=P(a,f,d);return"rgb("+a.r+","+a.g+","+a.b+")"};k.linear=function(){function a(h){return c((h-f)*b)}var f=0,d=1,g=0,e=1,b=1/(d-f),c=k.interpolate(g,e);a.invert=function(h){return(h-g)/b+f};a.domain=function(h){if(!arguments.length)return[f,d];f=h[0];d=h[1];b=1/(d-f);return a};a.range=function(h){if(!arguments.length)return[g,e];g=h[0];e=h[1];c=k.interpolate(g, <ide> e);return a};return a};k.log=function(){function a(d){return f(Math.log(d))}var f=k.linear();a.invert=function(d){return Math.exp(f.invert(d))};a.domain=function(d){if(!arguments.length)return f.domain().map(Math.exp);f.domain(d.map(Math.log));return a};a.range=function(){var d=f.range.apply(f,arguments);return arguments.length?a:d};return a};k.pow=function(){function a(c){return Math.pow(c,e)}function f(c){return Math.pow(c,b)}function d(c){return g(a(c))}var g=k.linear(),e=1,b=1/e;d.invert=function(c){return f(g.invert(c))}; <ide> d.domain=function(c){if(!arguments.length)return g.domain().map(f);g.domain(c.map(a));return d};d.range=function(){var c=g.range.apply(g,arguments);return arguments.length?d:c};d.exponent=function(c){if(!arguments.length)return e;var h=d.domain();e=c;b=1/c;return d.domain(h)};return d};k.sqrt=function(){return k.pow().exponent(0.5)};k.ordinal=function(){function a(b){b=b in d?d[b]:d[b]=f.push(b)-1;return g[b%g.length]}var f=[],d={},g=[],e=0;a.domain=function(b){if(!arguments.length)return f;f=b;d= <ide> {};for(var c=-1,h=-1,i=f.length;++c<i;){b=f[c];b in d||(d[b]=++h)}return a};a.range=function(b){if(!arguments.length)return g;g=b;return a};a.rangePoints=function(b,c){if(arguments.length<2)c=0;var h=b[0],i=b[1],l=(i-h)/(f.length-1+c);g=f.length==1?[(h+i)/2]:k.range(h+l*c/2,i+l/2,l);e=0;return a};a.rangeBands=function(b,c){if(arguments.length<2)c=0;var h=b[0],i=b[1],l=(i-h)/(f.length+c);g=k.range(h+l*c,i,l);e=l*(1-c);return a};a.rangeBand=function(){return e};return a};var j=[];k.select=function(a){return Q().select(a)}; <ide><path>src/transform_transition.js <ide> function d3_transform_transition(nodes) { <ide> <ide> // Bind the active transition to the node. <ide> function bind(interval) { <del> var s = d3_transform_stack; <ide> for (i = 0; i < m; ++i) { <ide> (o = nodes[i]).node.interval = interval; <ide> } <del> try { <del> d3.time = 0; <del> d3_transform_stack = stack; <del> d3_transform_transition_bind(actions, nodes); <del> } finally { <del> delete d3.time; <del> d3_transform_stack = s; <del> } <add> } <add> <add> // Compute the tween values. <add> try { <add> d3.time = 0; <add> d3_transform_transition_bind(actions, nodes); <add> } finally { <add> delete d3.time; <ide> } <ide> <ide> function tickOne() {
3
Python
Python
add get_user method
72722703110fc66d4919d6779297e3b85f253174
<ide><path>libcloud/common/openstack_identity.py <ide> def get_domain(self, domain_id): <ide> result = self._to_domain(data=response.object['domain']) <ide> return result <ide> <add> def get_user(self, user_id): <add> """ <add> Get a user account by ID. <add> <add> :param user_id: User's id. <add> :type name: ``str`` <add> <add> :return: Located user. <add> :rtype: :class:`.OpenStackIdentityUser` <add> """ <add> response = self.authenticated_request('/v3/users/%s' % user_id) <add> user = self._to_user(data=response.object['user']) <add> return user <add> <ide> def list_user_projects(self, user): <ide> """ <ide> Retrieve all the projects user belongs to. <ide><path>libcloud/test/common/test_openstack_identity.py <ide> def test_get_domain(self): <ide> domain = self.auth_instance.get_domain(domain_id='default') <ide> self.assertEqual(domain.name, 'Default') <ide> <add> def test_get_user(self): <add> user = self.auth_instance.get_user(user_id='a') <add> self.assertEqual(user.id, 'a') <add> self.assertEqual(user.domain_id, 'default') <add> self.assertEqual(user.enabled, True) <add> self.assertEqual(user.email, 'openstack-test@localhost') <add> <ide> def test_create_user(self): <ide> user = self.auth_instance.create_user(email='test2@localhost', password='test1', <ide> name='test2', domain_id='default') <ide> def _v3_users(self, method, url, body, headers): <ide> raise NotImplementedError() <ide> <ide> def _v3_users_a(self, method, url, body, headers): <add> if method == 'GET': <add> # look up a user <add> body = self.fixtures.load('v3_users_a.json') <add> return (httplib.OK, body, self.json_content_headers, httplib.responses[httplib.OK]) <ide> if method == 'PATCH': <ide> # enable / disable user <ide> body = self.fixtures.load('v3_users_a.json')
2
Python
Python
add parent argument
360a702ecdf468bcdc7e14906d09cdfe1860e764
<ide><path>spacy/cli/pretrain.py <ide> def pretrain_cli( <ide> # TODO: What's the solution here? How do we handle optional blocks? <ide> msg.fail("The [pretraining] block in your config is empty", exits=1) <ide> if not output_dir.exists(): <del> output_dir.mkdir() <add> output_dir.mkdir(parents=True) <ide> msg.good(f"Created output directory: {output_dir}") <ide> # Save non-interpolated config <ide> raw_config.to_disk(output_dir / "config.cfg")
1
PHP
PHP
remove pseudo-mock code
2335ef1a13db258a0b4c3fdafe45cae7cfc82708
<ide><path>lib/Cake/Test/Case/Network/CakeRequestTest.php <ide> <ide> class TestCakeRequest extends CakeRequest { <ide> <del> public $input; <del> <ide> public function reConstruct($url = 'some/path', $parseEnvironment = true) { <ide> $this->_base(); <ide> if (empty($url)) { <ide> public function reConstruct($url = 'some/path', $parseEnvironment = true) { <ide> $this->here = $this->base . '/' . $this->url; <ide> } <ide> <del> protected function _readInput() { <del> return $this->input; <del> } <del> <ide> } <ide> <ide> class CakeRequestTest extends CakeTestCase {
1
Javascript
Javascript
fix typo in query param test description
0be28eb608971605ae2f041940ffc2d98a8ffe27
<ide><path>packages/ember/tests/routing/query_params_test.js <ide> QUnit.test('warn user that routes query params configuration must be an Object, <ide> }, 'You passed in `[{"commitBy":{"replace":true}}]` as the value for `queryParams` but `queryParams` cannot be an Array'); <ide> }); <ide> <del>QUnit.test('handle routes names that class with Object.prototype properties', function() { <add>QUnit.test('handle routes names that clash with Object.prototype properties', function() { <ide> expect(1); <ide> <ide> Router.map(function() {
1
Go
Go
fix permissions on add/copy
cfc24769a26e825e4267cbfdd59af807e27508b9
<ide><path>builder/internals.go <ide> func copyAsDirectory(source, destination string) error { <ide> } <ide> <ide> func fixPermissions(source, destination string, uid, gid int) error { <add> // The copied root permission should not be changed for previously existing <add> // directories. <add> s, err := os.Stat(destination) <add> if err != nil && !os.IsNotExist(err) { <add> return err <add> } <add> fixRootPermission := (err != nil) || !s.IsDir() <add> <ide> // We Walk on the source rather than on the destination because we don't <ide> // want to change permissions on things we haven't created or modified. <ide> return filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error { <ide> // Do not alter the walk root itself as it potentially existed before. <del> if source == fullpath { <add> if !fixRootPermission && (source == fullpath) { <ide> return nil <ide> } <ide> // Path is prefixed by source: substitute with destination instead. <ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildStderr(t *testing.T) { <ide> } <ide> logDone("build - testing stderr") <ide> } <add> <add>func TestBuildChownSingleFile(t *testing.T) { <add> name := "testbuildchownsinglefile" <add> defer deleteImages(name) <add> <add> ctx, err := fakeContext(` <add>FROM busybox <add>COPY test / <add>RUN ls -l /test <add>RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ] <add>`, map[string]string{ <add> "test": "test", <add> }) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer ctx.Close() <add> <add> if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil { <add> t.Fatal(err) <add> } <add> <add> if _, err := buildImageFromContext(name, ctx, true); err != nil { <add> t.Fatal(err) <add> } <add> <add> logDone("build - change permission on single file") <add>}
2
Javascript
Javascript
add more punycode tests
10d4bd8266f7983929b57f6394fb5d99d60fa711
<ide><path>test/simple/test-punycode.js <ide> // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <ide> // THE SOFTWARE. <ide> <del>punycode = require('punycode'); <del>assert = require('assert'); <add>var punycode = require('punycode'); <add>var assert = require('assert'); <ide> <ide> assert.equal(punycode.encode('ü'), 'tda'); <ide> assert.equal(punycode.encode('Goethe'), 'Goethe-'); <ide> assert.equal(punycode.decode( <ide> 'Willst du die Blthe des frhen, die Frchte des spteren Jahres-x9e96lkal'), <ide> 'Willst du die Blüthe des frühen, die Früchte des späteren Jahres'); <ide> assert.equal(punycode.decode('wgv71a119e'), '日本語'); <add> <add>// http://tools.ietf.org/html/rfc3492#section-7.1 <add>var tests = { <add> // (A) Arabic (Egyptian) <add> 'egbpdaj6bu4bxfgehfvwxn': <add> '\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644\u0645\u0648' + <add> '\u0634\u0639\u0631\u0628\u064A\u061F', <add> <add> // (B) Chinese (simplified) <add> 'ihqwcrb4cv8a8dqg056pqjye': <add> '\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587', <add> <add> // (C) Chinese (traditional) <add> 'ihqwctvzc91f659drss3x8bo0yb': <add> '\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587', <add> <add> // (D) Czech: Pro<ccaron>prost<ecaron>nemluv<iacute><ccaron>esky <add> 'Proprostnemluvesky-uyb24dma41a': <add> '\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074\u011B\u006E' + <add> '\u0065\u006D\u006C\u0075\u0076\u00ED\u010D\u0065\u0073\u006B\u0079', <add> <add> // (E) Hebrew <add> '4dbcagdahymbxekheh6e0a7fei0b': <add> '\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8\u05DC\u05D0' + <add> '\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2\u05D1\u05E8\u05D9\u05EA', <add> <add> // (F) Hindi (Devanagari) <add> 'i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd': <add> '\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D\u0926\u0940' + <add> '\u0915\u094D\u092F\u094B\u0902\u0928\u0939\u0940\u0902\u092C\u094B' + <add> '\u0932\u0938\u0915\u0924\u0947\u0939\u0948\u0902', <add> <add> // (G) Japanese (kanji and hiragana) <add> 'n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa': <add> '\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092\u8A71\u3057' + <add> '\u3066\u304F\u308C\u306A\u3044\u306E\u304B', <add> <add> // (H) Korean (Hangul syllables) <add> '989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5jpsd879ccm6fea98c': <add> '\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774\uD55C\uAD6D' + <add> '\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74\uC5BC\uB9C8\uB098\uC88B' + <add> '\uC744\uAE4C', <add> <add> // (I) Russian (Cyrillic) <add> /* XXX disabled, fails - possibly a bug in the RFC <add> 'b1abfaaepdrnnbgefbaDotcwatmq2g4l': <add> '\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E\u043D\u0438' + <add> '\u043D\u0435\u0433\u043E\u0432\u043E\u0440\u044F\u0442\u043F\u043E' + <add> '\u0440\u0443\u0441\u0441\u043A\u0438', <add> */ <add> <add> // (J) Spanish: Porqu<eacute>nopuedensimplementehablarenEspa<ntilde>ol <add> 'PorqunopuedensimplementehablarenEspaol-fmd56a': <add> '\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070\u0075\u0065' + <add> '\u0064\u0065\u006E\u0073\u0069\u006D\u0070\u006C\u0065\u006D\u0065' + <add> '\u006E\u0074\u0065\u0068\u0061\u0062\u006C\u0061\u0072\u0065\u006E' + <add> '\u0045\u0073\u0070\u0061\u00F1\u006F\u006C', <add> <add> // (K) Vietnamese: T<adotbelow>isaoh<odotbelow>kh<ocirc>ngth<ecirchookabove>ch<ihookabove>n<oacute>iti<ecircacute>ngVi<ecircdotbelow>t <add> 'TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g': <add> '\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B\u0068\u00F4' + <add> '\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068\u1EC9\u006E\u00F3\u0069' + <add> '\u0074\u0069\u1EBF\u006E\u0067\u0056\u0069\u1EC7\u0074', <add> <add> // (L) 3<nen>B<gumi><kinpachi><sensei> <add> '3B-ww4c5e180e575a65lsy2b': <add> '\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F', <add> <add> // (M) <amuro><namie>-with-SUPER-MONKEYS <add> '-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n': <add> '\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074\u0068\u002D' + <add> '\u0053\u0055\u0050\u0045\u0052\u002D\u004D\u004F\u004E\u004B\u0045' + <add> '\u0059\u0053', <add> <add> // (N) Hello-Another-Way-<sorezore><no><basho> <add> 'Hello-Another-Way--fc4qua05auwb3674vfr0b': <add> '\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F\u0074\u0068' + <add> '\u0065\u0072\u002D\u0057\u0061\u0079\u002D\u305D\u308C\u305E\u308C' + <add> '\u306E\u5834\u6240', <add> <add> // (O) <hitotsu><yane><no><shita>2 <add> '2-u9tlzr9756bt3uc0v': <add> '\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032', <add> <add> // (P) Maji<de>Koi<suru>5<byou><mae> <add> 'MajiKoi5-783gue6qz075azm5e': <add> '\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059\u308B\u0035' + <add> '\u79D2\u524D', <add> <add> // (Q) <pafii>de<runba> <add> 'de-jg4avhby1noc0d': <add> '\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0', <add> <add> // (R) <sono><supiido><de> <add> 'd9juau41awczczp': <add> '\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067', <add> <add> // (S) -> $1.00 <- <add> '-> $1.00 <--': <add> '\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020\u003C\u002D' <add>}; <add> <add>var errors = 0; <add> <add>for (var encoded in tests) { <add> var decoded = tests[encoded]; <add> try { <add> assert.equal(punycode.encode(decoded), encoded); <add> } catch (e) { <add> console.error('FAIL: expected %j, got %j', e.expected, e.actual); <add> errors++; <add> } <add> try { <add> assert.equal(punycode.decode(encoded), decoded); <add> } catch (e) { <add> console.error('FAIL: expected %j, got %j', e.expected, e.actual); <add> errors++; <add> } <add>} <add> <add>assert.equal(errors, 0);
1
PHP
PHP
rewrite the check to work on php < 5.6.0 and hhvm
ef90fbb6f5d0bfd5bc6cfcc469d0221112f361d6
<ide><path>src/Illuminate/Validation/Validator.php <ide> protected function validateNotIn($attribute, $value, $parameters) <ide> */ <ide> protected function validateNoDuplicates($attribute, $value, $parameters) <ide> { <del> $data = array_filter(Arr::dot($this->data), function ($key) use ($attribute, $parameters) { <del> return $key != $attribute && Str::is($parameters[0], $key); <del> }, ARRAY_FILTER_USE_KEY); <add> $data = []; <add> <add> foreach (Arr::dot($this->data) as $key => $val) { <add> if ($key != $attribute && Str::is($parameters[0], $key)) { <add> $data[$key] = $val; <add> } <add> } <ide> <ide> return ! in_array($value, array_values($data)); <ide> }
1
Javascript
Javascript
use different promise check
f270f50caee371c4e9952a7a9547e37b2a084d60
<ide><path>lib/cache/PackFileCacheStrategy.js <ide> class PackContent { <ide> this.logger.time(timeMessage); <ide> } <ide> const value = this.lazy(); <del> if (value && typeof value.then === "function") { <add> if ("then" in value) { <ide> return value.then(data => { <ide> const map = data.map; <ide> if (timeMessage) { <ide> class PackContent { <ide> this.logger.time(timeMessage); <ide> } <ide> const value = this.lazy(); <del> if (value instanceof Promise && typeof value.then === "function") { <add> if ("then" in value) { <ide> return value.then(data => { <ide> if (timeMessage) { <ide> this.logger.timeEnd(timeMessage); <ide> class PackContent { <ide> } <ide> const value = this.lazy(); <ide> this.outdated = false; <del> if (value instanceof Promise && typeof value.then === "function") { <add> if ("then" in value) { <ide> // Move to state B1 <ide> this.lazy = write(() => <ide> value.then(data => {
1
Python
Python
fix gcslistobjectsoperator docstring
c8c4a4272354d090ebf01a5cf7a9f49026e65511
<ide><path>airflow/providers/google/cloud/operators/gcs.py <ide> class GCSListObjectsOperator(BaseOperator): <ide> List all objects from the bucket with the given string prefix and delimiter in name. <ide> <ide> This operator returns a python list with the name of objects which can be used by <del> `xcom` in the downstream task. <add> XCom in the downstream task. <ide> <ide> :param bucket: The Google Cloud Storage bucket to find the objects. (templated) <ide> :param prefix: Prefix string which filters objects whose name begin with
1
Text
Text
add note about case-sensitivity
1829d7120a86c85f440d753a89e5e60d1faea1f0
<ide><path>extra/DEVELOPER_DOCS/ExplosionBot.md <ide> Some things to note: <ide> @explosion-bot please test_gpu --run-on spacy-transformers --run-on-branch master --spacy-branch current_pr <ide> ``` <ide> <del> This will launch the GPU pipeline for the `spacy-transformers` repo on its `master` branch, using the current spaCy PR's branch to build spaCy. <add> This will launch the GPU pipeline for the `spacy-transformers` repo on its `master` branch, using the current spaCy PR's branch to build spaCy. The name of the repository passed to `--run-on` is case-sensitive, e.g: use `spaCy` instead of `spacy`. <ide> <ide> - General info about supported commands. <ide>
1
Python
Python
remove dropout quantization
7988fedfdf4274bb5f056f88678c33d9aac2287f
<ide><path>official/projects/qat/nlp/modeling/layers/mobile_bert_layers.py <ide> def __init__(self, <ide> bias_axes='d', <ide> kernel_initializer=initializer, <ide> name='bottleneck_output/dense') <del> dropout_layer = _output_quantize( <del> tf.keras.layers.Dropout( <del> self.hidden_dropout_prob, <del> name='bottleneck_output/dropout')) <add> dropout_layer = tf.keras.layers.Dropout( <add> self.hidden_dropout_prob, <add> name='bottleneck_output/dropout') <ide> layer_norm = _output_quantize( <ide> _get_norm_layer(self.normalization_type, <ide> name='bottleneck_output/norm')) <ide><path>official/projects/qat/nlp/modeling/layers/transformer_encoder_block.py <ide> def build(self, input_shape): <ide> self._intermediate_activation_layer = _output_quantize( <ide> tf.keras.layers.Activation( <ide> self._inner_activation, dtype=policy)) <del> self._inner_dropout_layer = _output_quantize( <del> tf.keras.layers.Dropout( <del> rate=self._inner_dropout)) <add> self._inner_dropout_layer = tf.keras.layers.Dropout( <add> rate=self._inner_dropout) <ide> self._output_dense = _quantized_einsum_dense( <ide> "abc,cd->abd", <ide> output_shape=(None, hidden_size), <ide> bias_axes="d", <ide> name="output", <ide> kernel_initializer=self._kernel_initializer, <ide> **common_kwargs) <del> self._output_dropout = _output_quantize( <del> tf.keras.layers.Dropout(rate=self._output_dropout)) <add> self._output_dropout = tf.keras.layers.Dropout(rate=self._output_dropout) <ide> # Use float32 in layernorm for numeric stability. <ide> self._output_layer_norm = _output_quantize( <ide> tf.keras.layers.LayerNormalization(
2
Text
Text
fix broken link
3bb0241dee98ead81e350a39e32a35656bd5665d
<ide><path>docs/charts/scatter.md <ide> Namespaces: <ide> * `options.elements.point` - options for all [point elements](../configuration/elements.md#point-configuration) <ide> * `options` - options for the whole chart <ide> <del>The scatter chart supports all of the same properties as the [line chart](./charts/line.md#dataset-properties). <add>The scatter chart supports all of the same properties as the [line chart](./line.md#dataset-properties). <ide> By default, the scatter chart will override the showLine property of the line chart to `false`. <ide> <ide> The index scale is of the type `linear`. This means if you are using the labels array the values have to be numbers or parsable to numbers, the same applies to the object format for the keys.
1
PHP
PHP
add deprecations in console package
b3684742418a92487f8969e41a04ef675cf91104
<ide><path>src/Console/ConsoleIo.php <ide> public function setOutputAs($mode) <ide> */ <ide> public function outputAs($mode) <ide> { <add> deprecationWarning('ConsoleIo::outputAs() is deprecated. Use ConsoleIo::setOutputAs() instead.'); <ide> $this->_out->setOutputAs($mode); <ide> } <ide> <ide><path>src/Console/ConsoleOptionParser.php <ide> public function getCommand() <ide> */ <ide> public function command($text = null) <ide> { <add> deprecationWarning( <add> 'ConsoleOptionParser::command() is deprecated. ' . <add> 'Use ConsoleOptionParser::setCommand()/getCommand() instead.' <add> ); <ide> if ($text !== null) { <ide> return $this->setCommand($text); <ide> } <ide> public function getDescription() <ide> */ <ide> public function description($text = null) <ide> { <add> deprecationWarning( <add> 'ConsoleOptionParser::description() is deprecated. ' . <add> 'Use ConsoleOptionParser::setDescription()/getDescription() instead.' <add> ); <ide> if ($text !== null) { <ide> return $this->setDescription($text); <ide> } <ide> public function getEpilog() <ide> */ <ide> public function epilog($text = null) <ide> { <add> deprecationWarning( <add> 'ConsoleOptionParser::epliog() is deprecated. ' . <add> 'Use ConsoleOptionParser::setEpilog()/getEpilog() instead.' <add> ); <ide> if ($text !== null) { <ide> return $this->setEpilog($text); <ide> } <ide> public function help($subcommand = null, $format = 'text', $width = 72) <ide> */ <ide> public function setHelpAlias($alias) <ide> { <add> deprecationWarning( <add> 'ConsoleOptionParser::setHelpAlias() is deprecated. ' . <add> 'Use ConsoleOptionParser::setRootName() instead.' <add> ); <ide> $this->rootName = $alias; <ide> } <ide> <ide><path>src/Console/ConsoleOutput.php <ide> public function setOutputAs($type) <ide> */ <ide> public function outputAs($type = null) <ide> { <add> deprecationWarning( <add> 'ConsoleOutput::outputAs() is deprecated. ' . <add> 'Use ConsoleOutput::setOutputAs()/getOutputAs() instead.' <add> ); <ide> if ($type === null) { <ide> return $this->_outputAs; <ide> } <ide><path>src/Console/Shell.php <ide> public function setIo(ConsoleIo $io) <ide> */ <ide> public function io(ConsoleIo $io = null) <ide> { <add> deprecationWarning( <add> 'Shell::io() is deprecated. ' . <add> 'Use Shell::setIo()/getIo() instead.' <add> ); <ide> if ($io !== null) { <ide> $this->_io = $io; <ide> } <ide> public function success($message = null, $newlines = 1, $level = Shell::NORMAL) <ide> */ <ide> protected function wrapMessageWithType($messageType, $message) <ide> { <add> deprecationWarning( <add> 'Shell::wrapMessageWithType() is deprecated. ' . <add> 'Use output methods on ConsoleIo instead.' <add> ); <ide> if (is_array($message)) { <ide> foreach ($message as $k => $v) { <ide> $message[$k] = "<$messageType>" . $v . "</$messageType>"; <ide> public function abort($message, $exitCode = self::CODE_ERROR) <ide> */ <ide> public function error($title, $message = null, $exitCode = self::CODE_ERROR) <ide> { <add> deprecationWarning('Shell::error() is deprecated. `Use Shell::abort() instead.'); <ide> $this->_io->err(sprintf('<error>Error:</error> %s', $title)); <ide> <ide> if (!empty($message)) { <ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php <ide> class ConsoleOptionParserTest extends TestCase <ide> { <ide> <add> /** <add> * test setting the console description <add> * <add> * @group deprecated <add> * @return void <add> */ <add> public function testDescriptionDeprecated() <add> { <add> $this->deprecated(function() { <add> $parser = new ConsoleOptionParser('test', false); <add> $result = $parser->description('A test'); <add> <add> $this->assertEquals($parser, $result, 'Setting description is not chainable'); <add> $this->assertEquals('A test', $parser->description(), 'getting value is wrong.'); <add> }); <add> } <add> <ide> /** <ide> * test setting the console description <ide> * <ide> class ConsoleOptionParserTest extends TestCase <ide> public function testDescription() <ide> { <ide> $parser = new ConsoleOptionParser('test', false); <del> $result = $parser->description('A test'); <add> $result = $parser->setDescription('A test'); <ide> <ide> $this->assertEquals($parser, $result, 'Setting description is not chainable'); <del> $this->assertEquals('A test', $parser->description(), 'getting value is wrong.'); <add> $this->assertEquals('A test', $parser->getDescription(), 'getting value is wrong.'); <add> <add> $result = $parser->setDescription(['A test', 'something']); <add> $this->assertEquals("A test\nsomething", $parser->getDescription(), 'getting value is wrong.'); <add> } <add> <add> /** <add> * test setting the console description <add> * <add> * @group deprecated <add> * @return void <add> */ <add> public function testEplilogDeprecated() <add> { <add> $this->deprecated(function() { <add> $parser = new ConsoleOptionParser('test', false); <add> $result = $parser->epilog('A test'); <ide> <del> $result = $parser->description(['A test', 'something']); <del> $this->assertEquals("A test\nsomething", $parser->description(), 'getting value is wrong.'); <add> $this->assertEquals($parser, $result, 'Setting epilog is not chainable'); <add> $this->assertEquals('A test', $parser->epilog(), 'getting value is wrong.'); <add> }); <ide> } <ide> <ide> /** <ide> public function testDescription() <ide> public function testEpilog() <ide> { <ide> $parser = new ConsoleOptionParser('test', false); <del> $result = $parser->epilog('A test'); <add> $result = $parser->setEpilog('A test'); <ide> <ide> $this->assertEquals($parser, $result, 'Setting epilog is not chainable'); <del> $this->assertEquals('A test', $parser->epilog(), 'getting value is wrong.'); <add> $this->assertEquals('A test', $parser->getEpilog(), 'getting value is wrong.'); <ide> <del> $result = $parser->epilog(['A test', 'something']); <del> $this->assertEquals("A test\nsomething", $parser->epilog(), 'getting value is wrong.'); <add> $result = $parser->setEpilog(['A test', 'something']); <add> $this->assertEquals("A test\nsomething", $parser->getEpilog(), 'getting value is wrong.'); <ide> } <ide> <ide> /** <ide> public function testHelpSubcommandHelpArray() <ide> public function testHelpWithRootName() <ide> { <ide> $parser = new ConsoleOptionParser('sample', false); <del> $parser->description('A command!') <add> $parser->setDescription('A command!') <ide> ->setRootName('tool') <ide> ->addOption('test', ['help' => 'A test option.']); <ide> <ide> public function testBuildFromArray() <ide> ]; <ide> $parser = ConsoleOptionParser::buildFromArray($spec); <ide> <del> $this->assertEquals($spec['description'], $parser->description()); <del> $this->assertEquals($spec['epilog'], $parser->epilog()); <add> $this->assertEquals($spec['description'], $parser->getDescription()); <add> $this->assertEquals($spec['epilog'], $parser->getEpilog()); <ide> <ide> $options = $parser->options(); <ide> $this->assertTrue(isset($options['name'])); <ide> public function testCreateFactory() <ide> { <ide> $parser = ConsoleOptionParser::create('factory', false); <ide> $this->assertInstanceOf('Cake\Console\ConsoleOptionParser', $parser); <del> $this->assertEquals('factory', $parser->command()); <add> $this->assertEquals('factory', $parser->getCommand()); <ide> } <ide> <ide> /** <ide> public function testCreateFactory() <ide> public function testCommandInflection() <ide> { <ide> $parser = new ConsoleOptionParser('CommandLine'); <del> $this->assertEquals('command_line', $parser->command()); <add> $this->assertEquals('command_line', $parser->getCommand()); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Console/ConsoleOutputTest.php <ide> public function setUp() <ide> $this->output = $this->getMockBuilder('Cake\Console\ConsoleOutput') <ide> ->setMethods(['_write']) <ide> ->getMock(); <del> $this->output->outputAs(ConsoleOutput::COLOR); <add> $this->output->setOutputAs(ConsoleOutput::COLOR); <ide> } <ide> <ide> /** <ide> public function testFormattingMultipleSameTags() <ide> $this->output->write('<error>Bad</error> <error>Warning</error> Regular', false); <ide> } <ide> <add> /** <add> * test deprecated outputAs <add> * <add> * @group deprecated <add> * @return void <add> */ <add> public function testOutputAsPlain() <add> { <add> $this->deprecated(function() { <add> $this->output->outputAs(ConsoleOutput::PLAIN); <add> $this->assertSame(ConsoleOutput::PLAIN, $this->output->outputAs()); <add> $this->output->expects($this->once())->method('_write') <add> ->with('Bad Regular'); <add> <add> $this->output->write('<error>Bad</error> Regular', false); <add> }); <add> } <add> <ide> /** <ide> * test raw output not getting tags replaced. <ide> * <ide> * @return void <ide> */ <del> public function testOutputAsRaw() <add> public function testSetOutputAsRaw() <ide> { <del> $this->output->outputAs(ConsoleOutput::RAW); <add> $this->output->setOutputAs(ConsoleOutput::RAW); <ide> $this->output->expects($this->once())->method('_write') <ide> ->with('<error>Bad</error> Regular'); <ide> <ide> public function testOutputAsRaw() <ide> * <ide> * @return void <ide> */ <del> public function testOutputAsPlain() <add> public function testSetOutputAsPlain() <ide> { <del> $this->output->outputAs(ConsoleOutput::PLAIN); <add> $this->output->setOutputAs(ConsoleOutput::PLAIN); <ide> $this->output->expects($this->once())->method('_write') <ide> ->with('Bad Regular'); <ide> <ide> public function testOutputAsPlain() <ide> * <ide> * @return void <ide> */ <del> public function testSetOutputAsPlain() <add> public function testSetSetOutputAsPlain() <ide> { <ide> $this->output->setOutputAs(ConsoleOutput::PLAIN); <ide> $this->output->expects($this->once())->method('_write') <ide> public function testSetOutputWrongType() <ide> * <ide> * @return void <ide> */ <del> public function testOutputAsPlainSelectiveTagRemoval() <add> public function testSetOutputAsPlainSelectiveTagRemoval() <ide> { <del> $this->output->outputAs(ConsoleOutput::PLAIN); <add> $this->output->setOutputAs(ConsoleOutput::PLAIN); <ide> $this->output->expects($this->once())->method('_write') <ide> ->with('Bad Regular <b>Left</b> <i>behind</i> <name>'); <ide> <ide><path>tests/TestCase/Console/HelpFormatterTest.php <ide> class HelpFormatterTest extends TestCase <ide> public function testWidthFormatting() <ide> { <ide> $parser = new ConsoleOptionParser('test', false); <del> $parser->description('This is fifteen This is fifteen This is fifteen') <add> $parser->setDescription('This is fifteen This is fifteen This is fifteen') <ide> ->addOption('four', ['help' => 'this is help text this is help text']) <ide> ->addArgument('four', ['help' => 'this is help text this is help text']) <ide> ->addSubcommand('four', ['help' => 'this is help text this is help text']); <ide> public function testHelpWithChoices() <ide> public function testHelpDescriptionAndEpilog() <ide> { <ide> $parser = new ConsoleOptionParser('mycommand', false); <del> $parser->description('Description text') <del> ->epilog('epilog text') <add> $parser->setDescription('Description text') <add> ->setEpilog('epilog text') <ide> ->addOption('test', ['help' => 'A test option.']) <ide> ->addArgument('model', ['help' => 'The model to make.', 'required' => true]); <ide> <ide> public function testXmlHelpWithChoices() <ide> public function testXmlHelpDescriptionAndEpilog() <ide> { <ide> $parser = new ConsoleOptionParser('mycommand', false); <del> $parser->description('Description text') <del> ->epilog('epilog text') <add> $parser->setDescription('Description text') <add> ->setEpilog('epilog text') <ide> ->addOption('test', ['help' => 'A test option.']) <ide> ->addArgument('model', ['help' => 'The model to make.', 'required' => true]); <ide> <ide><path>tests/TestCase/Console/ShellTest.php <ide> public function setUp() <ide> public function testConstruct() <ide> { <ide> $this->assertEquals('ShellTestShell', $this->Shell->name); <del> $this->assertInstanceOf('Cake\Console\ConsoleIo', $this->Shell->io()); <add> $this->assertInstanceOf(ConsoleIo::class, $this->Shell->getIo()); <add> } <add> <add> /** <add> * test io method <add> * <add> * @group deprecated <add> * @return void <add> */ <add> public function testIo() <add> { <add> $this->deprecated(function() { <add> $this->assertInstanceOf(ConsoleIo::class, $this->Shell->io()); <add> <add> $io = $this->getMockBuilder(ConsoleIo::class) <add> ->disableOriginalConstructor() <add> ->getMock(); <add> $this->assertSame($io, $this->Shell->io($io)); <add> $this->assertSame($io, $this->Shell->io()); <add> }); <ide> } <ide> <ide> /** <ide> public function testHr() <ide> /** <ide> * testError <ide> * <add> * @group deprecated <ide> * @return void <ide> */ <ide> public function testError() <ide> public function testError() <ide> ->method('err') <ide> ->with('Searched all...'); <ide> <del> $this->Shell->error('Foo Not Found', 'Searched all...'); <del> $this->assertSame($this->Shell->stopped, 1); <add> $this->deprecated(function() { <add> $this->Shell->error('Foo Not Found', 'Searched all...'); <add> $this->assertSame($this->Shell->stopped, 1); <add> }); <ide> } <ide> <ide> /** <ide> public function testRunCommandBaseClassMethod() <ide> ->setMethods(['startup', 'getOptionParser', 'hr']) <ide> ->disableOriginalConstructor() <ide> ->getMock(); <del> $shell->io( <add> $shell->setIo( <ide> $this->getMockBuilder('Cake\Console\ConsoleIo') <ide> ->setMethods(['err']) <ide> ->getMock() <ide> public function testRunCommandMissingMethod() <ide> ->setMethods(['startup', 'getOptionParser', 'hr']) <ide> ->disableOriginalConstructor() <ide> ->getMock(); <del> $shell->io( <add> $shell->setIo( <ide> $this->getMockBuilder('Cake\Console\ConsoleIo') <ide> ->setMethods(['err']) <ide> ->getMock() <ide> public function testRunCommandTriggeringHelp() <ide> ->setMethods(['getOptionParser', 'out', 'startup', '_welcome']) <ide> ->disableOriginalConstructor() <ide> ->getMock(); <del> $shell->io($this->getMockBuilder('Cake\Console\ConsoleIo')->getMock()); <add> $shell->setIo($this->getMockBuilder('Cake\Console\ConsoleIo')->getMock()); <ide> $shell->expects($this->once())->method('getOptionParser') <ide> ->will($this->returnValue($parser)); <ide> $shell->expects($this->once())->method('out'); <ide> public function testRunCommandNotCallUnexposedTask() <ide> ->setMethods(['startup', 'hasTask']) <ide> ->disableOriginalConstructor() <ide> ->getMock(); <del> $shell->io( <add> $shell->setIo( <ide> $this->getMockBuilder('Cake\Console\ConsoleIo') <ide> ->setMethods(['err']) <ide> ->getMock() <ide> public function testRunCommandHittingTaskInSubcommand() <ide> ->setMethods(['hasTask', 'startup', 'getOptionParser']) <ide> ->disableOriginalConstructor() <ide> ->getMock(); <del> $shell->io($io); <add> $shell->setIo($io); <ide> $task = $this->getMockBuilder('Cake\Console\Shell') <ide> ->setMethods(['main', 'runCommand']) <ide> ->disableOriginalConstructor() <ide> ->getMock(); <del> $task->io($io); <add> $task->setIo($io); <ide> $task->expects($this->once()) <ide> ->method('runCommand') <ide> ->with(['one'], false, ['requested' => true]); <ide> public function testGetOptionParser() <ide> $this->Shell->plugin = 'plugin'; <ide> $parser = $this->Shell->getOptionParser(); <ide> <del> $this->assertEquals('plugin.test', $parser->command()); <add> $this->assertEquals('plugin.test', $parser->getCommand()); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Shell/I18nShellTest.php <ide> public function testInit() <ide> unlink($deDir . 'cake.po'); <ide> } <ide> <del> $this->shell->io()->expects($this->at(0)) <add> $this->shell->getIo()->expects($this->at(0)) <ide> ->method('ask') <ide> ->will($this->returnValue('de_DE')); <del> $this->shell->io()->expects($this->at(1)) <add> $this->shell->getIo()->expects($this->at(1)) <ide> ->method('ask') <ide> ->will($this->returnValue($this->localeDir)); <ide>
9
Python
Python
add missing comma
ffe2c6d558a4d7843a1efed0af5bd0908892ef70
<ide><path>rest_framework/settings.py <ide> ), <ide> 'DEFAULT_PARSERS': ( <ide> 'rest_framework.parsers.JSONParser', <del> 'rest_framework.parsers.FormParser' <add> 'rest_framework.parsers.FormParser', <ide> 'rest_framework.parsers.MultiPartParser' <ide> ), <ide> 'DEFAULT_AUTHENTICATION': (
1
Text
Text
fix typo in esm.md
359a23234892acc6f481f5c90ca27c2435e32a01
<ide><path>doc/api/esm.md <ide> node --experimental-modules my-app.mjs <ide> <ide> Only the CLI argument for the main entry point to the program can be an entry <ide> point into an ESM graph. Dynamic import can also be used with the flag <del>`--harmony-dynamic-import` to create entry points into ESM graphs at run time. <add>`--harmony-dynamic-import` to create entry points into ESM graphs at runtime. <ide> <ide> ### Unsupported <ide>
1
PHP
PHP
fix some errors in view package
081b0b9f6ec59ad8d7838b6e3688f72157f5564a
<ide><path>src/Utility/Text.php <ide> public static function transliterate($string, $transliteratorId = null) <ide> * For e.g. this option can be set to '.' to generate clean file names. <ide> * <ide> * @param string $string the string you want to slug <del> * @param array $options If string it will be use as replacement character <add> * @param array|string $options If string it will be use as replacement character <ide> * or an array of options. <ide> * @return string <ide> */ <ide><path>src/View/Form/ArrayContext.php <ide> public function hasError($field) <ide> return false; <ide> } <ide> <del> return (bool)Hash::check($this->_context['errors'], $field); <add> return Hash::check($this->_context['errors'], $field); <ide> } <ide> <ide> /** <ide><path>src/View/Form/EntityContext.php <ide> protected function _getValidator($parts) <ide> /** <ide> * Get the table instance from a property path <ide> * <del> * @param array $parts Each one of the parts in a path for a field name <add> * @param array|string|\Cake\Datasource\EntityInterface $parts Each one of the parts in a path for a field name <ide> * @param bool $fallback Whether or not to fallback to the last found table <ide> * when a non-existent field/property is being encountered. <ide> * @return \Cake\ORM\Table|bool Table instance or false <ide><path>src/View/Helper/BreadcrumbsHelper.php <ide> public function add($title, $url = null, array $options = []) <ide> /** <ide> * Prepend a crumb to the start of the queue. <ide> * <del> * @param string $title If provided as a string, it represents the title of the crumb. <add> * @param string|array $title If provided as a string, it represents the title of the crumb. <ide> * Alternatively, if you want to add multiple crumbs at once, you can provide an array, with each values being a <ide> * single crumb. Arrays are expected to be of this form: <ide> * - *title* The title of the crumb <ide><path>src/View/Helper/FormHelper.php <ide> public function error($field, $text = null, array $options = []) <ide> if (!$context->hasError($field)) { <ide> return ''; <ide> } <del> $error = (array)$context->error($field); <add> $error = $context->error($field); <ide> <ide> if (is_array($text)) { <ide> $tmp = []; <ide> protected function _extractOption($name, $options, $default = null) <ide> * used instead of the generated values if present. <ide> * <ide> * @param string $fieldName The name of the field to generate label for. <del> * @param string $label Label text. <add> * @param string|array $label Label text or array with label attributes. <ide> * @param array $options Options for the label element. <ide> * @return string Generated label element <ide> */ <ide><path>src/View/Helper/HtmlHelper.php <ide> public function div($class = null, $text = null, array $options = []) <ide> * - `escape` Whether or not the contents should be html_entity escaped. <ide> * <ide> * @param string $class CSS class name of the p element. <del> * @param string $text String content that will appear inside the p element. <add> * @param string|null $text String content that will appear inside the p element. <ide> * @param array $options Additional HTML attributes of the P tag <ide> * @return string The formatted P element <ide> */ <ide> public function para($class, $text, array $options = []) <ide> { <del> if (isset($options['escape'])) { <add> if (!empty($options['escape'])) { <ide> $text = h($text); <ide> } <ide> if ($class && !empty($class)) { <ide><path>src/View/Helper/PaginatorHelper.php <ide> public function next($title = 'Next >>', array $options = []) <ide> * - `lock` Lock direction. Will only use the default direction then, defaults to false. <ide> * <ide> * @param string $key The name of the key that the recordset should be sorted. <del> * @param string|null $title Title for the link. If $title is null $key will be used <add> * @param string|array|null $title Title for the link. If $title is null $key will be used <ide> * for the title and will be generated by inflection. <ide> * @param array $options Options for sorting link. See above for list of keys. <ide> * @return string A link sorting default by 'asc'. If the resultset is sorted 'asc' by the specified <ide> public function hasPage($model = null, $page = 1) <ide> * Does $model have $page in its range? <ide> * <ide> * @param string $model Model name to get parameters for. <del> * @param int $page Page number you are checking. <del> * @return bool Whether model has $page <add> * @param string $dir Direction <add> * @return bool Whether model has $dir <ide> */ <del> protected function _hasPage($model, $page) <add> protected function _hasPage($model, $dir) <ide> { <ide> $params = $this->params($model); <ide> <del> return !empty($params) && $params[$page . 'Page']; <add> return !empty($params) && $params[$dir . 'Page']; <ide> } <ide> <ide> /** <ide> public function numbers(array $options = []) <ide> ]; <ide> $options += $defaults; <ide> <del> $params = (array)$this->params($options['model']) + ['page' => 1]; <add> $params = $this->params($options['model']) + ['page' => 1]; <ide> if ($params['pageCount'] <= 1) { <ide> return false; <ide> } <ide><path>src/View/Helper/RssHelper.php <ide> public function item($att = [], $elements = []) <ide> $content = implode('', $elements); <ide> } <ide> <del> return $this->elem('item', (array)$att, $content, !($content === null)); <add> return $this->elem('item', $att, $content, !($content === null)); <ide> } <ide> <ide> /** <ide><path>src/View/SerializedView.php <ide> public function loadHelpers() <ide> * <ide> * @param array|string $serialize The name(s) of the view variable(s) that <ide> * need(s) to be serialized <del> * @return string The serialized data <add> * @return string|false The serialized data or false. <ide> */ <ide> abstract protected function _serialize($serialize); <ide> <ide> abstract protected function _serialize($serialize); <ide> * names. If true all view variables will be serialized. If unset normal <ide> * view template will be rendered. <ide> * <del> * @param string|bool|null $view The view being rendered. <add> * @param string|false|null $view The view being rendered. <ide> * @param string|null $layout The layout being rendered. <ide> * @return string|null The rendered view. <ide> */ <ide> public function render($view = null, $layout = null) <ide> throw new RuntimeException('Serialization of View data failed.'); <ide> } <ide> <del> return (string)$result; <add> return $result; <ide> } <ide> if ($view !== false && $this->_getViewFileName($view)) { <ide> return parent::render($view, false); <ide><path>src/View/View.php <ide> class View implements EventDispatcherInterface <ide> * is the filename of the layout in /src/Template/Layout without the .ctp <ide> * extension. <ide> * <del> * @var string <add> * @var string|false <ide> */ <ide> public $layout = 'default'; <ide> <ide> public function isAutoLayoutEnabled() <ide> */ <ide> public function enableAutoLayout($enable = true) <ide> { <del> $this->autoLayout = (bool)$enable; <add> $this->autoLayout = $enable; <ide> <ide> return $this; <ide> } <ide> public function elementExists($name) <ide> * the template will be located along the regular view path cascade. <ide> * <ide> * @param string|false|null $view Name of view file to use <del> * @param string|null $layout Layout to use. <add> * @param string|null|false $layout Layout to use. False to disable. <ide> * @return string|null Rendered content or null if content already rendered and returned earlier. <ide> * @throws \Cake\Core\Exception\Exception If there is an error in the view. <ide> * @triggers View.beforeRender $this, [$viewFileName] <ide><path>src/View/XmlView.php <ide> class XmlView extends SerializedView <ide> * `_xmlOptions` You can set an array of custom options for Xml::fromArray() this way, e.g. <ide> * 'format' as 'attributes' instead of 'tags'. <ide> * <del> * @param array|string $serialize The name(s) of the view variable(s) that need(s) to be serialized <add> * @param array|string|true $serialize The name(s) of the view variable(s) that need(s) to be serialized <ide> * @return string The serialized data <ide> */ <ide> protected function _serialize($serialize)
11
Javascript
Javascript
use nested module api
00049b9863f5558a99e663432a27e4d4ffb43d14
<ide><path>tests/node/template-compiler-test.js <ide> var test = QUnit.test; <ide> <ide> var templateCompiler; <ide> <del>module('ember-template-compiler.js', { <del> beforeEach: function() { <add>module('ember-template-compiler.js', function(hooks) { <add> hooks.beforeEach(function() { <ide> templateCompiler = require(templateCompilerPath); <del> }, <add> }); <ide> <del> afterEach: function() { <add> hooks.afterEach(function() { <ide> // clear the previously cached version of this module <ide> delete require.cache[templateCompilerPath + '.js']; <del> }, <del>}); <del> <del>test('can be required', function(assert) { <del> assert.strictEqual( <del> typeof templateCompiler.precompile, <del> 'function', <del> 'precompile function is present' <del> ); <del> assert.strictEqual(typeof templateCompiler.compile, 'function', 'compile function is present'); <del>}); <del> <del>test('can access _Ember.ENV (private API used by ember-cli-htmlbars)', function(assert) { <del> assert.equal(typeof templateCompiler._Ember.ENV, 'object', '_Ember.ENV is present'); <del> assert.notEqual(typeof templateCompiler._Ember.ENV, null, '_Ember.ENV is not null'); <del>}); <del> <del>test('can access _Ember.FEATURES (private API used by ember-cli-htmlbars)', function(assert) { <del> assert.equal(typeof templateCompiler._Ember.FEATURES, 'object', '_Ember.FEATURES is present'); <del> assert.notEqual(typeof templateCompiler._Ember.FEATURES, null, '_Ember.FEATURES is not null'); <del>}); <del> <del>test('can access _Ember.VERSION (private API used by ember-cli-htmlbars)', function(assert) { <del> assert.equal(typeof templateCompiler._Ember.VERSION, 'string', '_Ember.VERSION is present'); <del>}); <del> <del>test('can generate a template with a server side generated `id`', function(assert) { <del> var TemplateJSON = JSON.parse(templateCompiler.precompile('<div>simple text</div>')); <del> <del> assert.ok(TemplateJSON.id, 'an `id` was generated'); <add> }); <add> <add> test('can be required', function(assert) { <add> assert.strictEqual( <add> typeof templateCompiler.precompile, <add> 'function', <add> 'precompile function is present' <add> ); <add> assert.strictEqual(typeof templateCompiler.compile, 'function', 'compile function is present'); <add> }); <add> <add> test('can access _Ember.ENV (private API used by ember-cli-htmlbars)', function(assert) { <add> assert.equal(typeof templateCompiler._Ember.ENV, 'object', '_Ember.ENV is present'); <add> assert.notEqual(typeof templateCompiler._Ember.ENV, null, '_Ember.ENV is not null'); <add> }); <add> <add> test('can access _Ember.FEATURES (private API used by ember-cli-htmlbars)', function(assert) { <add> assert.equal(typeof templateCompiler._Ember.FEATURES, 'object', '_Ember.FEATURES is present'); <add> assert.notEqual(typeof templateCompiler._Ember.FEATURES, null, '_Ember.FEATURES is not null'); <add> }); <add> <add> test('can access _Ember.VERSION (private API used by ember-cli-htmlbars)', function(assert) { <add> assert.equal(typeof templateCompiler._Ember.VERSION, 'string', '_Ember.VERSION is present'); <add> }); <add> <add> test('can generate a template with a server side generated `id`', function(assert) { <add> var TemplateJSON = JSON.parse(templateCompiler.precompile('<div>simple text</div>')); <add> <add> assert.ok(TemplateJSON.id, 'an `id` was generated'); <add> }); <ide> });
1
Ruby
Ruby
expand coverage of json gem tests
a6b2ace016202fd38e121f5e7075c842e3e61aa3
<ide><path>activesupport/test/core_ext/object/json_gem_encoding_test.rb <ide> class JsonGemEncodingTest < ActiveSupport::TestCase <ide> <ide> JSONTest::EncodingTestCases.constants.each_with_index do |name| <ide> JSONTest::EncodingTestCases.const_get(name).each_with_index do |(subject, _), i| <del> test("test #{name[0..-6].underscore} #{i}") do <del> begin <del> expected = JSON.generate(subject, quirks_mode: true) <del> rescue JSON::GeneratorError => e <del> exception = e <del> end <del> <del> require_or_skip 'active_support/core_ext/object/json' <del> <del> if exception <del> assert_raises_with_message JSON::GeneratorError, e.message do <del> JSON.generate(subject, quirks_mode: true) <del> end <del> else <del> assert_equal expected, JSON.generate(subject, quirks_mode: true) <del> end <add> test("#{name[0..-6].underscore} #{i}") do <add> assert_same_with_or_without_active_support(subject) <ide> end <ide> end <ide> end <ide> <add> class CustomToJson <add> def to_json(*) <add> '"custom"' <add> end <add> end <add> <add> test "custom to_json" do <add> assert_same_with_or_without_active_support(CustomToJson.new) <add> end <add> <ide> private <ide> def require_or_skip(file) <ide> require(file) || skip("'#{file}' was already loaded") <ide> end <ide> <add> def assert_same_with_or_without_active_support(subject) <add> begin <add> expected = JSON.generate(subject, quirks_mode: true) <add> rescue JSON::GeneratorError => e <add> exception = e <add> end <add> <add> require_or_skip 'active_support/core_ext/object/json' <add> <add> if exception <add> assert_raises_with_message JSON::GeneratorError, e.message do <add> JSON.generate(subject, quirks_mode: true) <add> end <add> else <add> assert_equal expected, JSON.generate(subject, quirks_mode: true) <add> end <add> end <add> <ide> def assert_raises_with_message(exception_class, message, &block) <ide> err = assert_raises(exception_class) { block.call } <ide> assert_match message, err.message
1
Text
Text
remove unnecessary model_type arg in example
492b352ab667d9765d1078ee5dc4466ba260a241
<ide><path>examples/text-classification/README.md <ide> export GLUE_DIR=/path/to/glue <ide> export TASK_NAME=MRPC <ide> <ide> python run_glue.py \ <del> --model_type bert \ <ide> --model_name_or_path bert-base-cased \ <ide> --task_name $TASK_NAME \ <ide> --do_train \
1
Text
Text
add versions documentation
bc0aa4e64ce4eaf53476aa448b71b711feb9939e
<ide><path>docs/Formula-Cookbook.md <ide> A formula is a package definition written in Ruby. It can be created with `brew <ide> | **Keg** | The installation prefix of a **Formula** | `/usr/local/Cellar/foo/0.1` | <ide> | **opt prefix** | A symlink to the active version of a **Keg** | `/usr/local/opt/foo ` | <ide> | **Cellar** | All **Kegs** are installed here | `/usr/local/Cellar` | <del>| **Tap** | An Git repository of **Formulae** and/or commands | `/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core` | <add>| **Tap** | A Git repository of **Formulae** and/or commands | `/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core` | <ide> | **Bottle** | Pre-built **Keg** used instead of building from source | `qt-4.8.4.mavericks.bottle.tar.gz` | <ide> | **Cask** | An [extension of homebrew](https://github.com/caskroom/homebrew-cask) to install macOS native apps | `/Applications/MacDown.app/Contents/SharedSupport/bin/macdown` | <ide> | **Brew Bundle**| An [extension of homebrew](https://github.com/Homebrew/homebrew-bundle) to describe dependencies | `brew 'myservice', restart_service: true` | <ide><path>docs/Tips-N'-Tricks.md <ide> <ide> ## Installing previous versions of formulae <ide> <del>The preferred and supported method of installing specific versions of <del>formulae is to use formula like e.g. `gcc@6`. If the version you’re looking for isn’t available, consider [opening a <add>The supported method of installing specific versions of <add>some formulae is to see if there is a versions formula like e.g. `gcc@6` available. If the version you’re looking for isn’t available, consider [opening a <ide> pull request](https://github.com/Homebrew/brew/blob/master/docs/How-To-Open-a-Homebrew-Pull-Request-(and-get-it-merged).md)! <ide> <ide> ### Installing directly from pull-requests <ide><path>docs/Versions.md <add># Versions <add>Now that [Homebrew/versions](https://github.com/homebrew/homebrew-versions) has been deprecated [Homebrew/core](https://github.com/homebrew/homebrew-core) supports multiple versions of formulae with a new naming format. <add> <add>In [Homebrew/versions](https://github.com/homebrew/homebrew-versions) the formula for GCC 6 was named `gcc6.rb` and began `class Gcc6 < Formula`. In [Homebrew/core](https://github.com/homebrew/homebrew-core) this same formula is named `gcc@6.rb` and begins `class GccAT6 < Formula`. <add> <add>## Acceptable Versioned Formulae <add>Homebrew's versions are not intended to be used for any old versions you personally require for your project; formulae submitted should be expected to be used by a large number of people and still supported by their upstream projects. <add> <add>Versioned formulae we include must meet the following standards: <add> <add>* Versioned formulae should differ in major/minor (not patch) versions from the current stable release. This is because patch versions indicate bug or security updates and we want to ensure you apply security updates. <add>* Formulae that depend on versioned formulae must not depend on the same formulae at two different versions twice in their recursive dependencies. For example, if you depend on `openssl@1.0` and `foo`, and `foo` depends on `openssl` then you must instead use `openssl`. <add>* Versioned formulae should strive to be linked at the same time as their non-versioned counterpart (without patching). If this is not possible, favour either `conflicts_with` or `keg_only` depending on whether users expect to have multiple versions installed at once or not. <add> <add>You should create your own [tap](https://github.com/Homebrew/brew/blob/master/docs/How-to-Create-and-Maintain-a-Tap.md) for formulae you or your organisation wishes to control the versioning of or those that do not meet the above standards.
3
Python
Python
fix unauthorized access exception for solusvm
6092330debb3cf7e4c8063c33bcee93af23685cf
<ide><path>libcloud/common/solusvm.py <ide> def success(self): <ide> return self.status in [httplib.OK, httplib.CREATED, httplib.NO_CONTENT] <ide> <ide> def parse_error(self): <del> <ide> if self.status == httplib.UNAUTHORIZED: <ide> body = self.parse_body() <del> error = body.get('errors', {}).get('base') <add> error = body.get('errors', {}) <ide> if error and isinstance(error, list): <ide> error = error[0] <ide> raise InvalidCredsError(error) <ide><path>libcloud/compute/drivers/solusvm.py <ide> def create_node(self, vttype='openvz', user_id=31, nodegroup_id=1, <ide> return new_node <ide> time.sleep(10) <ide> <del> <ide> def ex_start_node(self, node): <ide> """ <ide> Start a node
2
Javascript
Javascript
handle opacity in the tooltip update method
0fa03fad24040d83b713727f2158919f223387b4
<ide><path>src/core/core.tooltip.js <ide> <ide> var ctx = this._chart.ctx; <ide> <del> var element = this._active[0], <del> labelColors = [], <del> tooltipPosition; <del> <del> var tooltipItems = []; <del> <del> if (this._options.tooltips.mode == 'single') { <del> var yScale = element._yScale || element._scale; // handle radar || polarArea charts <del> tooltipItems.push({ <del> xLabel: element._xScale ? element._xScale.getLabelForIndex(element._index, element._datasetIndex) : '', <del> yLabel: yScale ? yScale.getLabelForIndex(element._index, element._datasetIndex) : '', <del> index: element._index, <del> datasetIndex: element._datasetIndex, <del> }); <del> tooltipPosition = this._active[0].tooltipPosition(); <del> } else { <del> helpers.each(this._data.datasets, function(dataset, datasetIndex) { <del> if (!helpers.isDatasetVisible(dataset)) { <del> return; <del> } <del> var currentElement = dataset.metaData[element._index]; <del> var yScale = element._yScale || element._scale; // handle radar || polarArea charts <add> if(this._active.length){ <add> this._model.opacity = 1; <add> <add> var element = this._active[0], <add> labelColors = [], <add> tooltipPosition; <add> <add> var tooltipItems = []; <ide> <add> if (this._options.tooltips.mode == 'single') { <add> var yScale = element._yScale || element._scale; // handle radar || polarArea charts <ide> tooltipItems.push({ <del> xLabel: currentElement._xScale ? currentElement._xScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', <del> yLabel: yScale ? yScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', <add> xLabel: element._xScale ? element._xScale.getLabelForIndex(element._index, element._datasetIndex) : '', <add> yLabel: yScale ? yScale.getLabelForIndex(element._index, element._datasetIndex) : '', <ide> index: element._index, <del> datasetIndex: datasetIndex, <add> datasetIndex: element._datasetIndex, <ide> }); <del> }); <del> <del> helpers.each(this._active, function(active, i) { <del> labelColors.push({ <del> borderColor: active._view.borderColor, <del> backgroundColor: active._view.backgroundColor <add> tooltipPosition = this._active[0].tooltipPosition(); <add> } else { <add> helpers.each(this._data.datasets, function(dataset, datasetIndex) { <add> if (!helpers.isDatasetVisible(dataset)) { <add> return; <add> } <add> var currentElement = dataset.metaData[element._index]; <add> var yScale = element._yScale || element._scale; // handle radar || polarArea charts <add> <add> tooltipItems.push({ <add> xLabel: currentElement._xScale ? currentElement._xScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', <add> yLabel: yScale ? yScale.getLabelForIndex(currentElement._index, currentElement._datasetIndex) : '', <add> index: element._index, <add> datasetIndex: datasetIndex, <add> }); <ide> }); <del> }, this); <ide> <del> tooltipPosition = this._active[0].tooltipPosition(); <del> tooltipPosition.y = this._active[0]._yScale.getPixelForDecimal(0.5); <del> } <add> helpers.each(this._active, function(active, i) { <add> labelColors.push({ <add> borderColor: active._view.borderColor, <add> backgroundColor: active._view.backgroundColor <add> }); <add> }, this); <ide> <del> // Build the Text Lines <del> helpers.extend(this._model, { <del> title: this.getTitle(tooltipItems, this._data), <del> beforeBody: this.getBeforeBody(tooltipItems, this._data), <del> body: this.getBody(tooltipItems, this._data), <del> afterBody: this.getAfterBody(tooltipItems, this._data), <del> footer: this.getFooter(tooltipItems, this._data), <del> }); <add> tooltipPosition = this._active[0].tooltipPosition(); <add> tooltipPosition.y = this._active[0]._yScale.getPixelForDecimal(0.5); <add> } <ide> <del> helpers.extend(this._model, { <del> x: Math.round(tooltipPosition.x), <del> y: Math.round(tooltipPosition.y), <del> caretPadding: tooltipPosition.padding, <del> labelColors: labelColors, <del> }); <add> // Build the Text Lines <add> helpers.extend(this._model, { <add> title: this.getTitle(tooltipItems, this._data), <add> beforeBody: this.getBeforeBody(tooltipItems, this._data), <add> body: this.getBody(tooltipItems, this._data), <add> afterBody: this.getAfterBody(tooltipItems, this._data), <add> footer: this.getFooter(tooltipItems, this._data), <add> }); <add> <add> helpers.extend(this._model, { <add> x: Math.round(tooltipPosition.x), <add> y: Math.round(tooltipPosition.y), <add> caretPadding: tooltipPosition.padding, <add> labelColors: labelColors, <add> }); <add> } <add> else{ <add> this._model.opacity = 0; <add> } <ide> <ide> if (this._options.tooltips.custom) { <ide> this._options.tooltips.custom.call(this, this._model);
1
Text
Text
add missing word in instructions - step 31
73e3565707e49543ff035c9311fa2abfde7b5b55
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-forms-by-building-a-registration-form/step-031.md <ide> The dropdown options are currently empty. To give them content, add the followin <ide> ```md <ide> (select one) <ide> freeCodeCamp News <del>freeCodeCamp YouTube <add>freeCodeCamp YouTube Channel <ide> freeCodeCamp Forum <ide> Other <ide> ```
1
Python
Python
preserve the request context in debug mode
7b5015010bc8c2a2d56c7c50b37e5b9facdad102
<ide><path>flask.py <ide> import sys <ide> <ide> from threading import local <del>from contextlib import contextmanager <ide> from jinja2 import Environment, PackageLoader, FileSystemLoader <ide> from werkzeug import Request as RequestBase, Response as ResponseBase, \ <ide> LocalStack, LocalProxy, create_environ, cached_property, \ <ide> def __init__(self, app, environ): <ide> self.g = _RequestGlobals() <ide> self.flashes = None <ide> <add> def __enter__(self): <add> _request_ctx_stack.push(self) <add> <add> def __exit__(self, exc_type, exc_value, tb): <add> # do not pop the request stack if we are in debug mode and an <add> # exception happened. This will allow the debugger to still <add> # access the request object in the interactive shell. <add> if tb is None or not self.app.debug: <add> _request_ctx_stack.pop() <add> <ide> <ide> def url_for(endpoint, **values): <ide> """Generates a URL to the given endpoint with the method provided. <ide> def wsgi_app(self, environ, start_response): <ide> response = self.process_response(response) <ide> return response(environ, start_response) <ide> <del> @contextmanager <ide> def request_context(self, environ): <ide> """Creates a request context from the given environment and binds <ide> it to the current context. This must be used in combination with <ide> def request_context(self, environ): <ide> <ide> :params environ: a WSGI environment <ide> """ <del> _request_ctx_stack.push(_RequestContext(self, environ)) <del> try: <del> yield <del> finally: <del> _request_ctx_stack.pop() <add> return _RequestContext(self, environ) <ide> <ide> def test_request_context(self, *args, **kwargs): <ide> """Creates a WSGI environment from the given values (see
1
Python
Python
fix model package loading from link
ea167e14dbd32e902fa693c83620b56f478cb277
<ide><path>spacy/util.py <ide> def load_model(name, **overrides): <ide> <ide> def load_model_from_link(name, **overrides): <ide> """Load a model from a shortcut link, or directory in spaCy data path.""" <del> spec = importlib.util.spec_from_file_location('model', get_data_path() / name) <add> init_file = get_data_path() / name / '__init__.py' <add> spec = importlib.util.spec_from_file_location(name, init_file) <ide> try: <ide> cls = importlib.util.module_from_spec(spec) <ide> except AttributeError:
1
PHP
PHP
use bytcode sequence for unicode ellipsis
c7fda5674e221bfb70aa315505cf58fa5d0cce2e
<ide><path>lib/Cake/Utility/String.php <ide> public static function truncate($text, $length = 100, $options = array()) { <ide> if (isset($options['ending'])) { <ide> $default['ellipsis'] = $options['ending']; <ide> } elseif (!empty($options['html']) && Configure::read('App.encoding') == 'UTF-8') { <del> $default['ellipsis'] = chr(226); <add> $default['ellipsis'] = "\xE2\x80\xA6"; <ide> } <ide> $options = array_merge($default, $options); <ide> extract($options);
1
Javascript
Javascript
add some failing tests for path.join
8c0e87f9c333f3519b6d6439099f669a316ed598
<ide><path>test/simple/test-path.js <ide> assert.equal(path.extname("file."), "."); <ide> <ide> assert.equal(path.join(".", "fixtures/b", "..", "/b/c.js"), "fixtures/b/c.js"); <ide> assert.equal(path.join("/foo", "../../../bar"), "/bar"); <add>assert.equal(path.join('./'), '.'); <add>assert.equal(path.join('.'), '.'); <add>assert.equal(path.join('', 'foo'), 'foo'); <add>assert.equal(path.join('foo', '/bar'), 'foo/bar'); <ide> <ide> assert.equal(path.normalize("./fixtures///b/../b/c.js"), "fixtures/b/c.js"); <ide> assert.equal(path.normalize("./fixtures///b/../b/c.js",true), "fixtures///b/c.js");
1
Javascript
Javascript
add the rest of the tests from
f3ed85359760121ce71ab8f61d9167857f4b24bc
<ide><path>packages/ember-glimmer/tests/integration/components/contextual-components-test.js <ide> moduleFor('Components test: contextual components', class extends RenderingTest <ide> this.assertText('Hodi Sigmundur 33'); <ide> } <ide> <add> ['@test nested components with positional params at middle layer are partially overwriten by hash parameters']() { <add> this.registerComponent('-looked-up', { <add> ComponentClass: Component.extend().reopenClass({ <add> positionalParams: ['greeting', 'name', 'age'] <add> }), <add> <add> template: '{{greeting}} {{name}} {{age}}' <add> }); <add> <add> this.render(strip` <add> {{#with (component "-looked-up" greeting="Hola" name="Dolores" age=33) as |first|}} <add> {{#with (component first "Hej" "Sigmundur") as |second|}} <add> {{component second greeting=model.greeting}} <add> {{/with}} <add> {{/with}}`, { <add> model: { <add> greeting: 'Hodi' <add> } <add> }); <add> <add> this.assertText('Hodi Sigmundur 33'); <add> <add> this.runTask(() => this.rerender()); <add> <add> this.assertText('Hodi Sigmundur 33'); <add> <add> this.runTask(() => this.context.set('model.greeting', 'Kaixo')); <add> <add> this.assertText('Kaixo Sigmundur 33'); <add> <add> this.runTask(() => this.context.set('model', { greeting: 'Hodi' })); <add> <add> this.assertText('Hodi Sigmundur 33'); <add> } <add> <add> ['@test nested components with positional params at invocation override earlier hash parameters']() { <add> this.registerComponent('-looked-up', { <add> ComponentClass: Component.extend().reopenClass({ <add> positionalParams: ['greeting', 'name', 'age'] <add> }), <add> <add> template: '{{greeting}} {{name}} {{age}}' <add> }); <add> <add> this.render(strip` <add> {{#with (component "-looked-up" greeting="Hola" name="Dolores" age=33) as |first|}} <add> {{#with (component first greeting="Hej" name="Sigmundur") as |second|}} <add> {{component second model.greeting}} <add> {{/with}} <add> {{/with}}`, { <add> model: { <add> greeting: 'Hodi' <add> } <add> }); <add> <add> this.assertText('Hodi Sigmundur 33'); <add> <add> this.runTask(() => this.rerender()); <add> <add> this.assertText('Hodi Sigmundur 33'); <add> <add> this.runTask(() => this.context.set('model.greeting', 'Kaixo')); <add> <add> this.assertText('Kaixo Sigmundur 33'); <add> <add> this.runTask(() => this.context.set('model', { greeting: 'Hodi' })); <add> <add> this.assertText('Hodi Sigmundur 33'); <add> } <add> <ide> ['@test nested components overwrite hash parameters']() { <ide> this.registerComponent('-looked-up', { <ide> template: '{{greeting}} {{name}} {{age}}' <ide> moduleFor('Components test: contextual components', class extends RenderingTest <ide> }, 'You cannot specify both a positional param (at position 0) and the hash argument `name`.'); <ide> } <ide> <del> ['@test conflicting positional and hash parameters raise and assertion if in the same component context with prior curried positional params']() { <add> ['@test conflicting positional and hash parameters raise an assertion if in the same component context with prior curried positional params']() { <ide> this.registerComponent('-looked-up', { <ide> ComponentClass: Component.extend().reopenClass({ <ide> positionalParams: ['name']
1
Javascript
Javascript
remove unnecessary import aliases
d904e7042d6e02725aec3ede207efcb980512ab6
<ide><path>packages/@ember/-internals/glimmer/tests/integration/application/actions-test.js <ide> import Controller from '@ember/controller'; <del>import { moduleFor, ApplicationTest, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, ApplicationTestCase, RenderingTestCase } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { getDebugFunction, setDebugFunction } from '@ember/debug'; <ide> <ide> const noop = function() {}; <ide> <ide> moduleFor( <ide> 'Application test: actions', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> constructor() { <ide> setDebugFunction('debug', noop); <ide> super(...arguments); <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Rendering test: non-interactive actions', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> getBootOptions() { <ide> return { isInteractive: false }; <ide> } <ide><path>packages/@ember/-internals/glimmer/tests/integration/application/engine-test.js <del>import { moduleFor, ApplicationTest } from '../../utils/test-case'; <add>import { moduleFor, ApplicationTestCase } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { compile } from '../../utils/helpers'; <ide> import Controller from '@ember/controller'; <ide> import { next } from '@ember/runloop'; <ide> <ide> moduleFor( <ide> 'Application test: engine rendering', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> get routerOptions() { <ide> return { <ide> location: 'none', <ide><path>packages/@ember/-internals/glimmer/tests/integration/application/hot-reload-test.js <ide> import { ENV } from '@ember/-internals/environment'; <ide> import Service, { inject as injectService } from '@ember/service'; <ide> import { Component, Helper } from '@ember/-internals/glimmer'; <ide> import { expect } from '@glimmer/util'; <del>import { moduleFor, ApplicationTest } from '../../utils/test-case'; <add>import { moduleFor, ApplicationTestCase } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <ide> // This simuates what the template hot-reloading would do in development mode <ide> // to avoid regressions <ide> <ide> moduleFor( <ide> 'Appliation test: template hot reloading', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> constructor() { <ide> super(...arguments); <ide> this._APPLICATION_TEMPLATE_WRAPPER = ENV._APPLICATION_TEMPLATE_WRAPPER; <ide><path>packages/@ember/-internals/glimmer/tests/integration/application/rendering-test.js <ide> import { ENV } from '@ember/-internals/environment'; <ide> import Controller from '@ember/controller'; <del>import { moduleFor, ApplicationTest } from '../../utils/test-case'; <add>import { moduleFor, ApplicationTestCase } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { Route } from '@ember/-internals/routing'; <ide> import { Component } from '@ember/-internals/glimmer'; <ide> <ide> moduleFor( <ide> 'Application test: rendering', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> constructor() { <ide> super(...arguments); <ide> this._APPLICATION_TEMPLATE_WRAPPER = ENV._APPLICATION_TEMPLATE_WRAPPER; <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/angle-bracket-invocation-test.js <ide> import { EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION } from '@ember/canary-features'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { Component } from '../../utils/helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { classes } from '../../utils/test-helpers'; <ide> if (EMBER_GLIMMER_ANGLE_BRACKET_INVOCATION) { <ide> moduleFor( <ide> 'AngleBracket Invocation', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> '@test it can resolve <XBlah /> to x-blah'() { <ide> this.registerComponent('x-blah', { template: 'hello' }); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/append-test.js <ide> import { set } from '@ember/-internals/metal'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { Component, compile } from '../../utils/helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <del>class AbstractAppendTest extends RenderingTest { <add>class AbstractAppendTest extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/attribute-bindings-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Attribute bindings integration', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it can have attribute bindings']() { <ide> let FooBarComponent = Component.extend({ <ide> attributeBindings: ['foo:data-foo', 'bar:data-bar'], <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/attrs-lookup-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { Component, htmlSafe } from '../../utils/helpers'; <ide> import { set, computed } from '@ember/-internals/metal'; <ide> import { styles } from '../../utils/test-helpers'; <ide> <ide> moduleFor( <ide> 'Components test: attrs lookup', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it should be able to lookup attrs without `attrs.` - template access']() { <ide> this.registerComponent('foo-bar', { template: '{{first}}' }); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/class-bindings-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { classes } from '../../utils/test-helpers'; <ide> import { set, computed } from '@ember/-internals/metal'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <ide> moduleFor( <ide> 'ClassNameBindings integration', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it can have class name bindings on the class definition']() { <ide> let FooBarComponent = Component.extend({ <ide> classNameBindings: ['foo', 'isEnabled:enabled', 'isHappy:happy:sad'], <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'ClassBinding integration', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it should apply classBinding without condition always']() { <ide> this.registerComponent('foo-bar', { template: 'hello' }); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/contextual-components-test.js <ide> import { assign } from '@ember/polyfills'; <ide> import { Component } from '../../utils/helpers'; <ide> import { applyMixins, strip } from '../../utils/abstract-test-case'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { isEmpty } from '@ember/-internals/metal'; <ide> import { A as emberA } from '@ember/-internals/runtime'; <ide> <ide> moduleFor( <ide> 'Components test: contextual components', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test renders with component helper']() { <ide> let expectedText = 'Hodi'; <ide> <ide> moduleFor( <ide> } <ide> ); <ide> <del>class ContextualComponentMutableParamsTest extends RenderingTest { <add>class ContextualComponentMutableParamsTest extends RenderingTestCase { <ide> render(templateStr, context = {}) { <ide> super.render( <ide> `${templateStr}<span class="value">{{model.val2}}</span>`, <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/curly-components-test.js <ide> import { Object as EmberObject, A as emberA } from '@ember/-internals/runtime'; <ide> import { jQueryDisabled } from '@ember/-internals/views'; <ide> import { Component, compile, htmlSafe } from '../../utils/helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { classes, equalTokens, equalsElement, styles } from '../../utils/test-helpers'; <ide> <ide> moduleFor( <ide> 'Components test: curly components', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it can render a basic component']() { <ide> this.registerComponent('foo-bar', { template: 'hello' }); <ide> <ide> moduleFor( <ide> if (jQueryDisabled) { <ide> moduleFor( <ide> 'Components test: curly components: jQuery disabled', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test jQuery proxy is not available without jQuery']() { <ide> let instance; <ide> <ide> if (jQueryDisabled) { <ide> } else { <ide> moduleFor( <ide> 'Components test: curly components: jQuery enabled', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it has a jQuery proxy to the element']() { <ide> let instance; <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/destroy-test.js <ide> import { set } from '@ember/-internals/metal'; <ide> import { Component } from '../../utils/helpers'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> <ide> moduleFor( <ide> 'Component destroy', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it correctly releases the destroyed components'](assert) { <ide> let FooBarComponent = Component.extend({}); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/dynamic-components-test.js <ide> import { set, computed } from '@ember/-internals/metal'; <ide> import { jQueryDisabled } from '@ember/-internals/views'; <ide> import { Component } from '../../utils/helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> <ide> moduleFor( <ide> 'Components test: dynamic components', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it can render a basic component with a static component name argument']() { <ide> this.registerComponent('foo-bar', { template: 'hello {{name}}' }); <ide> <ide> moduleFor( <ide> if (jQueryDisabled) { <ide> moduleFor( <ide> 'Components test: dynamic components: jQuery disabled', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test jQuery proxy is not available without jQuery']() { <ide> let instance; <ide> <ide> if (jQueryDisabled) { <ide> } else { <ide> moduleFor( <ide> 'Components test: dynamic components : jQuery enabled', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it has a jQuery proxy to the element']() { <ide> let instance; <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/error-handling-test.js <ide> import { set } from '@ember/-internals/metal'; <ide> import { Component } from '../../utils/helpers'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> <ide> moduleFor( <ide> 'Errors thrown during render', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it can recover resets the transaction when an error is thrown during initial render']( <ide> assert <ide> ) { <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/fragment-components-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Components test: fragment components', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> getCustomDispatcherEvents() { <ide> return { <ide> hitDem: 'folks', <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/instrumentation-compile-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { <ide> subscribe as instrumentationSubscribe, <ide> import { <ide> <ide> moduleFor( <ide> 'Components compile instrumentation', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/instrumentation-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { <ide> import { <ide> <ide> moduleFor( <ide> 'Components instrumentation', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/life-cycle-test.js <ide> import { set, setProperties } from '@ember/-internals/metal'; <ide> import { A as emberA } from '@ember/-internals/runtime'; <ide> import { Component } from '../../utils/helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { getViewId, getViewElement, jQueryDisabled } from '@ember/-internals/views'; <ide> import { classes } from '../../utils/test-helpers'; <ide> import { tryInvoke } from '@ember/-internals/utils'; <ide> import { runAppend } from 'internal-test-helpers'; <ide> <del>class LifeCycleHooksTest extends RenderingTest { <add>class LifeCycleHooksTest extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> this.hooks = []; <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Run loop and lifecycle hooks', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test afterRender set']() { <ide> let ComponentClass = Component.extend({ <ide> width: '5', <ide> moduleFor( <ide> if (!jQueryDisabled) { <ide> moduleFor( <ide> 'Run loop and lifecycle hooks - jQuery only', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test lifecycle hooks have proper access to this.$()'](assert) { <ide> assert.expect(6); <ide> let component; <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/link-to-test.js <del>import { moduleFor, ApplicationTest, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, ApplicationTestCase, RenderingTestCase } from '../../utils/test-case'; <ide> import Controller from '@ember/controller'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { LinkComponent } from '../../utils/helpers'; <ide> import { classes as classMatcher } from '../../utils/test-helpers'; <ide> <ide> moduleFor( <ide> 'Link-to component', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> visitWithDeprecation(path, deprecation) { <ide> let p; <ide> <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Link-to component with query-params', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> constructor() { <ide> super(...arguments); <ide> <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Link-to component', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test should be able to be inserted in DOM when the router is not present - block']() { <ide> this.render(`{{#link-to 'index'}}Go to Index{{/link-to}}`); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/local-lookup-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { compile } from 'ember-template-compiler'; <ide> import { ModuleBasedTestResolver } from 'internal-test-helpers'; <ide> import { moduleFor as applicationModuleFor, ApplicationTestCase } from 'internal-test-helpers'; <ide> import { Component } from '../../utils/helpers'; <ide> import { EMBER_MODULE_UNIFICATION } from '@ember/canary-features'; <ide> import { helper, Helper } from '@ember/-internals/glimmer'; <ide> <del>class LocalLookupTest extends RenderingTest { <add>class LocalLookupTest extends RenderingTestCase { <ide> ['@test it can lookup a local template']() { <ide> this.registerComponent('x-outer/x-inner', { <ide> template: 'Nested template says: {{yield}}', <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/namespaced-lookup-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { EMBER_MODULE_UNIFICATION } from '@ember/canary-features'; <ide> import { Component, helper } from '@ember/-internals/glimmer'; <ide> <ide> if (EMBER_MODULE_UNIFICATION) { <ide> moduleFor( <ide> 'Namespaced lookup', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it can render a namespaced component']() { <ide> this.addTemplate( <ide> { <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/target-action-test.js <ide> import { assign } from '@ember/polyfills'; <del>import { moduleFor, RenderingTest, ApplicationTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase, ApplicationTestCase } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { set, Mixin } from '@ember/-internals/metal'; <ide> import { Component } from '../../utils/helpers'; <ide> function expectSendActionDeprecation(fn) { <ide> <ide> moduleFor( <ide> 'Components test: sendAction', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> this.actionCounts = {}; <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Components test: sendAction to a controller', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> ["@test sendAction should trigger an action on the parent component's controller if it exists"]( <ide> assert <ide> ) { <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Components test: sendAction of a closure action', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test action should be called'](assert) { <ide> assert.expect(2); <ide> let component; <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Components test: send', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test sending to undefined actions triggers an error'](assert) { <ide> assert.expect(2); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/template-only-components-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { classes } from '../../utils/test-helpers'; <ide> import { ENV } from '@ember/-internals/environment'; <ide> <del>class TemplateOnlyComponentsTest extends RenderingTest { <add>class TemplateOnlyComponentsTest extends RenderingTestCase { <ide> registerComponent(name, template) { <ide> super.registerComponent(name, { template, ComponentClass: null }); <ide> } <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/to-string-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { Checkbox, Component, LinkComponent, TextArea, TextField } from '@ember/-internals/glimmer'; <ide> <ide> moduleFor( <ide> 'built-in component toString', <del> class AbstractAppendTest extends RenderingTest { <add> class AbstractAppendTest extends RenderingTestCase { <ide> '@test text-field has the correct toString value'(assert) { <ide> assert.strictEqual(TextField.toString(), '@ember/component/text-field'); <ide> } <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/utils-test.js <ide> import { <ide> getViewClientRects, <ide> getViewBoundingClientRect, <ide> } from '@ember/-internals/views'; <del>import { moduleFor, ApplicationTest, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, ApplicationTestCase, RenderingTestCase } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> <ide> moduleFor( <ide> 'View tree tests', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> constructor() { <ide> super(...arguments); <ide> <ide> let ClientRectListCtor, ClientRectCtor; <ide> <ide> moduleFor( <ide> 'Bounds tests', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test getViewBounds on a regular component'](assert) { <ide> let component; <ide> this.registerComponent('hi-mom', { <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/web-component-fallback-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Components test: web component fallback', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test custom elements are rendered']() { <ide> let template = `<foo-bar some-attr="123">hello</foo-bar>`; <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/will-destroy-element-hook-test.js <ide> import { set } from '@ember/-internals/metal'; <ide> import { Component } from '../../utils/helpers'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> <ide> moduleFor( <ide> 'Component willDestroyElement hook', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it calls willDestroyElement when removed by if'](assert) { <ide> let didInsertElementCount = 0; <ide> let willDestroyElementCount = 0; <ide><path>packages/@ember/-internals/glimmer/tests/integration/content-test.js <ide> /* globals EmberDev */ <del>import { RenderingTest, moduleFor } from '../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../utils/test-case'; <ide> import { applyMixins } from '../utils/abstract-test-case'; <ide> import { set, computed } from '@ember/-internals/metal'; <ide> import { getDebugFunction, setDebugFunction } from '@ember/debug'; <ide> import { Component, SafeString, htmlSafe } from '../utils/helpers'; <ide> <ide> moduleFor( <ide> 'Static content tests', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it can render a static text node']() { <ide> this.render('hello'); <ide> let text1 = this.assertTextNode(this.firstChild, 'hello'); <ide> moduleFor( <ide> } <ide> ); <ide> <del>class DynamicContentTest extends RenderingTest { <add>class DynamicContentTest extends RenderingTestCase { <ide> /* abstract */ <ide> renderPath(/* path, context = {} */) { <ide> throw new Error('Not implemented: `renderValues`'); <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Dynamic content tests (integration)', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it can render a dynamic template']() { <ide> let template = ` <ide> <div class="header"> <ide> moduleFor( <ide> ); <ide> <ide> let warnings, originalWarn; <del>class StyleTest extends RenderingTest { <add>class StyleTest extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> warnings = []; <ide><path>packages/@ember/-internals/glimmer/tests/integration/custom-component-manager-test.js <del>import { moduleFor, RenderingTest } from '../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../utils/test-case'; <ide> import { Object as EmberObject } from '@ember/-internals/runtime'; <ide> import { set, setProperties, computed } from '@ember/-internals/metal'; <ide> import { <ide> if (GLIMMER_CUSTOM_COMPONENT_MANAGER) { <ide> <ide> let InstrumentedComponentManager; <ide> <del> class ComponentManagerTest extends RenderingTest { <add> class ComponentManagerTest extends RenderingTestCase { <ide> constructor(assert) { <ide> super(...arguments); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/custom-modifier-manager-test.js <del>import { moduleFor, RenderingTest } from '../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../utils/test-case'; <ide> import { Object as EmberObject } from '@ember/-internals/runtime'; <ide> import { GLIMMER_MODIFIER_MANAGER } from '@ember/canary-features'; <ide> import { setModifierManager } from '@ember/-internals/glimmer'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> if (GLIMMER_MODIFIER_MANAGER) { <del> class ModifierManagerTest extends RenderingTest {} <add> class ModifierManagerTest extends RenderingTestCase {} <ide> <ide> class CustomModifierManager { <ide> constructor(owner) { <ide><path>packages/@ember/-internals/glimmer/tests/integration/event-dispatcher-test.js <del>import { RenderingTest, moduleFor } from '../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../utils/test-case'; <ide> import { Component } from '../utils/helpers'; <ide> import { getCurrentRunLoop, run } from '@ember/runloop'; <ide> import { <ide> function fireNativeWithDataTransfer(node, type, dataTransfer) { <ide> <ide> moduleFor( <ide> 'EventDispatcher', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test events bubble view hierarchy for form elements'](assert) { <ide> let receivedEvent; <ide> <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'EventDispatcher#setup', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> <ide> moduleFor( <ide> if (EMBER_IMPROVED_INSTRUMENTATION) { <ide> moduleFor( <ide> 'EventDispatcher - Instrumentation', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> teardown() { <ide> super.teardown(); <ide> instrumentationReset(); <ide> if (EMBER_IMPROVED_INSTRUMENTATION) { <ide> if (canDataTransfer) { <ide> moduleFor( <ide> 'EventDispatcher - Event Properties', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test dataTransfer property is added to drop event'](assert) { <ide> let receivedEvent; <ide> this.registerComponent('x-foo', { <ide> if (canDataTransfer) { <ide> if (jQueryDisabled) { <ide> moduleFor( <ide> 'EventDispatcher#native-events', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test native events are passed when jQuery is not present'](assert) { <ide> let receivedEvent; <ide> <ide> if (jQueryDisabled) { <ide> } else { <ide> moduleFor( <ide> 'EventDispatcher#jquery-events', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> beforeEach() { <ide> this.jqueryIntegration = window.ENV._JQUERY_INTEGRATION; <ide> } <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/-class-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { classes } from '../../utils/test-helpers'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{-class}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test casts binding to dasherized class']() { <ide> this.registerComponent('foo-bar', { template: '' }); <ide> this.render(`{{foo-bar class=(-class someTruth "someTruth")}}`, { <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/array-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { EMBER_GLIMMER_ARRAY_HELPER } from '@ember/canary-features'; <ide> if (EMBER_GLIMMER_ARRAY_HELPER) { <ide> moduleFor( <ide> 'Helpers test: {{array}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test returns an array']() { <ide> this.render(strip` <ide> {{#with (array "Sergio") as |people|}} <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/closure-action-test.js <ide> import { <ide> import { getCurrentRunLoop } from '@ember/runloop'; <ide> import { set, computed } from '@ember/-internals/metal'; <ide> import { EMBER_IMPROVED_INSTRUMENTATION } from '@ember/canary-features'; <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { Component, INVOKE } from '../../utils/helpers'; <ide> <ide> if (EMBER_IMPROVED_INSTRUMENTATION) { <ide> moduleFor( <ide> 'Helpers test: closure {{action}} improved instrumentation', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> subscribe(eventName, options) { <ide> this.subscriber = instrumentationSubscribe(eventName, options); <ide> } <ide> if (EMBER_IMPROVED_INSTRUMENTATION) { <ide> <ide> moduleFor( <ide> 'Helpers test: closure {{action}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test action should be called']() { <ide> let outerActionCalled = false; <ide> let component; <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/concat-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{concat}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it concats static arguments']() { <ide> this.render(`{{concat "foo" " " "bar" " " "baz"}}`); <ide> this.assertText('foo bar baz'); <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/custom-helper-test.js <ide> /* globals EmberDev */ <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { runDestroy } from 'internal-test-helpers'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Helpers test: custom helpers', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it cannot override built-in syntax']() { <ide> this.registerHelper('if', () => 'Nope'); <ide> expectAssertion(() => { <ide> moduleFor( <ide> ); <ide> <ide> if (!EmberDev.runningProdBuild) { <del> class HelperMutatingArgsTests extends RenderingTest { <add> class HelperMutatingArgsTests extends RenderingTestCase { <ide> buildCompute() { <ide> return (params, hash) => { <ide> this.assert.throws(() => { <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/element-action-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { set } from '@ember/-internals/metal'; <ide> const isIE11 = !window.ActiveXObject && 'ActiveXObject' in window; <ide> if (EMBER_IMPROVED_INSTRUMENTATION) { <ide> moduleFor( <ide> 'Helpers test: element action instrumentation', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> teardown() { <ide> super.teardown(); <ide> instrumentationReset(); <ide> if (EMBER_IMPROVED_INSTRUMENTATION) { <ide> <ide> moduleFor( <ide> 'Helpers test: element action', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it can call an action on its enclosing component']() { <ide> let fooCallCount = 0; <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/get-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { set, get } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{get}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test should be able to get an object value with a static key']() { <ide> this.render(`[{{get colors 'apple'}}] [{{if true (get colors 'apple')}}]`, { <ide> colors: { apple: 'red' }, <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/hash-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{hash}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test returns a hash with the right key-value']() { <ide> this.render(`{{#with (hash name=\"Sergio\") as |person|}}{{person.name}}{{/with}}`); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/input-test.js <ide> import { assign } from '@ember/polyfills'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { Component } from '../../utils/helpers'; <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { runDestroy } from 'internal-test-helpers'; <ide> import { jQuery } from '@ember/-internals/views'; <ide> <del>class InputRenderingTest extends RenderingTest { <add>class InputRenderingTest extends RenderingTestCase { <ide> $input() { <ide> return this.$('input'); <ide> } <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/loc-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { _setStrings } from '@ember/string'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{loc}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> _setStrings({ <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/log-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{log}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> /* eslint-disable no-console */ <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/mut-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { Component, htmlSafe } from '../../utils/helpers'; <ide> import { set, get, computed } from '@ember/-internals/metal'; <ide> import { styles } from '../../utils/test-helpers'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{mut}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test a simple mutable binding using `mut` propagates properly']() { <ide> let bottom; <ide> <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Mutable Bindings used in Computed Properties that are bound as attributeBindings', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test an attribute binding of a computed property of a 2-way bound attr recomputes when the attr changes']() { <ide> let input, output; <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/partial-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { A as emberA } from '@ember/-internals/runtime'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{partial}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test should render other templates registered with the container']() { <ide> this.registerPartial('_subTemplateFromContainer', 'sub-template'); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/readonly-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { Component } from '../../utils/helpers'; <ide> import { set, get } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{readonly}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test {{readonly}} of a path should work']() { <ide> let component; <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/text-area-test.js <ide> import { assign } from '@ember/polyfills'; <ide> import { set } from '@ember/-internals/metal'; <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { classes } from '../../utils/test-helpers'; <ide> import { applyMixins } from '../../utils/abstract-test-case'; <ide> <del>class TextAreaRenderingTest extends RenderingTest { <add>class TextAreaRenderingTest extends RenderingTestCase { <ide> assertTextArea({ attrs, value } = {}) { <ide> let mergedAttrs = assign({ class: classes('ember-view ember-text-area') }, attrs); <ide> this.assertComponentElement(this.firstChild, { <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/unbound-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { set, get, setProperties } from '@ember/-internals/metal'; <ide> import { Component } from '../../utils/helpers'; <ide> import { A as emberA } from '@ember/-internals/runtime'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{unbound}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test should be able to output a property without binding']() { <ide> this.render(`<div id="first">{{unbound content.anUnboundString}}</div>`, { <ide> content: { <ide><path>packages/@ember/-internals/glimmer/tests/integration/helpers/yield-test.js <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { Component } from '../../utils/helpers'; <ide> <ide> moduleFor( <ide> 'Helpers test: {{yield}} helper', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test can yield to block']() { <ide> this.registerComponent('yield-comp', { <ide> template: '[In layout:] {{yield}}', <ide><path>packages/@ember/-internals/glimmer/tests/integration/input-test.js <del>import { RenderingTest, moduleFor } from '../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../utils/test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'Input element tests', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> runAttributeTest(attributeName, values) { <ide> let template = `<input ${attributeName}={{value}}>`; <ide> this.render(template, { value: values[0] }); <ide><path>packages/@ember/-internals/glimmer/tests/integration/mount-test.js <ide> import { getOwner } from '@ember/-internals/owner'; <del>import { moduleFor, ApplicationTest, RenderingTest } from '../utils/test-case'; <add>import { moduleFor, ApplicationTestCase, RenderingTestCase } from '../utils/test-case'; <ide> import { compile, Component } from '../utils/helpers'; <ide> import Controller from '@ember/controller'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { EMBER_ENGINES_MOUNT_PARAMS } from '@ember/canary-features'; <ide> if (EMBER_ENGINES_MOUNT_PARAMS) { <ide> moduleFor( <ide> '{{mount}} single param assertion', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it asserts that only a single param is passed']() { <ide> expectAssertion(() => { <ide> this.render('{{mount "chat" "foo"}}'); <ide> if (EMBER_ENGINES_MOUNT_PARAMS) { <ide> } else { <ide> moduleFor( <ide> '{{mount}} single param assertion', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it asserts that only a single param is passed']() { <ide> expectAssertion(() => { <ide> this.render('{{mount "chat" "foo"}}'); <ide> if (EMBER_ENGINES_MOUNT_PARAMS) { <ide> <ide> moduleFor( <ide> '{{mount}} assertions', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it asserts when an invalid engine name is provided']() { <ide> expectAssertion(() => { <ide> this.render('{{mount engineName}}', { engineName: {} }); <ide> moduleFor( <ide> <ide> moduleFor( <ide> '{{mount}} test', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> constructor() { <ide> super(...arguments); <ide> <ide> moduleFor( <ide> if (EMBER_ENGINES_MOUNT_PARAMS) { <ide> moduleFor( <ide> '{{mount}} params tests', <del> class extends ApplicationTest { <add> class extends ApplicationTestCase { <ide> constructor() { <ide> super(...arguments); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/outlet-test.js <del>import { RenderingTest, moduleFor } from '../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../utils/test-case'; <ide> import { runAppend } from 'internal-test-helpers'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'outlet view', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/refinements-test.js <del>import { RenderingTest, moduleFor } from '../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../utils/test-case'; <ide> import { strip } from '../utils/abstract-test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> 'syntax refinements', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test block params should not be refined']() { <ide> this.registerHelper('foo', () => 'bar helper'); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/svg-test.js <del>import { RenderingTest, moduleFor } from '../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../utils/test-case'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { strip } from '../utils/abstract-test-case'; <ide> <ide> moduleFor( <ide> 'SVG element tests', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test unquoted viewBox property is output'](assert) { <ide> let viewBoxString = '0 0 100 100'; <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/syntax/each-in-test.js <ide> import { get, set } from '@ember/-internals/metal'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { Object as EmberObject, ObjectProxy } from '@ember/-internals/runtime'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { HAS_NATIVE_SYMBOL } from '@ember/-internals/utils'; <ide> moduleFor( <ide> moduleFor('Syntax test: {{#each-in}}', BasicSyntaxTest); <ide> <ide> // Rendering tests <del>class AbstractEachInTest extends RenderingTest { <add>class AbstractEachInTest extends RenderingTestCase { <ide> createHash(/* hash */) { <ide> throw new Error('Not implemented: `createHash`'); <ide> } <ide><path>packages/@ember/-internals/glimmer/tests/integration/syntax/each-test.js <ide> import { get, set, notifyPropertyChange } from '@ember/-internals/metal'; <ide> import { applyMixins, strip } from '../../utils/abstract-test-case'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { A as emberA, ArrayProxy, RSVP } from '@ember/-internals/runtime'; <ide> import { Component, htmlSafe } from '../../utils/helpers'; <ide> import { HAS_NATIVE_SYMBOL } from '@ember/-internals/utils'; <ide> moduleFor( <ide> } <ide> ); <ide> <del>class AbstractEachTest extends RenderingTest { <add>class AbstractEachTest extends RenderingTestCase { <ide> /* abstract */ <ide> createList(/* items */) { <ide> throw new Error('Not implemented: `createList`'); <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Syntax test: {{#each as}} undefined path', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test keying off of `undefined` does not render']() { <ide> this.render( <ide> strip` <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Syntax test: {{#each}} with sparse arrays', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test it should itterate over holes']() { <ide> let sparseArray = []; <ide> sparseArray[3] = 'foo'; <ide> moduleFor( <ide> if (typeof MutationObserver === 'function') { <ide> moduleFor( <ide> 'Syntax test: {{#each as}} DOM mutation test', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> constructor() { <ide> super(...arguments); <ide> this.observer = null; <ide><path>packages/@ember/-internals/glimmer/tests/integration/syntax/experimental-syntax-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { _registerMacros, _experimentalMacros } from '@ember/-internals/glimmer'; <ide> <ide> moduleFor( <ide> 'registerMacros', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> constructor() { <ide> let originalMacros = _experimentalMacros.slice(); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/integration/syntax/if-unless-test.js <ide> import { A as emberA } from '@ember/-internals/runtime'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <del>import { RenderingTest, moduleFor } from '../../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../../utils/test-case'; <ide> import { IfUnlessWithSyntaxTest } from '../../utils/shared-conditional-tests'; <ide> <ide> moduleFor( <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Syntax test: {{#if}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test using `if` with an `{{each}}` destroys components when transitioning to and from inverse (GH #12267)']( <ide> assert <ide> ) { <ide><path>packages/@ember/-internals/glimmer/tests/integration/syntax/in-element-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { equalTokens } from '../../utils/test-helpers'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> import { Component } from '@ember/-internals/glimmer'; <ide> import { set } from '@ember/-internals/metal'; <ide> <ide> moduleFor( <ide> '{{-in-element}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test using {{#in-element whatever}} asserts']() { <ide> // the in-element keyword is not yet public API this test should be removed <ide> // once https://github.com/emberjs/rfcs/pull/287 lands and is enabled <ide><path>packages/@ember/-internals/glimmer/tests/integration/syntax/let-test.js <ide> import { get, set } from '@ember/-internals/metal'; <ide> import { A as emberA, ObjectProxy, removeAt } from '@ember/-internals/runtime'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <ide> moduleFor( <ide> 'Syntax test: {{#let as}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> templateFor({ cond, truthy, falsy }) { <ide> return `{{#let ${cond} as |test|}}${truthy}{{else}}${falsy}{{/let}}`; <ide> } <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Syntax test: Multiple {{#let as}} helpers', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test re-using the same variable with different {{#let}} blocks does not override each other']() { <ide> this.render( <ide> `Admin: {{#let admin as |person|}}{{person.name}}{{/let}} User: {{#let user as |person|}}{{person.name}}{{/let}}`, <ide><path>packages/@ember/-internals/glimmer/tests/integration/syntax/with-dynamic-var-test.js <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <ide> moduleFor( <ide> '{{-with-dynamic-var}}', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test does not allow setting values other than outletState']() { <ide> expectAssertion(() => { <ide> this.render(strip` <ide><path>packages/@ember/-internals/glimmer/tests/integration/syntax/with-test.js <ide> import { get, set } from '@ember/-internals/metal'; <ide> import { A as emberA, ObjectProxy, removeAt } from '@ember/-internals/runtime'; <del>import { moduleFor, RenderingTest } from '../../utils/test-case'; <add>import { moduleFor, RenderingTestCase } from '../../utils/test-case'; <ide> import { IfUnlessWithSyntaxTest } from '../../utils/shared-conditional-tests'; <ide> import { strip } from '../../utils/abstract-test-case'; <ide> <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'Syntax test: Multiple {{#with as}} helpers', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test re-using the same variable with different {{#with}} blocks does not override each other']() { <ide> this.render( <ide> `Admin: {{#with admin as |person|}}{{person.name}}{{/with}} User: {{#with user as |person|}}{{person.name}}{{/with}}`, <ide><path>packages/@ember/-internals/glimmer/tests/unit/runtime-resolver-cache-test.js <del>import { RenderingTest, moduleFor } from '../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../utils/test-case'; <ide> import { Component } from '../utils/helpers'; <ide> import { set } from '@ember/-internals/metal'; <ide> import { runDestroy, runAppend } from 'internal-test-helpers'; <ide> <ide> moduleFor( <ide> 'ember-glimmer runtime resolver cache', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> '@test a helper definition is only generated once'(assert) { <ide> this.registerHelper('foo-bar', () => 'foo-bar helper!'); <ide> this.registerHelper('baz-qux', () => 'baz-qux helper!'); <ide><path>packages/@ember/-internals/glimmer/tests/unit/template-factory-test.js <ide> import { precompile, compile } from 'ember-template-compiler'; <ide> import { template } from '@ember/-internals/glimmer'; <del>import { RenderingTest, moduleFor } from '../utils/test-case'; <add>import { RenderingTestCase, moduleFor } from '../utils/test-case'; <ide> import { Component } from '../utils/helpers'; <ide> <ide> moduleFor( <ide> 'Template factory test', <del> class extends RenderingTest { <add> class extends RenderingTestCase { <ide> ['@test the template factory returned from precompile is the same as compile'](assert) { <ide> let { owner } = this; <ide> let { runtimeResolver } = this; <ide><path>packages/@ember/-internals/glimmer/tests/utils/abstract-test-case.js <del>export { AbstractTestCase as TestCase, applyMixins, strip } from 'internal-test-helpers'; <add>export { AbstractTestCase, applyMixins, strip } from 'internal-test-helpers'; <ide><path>packages/@ember/-internals/glimmer/tests/utils/shared-conditional-tests.js <ide> import { assign } from '@ember/polyfills'; <ide> import { applyMixins } from './abstract-test-case'; <del>import { RenderingTest } from './test-case'; <add>import { RenderingTestCase } from './test-case'; <ide> import { get, set } from '@ember/-internals/metal'; <ide> import { <ide> Object as EmberObject, <ide> import { <ide> } from '@ember/-internals/runtime'; <ide> import { Component } from './helpers'; <ide> <del>class AbstractConditionalsTest extends RenderingTest { <add>class AbstractConditionalsTest extends RenderingTestCase { <ide> get truthyValue() { <ide> return true; <ide> } <ide><path>packages/@ember/-internals/glimmer/tests/utils/string-test.js <ide> import { SafeString, htmlSafe, isHTMLSafe } from './helpers'; <del>import { TestCase } from './abstract-test-case'; <add>import { AbstractTestCase } from './abstract-test-case'; <ide> import { moduleFor } from './test-case'; <ide> <ide> moduleFor( <ide> 'SafeString', <del> class extends TestCase { <add> class extends AbstractTestCase { <ide> ['@test htmlSafe should return an instance of SafeString']() { <ide> let safeString = htmlSafe('you need to be more <b>bold</b>'); <ide> <ide> moduleFor( <ide> <ide> moduleFor( <ide> 'SafeString isHTMLSafe', <del> class extends TestCase { <add> class extends AbstractTestCase { <ide> ['@test isHTMLSafe should detect SafeString']() { <ide> let safeString = htmlSafe('<em>Emphasize</em> the important things.'); <ide> <ide><path>packages/@ember/-internals/glimmer/tests/utils/test-case.js <ide> export { <del> AbstractTestCase as TestCase, <del> ApplicationTestCase as ApplicationTest, <del> RenderingTestCase as RenderingTest, <add> AbstractTestCase, <add> ApplicationTestCase, <add> RenderingTestCase, <ide> moduleFor, <ide> } from 'internal-test-helpers';
67
Javascript
Javascript
fix a typo in {{bindattr}} doc
06bae5ad65bfcbf1c375bb79f40307bd55536b0e
<ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> EmberHandlebars.registerHelper('unless', function(context, options) { <ide> Results in the following rendered output: <ide> <ide> ```html <del> <img class=":class-name-to-always-apply"> <add> <img class="class-name-to-always-apply"> <ide> ``` <ide> <ide> All three strategies - string return value, boolean return value, and
1
Javascript
Javascript
initialize all measurements to 0
656cabda0f46136ee46528313cbb94ecaff6127c
<ide><path>src/text-editor-component.js <ide> class TextEditorComponent { <ide> this.didMouseDownOnContent = this.didMouseDownOnContent.bind(this) <ide> this.lineTopIndex = new LineTopIndex() <ide> this.updateScheduled = false <del> this.measurements = null <add> this.hasInitialMeasurements = false <add> this.measurements = { <add> lineHeight: 0, <add> baseCharacterWidth: 0, <add> doubleWidthCharacterWidth: 0, <add> halfWidthCharacterWidth: 0, <add> koreanCharacterWidth: 0, <add> gutterContainerWidth: 0, <add> lineNumberGutterWidth: 0, <add> clientContainerHeight: 0, <add> clientContainerWidth: 0, <add> verticalScrollbarWidth: 0, <add> horizontalScrollbarHeight: 0, <add> longestLineWidth: 0 <add> } <ide> this.visible = false <ide> this.cursorsBlinking = false <ide> this.cursorsBlinkedOff = false <ide> class TextEditorComponent { <ide> <ide> let clientContainerHeight = '100%' <ide> let clientContainerWidth = '100%' <del> if (this.measurements) { <add> if (this.hasInitialMeasurements) { <ide> if (model.getAutoHeight()) { <ide> clientContainerHeight = this.getContentHeight() <ide> if (this.isHorizontalScrollbarVisible()) clientContainerHeight += this.getHorizontalScrollbarHeight() <ide> class TextEditorComponent { <ide> backgroundColor: 'inherit' <ide> } <ide> <del> if (this.measurements) { <add> if (this.hasInitialMeasurements) { <ide> style.left = this.getGutterContainerWidth() + 'px' <ide> style.width = this.getScrollContainerWidth() + 'px' <ide> } <ide> class TextEditorComponent { <ide> overflow: 'hidden', <ide> backgroundColor: 'inherit' <ide> } <del> if (this.measurements) { <add> if (this.hasInitialMeasurements) { <ide> style.width = this.getScrollWidth() + 'px' <ide> style.height = this.getScrollHeight() + 'px' <ide> style.willChange = 'transform' <ide> class TextEditorComponent { <ide> let scrollHeight, scrollTop, horizontalScrollbarHeight <ide> let scrollWidth, scrollLeft, verticalScrollbarWidth, forceScrollbarVisible <ide> <del> if (this.measurements) { <add> if (this.hasInitialMeasurements) { <ide> scrollHeight = this.getScrollHeight() <ide> scrollWidth = this.getScrollWidth() <ide> scrollTop = this.getScrollTop() <ide> class TextEditorComponent { <ide> didShow () { <ide> if (!this.visible && this.isVisible()) { <ide> this.visible = true <del> if (!this.measurements) this.performInitialMeasurements() <add> if (!this.hasInitialMeasurements) this.measureDimensions() <ide> this.props.model.setVisible(true) <ide> this.updateSync() <ide> this.flushPendingLogicalScrollPosition() <ide> class TextEditorComponent { <ide> return marginInBaseCharacters * this.getBaseCharacterWidth() <ide> } <ide> <del> performInitialMeasurements () { <del> this.measurements = {} <del> this.measureDimensions() <del> } <del> <ide> // This method exists because it existed in the previous implementation and some <ide> // package tests relied on it <ide> measureDimensions () { <ide> class TextEditorComponent { <ide> this.measureClientContainerHeight() <ide> this.measureClientContainerWidth() <ide> this.measureScrollbarDimensions() <add> this.hasInitialMeasurements = true <ide> } <ide> <ide> measureCharacterDimensions () { <ide> class TextEditorComponent { <ide> } <ide> <ide> measureClientContainerHeight () { <del> if (!this.measurements) return false <del> <ide> const clientContainerHeight = this.refs.clientContainer.offsetHeight <ide> if (clientContainerHeight !== this.measurements.clientContainerHeight) { <ide> this.measurements.clientContainerHeight = clientContainerHeight <ide> class TextEditorComponent { <ide> } <ide> <ide> measureClientContainerWidth () { <del> if (!this.measurements) return false <del> <ide> const clientContainerWidth = this.refs.clientContainer.offsetWidth <ide> if (clientContainerWidth !== this.measurements.clientContainerWidth) { <ide> this.measurements.clientContainerWidth = clientContainerWidth <ide> class TextEditorComponent { <ide> } <ide> <ide> getBaseCharacterWidth () { <del> return this.measurements ? this.measurements.baseCharacterWidth : null <add> return this.measurements.baseCharacterWidth <ide> } <ide> <ide> getLongestLineWidth () { <ide> class TextEditorComponent { <ide> } <ide> <ide> getGutterContainerWidth () { <del> return (this.measurements) ? this.measurements.gutterContainerWidth : 0 <add> return this.measurements.gutterContainerWidth <ide> } <ide> <ide> getLineNumberGutterWidth () { <ide> class TextEditorComponent { <ide> } <ide> <ide> getFirstVisibleRow () { <del> if (this.measurements) { <del> return this.rowForPixelPosition(this.getScrollTop()) <del> } <add> return this.rowForPixelPosition(this.getScrollTop()) <ide> } <ide> <ide> getLastVisibleRow () { <del> if (this.measurements) { <del> return Math.min( <del> this.props.model.getApproximateScreenLineCount() - 1, <del> this.rowForPixelPosition(this.getScrollBottom()) <del> ) <del> } <add> return Math.min( <add> this.props.model.getApproximateScreenLineCount() - 1, <add> this.rowForPixelPosition(this.getScrollBottom()) <add> ) <ide> } <ide> <ide> getFirstVisibleColumn () { <del> if (this.measurements) { <del> return Math.floor(this.getScrollLeft() / this.getBaseCharacterWidth()) <del> } <add> return Math.floor(this.getScrollLeft() / this.getBaseCharacterWidth()) <ide> } <ide> <ide> getVisibleTileCount () { <ide> class TextEditorComponent { <ide> } <ide> <ide> setScrollTopRow (scrollTopRow, scheduleUpdate = true) { <del> if (this.measurements) { <add> if (this.hasInitialMeasurements) { <ide> const didScroll = this.setScrollTop(this.pixelPositionBeforeBlocksForRow(scrollTopRow)) <ide> if (didScroll && scheduleUpdate) { <ide> this.scheduleUpdate() <ide> class TextEditorComponent { <ide> } <ide> <ide> getScrollTopRow () { <del> if (this.measurements) { <add> if (this.hasInitialMeasurements) { <ide> return this.rowForPixelPosition(this.getScrollTop()) <ide> } else { <ide> return this.pendingScrollTopRow || 0 <ide> } <ide> } <ide> <ide> setScrollLeftColumn (scrollLeftColumn, scheduleUpdate = true) { <del> if (this.measurements && this.getLongestLineWidth() != null) { <add> if (this.hasInitialMeasurements && this.getLongestLineWidth() != null) { <ide> const didScroll = this.setScrollLeft(scrollLeftColumn * this.getBaseCharacterWidth()) <ide> if (didScroll && scheduleUpdate) { <ide> this.scheduleUpdate() <ide> class TextEditorComponent { <ide> } <ide> <ide> getScrollLeftColumn () { <del> if (this.measurements) { <add> if (this.hasInitialMeasurements && this.getLongestLineWidth() != null) { <ide> return Math.floor(this.getScrollLeft() / this.getBaseCharacterWidth()) <ide> } else { <ide> return this.pendingScrollLeftColumn || 0 <ide> class GutterContainer { <ide> <ide> if (!rootComponent.props.model.isLineNumberGutterVisible()) return null <ide> <del> if (rootComponent.measurements) { <add> if (rootComponent.hasInitialMeasurements) { <ide> const {maxDigits, keys, bufferRows, softWrappedFlags, foldableFlags} = rootComponent.lineNumbersToRender <ide> return $(LineNumberGutterComponent, { <ide> ref: 'lineNumberGutter',
1
Javascript
Javascript
add some test cases for validateoffsetlengthwrite
a9d9d7689d326d363c8d9546a80ba76f4cd0decb
<ide><path>test/parallel/test-fs-util-validateoffsetlengthwrite.js <add>// Flags: --expose-internals <add>'use strict'; <add> <add>const common = require('../common'); <add> <add>const { validateOffsetLengthWrite } = require('internal/fs/utils'); <add>const { kMaxLength } = require('buffer'); <add> <add>// RangeError when offset > byteLength <add>{ <add> const offset = 100; <add> const length = 100; <add> const byteLength = 50; <add> common.expectsError( <add> () => validateOffsetLengthWrite(offset, length, byteLength), <add> { <add> code: 'ERR_OUT_OF_RANGE', <add> type: RangeError, <add> message: 'The value of "offset" is out of range. ' + <add> `It must be <= ${byteLength}. Received ${offset}` <add> } <add> ); <add>} <add> <add>// RangeError when byteLength > kMaxLength, and length > kMaxLength - offset . <add>{ <add> const offset = kMaxLength; <add> const length = 100; <add> const byteLength = kMaxLength + 1; <add> common.expectsError( <add> () => validateOffsetLengthWrite(offset, length, byteLength), <add> { <add> code: 'ERR_OUT_OF_RANGE', <add> type: RangeError, <add> message: 'The value of "length" is out of range. ' + <add> `It must be <= ${kMaxLength - offset}. Received ${length}` <add> } <add> ); <add>} <add> <add>// RangeError when byteLength < kMaxLength, and length > byteLength - offset . <add>{ <add> const offset = kMaxLength - 150; <add> const length = 200; <add> const byteLength = kMaxLength - 100; <add> common.expectsError( <add> () => validateOffsetLengthWrite(offset, length, byteLength), <add> { <add> code: 'ERR_OUT_OF_RANGE', <add> type: RangeError, <add> message: 'The value of "length" is out of range. ' + <add> `It must be <= ${byteLength - offset}. Received ${length}` <add> } <add> ); <add>}
1
Python
Python
add unicode declaration
e6f1a5d0a13df8bc84609682aaaade5166612218
<ide><path>spacy/en/lemmatizer/__init__.py <add># coding: utf8 <add>from __future__ import unicode_literals <ide> <ide> from .lookup import LOOKUP <ide> from ._adjectives import ADJECTIVES
1
Python
Python
improve histogram2d() example
2a86f356db2cb061b08be03813b77685dd149e2a
<ide><path>numpy/lib/twodim_base.py <ide> def histogram2d(x, y, bins=10, range=None, normed=False, weights=None): <ide> Construct a 2-D histogram with variable bin width. First define the bin <ide> edges: <ide> <del> >>> xedges = [0, 1, 1.5, 3, 5] <add> >>> xedges = [0, 1, 3, 5] <ide> >>> yedges = [0, 2, 3, 4, 6] <ide> <ide> Next we create a histogram H with random bin content: <ide> <del> >>> x = np.random.normal(3, 1, 100) <add> >>> x = np.random.normal(2, 1, 100) <ide> >>> y = np.random.normal(1, 1, 100) <del> >>> H, xedges, yedges = np.histogram2d(y, x, bins=(xedges, yedges)) <add> >>> H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges)) <add> >>> H = H.T # Let each row list bins with common y range. <ide> <del> Or we fill the histogram H with a determined bin content: <del> <del> >>> H = np.ones((4, 4)).cumsum().reshape(4, 4) <del> >>> print(H[::-1]) # This shows the bin content in the order as plotted <del> [[ 13. 14. 15. 16.] <del> [ 9. 10. 11. 12.] <del> [ 5. 6. 7. 8.] <del> [ 1. 2. 3. 4.]] <del> <del> Imshow can only do an equidistant representation of bins: <add> :func:`imshow <matplotlib.pyplot.imshow>` can only display square bins: <ide> <ide> >>> fig = plt.figure(figsize=(7, 3)) <del> >>> ax = fig.add_subplot(131) <del> >>> ax.set_title('imshow: equidistant') <del> >>> im = plt.imshow(H, interpolation='nearest', origin='low', <del> ... extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) <add> >>> ax = fig.add_subplot(131, title='imshow: square bins') <add> >>> plt.imshow(H, interpolation='nearest', origin='low', <add> ... extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) <ide> <del> pcolormesh can display exact bin edges: <add> :func:`pcolormesh <matplotlib.pyplot.pcolormesh>` can display actual edges: <ide> <del> >>> ax = fig.add_subplot(132) <del> >>> ax.set_title('pcolormesh: exact bin edges') <add> >>> ax = fig.add_subplot(132, title='pcolormesh: actual edges', <add> ... aspect='equal') <ide> >>> X, Y = np.meshgrid(xedges, yedges) <ide> >>> ax.pcolormesh(X, Y, H) <del> >>> ax.set_aspect('equal') <ide> <del> NonUniformImage displays exact bin edges with interpolation: <add> :class:`NonUniformImage <matplotlib.image.NonUniformImage>` can be used to <add> display actual bin edges with interpolation: <ide> <del> >>> ax = fig.add_subplot(133) <del> >>> ax.set_title('NonUniformImage: interpolated') <add> >>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated', <add> ... aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) <ide> >>> im = mpl.image.NonUniformImage(ax, interpolation='bilinear') <del> >>> xcenters = xedges[:-1] + 0.5 * (xedges[1:] - xedges[:-1]) <del> >>> ycenters = yedges[:-1] + 0.5 * (yedges[1:] - yedges[:-1]) <add> >>> xcenters = (xedges[:-1] + xedges[1:]) / 2 <add> >>> ycenters = (yedges[:-1] + yedges[1:]) / 2 <ide> >>> im.set_data(xcenters, ycenters, H) <ide> >>> ax.images.append(im) <del> >>> ax.set_xlim(xedges[0], xedges[-1]) <del> >>> ax.set_ylim(yedges[0], yedges[-1]) <del> >>> ax.set_aspect('equal') <ide> >>> plt.show() <ide> <ide> """
1
Text
Text
update the wording for 'pwa'
b7564a58866be83773c09a34a318e2e0f999884f
<ide><path>guide/chinese/progressive-web-apps/index.md <ide> localeTitle: 渐进式Web应用程序 <ide> --- <ide> ## 渐进式Web应用程序 <ide> <del>渐进式网络应用程序或“PWA”似乎不仅仅是一种时尚,而是一种从根本上不同的方式来处理网站可以和应该在您正在查看的任何平台上的内容。 <add>渐进式网络应用程序或“PWA”似乎不仅仅是一种时尚,而是用另一种不同的方式来处理网站,也可以查看任何平台上的内容。 <ide> <ide> PWA可以将部分自身安装到设备上以供离线查看,使用服务工作人员在连接可用时根据需要提供内容,最重要的是标准化移动和桌面设备之间的某些功能。 <ide> <ide> PWA的具体功能包括: <ide> ### 参考 <ide> <ide> 1. [拉塞尔,亚历克斯。 “渐进的网络应用程序:逃避标签而不会失去我们的灵魂”“不经常注意到”发布日期:2015年6月15日。](https://infrequently.org/2015/06/progressive-apps-escaping-tabs-without-losing-our-soul/) <del>2. [渐进式网络应用程序 - Google Developers](https://developers.google.com/web/progressive-web-apps/) <ide>\ No newline at end of file <add>2. [渐进式网络应用程序 - Google Developers](https://developers.google.com/web/progressive-web-apps/)
1
Python
Python
fix typo in stopwords (fixes #689)
5031a015e2b14b5795e01385613bf245d816741d
<ide><path>spacy/en/language_data.py <ide> cry de describe detail did didn do does doesn doing don done down due <ide> during each eg eight either eleven else elsewhere empty enough etc <ide> even ever every everyone everything everywhere except few fifteen <del>fify fill find fire first five for former formerly forty found four <add>fifty fill find fire first five for former formerly forty found four <ide> from front full further get give go had has hasnt have he hence her <ide> here hereafter hereby herein hereupon hers herself him himself his <ide> how however hundred i ie if in inc indeed interest into is it its
1
Javascript
Javascript
prefix boolean flags w/java conventions
01fc2a683a92ddf5d069a33eb92f6af2c37582c2
<ide><path>packages/ember-application/lib/system/application-instance.js <ide> let ApplicationInstance = EmberObject.extend(RegistryProxy, ContainerProxy, { <ide> <ide> registry.register('renderer:-dom', { <ide> create() { <del> return new Renderer(new DOMHelper(options.document), options.interactive); <add> return new Renderer(new DOMHelper(options.document), options.isInteractive); <ide> } <ide> }); <ide> <ide> let ApplicationInstance = EmberObject.extend(RegistryProxy, ContainerProxy, { <ide> <ide> this.application.runInstanceInitializers(this); <ide> <del> if (options.interactive) { <add> if (options.isInteractive) { <ide> this.setupEventDispatcher(); <ide> } <ide> } else { <ide> if (isEnabled('ember-application-visit')) { <ide> @default auto-detected <ide> @private <ide> */ <del> this.jQuery = jQuery; <add> this.jQuery = jQuery; // This default is overridable below <ide> <ide> /** <ide> Interactive mode: whether we need to set up event delegation and invoke <ide> lifecycle callbacks on Components. <ide> <del> @property interactive <add> @property isInteractive <ide> @type boolean <ide> @default auto-detected <ide> @private <ide> */ <del> this.interactive = environment.hasDOM; <add> this.isInteractive = environment.hasDOM; // This default is overridable below <ide> <ide> /** <ide> Run in a full browser environment. <ide> if (isEnabled('ember-application-visit')) { <ide> the location adapter specified in the app's router instead, you can also <ide> specify `{ location: null }` to specifically opt-out.) <ide> <del> @property browser <add> @property isBrowser <ide> @type boolean <ide> @default auto-detected <ide> @public <ide> */ <del> if (options.browser !== undefined) { <del> this.browser = !!options.browser; <add> if (options.isBrowser !== undefined) { <add> this.isBrowser = !!options.isBrowser; <ide> } else { <del> this.browser = environment.hasDOM; <add> this.isBrowser = environment.hasDOM; <ide> } <ide> <del> if (!this.browser) { <add> if (!this.isBrowser) { <ide> this.jQuery = null; <del> this.interactive = false; <add> this.isInteractive = false; <ide> this.location = 'none'; <ide> } <ide> <ide> if (isEnabled('ember-application-visit')) { <ide> pipeline. Essentially, this puts the app into "routing-only" mode. No <ide> templates will be rendered, and no Components will be created. <ide> <del> @property render <add> @property shouldRender <ide> @type boolean <ide> @default true <ide> @public <ide> */ <del> if (options.render !== undefined) { <del> this.render = !!options.render; <add> if (options.shouldRender !== undefined) { <add> this.shouldRender = !!options.shouldRender; <ide> } else { <del> this.render = true; <add> this.shouldRender = true; <ide> } <ide> <del> if (!this.render) { <add> if (!this.shouldRender) { <ide> this.jQuery = null; <del> this.interactive = false; <add> this.isInteractive = false; <ide> } <ide> <ide> /** <ide> if (isEnabled('ember-application-visit')) { <ide> this.rootElement = options.rootElement; <ide> } <ide> <add> // Set these options last to give the user a chance to override the <add> // defaults from the "combo" options like `isBrowser` (although in <add> // practice, the resulting combination is probably invalid) <add> <ide> /** <ide> If present, overrides the router's `location` property with this <ide> value. This is useful for environments where trying to modify the <ide> if (isEnabled('ember-application-visit')) { <ide> this.jQuery = options.jQuery; <ide> } <ide> <del> if (options.interactive !== undefined) { <del> this.interactive = !!options.interactive; <add> if (options.isInteractive !== undefined) { <add> this.isInteractive = !!options.isInteractive; <ide> } <ide> }; <ide> <ide><path>packages/ember-application/lib/system/application.js <ide> var Application = Namespace.extend(RegistryProxy, { <ide> } else { <ide> // Force-assign these flags to their default values when the feature is <ide> // disabled, this ensures we can rely on their values in other paths. <del> this.autoboot = true; <del> this._globalsMode = true; <add> this.autoboot = this._globalsMode = true; <ide> } <ide> <ide> if (this._globalsMode) { <ide> if (isEnabled('ember-application-visit')) { <ide> MyApp.visit("/", { location: "none", rootElement: "#container" }); <ide> ``` <ide> <del> All options are optional. <del> <ide> ### Supported Scenarios <ide> <ide> While the `BootOptions` class exposes a large number of knobs, not all <ide> combinations of them are valid; certain incompatible combinations might <ide> result in unexpected behavior. <ide> <ide> For example, booting the instance in the full browser environment <del> while specifying a foriegn `document` object (e.g. <del> `{ browser: true, document: iframe.contentDocument }`) does not work <del> correctly today, largely due to Ember's jQuery dependency. <add> while specifying a foriegn `document` object (e.g. `{ isBrowser: true, <add> document: iframe.contentDocument }`) does not work correctly today, <add> largely due to Ember's jQuery dependency. <ide> <ide> Currently, there are three officially supported scenarios/configurations. <ide> Usages outside of these scenarios are not guaranteed to work, but please <ide> if (isEnabled('ember-application-visit')) { <ide> let sessionId = MyApp.generateSessionID(); <ide> <ide> let player1 = App.visit(`/matches/join?name=Player+1&session=${sessionId}`, { rootElement: '#left', location: 'none' }); <del> let player2 = App.visit(`/matches/join?name=Player+2&session=${sessionId}`, { rootElement: '#left', location: 'none' }); <add> let player2 = App.visit(`/matches/join?name=Player+2&session=${sessionId}`, { rootElement: '#right', location: 'none' }); <ide> <ide> Promise.all([player1, player2]).then(() => { <ide> // Both apps have completed the initial render <ide> if (isEnabled('ember-application-visit')) { <ide> function renderURL(url) { <ide> let dom = new SimpleDOM.Document(); <ide> let rootElement = dom.body; <del> let options = { browser: false, document: dom, rootElement: rootElement }; <add> let options = { isBrowser: false, document: dom, rootElement: rootElement }; <ide> <ide> return MyApp.visit(options).then(instance => { <ide> try { <ide> if (isEnabled('ember-application-visit')) { <ide> specify a DOM `Element` object in the same `document` for the `rootElement` option <ide> (as opposed to a selector string like `"body"`). <ide> <del> See the documentation on the `browser`, `document` and `rootElement` properties <add> See the documentation on the `isBrowser`, `document` and `rootElement` properties <ide> on `Ember.ApplicationInstance.BootOptions` for details. <ide> <ide> #### Server-Side Resource Discovery <ide> if (isEnabled('ember-application-visit')) { <ide> import BrowserNetworkService from 'app/services/network/browser'; <ide> import NodeNetworkService from 'app/services/network/node'; <ide> <add> // Inject a (hypothetical) service for abstracting all AJAX calls and use <add> // the appropiate implementaion on the client/server. This also allows the <add> // server to log all the AJAX calls made during a particular request and use <add> // that for resource-discovery purpose. <add> <ide> export function initialize(application) { <ide> if (window) { // browser <ide> application.register('service:network', BrowserNetworkService); <ide> if (isEnabled('ember-application-visit')) { <ide> ``` <ide> <ide> ```app/routes/post.js <add> import Ember from 'ember'; <add> <add> // An example of how the (hypothetical) service is used in routes. <add> <ide> export default Ember.Route.extend({ <ide> model(params) { <ide> return this.network.fetch(`/api/posts/${params.post_id}.json`); <ide> if (isEnabled('ember-application-visit')) { <ide> ``` <ide> <ide> ```javascript <add> // Finally, put all the pieces together <add> <ide> function discoverResourcesFor(url) { <del> return MyApp.visit(options).then(instance => { <add> return MyApp.visit(url, { isBrowser: false, shouldRender: false }).then(instance => { <ide> let networkService = instance.lookup('service:network'); <ide> return networkService.requests; // => { "/api/posts/123.json": "..." } <ide> }); <ide><path>packages/ember-application/tests/system/visit_test.js <ide> if (isEnabled('ember-application-visit')) { <ide> let a = run(function() { <ide> let dom = makeFakeDom(); <ide> <del> return App.visit('/a', { browser: false, document: dom, rootElement: dom.body }).then(instance => { <add> return App.visit('/a', { isBrowser: false, document: dom, rootElement: dom.body }).then(instance => { <ide> QUnit.start(); <ide> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance'); <ide> assert.equal(instance.getURL(), '/a'); <ide> if (isEnabled('ember-application-visit')) { <ide> let b = run(function() { <ide> let dom = makeFakeDom(); <ide> <del> return App.visit('/b', { browser: false, document: dom, rootElement: dom.body }).then(instance => { <add> return App.visit('/b', { isBrowser: false, document: dom, rootElement: dom.body }).then(instance => { <ide> QUnit.start(); <ide> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance'); <ide> assert.equal(instance.getURL(), '/b'); <ide> if (isEnabled('ember-application-visit')) { <ide> } <ide> <ide> let a = run(function() { <del> return App.visit('/a', { browser: false, render: false }).then((instance) => { <add> return App.visit('/a', { isBrowser: false, shouldRender: false }).then((instance) => { <ide> QUnit.start(); <ide> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance'); <ide> <ide> if (isEnabled('ember-application-visit')) { <ide> }); <ide> <ide> let b = run(function() { <del> return App.visit('/b', { browser: false, render: false }).then((instance) => { <add> return App.visit('/b', { isBrowser: false, shouldRender: false }).then((instance) => { <ide> QUnit.start(); <ide> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance'); <ide> <ide> if (isEnabled('ember-application-visit')) { <ide> }); <ide> <ide> let c = run(function() { <del> return App.visit('/c', { browser: false, render: false }).then((instance) => { <add> return App.visit('/c', { isBrowser: false, shouldRender: false }).then((instance) => { <ide> QUnit.start(); <ide> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance'); <ide> <ide> if (isEnabled('ember-application-visit')) { <ide> }); <ide> <ide> let d = run(function() { <del> return App.visit('/d', { browser: false, render: false }).then((instance) => { <add> return App.visit('/d', { isBrowser: false, shouldRender: false }).then((instance) => { <ide> QUnit.start(); <ide> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance'); <ide> <ide> if (isEnabled('ember-application-visit')) { <ide> }); <ide> <ide> let e = run(function() { <del> return App.visit('/e', { browser: false, render: false }).then((instance) => { <add> return App.visit('/e', { isBrowser: false, shouldRender: false }).then((instance) => { <ide> QUnit.start(); <ide> assert.ok(instance instanceof ApplicationInstance, 'promise is resolved with an ApplicationInstance'); <ide> <ide><path>packages/ember-routing/lib/system/route.js <ide> var Route = EmberObject.extend(ActionHandler, Evented, { <ide> this.setupController(controller, context, transition); <ide> <ide> if (isEnabled('ember-application-visit')) { <del> if (!this._environment || this._environment.options.render) { <add> if (!this._environment || this._environment.options.shouldRender) { <ide> this.renderTemplate(controller, context); <ide> } <ide> } else {
4
Javascript
Javascript
remove defaultprops from flatlist
7d5895df4e3c57ebfa1c146cadc989497b006623
<ide><path>Libraries/Lists/FlatList.js <ide> type OptionalProps<ItemT> = {| <ide> /** <ide> * Multiple columns can only be rendered with `horizontal={false}` and will zig-zag like a <ide> * `flexWrap` layout. Items should all be the same height - masonry layouts are not supported. <add> * <add> * The default value is 1. <ide> */ <del> numColumns: number, <add> numColumns?: number, <add> /** <add> * Note: may have bugs (missing content) in some circumstances - use at your own risk. <add> * <add> * This may improve scroll performance for large lists. <add> * <add> * The default value is true for Android. <add> */ <add> removeClippedSubviews?: boolean, <ide> /** <ide> * See `ScrollView` for flow type and further documentation. <ide> */ <ide> fadingEdgeLength?: ?number, <ide> |}; <ide> <add>/** <add> * Default Props Helper Functions <add> * Use the following helper functions for default values <add> */ <add> <add>// removeClippedSubviewsOrDefault(this.props.removeClippedSubviews) <add>function removeClippedSubviewsOrDefault(removeClippedSubviews: ?boolean) { <add> return removeClippedSubviews ?? Platform.OS === 'android'; <add>} <add> <add>// numColumnsOrDefault(this.props.numColumns) <add>function numColumnsOrDefault(numColumns: ?number) { <add> return numColumns ?? 1; <add>} <add> <ide> type FlatListProps<ItemT> = {| <ide> ...RequiredProps<ItemT>, <ide> ...OptionalProps<ItemT>, <ide> export type Props<ItemT> = { <ide> ... <ide> }; <ide> <del>const defaultProps = { <del> numColumns: 1, <del> /** <del> * Enabling this prop on Android greatly improves scrolling performance with no known issues. <del> * The alternative is that scrolling on Android is unusably bad. Enabling it on iOS has a few <del> * known issues. <del> */ <del> removeClippedSubviews: Platform.OS === 'android', <del>}; <del>export type DefaultProps = typeof defaultProps; <del> <ide> /** <ide> * A performant interface for rendering simple, flat lists, supporting the most handy features: <ide> * <ide> export type DefaultProps = typeof defaultProps; <ide> * Also inherits [ScrollView Props](docs/scrollview.html#props), unless it is nested in another FlatList of same orientation. <ide> */ <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <del> static defaultProps: DefaultProps = defaultProps; <ide> props: Props<ItemT>; <ide> /** <ide> * Scrolls to the end of the content. May be janky without `getItemLayout` prop. <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> // $FlowFixMe[prop-missing] this prop doesn't exist, is only used for an invariant <ide> getItemCount, <ide> horizontal, <del> numColumns, <ide> columnWrapperStyle, <ide> onViewableItemsChanged, <ide> viewabilityConfigCallbackPairs, <ide> } = props; <add> const numColumns = numColumnsOrDefault(this.props.numColumns); <ide> invariant( <ide> !getItem && !getItemCount, <ide> 'FlatList does not support custom data formats.', <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> } <ide> <ide> _getItem = (data: Array<ItemT>, index: number) => { <del> const {numColumns} = this.props; <add> const numColumns = numColumnsOrDefault(this.props.numColumns); <ide> if (numColumns > 1) { <ide> const ret = []; <ide> for (let kk = 0; kk < numColumns; kk++) { <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> <ide> _getItemCount = (data: ?Array<ItemT>): number => { <ide> if (data) { <del> const {numColumns} = this.props; <add> const numColumns = numColumnsOrDefault(this.props.numColumns); <ide> return numColumns > 1 ? Math.ceil(data.length / numColumns) : data.length; <ide> } else { <ide> return 0; <ide> } <ide> }; <ide> <ide> _keyExtractor = (items: ItemT | Array<ItemT>, index: number) => { <del> const {numColumns} = this.props; <add> const numColumns = numColumnsOrDefault(this.props.numColumns); <ide> const keyExtractor = this.props.keyExtractor ?? defaultKeyExtractor; <ide> <ide> if (numColumns > 1) { <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> }; <ide> <ide> _pushMultiColumnViewable(arr: Array<ViewToken>, v: ViewToken): void { <del> const {numColumns} = this.props; <add> const numColumns = numColumnsOrDefault(this.props.numColumns); <ide> const keyExtractor = this.props.keyExtractor ?? defaultKeyExtractor; <ide> v.item.forEach((item, ii) => { <ide> invariant(v.index != null, 'Missing index!'); <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> changed: Array<ViewToken>, <ide> ... <ide> }) => { <del> const {numColumns} = this.props; <add> const numColumns = numColumnsOrDefault(this.props.numColumns); <ide> if (onViewableItemsChanged) { <ide> if (numColumns > 1) { <ide> const changed = []; <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> } <ide> <ide> _renderer = () => { <del> const { <del> ListItemComponent, <del> renderItem, <del> numColumns, <del> columnWrapperStyle, <del> } = this.props; <add> const {ListItemComponent, renderItem, columnWrapperStyle} = this.props; <add> const numColumns = numColumnsOrDefault(this.props.numColumns); <ide> <ide> let virtualizedListRenderKey = ListItemComponent <ide> ? 'ListItemComponent' <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> }; <ide> <ide> render(): React.Node { <del> const {numColumns, columnWrapperStyle, ...restProps} = this.props; <add> const { <add> numColumns, <add> columnWrapperStyle, <add> removeClippedSubviews: _removeClippedSubviews, <add> ...restProps <add> } = this.props; <ide> <ide> return ( <ide> <VirtualizedList <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> keyExtractor={this._keyExtractor} <ide> ref={this._captureRef} <ide> viewabilityConfigCallbackPairs={this._virtualizedListPairs} <add> removeClippedSubviews={removeClippedSubviewsOrDefault( <add> _removeClippedSubviews, <add> )} <ide> {...this._renderer()} <ide> /> <ide> );
1
Go
Go
change the base filesystem size in unit tests
48070274ee93bf0d4cef7486a4ec19c4d97ac9ce
<ide><path>runtime_test.go <ide> func cleanupDevMapper() { <ide> <ide> func init() { <ide> os.Setenv("TEST", "1") <add> os.Setenv("DOCKER_LOOPBACK_DATA_SIZE", "209715200") // 200MB <add> os.Setenv("DOCKER_LOOPBACK_META_SIZE", "104857600") // 100MB <add> os.Setenv("DOCKER_BASE_FS_SIZE", "157286400") // 150MB <ide> <ide> // Hack to run sys init during unit testing <ide> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || selfPath == "/.dockerinit" {
1
Ruby
Ruby
fix a subtle bug involving rails_root
8baba5f13ea67f62d78318490f833e43c9674664
<ide><path>railties/lib/rails/deprecation.rb <ide> def initialize(old, new) <ide> def method_missing(meth, *args, &block) <ide> ActiveSupport::Deprecation.warn("#{@old} is deprecated. Please use #{@new}") unless @warned <ide> @warned = true <del> @target.call.send(meth, *args, &block) <add> <add> target = @target.call <add> if target.respond_to?(meth) <add> target.send(meth, *args, &block) <add> else <add> super <add> end <ide> end <ide> end <ide> <del> DeprecatedConstant.deprecate("RAILS_ROOT", "Rails.root") <add> DeprecatedConstant.deprecate("RAILS_ROOT", "Rails.root.to_s") <ide> DeprecatedConstant.deprecate("RAILS_ENV", "Rails.env") <ide> DeprecatedConstant.deprecate("RAILS_DEFAULT_LOGGER", "Rails.logger") <ide> end
1
Ruby
Ruby
log streaming downloads
e03add224899e0a10e7cfa28c09e68c8b9c920ed
<ide><path>activestorage/lib/active_storage/log_subscriber.rb <ide> def service_download(event) <ide> info event, color("Downloaded file from key: #{key_in(event)}", BLUE) <ide> end <ide> <add> alias_method :service_streaming_download, :service_download <add> <ide> def service_delete(event) <ide> info event, color("Deleted file from key: #{key_in(event)}", RED) <ide> end
1
Python
Python
open src and dst in binary for samba copy
63ca12c0f2b4b6db1c46dd55405f7055dcb1c02c
<ide><path>airflow/providers/samba/hooks/samba.py <ide> def setxattr(self, path, attribute, value, flags=0, follow_symlinks=True): <ide> <ide> def push_from_local(self, destination_filepath: str, local_filepath: str): <ide> """Push local file to samba server""" <del> with open(local_filepath, "rb") as f, self.open_file(destination_filepath, mode="w") as g: <add> with open(local_filepath, "rb") as f, self.open_file(destination_filepath, mode="wb") as g: <ide> copyfileobj(f, g)
1
Javascript
Javascript
build three.js with cinematiccamera
2321132bf8fccb1b93e7df1053352191810b31db
<ide><path>build/three.js <ide> THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) { <ide> * @author mrdoob / http://mrdoob.com/ <ide> * @author greggman / http://games.greggman.com/ <ide> * @author zz85 / http://www.lab4games.net/zz85/blog <del> * @author kaypikun <add> * @author kaypiKun <ide> */ <ide> <ide> //Inheriting PerspectiveCamera <ide><path>src/cameras/CinematicCamera.js <ide> * @author mrdoob / http://mrdoob.com/ <ide> * @author greggman / http://games.greggman.com/ <ide> * @author zz85 / http://www.lab4games.net/zz85/blog <del> * @author kaypikun <add> * @author kaypiKun <ide> */ <ide> <ide> //Inheriting PerspectiveCamera
2
Javascript
Javascript
prevent aspect from affecting rotate speed
1b56759e45641e6cf5c635c48406435de8fd25e5
<ide><path>examples/js/controls/OrbitControls.js <ide> THREE.OrbitControls = function ( object, domElement ) { <ide> <ide> var element = scope.domElement === document ? scope.domElement.body : scope.domElement; <ide> <del> // rotating across whole screen goes 360 degrees around <del> rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth ); <add> rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height <ide> <del> // rotating up and down along whole screen attempts to go 360, but limited to 180 <ide> rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); <ide> <ide> rotateStart.copy( rotateEnd ); <ide> THREE.OrbitControls = function ( object, domElement ) { <ide> <ide> var element = scope.domElement === document ? scope.domElement.body : scope.domElement; <ide> <del> // rotating across whole screen goes 360 degrees around <del> rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientWidth ); <add> rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height <ide> <del> // rotating up and down along whole screen attempts to go 360, but limited to 180 <ide> rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight ); <ide> <ide> rotateStart.copy( rotateEnd );
1
Python
Python
use primarykeyrelatedfield pkfield in openapi
b79099f7baf104336bfe7fff7a8c57bc451a8d96
<ide><path>rest_framework/schemas/openapi.py <ide> def map_field(self, field): <ide> 'items': self.map_field(field.child_relation) <ide> } <ide> if isinstance(field, serializers.PrimaryKeyRelatedField): <add> if getattr(field, "pk_field", False): <add> return self.map_field(field=field.pk_field) <ide> model = getattr(field.queryset, 'model', None) <ide> if model is not None: <ide> model_field = model._meta.pk <ide><path>tests/schemas/test_openapi.py <ide> from rest_framework.request import Request <ide> from rest_framework.schemas.openapi import AutoSchema, SchemaGenerator <ide> <add>from ..models import BasicModel <ide> from . import views <ide> <ide> <ide> class Meta: <ide> assert data['properties']['ro_field']['nullable'], "ro_field nullable must be true" <ide> assert data['properties']['ro_field']['readOnly'], "ro_field read_only must be true" <ide> <add> def test_primary_key_related_field(self): <add> class PrimaryKeyRelatedFieldSerializer(serializers.Serializer): <add> basic = serializers.PrimaryKeyRelatedField(queryset=BasicModel.objects.all()) <add> uuid = serializers.PrimaryKeyRelatedField(queryset=BasicModel.objects.all(), <add> pk_field=serializers.UUIDField()) <add> char = serializers.PrimaryKeyRelatedField(queryset=BasicModel.objects.all(), <add> pk_field=serializers.CharField()) <add> <add> serializer = PrimaryKeyRelatedFieldSerializer() <add> inspector = AutoSchema() <add> <add> data = inspector.map_serializer(serializer=serializer) <add> assert data['properties']['basic']['type'] == "integer" <add> assert data['properties']['uuid']['format'] == "uuid" <add> assert data['properties']['char']['type'] == "string" <add> <ide> <ide> @pytest.mark.skipif(uritemplate is None, reason='uritemplate not installed.') <ide> class TestOperationIntrospection(TestCase):
2
Javascript
Javascript
modernize js and tighten equality checking
759cf172280e8ce449a53e97f554fcd8e96e1de2
<ide><path>test/parallel/test-net-binary.js <ide> /* eslint-disable strict */ <ide> require('../common'); <del>var assert = require('assert'); <del>var net = require('net'); <add>const assert = require('assert'); <add>const net = require('net'); <ide> <ide> var binaryString = ''; <ide> for (var i = 255; i >= 0; i--) { <del> var s = '\'\\' + i.toString(8) + '\''; <del> var S = eval(s); <del> assert.ok(S.charCodeAt(0) == i); <del> assert.ok(S == String.fromCharCode(i)); <add> const s = `'\\${i.toString(8)}'`; <add> const S = eval(s); <add> assert.strictEqual(S.charCodeAt(0), i); <add> assert.strictEqual(S, String.fromCharCode(i)); <ide> binaryString += S; <ide> } <ide> <ide> var recv = ''; <ide> <ide> echoServer.on('listening', function() { <ide> var j = 0; <del> var c = net.createConnection({ <add> const c = net.createConnection({ <ide> port: this.address().port <ide> }); <ide> <ide> c.setEncoding('latin1'); <ide> c.on('data', function(chunk) { <del> var n = j + chunk.length; <add> const n = j + chunk.length; <ide> while (j < n && j < 256) { <ide> c.write(String.fromCharCode(j), 'latin1'); <ide> j++; <ide> echoServer.on('listening', function() { <ide> process.on('exit', function() { <ide> assert.equal(2 * 256, recv.length); <ide> <del> var a = recv.split(''); <add> const a = recv.split(''); <ide> <del> var first = a.slice(0, 256).reverse().join(''); <add> const first = a.slice(0, 256).reverse().join(''); <ide> <del> var second = a.slice(256, 2 * 256).join(''); <add> const second = a.slice(256, 2 * 256).join(''); <ide> <del> assert.equal(first, second); <add> assert.strictEqual(first, second); <ide> });
1
PHP
PHP
fix zero parameter for routes
910cc7473c0772032a8ac4fedb27e695ee69f9f0
<ide><path>src/Illuminate/Routing/RouteUrlGenerator.php <ide> protected function replaceRouteParameters($path, array &$parameters) <ide> protected function replaceNamedParameters($path, &$parameters) <ide> { <ide> return preg_replace_callback('/\{(.*?)(\?)?\}/', function ($m) use (&$parameters) { <del> if (isset($parameters[$m[1]]) && $parameters[$m[1]] != '') { <add> if (isset($parameters[$m[1]]) && $parameters[$m[1]] !== '') { <ide> return Arr::pull($parameters, $m[1]); <ide> } elseif (isset($this->defaultParameters[$m[1]])) { <ide> return $this->defaultParameters[$m[1]]; <ide><path>tests/Routing/RoutingUrlGeneratorTest.php <ide> public function testBasicRouteGeneration() <ide> $this->assertSame('/foo/bar?foo=bar', $url->route('foo', ['foo' => 'bar'], false)); <ide> $this->assertSame('http://www.foo.com/foo/bar/taylor/breeze/otwell?fly=wall', $url->route('bar', ['taylor', 'otwell', 'fly' => 'wall'])); <ide> $this->assertSame('http://www.foo.com/foo/bar/otwell/breeze/taylor?fly=wall', $url->route('bar', ['boom' => 'taylor', 'baz' => 'otwell', 'fly' => 'wall'])); <add> $this->assertSame('http://www.foo.com/foo/bar/0', $url->route('foobar', 0)); <ide> $this->assertSame('http://www.foo.com/foo/bar/2', $url->route('foobar', 2)); <ide> $this->assertSame('http://www.foo.com/foo/bar/taylor', $url->route('foobar', 'taylor')); <ide> $this->assertSame('/foo/bar/taylor/breeze/otwell?fly=wall', $url->route('bar', ['taylor', 'otwell', 'fly' => 'wall'], false)); <ide> public function testBasicRouteGeneration() <ide> $this->assertSame('http://www.foo.com/foo/bar', $url->route('optional')); <ide> $this->assertSame('http://www.foo.com/foo/bar', $url->route('optional', ['baz' => null])); <ide> $this->assertSame('http://www.foo.com/foo/bar', $url->route('optional', ['baz' => ''])); <add> $this->assertSame('http://www.foo.com/foo/bar/0', $url->route('optional', ['baz' => 0])); <ide> $this->assertSame('http://www.foo.com/foo/bar/taylor', $url->route('optional', 'taylor')); <ide> $this->assertSame('http://www.foo.com/foo/bar/taylor', $url->route('optional', ['taylor'])); <ide> $this->assertSame('http://www.foo.com/foo/bar/taylor?breeze', $url->route('optional', ['taylor', 'breeze']));
2
Java
Java
fix protobufdecoder handling of split message size
91de8d265e332ba378f191105592190d4f90bb48
<ide><path>spring-web/src/main/java/org/springframework/http/codec/protobuf/ProtobufDecoder.java <ide> private class MessageDecoderFunction implements Function<DataBuffer, Iterable<? <ide> <ide> private int messageBytesToRead; <ide> <add> private int offset; <add> <ide> <ide> public MessageDecoderFunction(ResolvableType elementType, int maxMessageSize) { <ide> this.elementType = elementType; <ide> public Iterable<? extends Message> apply(DataBuffer input) { <ide> <ide> do { <ide> if (this.output == null) { <del> int firstByte = input.read(); <del> if (firstByte == -1) { <del> throw new DecodingException("Cannot parse message size"); <add> if (!readMessageSize(input)) { <add> return messages; <ide> } <del> this.messageBytesToRead = CodedInputStream.readRawVarint32(firstByte, input.asInputStream()); <ide> if (this.messageBytesToRead > this.maxMessageSize) { <ide> throw new DecodingException( <ide> "The number of bytes to read from the incoming stream " + <ide> public Iterable<? extends Message> apply(DataBuffer input) { <ide> DataBufferUtils.release(input); <ide> } <ide> } <add> <add> /** <add> * Parse message size as a varint from the input stream, updating {@code messageBytesToRead} and <add> * {@code offset} fields if needed to allow processing of upcoming chunks. <add> * Inspired from {@link CodedInputStream#readRawVarint32(int, java.io.InputStream)} <add> * <add> * @return {code true} when the message size is parsed successfully, {code false} when the message size is <add> * truncated <add> * @see <a href ="https://developers.google.com/protocol-buffers/docs/encoding#varints">Base 128 Varints</a> <add> */ <add> private boolean readMessageSize(DataBuffer input) { <add> if (this.offset == 0) { <add> if (input.readableByteCount() == 0) { <add> return false; <add> } <add> int firstByte = input.read(); <add> if ((firstByte & 0x80) == 0) { <add> this.messageBytesToRead = firstByte; <add> return true; <add> } <add> this.messageBytesToRead = firstByte & 0x7f; <add> this.offset = 7; <add> } <add> <add> if (this.offset < 32) { <add> for (; this.offset < 32; this.offset += 7) { <add> if (input.readableByteCount() == 0) { <add> return false; <add> } <add> final int b = input.read(); <add> this.messageBytesToRead |= (b & 0x7f) << offset; <add> if ((b & 0x80) == 0) { <add> this.offset = 0; <add> return true; <add> } <add> } <add> } <add> // Keep reading up to 64 bits. <add> for (; this.offset < 64; this.offset += 7) { <add> if (input.readableByteCount() == 0) { <add> return false; <add> } <add> final int b = input.read(); <add> if ((b & 0x80) == 0) { <add> this.offset = 0; <add> return true; <add> } <add> } <add> this.offset = 0; <add> throw new DecodingException("Cannot parse message size: malformed varint"); <add> } <ide> } <ide> <ide> } <ide><path>spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java <ide> public void decode() { <ide> } <ide> <ide> @Test <del> public void decodeSplitChunks() throws IOException { <add> public void decodeSplitChunks() { <add> <add> <ide> Flux<DataBuffer> input = Flux.just(this.testMsg1, this.testMsg2) <ide> .flatMap(msg -> Mono.defer(() -> { <ide> DataBuffer buffer = this.bufferFactory.allocateBuffer(); <ide> public void decodeSplitChunks() throws IOException { <ide> .verifyComplete()); <ide> } <ide> <add> @Test // SPR-17429 <add> public void decodeSplitMessageSize() { <add> this.decoder.setMaxMessageSize(100009); <add> StringBuilder builder = new StringBuilder(); <add> for (int i = 0; i < 10000; i++) { <add> builder.append("azertyuiop"); <add> } <add> Msg bigMessage = Msg.newBuilder().setFoo(builder.toString()).setBlah(secondMsg2).build(); <add> <add> Flux<DataBuffer> input = Flux.just(bigMessage, bigMessage) <add> .flatMap(msg -> Mono.defer(() -> { <add> DataBuffer buffer = this.bufferFactory.allocateBuffer(); <add> try { <add> msg.writeDelimitedTo(buffer.asOutputStream()); <add> return Mono.just(buffer); <add> } <add> catch (IOException e) { <add> release(buffer); <add> return Mono.error(e); <add> } <add> })) <add> .flatMap(buffer -> { <add> int len = 2; <add> Flux<DataBuffer> result = Flux.just( <add> DataBufferUtils.retain(buffer.slice(0, len)), <add> DataBufferUtils <add> .retain(buffer.slice(len, buffer.readableByteCount() - len)) <add> ); <add> release(buffer); <add> return result; <add> }); <add> <add> testDecode(input, Msg.class, step -> step <add> .expectNext(bigMessage) <add> .expectNext(bigMessage) <add> .verifyComplete()); <add> } <add> <ide> @Test <ide> public void decodeMergedChunks() throws IOException { <ide> DataBuffer buffer = this.bufferFactory.allocateBuffer();
2
Javascript
Javascript
add types to environmentplugin
2d9db1a1f633610b5df6afdbe5455f9ba9274965
<ide><path>lib/EnvironmentPlugin.js <ide> <ide> "use strict"; <ide> <add>/** @typedef {import("./Compiler")} Compiler */ <add> <add>const WebpackError = require("./WebpackError"); <ide> const DefinePlugin = require("./DefinePlugin"); <ide> <ide> const needsEnvVarFix = <ide> class EnvironmentPlugin { <ide> } <ide> } <ide> <add> /** <add> * @param {Compiler} compiler webpack compiler instance <add> * @returns {void} <add> */ <ide> apply(compiler) { <ide> const definitions = this.keys.reduce((defs, key) => { <ide> // TODO remove once the fix has made its way into Node 8. <ide> class EnvironmentPlugin { <ide> <ide> if (value === undefined) { <ide> compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => { <del> const error = new Error( <add> const error = new WebpackError( <ide> `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` + <ide> "You can pass an object with default values to suppress this warning.\n" + <ide> "See https://webpack.js.org/plugins/environment-plugin for example."
1
Python
Python
unbreak non-linux platforms
075ba72d79c6fb1a7b5f51e731273f4ddde1e35c
<ide><path>unitest-restful.py <ide> import requests <ide> import json <ide> <del>from glances.core.glances_globals import ( <del> appname, <del> is_linux, <del> version <del>) <add>from glances.core.glances_globals import version <ide> <ide> SERVER_PORT = 61234 <ide> URL = "http://localhost:%s/api/2" % SERVER_PORT <ide> # Global variables <ide> # ================= <ide> <del># Unitary test is only available from a GNU/Linus machine <del>if not is_linux: <del> print( <del> 'ERROR: RESTFul API unitaries tests should be ran on GNU/Linux operating system') <del> sys.exit(2) <del>else: <del> print('Unitary tests for {0} {1}'.format(appname, version)) <del> <ide> # Init Glances core <ide> from glances.core.glances_main import GlancesMain <ide> core = GlancesMain() <ide> <ide> # Unitest class <ide> # ============== <add>print('RESTful API unitary tests for Glances %s' % version) <add> <ide> <ide> class TestGlances(unittest.TestCase): <ide> <ide> def test_000_start_server(self): <ide> <ide> global pid <ide> <del> cmdline = "/usr/bin/env python -m glances -w -p %s" % SERVER_PORT <add> cmdline = "python -m glances -w -p %s" % SERVER_PORT <ide> print("Run the Glances Web Server on port %s" % SERVER_PORT) <ide> args = shlex.split(cmdline) <ide> pid = subprocess.Popen(args)
1
Javascript
Javascript
keep existing properties in object.userdata
d7a2400097fc9c9698641839e97020d09a8f0134
<ide><path>examples/js/loaders/GLTFLoader.js <ide> THREE.GLTFLoader = ( function () { <ide> <ide> if ( typeof gltfDef.extras === 'object' ) { <ide> <del> object.userData = gltfDef.extras; <add> object.userData = Object.assign(object.userData, gltfDef.extras); <ide> <ide> } else { <ide>
1
Java
Java
update stomp support to reactor-netty 0.6
2802926c1dae64c1ec067effb4d22c616e1183ba
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/ReactorNettyTcpConnection.java <ide> public ReactorNettyTcpConnection(NettyInbound inbound, NettyOutbound outbound, <ide> <ide> @Override <ide> public ListenableFuture<Void> send(Message<P> message) { <del> ByteBuf byteBuf = this.inbound.alloc() <del> .buffer(); <add> ByteBuf byteBuf = this.outbound.alloc() <add> .buffer(); <ide> this.encoder.accept(byteBuf, message); <del> return new MonoToListenableFutureAdapter<>(this.outbound.send(Mono.just(byteBuf) <del> .then())); <add> return new MonoToListenableFutureAdapter<>(this.outbound.send(Mono.just(byteBuf)) <add> .then()); <ide> } <ide> <ide> @Override
1
Python
Python
fix mypy violations
c31902e11abbafa316ffd4151083701aae3e41a1
<ide><path>libcloud/compute/base.py <ide> ) <ide> else: <ide> SSH_TIMEOUT_EXCEPTION_CLASSES = ( <del> IOError, <add> IOError, # type: ignore <ide> socket.gaierror, # type: ignore <ide> socket.error, <ide> ) # type: ignore
1
PHP
PHP
apply fixes from styleci
23f0c68b392613587b263b00b64476c9ba8d9dcc
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php <ide> protected function invalidJson($request, ValidationException $exception) <ide> { <ide> return response()->json([ <ide> 'message' => $exception->getMessage(), <del> 'errors' => $exception->validator->errors()->messages() <add> 'errors' => $exception->validator->errors()->messages(), <ide> ], 422); <ide> } <ide>
1
PHP
PHP
add exists method to session store
b3606975fb65f6a65a592dd160f010017b6627dc
<ide><path>src/Illuminate/Session/SessionInterface.php <ide> public function handlerNeedsRequest(); <ide> * @return void <ide> */ <ide> public function setRequestOnHandler(Request $request); <add> <add> /** <add> * Checks if an attribute exists. <add> * <add> * @param string|array $key <add> * <add> * @return bool <add> */ <add> public function exists($key); <ide> } <ide><path>src/Illuminate/Session/Store.php <ide> public function has($name) <ide> return true; <ide> } <ide> <add> /** <add> * {@inheritdoc} <add> */ <add> public function exists($key) <add> { <add> $keys = is_array($key) ? $key : func_get_args(); <add> <add> foreach ($keys as $value) { <add> if (! Arr::exists($this->attributes, $value)) { <add> return false; <add> } <add> } <add> <add> return true; <add> } <add> <ide> /** <ide> * {@inheritdoc} <ide> */ <ide><path>tests/Session/SessionStoreTest.php <ide> public function testName() <ide> $this->assertEquals($session->getName(), 'foo'); <ide> } <ide> <add> public function testKeyExists() <add> { <add> $session = $this->getSession(); <add> $session->set('foo', 'bar'); <add> $this->assertTrue($session->exists('foo')); <add> $session->set('baz', null); <add> $this->assertFalse($session->has('baz')); <add> $this->assertTrue($session->exists('baz')); <add> $this->assertFalse($session->exists('bogus')); <add> $this->assertTrue($session->exists(['foo', 'baz'])); <add> $this->assertFalse($session->exists(['foo', 'baz', 'bogus'])); <add> } <add> <ide> public function getSession() <ide> { <ide> $reflection = new ReflectionClass('Illuminate\Session\Store');
3
Go
Go
add methods to walk endpoints and networks
1c7c0f371baf30055526760d99e57cb48989beea
<ide><path>libnetwork/libnetwork_test.go <ide> func TestBridge(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> epList := network.Endpoints() <del> if len(epList) != 1 { <del> t.Fatal(err) <del> } <del> if ep != epList[0] { <del> t.Fatal(err) <del> } <del> <ide> if err := ep.Delete(); err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestUnknownEndpoint(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> } <add> <add>func TestNetworkEndpointsWalkers(t *testing.T) { <add> defer netutils.SetupTestNetNS(t)() <add> controller := libnetwork.New() <add> netType := "bridge" <add> <add> option := options.Generic{} <add> err := controller.ConfigureNetworkDriver(netType, option) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> // Create network 1 and add 2 endpoint: ep11, ep12 <add> net1, err := controller.NewNetwork(netType, "network1", "") <add> if err != nil { <add> t.Fatal(err) <add> } <add> ep11, err := net1.CreateEndpoint("ep11", "sbox1", nil) <add> if err != nil { <add> t.Fatal(err) <add> } <add> ep12, err := net1.CreateEndpoint("ep12", "sbox2", nil) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> // Test list methods on net1 <add> epList1 := net1.Endpoints() <add> if len(epList1) != 2 { <add> t.Fatalf("Endpoints() returned wrong number of elements: %d instead of 2", len(epList1)) <add> } <add> // endpoint order is not guaranteed <add> for _, e := range epList1 { <add> if e != ep11 && e != ep12 { <add> t.Fatal("Endpoints() did not return all the expected elements") <add> } <add> } <add> <add> // Test Endpoint Walk method <add> var epName string <add> var epWanted libnetwork.Endpoint <add> wlk := func(ep libnetwork.Endpoint) bool { <add> if ep.Name() == epName { <add> epWanted = ep <add> return true <add> } <add> return false <add> } <add> <add> // Look for ep1 on network1 <add> epName = "ep11" <add> net1.WalkEndpoints(wlk) <add> if epWanted == nil { <add> t.Fatal(err) <add> } <add> if ep11 != epWanted { <add> t.Fatal(err) <add> } <add> <add> // Test Network Walk method <add> var netName string <add> var netWanted libnetwork.Network <add> nwWlk := func(nw libnetwork.Network) bool { <add> if nw.Name() == netName { <add> netWanted = nw <add> return true <add> } <add> return false <add> } <add> <add> // Look for network named "network1" <add> netName = "network1" <add> controller.WalkNetworks(nwWlk) <add> if netWanted == nil { <add> t.Fatal(err) <add> } <add> if net1 != netWanted { <add> t.Fatal(err) <add> } <add>} <ide><path>libnetwork/network.go <ide> import ( <ide> type NetworkController interface { <ide> // ConfigureNetworkDriver applies the passed options to the driver instance for the specified network type <ide> ConfigureNetworkDriver(networkType string, options interface{}) error <add> <ide> // Create a new network. The options parameter carries network specific options. <ide> // Labels support will be added in the near future. <ide> NewNetwork(networkType, name string, options interface{}) (Network, error) <add> <add> // Networks returns the list of Network(s) managed by this controller. <add> Networks() []Network <add> <add> // WalkNetworks uses the provided function to walk the Network(s) managed by this controller. <add> WalkNetworks(walker NetworkWalker) <ide> } <ide> <ide> // A Network represents a logical connectivity zone that containers may <ide> type Network interface { <ide> // Labels support will be added in the near future. <ide> CreateEndpoint(name string, sboxKey string, options interface{}) (Endpoint, error) <ide> <del> // Endpoints returns the list of Endpoint in this network. <add> // Endpoints returns the list of Endpoint(s) in this network. <ide> Endpoints() []Endpoint <ide> <add> // WalkEndpoints uses the provided function to walk the Endpoints <add> WalkEndpoints(walker EndpointWalker) <add> <ide> // Delete the network. <ide> Delete() error <ide> } <ide> <add>// NetworkWalker is a client provided function which will be used to walk the Networks. <add>// When the function returns true, the walk will stop. <add>type NetworkWalker func(nw Network) bool <add> <ide> // Endpoint represents a logical connection between a network and a sandbox. <ide> type Endpoint interface { <ide> // A system generated id for this endpoint. <ide> type Endpoint interface { <ide> Delete() error <ide> } <ide> <del>type endpoint struct { <del> name string <del> id types.UUID <del> network *network <del> sandboxInfo *sandbox.Info <del>} <add>// EndpointWalker is a client provided function which will be used to walk the Endpoints. <add>// When the function returns true, the walk will stop. <add>type EndpointWalker func(ep Endpoint) bool <ide> <ide> type network struct { <ide> ctrlr *controller <ide> type network struct { <ide> sync.Mutex <ide> } <ide> <add>type endpoint struct { <add> name string <add> id types.UUID <add> network *network <add> sandboxInfo *sandbox.Info <add>} <add> <ide> type networkTable map[types.UUID]*network <ide> type endpointTable map[types.UUID]*endpoint <ide> <ide> func (c *controller) NewNetwork(networkType, name string, options interface{}) ( <ide> return network, nil <ide> } <ide> <add>func (c *controller) Networks() []Network { <add> c.Lock() <add> defer c.Unlock() <add> <add> list := make([]Network, 0, len(c.networks)) <add> for _, n := range c.networks { <add> list = append(list, n) <add> } <add> <add> return list <add>} <add> <add>func (c *controller) WalkNetworks(walker NetworkWalker) { <add> for _, n := range c.Networks() { <add> if walker(n) { <add> return <add> } <add> } <add>} <add> <ide> func (n *network) Name() string { <ide> return n.name <ide> } <ide> func (n *network) CreateEndpoint(name string, sboxKey string, options interface{ <ide> func (n *network) Endpoints() []Endpoint { <ide> n.Lock() <ide> defer n.Unlock() <del> <del> list := make([]Endpoint, len(n.endpoints)) <del> <del> idx := 0 <add> list := make([]Endpoint, 0, len(n.endpoints)) <ide> for _, e := range n.endpoints { <del> list[idx] = e <del> idx++ <add> list = append(list, e) <ide> } <ide> <ide> return list <ide> } <ide> <add>func (n *network) WalkEndpoints(walker EndpointWalker) { <add> for _, e := range n.Endpoints() { <add> if walker(e) { <add> return <add> } <add> } <add>} <add> <ide> func (ep *endpoint) ID() string { <ide> return string(ep.id) <ide> }
2
Ruby
Ruby
need a assert here in tests
ddf58fa9aa15bb2f58bc8779aab5bd273d35edde
<ide><path>activerecord/test/cases/mass_assignment_security_test.rb <ide> def test_mass_assigning_invalid_attribute <ide> end <ide> <ide> def test_mass_assigning_does_not_choke_on_nil <del> Firm.new.assign_attributes(nil) <add> assert_nil Firm.new.assign_attributes(nil) <ide> end <ide> <ide> def test_mass_assigning_does_not_choke_on_empty_hash <del> Firm.new.assign_attributes({}) <add> assert_nil Firm.new.assign_attributes({}) <ide> end <ide> <ide> def test_assign_attributes_uses_default_role_when_no_role_is_provided
1
Javascript
Javascript
remove unnecessary comment
87834537840b74744de8e136b027e4456080bb43
<ide><path>test/helpers/privateMocks.js <ide> function tthey(msg, vals, spec) { <ide> } <ide> <ide> function xthey(msg, vals, spec) { <del> /* jshint -W040 : ignore possible strict violation due to use of this */ <ide> baseThey(msg, vals, spec, xit); <ide> } <ide>
1
Ruby
Ruby
fix incorrect behavior specified in test
963c36004cfbe6c041460bab9c05718fc3bd7b58
<ide><path>activesupport/test/multibyte_chars_test.rb <ide> def test_slice_bang_returns_sliced_out_substring <ide> def test_slice_bang_removes_the_slice_from_the_receiver <ide> chars = 'úüù'.mb_chars <ide> chars.slice!(0,2) <del> assert_equal 'úü', chars <add> assert_equal 'ù', chars <ide> end <ide> <ide> def test_slice_should_throw_exceptions_on_invalid_arguments
1
Javascript
Javascript
allow redefine nodes dynamically
7b8aad6fded9cbb716b7225b024e26ab612f0251
<ide><path>examples/js/materials/nodes/ConstNode.js <ide> <ide> THREE.ConstNode = function( name, useDefine ) { <ide> <del> name = name || THREE.ConstNode.PI; <add> THREE.TempNode.call( this ); <ide> <del> var rDeclaration = /^([a-z_0-9]+)\s([a-z_0-9]+)\s?\=(.*?)\;/i; <del> var type = 'fv1'; <add> this.parse( name || THREE.ConstNode.PI, useDefine ); <add> <add>}; <add> <add>THREE.ConstNode.prototype = Object.create( THREE.TempNode.prototype ); <add>THREE.ConstNode.prototype.constructor = THREE.ConstNode; <add> <add>THREE.ConstNode.PI = 'PI'; <add>THREE.ConstNode.PI2 = 'PI2'; <add>THREE.ConstNode.RECIPROCAL_PI = 'RECIPROCAL_PI'; <add>THREE.ConstNode.RECIPROCAL_PI2 = 'RECIPROCAL_PI2'; <add>THREE.ConstNode.LOG2 = 'LOG2'; <add>THREE.ConstNode.EPSILON = 'EPSILON'; <add> <add>THREE.ConstNode.prototype.parse = function( src, useDefine ) { <add> <add> var name, type; <ide> <del> var match = name.match( rDeclaration ); <add> var rDeclaration = /^([a-z_0-9]+)\s([a-z_0-9]+)\s?\=(.*?)\;/i; <add> var match = src.match( rDeclaration ); <ide> <ide> if ( match && match.length > 1 ) { <ide> <ide> THREE.ConstNode = function( name, useDefine ) { <ide> } <ide> <ide> } <add> else { <ide> <del> this.name = name; <del> <del> THREE.TempNode.call( this, type ); <add> name = src; <add> type = 'fv1'; <ide> <del>}; <add> } <ide> <del>THREE.ConstNode.prototype = Object.create( THREE.TempNode.prototype ); <del>THREE.ConstNode.prototype.constructor = THREE.ConstNode; <add> this.name = name; <add> this.type = type; <ide> <del>THREE.ConstNode.PI = 'PI'; <del>THREE.ConstNode.PI2 = 'PI2'; <del>THREE.ConstNode.RECIPROCAL_PI = 'RECIPROCAL_PI'; <del>THREE.ConstNode.RECIPROCAL_PI2 = 'RECIPROCAL_PI2'; <del>THREE.ConstNode.LOG2 = 'LOG2'; <del>THREE.ConstNode.EPSILON = 'EPSILON'; <add>}; <ide> <ide> THREE.ConstNode.prototype.generate = function( builder, output ) { <ide> <ide><path>examples/js/materials/nodes/accessors/CameraNode.js <ide> THREE.CameraNode = function( scope, camera ) { <ide> <ide> THREE.TempNode.call( this, 'v3' ); <ide> <del> this.scope = scope || THREE.CameraNode.POSITION; <add> this.setScope( scope || THREE.CameraNode.POSITION ); <ide> this.camera = camera; <ide> <add> this.requestUpdate = this.camera !== undefined; <add> <add>}; <add> <add>THREE.CameraNode.prototype = Object.create( THREE.TempNode.prototype ); <add>THREE.CameraNode.prototype.constructor = THREE.CameraNode; <add> <add>THREE.CameraNode.POSITION = 'position'; <add>THREE.CameraNode.DEPTH = 'depth'; <add> <add>THREE.CameraNode.prototype.setScope = function( scope ) { <add> <add> switch ( this.scope ) { <add> <add> case THREE.CameraNode.DEPTH: <add> <add> delete this.near; <add> delete this.far; <add> <add> break; <add> <add> } <add> <add> this.scope = scope; <add> <ide> switch ( scope ) { <ide> <ide> case THREE.CameraNode.DEPTH: <ide> THREE.CameraNode = function( scope, camera ) { <ide> <ide> } <ide> <del> this.requestUpdate = this.camera !== undefined; <del> <ide> }; <ide> <del>THREE.CameraNode.prototype = Object.create( THREE.TempNode.prototype ); <del>THREE.CameraNode.prototype.constructor = THREE.CameraNode; <del> <del>THREE.CameraNode.POSITION = 'position'; <del>THREE.CameraNode.DEPTH = 'depth'; <del> <ide> THREE.CameraNode.prototype.getType = function( builder ) { <ide> <ide> switch ( this.scope ) {
2
PHP
PHP
add `failed()` on interactswithqueue
638e32ab500150b36956bc9942c5c9719883071d
<ide><path>src/Illuminate/Queue/InteractsWithQueue.php <ide> trait InteractsWithQueue <ide> */ <ide> protected $job; <ide> <add> /** <add> * Get the number of times the job has been attempted. <add> * <add> * @return int <add> */ <add> public function attempts() <add> { <add> return $this->job ? $this->job->attempts() : 1; <add> } <add> <ide> /** <ide> * Delete the job from the queue. <ide> * <ide> public function delete() <ide> } <ide> <ide> /** <del> * Release the job back into the queue. <add> * Fail the job from the queue. <ide> * <del> * @param int $delay <ide> * @return void <ide> */ <del> public function release($delay = 0) <add> public function failed() <ide> { <ide> if ($this->job) { <del> return $this->job->release($delay); <add> return $this->job->failed(); <ide> } <ide> } <ide> <ide> /** <del> * Get the number of times the job has been attempted. <add> * Release the job back into the queue. <ide> * <del> * @return int <add> * @param int $delay <add> * @return void <ide> */ <del> public function attempts() <add> public function release($delay = 0) <ide> { <del> return $this->job ? $this->job->attempts() : 1; <add> if ($this->job) { <add> return $this->job->release($delay); <add> } <ide> } <ide> <ide> /**
1
Python
Python
fix typo in add_library
0407363fe009c004da0e2c2bbbaa421cb64e160d
<ide><path>numpy/distutils/misc_util.py <ide> def add_library(self,name,sources,**build_info): <ide> f2py_options <ide> language <ide> """ <del> self._add_library(name, sources, install_dir, build_info) <add> self._add_library(name, sources, None, build_info) <ide> <ide> dist = self.get_distribution() <ide> if dist is not None:
1
PHP
PHP
remove unused import
48f8a90c10b8490d0e442a8f0cf258471208009f
<ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Str; <ide> use InvalidArgumentException; <del>use Illuminate\Support\Carbon; <ide> use Illuminate\Http\UploadedFile; <ide> use Illuminate\Support\Collection; <ide> use League\Flysystem\AdapterInterface;
1
Python
Python
use tensorflow-datasets to load the data.
56b5d0374a60fffc0c6f74d3da21529d310977fc
<ide><path>tutorials/image/cifar10/cifar10.py <ide> from __future__ import division <ide> from __future__ import print_function <ide> <del>import os <ide> import re <del>import sys <del>import tarfile <ide> <del>from six.moves import urllib <ide> import tensorflow as tf <ide> <ide> import cifar10_input <ide> # Basic model parameters. <ide> tf.app.flags.DEFINE_integer('batch_size', 128, <ide> """Number of images to process in a batch.""") <del>tf.app.flags.DEFINE_string('data_dir', '/tmp/cifar10_data', <del> """Path to the CIFAR-10 data directory.""") <ide> tf.app.flags.DEFINE_boolean('use_fp16', False, <ide> """Train the model using fp16.""") <ide> <ide> # names of the summaries when visualizing a model. <ide> TOWER_NAME = 'tower' <ide> <del>DATA_URL = 'https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz' <del> <ide> <ide> def _activation_summary(x): <ide> """Helper to create summaries for activations. <ide> def _activation_summary(x): <ide> # session. This helps the clarity of presentation on tensorboard. <ide> tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name) <ide> tf.summary.histogram(tensor_name + '/activations', x) <del> tf.summary.scalar(tensor_name + '/sparsity', <del> tf.nn.zero_fraction(x)) <add> tf.summary.scalar(tensor_name + '/sparsity', tf.nn.zero_fraction(x)) <ide> <ide> <ide> def _variable_on_cpu(name, shape, initializer): <ide> def distorted_inputs(): <ide> Returns: <ide> images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. <ide> labels: Labels. 1D tensor of [batch_size] size. <del> <del> Raises: <del> ValueError: If no data_dir <ide> """ <del> if not FLAGS.data_dir: <del> raise ValueError('Please supply a data_dir') <del> data_dir = os.path.join(FLAGS.data_dir, 'cifar-10-batches-bin') <del> images, labels = cifar10_input.distorted_inputs(data_dir=data_dir, <del> batch_size=FLAGS.batch_size) <add> images, labels = cifar10_input.distorted_inputs(batch_size=FLAGS.batch_size) <ide> if FLAGS.use_fp16: <ide> images = tf.cast(images, tf.float16) <ide> labels = tf.cast(labels, tf.float16) <ide> def inputs(eval_data): <ide> Returns: <ide> images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. <ide> labels: Labels. 1D tensor of [batch_size] size. <del> <del> Raises: <del> ValueError: If no data_dir <ide> """ <del> if not FLAGS.data_dir: <del> raise ValueError('Please supply a data_dir') <del> data_dir = os.path.join(FLAGS.data_dir, 'cifar-10-batches-bin') <ide> images, labels = cifar10_input.inputs(eval_data=eval_data, <del> data_dir=data_dir, <ide> batch_size=FLAGS.batch_size) <ide> if FLAGS.use_fp16: <ide> images = tf.cast(images, tf.float16) <ide> def inference(images): <ide> # local3 <ide> with tf.variable_scope('local3') as scope: <ide> # Move everything into depth so we can perform a single matrix multiply. <del> reshape = tf.reshape(pool2, [images.get_shape().as_list()[0], -1]) <add> reshape = tf.keras.layers.Flatten()(pool2) <ide> dim = reshape.get_shape()[1].value <ide> weights = _variable_with_weight_decay('weights', shape=[dim, 384], <ide> stddev=0.04, wd=0.004) <ide> def train(total_loss, global_step): <ide> variables_averages_op = variable_averages.apply(tf.trainable_variables()) <ide> <ide> return variables_averages_op <del> <del> <del>def maybe_download_and_extract(): <del> """Download and extract the tarball from Alex's website.""" <del> dest_directory = FLAGS.data_dir <del> if not os.path.exists(dest_directory): <del> os.makedirs(dest_directory) <del> filename = DATA_URL.split('/')[-1] <del> filepath = os.path.join(dest_directory, filename) <del> if not os.path.exists(filepath): <del> def _progress(count, block_size, total_size): <del> sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename, <del> float(count * block_size) / float(total_size) * 100.0)) <del> sys.stdout.flush() <del> filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress) <del> print() <del> statinfo = os.stat(filepath) <del> print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') <del> extracted_dir_path = os.path.join(dest_directory, 'cifar-10-batches-bin') <del> if not os.path.exists(extracted_dir_path): <del> tarfile.open(filepath, 'r:gz').extractall(dest_directory) <ide><path>tutorials/image/cifar10/cifar10_eval.py <ide> """Either 'test' or 'train_eval'.""") <ide> tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/cifar10_train', <ide> """Directory where to read model checkpoints.""") <del>tf.app.flags.DEFINE_integer('eval_interval_secs', 60 * 5, <add>tf.app.flags.DEFINE_integer('eval_interval_secs', 5, <ide> """How often to run the eval.""") <del>tf.app.flags.DEFINE_integer('num_examples', 10000, <add>tf.app.flags.DEFINE_integer('num_examples', 1000, <ide> """Number of examples to run.""") <ide> tf.app.flags.DEFINE_boolean('run_once', False, <del> """Whether to run eval only once.""") <add> """Whether to run eval only once.""") <ide> <ide> <ide> def eval_once(saver, summary_writer, top_k_op, summary_op): <ide> def eval_once(saver, summary_writer, top_k_op, summary_op): <ide> threads.extend(qr.create_threads(sess, coord=coord, daemon=True, <ide> start=True)) <ide> <del> num_iter = int(math.ceil(FLAGS.num_examples / FLAGS.batch_size)) <add> num_iter = int(math.ceil(float(FLAGS.num_examples) / FLAGS.batch_size)) <ide> true_count = 0 # Counts the number of correct predictions. <ide> total_sample_count = num_iter * FLAGS.batch_size <ide> step = 0 <ide> def evaluate(): <ide> <ide> <ide> def main(argv=None): # pylint: disable=unused-argument <del> cifar10.maybe_download_and_extract() <ide> if tf.gfile.Exists(FLAGS.eval_dir): <ide> tf.gfile.DeleteRecursively(FLAGS.eval_dir) <ide> tf.gfile.MakeDirs(FLAGS.eval_dir) <ide><path>tutorials/image/cifar10/cifar10_input.py <ide> from __future__ import division <ide> from __future__ import print_function <ide> <del>import os <del> <del>from six.moves import xrange # pylint: disable=redefined-builtin <ide> import tensorflow as tf <add>import tensorflow_datasets as tfds <ide> <ide> # Process images of this size. Note that this differs from the original CIFAR <ide> # image size of 32 x 32. If one alters this number, then the entire model <ide> NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10000 <ide> <ide> <del>def read_cifar10(filename_queue): <del> """Reads and parses examples from CIFAR10 data files. <del> <del> Recommendation: if you want N-way read parallelism, call this function <del> N times. This will give you N independent Readers reading different <del> files & positions within those files, which will give better mixing of <del> examples. <del> <del> Args: <del> filename_queue: A queue of strings with the filenames to read from. <del> <del> Returns: <del> An object representing a single example, with the following fields: <del> height: number of rows in the result (32) <del> width: number of columns in the result (32) <del> depth: number of color channels in the result (3) <del> key: a scalar string Tensor describing the filename & record number <del> for this example. <del> label: an int32 Tensor with the label in the range 0..9. <del> uint8image: a [height, width, depth] uint8 Tensor with the image data <del> """ <del> <del> class CIFAR10Record(object): <del> pass <del> result = CIFAR10Record() <del> <del> # Dimensions of the images in the CIFAR-10 dataset. <del> # See http://www.cs.toronto.edu/~kriz/cifar.html for a description of the <del> # input format. <del> label_bytes = 1 # 2 for CIFAR-100 <del> result.height = 32 <del> result.width = 32 <del> result.depth = 3 <del> image_bytes = result.height * result.width * result.depth <del> # Every record consists of a label followed by the image, with a <del> # fixed number of bytes for each. <del> record_bytes = label_bytes + image_bytes <del> <del> # Read a record, getting filenames from the filename_queue. No <del> # header or footer in the CIFAR-10 format, so we leave header_bytes <del> # and footer_bytes at their default of 0. <del> reader = tf.FixedLengthRecordReader(record_bytes=record_bytes) <del> result.key, value = reader.read(filename_queue) <del> <del> # Convert from a string to a vector of uint8 that is record_bytes long. <del> record_bytes = tf.decode_raw(value, tf.uint8) <del> <del> # The first bytes represent the label, which we convert from uint8->int32. <del> result.label = tf.cast( <del> tf.strided_slice(record_bytes, [0], [label_bytes]), tf.int32) <del> <del> # The remaining bytes after the label represent the image, which we reshape <del> # from [depth * height * width] to [depth, height, width]. <del> depth_major = tf.reshape( <del> tf.strided_slice(record_bytes, [label_bytes], <del> [label_bytes + image_bytes]), <del> [result.depth, result.height, result.width]) <del> # Convert from [depth, height, width] to [height, width, depth]. <del> result.uint8image = tf.transpose(depth_major, [1, 2, 0]) <del> <del> return result <del> <del> <del>def _generate_image_and_label_batch(image, label, min_queue_examples, <del> batch_size, shuffle): <del> """Construct a queued batch of images and labels. <del> <del> Args: <del> image: 3-D Tensor of [height, width, 3] of type.float32. <del> label: 1-D Tensor of type.int32 <del> min_queue_examples: int32, minimum number of samples to retain <del> in the queue that provides of batches of examples. <del> batch_size: Number of images per batch. <del> shuffle: boolean indicating whether to use a shuffling queue. <del> <del> Returns: <del> images: Images. 4D tensor of [batch_size, height, width, 3] size. <del> labels: Labels. 1D tensor of [batch_size] size. <del> """ <del> # Create a queue that shuffles the examples, and then <del> # read 'batch_size' images + labels from the example queue. <del> num_preprocess_threads = 16 <del> if shuffle: <del> images, label_batch = tf.train.shuffle_batch( <del> [image, label], <del> batch_size=batch_size, <del> num_threads=num_preprocess_threads, <del> capacity=min_queue_examples + 3 * batch_size, <del> min_after_dequeue=min_queue_examples) <del> else: <del> images, label_batch = tf.train.batch( <del> [image, label], <del> batch_size=batch_size, <del> num_threads=num_preprocess_threads, <del> capacity=min_queue_examples + 3 * batch_size) <del> <del> # Display the training images in the visualizer. <add>def _get_images_labels(batch_size, split, distords=False): <add> """Returns Dataset for given split.""" <add> dataset = tfds.load(name='cifar10', split=split) <add> scope = 'data_augmentation' if distords else 'input' <add> with tf.name_scope(scope): <add> dataset = dataset.map(DataPreprocessor(distords), num_parallel_calls=10) <add> # Dataset is small enough to be fully loaded on memory: <add> dataset = dataset.prefetch(-1) <add> dataset = dataset.repeat().batch(batch_size) <add> iterator = dataset.make_one_shot_iterator() <add> images_labels = iterator.get_next() <add> images, labels = images_labels['input'], images_labels['target'] <ide> tf.summary.image('images', images) <del> <del> return images, tf.reshape(label_batch, [batch_size]) <add> return images, labels <add> <add> <add>class DataPreprocessor(object): <add> """Applies transformations to dataset record.""" <add> <add> def __init__(self, distords): <add> self._distords = distords <add> <add> def __call__(self, record): <add> """Process img for training or eval.""" <add> img = record['image'] <add> img = tf.cast(img, tf.float32) <add> if self._distords: # training <add> # Randomly crop a [height, width] section of the image. <add> img = tf.random_crop(img, [IMAGE_SIZE, IMAGE_SIZE, 3]) <add> # Randomly flip the image horizontally. <add> img = tf.image.random_flip_left_right(img) <add> # Because these operations are not commutative, consider randomizing <add> # the order their operation. <add> # NOTE: since per_image_standardization zeros the mean and makes <add> # the stddev unit, this likely has no effect see tensorflow#1458. <add> img = tf.image.random_brightness(img, max_delta=63) <add> img = tf.image.random_contrast(img, lower=0.2, upper=1.8) <add> else: # Image processing for evaluation. <add> # Crop the central [height, width] of the image. <add> img = tf.image.resize_image_with_crop_or_pad(img, IMAGE_SIZE, IMAGE_SIZE) <add> # Subtract off the mean and divide by the variance of the pixels. <add> img = tf.image.per_image_standardization(img) <add> return dict(input=img, target=record['label']) <ide> <ide> <del>def distorted_inputs(data_dir, batch_size): <add>def distorted_inputs(batch_size): <ide> """Construct distorted input for CIFAR training using the Reader ops. <ide> <ide> Args: <del> data_dir: Path to the CIFAR-10 data directory. <ide> batch_size: Number of images per batch. <ide> <ide> Returns: <ide> images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. <ide> labels: Labels. 1D tensor of [batch_size] size. <ide> """ <del> filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i) <del> for i in xrange(1, 6)] <del> for f in filenames: <del> if not tf.gfile.Exists(f): <del> raise ValueError('Failed to find file: ' + f) <del> <del> # Create a queue that produces the filenames to read. <del> filename_queue = tf.train.string_input_producer(filenames) <del> <del> with tf.name_scope('data_augmentation'): <del> # Read examples from files in the filename queue. <del> read_input = read_cifar10(filename_queue) <del> reshaped_image = tf.cast(read_input.uint8image, tf.float32) <del> <del> height = IMAGE_SIZE <del> width = IMAGE_SIZE <del> <del> # Image processing for training the network. Note the many random <del> # distortions applied to the image. <del> <del> # Randomly crop a [height, width] section of the image. <del> distorted_image = tf.random_crop(reshaped_image, [height, width, 3]) <del> <del> # Randomly flip the image horizontally. <del> distorted_image = tf.image.random_flip_left_right(distorted_image) <del> <del> # Because these operations are not commutative, consider randomizing <del> # the order their operation. <del> # NOTE: since per_image_standardization zeros the mean and makes <del> # the stddev unit, this likely has no effect see tensorflow#1458. <del> distorted_image = tf.image.random_brightness(distorted_image, <del> max_delta=63) <del> distorted_image = tf.image.random_contrast(distorted_image, <del> lower=0.2, upper=1.8) <del> <del> # Subtract off the mean and divide by the variance of the pixels. <del> float_image = tf.image.per_image_standardization(distorted_image) <del> <del> # Set the shapes of tensors. <del> float_image.set_shape([height, width, 3]) <del> read_input.label.set_shape([1]) <add> return _get_images_labels(batch_size, tfds.Split.TRAIN, distords=True) <ide> <del> # Ensure that the random shuffling has good mixing properties. <del> min_fraction_of_examples_in_queue = 0.4 <del> min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN * <del> min_fraction_of_examples_in_queue) <del> print ('Filling queue with %d CIFAR images before starting to train. ' <del> 'This will take a few minutes.' % min_queue_examples) <ide> <del> # Generate a batch of images and labels by building up a queue of examples. <del> return _generate_image_and_label_batch(float_image, read_input.label, <del> min_queue_examples, batch_size, <del> shuffle=True) <del> <del> <del>def inputs(eval_data, data_dir, batch_size): <add>def inputs(eval_data, batch_size): <ide> """Construct input for CIFAR evaluation using the Reader ops. <ide> <ide> Args: <ide> eval_data: bool, indicating if one should use the train or eval data set. <del> data_dir: Path to the CIFAR-10 data directory. <ide> batch_size: Number of images per batch. <ide> <ide> Returns: <ide> images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size. <ide> labels: Labels. 1D tensor of [batch_size] size. <ide> """ <del> if not eval_data: <del> filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i) <del> for i in xrange(1, 6)] <del> num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN <del> else: <del> filenames = [os.path.join(data_dir, 'test_batch.bin')] <del> num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_EVAL <del> <del> for f in filenames: <del> if not tf.gfile.Exists(f): <del> raise ValueError('Failed to find file: ' + f) <del> <del> with tf.name_scope('input'): <del> # Create a queue that produces the filenames to read. <del> filename_queue = tf.train.string_input_producer(filenames) <del> <del> # Read examples from files in the filename queue. <del> read_input = read_cifar10(filename_queue) <del> reshaped_image = tf.cast(read_input.uint8image, tf.float32) <del> <del> height = IMAGE_SIZE <del> width = IMAGE_SIZE <del> <del> # Image processing for evaluation. <del> # Crop the central [height, width] of the image. <del> resized_image = tf.image.resize_image_with_crop_or_pad(reshaped_image, <del> height, width) <del> <del> # Subtract off the mean and divide by the variance of the pixels. <del> float_image = tf.image.per_image_standardization(resized_image) <del> <del> # Set the shapes of tensors. <del> float_image.set_shape([height, width, 3]) <del> read_input.label.set_shape([1]) <del> <del> # Ensure that the random shuffling has good mixing properties. <del> min_fraction_of_examples_in_queue = 0.4 <del> min_queue_examples = int(num_examples_per_epoch * <del> min_fraction_of_examples_in_queue) <del> <del> # Generate a batch of images and labels by building up a queue of examples. <del> return _generate_image_and_label_batch(float_image, read_input.label, <del> min_queue_examples, batch_size, <del> shuffle=False) <add> split = tfds.Split.TEST if eval_data == 'test' else tfds.Split.TRAIN <add> return _get_images_labels(batch_size, split) <ide><path>tutorials/image/cifar10/cifar10_train.py <ide> def after_run(self, run_context, run_values): <ide> <ide> <ide> def main(argv=None): # pylint: disable=unused-argument <del> cifar10.maybe_download_and_extract() <ide> if tf.gfile.Exists(FLAGS.train_dir): <ide> tf.gfile.DeleteRecursively(FLAGS.train_dir) <ide> tf.gfile.MakeDirs(FLAGS.train_dir)
4
Ruby
Ruby
add `determine_mirror` helper method
c983d85eea9d9579bfb8685c0e1fc73651cb8175
<ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb <ide> def bump_formula_pr <ide> new_tag = args.tag <ide> new_revision = args.revision <ide> new_mirrors ||= args.mirror <del> new_mirror ||= case new_url <del> when %r{.*ftp.gnu.org/gnu.*} <del> new_url.sub "ftp.gnu.org/gnu", "ftpmirror.gnu.org" <del> when %r{.*download.savannah.gnu.org/*} <del> new_url.sub "download.savannah.gnu.org", "download-mirror.savannah.gnu.org" <del> when %r{.*www.apache.org/dyn/closer.lua\?path=.*} <del> new_url.sub "www.apache.org/dyn/closer.lua?path=", "archive.apache.org/dist/" <del> when %r{.*mirrors.ocf.berkeley.edu/debian.*} <del> new_url.sub "mirrors.ocf.berkeley.edu/debian", "mirrorservice.org/sites/ftp.debian.org/debian" <del> end <add> new_mirror ||= determine_mirror(new_url) <ide> new_mirrors ||= [new_mirror] unless new_mirror.nil? <ide> old_url = formula_spec.url <ide> old_tag = formula_spec.specs[:tag] <ide> def determine_formula_from_url(url) <ide> odie "Couldn't guess formula for sure; could be one of these:\n#{guesses.map(&:name).join(", ")}" <ide> end <ide> <add> def determine_mirror(url) <add> case url <add> when %r{.*ftp.gnu.org/gnu.*} <add> url.sub "ftp.gnu.org/gnu", "ftpmirror.gnu.org" <add> when %r{.*download.savannah.gnu.org/*} <add> url.sub "download.savannah.gnu.org", "download-mirror.savannah.gnu.org" <add> when %r{.*www.apache.org/dyn/closer.lua\?path=.*} <add> url.sub "www.apache.org/dyn/closer.lua?path=", "archive.apache.org/dist/" <add> when %r{.*mirrors.ocf.berkeley.edu/debian.*} <add> url.sub "mirrors.ocf.berkeley.edu/debian", "mirrorservice.org/sites/ftp.debian.org/debian" <add> end <add> end <add> <ide> def fetch_resource(formula, new_version, url, **specs) <ide> resource = Resource.new <ide> resource.url(url, specs)
1
Java
Java
add strategy for customizing id/timestamp headers
95e25d4e6f14a20767f0bc62a1dd1052c2a5ca35
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/DefaultSimpMessageHeaderAccessorFactory.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.messaging.simp; <del> <del>import org.springframework.messaging.Message; <del>import org.springframework.messaging.MessageHeaders; <del>import org.springframework.messaging.support.MessageHeaderAccessorFactorySupport; <del>import org.springframework.util.IdGenerator; <del> <del>import java.util.UUID; <del> <del>/** <del> * A default implementation of <del> * {@link org.springframework.messaging.simp.SimpMessageHeaderAccessorFactory}. <del> * <del> * @author Rossen Stoyanchev <del> * @since 4.1 <del> */ <del>public class DefaultSimpMessageHeaderAccessorFactory extends MessageHeaderAccessorFactorySupport <del> implements SimpMessageHeaderAccessorFactory { <del> <del> <del> public DefaultSimpMessageHeaderAccessorFactory() { <del> super.setIdGenerator(ID_VALUE_NONE_GENERATOR); <del> } <del> <del> <del> @Override <del> public SimpMessageHeaderAccessor create() { <del> SimpMessageHeaderAccessor accessor = new SimpMessageHeaderAccessor(SimpMessageType.MESSAGE, null); <del> updateMessageHeaderAccessor(accessor); <del> return accessor; <del> } <del> <del> @Override <del> public SimpMessageHeaderAccessor create(SimpMessageType messageType) { <del> SimpMessageHeaderAccessor accessor = new SimpMessageHeaderAccessor(messageType, null); <del> updateMessageHeaderAccessor(accessor); <del> return accessor; <del> } <del> <del> @Override <del> public SimpMessageHeaderAccessor wrap(Message<?> message) { <del> SimpMessageHeaderAccessor accessor = new SimpMessageHeaderAccessor(message); <del> updateMessageHeaderAccessor(accessor); <del> return accessor; <del> } <del> <del> <del> private static final IdGenerator ID_VALUE_NONE_GENERATOR = new IdGenerator() { <del> @Override <del> public UUID generateId() { <del> return MessageHeaders.ID_VALUE_NONE; <del> } <del> }; <del>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageHeaderAccessor.java <ide> import java.util.Map; <ide> <ide> import org.springframework.messaging.Message; <del>import org.springframework.messaging.MessageHeaders; <add>import org.springframework.messaging.support.IdTimestampMessageHeaderInitializer; <ide> import org.springframework.messaging.support.MessageHeaderAccessor; <ide> import org.springframework.messaging.support.NativeMessageHeaderAccessor; <ide> import org.springframework.util.Assert; <ide> */ <ide> public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor { <ide> <del> private static final SimpMessageHeaderAccessorFactory factory = new DefaultSimpMessageHeaderAccessorFactory(); <add> private static final IdTimestampMessageHeaderInitializer headerInitializer; <add> <add> static { <add> headerInitializer = new IdTimestampMessageHeaderInitializer(); <add> headerInitializer.setDisableIdGeneration(); <add> headerInitializer.setEnableTimestamp(false); <add> } <ide> <ide> // SiMP header names <ide> <ide> protected SimpMessageHeaderAccessor(SimpMessageType messageType, Map<String, Lis <ide> super(externalSourceHeaders); <ide> Assert.notNull(messageType, "MessageType must not be null"); <ide> setHeader(MESSAGE_TYPE_HEADER, messageType); <add> headerInitializer.initHeaders(this); <ide> } <ide> <ide> /** <ide> protected SimpMessageHeaderAccessor(SimpMessageType messageType, Map<String, Lis <ide> */ <ide> protected SimpMessageHeaderAccessor(Message<?> message) { <ide> super(message); <add> headerInitializer.initHeaders(this); <ide> } <ide> <ide> <ide> protected SimpMessageHeaderAccessor(Message<?> message) { <ide> * {@link org.springframework.messaging.simp.SimpMessageType} {@code MESSAGE}. <ide> */ <ide> public static SimpMessageHeaderAccessor create() { <del> return factory.create(); <add> return new SimpMessageHeaderAccessor(SimpMessageType.MESSAGE, null); <ide> } <ide> <ide> /** <ide> * Create an instance with the given <ide> * {@link org.springframework.messaging.simp.SimpMessageType}. <ide> */ <ide> public static SimpMessageHeaderAccessor create(SimpMessageType messageType) { <del> return factory.create(messageType); <add> return new SimpMessageHeaderAccessor(messageType, null); <ide> } <ide> <ide> /** <ide> * Create an instance from the payload and headers of the given Message. <ide> */ <ide> public static SimpMessageHeaderAccessor wrap(Message<?> message) { <del> return factory.wrap(message); <add> return new SimpMessageHeaderAccessor(message); <ide> } <ide> <ide> <ide> @Override <ide> protected MessageHeaderAccessor createAccessor(Message<?> message) { <del> return factory.wrap(message); <add> return wrap(message); <ide> } <ide> <ide> public void setMessageTypeIfNotSet(SimpMessageType messageType) { <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageHeaderAccessorFactory.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.messaging.simp; <del> <del> <del>import org.springframework.messaging.Message; <del> <del>/** <del> * A factory for creating pre-configured instances of type <del> * {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor}. <del> * <del> * @author Rossen Stoyanchev <del> * @since 4.1 <del> */ <del>public interface SimpMessageHeaderAccessorFactory { <del> <del> /** <del> * Create an instance with <del> * {@link org.springframework.messaging.simp.SimpMessageType} {@code MESSAGE}. <del> */ <del> SimpMessageHeaderAccessor create(); <del> <del> /** <del> * Create an instance with the given <del> * {@link org.springframework.messaging.simp.SimpMessageType}. <del> */ <del> SimpMessageHeaderAccessor create(SimpMessageType messageType); <del> <del> /** <del> * Create an instance from the payload and headers of the given Message. <del> */ <del> SimpMessageHeaderAccessor wrap(Message<?> message); <del> <del>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/DefaultStompHeaderAccessorFactory.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.messaging.simp.stomp; <del> <del>import org.springframework.messaging.Message; <del>import org.springframework.messaging.MessageHeaders; <del>import org.springframework.messaging.support.MessageHeaderAccessorFactorySupport; <del>import org.springframework.util.IdGenerator; <del> <del>import java.util.List; <del>import java.util.Map; <del>import java.util.UUID; <del> <del>/** <del> * A default implementation of <del> * {@link org.springframework.messaging.simp.stomp.StompHeaderAccessorFactory}. <del> * <del> * @author Rossen Stoyanchev <del> * @since 4.1 <del> */ <del>public class DefaultStompHeaderAccessorFactory extends MessageHeaderAccessorFactorySupport <del> implements StompHeaderAccessorFactory { <del> <del> <del> public DefaultStompHeaderAccessorFactory() { <del> super.setIdGenerator(ID_VALUE_NONE_GENERATOR); <del> } <del> <del> <del> @Override <del> public StompHeaderAccessor create(StompCommand command) { <del> StompHeaderAccessor accessor = new StompHeaderAccessor(command, null); <del> updateMessageHeaderAccessor(accessor); <del> return accessor; <del> } <del> <del> @Override <del> public StompHeaderAccessor create(StompCommand command, Map<String, List<String>> headers) { <del> StompHeaderAccessor accessor = new StompHeaderAccessor(command, headers); <del> updateMessageHeaderAccessor(accessor); <del> return accessor; <del> } <del> <del> @Override <del> public StompHeaderAccessor createForHeartbeat() { <del> StompHeaderAccessor accessor = new StompHeaderAccessor(); <del> updateMessageHeaderAccessor(accessor); <del> return accessor; <del> } <del> <del> @Override <del> public StompHeaderAccessor wrap(Message<?> message) { <del> StompHeaderAccessor accessor = new StompHeaderAccessor(message); <del> updateMessageHeaderAccessor(accessor); <del> return accessor; <del> } <del> <del> private static final IdGenerator ID_VALUE_NONE_GENERATOR = new IdGenerator() { <del> @Override <del> public UUID generateId() { <del> return MessageHeaders.ID_VALUE_NONE; <del> } <del> }; <del>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompHeaderAccessor.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.MimeType; <ide> import org.springframework.util.MimeTypeUtils; <del>import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.StringUtils; <ide> <ide> /** <ide> */ <ide> public class StompHeaderAccessor extends SimpMessageHeaderAccessor { <ide> <del> private static final StompHeaderAccessorFactory factory = new DefaultStompHeaderAccessorFactory(); <del> <ide> private static final AtomicLong messageIdCounter = new AtomicLong(); <ide> <ide> private static final long[] DEFAULT_HEARTBEAT = new long[] {0, 0}; <ide> private void updateStompHeadersFromSimpMessageHeaders() { <ide> * Create an instance for the given STOMP command. <ide> */ <ide> public static StompHeaderAccessor create(StompCommand command) { <del> return factory.create(command); <add> return new StompHeaderAccessor(command, null); <ide> } <ide> <ide> /** <ide> * Create an instance for the given STOMP command and headers. <ide> */ <ide> public static StompHeaderAccessor create(StompCommand command, Map<String, List<String>> headers) { <del> return factory.create(command, headers); <add> return new StompHeaderAccessor(command, headers); <ide> } <ide> <ide> /** <ide> * Create headers for a heartbeat. While a STOMP heartbeat frame does not <ide> * have headers, a session id is needed for processing purposes at a minimum. <ide> */ <ide> public static StompHeaderAccessor createForHeartbeat() { <del> return factory.createForHeartbeat(); <add> return new StompHeaderAccessor(); <ide> } <ide> <ide> /** <ide> * Create an instance from the payload and headers of the given Message. <ide> */ <ide> public static StompHeaderAccessor wrap(Message<?> message) { <del> return factory.wrap(message); <add> return new StompHeaderAccessor(message); <ide> } <ide> <ide> <ide> @Override <ide> protected MessageHeaderAccessor createAccessor(Message<?> message) { <del> return factory.wrap(message); <add> return wrap(message); <ide> } <ide> <ide> Map<String, List<String>> getNativeHeaders() { <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorFactory.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.messaging.simp.stomp; <del> <del> <del>import org.springframework.messaging.Message; <del> <del>import java.util.List; <del>import java.util.Map; <del> <del>/** <del> * A factory for creating pre-configured instances of type <del> * {@link org.springframework.messaging.simp.stomp.StompHeaderAccessor}. <del> * <del> * @author Rossen Stoyanchev <del> * @since 4.1 <del> */ <del>public interface StompHeaderAccessorFactory { <del> <del> /** <del> * Create an instance for the given STOMP command. <del> */ <del> StompHeaderAccessor create(StompCommand command); <del> <del> /** <del> * Create an instance for the given STOMP command and headers. <del> */ <del> StompHeaderAccessor create(StompCommand command, Map<String, List<String>> headers); <del> <del> /** <del> * Create headers for a heartbeat. While a STOMP heartbeat frame does not <del> * have headers, a session id is needed for processing purposes at a minimum. <del> */ <del> StompHeaderAccessor createForHeartbeat(); <del> <del> /** <del> * Create an instance from the payload and headers of the given Message. <del> */ <del> StompHeaderAccessor wrap(Message<?> message); <del> <del>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/IdTimestampMessageHeaderInitializer.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.messaging.support; <add> <add>import org.springframework.messaging.MessageHeaders; <add>import org.springframework.util.IdGenerator; <add> <add>import java.util.UUID; <add> <add>/** <add> * A {@link org.springframework.messaging.support.MessageHeaderInitializer MessageHeaderInitializer} <add> * to customize the strategy for ID and TIMESTAMP message header generation. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public class IdTimestampMessageHeaderInitializer implements MessageHeaderInitializer { <add> <add> private IdGenerator idGenerator; <add> <add> private boolean enableTimestamp; <add> <add> <add> /** <add> * Configure the IdGenerator strategy to initialize {@code MessageHeaderAccessor} <add> * instances with. <add> * <add> * <p>By default this property is set to {@code null} in which case the default <add> * IdGenerator of {@link org.springframework.messaging.MessageHeaders} is used. <add> * <add> * <p>To have no id's generated at all, see {@@link #setDisableIdGeneration()}. <add> */ <add> public void setIdGenerator(IdGenerator idGenerator) { <add> this.idGenerator = idGenerator; <add> } <add> <add> /** <add> * A shortcut for calling <add> * {@link #setIdGenerator(org.springframework.util.IdGenerator)} with an <add> * id generation strategy to <add> * <add> */ <add> public void setDisableIdGeneration() { <add> this.idGenerator = ID_VALUE_NONE_GENERATOR; <add> } <add> <add> /** <add> * @return the configured {@code IdGenerator} if any. <add> */ <add> public IdGenerator getIdGenerator() { <add> return this.idGenerator; <add> } <add> <add> /** <add> * Whether to enable the automatic addition of the <add> * {@link org.springframework.messaging.MessageHeaders#TIMESTAMP} header on <add> * {@code MessageHeaderAccessor} instances being initialized. <add> * <add> * <p>By default this property is set to false. <add> */ <add> public void setEnableTimestamp(boolean enableTimestamp) { <add> this.enableTimestamp = enableTimestamp; <add> } <add> <add> /** <add> * @return Whether the timestamp header is enabled or not. <add> */ <add> public boolean isEnableTimestamp() { <add> return this.enableTimestamp; <add> } <add> <add> @Override <add> public void initHeaders(MessageHeaderAccessor headerAccessor) { <add> headerAccessor.setIdGenerator(getIdGenerator()); <add> headerAccessor.setEnableTimestamp(isEnableTimestamp()); <add> } <add> <add> <add> private static final IdGenerator ID_VALUE_NONE_GENERATOR = new IdGenerator() { <add> @Override <add> public UUID generateId() { <add> return MessageHeaders.ID_VALUE_NONE; <add> } <add> }; <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/MessageHeaderAccessor.java <ide> public MessageHeaderAccessor() { <ide> public MessageHeaderAccessor(Message<?> message) { <ide> if (message != null) { <ide> this.headers = new MutableMessageHeaders(message.getHeaders()); <del> MessageHeaderAccessor accessor = getAccessor(message, MessageHeaderAccessor.class); <del> if (accessor != null) { <del> this.idGenerator = accessor.idGenerator; <del> this.enableTimestamp = accessor.enableTimestamp; <del> } <ide> } <ide> else { <ide> this.headers = new MutableMessageHeaders(); <ide> public boolean isMutable() { <ide> } <ide> <ide> /** <del> * A private mechanism for providing an alternate IdGenerator strategy. <add> * A package private mechanism to configure the IdGenerator strategy to use. <ide> * <ide> * <p>By default this property is not set in which case the default IdGenerator <del> * of {@link org.springframework.messaging.MessageHeaders} is used. <add> * in {@link org.springframework.messaging.MessageHeaders} is used. <ide> * <del> * @see org.springframework.messaging.support.MessageHeaderAccessorFactorySupport <add> * @see org.springframework.messaging.support.IdTimestampMessageHeaderInitializer <ide> */ <ide> void setIdGenerator(IdGenerator idGenerator) { <ide> this.idGenerator = idGenerator; <ide> } <ide> <ide> /** <del> * A private mechanism to enable having a timestamp added to every message. <add> * A package private mechanism to enables the automatic addition of the <add> * {@link org.springframework.messaging.MessageHeaders#TIMESTAMP} header. <ide> * <ide> * <p>By default this property is set to false. <ide> * <del> * @see org.springframework.messaging.support.MessageHeaderAccessorFactorySupport <add> * @see org.springframework.messaging.support.IdTimestampMessageHeaderInitializer <ide> */ <ide> void setEnableTimestamp(boolean enableTimestamp) { <ide> this.enableTimestamp = enableTimestamp; <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/MessageHeaderAccessorFactorySupport.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.messaging.support; <del> <del>import org.springframework.util.IdGenerator; <del> <del>/** <del> * A support class for factories creating pre-configured instances of type <del> * {@link org.springframework.messaging.support.MessageHeaderAccessor}. <del> * <del> * @author Rossen Stoyanchev <del> * @since 4.1 <del> */ <del>public class MessageHeaderAccessorFactorySupport { <del> <del> private IdGenerator idGenerator; <del> <del> private Boolean enableTimestamp; <del> <del> <del> protected MessageHeaderAccessorFactorySupport() { <del> } <del> <del> /** <del> * <del> * @param idGenerator <del> */ <del> public void setIdGenerator(IdGenerator idGenerator) { <del> this.idGenerator = idGenerator; <del> } <del> <del> public IdGenerator getIdGenerator() { <del> return this.idGenerator; <del> } <del> <del> public void setEnableTimestamp(boolean enableTimestamp) { <del> this.enableTimestamp = enableTimestamp; <del> } <del> <del> public boolean isEnableTimestamp() { <del> return this.enableTimestamp; <del> } <del> <del> protected void updateMessageHeaderAccessor(MessageHeaderAccessor headerAccessor) { <del> if (this.idGenerator != null) { <del> headerAccessor.setIdGenerator(this.idGenerator); <del> } <del> if (this.enableTimestamp != null) { <del> headerAccessor.setEnableTimestamp(this.enableTimestamp); <del> } <del> } <del> <del>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/MessageHeaderInitializer.java <add>/* <add> * Copyright 2002-2014 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.messaging.support; <add> <add>/** <add> * Callback interface for initializing a <add> * {@link org.springframework.messaging.support.MessageHeaderAccessor MessageHeaderAccessor}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public interface MessageHeaderInitializer { <add> <add> /** <add> * Initialize the given {@code MessageHeaderAccessor}. <add> * <add> * @param headerAccessor the instance to initialize <add> */ <add> void initHeaders(MessageHeaderAccessor headerAccessor); <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompHeaderAccessorTests.java <ide> import org.springframework.messaging.MessageHeaders; <ide> import org.springframework.messaging.simp.SimpMessageHeaderAccessor; <ide> import org.springframework.messaging.simp.SimpMessageType; <add>import org.springframework.messaging.support.IdTimestampMessageHeaderInitializer; <ide> import org.springframework.messaging.support.MessageBuilder; <ide> import org.springframework.messaging.support.MessageHeaderAccessor; <ide> import org.springframework.util.AlternativeJdkIdGenerator; <ide> public void messageIdAndTimestampDefaultBehavior() { <ide> <ide> @Test <ide> public void messageIdAndTimestampEnabled() { <del> DefaultStompHeaderAccessorFactory factory = new DefaultStompHeaderAccessorFactory(); <del> factory.setIdGenerator(new AlternativeJdkIdGenerator()); <del> factory.setEnableTimestamp(true); <add> IdTimestampMessageHeaderInitializer headerInitializer = new IdTimestampMessageHeaderInitializer(); <add> headerInitializer.setIdGenerator(new AlternativeJdkIdGenerator()); <add> headerInitializer.setEnableTimestamp(true); <ide> <del> StompHeaderAccessor headerAccessor = factory.create(StompCommand.SEND); <del> MessageHeaders headers = headerAccessor.getMessageHeaders(); <add> StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.SEND); <add> headerInitializer.initHeaders(headerAccessor); <ide> <del> assertNotNull(headers.getId()); <del> assertNotNull(headers.getTimestamp()); <add> assertNotNull(headerAccessor.getMessageHeaders().getId()); <add> assertNotNull(headerAccessor.getMessageHeaders().getTimestamp()); <ide> } <ide> <ide> @Test
11
Python
Python
add support for bitsandbytes
3104036e7f1a3cd6e07a69d648c3597de32f72fe
<ide><path>src/transformers/testing_utils.py <ide> from transformers import logging as transformers_logging <ide> <ide> from .deepspeed import is_deepspeed_available <del>from .integrations import is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available <add>from .integrations import ( <add> is_fairscale_available, <add> is_optuna_available, <add> is_ray_available, <add> is_sigopt_available, <add> is_wandb_available, <add>) <ide> from .utils import ( <add> is_apex_available, <add> is_bitsandbytes_available, <ide> is_detectron2_available, <ide> is_faiss_available, <ide> is_flax_available, <ide> def require_deepspeed(test_case): <ide> return test_case <ide> <ide> <add>def require_fairscale(test_case): <add> """ <add> Decorator marking a test that requires fairscale <add> """ <add> if not is_fairscale_available(): <add> return unittest.skip("test requires fairscale")(test_case) <add> else: <add> return test_case <add> <add> <add>def require_apex(test_case): <add> """ <add> Decorator marking a test that requires apex <add> """ <add> if not is_apex_available(): <add> return unittest.skip("test requires apex")(test_case) <add> else: <add> return test_case <add> <add> <add>def require_bitsandbytes(test_case): <add> """ <add> Decorator for bits and bytes (bnb) dependency <add> """ <add> if not is_bitsandbytes_available(): <add> return unittest.skip("test requires bnb")(test_case) <add> else: <add> return test_case <add> <add> <ide> def require_phonemizer(test_case): <ide> """ <ide> Decorator marking a test that requires phonemizer <ide><path>src/transformers/trainer.py <ide> def create_optimizer(self): <ide> ) <ide> else: <ide> self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs) <add> if optimizer_cls.__name__ == "Adam8bit": <add> import bitsandbytes <add> <add> manager = bitsandbytes.optim.GlobalOptimManager.get_instance() <add> <add> for module in self.model.modules(): <add> if isinstance(module, nn.Embedding): <add> manager.register_module_override(module, "weight", {"optim_bits": 32}) <add> logger.debug(f"bitsandbytes: will optimize {module} in fp32") <ide> <ide> if is_sagemaker_mp_enabled(): <ide> self.optimizer = smp.DistributedOptimizer(self.optimizer) <ide> def get_optimizer_cls_and_kwargs(args: TrainingArguments) -> Tuple[Any, Any]: <ide> optimizer_kwargs.update(adam_kwargs) <ide> except ImportError: <ide> raise ValueError("Trainer tried to instantiate apex FusedAdam but apex is not installed!") <add> elif args.optim == OptimizerNames.ADAMW_BNB: <add> try: <add> from bitsandbytes.optim import Adam8bit <add> <add> optimizer_cls = Adam8bit <add> optimizer_kwargs.update(adam_kwargs) <add> except ImportError: <add> raise ValueError("Trainer tried to instantiate bnb Adam8bit but bnb is not installed!") <ide> else: <ide> raise ValueError(f"Trainer cannot instantiate unsupported optimizer: {args.optim}") <ide> return optimizer_cls, optimizer_kwargs <ide><path>src/transformers/training_args.py <ide> class OptimizerNames(ExplicitEnum): <ide> ADAMW_TORCH_XLA = "adamw_torch_xla" <ide> ADAMW_APEX_FUSED = "adamw_apex_fused" <ide> ADAFACTOR = "adafactor" <add> ADAMW_BNB = "adamw_bnb_8bit" <ide> <ide> <ide> @dataclass <ide><path>src/transformers/utils/__init__.py <ide> DummyObject, <ide> _LazyModule, <ide> is_apex_available, <add> is_bitsandbytes_available, <ide> is_coloredlogs_available, <ide> is_datasets_available, <ide> is_detectron2_available, <ide><path>src/transformers/utils/import_utils.py <ide> def is_apex_available(): <ide> return importlib.util.find_spec("apex") is not None <ide> <ide> <add>def is_bitsandbytes_available(): <add> return importlib.util.find_spec("bitsandbytes") is not None <add> <add> <ide> def is_faiss_available(): <ide> return _faiss_available <ide> <ide><path>tests/extended/test_trainer_ext.py <ide> import re <ide> import sys <ide> import unittest <add>from typing import Tuple <ide> from unittest.mock import patch <ide> <ide> from parameterized import parameterized <del>from transformers.integrations import is_fairscale_available <add>from transformers import AutoModel <ide> from transformers.testing_utils import ( <ide> CaptureStderr, <ide> ExtendSysPath, <ide> TestCasePlus, <ide> execute_subprocess_async, <ide> get_gpu_count, <ide> get_torch_dist_unique_port, <add> require_apex, <add> require_bitsandbytes, <add> require_fairscale, <ide> require_torch, <ide> require_torch_gpu, <ide> require_torch_multi_gpu, <ide> ) <ide> from transformers.trainer_callback import TrainerState <ide> from transformers.trainer_utils import set_seed <del>from transformers.utils import is_apex_available <ide> <ide> <ide> bindir = os.path.abspath(os.path.dirname(__file__)) <ide> MBART_TINY = "sshleifer/tiny-mbart" <ide> <ide> <del># a candidate for testing_utils <del>def require_fairscale(test_case): <del> """ <del> Decorator marking a test that requires fairscale <del> """ <del> if not is_fairscale_available(): <del> return unittest.skip("test requires fairscale")(test_case) <del> else: <del> return test_case <del> <del> <del># a candidate for testing_utils <del>def require_apex(test_case): <del> """ <del> Decorator marking a test that requires apex <del> """ <del> if not is_apex_available(): <del> return unittest.skip("test requires apex")(test_case) <del> else: <del> return test_case <del> <del> <ide> @require_torch <ide> class TestTrainerExt(TestCasePlus): <ide> def run_seq2seq_quick( <ide> def test_trainer_log_level_replica(self, experiment_id): <ide> self.assertEqual(n_matches, data["n_matches"]) <ide> <ide> @slow <del> def test_run_seq2seq_slow(self): <add> def test_run_seq2seq(self): <ide> output_dir = self.run_trainer( <ide> eval_steps=2, <ide> max_len=128, <ide> def test_run_seq2seq_slow(self): <ide> assert "generated_predictions.txt" in contents <ide> assert "predict_results.json" in contents <ide> <add> @slow <add> @require_bitsandbytes <add> def test_run_seq2seq_bnb(self): <add> from transformers.training_args import OptimizerNames <add> <add> def train_and_return_metrics(optim: str) -> Tuple[int, float]: <add> from pathlib import Path <add> <add> extra_args = ( <add> f"--skip_memory_metrics 0 --optim {optim} --do_eval False --do_predict " <add> "False --adafactor False --log_level debug" <add> ) <add> <add> output_dir = self.run_trainer( <add> eval_steps=2, <add> max_len=128, <add> model_name=MARIAN_MODEL, <add> learning_rate=3e-4, <add> num_train_epochs=1, <add> distributed=True, # force run in a new process <add> extra_args_str=extra_args, <add> do_eval=False, <add> do_predict=False, <add> ) <add> <add> # Check metrics <add> logs = TrainerState.load_from_json(Path(output_dir, "trainer_state.json")).log_history <add> gpu_peak_mem = logs[0]["train_mem_gpu_peaked_delta"] <add> gpu_alloc_mem = logs[0]["train_mem_gpu_alloc_delta"] <add> <add> loss = logs[0]["train_loss"] <add> return gpu_peak_mem, gpu_alloc_mem, loss <add> <add> gpu_peak_mem_orig, gpu_alloc_mem_orig, loss_orig = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value) <add> gpu_peak_mem_bnb, gpu_alloc_mem_bnb, loss_bnb = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value) <add> <add> gpu_peak_mem_diff_bytes = gpu_peak_mem_orig - gpu_peak_mem_bnb <add> gpu_peak_mem_diff_percent = gpu_peak_mem_diff_bytes / gpu_peak_mem_bnb <add> <add> gpu_total_mem_orig = gpu_peak_mem_orig + gpu_alloc_mem_orig <add> gpu_total_mem_bnb = gpu_peak_mem_bnb + gpu_alloc_mem_bnb <add> <add> gpu_total_mem_diff_bytes = gpu_total_mem_orig - gpu_total_mem_bnb <add> gpu_total_mem_diff_percent = gpu_total_mem_diff_bytes / gpu_total_mem_bnb <add> <add> # leave this for now if CI gets very different results <add> # print(f"{gpu_alloc_mem_orig=:010d} {gpu_peak_mem_orig=:010d} {gpu_alloc_mem_orig+gpu_peak_mem_orig=:010d}" ) <add> # print(f" {gpu_alloc_mem_bnb=:010d} {gpu_peak_mem_bnb=:010d} {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=:010d}") <add> # print(f"{gpu_peak_mem_diff_bytes=}, {gpu_peak_mem_diff_percent=}") <add> # print(f"{gpu_total_mem_orig=}, {gpu_total_mem_bnb=}") <add> # print(f"{gpu_total_mem_diff_bytes=}, {gpu_total_mem_diff_percent=}") <add> <add> self.assertGreater( <add> gpu_peak_mem_diff_percent, <add> 10, # basically a huge difference - got ~30x on my desktop <add> "should use very little peak gpu memory with BNB, compared to without it" <add> f"but got gpu_peak_mem_orig={gpu_peak_mem_orig} and gpu_peak_mem_bnb={gpu_peak_mem_bnb}", <add> ) <add> <add> self.assertGreater( <add> gpu_total_mem_diff_percent, <add> 0.20, # could easily be 0.50, but let's stay on the safe side <add> "Using BNB should use less total GPU memory than without it" <add> f"but got gpu_total_mem_orig={gpu_total_mem_orig} and gpu_total_mem_bnb={gpu_total_mem_bnb}", <add> ) <add> <add> self.assertEqual( <add> loss_orig, loss_bnb, "loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}" <add> ) <add> <add> # Additionally let's test that the absolute gpu memory difference is larger or about the <add> # same as the expected saving coming from BNB (6 bytes per param) <add> model = AutoModel.from_pretrained(MARIAN_MODEL) <add> total_numel = sum(dict((p.data_ptr(), p.numel()) for p in model.parameters()).values()) <add> bnb_saved_bytes = total_numel * 6 # 324MB <add> <add> self.assertGreater( <add> gpu_total_mem_diff_bytes, <add> bnb_saved_bytes * 0.8, # add a safety margin, if it saved slightly less <add> f"BNB should have saved about {bnb_saved_bytes} bytes, but the saved bytes were {gpu_total_mem_diff_bytes}", <add> ) <add> <ide> def run_trainer( <ide> self, <ide> eval_steps: int, <ide> def run_trainer( <ide> {self.examples_dir_str}/pytorch/translation/run_translation.py <ide> """.split() <ide> cmd = [sys.executable] + distributed_args + args <add> # keep for quick debug <add> # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die <ide> execute_subprocess_async(cmd, env=self.get_env()) <ide> else: <ide> testargs = ["run_translation.py"] + args <ide><path>tests/trainer/test_trainer.py <ide> ) <ide> from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR <ide> from transformers.training_args import OptimizerNames <del>from transformers.utils import WEIGHTS_NAME, is_apex_available <add>from transformers.utils import WEIGHTS_NAME, is_apex_available, is_bitsandbytes_available <ide> from transformers.utils.hp_naming import TrialShortNamer <ide> <ide> <ide> def hp_name(trial): <ide> }, <ide> ), <ide> ] <add> <ide> if is_apex_available(): <ide> import apex <ide> <ide> def hp_name(trial): <ide> ) <ide> ) <ide> <add> if is_bitsandbytes_available(): <add> import bitsandbytes as bnb <add> <add> optim_test_params.append( <add> ( <add> OptimizerNames.ADAMW_BNB, <add> bnb.optim.Adam8bit, <add> default_adam_kwargs, <add> ) <add> ) <add> <ide> <ide> @require_torch <ide> class TrainerOptimizerChoiceTest(unittest.TestCase): <ide> def test_optim_supported(self, name: str, expected_cls, mandatory_kwargs): <ide> <ide> def test_fused_adam(self): <ide> # Pretend that apex is installed and mock apex.optimizers.FusedAdam exists. <del> # Trainer.get_optimizer_cls_and_kwargs does not use FusedAdam, but only has to return a <del> # class called, so mocking apex.optimizers.FusedAdam should be fine for testing and allow <add> # Trainer.get_optimizer_cls_and_kwargs does not use FusedAdam. It only has to return the <add> # class given, so mocking apex.optimizers.FusedAdam should be fine for testing and allow <ide> # the test to run without requiring an apex installation. <ide> mock = Mock() <ide> modules = { <ide> def test_fused_adam_no_apex(self): <ide> with self.assertRaises(ValueError): <ide> Trainer.get_optimizer_cls_and_kwargs(args) <ide> <add> def test_bnb_adam8bit(self): <add> # Pretend that Bits and Bytes is installed and mock bnb.optim.Adam8bit exists. <add> # Trainer.get_optimizer_cls_and_kwargs does not use Adam8bit. It only has to return the <add> # class given, so mocking bnb.optim.Adam8bit should be fine for testing and allow <add> # the test to run without requiring a bnb installation. <add> mock = Mock() <add> modules = { <add> "bitsandbytes": mock, <add> "bitsandbytes.optim": mock.optim, <add> "bitsandbytes.optim.Adam8bit": mock.optim.Adam8bit, <add> } <add> with patch.dict("sys.modules", modules): <add> self.check_optim_and_kwargs( <add> OptimizerNames.ADAMW_BNB, <add> default_adam_kwargs, <add> mock.optim.Adam8bit, <add> ) <add> <add> def test_bnb_adam8bit_no_bnb(self): <add> args = TrainingArguments(optim=OptimizerNames.ADAMW_BNB, output_dir="None") <add> <add> # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing <add> # bnb will fail even if bnb is installed. <add> with patch.dict("sys.modules", {"bnb.optim": None}): <add> with self.assertRaises(ValueError): <add> Trainer.get_optimizer_cls_and_kwargs(args) <add> <ide> <ide> @require_torch <ide> @require_wandb
7
Ruby
Ruby
avoid a new hash object
a9c0eb439263a10937918a32b19d23478245d7f8
<ide><path>actionpack/lib/action_controller/metal/url_for.rb <ide> def url_options <ide> :port => request.optional_port, <ide> :protocol => request.protocol, <ide> :_recall => request.path_parameters <del> }.merge(super).freeze <add> }.merge!(super).freeze <ide> <ide> if (same_origin = _routes.equal?(env["action_dispatch.routes".freeze])) || <ide> (script_name = env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]) ||
1
Python
Python
change metric_key_prefix in seq2seq_trainer.py
285131bfb4d05c2f15a4c22a4583bddaa2b47c7e
<ide><path>src/transformers/trainer_seq2seq.py <ide> def predict( <ide> self, <ide> test_dataset: Dataset, <ide> ignore_keys: Optional[List[str]] = None, <del> metric_key_prefix: str = "eval", <add> metric_key_prefix: str = "test", <ide> max_length: Optional[int] = None, <ide> num_beams: Optional[int] = None, <ide> ) -> PredictionOutput:
1
Mixed
Ruby
rotate default logs on each 100mb
cdce275f70f364567e34fa01c82c1193e7b1913c
<ide><path>guides/source/configuring.md <ide> Below are the default values associated with each target version. In cases of co <ide> - [`config.active_support.default_message_encryptor_serializer`](#config-active-support-default-message-encryptor-serializer): `:json` <ide> - [`config.active_support.default_message_verifier_serializer`](#config-active-support-default-message-verifier-serializer): `:json` <ide> - [`config.action_controller.allow_deprecated_parameters_hash_equality`](#config-action-controller-allow-deprecated-parameters-hash-equality): `false` <add>- [`config.log_file_size`](#config-log-file-size): `100.megabytes` <ide> <ide> #### Default Values for Target Version 7.0 <ide> <ide> Forces all requests to be served over HTTPS, and sets "https://" as the default <ide> <ide> Sets the path where your app's JavaScript lives relative to the `app` directory. The default is `javascript`, used by [webpacker](https://github.com/rails/webpacker). An app's configured `javascript_path` will be excluded from `autoload_paths`. <ide> <add>#### `config.log_file_size` <add> <add>Defines the maximum size of the Rails log file. Defaults to 100 MB in development and test, and unlimited in all other environments. <add> <ide> #### `config.log_formatter` <ide> <ide> Defines the formatter of the Rails logger. This option defaults to an instance of `ActiveSupport::Logger::SimpleFormatter` for all environments. If you are setting a value for `config.logger` you must manually pass the value of your formatter to your logger before it is wrapped in an `ActiveSupport::TaggedLogging` instance, Rails will not do it for you. <ide><path>railties/CHANGELOG.md <add>* Allow configuration of logger size for local and test environments <add> <add> `config.log_file_size` <add> <add> Defaults to `100` megabytes. <add> <add> *Bernie Chiu* <add> <ide> * Enroll new apps in decrypted diffs of credentials by default. This behavior <ide> can be opted out of with the app generator's `--skip-decrypted-diffs` flag. <ide> <ide><path>railties/lib/rails/application/bootstrap.rb <ide> module Bootstrap <ide> # Initialize the logger early in the stack in case we need to log some deprecation. <ide> initializer :initialize_logger, group: :all do <ide> Rails.logger ||= config.logger || begin <del> logger = ActiveSupport::Logger.new(config.default_log_file) <add> logger = if config.log_file_size <add> ActiveSupport::Logger.new(config.default_log_file, 1, config.log_file_size) <add> else <add> ActiveSupport::Logger.new(config.default_log_file) <add> end <ide> logger.formatter = config.log_formatter <ide> logger = ActiveSupport::TaggedLogging.new(logger) <ide> logger <ide><path>railties/lib/rails/application/configuration.rb <ide> class Configuration < ::Rails::Engine::Configuration <ide> :read_encrypted_secrets, :log_level, :content_security_policy_report_only, <ide> :content_security_policy_nonce_generator, :content_security_policy_nonce_directives, <ide> :require_master_key, :credentials, :disable_sandbox, :add_autoload_paths_to_load_path, <del> :rake_eager_load, :server_timing <add> :rake_eager_load, :server_timing, :log_file_size <ide> <ide> attr_reader :encoding, :api_only, :loaded_config_version <ide> <ide> def initialize(*) <ide> @time_zone = "UTC" <ide> @beginning_of_week = :monday <ide> @log_level = :debug <add> @log_file_size = nil <ide> @generators = app_generators <ide> @cache_store = [ :file_store, "#{root}/tmp/cache/" ] <ide> @railties_order = [:all] <ide> def load_defaults(target_version) <ide> <ide> self.add_autoload_paths_to_load_path = false <ide> <add> if Rails.env.development? || Rails.env.test? <add> self.log_file_size = (100 * 1024 * 1024) <add> end <add> <ide> if respond_to?(:action_dispatch) <ide> action_dispatch.default_headers = { <ide> "X-Frame-Options" => "SAMEORIGIN", <ide><path>railties/test/application/configuration_test.rb <ide> def index <ide> assert_equal Rails.application.config.paths["log"].first, app.config.default_log_file.path <ide> end <ide> <add> test "config.log_file_size returns a 100MB size number in development" do <add> app "development" <add> <add> assert_equal 100.megabytes, app.config.log_file_size <add> end <add> <add> test "config.log_file_size returns a 100MB size number in test" do <add> app "test" <add> <add> assert_equal 100.megabytes, app.config.log_file_size <add> end <add> <add> test "config.log_file_size returns no limit in production" do <add> app "production" <add> <add> assert_equal nil, app.config.log_file_size <add> end <add> <ide> test "rake_tasks block works at instance level" do <ide> app_file "config/environments/development.rb", <<-RUBY <ide> Rails.application.configure do
5
Javascript
Javascript
add modifications to portuguese language
1d13d7c486afcb8e9be0869b04a5045c4cd8d443
<ide><path>underscore.date.languages.js <add>exports.portuguese = function (){ <add> _date.months = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]; <add> _date.monthsShort = ["Jan", "Feb", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"]; <add> _date.weekdays = ["Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado"]; <add> _date.weekdaysShort = ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"]; <add> _date.relativeTime = { <add> future: "em %s", <add> past: "%s atrás", <add> s: "segundos", <add> m: "um minuto", <add> mm: "%d minutos", <add> h: "uma hora", <add> hh: "%d horas", <add> d: "um dia", <add> dd: "%d dias", <add> M: "um mês", <add> MM: "%d meses", <add> y: "um ano", <add> yy: "%d anos" <add> }; <add> _date.ordinal = function (number) { <add> return 'º'; <add> }; <add>} <ide>\ No newline at end of file
1
PHP
PHP
fix cs errors
c481be289a10fdeadedff1f4c5219504effd5d0d
<ide><path>src/Core/HttpApplicationInterface.php <ide> namespace Cake\Core; <ide> <ide> use Cake\Http\MiddlewareQueue; <del>use Cake\Routing\RouteBuilder; <ide> use Psr\Http\Server\RequestHandlerInterface; <ide> <ide> /** <ide> interface HttpApplicationInterface extends RequestHandlerInterface <ide> * @return void <ide> */ <ide> public function bootstrap(): void; <add> <ide> /** <ide> * Define the HTTP middleware layers for an application. <ide> *
1
Text
Text
remove extra backtick
36c212e25e524d4bd7d88c28cd72bc8259406391
<ide><path>CPP_STYLE_GUIDE.md <ide> class Foo { <ide> <ide> ### `snake_case` for C-like structs <ide> <del>For `plain C-like structs snake_case can be used. <add>For plain C-like structs snake_case can be used. <ide> <ide> ```c++ <ide> struct foo_bar {
1
Javascript
Javascript
remove app variable as it’s only used once
61894816ba7ed65f498c373d039beb54164d5374
<ide><path>packages/next-server/server/render.js <ide> async function doRender (req, res, pathname, query, { <ide> } <ide> } <ide> <del> const app = <LoadableCapture report={moduleName => reactLoadableModules.push(moduleName)}> <del> <EnhancedApp {...{ <del> Component: EnhancedComponent, <del> router, <del> ...props <del> }} /> <del> </LoadableCapture> <del> <ide> const render = staticMarkup ? renderToStaticMarkup : renderToString <ide> <ide> let html <ide> async function doRender (req, res, pathname, query, { <ide> const ErrorDebug = require(join(distDir, SERVER_DIRECTORY, 'error-debug')).default <ide> html = render(<ErrorDebug error={err} />) <ide> } else { <del> html = render(app) <add> html = render( <add> <LoadableCapture report={moduleName => reactLoadableModules.push(moduleName)}> <add> <EnhancedApp <add> Component={EnhancedComponent} <add> router={router} <add> {...props} <add> /> <add> </LoadableCapture> <add> ) <ide> } <ide> } finally { <ide> head = Head.rewind() || defaultHead()
1
Text
Text
fix conflict text
d9bdb4f9bab15e35d6c4e084cc1b58d1ae0dc822
<ide><path>laravel/documentation/changes.md <ide> <ide> ## Contents <ide> <del><<<<<<< HEAD:laravel/documentation/changes.md <ide> - [Laravel 3.2](#3.2) <ide> - [Upgrading From 3.1](#upgrade-3.2) <del>======= <ide> - [Laravel 3.1.9](#3.1.9) <ide> - [Upgrading From 3.1.8](#upgrade-3.1.9) <del>>>>>>>> master:changes.md <ide> - [Laravel 3.1.8](#3.1.8) <ide> - [Upgrading From 3.1.7](#upgrade-3.1.8) <ide> - [Laravel 3.1.7](#3.1.7)
1
Text
Text
add a closing parenthesis
3edafd9e891a2da7acb2b7f1db70dcff8e52f333
<ide><path>curriculum/challenges/english/07-scientific-computing-with-python/scientific-computing-with-python-projects/arithmetic-formatter.md <ide> The function will return the correct conversion if the supplied problems are pro <ide> - Each operand (aka number on each side of the operator) has a max of four digits in width. Otherwise, the error string returned will be: <ide> `Error: Numbers cannot be more than four digits.` <ide> - If the user supplied the correct format of problems, the conversion you return will follow these rules: <del> - There should be a single space between the operator and the longest of the two operands, the operator will be on the same line as the second operand, both operands will be in the same order as provided (the first will be the top one and the second will be the bottom. <add> - There should be a single space between the operator and the longest of the two operands, the operator will be on the same line as the second operand, both operands will be in the same order as provided (the first will be the top one and the second will be the bottom). <ide> - Numbers should be right-aligned. <ide> - There should be four spaces between each problem. <ide> - There should be dashes at the bottom of each problem. The dashes should run along the entire length of each problem individually. (The example above shows what this should look like.)
1
PHP
PHP
add withlength() immutable helper
f4d7d350c38629c21ce1936ede0b8e63d0434d92
<ide><path>src/Network/Response.php <ide> public function protocol($protocol = null) <ide> * <ide> * @param int|null $bytes Number of bytes <ide> * @return int|null <add> * @deprecated 3.4.0 Use withLength() to set length instead. <ide> */ <ide> public function length($bytes = null) <ide> { <ide> public function length($bytes = null) <ide> return null; <ide> } <ide> <add> /** <add> * Create a new response with the Content-Length header set. <add> * <add> * @param int|string $bytes Number of bytes <add> * @return static <add> */ <add> public function withLength($bytes) <add> { <add> return $this->withHeader('Content-Length', (string)$bytes); <add> } <add> <ide> /** <ide> * Checks whether a response has not been modified according to the 'If-None-Match' <ide> * (Etags) and 'If-Modified-Since' (last modification date) request <ide><path>tests/TestCase/Network/ResponseTest.php <ide> public function testLength() <ide> $this->assertEquals('100', $response->getHeaderLine('Content-Length')); <ide> } <ide> <add> /** <add> * Tests settings the content length <add> * <add> * @return void <add> */ <add> public function testWithLength() <add> { <add> $response = new Response(); <add> $this->assertFalse($response->hasHeader('Content-Length')); <add> <add> $new = $response->withLength(100); <add> $this->assertFalse($response->hasHeader('Content-Length'), 'Old instance not modified'); <add> <add> $this->assertSame('100', $new->getHeaderLine('Content-Length')); <add> $this->assertSame('100', $new->length(), 'new method is compat with old.'); <add> } <add> <ide> /** <ide> * Tests setting the expiration date <ide> *
2
Python
Python
fix warning in autoschema.get_serializer_fields()
50acb9b2feb2fc3815e06cb881f81d3e16ff4864
<ide><path>rest_framework/schemas/inspectors.py <ide> def get_serializer_fields(self, path, method): <ide> serializer = None <ide> warnings.warn('{}.get_serializer() raised an exception during ' <ide> 'schema generation. Serializer fields will not be ' <del> 'generated for {} {}.'.format( <del> type(view), method, path)) <add> 'generated for {} {}.' <add> .format(view.__class__.__name__, method, path)) <ide> <ide> if isinstance(serializer, serializers.ListSerializer): <ide> return [
1
PHP
PHP
add support for nested having in queries
af03b0d634c9341d2ff8f3c92160fdf37428f4dc
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function addNestedWhereQuery($query, $boolean = 'and') <ide> return $this; <ide> } <ide> <add> public function havingNested(Closure $callback, $boolean = 'and') <add> { <add> call_user_func($callback, $query = $this->forNestedWhere()); <add> <add> return $this->addNestedHavingQuery($query, $boolean); <add> } <add> <add> /** <add> * Add another query builder as a nested where to the query builder. <add> * <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param string $boolean <add> * @return $this <add> */ <add> public function addNestedHavingQuery($query, $boolean = 'and') <add> { <add> if (count($query->havings)) { <add> $type = 'Nested'; <add> <add> $this->havings[] = compact('type', 'query', 'boolean'); <add> <add> $this->addBinding($query->getRawBindings()['having'], 'having'); <add> } <add> <add> return $this; <add> } <add> <ide> /** <ide> * Add a full sub-select to the query. <ide> * <ide> public function groupByRaw($sql, array $bindings = []) <ide> /** <ide> * Add a "having" clause to the query. <ide> * <del> * @param string $column <add> * @param \Closure|string $column <ide> * @param string|null $operator <ide> * @param string|null $value <ide> * @param string $boolean <ide> public function having($column, $operator = null, $value = null, $boolean = 'and <ide> $value, $operator, func_num_args() === 2 <ide> ); <ide> <add> // If the columns is actually a Closure instance, we will assume the developer <add> // wants to begin a nested having statement which is wrapped in parenthesis. <add> // We'll add that Closure to the query then return back out immediately. <add> if ($column instanceof Closure && is_null($operator)) { <add> return $this->havingNested($column, $boolean); <add> } <add> <ide> // If the given operator is not found in the list of valid operators we will <ide> // assume that the developer is just short-cutting the '=' operators and <ide> // we will set the operators to '=' and set the values appropriately. <ide> public function having($column, $operator = null, $value = null, $boolean = 'and <ide> /** <ide> * Add an "or having" clause to the query. <ide> * <del> * @param string $column <add> * @param \Closure|string $column <ide> * @param string|null $operator <ide> * @param string|null $value <ide> * @return $this <ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php <ide> protected function compileGroups(Builder $query, $groups) <ide> * @param array $havings <ide> * @return string <ide> */ <del> protected function compileHavings(Builder $query, $havings) <add> protected function compileHavings(Builder $query) <ide> { <del> $sql = implode(' ', array_map([$this, 'compileHaving'], $havings)); <add> $sql = collect($query->havings)->map(function ($having) { <add> return $having['boolean'].' '.$this->compileHaving($having); <add> })->implode(' '); <ide> <ide> return 'having '.$this->removeLeadingBoolean($sql); <ide> } <ide> <ide> /** <ide> * Compile a single having clause. <ide> * <add> * @param \Illuminate\Database\Query\Builder $query <ide> * @param array $having <ide> * @return string <ide> */ <ide> protected function compileHaving(array $having) <ide> // without doing any more processing on it. Otherwise, we will compile the <ide> // clause into SQL based on the components that make it up from builder. <ide> if ($having['type'] === 'Raw') { <del> return $having['boolean'].' '.$having['sql']; <add> return $having['sql']; <ide> } elseif ($having['type'] === 'between') { <ide> return $this->compileHavingBetween($having); <ide> } elseif ($having['type'] === 'Null') { <ide> protected function compileHaving(array $having) <ide> return $this->compileHavingNotNull($having); <ide> } elseif ($having['type'] === 'bit') { <ide> return $this->compileHavingBit($having); <add> } elseif ($having['type'] === 'Nested') { <add> return $this->compileNestedHavings($having); <ide> } <ide> <ide> return $this->compileBasicHaving($having); <ide> } <ide> <add> /** <add> * Compile a nested having clause. <add> * <add> * @param array $having <add> * @return string <add> */ <add> protected function compileNestedHavings($having) <add> { <add> return '('.substr($this->compileHavings($having['query']), 7).')'; <add> } <add> <ide> /** <ide> * Compile a basic having clause. <ide> * <ide> protected function compileBasicHaving($having) <ide> <ide> $parameter = $this->parameter($having['value']); <ide> <del> return $having['boolean'].' '.$column.' '.$having['operator'].' '.$parameter; <add> return $column.' '.$having['operator'].' '.$parameter; <ide> } <ide> <ide> /** <ide> protected function compileHavingBetween($having) <ide> <ide> $max = $this->parameter(last($having['values'])); <ide> <del> return $having['boolean'].' '.$column.' '.$between.' '.$min.' and '.$max; <add> return $column.' '.$between.' '.$min.' and '.$max; <ide> } <ide> <ide> /** <ide> protected function compileHavingNull($having) <ide> { <ide> $column = $this->wrap($having['column']); <ide> <del> return $having['boolean'].' '.$column.' is null'; <add> return $column.' is null'; <ide> } <ide> <ide> /** <ide> protected function compileHavingNotNull($having) <ide> { <ide> $column = $this->wrap($having['column']); <ide> <del> return $having['boolean'].' '.$column.' is not null'; <add> return $column.' is not null'; <ide> } <ide> <ide> /** <ide> protected function compileHavingBit($having) <ide> <ide> $parameter = $this->parameter($having['value']); <ide> <del> return $having['boolean'].' ('.$column.' '.$having['operator'].' '.$parameter.') != 0'; <add> return '('.$column.' '.$having['operator'].' '.$parameter.') != 0'; <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testHavings() <ide> $this->assertSame('select "category", count(*) as "total" from "item" where "department" = ? group by "category" having "total" > ?', $builder->toSql()); <ide> } <ide> <add> public function testNestedHavings() <add> { <add> $builder = $this->getBuilder(); <add> $builder->select('*')->from('users')->having('email', '=', 'foo')->orHaving(function ($q) { <add> $q->having('name', '=', 'bar')->having('age', '=', 25); <add> }); <add> $this->assertSame('select * from "users" having "email" = ? or ("name" = ? and "age" = ?)', $builder->toSql()); <add> $this->assertEquals([0 => 'foo', 1 => 'bar', 2 => 25], $builder->getBindings()); <add> } <add> <add> public function testNestedHavingBindings() <add> { <add> $builder = $this->getBuilder(); <add> $builder->having('email', '=', 'foo')->having(function ($q) { <add> $q->selectRaw('?', ['ignore'])->having('name', '=', 'bar'); <add> }); <add> $this->assertEquals([0 => 'foo', 1 => 'bar'], $builder->getBindings()); <add> } <add> <ide> public function testHavingBetweens() <ide> { <ide> $builder = $this->getBuilder();
3
Python
Python
update interface for node driver
af698ec0f200991b599eb20f012243ebd3d0f01b
<ide><path>libcloud/interface.py <ide> class INodeDriver(Interface): <ide> NODE_STATE_MAP = Attribute("""A mapping of states found in the response to <ide> their standard type. This is a constant.""") <ide> <del> def create_node(name, image, size, **kwargs): <add> def create_node(name, options, **kwargs): <ide> """ <ide> Creates a new node based on provided params. Name is ignored on some providers. <ide>
1
PHP
PHP
fix cs errors
1357fd172f09388c4debdbdc34c0f993ef4490c1
<ide><path>src/Database/Type/DateTimeType.php <ide> protected function _setClassName(string $class, string $fallback): void <ide> $class = $fallback; <ide> } <ide> $this->_className = $class; <del> $this->_datetimeInstance = new $this->_className; <add> $this->_datetimeInstance = new $this->_className(); <ide> } <ide> <ide> /** <ide><path>src/Form/Form.php <ide> public function implementedEvents(): array <ide> public function schema(?Schema $schema = null): Schema <ide> { <ide> if ($schema === null && empty($this->_schema)) { <del> $schema = $this->_buildSchema(new $this->_schemaClass); <add> $schema = $this->_buildSchema(new $this->_schemaClass()); <ide> } <ide> if ($schema) { <ide> $this->_schema = $schema; <ide><path>src/Http/MiddlewareQueue.php <ide> protected function resolve(int $index): ?callable <ide> $class <ide> )); <ide> } <del> $callable = new $className; <add> $callable = new $className(); <ide> } else { <ide> $callable = $this->queue[$index]; <ide> } <ide><path>src/I18n/I18n.php <ide> public static function translators(): TranslatorRegistry <ide> } <ide> <ide> static::$_collection = new TranslatorRegistry( <del> new PackageLocator, <add> new PackageLocator(), <ide> new FormatterLocator([ <ide> 'sprintf' => function () { <ide> return new SprintfFormatter(); <ide> public static function translators(): TranslatorRegistry <ide> return new IcuFormatter(); <ide> }, <ide> ]), <del> new TranslatorFactory, <add> new TranslatorFactory(), <ide> static::getLocale() <ide> ); <ide> <ide><path>src/I18n/MessagesFileLoader.php <ide> public function __invoke() <ide> throw new RuntimeException(sprintf('Could not find class %s', "{$name}FileParser")); <ide> } <ide> <del> $messages = (new $class)->parse($file); <add> $messages = (new $class())->parse($file); <ide> $package = new Package('default'); <ide> $package->setMessages($messages); <ide> <ide><path>src/ORM/Table.php <ide> public function getSaveOptionsBuilder(array $options = []): SaveOptionsBuilder <ide> */ <ide> public function loadInto($entities, array $contain) <ide> { <del> return (new LazyEagerLoader)->loadInto($entities, $contain, $this); <add> return (new LazyEagerLoader())->loadInto($entities, $contain, $this); <ide> } <ide> <ide> /** <ide><path>src/Validation/ValidatorAwareTrait.php <ide> protected function createValidator(string $name): Validator <ide> throw new RuntimeException($message); <ide> } <ide> <del> $validator = new $this->_validatorClass; <add> $validator = new $this->_validatorClass(); <ide> $validator = $this->$method($validator); <ide> if ($this instanceof EventDispatcherInterface) { <ide> $event = defined(self::class . '::BUILD_VALIDATOR_EVENT') ? self::BUILD_VALIDATOR_EVENT : 'Model.buildValidator';
7
Javascript
Javascript
add flow types to accessibilityexample.js
2b49664cb8667a7381936746c8006c56968143c3
<ide><path>packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js <ide> * LICENSE file in the root directory of this source tree. <ide> * <ide> * @format <add> * @flow <ide> */ <ide> <ide> 'use strict'; <ide> const { <ide> StyleSheet, <ide> Platform, <ide> } = require('react-native'); <add>import type {EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter'; <ide> <ide> const RNTesterBlock = require('../../components/RNTesterBlock'); <ide> <ide> const styles = StyleSheet.create({ <ide> }, <ide> }); <ide> <del>class AccessibilityExample extends React.Component { <del> render() { <add>class AccessibilityExample extends React.Component<{}> { <add> render(): React.Node { <ide> return ( <ide> <View> <ide> <RNTesterBlock title="TextView without label"> <ide> class AccessibilityExample extends React.Component { <ide> </RNTesterBlock> <ide> <ide> {/* Android screen readers will say the accessibility hint instead of the text <del> since the view doesn't have a label. */} <add> since the view doesn't have a label. */} <ide> <RNTesterBlock title="Accessible view with TextViews with hint"> <ide> <View accessibilityHint="Accessibility hint." accessible={true}> <ide> <Text style={{color: 'green'}}>This is text one.</Text> <ide> class AccessibilityExample extends React.Component { <ide> } <ide> } <ide> <del>class CheckboxExample extends React.Component { <add>class CheckboxExample extends React.Component< <add> {}, <add> { <add> checkboxState: boolean | 'mixed', <add> }, <add>> { <ide> state = { <ide> checkboxState: true, <ide> }; <ide> class CheckboxExample extends React.Component { <ide> } <ide> } <ide> <del>class SwitchExample extends React.Component { <add>class SwitchExample extends React.Component< <add> {}, <add> { <add> switchState: boolean, <add> }, <add>> { <ide> state = { <ide> switchState: true, <ide> }; <ide> class SwitchExample extends React.Component { <ide> } <ide> } <ide> <del>class SelectionExample extends React.Component { <del> constructor(props) { <add>class SelectionExample extends React.Component< <add> {}, <add> { <add> isSelected: boolean, <add> isEnabled: boolean, <add> }, <add>> { <add> constructor(props: {}) { <ide> super(props); <del> this.selectableElement = React.createRef(); <add> this.selectableElement = createRef(); <ide> } <add> selectableElement: { <add> current: React.ElementRef<typeof TouchableOpacity> | null, <add> }; <ide> <ide> state = { <ide> isSelected: true, <ide> isEnabled: false, <ide> }; <ide> <del> render() { <add> render(): React.Node { <ide> const {isSelected, isEnabled} = this.state; <ide> let accessibilityHint = 'click me to select'; <ide> if (isSelected) { <ide> class SelectionExample extends React.Component { <ide> } <ide> } <ide> <del>class ExpandableElementExample extends React.Component { <add>class ExpandableElementExample extends React.Component< <add> {}, <add> { <add> expandState: boolean, <add> }, <add>> { <ide> state = { <ide> expandState: false, <ide> }; <ide> class ExpandableElementExample extends React.Component { <ide> } <ide> } <ide> <del>class NestedCheckBox extends React.Component { <add>class NestedCheckBox extends React.Component< <add> {}, <add> { <add> checkbox1: boolean | 'mixed', <add> checkbox2: boolean | 'mixed', <add> checkbox3: boolean | 'mixed', <add> }, <add>> { <ide> state = { <ide> checkbox1: false, <ide> checkbox2: false, <ide> class NestedCheckBox extends React.Component { <ide> } <ide> <ide> class AccessibilityRoleAndStateExample extends React.Component<{}> { <del> render() { <add> render(): React.Node { <ide> return ( <ide> <View> <ide> <View <ide> class AccessibilityRoleAndStateExample extends React.Component<{}> { <ide> } <ide> } <ide> <del>class AccessibilityActionsExample extends React.Component { <del> render() { <add>class AccessibilityActionsExample extends React.Component<{}> { <add> render(): React.Node { <ide> return ( <ide> <View> <ide> <RNTesterBlock title="Non-touchable with activate action"> <ide> class AccessibilityActionsExample extends React.Component { <ide> } <ide> } <ide> <del>class FakeSliderExample extends React.Component { <del> state = { <add>type FakeSliderExampleState = { <add> current: number, <add> textualValue: 'center' | 'left' | 'right', <add>}; <add>class FakeSliderExample extends React.Component<{}, FakeSliderExampleState> { <add> state: FakeSliderExampleState = { <ide> current: 50, <ide> textualValue: 'center', <ide> }; <ide> <del> increment = () => { <add> increment: () => void = () => { <ide> let newValue = this.state.current + 2; <ide> if (newValue > 100) { <ide> newValue = 100; <ide> class FakeSliderExample extends React.Component { <ide> }); <ide> }; <ide> <del> decrement = () => { <add> decrement: () => void = () => { <ide> let newValue = this.state.current - 2; <ide> if (newValue < 0) { <ide> newValue = 0; <ide> class FakeSliderExample extends React.Component { <ide> }); <ide> }; <ide> <del> render() { <add> render(): React.Node { <ide> return ( <ide> <View> <ide> <View <ide> class AnnounceForAccessibility extends React.Component<{}> { <ide> _handleOnPress = () => <ide> AccessibilityInfo.announceForAccessibility('Announcement Test'); <ide> <del> render() { <add> render(): React.Node { <ide> return ( <ide> <View> <ide> <Button <ide> class AnnounceForAccessibility extends React.Component<{}> { <ide> } <ide> <ide> class SetAccessibilityFocusExample extends React.Component<{}> { <del> render() { <del> const myRef = createRef(); <add> render(): React.Node { <add> const myRef: {current: React.ElementRef<any> | null} = createRef(); <ide> <ide> const onClose = () => { <ide> if (myRef && myRef.current) { <ide> class SetAccessibilityFocusExample extends React.Component<{}> { <ide> } <ide> <ide> class EnabledExamples extends React.Component<{}> { <del> render() { <add> render(): React.Node { <ide> return ( <ide> <View> <ide> {Platform.OS === 'ios' ? ( <ide> class EnabledExamples extends React.Component<{}> { <ide> } <ide> } <ide> <del>class EnabledExample extends React.Component<{}> { <add>class EnabledExample extends React.Component< <add> { <add> eventListener: <add> | 'reduceMotionChanged' <add> | 'boldTextChanged' <add> | 'grayscaleChanged' <add> | 'invertColorsChanged' <add> | 'reduceTransparencyChanged' <add> | 'reduceMotionChanged' <add> | 'screenReaderChanged', <add> test: string, <add> }, <add> { <add> isEnabled: boolean, <add> }, <add>> { <ide> state = { <ide> isEnabled: false, <ide> }; <del> <add> _subscription: EventSubscription; <ide> componentDidMount() { <ide> this._subscription = AccessibilityInfo.addEventListener( <ide> this.props.eventListener, <ide> class EnabledExample extends React.Component<{}> { <ide> <ide> _handleToggled = isEnabled => { <ide> if (!this.state.isEnabled) { <del> this.setState({isEnabled}); <add> this.setState({isEnabled: true}); <ide> } else { <ide> this.setState({isEnabled: false}); <ide> } <ide> }; <ide> <del> render() { <add> render(): React.Node { <ide> return ( <ide> <View> <ide> <Text> <ide> exports.examples = [ <ide> }, <ide> { <ide> title: 'New accessibility roles and states', <del> render(): React.Element<typeof AccessibilityRoleAndStateExamples> { <add> render(): React.Element<typeof AccessibilityRoleAndStateExample> { <ide> return <AccessibilityRoleAndStateExample />; <ide> }, <ide> },
1
Text
Text
clarify active record encryption docs
85b2f7f2bd522abc18c569b3cd2144b44db2c787
<ide><path>guides/source/active_record_encryption.md <ide> Active Record Encryption <ide> <ide> This guide covers encrypting your database information using Active Record. <ide> <del>After reading this guide you will know: <add>After reading this guide, you will know: <ide> <ide> * How to set up database encryption with Active Record. <ide> * How to migrate unencrypted data <ide> After reading this guide you will know: <ide> <ide> -------------------------------------------------------------------------------- <ide> <del>Active Record supports application-level encryption. It works by declaring which attributes should be encrypted and seamlessly encrypting and decrypting them when necessary. The encryption layer is placed between the database and the application. The application will access unencrypted data but the database will store it encrypted. <add>Active Record supports application-level encryption. It works by declaring which attributes should be encrypted and seamlessly encrypting and decrypting them when necessary. The encryption layer sits between the database and the application. The application will access unencrypted data, but the database will store it encrypted. <ide> <ide> ## Why Encrypt Data at the Application Level? <ide> <del>Active Record Encryption is meant to protect sensitive information in your application. A typical example is personal information from customers. But why would you want to do this if, for example, you are already encrypting your database at rest? <add>Active Record Encryption exists to protect sensitive information in your application. A typical example is personally identifiable information from users. But why would you want application-level encryption if you are already encrypting your database at rest? <ide> <del>As an immediate practical benefit, encrypting sensitive attributes adds an additional security layer. For example, if an attacker gained access to your database, a snapshot of it, or your application logs, they wouldn't be able to make sense of the encrypted information. And even without thinking about malicious actors, checking application logs for legit reasons shouldn't expose personal information from customers either. <add>As an immediate practical benefit, encrypting sensitive attributes adds an additional security layer. For example, if an attacker gained access to your database, a snapshot of it, or your application logs, they wouldn't be able to make sense of the encrypted information. Additionally, encryption can prevent developers from unintentionally exposing users' sensitive data in application logs. <ide> <del>But more importantly, by using Active Record Encryption, you define what constitutes sensitive information in your application at the code level. This enables controlling how this information is accessed and building services around it. As examples, think about auditable Rails consoles that protect encrypted data or check the built-in system to [filter controller params automatically](#filtering-params-named-as-encrypted-columns). <add>But more importantly, by using Active Record Encryption, you define what constitutes sensitive information in your application at the code level. Active Record Encryption enables granular control of data access in your application and services consuming data from your application. For example, consider auditable Rails consoles that protect encrypted data or check the built-in system to [filter controller params automatically](#filtering-params-named-as-encrypted-columns). <ide> <ide> ## Basic Usage <ide> <ide> ### Setup <ide> <del>First, you need to add some keys to your [rails credentials](/security.html#custom-credentials). Run `bin/rails db:encryption:init` to generate a random key set: <add>First, you need to add some keys to your [Rails credentials](/security.html#custom-credentials). Run `bin/rails db:encryption:init` to generate a random key set: <ide> <ide> ```bash <ide> $ bin/rails db:encryption:init <ide> active_record_encryption: <ide> key_derivation_salt: xEY0dt6TZcAMg52K7O84wYzkjvbA62Hz <ide> ``` <ide> <del>NOTE: These generated keys and salt are 32 bytes length. If you generate these yourself, the minimum lengths you should use are 12 bytes for the primary key (this will be used to derive the AES 32 bytes key) and 20 bytes for the salt. <add>NOTE: These generated values are 32 bytes in length. If you generate these yourself, the minimum lengths you should use are 12 bytes for the primary key (this will be used to derive the AES 32 bytes key) and 20 bytes for the salt. <ide> <ide> ### Declaration of Encrypted Attributes <ide> <ide> class Article < ApplicationRecord <ide> end <ide> ```` <ide> <del>The library will transparently encrypt these attributes before saving them into the database, and will decrypt them when retrieving their values: <add>The library will transparently encrypt these attributes before saving them in the database and will decrypt them upon retrieval: <ide> <ide> ```ruby <ide> article = Article.create title: "Encrypt it all!" <ide> article.title # => "Encrypt it all!" <ide> ``` <ide> <del>But, under the hood, the executed SQL would look like this: <add>But, under the hood, the executed SQL looks like this: <ide> <ide> ```sql <ide> INSERT INTO `articles` (`title`) VALUES ('{\"p\":\"n7J0/ol+a7DRMeaE\",\"h\":{\"iv\":\"DXZMDWUKfp3bg/Yu\",\"at\":\"X1/YjMHbHD4talgF9dt61A==\"}}') <ide> ``` <ide> <del>Encryption takes additional space in the column. You can estimate the worst-case overload in around 250 bytes when the built-in envelope encryption key provider is used. For medium and large text columns this overload is negligible, but for `string` columns of 255 bytes, you should increase their limit accordingly (510 is recommended). <del> <del>NOTE: The reason for the additional space are Base 64 encoding and additional metadata stored with the encrypted values. <add>Because Base 64 encoding and metadata are stored with the values, encryption requires extra space in the column. You can estimate the worst-case overload at around 250 bytes when the built-in envelope encryption key provider is used. This overload is negligible for medium and large text columns, but for `string` columns of 255 bytes, you should increase their limit accordingly (510 bytes is recommended). <ide> <ide> ### Deterministic and Non-deterministic Encryption <ide> <del>By default, Active Record Encryption uses a non-deterministic approach to encryption. This means that encrypting the same content with the same password twice will result in different ciphertexts. This is good for security, since it makes crypto-analysis of encrypted content much harder, but it makes querying the database impossible. <add>By default, Active Record Encryption uses a non-deterministic approach to encryption. Non-deterministic, in this context, means that encrypting the same content with the same password twice will result in different ciphertexts. This approach improves security by making crypto-analysis of ciphertexts harder, and querying the database impossible. <ide> <ide> You can use the `deterministic:` option to generate initialization vectors in a deterministic way, effectively enabling querying encrypted data. <ide> <ide> end <ide> Author.find_by_email("some@email.com") # You can query the model normally <ide> ``` <ide> <del>The recommendation is using the default (non deterministic) unless you need to query the data. <add>The non-deterministic approach is recommended unless you need to query the data. <ide> <del>NOTE: In non-deterministic mode, it uses AES-GCM with a 256-bits key and a random initialization vector. In deterministic mode, it uses AES-GCM too but the initialization vector is generated as a HMAC-SHA-256 digest of the key and contents to encrypt. <add>NOTE: In non-deterministic mode, Active Record uses AES-GCM with a 256-bits key and a random initialization vector. In deterministic mode, it also uses AES-GCM, but the initialization vector is generated as an HMAC-SHA-256 digest of the key and contents to encrypt. <ide> <del>NOTE: You can disable deterministic encryption just by not configuring a `deterministic_key`. <add>NOTE: You can disable deterministic encryption by omitting a `deterministic_key`. <ide> <ide> ## Features <ide> <ide> When enabled, all the encryptable attributes will be encrypted according to the <ide> <ide> #### Action Text Fixtures <ide> <del>To encrypt action text fixtures you should place them in `fixtures/action_text/encrypted_rich_texts.yml`. <add>To encrypt action text fixtures, you should place them in `fixtures/action_text/encrypted_rich_texts.yml`. <ide> <ide> ### Supported Types <ide> <ide> To encrypt action text fixtures you should place them in `fixtures/action_text/e <ide> If you need to support a custom type, the recommended way is using a [serialized attribute](https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html). The declaration of the serialized attribute should go **before** the encryption declaration: <ide> <ide> ```ruby <del># GOOD <add># CORRECT <ide> class Article < ApplicationRecord <ide> serialize :title, Title <ide> encrypts :title <ide> end <ide> <del># WRONG <add># INCORRECT <ide> class Article < ApplicationRecord <ide> encrypts :title <ide> serialize :title, Title <ide> end <ide> <ide> ### Ignoring Case <ide> <del>You might need to ignore case when querying deterministically encrypted data. There are two options that can help you here. <add>You might need to ignore casing when querying deterministically encrypted data. Two approaches make accomplishing this easier: <ide> <ide> You can use the `:downcase` option when declaring the encrypted attribute to downcase the content before encryption occurs. <ide> <ide> class Person <ide> end <ide> ``` <ide> <del>When using `:downcase`, the original case is lost. In some situations, you might want to ignore the case only when querying, while also storing the original case. For those situations, you can use the option `:ignore_case`. This requires you to add a new column named `original_<column_name>` to store the content with the case unchanged: <add>When using `:downcase`, the original case is lost. In some situations, you might want to ignore the case only when querying while also storing the original case. For those situations, you can use the option `:ignore_case`. This requires you to add a new column named `original_<column_name>` to store the content with the case unchanged: <ide> <ide> ```ruby <ide> class Label <ide> end <ide> To ease migrations of unencrypted data, the library includes the option `config.active_record.encryption.support_unencrypted_data`. When set to `true`: <ide> <ide> * Trying to read encrypted attributes that are not encrypted will work normally, without raising any error <del>* Queries with deterministically-encrypted attributes will include the "clear text" version of them, to support finding both encrypted and unencrypted content. You need to set `config.active_record.encryption.extend_queries = true` to enable this. <add>* Queries with deterministically-encrypted attributes will include the "clear text" version of them to support finding both encrypted and unencrypted content. You need to set `config.active_record.encryption.extend_queries = true` to enable this. <ide> <del>**This options is meant to be used in transition periods** while clear data and encrypted data need to coexist. Their value is `false` by default, which is the recommended goal for any application: errors will be raised when working with unencrypted data. <add>**This option is meant to be used during transition periods** while clear data and encrypted data must coexist. Both are set to `false` by default, which is the recommended goal for any application: errors will be raised when working with unencrypted data. <ide> <ide> ### Support for Previous Encryption Schemes <ide> <del>Changing encryption properties of attributes can break existing data. For example, imagine you want to make a "deterministic" attribute "not deterministic". If you just change the declaration in the model, reading existing ciphertexts will fail because they are different now. <add>Changing encryption properties of attributes can break existing data. For example, imagine you want to make a deterministic attribute non-deterministic. If you just change the declaration in the model, reading existing ciphertexts will fail because the encryption method is different now. <ide> <ide> To support these situations, you can declare previous encryption schemes that will be used in two scenarios: <ide> <ide> * When reading encrypted data, Active Record Encryption will try previous encryption schemes if the current scheme doesn't work. <del>* When querying deterministic data, it will add ciphertexts using previous schemes to the queries so that queries work seamlessly with data encrypted with different scheme. You need to set `config.active_record.encryption.extend_queries = true` to enable this. <add>* When querying deterministic data, it will add ciphertexts using previous schemes so that queries work seamlessly with data encrypted with different schemes. You must set `config.active_record.encryption.extend_queries = true` to enable this. <ide> <ide> You can configure previous encryption schemes: <ide> <ide> When adding previous encryption schemes: <ide> * With **non-deterministic encryption**, new information will always be encrypted with the *newest* (current) encryption scheme. <ide> * With **deterministic encryption**, new information will always be encrypted with the *oldest* encryption scheme by default. <ide> <del>The reason is that, with deterministic encryption, you normally want ciphertexts to remain constant. You can change this behavior by setting `deterministic: { fixed: false }`. In that case, it will use the *newest* encryption scheme for encrypting new data. <add>Typically, with deterministic encryption, you want ciphertexts to remain constant. You can change this behavior by setting `deterministic: { fixed: false }`. In that case, it will use the *newest* encryption scheme for encrypting new data. <ide> <ide> ### Unique Constraints <ide> <del>NOTE: Unique constraints can only be used with data encrypted deterministically. <add>NOTE: Unique constraints can only be used with deterministically encrypted data. <ide> <ide> #### Unique Validations <ide> <ide> class Person <ide> end <ide> ``` <ide> <del>They will also work when combining encrypted and unencrypted data, and when configuring previous encryption schemes. <add>They will also work when combining encrypted and unencrypted data,git and when configuring previous encryption schemes. <ide> <del>NOTE: If you want to ignore case make sure to use `downcase:` or `ignore_case:` in the `encrypts` declaration. Using the `case_sensitive:` option in the validation won't work. <add>NOTE: If you want to ignore case, make sure to use `downcase:` or `ignore_case:` in the `encrypts` declaration. Using the `case_sensitive:` option in the validation won't work. <ide> <ide> #### Unique Indexes <ide> <del>To support unique indexes on deterministically-encrypted columns, you need to make sure their ciphertext doesn't ever change. <add>To support unique indexes on deterministically-encrypted columns, you need to ensure their ciphertext doesn't ever change. <ide> <del>To encourage this, by default, deterministic attributes will always use the oldest encryption scheme, when multiple encryption schemes are configured. Other than this, it's up to you making sure that encryption properties don't change for these attributes, or the unique indexes won't work. <add>To encourage this, deterministic attributes will always use the oldest available encryption scheme by default when multiple encryption schemes are configured. Otherwise, it's your job to ensure encryption properties don't change for these attributes, or the unique indexes won't work. <ide> <ide> ```ruby <ide> class Person <ide> end <ide> <ide> ### Filtering Params Named as Encrypted Columns <ide> <del>By default, encrypted columns are configured to be [automatically filtered in Rails logs](https://guides.rubyonrails.org/action_controller_overview.html#parameters-filtering). You can disable this behavior by adding this to your `application.rb`: <add>By default, encrypted columns are configured to be [automatically filtered in Rails logs](https://guides.rubyonrails.org/action_controller_overview.html#parameters-filtering). You can disable this behavior by adding the following to your `application.rb`: <ide> <ide> ```ruby <ide> config.active_record.encryption.add_to_filter_parameters = false <ide> In case you want exclude specific columns from this automatic filtering, add the <ide> <ide> The library will preserve the encoding for string values encrypted non-deterministically. <ide> <del>For values encrypted deterministically, by default, the library will force UTF-8 encoding. The reason is that encoding is stored along with the encrypted payload. This means that the same value with a different encoding will result in different ciphertexts when encrypted. You normally want to avoid this to keep queries and uniqueness constraints working, so the library will perform the conversion automatically on your behalf. <add>Because encoding is stored along with the encrypted payload, values encrypted deterministically will force UTF-8 encoding by default. Therefore the same value with a different encoding will result in a different ciphertext when encrypted. You usually want to avoid this to keep queries and uniqueness constraints working, so the library will perform the conversion automatically on your behalf. <ide> <ide> You can configure the desired default encoding for deterministic encryption with: <ide> <ide> config.active_record.encryption.forced_encoding_for_deterministic_encryption = n <ide> <ide> ## Key Management <ide> <del>Key management strategies are implemented by key providers. You can configure key providers globally or on a per-attribute basis. <add>Key providers implement key management strategies. You can configure key providers globally, or on a per attribute basis. <ide> <ide> ### Built-in Key Providers <ide> <ide> Implements a simple [envelope encryption](https://docs.aws.amazon.com/kms/latest <ide> - It generates a random key for each data-encryption operation <ide> - It stores the data-key with the data itself, encrypted with a primary key defined in the credential `active_record.encryption.primary_key`. <ide> <del>You can configure by adding this to your `application.rb`: <add>You can configure Active Record to use this key provider by adding this to your `application.rb`: <ide> <ide> ```ruby <ide> config.active_record.encryption.key_provider = ActiveRecord::Encryption::EnvelopeEncryptionKeyProvider.new <ide> ``` <ide> <del>As with other built-in key providers, you can provide a list of primary keys in `active_record.encryption.primary_key`, to implement key-rotation schemes. <add>As with other built-in key providers, you can provide a list of primary keys in `active_record.encryption.primary_key` to implement key-rotation schemes. <ide> <ide> ### Custom Key Providers <ide> <ide> class Article < ApplicationRecord <ide> end <ide> ``` <ide> <del>The key will be used internally to derive the key used to encrypt and decrypt the data. <add>Active Record uses the key to derive the key used to encrypt and decrypt the data. <ide> <ide> ### Rotating Keys <ide> <ide> active_record <ide> key_derivation_salt: a3226b97b3b2f8372d1fc6d497a0c0d3 <ide> ``` <ide> <del>This enables workflows where you keep a short list of keys, by adding new keys, re-encrypting content and deleting old keys. <add>This enables workflows in which you keep a short list of keys by adding new keys, re-encrypting content, and deleting old keys. <ide> <ide> NOTE: Rotating keys is not currently supported for deterministic encryption. <ide> <ide> NOTE: Active Record Encryption doesn't provide automatic management of key rotation processes yet. All the pieces are there, but this hasn't been implemented yet. <ide> <ide> ### Storing Key References <ide> <del>There is a setting `active_record.encryption.store_key_references` you can use to make `active_record.encryption` store a reference to the encryption key in the encrypted message itself. <add>You can configure `active_record.encryption.store_key_references` to make `active_record.encryption` store a reference to the encryption key in the encrypted message itself. <ide> <ide> ```ruby <ide> config.active_record.encryption.store_key_references = true <ide> ``` <ide> <del>This makes for a more performant decryption since, instead of trying lists of keys, the system can now locate keys directly. The price to pay is storage: encrypted data will be a bit bigger in size. <add>Doing so makes for more performant decryption because the system can now locate keys directly instead of trying lists of keys. The price to pay is storage: encrypted data will be a bit bigger. <ide> <ide> ## API <ide> <ide> ### Basic API <ide> <del>ActiveRecord encryption is meant to be used declaratively, but it presents an API for advanced usage scenarios. <add>ActiveRecord encryption is meant to be used declaratively, but it offers an API for advanced usage scenarios. <ide> <ide> #### Encrypt and Decrypt <ide> <ide> article.encrypted_attribute?(:title) <ide> <ide> ### Configuration Options <ide> <del>You can configure Active Record Encryption options by setting them in your `application.rb` (most common scenario) or in a specific environment config file `config/environments/<env name>.rb` if you want to set them on a per-environment basis. <add>You can configure Active Record Encryption options in your `application.rb` (most common scenario) or in a specific environment config file `config/environments/<env name>.rb` if you want to set them on a per-environment basis. <ide> <ide> All the config options are namespaced in `active_record.encryption.config`. For example: <ide> <ide> The available config options are: <ide> <ide> | Key | Value | <ide> | ------------------------------------------------------------ | ------------------------------------------------------------ | <del>| `support_unencrypted_data` | When true, unencrypted data can be read normally. When false, it will raise. Default: false. | <del>| `extend_queries` | When true, queries referencing deterministically encrypted attributes will be modified to include additional values if needed. Those additional values will be the clean version of the value, when `support_unencrypted_data` is true) and values encrypted with previous encryption schemes if any (as provided with the `previous:` option). Default: false (experimental). | <del>| `encrypt_fixtures` | When true, encryptable attributes in fixtures will be automatically encrypted when those are loaded. Default: false. | <del>| `store_key_references` | When true, a reference to the encryption key is stored in the headers of the encrypted message. This makes for a faster decryption when multiple keys are in use. Default: false. | <del>| `add_to_filter_parameters` | When true, encrypted attribute names are added automatically to the [list of filtered params](https://guides.rubyonrails.org/configuring.html#rails-general-configuration) that won't be shown in logs. Default: true. | <add>| `support_unencrypted_data` | When true, unencrypted data can be read normally. When false, it will raise errors. Default: false. | <add>| `extend_queries` | When true, queries referencing deterministically encrypted attributes will be modified to include additional values if needed. Those additional values will be the clean version of the value (when `support_unencrypted_data` is true) and values encrypted with previous encryption schemes, if any (as provided with the `previous:` option). Default: false (experimental). | <add>| `encrypt_fixtures` | When true, encryptable attributes in fixtures will be automatically encrypted when loaded. Default: false. | <add>| `store_key_references` | When true, a reference to the encryption key is stored in the headers of the encrypted message. This makes for faster decryption when multiple keys are in use. Default: false. | <add>| `add_to_filter_parameters` | When true, encrypted attribute names are added automatically to the [list of filtered params](https://guides.rubyonrails.org/configuring.html#rails-general-configuration) and won't be shown in logs. Default: true. | <ide> | `excluded_from_filter_parameters` | You can configure a list of params that won't be filtered out when `add_to_filter_parameters` is true. Default: []. | <ide> | `validate_column_size` | Adds a validation based on the column size. This is recommended to prevent storing huge values using highly compressible payloads. Default: true. | <del>| `primary_key` | The key or lists of keys that is used to derive root data-encryption keys. They way they are used depends on the key provider configured. It's preferred to configure it via a credential `active_record_encryption.primary_key`. | <add>| `primary_key` | The key or lists of keys used to derive root data-encryption keys. The way they are used depends on the key provider configured. It's preferred to configure it via a credential `active_record_encryption.primary_key`. | <ide> | `deterministic_key` | The key or list of keys used for deterministic encryption. It's preferred to configure it via a credential `active_record_encryption.deterministic_key`. | <ide> | `key_derivation_salt` | The salt used when deriving keys. It's preferred to configure it via a credential `active_record_encryption.key_derivation_salt`. | <ide> | `forced_encoding_for_deterministic_encryption` | The default encoding for attributes encrypted deterministically. You can disable forced encoding by setting this option to `nil`. It's `Encoding::UTF_8` by default. | <ide> <del>NOTE: It's recommended to use Rails built-in credentials support to store keys. If you prefer to set them manually via config properties, make sure you don't commit them with your code (e.g: use environment variables). <add>NOTE: It's recommended to use Rails built-in credentials support to store keys. If you prefer to set them manually via config properties, make sure you don't commit them with your code (e.g. use environment variables). <ide> <ide> ### Encryption Contexts <ide> <ide> NOTE: Encryption contexts are a flexible but advanced configuration mechanism. M <ide> The main components of encryption contexts are: <ide> <ide> * `encryptor`: exposes the internal API for encrypting and decrypting data. It interacts with a `key_provider` to build encrypted messages and deal with their serialization. The encryption/decryption itself is done by the `cipher` and the serialization by `message_serializer`. <del>* `cipher` the encryption algorithm itself (Aes 256 GCM) <del>* `key_provider` serves encryption and decryption keys. <add>* `cipher`: the encryption algorithm itself (AES 256 GCM) <add>* `key_provider`: serves encryption and decryption keys. <ide> * `message_serializer`: serializes and deserializes encrypted payloads (`Message`). <ide> <del>NOTE: If you decide to build your own `message_serializer`, It's important to use safe mechanisms that can't deserialize arbitrary objects. A common supported scenario is encrypting existing unencrypted data. An attacker can leverage this to enter a tampered payload before encryption takes place and perform RCE attacks. This means custom serializers should avoid `Marshal`, `YAML.load` (use `YAML.safe_load` instead) or `JSON.load` (use `JSON.parse` instead). <add>NOTE: If you decide to build your own `message_serializer`, it's important to use safe mechanisms that can't deserialize arbitrary objects. A common supported scenario is encrypting existing unencrypted data. An attacker can leverage this to enter a tampered payload before encryption takes place and perform RCE attacks. This means custom serializers should avoid `Marshal`, `YAML.load` (use `YAML.safe_load` instead), or `JSON.load` (use `JSON.parse` instead). <ide> <ide> #### Global Encryption Context <ide> <ide> ActiveRecord::Encryption.without_encryption do <ide> ... <ide> end <ide> ``` <del>This means that reading encrypted text will return the ciphertext and saved content will be stored unencrypted. <add>This means that reading encrypted text will return the ciphertext, and saved content will be stored unencrypted. <ide> <ide> ##### Protect Encrypted Data <ide> <del>You can run code without encryption but preventing overwriting encrypted content: <add>You can run code without encryption but prevent overwriting encrypted content: <ide> <ide> ```ruby <ide> ActiveRecord::Encryption.protecting_encrypted_data do <ide> ... <ide> end <ide> ``` <del>This can be handy if you want to protect encrypted data while still letting someone run arbitrary code against it (e.g: in a Rails console). <add>This can be handy if you want to protect encrypted data while still running arbitrary code against it (e.g. in a Rails console).
1
Javascript
Javascript
update panecontainer specs for async confirm
f960b43782c0020176fd1ad2686583647523d9e4
<ide><path>spec/pane-container-spec.js <ide> describe('PaneContainer', () => { <ide> let confirm, params <ide> <ide> beforeEach(() => { <del> confirm = spyOn(atom.applicationDelegate, 'confirm').andReturn(0) <add> confirm = spyOn(atom.applicationDelegate, 'confirm').andCallFake((options, callback) => callback(0)) <ide> params = { <ide> location: 'center', <ide> config: atom.config, <ide> describe('PaneContainer', () => { <ide> }) <ide> <ide> it('returns true if the user saves all modified files when prompted', async () => { <del> confirm.andReturn(0) <add> confirm.andCallFake((options, callback) => callback(0)) <ide> const saved = await container.confirmClose() <ide> expect(confirm).toHaveBeenCalled() <ide> expect(saved).toBeTruthy() <ide> }) <ide> <ide> it('returns false if the user cancels saving any modified file', async () => { <del> confirm.andReturn(1) <add> confirm.andCallFake((options, callback) => callback(1)) <ide> const saved = await container.confirmClose() <ide> expect(confirm).toHaveBeenCalled() <ide> expect(saved).toBeFalsy()
1
Text
Text
fix a typo in index.md
1107073a9802fd8893e2ee3fa369c5d65beabb48
<ide><path>docs/developers/index.md <ide> Version 3 has a largely different API than earlier versions. <ide> <ide> Most earlier version options have current equivalents or are the same. <ide> <del>Please note - documentation for previous versions are available online or in the GitHub repo. <add>Please note - documentation for previous versions is available online or in the GitHub repo. <ide> <ide> - [2.9.4 Documentation](https://www.chartjs.org/docs/2.9.4/) <ide> - [1.x Documentation](https://github.com/chartjs/Chart.js/tree/v1.1.1/docs)
1
Ruby
Ruby
encapsulate sleep margin when touching files
dda54de48ccf72caa447b251986c65d032d81bba
<ide><path>activesupport/test/file_update_checker_with_enumerable_test_cases.rb <ide> def wait <ide> # noop <ide> end <ide> <add> def touch(files) <add> sleep 1 <add> super <add> end <add> <ide> def setup <ide> @tmpdir = Dir.mktmpdir <ide> <ide> @files = %w(foo.rb bar.rb baz.rb).map {|f| "#{@tmpdir}/#{f}"} <del> touch(@files) <add> FileUtils.touch(@files) <ide> end <ide> <ide> def teardown <ide> def test_should_invoke_the_block_if_a_file_has_changed <ide> <ide> checker = new_checker(@files) { i += 1 } <ide> <del> sleep 1 <ide> touch(@files) <ide> wait <ide> <ide> def test_should_be_robust_to_handle_files_with_wrong_modified_time <ide> <ide> checker = new_checker(@files) { i += 1 } <ide> <del> sleep 1 <ide> touch(@files[1..-1]) <ide> wait <ide> <ide> def test_should_cache_updated_result_until_execute <ide> checker = new_checker(@files) { i += 1 } <ide> assert !checker.updated? <ide> <del> sleep 1 <ide> touch(@files) <ide> wait <ide> <ide> def test_should_invoke_the_block_if_a_watched_dir_changes <ide> <ide> checker = new_checker([], @tmpdir => :rb) { i += 1 } <ide> <del> sleep 1 <ide> touch(@files) <ide> wait <ide>
1
Ruby
Ruby
remove trailing whitespace
cacdbb94374ebdc1c1fa5445467fca3d12ca31cd
<ide><path>activesupport/test/core_ext/array_ext_test.rb <ide> class ArrayPrependAppendTest < Test::Unit::TestCase <ide> def test_append <ide> assert_equal [1, 2], [1].append(2) <ide> end <del> <add> <ide> def test_prepend <ide> assert_equal [2, 1], [1].prepend(2) <ide> end <del>end <ide>\ No newline at end of file <add>end
1
Python
Python
update textcat example
8f1d3fc3ee2b366a280c9ff61afb31102982bbae
<ide><path>examples/training/train_textcat.py <ide> @plac.annotations( <ide> model=("Model name. Defaults to blank 'en' model.", "option", "m", str), <ide> output_dir=("Optional output directory", "option", "o", Path), <del> n_examples=("Number of texts to train from", "option", "N", int), <add> n_texts=("Number of texts to train from", "option", "t", int), <ide> n_iter=("Number of training iterations", "option", "n", int)) <ide> def main(model=None, output_dir=None, n_iter=20, n_texts=2000): <ide> if model is not None: <ide> def main(model=None, output_dir=None, n_iter=20, n_texts=2000): <ide> # add the text classifier to the pipeline if it doesn't exist <ide> # nlp.create_pipe works for built-ins that are registered with spaCy <ide> if 'textcat' not in nlp.pipe_names: <del> # textcat = nlp.create_pipe('textcat') <del> textcat = TextCategorizer(nlp.vocab, labels=['POSITIVE']) <add> textcat = nlp.create_pipe('textcat') <ide> nlp.add_pipe(textcat, last=True) <ide> # otherwise, get it, so we can add labels to it <ide> else: <ide> textcat = nlp.get_pipe('textcat') <ide> <ide> # add label to text classifier <del> # textcat.add_label('POSITIVE') <add> textcat.add_label('POSITIVE') <ide> <ide> # load the IMBD dataset <ide> print("Loading IMDB data...") <del> print("Using %d training examples" % n_texts) <ide> (train_texts, train_cats), (dev_texts, dev_cats) = load_data(limit=n_texts) <add> print("Using %d training examples" % n_texts) <ide> train_docs = [nlp.tokenizer(text) for text in train_texts] <ide> train_gold = [GoldParse(doc, cats=cats) for doc, cats in <ide> zip(train_docs, train_cats)]
1
PHP
PHP
shorten path line
aeda6b13cdfcd662089c30d428839965c7443ab9
<ide><path>bootstrap/start.php <ide> | <ide> */ <ide> <del>$framework = $app['path.base'].'/vendor/laravel/framework/src'; <add>$framework = $app['path.base']. <add> '/vendor/laravel/framework/src'; <ide> <ide> require $framework.'/Illuminate/Foundation/start.php'; <ide>
1
Ruby
Ruby
use a `formulary`-like approach to load casks
d1995dad4bf76b447d9c97f1c2db99c6b3854b51
<ide><path>Library/Homebrew/cask/lib/hbc.rb <ide> require "hbc/cache" <ide> require "hbc/cask" <ide> require "hbc/cask_loader" <del>require "hbc/without_source" <ide> require "hbc/caskroom" <ide> require "hbc/checkable" <ide> require "hbc/cli" <ide> require "hbc/pkg" <ide> require "hbc/qualified_token" <ide> require "hbc/scopes" <del>require "hbc/source" <ide> require "hbc/staged" <ide> require "hbc/system_command" <ide> require "hbc/topological_hash" <ide> def self.init <ide> Caskroom.ensure_caskroom_exists <ide> end <ide> <del> def self.load(query) <del> odebug "Loading Cask definitions" <del> cask = Source.for_query(query).load <del> cask.dumpcask <del> cask <add> def self.load(ref) <add> CaskLoader.load(ref) <ide> end <ide> end <ide><path>Library/Homebrew/cask/lib/hbc/cask_loader.rb <ide> module Hbc <del> class CaskLoader <del> def self.load_from_file(path) <del> raise CaskError, "File '#{path}' does not exist" unless path.exist? <del> raise CaskError, "File '#{path}' is not readable" unless path.readable? <del> raise CaskError, "File '#{path}' is not a plain file" unless path.file? <add> module CaskLoader <add> class FromContentLoader <add> def initialize(content) <add> @content = content <add> end <add> <add> def load <add> instance_eval(@content.force_encoding("UTF-8"), __FILE__, __LINE__) <add> end <ide> <del> token = path.basename(".rb").to_s <del> content = IO.read(path).force_encoding("UTF-8") <add> private <ide> <del> new(token, content, path).load <add> def cask(header_token, &block) <add> Cask.new(header_token, &block) <add> end <ide> end <ide> <del> def self.load_from_string(token, content) <del> new(token, content).load <add> class FromPathLoader < FromContentLoader <add> def self.can_load?(ref) <add> path = Pathname.new(ref) <add> path.extname == ".rb" && path.expand_path.exist? <add> end <add> <add> attr_reader :token, :path <add> <add> def initialize(path) <add> path = Pathname.new(path).expand_path <add> <add> @token = path.basename(".rb").to_s <add> @path = path <add> end <add> <add> def load <add> raise CaskError, "'#{@path}' does not exist." unless @path.exist? <add> raise CaskError, "'#{@path}' is not readable." unless @path.readable? <add> raise CaskError, "'#{@path}' is not a file." unless @path.file? <add> <add> @content = IO.read(@path) <add> <add> super <add> end <add> <add> private <add> <add> def cask(header_token, &block) <add> if @token != header_token <add> raise CaskTokenDoesNotMatchError.new(@token, header_token) <add> end <add> <add> Cask.new(header_token, sourcefile_path: @path, &block) <add> end <ide> end <ide> <del> def load <del> instance_eval(@content, __FILE__, __LINE__) <del> rescue CaskError, StandardError, ScriptError => e <del> e.message.concat(" while loading '#{@token}'") <del> e.message.concat(" from '#{@path}'") unless @path.nil? <del> raise e, e.message <add> class FromURILoader < FromPathLoader <add> def self.can_load?(ref) <add> !(ref.to_s !~ ::URI.regexp) <add> end <add> <add> def initialize(url) <add> @url = url <add> uri = URI(url) <add> super Hbc.cache/File.basename(uri.path) <add> end <add> <add> def load <add> Hbc.cache.mkpath <add> FileUtils.rm_f @path <add> <add> begin <add> ohai "Downloading #{@url}." <add> curl @url, "-o", @path <add> rescue ErrorDuringExecution <add> raise CaskUnavailableError, @url <add> end <add> <add> super <add> end <ide> end <ide> <del> private <add> class FromTapLoader < FromPathLoader <add> def self.can_load?(ref) <add> !(ref.to_s !~ HOMEBREW_TAP_CASK_REGEX) <add> end <add> <add> def initialize(tapped_name) <add> user, repo, token = tapped_name.split("/", 3).map(&:downcase) <add> @tap = Tap.fetch(user, repo) <add> <add> super @tap.cask_dir/"#{token}.rb" <add> end <ide> <del> def initialize(token, content, path = nil) <del> @token = token <del> @content = content <del> @path = path unless path.nil? <add> def load <add> @tap.install unless @tap.installed? <add> <add> super <add> end <add> end <add> <add> class NullLoader < FromPathLoader <add> def self.can_load?(*) <add> true <add> end <add> <add> def initialize(ref) <add> @token = File.basename(ref, ".rb") <add> super CaskLoader.default_path(@token) <add> end <add> <add> def load <add> raise CaskUnavailableError, @token <add> end <add> end <add> <add> def self.load_from_file(path) <add> FromPathLoader.new(path).load <add> end <add> <add> def self.load_from_string(content) <add> FromContentLoader.new(content).load <ide> end <ide> <del> def cask(header_token, &block) <del> raise CaskTokenDoesNotMatchError.new(@token, header_token) unless @token == header_token <add> def self.path(ref) <add> self.for(ref).path <add> end <add> <add> def self.load(ref) <add> self.for(ref).load <add> end <add> <add> def self.for(ref) <add> [ <add> FromURILoader, <add> FromTapLoader, <add> FromPathLoader, <add> ].each do |loader_class| <add> return loader_class.new(ref) if loader_class.can_load?(ref) <add> end <add> <add> if FromPathLoader.can_load?(default_path(ref)) <add> return FromPathLoader.new(default_path(ref)) <add> end <ide> <del> if @path.nil? <del> Cask.new(@token, &block) <del> else <del> Cask.new(@token, sourcefile_path: @path, &block) <add> possible_tap_casks = tap_paths(ref) <add> if possible_tap_casks.count == 1 <add> possible_tap_cask = possible_tap_casks.first <add> return FromPathLoader.new(possible_tap_cask) <ide> end <add> <add> possible_installed_cask = Cask.new(ref) <add> if possible_installed_cask.installed? <add> return FromPathLoader.new(possible_installed_cask.installed_caskfile) <add> end <add> <add> NullLoader.new(ref) <add> end <add> <add> def self.default_path(token) <add> Hbc.default_tap.cask_dir/"#{token.to_s.downcase}.rb" <add> end <add> <add> def self.tap_paths(token) <add> Tap.map { |t| t.cask_dir/"#{token.to_s.downcase}.rb" } <add> .select(&:exist?) <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/cask/lib/hbc/locations.rb <ide> def path(query) <ide> end <ide> <ide> if token_with_tap <del> user, repo, token = token_with_tap.split("/") <add> user, repo, token = token_with_tap.split("/", 3) <ide> tap = Tap.fetch(user, repo) <ide> else <ide> token = query_without_extension <ide> tap = Hbc.default_tap <ide> end <ide> <del> return query_path if tap.cask_dir.nil? <del> tap.cask_dir.join("#{token}.rb") <add> CaskLoader.default_path(token) <ide> end <ide> <ide> def tcc_db <ide><path>Library/Homebrew/cask/lib/hbc/scopes.rb <ide> def all <ide> end <ide> <ide> def all_tapped_cask_dirs <del> Tap.map(&:cask_dir).compact <add> Tap.map(&:cask_dir).select(&:directory?) <ide> end <ide> <ide> def all_tokens <del> Tap.map do |t| <add> Tap.flat_map do |t| <ide> t.cask_files.map do |p| <ide> "#{t.name}/#{File.basename(p, ".rb")}" <ide> end <del> end.flatten <add> end <ide> end <ide> <ide> def installed <ide><path>Library/Homebrew/cask/lib/hbc/source.rb <del>require "hbc/source/gone" <del>require "hbc/source/path_slash_required" <del>require "hbc/source/path_slash_optional" <del>require "hbc/source/tapped_qualified" <del>require "hbc/source/untapped_qualified" <del>require "hbc/source/tapped" <del>require "hbc/source/uri" <del> <del>module Hbc <del> module Source <del> def self.sources <del> [ <del> URI, <del> PathSlashRequired, <del> TappedQualified, <del> UntappedQualified, <del> Tapped, <del> PathSlashOptional, <del> Gone, <del> ] <del> end <del> <del> def self.for_query(query) <del> odebug "Translating '#{query}' into a valid Cask source" <del> raise CaskUnavailableError, query if query.to_s =~ /^\s*$/ <del> source = sources.find do |s| <del> odebug "Testing source class #{s}" <del> s.me?(query) <del> end <del> raise CaskUnavailableError, query unless source <del> odebug "Success! Using source class #{source}" <del> resolved_cask_source = source.new(query) <del> odebug "Resolved Cask URI or file source to '#{resolved_cask_source}'" <del> resolved_cask_source <del> end <del> end <del>end <ide><path>Library/Homebrew/cask/lib/hbc/source/gone.rb <del>module Hbc <del> module Source <del> class Gone <del> def self.me?(query) <del> WithoutSource.new(query).installed? <del> end <del> <del> attr_reader :query <del> <del> def initialize(query) <del> @query = query <del> end <del> <del> def load <del> WithoutSource.new(query) <del> end <del> <del> def to_s <del> "" <del> end <del> end <del> end <del>end <ide><path>Library/Homebrew/cask/lib/hbc/source/path_base.rb <del>require "rubygems" <del>require "hbc/cask_loader" <del> <del>module Hbc <del> module Source <del> class PathBase <del> # derived classes must define method self.me? <del> <del> def self.path_for_query(query) <del> Pathname.new(query).sub(/(\.rb)?$/, ".rb") <del> end <del> <del> attr_reader :path <del> <del> def initialize(path) <del> @path = Pathname.new(path).expand_path <del> end <del> <del> def load <del> CaskLoader.load_from_file(@path) <del> end <del> <del> def to_s <del> # stringify to fully-resolved location <del> @path.to_s <del> end <del> end <del> end <del>end <ide><path>Library/Homebrew/cask/lib/hbc/source/path_slash_optional.rb <del>require "hbc/source/path_base" <del> <del>module Hbc <del> module Source <del> class PathSlashOptional < PathBase <del> def self.me?(query) <del> path = path_for_query(query) <del> path.exist? <del> end <del> end <del> end <del>end <ide><path>Library/Homebrew/cask/lib/hbc/source/path_slash_required.rb <del>require "hbc/source/path_base" <del> <del>module Hbc <del> module Source <del> class PathSlashRequired < PathBase <del> def self.me?(query) <del> path = path_for_query(query) <del> path.to_s.include?("/") && path.exist? <del> end <del> end <del> end <del>end <ide><path>Library/Homebrew/cask/lib/hbc/source/tapped.rb <del>module Hbc <del> module Source <del> class Tapped <del> def self.me?(query) <del> Hbc.path(query).exist? <del> end <del> <del> attr_reader :token <del> <del> def initialize(token) <del> @token = token <del> end <del> <del> def load <del> PathSlashOptional.new(Hbc.path(token)).load <del> end <del> <del> def to_s <del> # stringify to fully-resolved location <del> Hbc.path(token).expand_path.to_s <del> end <del> end <del> end <del>end <ide><path>Library/Homebrew/cask/lib/hbc/source/tapped_qualified.rb <del>require "hbc/source/tapped" <del> <del>module Hbc <del> module Source <del> class TappedQualified < Tapped <del> def self.me?(query) <del> return if (tap = tap_for_query(query)).nil? <del> <del> tap.installed? && Hbc.path(query).exist? <del> end <del> <del> def self.tap_for_query(query) <del> qualified_token = QualifiedToken.parse(query) <del> return if qualified_token.nil? <del> <del> user, repo = qualified_token[0..1] <del> Tap.fetch(user, repo) <del> end <del> end <del> end <del>end <ide><path>Library/Homebrew/cask/lib/hbc/source/untapped_qualified.rb <del>require "hbc/source/tapped_qualified" <del> <del>module Hbc <del> module Source <del> class UntappedQualified < TappedQualified <del> def self.me?(query) <del> return if (tap = tap_for_query(query)).nil? <del> <del> tap.install <del> tap.installed? && Hbc.path(query).exist? <del> end <del> end <del> end <del>end <ide><path>Library/Homebrew/cask/lib/hbc/source/uri.rb <del>module Hbc <del> module Source <del> class URI <del> def self.me?(query) <del> !(query.to_s =~ ::URI.regexp).nil? <del> end <del> <del> attr_reader :uri <del> <del> def initialize(uri) <del> @uri = uri <del> end <del> <del> def load <del> Hbc.cache.mkpath <del> path = Hbc.cache.join(File.basename(uri)) <del> ohai "Downloading #{uri}" <del> odebug "Download target -> #{path}" <del> begin <del> curl(uri, "-o", path.to_s) <del> rescue ErrorDuringExecution <del> raise CaskUnavailableError, uri <del> end <del> PathSlashOptional.new(path).load <del> end <del> <del> def to_s <del> uri.to_s <del> end <del> end <del> end <del>end <ide><path>Library/Homebrew/cask/lib/hbc/without_source.rb <del>module Hbc <del> class WithoutSource < Cask <del> # Override from `Hbc::DSL` because we don't have a cask source file to work <del> # with, so we don't know the cask's `version`. <del> def staged_path <del> (caskroom_path.children - [metadata_master_container_path]).first <del> end <del> <del> def to_s <del> "#{token} (!)" <del> end <del> <del> def installed? <del> caskroom_path.exist? <del> end <del> end <del>end <ide><path>Library/Homebrew/cmd/irb.rb <ide> def f(*args) <ide> end <ide> end <ide> <add>def cask <add> $LOAD_PATH.unshift("#{HOMEBREW_LIBRARY_PATH}/cask/lib") <add> require "hbc" <add>end <add> <ide> module Homebrew <ide> module_function <ide> <ide><path>Library/Homebrew/compat/hbc/cask_loader.rb <ide> def cask(header_token, &block) <ide> end <ide> <ide> module Hbc <del> class CaskLoader <del> prepend CaskLoaderCompatibilityLayer <add> module CaskLoader <add> class FromContentLoader; end <add> <add> class FromPathLoader < FromContentLoader <add> prepend CaskLoaderCompatibilityLayer <add> end <ide> end <ide> end <ide><path>Library/Homebrew/tap.rb <ide> def custom_remote? <ide> <ide> # path to the directory of all {Formula} files for this {Tap}. <ide> def formula_dir <del> @formula_dir ||= potential_formula_dirs.detect(&:directory?) <add> @formula_dir ||= potential_formula_dirs.detect(&:directory?) || path/"Formula" <ide> end <ide> <ide> def potential_formula_dirs <ide> def potential_formula_dirs <ide> <ide> # path to the directory of all {Cask} files for this {Tap}. <ide> def cask_dir <del> @cask_dir ||= [path/"Casks"].detect(&:directory?) <add> @cask_dir ||= path/"Casks" <ide> end <ide> <ide> # an array of all {Formula} files of this {Tap}. <ide> def formula_files <del> @formula_files ||= if formula_dir <add> @formula_files ||= if formula_dir.directory? <ide> formula_dir.children.select(&method(:formula_file?)) <ide> else <ide> [] <ide> def formula_files <ide> <ide> # an array of all {Cask} files of this {Tap}. <ide> def cask_files <del> @cask_files ||= if cask_dir <add> @cask_files ||= if cask_dir.directory? <ide> cask_dir.children.select(&method(:cask_file?)) <ide> else <ide> [] <ide><path>Library/Homebrew/test/cask/cli/list_spec.rb <ide> end <ide> end <ide> <del> describe "when Casks have been renamed" do <del> let(:caskroom_path) { Hbc.caskroom.join("ive-been-renamed") } <del> let(:staged_path) { caskroom_path.join("latest") } <del> <del> before do <del> staged_path.mkpath <del> end <del> <del> it "lists installed Casks without backing ruby files (due to renames or otherwise)" do <del> expect { <del> Hbc::CLI::List.run <del> }.to output(<<-EOS.undent).to_stdout <del> ive-been-renamed (!) <del> EOS <del> end <del> end <del> <ide> describe "given a set of installed Casks" do <ide> let(:caffeine) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-caffeine.rb") } <ide> let(:transmission) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb") }
18
Go
Go
handle errors during the creation of port mapper
371225520fc86fa58fadd182730b958a0f7ef9ab
<ide><path>network.go <ide> func newNetworkManager(bridgeIface string) (*NetworkManager, error) { <ide> } <ide> <ide> portMapper, err := newPortMapper() <add> if err != nil { <add> return nil, err <add> } <ide> <ide> manager := &NetworkManager{ <ide> bridgeIface: bridgeIface,
1
Text
Text
add travix to inthewild.md
f62e690efeb80863855282d33d3e047d01af2db0
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [TokenAnalyst](https://github.com/tokenanalyst) [[@simonohanlon101](https://github.com/simonohanlon101), [@ankitchiplunkar](https://github.com/ankitchiplunkar), [@sidshekhar](https://github.com/sidshekhar), [@sp6pe](https://github.com/sp6pe)] <ide> 1. [Tokopedia](https://www.tokopedia.com/) [[@topedmaria](https://github.com/topedmaria)] <ide> 1. [Trade Republic](https://traderepublic.com/) [[@feluelle](https://github.com/feluelle)] <add>1. [Travix](https://www.travix.com/) <ide> 1. [Trocafone](https://www.trocafone.com/) [[@idontdomath](https://github.com/idontdomath) & [@gseva](https://github.com/gseva) & [@ordonezf](https://github.com/ordonezf) & [@PalmaLeandro](https://github.com/PalmaLeandro)] <ide> 1. [TruFactor](https://trufactor.io/) [[@gholmes](https://github.com/gholmes) & [@angadsingh](https://github.com/angadsingh/)] <ide> 1. [Twine Labs](https://www.twinelabs.com/) [[@ivorpeles](https://github.com/ivorpeles)]
1
Python
Python
fix manifest generation
4e99df67658a4e43f68e2fa5773267583ac586ea
<ide><path>numpy/distutils/mingw32ccompiler.py <ide> def build_import_library(): <ide> # XXX: ideally, we should use exactly the same version as used by python. I <ide> # submitted a patch to get this version, but it was only included for python <ide> # 2.6.1 and above. So for versions below, we use a "best guess". <del>_MSVCRVER_TO_FULLVER = {'90': None} <del> <del>def msvcrt_version(num): <del> k = _MSVCRVER_TO_FULLVER[num] <del> if not k: <del> try: <del> import msvcrt <del> if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"): <del> _MSVCRVER_TO_FULLVER['90'] = msvcrt.CRT_ASSEMBLY_VERSION <del> else: <del> _MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8" <del> except ImportError: <del> # If we are here, means python was not built with MSVC. Not sure what to do <del> # in that case: manifest building will fail, but it should not be used in <del> # that case anyway <del> log.warn('Cannot import msvcrt: using manifest will not be possible') <add>_MSVCRVER_TO_FULLVER = {} <add>if sys.platform == 'win32': <add> try: <add> import msvcrt <add> if hasattr(msvcrt, "CRT_ASSEMBLY_VERSION"): <add> _MSVCRVER_TO_FULLVER['90'] = msvcrt.CRT_ASSEMBLY_VERSION <add> else: <add> _MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8" <add> except ImportError: <add> # If we are here, means python was not built with MSVC. Not sure what to do <add> # in that case: manifest building will fail, but it should not be used in <add> # that case anyway <add> log.warn('Cannot import msvcrt: using manifest will not be possible') <ide> <ide> def msvc_manifest_xml(maj, min): <ide> """Given a major and minor version of the MSVCR, returns the <ide> corresponding XML file.""" <ide> try: <del> fullver = msvcrt_version(str(maj * 10 + min)) <add> fullver = _MSVCRVER_TO_FULLVER[str(maj * 10 + min)] <ide> except KeyError: <ide> raise ValueError("Version %d,%d of MSVCRT not supported yet" \ <ide> % (maj, min))
1
Javascript
Javascript
fix nesting issues and add tests
089c0f8b0e64f00e2629de07f35af03f01c34686
<ide><path>src/directive/form.js <ide> 'use strict'; <ide> <ide> <add>var nullFormCtrl = { <add> $addControl: noop, <add> $removeControl: noop, <add> $setValidity: noop <add>} <add> <ide> /** <ide> * @ngdoc object <ide> * @name angular.module.ng.$compileProvider.directive.form.FormController <ide> * of `FormController`. <ide> * <ide> */ <del>FormController.$inject = ['name', '$element']; <del>function FormController(name, element) { <add>FormController.$inject = ['name', '$element', '$attrs']; <add>function FormController(name, element, attrs) { <ide> var form = this, <del> parentForm = element.parent().inheritedData('$formController'), <add> parentForm = element.parent().inheritedData('$formController') || nullFormCtrl, <ide> errors = form.$error = {}; <ide> <add> // init state <add> form.$name = attrs.name; <add> form.$dirty = false; <add> form.$pristine = true; <add> form.$valid = true; <add> form.$invalid = false; <add> <ide> // publish the form into scope <ide> name(this); <ide> <del> if (parentForm) { <del> parentForm.$addControl(form); <del> } <add> parentForm.$addControl(form); <ide> <ide> form.$addControl = function(control) { <ide> if (control.$name && !form.hasOwnProperty(control.$name)) { <ide> function FormController(name, element) { <ide> form.$pristine = false; <ide> } <ide> <del> // init state <del> form.$dirty = false; <del> form.$pristine = true; <del> form.$valid = true; <del> form.$invalid = false; <del> <ide> function cleanupControlErrors(queue, validationToken, control) { <ide> if (queue) { <ide> control = control || this; // so that we can be used in forEach; <del> for (var i = 0, length = queue.length; i < length; i++) { <del> if (queue[i] === control) { <del> queue.splice(i, 1); <del> if (!queue.length) { <del> delete errors[validationToken]; <del> <del> if (parentForm) { <del> parentForm.$setValidity(validationToken, true, form); <del> } <del> } <del> } <add> arrayRemove(queue, control); <add> if (!queue.length) { <add> delete errors[validationToken]; <add> parentForm.$setValidity(validationToken, true, form); <ide> } <ide> } <ide> } <ide> <ide> function addControlError(validationToken, control) { <ide> var queue = errors[validationToken]; <ide> if (queue) { <del> if (indexOf(queue, control)) return; <add> if (includes(queue, control)) return; <ide> } else { <ide> errors[validationToken] = queue = []; <del> <del> if (parentForm) { <del> parentForm.$setValidity(validationToken, false, form); <del> } <add> parentForm.$setValidity(validationToken, false, form); <ide> } <ide> queue.push(control); <ide> } <ide> var formDirective = [function() { <ide> formElement[value ? 'addClass' : 'removeClass']('ng-' + name); <ide> }); <ide> }); <add> <add> var parentFormCtrl = formElement.parent().inheritedData('$formController'); <add> if (parentFormCtrl) { <add> formElement.bind('$destroy', function() { <add> parentFormCtrl.$removeControl(controller); <add> if (attr.name) delete scope[attr.name]; <add> extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards <add> }); <add> } <ide> } <ide> }; <ide> } <ide><path>test/directive/formSpec.js <ide> describe('form', function() { <ide> }); <ide> <ide> <del> it('should chain nested forms', function() { <del> doc = jqLite( <del> '<ng:form name="parent">' + <del> '<ng:form name="child">' + <del> '<input ng:model="modelA" name="inputA">' + <del> '</ng:form>' + <del> '</ng:form>'); <del> $compile(doc)(scope); <del> <del> var parent = scope.parent; <del> var child = scope.child; <del> var input = child.inputA; <del> <del> input.$setValidity('MyError', false); <del> expect(parent.$error.MyError).toEqual([child]); <del> expect(child.$error.MyError).toEqual([input]); <del> <del> input.$setValidity('MyError', true); <del> expect(parent.$error.MyError).toBeUndefined(); <del> expect(child.$error.MyError).toBeUndefined(); <del> }); <del> <del> <ide> it('should support two forms on a single scope', function() { <ide> doc = $compile( <ide> '<div>' + <ide> describe('form', function() { <ide> }); <ide> <ide> <del> it('should chain nested forms in repeater', function() { <del> doc = jqLite( <del> '<ng:form name=parent>' + <del> '<ng:form ng:repeat="f in forms" name=child>' + <del> '<input type=text ng:model=text name=text>' + <del> '</ng:form>' + <del> '</ng:form>'); <del> $compile(doc)(scope); <del> <del> scope.$apply(function() { <del> scope.forms = [1]; <del> }); <del> <del> var parent = scope.parent; <del> var child = doc.find('input').scope().child; <del> var input = child.text; <del> <del> expect(parent).toBeDefined(); <del> expect(child).toBeDefined(); <del> expect(input).toBeDefined(); <del> <del> input.$setValidity('myRule', false); <del> expect(input.$error.myRule).toEqual(true); <del> expect(child.$error.myRule).toEqual([input]); <del> expect(parent.$error.myRule).toEqual([child]); <del> <del> input.$setValidity('myRule', true); <del> expect(parent.$error.myRule).toBeUndefined(); <del> expect(child.$error.myRule).toBeUndefined(); <del> }); <del> <del> <ide> it('should publish widgets', function() { <ide> doc = jqLite('<form name="form"><input type="text" name="w1" ng-model="some" /></form>'); <ide> $compile(doc)(scope); <ide> describe('form', function() { <ide> }); <ide> <ide> <add> describe('nested forms', function() { <add> <add> it('should chain nested forms', function() { <add> doc = jqLite( <add> '<ng:form name="parent">' + <add> '<ng:form name="child">' + <add> '<input ng:model="modelA" name="inputA">' + <add> '<input ng:model="modelB" name="inputB">' + <add> '</ng:form>' + <add> '</ng:form>'); <add> $compile(doc)(scope); <add> <add> var parent = scope.parent, <add> child = scope.child, <add> inputA = child.inputA, <add> inputB = child.inputB; <add> <add> inputA.$setValidity('MyError', false); <add> inputB.$setValidity('MyError', false); <add> expect(parent.$error.MyError).toEqual([child]); <add> expect(child.$error.MyError).toEqual([inputA, inputB]); <add> <add> inputA.$setValidity('MyError', true); <add> expect(parent.$error.MyError).toEqual([child]); <add> expect(child.$error.MyError).toEqual([inputB]); <add> <add> inputB.$setValidity('MyError', true); <add> expect(parent.$error.MyError).toBeUndefined(); <add> expect(child.$error.MyError).toBeUndefined(); <add> }); <add> <add> <add> it('should deregister a child form when its DOM is removed', function() { <add> doc = jqLite( <add> '<ng:form name="parent">' + <add> '<ng:form name="child">' + <add> '<input ng:model="modelA" name="inputA" required>' + <add> '</ng:form>' + <add> '</ng:form>'); <add> $compile(doc)(scope); <add> scope.$apply(); <add> <add> var parent = scope.parent, <add> child = scope.child; <add> <add> expect(parent.$error.required).toEqual([child]); <add> doc.children().remove(); //remove child <add> <add> expect(parent.child).toBeUndefined(); <add> expect(scope.child).toBeUndefined(); <add> expect(parent.$error.required).toBeUndefined(); <add> }); <add> <add> <add> it('should chain nested forms in repeater', function() { <add> doc = jqLite( <add> '<ng:form name=parent>' + <add> '<ng:form ng:repeat="f in forms" name=child>' + <add> '<input type=text ng:model=text name=text>' + <add> '</ng:form>' + <add> '</ng:form>'); <add> $compile(doc)(scope); <add> <add> scope.$apply(function() { <add> scope.forms = [1]; <add> }); <add> <add> var parent = scope.parent; <add> var child = doc.find('input').scope().child; <add> var input = child.text; <add> <add> expect(parent).toBeDefined(); <add> expect(child).toBeDefined(); <add> expect(input).toBeDefined(); <add> <add> input.$setValidity('myRule', false); <add> expect(input.$error.myRule).toEqual(true); <add> expect(child.$error.myRule).toEqual([input]); <add> expect(parent.$error.myRule).toEqual([child]); <add> <add> input.$setValidity('myRule', true); <add> expect(parent.$error.myRule).toBeUndefined(); <add> expect(child.$error.myRule).toBeUndefined(); <add> }); <add> }) <add> <add> <ide> describe('validation', function() { <ide> <ide> beforeEach(function() {
2
Text
Text
add links to node and npm in requirements
b5775737307b7b0806aa25a7c174e690454dcce4
<ide><path>docs/GettingStarted.md <ide> next: tutorial <ide> 1. OS X - This repo only contains the iOS implementation right now, and Xcode only runs on Mac. <ide> 2. New to Xcode? [Download it](https://developer.apple.com/xcode/downloads/) from the Mac App Store. <ide> 3. [Homebrew](http://brew.sh/) is the recommended way to install node, watchman, and flow. <del>4. `brew install node`. New to node or npm? <add>4. `brew install node`. New to [node](https://nodejs.org/) or [npm](https://docs.npmjs.com/)? <ide> 5. `brew install watchman`. We recommend installing [watchman](https://facebook.github.io/watchman/docs/install.html), otherwise you might hit a node file watching bug. <ide> 6. `brew install flow`. If you want to use [flow](http://www.flowtype.org). <ide>
1
Text
Text
add instructions 08
0deac73642a1ed09a84d76da296250d19d621932
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/demographic-data-analyzer.md <ide> dashedName: demographic-data-analyzer <ide> <ide> # --description-- <ide> <del>In this challenge you must analyze demographic data using Pandas. You are given a dataset of demographic data that was extracted from the 1994 Census database. <add>You will be [working on this project with our Replit starter code](https://replit.com/github/freeCodeCamp/boilerplate-demographic-data-analyzer). <ide> <del>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-demographic-data-analyzer). <add>We are still developing the interactive instructional part of the Python curriculum. For now, here are some videos on the freeCodeCamp.org YouTube channel that will teach you everything you need to know to complete this project: <ide> <del>After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below. <add>- [Python for Everybody Video Course](https://www.freecodecamp.org/news/python-for-everybody/) (14 hours) <add>- [Learn Python Video Course](https://www.freecodecamp.org/news/learn-python-video-course/) (10 hours) <ide> <del>We are still developing the interactive instructional part of the data analysis with Python curriculum. For now, you will have to use other resources to learn how to pass this challenge. <add># --instructions-- <add> <add>In this challenge you must analyze demographic data using Pandas. You are given a dataset of demographic data that was extracted from the 1994 Census database. Here is a sample of what the data looks like: <add> <add>```markdown <add>| | age | workclass | fnlwgt | education | education-num | marital-status | occupation | relationship | race | sex | capital-gain | capital-loss | hours-per-week | native-country | salary | <add>|---:|------:|:-----------------|---------:|:------------|----------------:|:-------------------|:------------------|:---------------|:-------|:-------|---------------:|---------------:|-----------------:|:-----------------|:---------| <add>| 0 | 39 | State-gov | 77516 | Bachelors | 13 | Never-married | Adm-clerical | Not-in-family | White | Male | 2174 | 0 | 40 | United-States | <=50K | <add>| 1 | 50 | Self-emp-not-inc | 83311 | Bachelors | 13 | Married-civ-spouse | Exec-managerial | Husband | White | Male | 0 | 0 | 13 | United-States | <=50K | <add>| 2 | 38 | Private | 215646 | HS-grad | 9 | Divorced | Handlers-cleaners | Not-in-family | White | Male | 0 | 0 | 40 | United-States | <=50K | <add>| 3 | 53 | Private | 234721 | 11th | 7 | Married-civ-spouse | Handlers-cleaners | Husband | Black | Male | 0 | 0 | 40 | United-States | <=50K | <add>| 4 | 28 | Private | 338409 | Bachelors | 13 | Married-civ-spouse | Prof-specialty | Wife | Black | Female | 0 | 0 | 40 | Cuba | <=50K | <add>``` <add> <add>You must use Pandas to answer the following questions: <add> <add>- How many people of each race are represented in this dataset? This should be a Pandas series with race names as the index labels. (`race` column) <add>- What is the average age of men? <add>- What is the percentage of people who have a Bachelor's degree? <add>- What percentage of people with advanced education (`Bachelors`, `Masters`, or `Doctorate`) make more than 50K? <add>- What percentage of people without advanced education make more than 50K? <add>- What is the minimum number of hours a person works per week? <add>- What percentage of the people who work the minimum number of hours per week have a salary of more than 50K? <add>- What country has the highest percentage of people that earn >50K and what is that percentage? <add>- Identify the most popular occupation for those who earn >50K in India. <add> <add>Use the starter code in the file `demographic_data_analyzer`. Update the code so all variables set to "None" are set to the appropriate calculation or code. Round all decimals to the nearest tenth. <add> <add>Unit tests are written for you under `test_module.py`. <add> <add>## Development <add> <add>For development, you can use `main.py` to test your functions. Click the "run" button and `main.py` will run. <add> <add>## Testing <add> <add>We imported the tests from `test_module.py` to `main.py` for your convenience. The tests will run automatically whenever you hit the "run" button. <add> <add>## Submitting <add> <add>Copy your project's URL and submit it to freeCodeCamp. <add> <add>## Dataset Source <add> <add>Dua, D. and Graff, C. (2019). [UCI Machine Learning Repository](http://archive.ics.uci.edu/ml). Irvine, CA: University of California, School of Information and Computer Science. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/mean-variance-standard-deviation-calculator.md <ide> dashedName: mean-variance-standard-deviation-calculator <ide> <ide> # --description-- <ide> <del>Create a function that uses Numpy to output the mean, variance, and standard deviation of the rows, columns, and elements in a 3 x 3 matrix. <add>You will be [working on this project with our Replit starter code](https://replit.com/github/freeCodeCamp/boilerplate-mean-variance-standard-deviation-calculator). <ide> <del>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-mean-variance-standard-deviation-calculator). <add>We are still developing the interactive instructional part of the Python curriculum. For now, here are some videos on the freeCodeCamp.org YouTube channel that will teach you everything you need to know to complete this project: <ide> <del>After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below. <add>- [Python for Everybody Video Course](https://www.freecodecamp.org/news/python-for-everybody/) (14 hours) <add>- [Learn Python Video Course](https://www.freecodecamp.org/news/learn-python-video-course/) (10 hours) <ide> <del>We are still developing the interactive instructional part of the data analysis with Python curriculum. For now, you will have to use other resources to learn how to pass this challenge. <add># --instructions-- <add> <add>Create a function named `calculate()` in `mean_var_std.py` that uses Numpy to output the mean, variance, standard deviation, max, min, and sum of the rows, columns, and elements in a 3 x 3 matrix. <add> <add>The input of the function should be a list containing 9 digits. The function should convert the list into a 3 x 3 Numpy array, and then return a dictionary containing the mean, variance, standard deviation, max, min, and sum along both axes and for the flattened matrix. <add> <add>The returned dictionary should follow this format: <add> <add>```py <add>{ <add> 'mean': [axis1, axis2, flattened], <add> 'variance': [axis1, axis2, flattened], <add> 'standard deviation': [axis1, axis2, flattened], <add> 'max': [axis1, axis2, flattened], <add> 'min': [axis1, axis2, flattened], <add> 'sum': [axis1, axis2, flattened] <add>} <add>``` <add> <add>If a list containing less than 9 elements is passed into the function, it should raise a `ValueError` exception with the message: "List must contain nine numbers." The values in the returned dictionary should be lists and not Numpy arrays. <add> <add>For example, `calculate([0,1,2,3,4,5,6,7,8])` should return: <add> <add>```py <add>{ <add> 'mean': [[3.0, 4.0, 5.0], [1.0, 4.0, 7.0], 4.0], <add> 'variance': [[6.0, 6.0, 6.0], [0.6666666666666666, 0.6666666666666666, 0.6666666666666666], 6.666666666666667], <add> 'standard deviation': [[2.449489742783178, 2.449489742783178, 2.449489742783178], [0.816496580927726, 0.816496580927726, 0.816496580927726], 2.581988897471611], <add> 'max': [[6, 7, 8], [2, 5, 8], 8], <add> 'min': [[0, 1, 2], [0, 3, 6], 0], <add> 'sum': [[9, 12, 15], [3, 12, 21], 36] <add>} <add>``` <add> <add>The unit tests for this project are in `test_module.py`. <add> <add>## Development <add> <add>For development, you can use `main.py` to test your `calculate()` function. Click the "run" button and `main.py` will run. <add> <add>## Testing <add> <add>We imported the tests from `test_module.py` to `main.py` for your convenience. The tests will run automatically whenever you hit the "run" button. <add> <add>## Submitting <add> <add>Copy your project's URL and submit it to freeCodeCamp. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/medical-data-visualizer.md <ide> dashedName: medical-data-visualizer <ide> <ide> # --description-- <ide> <del>In this project, you will visualize and make calculations from medical examination data using matplotlib, seaborn, and pandas. <add>You will be [working on this project with our Replit starter code](https://replit.com/github/freeCodeCamp/boilerplate-medical-data-visualizer). <ide> <del>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-medical-data-visualizer). <add>We are still developing the interactive instructional part of the Python curriculum. For now, here are some videos on the freeCodeCamp.org YouTube channel that will teach you everything you need to know to complete this project: <ide> <del>After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below. <add>- [Python for Everybody Video Course](https://www.freecodecamp.org/news/python-for-everybody/) (14 hours) <add>- [Learn Python Video Course](https://www.freecodecamp.org/news/learn-python-video-course/) (10 hours) <ide> <del>We are still developing the interactive instructional part of the data analysis with Python curriculum. For now, you will have to use other resources to learn how to pass this challenge. <add># --instructions-- <add> <add>In this project, you will visualize and make calculations from medical examination data using matplotlib, seaborn, and pandas. The dataset values were collected during medical examinations. <add> <add>## Data description <add> <add>The rows in the dataset represent patients and the columns represent information like body measurements, results from various blood tests, and lifestyle choices. You will use the dataset to explore the relationship between cardiac disease, body measurements, blood markers, and lifestyle choices. <add> <add>File name: medical_examination.csv <add> <add>| Feature | Variable Type | Variable | Value Type | <add>|:-------:|:------------:|:-------------:|:----------:| <add>| Age | Objective Feature | age | int (days) | <add>| Height | Objective Feature | height | int (cm) | <add>| Weight | Objective Feature | weight | float (kg) | <add>| Gender | Objective Feature | gender | categorical code | <add>| Systolic blood pressure | Examination Feature | ap_hi | int | <add>| Diastolic blood pressure | Examination Feature | ap_lo | int | <add>| Cholesterol | Examination Feature | cholesterol | 1: normal, 2: above normal, 3: well above normal | <add>| Glucose | Examination Feature | gluc | 1: normal, 2: above normal, 3: well above normal | <add>| Smoking | Subjective Feature | smoke | binary | <add>| Alcohol intake | Subjective Feature | alco | binary | <add>| Physical activity | Subjective Feature | active | binary | <add>| Presence or absence of cardiovascular disease | Target Variable | cardio | binary | <add> <add>## Tasks <add> <add>Create a chart similar to `examples/Figure_1.png`, where we show the counts of good and bad outcomes for the `cholesterol`, `gluc`, `alco`, `active`, and `smoke` variables for patients with cardio=1 and cardio=0 in different panels. <add> <add>Use the data to complete the following tasks in `medical_data_visualizer.py`: <add> <add>- Add an `overweight` column to the data. To determine if a person is overweight, first calculate their BMI by dividing their weight in kilograms by the square of their height in meters. If that value is > 25 then the person is overweight. Use the value 0 for NOT overweight and the value 1 for overweight. <add>- Normalize the data by making 0 always good and 1 always bad. If the value of `cholesterol` or `gluc` is 1, make the value 0. If the value is more than 1, make the value 1. <add>- Convert the data into long format and create a chart that shows the value counts of the categorical features using seaborn's `catplot()`. The dataset should be split by 'Cardio' so there is one chart for each `cardio` value. The chart should look like `examples/Figure_1.png`. <add>- Clean the data. Filter out the following patient segments that represent incorrect data: <add> - diastolic pressure is higher than systolic (Keep the correct data with `(df['ap_lo'] <= df['ap_hi'])`) <add> - height is less than the 2.5th percentile (Keep the correct data with `(df['height'] >= df['height'].quantile(0.025))`) <add> - height is more than the 97.5th percentile <add> - weight is less than the 2.5th percentile <add> - weight is more than the 97.5th percentile <add>- Create a correlation matrix using the dataset. Plot the correlation matrix using seaborn's `heatmap()`. Mask the upper triangle. The chart should look like `examples/Figure_2.png`. <add> <add>Any time a variable is set to `None`, make sure to set it to the correct code. <add> <add>Unit tests are written for you under `test_module.py`. <add> <add>## Development <add> <add>For development, you can use `main.py` to test your functions. Click the "run" button and `main.py` will run. <add> <add>## Testing <add> <add>We imported the tests from `test_module.py` to `main.py` for your convenience. The tests will run automatically whenever you hit the "run" button. <add> <add>## Submitting <add> <add>Copy your project's URL and submit it to freeCodeCamp. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/page-view-time-series-visualizer.md <ide> dashedName: page-view-time-series-visualizer <ide> <ide> # --description-- <ide> <del>For this project you will visualize time series data using a line chart, bar chart, and box plots. You will use Pandas, matplotlib, and seaborn to visualize a dataset containing the number of page views each day on the freeCodeCamp.org forum from 2016-05-09 to 2019-12-03. The data visualizations will help you understand the patterns in visits and identify yearly and monthly growth. <add>You will be [working on this project with our Replit starter code](https://replit.com/github/freeCodeCamp/boilerplate-page-view-time-series-visualizer). <ide> <del>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-page-view-time-series-visualizer). <add>We are still developing the interactive instructional part of the Python curriculum. For now, here are some videos on the freeCodeCamp.org YouTube channel that will teach you everything you need to know to complete this project: <ide> <del>After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below. <add>- [Python for Everybody Video Course](https://www.freecodecamp.org/news/python-for-everybody/) (14 hours) <add>- [Learn Python Video Course](https://www.freecodecamp.org/news/learn-python-video-course/) (10 hours) <ide> <del>We are still developing the interactive instructional part of the data analysis with Python curriculum. For now, you will have to use other resources to learn how to pass this challenge. <add># --instructions-- <add> <add>For this project you will visualize time series data using a line chart, bar chart, and box plots. You will use Pandas, Matplotlib, and Seaborn to visualize a dataset containing the number of page views each day on the freeCodeCamp.org forum from 2016-05-09 to 2019-12-03. The data visualizations will help you understand the patterns in visits and identify yearly and monthly growth. <add> <add>Use the data to complete the following tasks: <add> <add>- Use Pandas to import the data from "fcc-forum-pageviews.csv". Set the index to the "date" column. <add>- Clean the data by filtering out days when the page views were in the top 2.5% of the dataset or bottom 2.5% of the dataset. <add>- Create a `draw_line_plot` function that uses Matplotlib to draw a line chart similar to "examples/Figure_1.png". The title should be "Daily freeCodeCamp Forum Page Views 5/2016-12/2019". The label on the x axis should be "Date" and the label on the y axis should be "Page Views". <add>- Create a `draw_bar_plot` function that draws a bar chart similar to "examples/Figure_2.png". It should show average daily page views for each month grouped by year. The legend should show month labels and have a title of "Months". On the chart, the label on the x axis should be "Years" and the label on the y axis should be "Average Page Views". <add>- Create a `draw_box_plot` function that uses Searborn to draw two adjacent box plots similar to "examples/Figure_3.png". These box plots should show how the values are distributed within a given year or month and how it compares over time. The title of the first chart should be "Year-wise Box Plot (Trend)" and the title of the second chart should be "Month-wise Box Plot (Seasonality)". Make sure the month labels on bottom start at "Jan" and the x and x axis are labeled correctly. The boilerplate includes commands to prepare the data. <add> <add>For each chart, make sure to use a copy of the data frame. Unit tests are written for you under `test_module.py`. <add> <add>The boilerplate also includes commands to save and return the image. <add> <add>## Development <add> <add>For development, you can use `main.py` to test your functions. Click the "run" button and `main.py` will run. <add> <add>## Testing <add> <add>We imported the tests from `test_module.py` to `main.py` for your convenience. The tests will run automatically whenever you hit the "run" button. <add> <add>## Submitting <add> <add>Copy your project's URL and submit it to freeCodeCamp. <ide> <ide> # --hints-- <ide> <ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-projects/sea-level-predictor.md <ide> dashedName: sea-level-predictor <ide> <ide> # --description-- <ide> <del>In this project, you will analyze a dataset of the global average sea level change since 1880. You will use the data to predict the sea level change through year 2050. <add>You will be [working on this project with our Replit starter code](https://replit.com/github/freeCodeCamp/boilerplate-sea-level-predictor). <ide> <del>You can access [the full project description and starter code on Replit](https://replit.com/github/freeCodeCamp/boilerplate-sea-level-predictor). <add>We are still developing the interactive instructional part of the Python curriculum. For now, here are some videos on the freeCodeCamp.org YouTube channel that will teach you everything you need to know to complete this project: <ide> <del>After going to that link, fork the project. Once you complete the project based on the instructions in 'README.md', submit your project link below. <add>- [Python for Everybody Video Course](https://www.freecodecamp.org/news/python-for-everybody/) (14 hours) <add>- [Learn Python Video Course](https://www.freecodecamp.org/news/learn-python-video-course/) (10 hours) <add> <add># --instructions-- <add> <add>You will analyze a dataset of the global average sea level change since 1880. You will use the data to predict the sea level change through year 2050. <add> <add>Use the data to complete the following tasks: <add> <add>- Use Pandas to import the data from `epa-sea-level.csv`. <add>- Use matplotlib to create a scatter plot using the "Year" column as the x-axis and the "CSIRO Adjusted Sea Level" column as the y-axix. <add>- Use the `linregress` function from `scipy.stats` to get the slope and y-intercept of the line of best fit. Plot the line of best fit over the top of the scatter plot. Make the line go through the year 2050 to predict the sea level rise in 2050. <add>- Plot a new line of best fit just using the data from year 2000 through the most recent year in the dataset. Make the line also go through the year 2050 to predict the sea level rise in 2050 if the rate of rise continues as it has since the year 2000. <add>- The x label should be "Year", the y label should be "Sea Level (inches)", and the title should be "Rise in Sea Level". <add> <add>Unit tests are written for you under `test_module.py`. <add> <add>The boilerplate also includes commands to save and return the image. <add> <add>## Development <add> <add>For development, you can use `main.py` to test your functions. Click the "run" button and `main.py` will run. <add> <add>## Testing <add> <add>We imported the tests from `test_module.py` to `main.py` for your convenience. The tests will run automatically whenever you hit the "run" button. <add> <add>## Submitting <add> <add>Copy your project's URL and submit it to freeCodeCamp. <add> <add>## Data Source <add>[Global Average Absolute Sea Level Change](https://datahub.io/core/sea-level-rise), 1880-2014 from the US Environmental Protection Agency using data from CSIRO, 2015; NOAA, 2015. <ide> <del>We are still developing the interactive instructional part of the data analysis with Python curriculum. For now, you will have to use other resources to learn how to pass this challenge. <ide> <ide> # --hints-- <ide>
5
Python
Python
fix typo in iris_data.py
80eb727ab08d91be34e49449a6aa8c267ddba8c2
<ide><path>samples/core/get_started/iris_data.py <ide> def eval_input_fn(features, labels, batch_size): <ide> <ide> <ide> # The remainder of this file contains a simple example of a csv parser, <del># implemented using a the `Dataset` class. <add># implemented using the `Dataset` class. <ide> <ide> # `tf.parse_csv` sets the types of the outputs to match the examples given in <ide> # the `record_defaults` argument.
1
Javascript
Javascript
add reference to issue
e7f316c7a7cc0262e1e58ce485d60dc3112cf769
<ide><path>src/renderers/webgl/WebGLTextures.js <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> <ide> _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST ); <ide> <del> _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); <add> _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905 <ide> <ide> } else { <ide>
1
Javascript
Javascript
add more non-react events to the priority list
ad8211d96a7990a91d4f6c9915b8b30566c3c0af
<ide><path>packages/react-dom/src/__tests__/ReactDOMNativeEventHeuristic-test.js <ide> let React; <ide> <ide> let ReactDOM; <ide> let Scheduler; <add>let act; <ide> <ide> describe('ReactDOMNativeEventHeuristic-test', () => { <ide> let container; <ide> describe('ReactDOMNativeEventHeuristic-test', () => { <ide> React = require('react'); <ide> ReactDOM = require('react-dom'); <ide> Scheduler = require('scheduler'); <add> act = require('react-dom/test-utils').unstable_concurrentAct; <ide> <ide> document.body.appendChild(container); <ide> }); <ide> describe('ReactDOMNativeEventHeuristic-test', () => { <ide> // Therefore the form should have been submitted. <ide> expect(formSubmitted).toBe(true); <ide> }); <add> <add> // @gate experimental <add> // @gate enableDiscreteEventMicroTasks && enableNativeEventPriorityInference <add> it('mouse over should be user-blocking but not discrete', async () => { <add> const root = ReactDOM.unstable_createRoot(container); <add> <add> const target = React.createRef(null); <add> function Foo() { <add> const [isHover, setHover] = React.useState(false); <add> React.useLayoutEffect(() => { <add> target.current.onmouseover = () => setHover(true); <add> }); <add> return <div ref={target}>{isHover ? 'hovered' : 'not hovered'}</div>; <add> } <add> <add> await act(async () => { <add> root.render(<Foo />); <add> }); <add> expect(container.textContent).toEqual('not hovered'); <add> <add> await act(async () => { <add> const mouseOverEvent = document.createEvent('MouseEvents'); <add> mouseOverEvent.initEvent('mouseover', true, true); <add> dispatchAndSetCurrentEvent(target.current, mouseOverEvent); <add> <add> // 3s should be enough to expire the updates <add> Scheduler.unstable_advanceTime(3000); <add> expect(Scheduler).toFlushExpired([]); <add> expect(container.textContent).toEqual('hovered'); <add> }); <add> }); <add> <add> // @gate experimental <add> // @gate enableDiscreteEventMicroTasks && enableNativeEventPriorityInference <add> it('mouse enter should be user-blocking but not discrete', async () => { <add> const root = ReactDOM.unstable_createRoot(container); <add> <add> const target = React.createRef(null); <add> function Foo() { <add> const [isHover, setHover] = React.useState(false); <add> React.useLayoutEffect(() => { <add> target.current.onmouseenter = () => setHover(true); <add> }); <add> return <div ref={target}>{isHover ? 'hovered' : 'not hovered'}</div>; <add> } <add> <add> await act(async () => { <add> root.render(<Foo />); <add> }); <add> expect(container.textContent).toEqual('not hovered'); <add> <add> await act(async () => { <add> // Note: React does not use native mouseenter/mouseleave events <add> // but we should still correctly determine their priority. <add> const mouseEnterEvent = document.createEvent('MouseEvents'); <add> mouseEnterEvent.initEvent('mouseenter', true, true); <add> dispatchAndSetCurrentEvent(target.current, mouseEnterEvent); <add> <add> // 3s should be enough to expire the updates <add> Scheduler.unstable_advanceTime(3000); <add> expect(Scheduler).toFlushExpired([]); <add> expect(container.textContent).toEqual('hovered'); <add> }); <add> }); <ide> }); <ide><path>packages/react-dom/src/events/DOMEventNames.js <ide> export type DOMEventName = <ide> // 'animationend | <ide> // 'animationstart' | <ide> | 'beforeblur' // Not a real event. This is used by event experiments. <add> | 'beforeinput' <add> | 'blur' <ide> | 'canplay' <ide> | 'canplaythrough' <ide> | 'cancel' <ide> export type DOMEventName = <ide> | 'encrypted' <ide> | 'ended' <ide> | 'error' <add> | 'focus' <ide> | 'focusin' <ide> | 'focusout' <add> | 'fullscreenchange' <ide> | 'gotpointercapture' <add> | 'hashchange' <ide> | 'input' <ide> | 'invalid' <ide> | 'keydown' <ide> export type DOMEventName = <ide> | 'loadedmetadata' <ide> | 'lostpointercapture' <ide> | 'mousedown' <add> | 'mouseenter' <add> | 'mouseleave' <ide> | 'mousemove' <ide> | 'mouseout' <ide> | 'mouseover' <ide> export type DOMEventName = <ide> | 'pointerout' <ide> | 'pointerover' <ide> | 'pointerup' <add> | 'popstate' <ide> | 'progress' <ide> | 'ratechange' <ide> | 'reset' <ide> | 'scroll' <ide> | 'seeked' <ide> | 'seeking' <add> | 'select' <add> | 'selectstart' <ide> | 'selectionchange' <ide> | 'stalled' <ide> | 'submit' <ide><path>packages/react-dom/src/events/ReactDOMEventListener.js <ide> export function getEventPriority(domEventName: DOMEventName): * { <ide> // eslint-disable-next-line no-fallthrough <ide> case 'beforeblur': <ide> case 'afterblur': <add> // Not used by React but could be by user code: <add> // eslint-disable-next-line no-fallthrough <add> case 'beforeinput': <add> case 'blur': <add> case 'fullscreenchange': <add> case 'focus': <add> case 'hashchange': <add> case 'popstate': <add> case 'select': <add> case 'selectstart': <ide> return InputDiscreteLanePriority; <ide> case 'drag': <ide> case 'dragenter': <ide> export function getEventPriority(domEventName: DOMEventName): * { <ide> case 'toggle': <ide> case 'touchmove': <ide> case 'wheel': <add> // Not used by React but could be by user code: <add> // eslint-disable-next-line no-fallthrough <add> case 'mouseenter': <add> case 'mouseleave': <ide> return InputContinuousLanePriority; <ide> default: <ide> return DefaultLanePriority;
3