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
improve debug hash with stack trace
e3c63b44240573b05cec62f292e7a565ea242bc2
<ide><path>lib/util/createHash.js <ide> class DebugHash { <ide> <ide> update(data, inputEncoding) { <ide> if (typeof data !== "string") data = data.toString("utf-8"); <del> this.string += data; <add> if (data.startsWith("debug-digest-")) { <add> data = Buffer.from(data.slice("debug-digest-".length), "hex").toString(); <add> } <add> this.string += `[${data}](${new Error().stack.split("\n")[2]})\n`; <ide> return this; <ide> } <ide> <ide> digest(encoding) { <del> return this.string.replace(/[^a-z0-9]+/gi, m => <del> Buffer.from(m).toString("hex") <del> ); <add> return "debug-digest-" + Buffer.from(this.string).toString("hex"); <ide> } <ide> } <ide>
1
Go
Go
copy authconfigs on save so data is not modified
9332c00ca562e97045490d3d45d8f805fae30330
<ide><path>auth/auth.go <ide> func SaveConfig(configFile *ConfigFile) error { <ide> os.Remove(confFile) <ide> return nil <ide> } <add> <add> configs := make(map[string]AuthConfig, len(configFile.Configs)) <ide> for k, authConfig := range configFile.Configs { <del> authConfig.Auth = encodeAuth(&authConfig) <del> authConfig.Username = "" <del> authConfig.Password = "" <del> configFile.Configs[k] = authConfig <add> authCopy := authConfig <add> <add> authCopy.Auth = encodeAuth(&authCopy) <add> authCopy.Username = "" <add> authCopy.Password = "" <add> <add> configs[k] = authCopy <ide> } <ide> <del> b, err := json.Marshal(configFile.Configs) <add> b, err := json.Marshal(configs) <ide> if err != nil { <ide> return err <ide> }
1
Javascript
Javascript
horizon chart improvements
a15165398d8633d0eeb929cade77c0557def0479
<ide><path>d3.chart.js <ide> function d3_chart_boxQuartiles(d) { <ide> return ~~q === q ? (d[q] + d[q + 1]) / 2 : d[Math.round(q)]; <ide> }); <ide> } <del>// ranges (bad, satisfactory, good) <del>// measures (actual, forecast) <del>// markers (previous, goal) <del> <del>/* <del> * Chart design based on the recommendations of Stephen Few. Implementation <del> * based on the work of Clint Ivy, Jamie Love, and Jason Davies. <del> * http://projects.instantcognition.com/protovis/bulletchart/ <del> */ <del> <add>// Chart design based on the recommendations of Stephen Few. Implementation <add>// based on the work of Clint Ivy, Jamie Love, and Jason Davies. <add>// http://projects.instantcognition.com/protovis/bulletchart/ <ide> d3.chart.bullet = function() { <ide> var orient = "left", // TODO top & bottom <ide> reverse = false, <ide> d3.chart.bullet = function() { <ide> return bullet; <ide> }; <ide> <add> // ranges (bad, satisfactory, good) <ide> bullet.ranges = function(x) { <ide> if (!arguments.length) return ranges; <ide> ranges = x; <ide> return bullet; <ide> }; <ide> <add> // markers (previous, goal) <ide> bullet.markers = function(x) { <ide> if (!arguments.length) return markers; <ide> markers = x; <ide> return bullet; <ide> }; <ide> <add> // measures (actual, forecast) <ide> bullet.measures = function(x) { <ide> if (!arguments.length) return measures; <ide> measures = x; <ide> function d3_chart_bulletWidth(x) { <ide> // area chart where the area is folded into multiple bands. Color is used to <ide> // encode band, allowing the size of the chart to be reduced significantly <ide> // without impeding readability. This layout algorithm is based on the work of <del>// J. Heer, N. Kong and M. Agrawala in <a <del>// href="http://hci.stanford.edu/publications/2009/heer-horizon-chi09.pdf">"Sizing <del>// the Horizon: The Effects of Chart Size and Layering on the Graphical <del>// Perception of Time Series Visualizations"</a>, CHI 2009. <add>// J. Heer, N. Kong and M. Agrawala in "Sizing the Horizon: The Effects of Chart <add>// Size and Layering on the Graphical Perception of Time Series Visualizations", <add>// CHI 2009. http://hci.stanford.edu/publications/2009/heer-horizon-chi09.pdf <ide> d3.chart.horizon = function() { <del> var bands = 2, <del> mode, // TODO "mirror" and "offset" <del> xValue = d3_chart_horizonX, <del> yValue = d3_chart_horizonY, <del> size = [1, 1], <add> var bands = 1, // between 1 and 5, typically <add> mode = "offset", // or mirror <add> interpolate = "linear", // or basis, monotone, step-before, etc. <add> x = d3_chart_horizonX, <add> y = d3_chart_horizonY, <add> w = 960, <add> h = 40, <ide> duration = 0; <ide> <ide> // For each small multiple… <ide> function horizon(g) { <del> var w = size[0], h = size[1]; <ide> g.each(function(d, i) { <ide> var g = d3.select(this), <del> xMin = Infinity, xMax = -Infinity, <del> yMin = Infinity, yMax = -Infinity, <add> n = 2 * bands + 1, <add> xMin = Infinity, <add> xMax = -Infinity, <add> yMax = -Infinity, <ide> x0, // old x-scale <del> y0; // old y-scale <del> <del> // Compute x- and y-values along with extents. <del> var data = d.map(function(d, i) { <del> var x = xValue.call(this, d, i), <del> y = yValue.call(this, d, i); <del> if (x < xMin) xMin = x; <del> if (x > xMax) xMax = x; <del> if (y < yMin) yMin = y; <del> if (y > yMax) yMax = y; <del> return [x, y]; <add> y0, // old y-scale <add> id; // unique id for paths <add> <add> // Compute x- and y-values along with extents. <add> var data = d.map(function(d, i) { <add> var xv = x.call(this, d, i), <add> yv = y.call(this, d, i); <add> if (xv < xMin) xMin = xv; <add> if (xv > xMax) xMax = xv; <add> if (-yv > yMax) yMax = -yv; <add> if (yv > yMax) yMax = yv; <add> return [xv, yv]; <ide> }); <ide> <ide> // Compute the new x- and y-scales. <ide> var x1 = d3.scale.linear().domain([xMin, xMax]).range([0, w]), <del> y1 = d3.scale.linear().domain([yMin, yMax]).range([0, h * bands]); <add> y1 = d3.scale.linear().domain([0, yMax]).range([0, h * bands]); <ide> <ide> // Retrieve the old scales, if this is an update. <ide> if (this.__chart__) { <ide> x0 = this.__chart__.x; <ide> y0 = this.__chart__.y; <add> id = this.__chart__.id; <ide> } else { <ide> x0 = d3.scale.linear().domain([0, Infinity]).range(x1.range()); <ide> y0 = d3.scale.linear().domain([0, Infinity]).range(y1.range()); <add> id = ++d3_chart_horizonId; <ide> } <ide> <ide> // Stash the new scales. <del> this.__chart__ = {x: x1, y: y1}; <add> this.__chart__ = {x: x1, y: y1, id: id}; <ide> <del> // Render the path as a referenceable definition. <del> var area0 = d3.svg.area() <add> // We'll use a defs to store the area path and the clip path. <add> var defs = g.selectAll("defs") <add> .data([data]); <add> <add> var defsEnter = defs.enter().append("svg:defs"); <add> <add> // The clip path is a simple rect. <add> defsEnter.append("svg:clipPath") <add> .attr("id", "d3_chart_horizon_clip" + id) <add> .append("svg:rect") <add> .attr("width", w) <add> .attr("height", h); <add> <add> defs.select("rect").transition() <add> .duration(duration) <add> .attr("width", w) <add> .attr("height", h); <add> <add> // The area path is rendered with our resuable d3.svg.area. <add> defsEnter.append("svg:path") <add> .attr("id", "d3_chart_horizon_path" + id) <add> .attr("d", d3_chart_horizonArea <add> .interpolate(interpolate) <ide> .x(function(d) { return x0(d[0]); }) <ide> .y0(h * bands) <del> .y1(function(d) { return h * bands - y0(d[1]); }), <del> area1 = d3.svg.area() <add> .y1(function(d) { return h * bands - y0(d[1]); })) <add> .transition() <add> .duration(duration) <add> .attr("d", d3_chart_horizonArea <ide> .x(function(d) { return x1(d[0]); }) <del> .y0(h * bands) <del> .y1(function(d) { return h * bands - y1(d[1]); }); <add> .y1(function(d) { return h * bands - y1(d[1]); })); <ide> <del> var defs = g.selectAll("defs") <del> .data([data]); <del> defs.enter().append("svg:defs").append("svg:path") <del> .attr("id", "d3_chart_horizon_" + i) <del> .attr("d", area0) <del> .transition().duration(duration) <del> .attr("d", area1); <del> defs.select("path") <del> .transition().duration(duration) <del> .attr("d", area1); <del> <del> // Instantiate `n` copies of the path with different offsets. <del> var use = g.selectAll("use") <del> .data(d3.range(bands)); <del> use.enter().append("svg:use") <del> .attr("class", function(d, i) { return "q" + i + "-" + bands; }) <del> .attr("y", function(d, i) { return -(bands - i - 1) * h; }) <del> .attr("xlink:href", "#d3_chart_horizon_" + i); <del> use.exit().remove(); <add> defs.select("path").transition() <add> .duration(duration) <add> .attr("d", d3_chart_horizonArea); <add> <add> // We'll use a container to clip all horizon layers at once. <add> g.selectAll("g") <add> .data([null]) <add> .enter().append("svg:g") <add> .attr("clip-path", "url(#d3_chart_horizon_clip" + id + ")"); <add> <add> // Define the transform function based on the mode. <add> var transform = mode == "offset" <add> ? function(d) { return "translate(0," + (d + (d < 0) - bands) * h + ")"; } <add> : function(d) { return (d < 0 ? "scale(1,-1)" : "") + "translate(0," + (d - bands) * h + ")"; }; <add> <add> // Instantiate each copy of the path with different transforms. <add> var u = g.select("g").selectAll("use") <add> .data(d3.range(-1, -bands - 1, -1).concat(d3.range(1, bands + 1))) <add> .attr("class", function(d) { return "q" + (d + bands) + "-" + n; }); <add> <add> u.enter().append("svg:use") <add> .attr("xlink:href", "#d3_chart_horizon_path" + id) <add> .attr("class", function(d) { return "q" + (d + bands) + "-" + n; }) <add> .attr("transform", transform); <add> <add> // TODO Better transitions when the number of bands changes. <add> u.transition() <add> .duration(duration) <add> .attr("transform", transform); <add> <add> u.exit().remove(); <ide> }); <ide> d3.timer.flush(); <ide> } <ide> <ide> horizon.duration = function(x) { <ide> if (!arguments.length) return duration; <del> duration = x; <add> duration = +x; <ide> return horizon; <ide> }; <ide> <ide> horizon.bands = function(x) { <ide> if (!arguments.length) return bands; <del> bands = x; <add> bands = +x; <ide> return horizon; <ide> }; <ide> <ide> horizon.mode = function(x) { <ide> if (!arguments.length) return mode; <del> mode = x; <add> mode = x + ""; <ide> return horizon; <ide> }; <ide> <del> horizon.x = function(x) { <del> if (!arguments.length) return xValue; <del> xValue = x; <add> horizon.interpolate = function(x) { <add> if (!arguments.length) return interpolate; <add> interpolate = x + ""; <ide> return horizon; <ide> }; <ide> <del> horizon.y = function(x) { <del> if (!arguments.length) return yValue; <del> yValue = x; <add> horizon.x = function(z) { <add> if (!arguments.length) return x; <add> x = z; <ide> return horizon; <ide> }; <ide> <del> horizon.size = function(x) { <del> if (!arguments.length) return size; <del> size = x; <add> horizon.y = function(z) { <add> if (!arguments.length) return y; <add> y = z; <ide> return horizon; <ide> }; <del> <add> <add> horizon.width = function(x) { <add> if (!arguments.length) return width; <add> w = +x; <add> return horizon; <add> }; <add> <add> horizon.height = function(x) { <add> if (!arguments.length) return height; <add> h = +x; <add> return horizon; <add> }; <add> <ide> return horizon; <ide> }; <ide> <add>var d3_chart_horizonArea = d3.svg.area(), <add> d3_chart_horizonId = 0; <add> <ide> function d3_chart_horizonX(d) { <del> return d.x; <add> return d[0]; <ide> } <ide> <ide> function d3_chart_horizonY(d) { <del> return d.y; <add> return d[1]; <ide> } <ide> // Based on http://vis.stanford.edu/protovis/ex/qqplot.html <ide> d3.chart.qq = function() { <ide><path>d3.chart.min.js <del>(function(){function l(a){return a.y}function k(a){return a.x}function j(a,b){var c=b.length-1;b=b.slice().sort(d3.ascending);return d3.range(a).map(function(d){return b[~~(d*c/a)]})}function i(a){return a.y}function h(a){return a.x}function g(a){var b=a(0);return function(c){return Math.abs(a(c)-b)}}function f(a){return function(b){return"translate("+a(b)+",0)"}}function e(a){return a.measures}function d(a){return a.markers}function c(a){return a.ranges}function b(a){var b=a.length;return[.25,.5,.75].map(function(c){c*=b;return~~c===c?(a[c]+a[c+1])/2:a[Math.round(c)]})}function a(a){return[0,a.length-1]}d3.chart={},d3.chart.box=function(){function k(a){a.each(function(a,b){a=a.map(g).sort(d3.ascending);var k=d3.select(this),l=a.length,m=a[0],n=a[l-1],o=a.quartiles=i(a),p=h&&h.call(this,a,b),q=p&&p.map(function(b){return a[b]}),r=p?d3.range(0,p[0]).concat(d3.range(p[1]+1,l)):d3.range(l),s=d3.scale.linear().domain(f&&f.call(this,a,b)||[m,n]).range([d,0]),t=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(s.range());this.__chart__=s;var u=k.selectAll("line.center").data(q?[q]:[]);u.enter().insert("svg:line","rect").attr("class","center").attr("x1",c/2).attr("y1",function(a){return t(a[0])}).attr("x2",c/2).attr("y2",function(a){return t(a[1])}).style("opacity",1e-6).transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.exit().transition().duration(e).style("opacity",1e-6).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}).remove();var v=k.selectAll("rect.box").data([o]);v.enter().append("svg:rect").attr("class","box").attr("x",0).attr("y",function(a){return t(a[2])}).attr("width",c).attr("height",function(a){return t(a[0])-t(a[2])}).transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])}),v.transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])});var w=k.selectAll("line.median").data([o[1]]);w.enter().append("svg:line").attr("class","median").attr("x1",0).attr("y1",t).attr("x2",c).attr("y2",t).transition().duration(e).attr("y1",s).attr("y2",s),w.transition().duration(e).attr("y1",s).attr("y2",s);var x=k.selectAll("line.whisker").data(q||[]);x.enter().insert("svg:line","circle, text").attr("class","whisker").attr("x1",0).attr("y1",t).attr("x2",c).attr("y2",t).style("opacity",1e-6).transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.exit().transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1e-6).remove();var y=k.selectAll("circle.outlier").data(r,Number);y.enter().insert("svg:circle","text").attr("class","outlier").attr("r",5).attr("cx",c/2).attr("cy",function(b){return t(a[b])}).style("opacity",1e-6).transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.exit().transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1e-6).remove();var z=j||s.tickFormat(8),A=k.selectAll("text.box").data(o);A.enter().append("svg:text").attr("class","box").attr("dy",".3em").attr("dx",function(a,b){return b&1?6:-6}).attr("x",function(a,b){return b&1?c:0}).attr("y",t).attr("text-anchor",function(a,b){return b&1?"start":"end"}).text(z).transition().duration(e).attr("y",s),A.transition().duration(e).text(z).attr("y",s);var B=k.selectAll("text.whisker").data(q||[]);B.enter().append("svg:text").attr("class","whisker").attr("dy",".3em").attr("dx",6).attr("x",c).attr("y",t).text(z).style("opacity",1e-6).transition().duration(e).attr("y",s).style("opacity",1),B.transition().duration(e).text(z).attr("y",s).style("opacity",1),B.exit().transition().duration(e).attr("y",s).style("opacity",1e-6).remove()}),d3.timer.flush()}var c=1,d=1,e=0,f=null,g=Number,h=a,i=b,j=null;k.width=function(a){if(!arguments.length)return c;c=a;return k},k.height=function(a){if(!arguments.length)return d;d=a;return k},k.tickFormat=function(a){if(!arguments.length)return j;j=a;return k},k.duration=function(a){if(!arguments.length)return e;e=a;return k},k.domain=function(a){if(!arguments.length)return f;f=a==null?a:d3.functor(a);return k},k.value=function(a){if(!arguments.length)return g;g=a;return k},k.whiskers=function(a){if(!arguments.length)return h;h=a;return k},k.quartiles=function(a){if(!arguments.length)return i;i=a;return k};return k},d3.chart.bullet=function(){function o(a){a.each(function(a,c){var d=i.call(this,a,c).slice().sort(d3.descending),e=j.call(this,a,c).slice().sort(d3.descending),o=k.call(this,a,c).slice().sort(d3.descending),p=d3.select(this),q=d3.scale.linear().domain([0,Math.max(d[0],e[0],o[0])]).range(b?[l,0]:[0,l]),r=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(q.range());this.__chart__=q;var s=g(r),t=g(q),u=p.selectAll("rect.range").data(d);u.enter().append("svg:rect").attr("class",function(a,b){return"range s"+b}).attr("width",s).attr("height",m).attr("x",b?r:0).transition().duration(h).attr("width",t).attr("x",b?q:0),u.transition().duration(h).attr("x",b?q:0).attr("width",t).attr("height",m);var v=p.selectAll("rect.measure").data(o);v.enter().append("svg:rect").attr("class",function(a,b){return"measure s"+b}).attr("width",s).attr("height",m/3).attr("x",b?r:0).attr("y",m/3).transition().duration(h).attr("width",t).attr("x",b?q:0),v.transition().duration(h).attr("width",t).attr("height",m/3).attr("x",b?q:0).attr("y",m/3);var w=p.selectAll("line.marker").data(e);w.enter().append("svg:line").attr("class","marker").attr("x1",r).attr("x2",r).attr("y1",m/6).attr("y2",m*5/6).transition().duration(h).attr("x1",q).attr("x2",q),w.transition().duration(h).attr("x1",q).attr("x2",q).attr("y1",m/6).attr("y2",m*5/6);var x=n||q.tickFormat(8),y=p.selectAll("g.tick").data(q.ticks(8),function(a){return this.textContent||x(a)}),z=y.enter().append("svg:g").attr("class","tick").attr("transform",f(r)).attr("opacity",1e-6);z.append("svg:line").attr("y1",m).attr("y2",m*7/6),z.append("svg:text").attr("text-anchor","middle").attr("dy","1em").attr("y",m*7/6).text(x),z.transition().duration(h).attr("transform",f(q)).attr("opacity",1);var A=y.transition().duration(h).attr("transform",f(q)).attr("opacity",1);A.select("line").attr("y1",m).attr("y2",m*7/6),A.select("text").attr("y",m*7/6),y.exit().transition().duration(h).attr("transform",f(q)).attr("opacity",1e-6).remove()}),d3.timer.flush()}var a="left",b=!1,h=0,i=c,j=d,k=e,l=380,m=30,n=null;o.orient=function(c){if(!arguments.length)return a;a=c,b=a=="right"||a=="bottom";return o},o.ranges=function(a){if(!arguments.length)return i;i=a;return o},o.markers=function(a){if(!arguments.length)return j;j=a;return o},o.measures=function(a){if(!arguments.length)return k;k=a;return o},o.width=function(a){if(!arguments.length)return l;l=a;return o},o.height=function(a){if(!arguments.length)return m;m=a;return o},o.tickFormat=function(a){if(!arguments.length)return n;n=a;return o},o.duration=function(a){if(!arguments.length)return h;h=a;return o};return o},d3.chart.horizon=function(){function g(b){var g=e[0],h=e[1];b.each(function(b,e){var i=d3.select(this),j=Infinity,k=-Infinity,l=Infinity,m=-Infinity,n,o,p=b.map(function(a,b){var e=c.call(this,a,b),f=d.call(this,a,b);e<j&&(j=e),e>k&&(k=e),f<l&&(l=f),f>m&&(m=f);return[e,f]}),q=d3.scale.linear().domain([j,k]).range([0,g]),r=d3.scale.linear().domain([l,m]).range([0,h*a]);this.__chart__?(n=this.__chart__.x,o=this.__chart__.y):(n=d3.scale.linear().domain([0,Infinity]).range(q.range()),o=d3.scale.linear().domain([0,Infinity]).range(r.range())),this.__chart__={x:q,y:r};var s=d3.svg.area().x(function(a){return n(a[0])}).y0(h*a).y1(function(b){return h*a-o(b[1])}),t=d3.svg.area().x(function(a){return q(a[0])}).y0(h*a).y1(function(b){return h*a-r(b[1])}),u=i.selectAll("defs").data([p]);u.enter().append("svg:defs").append("svg:path").attr("id","d3_chart_horizon_"+e).attr("d",s).transition().duration(f).attr("d",t),u.select("path").transition().duration(f).attr("d",t);var v=i.selectAll("use").data(d3.range(a));v.enter().append("svg:use").attr("class",function(b,c){return"q"+c+"-"+a}).attr("y",function(b,c){return-(a-c-1)*h}).attr("xlink:href","#d3_chart_horizon_"+e),v.exit().remove()}),d3.timer.flush()}var a=2,b,c=h,d=i,e=[1,1],f=0;g.duration=function(a){if(!arguments.length)return f;f=a;return g},g.bands=function(b){if(!arguments.length)return a;a=b;return g},g.mode=function(a){if(!arguments.length)return b;b=a;return g},g.x=function(a){if(!arguments.length)return c;c=a;return g},g.y=function(a){if(!arguments.length)return d;d=a;return g},g.size=function(a){if(!arguments.length)return e;e=a;return g};return g},d3.chart.qq=function(){function i(i){i.each(function(i,k){var l=d3.select(this),m=j(f,g.call(this,i,k)),o=j(f,h.call(this,i,k)),p=d&&d.call(this,i,k)||[d3.min(m),d3.max(m)],q=d&&d.call(this,i,k)||[d3.min(o),d3.max(o)],r,s,t=d3.scale.linear().domain(p).range([0,a]),u=d3.scale.linear().domain(q).range([b,0]);this.__chart__?(r=this.__chart__.x,s=this.__chart__.y):(r=d3.scale.linear().domain([0,Infinity]).range(t.range()),s=d3.scale.linear().domain([0,Infinity]).range(u.range())),this.__chart__={x:t,y:u};var v=l.selectAll("line.diagonal").data([null]);v.enter().append("svg:line").attr("class","diagonal").attr("x1",t(q[0])).attr("y1",u(p[0])).attr("x2",t(q[1])).attr("y2",u(p[1])),v.transition().duration(c).attr("x1",t(q[0])).attr("y1",u(p[0])).attr("x2",t(q[1])).attr("y2",u(p[1]));var w=l.selectAll("circle").data(d3.range(f).map(function(a){return{x:m[a],y:o[a]}}));w.enter().append("svg:circle").attr("class","quantile").attr("r",4.5).attr("cx",function(a){return r(a.x)}).attr("cy",function(a){return s(a.y)}).style("opacity",1e-6).transition().duration(c).attr("cx",function(a){return t(a.x)}).attr("cy",function(a){return u(a.y)}).style("opacity",1),w.transition().duration(c).attr("cx",function(a){return t(a.x)}).attr("cy",function(a){return u(a.y)}).style("opacity",1),w.exit().transition().duration(c).attr("cx",function(a){return t(a.x)}).attr("cy",function(a){return u(a.y)}).style("opacity",1e-6).remove();var z=e||t.tickFormat(4),A=e||u.tickFormat(4),B=function(a){return"translate("+t(a)+","+b+")"},C=function(a){return"translate(0,"+u(a)+")"},D=l.selectAll("g.x.tick").data(t.ticks(4),function(a){return this.textContent||z(a)}),E=D.enter().append("svg:g").attr("class","x tick").attr("transform",function(a){return"translate("+r(a)+","+b+")"}).attr("opacity",1e-6);E.append("svg:line").attr("y1",0).attr("y2",-6),E.append("svg:text").attr("text-anchor","middle").attr("dy","1em").text(z),E.transition().duration(c).attr("transform",B).attr("opacity",1),D.transition().duration(c).attr("transform",B).attr("opacity",1),D.exit().transition().duration(c).attr("transform",B).attr("opacity",1e-6).remove();var F=l.selectAll("g.y.tick").data(u.ticks(4),function(a){return this.textContent||A(a)}),G=F.enter().append("svg:g").attr("class","y tick").attr("transform",function(a){return"translate(0,"+s(a)+")"}).attr("opacity",1e-6);G.append("svg:line").attr("x1",0).attr("x2",6),G.append("svg:text").attr("text-anchor","end").attr("dx","-.5em").attr("dy",".3em").text(A),G.transition().duration(c).attr("transform",C).attr("opacity",1),F.transition().duration(c).attr("transform",C).attr("opacity",1),F.exit().transition().duration(c).attr("transform",C).attr("opacity",1e-6).remove()})}var a=1,b=1,c=0,d=null,e=null,f=100,g=k,h=l;i.width=function(b){if(!arguments.length)return a;a=b;return i},i.height=function(a){if(!arguments.length)return b;b=a;return i},i.duration=function(a){if(!arguments.length)return c;c=a;return i},i.domain=function(a){if(!arguments.length)return d;d=a==null?a:d3.functor(a);return i},i.count=function(a){if(!arguments.length)return f;f=a;return i},i.x=function(a){if(!arguments.length)return g;g=a;return i},i.y=function(a){if(!arguments.length)return h;h=a;return i},i.tickFormat=function(a){if(!arguments.length)return e;e=a;return i};return i}})() <ide>\ No newline at end of file <add>(function(){function n(a){return a.y}function m(a){return a.x}function l(a,b){var c=b.length-1;b=b.slice().sort(d3.ascending);return d3.range(a).map(function(d){return b[~~(d*c/a)]})}function k(a){return a[1]}function j(a){return a[0]}function g(a){var b=a(0);return function(c){return Math.abs(a(c)-b)}}function f(a){return function(b){return"translate("+a(b)+",0)"}}function e(a){return a.measures}function d(a){return a.markers}function c(a){return a.ranges}function b(a){var b=a.length;return[.25,.5,.75].map(function(c){c*=b;return~~c===c?(a[c]+a[c+1])/2:a[Math.round(c)]})}function a(a){return[0,a.length-1]}d3.chart={},d3.chart.box=function(){function k(a){a.each(function(a,b){a=a.map(g).sort(d3.ascending);var k=d3.select(this),l=a.length,m=a[0],n=a[l-1],o=a.quartiles=i(a),p=h&&h.call(this,a,b),q=p&&p.map(function(b){return a[b]}),r=p?d3.range(0,p[0]).concat(d3.range(p[1]+1,l)):d3.range(l),s=d3.scale.linear().domain(f&&f.call(this,a,b)||[m,n]).range([d,0]),t=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(s.range());this.__chart__=s;var u=k.selectAll("line.center").data(q?[q]:[]);u.enter().insert("svg:line","rect").attr("class","center").attr("x1",c/2).attr("y1",function(a){return t(a[0])}).attr("x2",c/2).attr("y2",function(a){return t(a[1])}).style("opacity",1e-6).transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.transition().duration(e).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.exit().transition().duration(e).style("opacity",1e-6).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}).remove();var v=k.selectAll("rect.box").data([o]);v.enter().append("svg:rect").attr("class","box").attr("x",0).attr("y",function(a){return t(a[2])}).attr("width",c).attr("height",function(a){return t(a[0])-t(a[2])}).transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])}),v.transition().duration(e).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])});var w=k.selectAll("line.median").data([o[1]]);w.enter().append("svg:line").attr("class","median").attr("x1",0).attr("y1",t).attr("x2",c).attr("y2",t).transition().duration(e).attr("y1",s).attr("y2",s),w.transition().duration(e).attr("y1",s).attr("y2",s);var x=k.selectAll("line.whisker").data(q||[]);x.enter().insert("svg:line","circle, text").attr("class","whisker").attr("x1",0).attr("y1",t).attr("x2",c).attr("y2",t).style("opacity",1e-6).transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1),x.exit().transition().duration(e).attr("y1",s).attr("y2",s).style("opacity",1e-6).remove();var y=k.selectAll("circle.outlier").data(r,Number);y.enter().insert("svg:circle","text").attr("class","outlier").attr("r",5).attr("cx",c/2).attr("cy",function(b){return t(a[b])}).style("opacity",1e-6).transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.exit().transition().duration(e).attr("cy",function(b){return s(a[b])}).style("opacity",1e-6).remove();var z=j||s.tickFormat(8),A=k.selectAll("text.box").data(o);A.enter().append("svg:text").attr("class","box").attr("dy",".3em").attr("dx",function(a,b){return b&1?6:-6}).attr("x",function(a,b){return b&1?c:0}).attr("y",t).attr("text-anchor",function(a,b){return b&1?"start":"end"}).text(z).transition().duration(e).attr("y",s),A.transition().duration(e).text(z).attr("y",s);var B=k.selectAll("text.whisker").data(q||[]);B.enter().append("svg:text").attr("class","whisker").attr("dy",".3em").attr("dx",6).attr("x",c).attr("y",t).text(z).style("opacity",1e-6).transition().duration(e).attr("y",s).style("opacity",1),B.transition().duration(e).text(z).attr("y",s).style("opacity",1),B.exit().transition().duration(e).attr("y",s).style("opacity",1e-6).remove()}),d3.timer.flush()}var c=1,d=1,e=0,f=null,g=Number,h=a,i=b,j=null;k.width=function(a){if(!arguments.length)return c;c=a;return k},k.height=function(a){if(!arguments.length)return d;d=a;return k},k.tickFormat=function(a){if(!arguments.length)return j;j=a;return k},k.duration=function(a){if(!arguments.length)return e;e=a;return k},k.domain=function(a){if(!arguments.length)return f;f=a==null?a:d3.functor(a);return k},k.value=function(a){if(!arguments.length)return g;g=a;return k},k.whiskers=function(a){if(!arguments.length)return h;h=a;return k},k.quartiles=function(a){if(!arguments.length)return i;i=a;return k};return k},d3.chart.bullet=function(){function o(a){a.each(function(a,c){var d=i.call(this,a,c).slice().sort(d3.descending),e=j.call(this,a,c).slice().sort(d3.descending),o=k.call(this,a,c).slice().sort(d3.descending),p=d3.select(this),q=d3.scale.linear().domain([0,Math.max(d[0],e[0],o[0])]).range(b?[l,0]:[0,l]),r=this.__chart__||d3.scale.linear().domain([0,Infinity]).range(q.range());this.__chart__=q;var s=g(r),t=g(q),u=p.selectAll("rect.range").data(d);u.enter().append("svg:rect").attr("class",function(a,b){return"range s"+b}).attr("width",s).attr("height",m).attr("x",b?r:0).transition().duration(h).attr("width",t).attr("x",b?q:0),u.transition().duration(h).attr("x",b?q:0).attr("width",t).attr("height",m);var v=p.selectAll("rect.measure").data(o);v.enter().append("svg:rect").attr("class",function(a,b){return"measure s"+b}).attr("width",s).attr("height",m/3).attr("x",b?r:0).attr("y",m/3).transition().duration(h).attr("width",t).attr("x",b?q:0),v.transition().duration(h).attr("width",t).attr("height",m/3).attr("x",b?q:0).attr("y",m/3);var w=p.selectAll("line.marker").data(e);w.enter().append("svg:line").attr("class","marker").attr("x1",r).attr("x2",r).attr("y1",m/6).attr("y2",m*5/6).transition().duration(h).attr("x1",q).attr("x2",q),w.transition().duration(h).attr("x1",q).attr("x2",q).attr("y1",m/6).attr("y2",m*5/6);var x=n||q.tickFormat(8),y=p.selectAll("g.tick").data(q.ticks(8),function(a){return this.textContent||x(a)}),z=y.enter().append("svg:g").attr("class","tick").attr("transform",f(r)).attr("opacity",1e-6);z.append("svg:line").attr("y1",m).attr("y2",m*7/6),z.append("svg:text").attr("text-anchor","middle").attr("dy","1em").attr("y",m*7/6).text(x),z.transition().duration(h).attr("transform",f(q)).attr("opacity",1);var A=y.transition().duration(h).attr("transform",f(q)).attr("opacity",1);A.select("line").attr("y1",m).attr("y2",m*7/6),A.select("text").attr("y",m*7/6),y.exit().transition().duration(h).attr("transform",f(q)).attr("opacity",1e-6).remove()}),d3.timer.flush()}var a="left",b=!1,h=0,i=c,j=d,k=e,l=380,m=30,n=null;o.orient=function(c){if(!arguments.length)return a;a=c,b=a=="right"||a=="bottom";return o},o.ranges=function(a){if(!arguments.length)return i;i=a;return o},o.markers=function(a){if(!arguments.length)return j;j=a;return o},o.measures=function(a){if(!arguments.length)return k;k=a;return o},o.width=function(a){if(!arguments.length)return l;l=a;return o},o.height=function(a){if(!arguments.length)return m;m=a;return o},o.tickFormat=function(a){if(!arguments.length)return n;n=a;return o},o.duration=function(a){if(!arguments.length)return h;h=a;return o};return o},d3.chart.horizon=function(){function m(j){j.each(function(j,k){var m=d3.select(this),n=2*a+1,o=Infinity,p=-Infinity,q=-Infinity,r,s,t,u=j.map(function(a,b){var c=d.call(this,a,b),f=e.call(this,a,b);c<o&&(o=c),c>p&&(p=c),-f>q&&(q=-f),f>q&&(q=f);return[c,f]}),v=d3.scale.linear().domain([o,p]).range([0,f]),z=d3.scale.linear().domain([0,q]).range([0,g*a]);this.__chart__?(r=this.__chart__.x,s=this.__chart__.y,t=this.__chart__.id):(r=d3.scale.linear().domain([0,Infinity]).range(v.range()),s=d3.scale.linear().domain([0,Infinity]).range(z.range()),t=++i),this.__chart__={x:v,y:z,id:t};var A=m.selectAll("defs").data([u]),B=A.enter().append("svg:defs");B.append("svg:clipPath").attr("id","d3_chart_horizon_clip"+t).append("svg:rect").attr("width",f).attr("height",g),A.select("rect").transition().duration(l).attr("width",f).attr("height",g),B.append("svg:path").attr("id","d3_chart_horizon_path"+t).attr("d",h.interpolate(c).x(function(a){return r(a[0])}).y0(g*a).y1(function(b){return g*a-s(b[1])})).transition().duration(l).attr("d",h.x(function(a){return v(a[0])}).y1(function(b){return g*a-z(b[1])})),A.select("path").transition().duration(l).attr("d",h),m.selectAll("g").data([null]).enter().append("svg:g").attr("clip-path","url(#d3_chart_horizon_clip"+t+")");var C=b=="offset"?function(b){return"translate(0,"+(b+(b<0)-a)*g+")"}:function(b){return(b<0?"scale(1,-1)":"")+"translate(0,"+(b-a)*g+")"},D=m.select("g").selectAll("use").data(d3.range(-1,-a-1,-1).concat(d3.range(1,a+1))).attr("class",function(b){return"q"+(b+a)+"-"+n});D.enter().append("svg:use").attr("xlink:href","#d3_chart_horizon_path"+t).attr("class",function(b){return"q"+(b+a)+"-"+n}).attr("transform",C),D.transition().duration(l).attr("transform",C),D.exit().remove()}),d3.timer.flush()}var a=1,b="offset",c="linear",d=j,e=k,f=960,g=40,l=0;m.duration=function(a){if(!arguments.length)return l;l=+a;return m},m.bands=function(b){if(!arguments.length)return a;a=+b;return m},m.mode=function(a){if(!arguments.length)return b;b=a+"";return m},m.interpolate=function(a){if(!arguments.length)return c;c=a+"";return m},m.x=function(a){if(!arguments.length)return d;d=a;return m},m.y=function(a){if(!arguments.length)return e;e=a;return m},m.width=function(a){if(!arguments.length)return width;f=+a;return m},m.height=function(a){if(!arguments.length)return height;g=+a;return m};return m};var h=d3.svg.area(),i=0;d3.chart.qq=function(){function i(i){i.each(function(i,j){var k=d3.select(this),m=l(f,g.call(this,i,j)),n=l(f,h.call(this,i,j)),o=d&&d.call(this,i,j)||[d3.min(m),d3.max(m)],p=d&&d.call(this,i,j)||[d3.min(n),d3.max(n)],q,r,s=d3.scale.linear().domain(o).range([0,a]),t=d3.scale.linear().domain(p).range([b,0]);this.__chart__?(q=this.__chart__.x,r=this.__chart__.y):(q=d3.scale.linear().domain([0,Infinity]).range(s.range()),r=d3.scale.linear().domain([0,Infinity]).range(t.range())),this.__chart__={x:s,y:t};var u=k.selectAll("line.diagonal").data([null]);u.enter().append("svg:line").attr("class","diagonal").attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1])),u.transition().duration(c).attr("x1",s(p[0])).attr("y1",t(o[0])).attr("x2",s(p[1])).attr("y2",t(o[1]));var v=k.selectAll("circle").data(d3.range(f).map(function(a){return{x:m[a],y:n[a]}}));v.enter().append("svg:circle").attr("class","quantile").attr("r",4.5).attr("cx",function(a){return q(a.x)}).attr("cy",function(a){return r(a.y)}).style("opacity",1e-6).transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1),v.exit().transition().duration(c).attr("cx",function(a){return s(a.x)}).attr("cy",function(a){return t(a.y)}).style("opacity",1e-6).remove();var w=e||s.tickFormat(4),z=e||t.tickFormat(4),A=function(a){return"translate("+s(a)+","+b+")"},B=function(a){return"translate(0,"+t(a)+")"},C=k.selectAll("g.x.tick").data(s.ticks(4),function(a){return this.textContent||w(a)}),D=C.enter().append("svg:g").attr("class","x tick").attr("transform",function(a){return"translate("+q(a)+","+b+")"}).attr("opacity",1e-6);D.append("svg:line").attr("y1",0).attr("y2",-6),D.append("svg:text").attr("text-anchor","middle").attr("dy","1em").text(w),D.transition().duration(c).attr("transform",A).attr("opacity",1),C.transition().duration(c).attr("transform",A).attr("opacity",1),C.exit().transition().duration(c).attr("transform",A).attr("opacity",1e-6).remove();var E=k.selectAll("g.y.tick").data(t.ticks(4),function(a){return this.textContent||z(a)}),F=E.enter().append("svg:g").attr("class","y tick").attr("transform",function(a){return"translate(0,"+r(a)+")"}).attr("opacity",1e-6);F.append("svg:line").attr("x1",0).attr("x2",6),F.append("svg:text").attr("text-anchor","end").attr("dx","-.5em").attr("dy",".3em").text(z),F.transition().duration(c).attr("transform",B).attr("opacity",1),E.transition().duration(c).attr("transform",B).attr("opacity",1),E.exit().transition().duration(c).attr("transform",B).attr("opacity",1e-6).remove()})}var a=1,b=1,c=0,d=null,e=null,f=100,g=m,h=n;i.width=function(b){if(!arguments.length)return a;a=b;return i},i.height=function(a){if(!arguments.length)return b;b=a;return i},i.duration=function(a){if(!arguments.length)return c;c=a;return i},i.domain=function(a){if(!arguments.length)return d;d=a==null?a:d3.functor(a);return i},i.count=function(a){if(!arguments.length)return f;f=a;return i},i.x=function(a){if(!arguments.length)return g;g=a;return i},i.y=function(a){if(!arguments.length)return h;h=a;return i},i.tickFormat=function(a){if(!arguments.length)return e;e=a;return i};return i}})() <ide>\ No newline at end of file <ide><path>examples/horizon/horizon.js <ide> var w = 960, <ide> h = 40; <ide> <ide> var chart = d3.chart.horizon() <del> .size([w, h]) <del> .bands(9) <del> .x(function(d) { return d.date; }) <del> .y(function(d) { return d.rate; }); <add> .width(w) <add> .height(h) <add> .bands(5) <add> .mode("offset") <add> .interpolate("basis"); <ide> <ide> d3.json("unemployment.json", function(data) { <ide> <add> // Offset so that positive is above-average and negative is below-average. <add> var mean = data.rate.reduce(function(p, v) { return p + v; }, 0) / data.rate.length; <add> <ide> // Transpose column values to rows. <ide> data = data.rate.map(function(rate, i) { <del> return {date: +new Date(data.year[i], data.month[i] - 1), rate: rate}; <add> return [Date.UTC(data.year[i], data.month[i] - 1), rate - mean]; <ide> }); <ide> <del> var svg = d3.select("body").selectAll("svg") <add> d3.select("body").append("svg:svg") <ide> .data([data]) <del> .enter().append("svg:svg") <del> .attr("class", "Blues") <add> .attr("class", "RdBu") <ide> .attr("width", w) <ide> .attr("height", h) <ide> .call(chart); <ide><path>src/chart/bullet.js <del>// ranges (bad, satisfactory, good) <del>// measures (actual, forecast) <del>// markers (previous, goal) <del> <del>/* <del> * Chart design based on the recommendations of Stephen Few. Implementation <del> * based on the work of Clint Ivy, Jamie Love, and Jason Davies. <del> * http://projects.instantcognition.com/protovis/bulletchart/ <del> */ <del> <add>// Chart design based on the recommendations of Stephen Few. Implementation <add>// based on the work of Clint Ivy, Jamie Love, and Jason Davies. <add>// http://projects.instantcognition.com/protovis/bulletchart/ <ide> d3.chart.bullet = function() { <ide> var orient = "left", // TODO top & bottom <ide> reverse = false, <ide> d3.chart.bullet = function() { <ide> return bullet; <ide> }; <ide> <add> // ranges (bad, satisfactory, good) <ide> bullet.ranges = function(x) { <ide> if (!arguments.length) return ranges; <ide> ranges = x; <ide> return bullet; <ide> }; <ide> <add> // markers (previous, goal) <ide> bullet.markers = function(x) { <ide> if (!arguments.length) return markers; <ide> markers = x; <ide> return bullet; <ide> }; <ide> <add> // measures (actual, forecast) <ide> bullet.measures = function(x) { <ide> if (!arguments.length) return measures; <ide> measures = x; <ide><path>src/chart/horizon.js <ide> // area chart where the area is folded into multiple bands. Color is used to <ide> // encode band, allowing the size of the chart to be reduced significantly <ide> // without impeding readability. This layout algorithm is based on the work of <del>// J. Heer, N. Kong and M. Agrawala in <a <del>// href="http://hci.stanford.edu/publications/2009/heer-horizon-chi09.pdf">"Sizing <del>// the Horizon: The Effects of Chart Size and Layering on the Graphical <del>// Perception of Time Series Visualizations"</a>, CHI 2009. <add>// J. Heer, N. Kong and M. Agrawala in "Sizing the Horizon: The Effects of Chart <add>// Size and Layering on the Graphical Perception of Time Series Visualizations", <add>// CHI 2009. http://hci.stanford.edu/publications/2009/heer-horizon-chi09.pdf <ide> d3.chart.horizon = function() { <del> var bands = 2, <del> mode, // TODO "mirror" and "offset" <del> xValue = d3_chart_horizonX, <del> yValue = d3_chart_horizonY, <del> size = [1, 1], <add> var bands = 1, // between 1 and 5, typically <add> mode = "offset", // or mirror <add> interpolate = "linear", // or basis, monotone, step-before, etc. <add> x = d3_chart_horizonX, <add> y = d3_chart_horizonY, <add> w = 960, <add> h = 40, <ide> duration = 0; <ide> <ide> // For each small multiple… <ide> function horizon(g) { <del> var w = size[0], h = size[1]; <ide> g.each(function(d, i) { <ide> var g = d3.select(this), <del> xMin = Infinity, xMax = -Infinity, <del> yMin = Infinity, yMax = -Infinity, <add> n = 2 * bands + 1, <add> xMin = Infinity, <add> xMax = -Infinity, <add> yMax = -Infinity, <ide> x0, // old x-scale <del> y0; // old y-scale <del> <del> // Compute x- and y-values along with extents. <del> var data = d.map(function(d, i) { <del> var x = xValue.call(this, d, i), <del> y = yValue.call(this, d, i); <del> if (x < xMin) xMin = x; <del> if (x > xMax) xMax = x; <del> if (y < yMin) yMin = y; <del> if (y > yMax) yMax = y; <del> return [x, y]; <add> y0, // old y-scale <add> id; // unique id for paths <add> <add> // Compute x- and y-values along with extents. <add> var data = d.map(function(d, i) { <add> var xv = x.call(this, d, i), <add> yv = y.call(this, d, i); <add> if (xv < xMin) xMin = xv; <add> if (xv > xMax) xMax = xv; <add> if (-yv > yMax) yMax = -yv; <add> if (yv > yMax) yMax = yv; <add> return [xv, yv]; <ide> }); <ide> <ide> // Compute the new x- and y-scales. <ide> var x1 = d3.scale.linear().domain([xMin, xMax]).range([0, w]), <del> y1 = d3.scale.linear().domain([yMin, yMax]).range([0, h * bands]); <add> y1 = d3.scale.linear().domain([0, yMax]).range([0, h * bands]); <ide> <ide> // Retrieve the old scales, if this is an update. <ide> if (this.__chart__) { <ide> x0 = this.__chart__.x; <ide> y0 = this.__chart__.y; <add> id = this.__chart__.id; <ide> } else { <ide> x0 = d3.scale.linear().domain([0, Infinity]).range(x1.range()); <ide> y0 = d3.scale.linear().domain([0, Infinity]).range(y1.range()); <add> id = ++d3_chart_horizonId; <ide> } <ide> <ide> // Stash the new scales. <del> this.__chart__ = {x: x1, y: y1}; <add> this.__chart__ = {x: x1, y: y1, id: id}; <ide> <del> // Render the path as a referenceable definition. <del> var area0 = d3.svg.area() <add> // We'll use a defs to store the area path and the clip path. <add> var defs = g.selectAll("defs") <add> .data([data]); <add> <add> var defsEnter = defs.enter().append("svg:defs"); <add> <add> // The clip path is a simple rect. <add> defsEnter.append("svg:clipPath") <add> .attr("id", "d3_chart_horizon_clip" + id) <add> .append("svg:rect") <add> .attr("width", w) <add> .attr("height", h); <add> <add> defs.select("rect").transition() <add> .duration(duration) <add> .attr("width", w) <add> .attr("height", h); <add> <add> // The area path is rendered with our resuable d3.svg.area. <add> defsEnter.append("svg:path") <add> .attr("id", "d3_chart_horizon_path" + id) <add> .attr("d", d3_chart_horizonArea <add> .interpolate(interpolate) <ide> .x(function(d) { return x0(d[0]); }) <ide> .y0(h * bands) <del> .y1(function(d) { return h * bands - y0(d[1]); }), <del> area1 = d3.svg.area() <add> .y1(function(d) { return h * bands - y0(d[1]); })) <add> .transition() <add> .duration(duration) <add> .attr("d", d3_chart_horizonArea <ide> .x(function(d) { return x1(d[0]); }) <del> .y0(h * bands) <del> .y1(function(d) { return h * bands - y1(d[1]); }); <del> <del> var defs = g.selectAll("defs") <del> .data([data]); <del> defs.enter().append("svg:defs").append("svg:path") <del> .attr("id", "d3_chart_horizon_" + i) <del> .attr("d", area0) <del> .transition().duration(duration) <del> .attr("d", area1); <del> defs.select("path") <del> .transition().duration(duration) <del> .attr("d", area1); <del> <del> // Instantiate `n` copies of the path with different offsets. <del> var use = g.selectAll("use") <del> .data(d3.range(bands)); <del> use.enter().append("svg:use") <del> .attr("class", function(d, i) { return "q" + i + "-" + bands; }) <del> .attr("y", function(d, i) { return -(bands - i - 1) * h; }) <del> .attr("xlink:href", "#d3_chart_horizon_" + i); <del> use.exit().remove(); <add> .y1(function(d) { return h * bands - y1(d[1]); })); <add> <add> defs.select("path").transition() <add> .duration(duration) <add> .attr("d", d3_chart_horizonArea); <add> <add> // We'll use a container to clip all horizon layers at once. <add> g.selectAll("g") <add> .data([null]) <add> .enter().append("svg:g") <add> .attr("clip-path", "url(#d3_chart_horizon_clip" + id + ")"); <add> <add> // Define the transform function based on the mode. <add> var transform = mode == "offset" <add> ? function(d) { return "translate(0," + (d + (d < 0) - bands) * h + ")"; } <add> : function(d) { return (d < 0 ? "scale(1,-1)" : "") + "translate(0," + (d - bands) * h + ")"; }; <add> <add> // Instantiate each copy of the path with different transforms. <add> var u = g.select("g").selectAll("use") <add> .data(d3.range(-1, -bands - 1, -1).concat(d3.range(1, bands + 1))) <add> .attr("class", function(d) { return "q" + (d + bands) + "-" + n; }); <add> <add> u.enter().append("svg:use") <add> .attr("xlink:href", "#d3_chart_horizon_path" + id) <add> .attr("class", function(d) { return "q" + (d + bands) + "-" + n; }) <add> .attr("transform", transform); <add> <add> // TODO Better transitions when the number of bands changes. <add> u.transition() <add> .duration(duration) <add> .attr("transform", transform); <add> <add> u.exit().remove(); <ide> }); <ide> d3.timer.flush(); <ide> } <ide> <ide> horizon.duration = function(x) { <ide> if (!arguments.length) return duration; <del> duration = x; <add> duration = +x; <ide> return horizon; <ide> }; <ide> <ide> horizon.bands = function(x) { <ide> if (!arguments.length) return bands; <del> bands = x; <add> bands = +x; <ide> return horizon; <ide> }; <ide> <ide> horizon.mode = function(x) { <ide> if (!arguments.length) return mode; <del> mode = x; <add> mode = x + ""; <ide> return horizon; <ide> }; <ide> <del> horizon.x = function(x) { <del> if (!arguments.length) return xValue; <del> xValue = x; <add> horizon.interpolate = function(x) { <add> if (!arguments.length) return interpolate; <add> interpolate = x + ""; <ide> return horizon; <ide> }; <ide> <del> horizon.y = function(x) { <del> if (!arguments.length) return yValue; <del> yValue = x; <add> horizon.x = function(z) { <add> if (!arguments.length) return x; <add> x = z; <ide> return horizon; <ide> }; <ide> <del> horizon.size = function(x) { <del> if (!arguments.length) return size; <del> size = x; <add> horizon.y = function(z) { <add> if (!arguments.length) return y; <add> y = z; <ide> return horizon; <ide> }; <del> <add> <add> horizon.width = function(x) { <add> if (!arguments.length) return width; <add> w = +x; <add> return horizon; <add> }; <add> <add> horizon.height = function(x) { <add> if (!arguments.length) return height; <add> h = +x; <add> return horizon; <add> }; <add> <ide> return horizon; <ide> }; <ide> <add>var d3_chart_horizonArea = d3.svg.area(), <add> d3_chart_horizonId = 0; <add> <ide> function d3_chart_horizonX(d) { <del> return d.x; <add> return d[0]; <ide> } <ide> <ide> function d3_chart_horizonY(d) { <del> return d.y; <add> return d[1]; <ide> }
5
Go
Go
move testbuildinheritance to integration-cli
f1d7ed35bd17c5e8e8f4d1882b5e98ae5419e9f1
<ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildADDFileNotFound(t *testing.T) { <ide> } <ide> logDone("build - add file not found") <ide> } <add> <add>func TestBuildInheritance(t *testing.T) { <add> name := "testbuildinheritance" <add> defer deleteImages(name) <add> <add> _, err := buildImage(name, <add> `FROM scratch <add> EXPOSE 2375`, <add> true) <add> if err != nil { <add> t.Fatal(err) <add> } <add> ports1, err := inspectField(name, "Config.ExposedPorts") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> _, err = buildImage(name, <add> fmt.Sprintf(`FROM %s <add> ENTRYPOINT ["/bin/echo"]`, name), <add> true) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> res, err := inspectField(name, "Config.Entrypoint") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if expected := "[/bin/echo]"; res != expected { <add> t.Fatalf("Entrypoint %s, expected %s", res, expected) <add> } <add> ports2, err := inspectField(name, "Config.ExposedPorts") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if ports1 != ports2 { <add> t.Fatalf("Ports must be same: %s != %s", ports1, ports2) <add> } <add> logDone("build - inheritance") <add>} <ide><path>integration/buildfile_test.go <ide> import ( <ide> "github.com/dotcloud/docker/archive" <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/image" <del> "github.com/dotcloud/docker/nat" <ide> "github.com/dotcloud/docker/server" <ide> "github.com/dotcloud/docker/utils" <ide> ) <ide> func buildImage(context testContextTemplate, t *testing.T, eng *engine.Engine, u <ide> return image, err <ide> } <ide> <del>func TestBuildInheritance(t *testing.T) { <del> eng := NewTestEngine(t) <del> defer nuke(mkDaemonFromEngine(eng, t)) <del> <del> img, err := buildImage(testContextTemplate{` <del> from {IMAGE} <del> expose 2375 <del> `, <del> nil, nil}, t, eng, true) <del> <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> img2, _ := buildImage(testContextTemplate{fmt.Sprintf(` <del> from %s <del> entrypoint ["/bin/echo"] <del> `, img.ID), <del> nil, nil}, t, eng, true) <del> <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> // from child <del> if img2.Config.Entrypoint[0] != "/bin/echo" { <del> t.Fail() <del> } <del> <del> // from parent <del> if _, exists := img.Config.ExposedPorts[nat.NewPort("tcp", "2375")]; !exists { <del> t.Fail() <del> } <del>} <del> <ide> func TestBuildFails(t *testing.T) { <ide> _, err := buildImage(testContextTemplate{` <ide> from {IMAGE}
2
Ruby
Ruby
append a "_" to memoized instance variables
7f0346237e30e55d6cd16a8b4a9dfe4193f61804
<ide><path>activesupport/lib/active_support/memoizable.rb <ide> def self.included(base) #:nodoc: <ide> module ClassMethods <ide> def memoize(symbol) <ide> original_method = "_unmemoized_#{symbol}" <add> memoized_ivar = "@_memoized_#{symbol}" <ide> raise "Already memoized #{symbol}" if instance_methods.map(&:to_s).include?(original_method) <ide> <ide> alias_method original_method, symbol <ide> class_eval <<-EOS, __FILE__, __LINE__ <ide> def #{symbol} <del> if defined? @#{symbol} <del> @#{symbol} <add> if defined? #{memoized_ivar} <add> #{memoized_ivar} <ide> else <del> @#{symbol} = #{original_method} <add> #{memoized_ivar} = #{original_method} <ide> end <ide> end <ide> EOS
1
Javascript
Javascript
launch mksnapshot.js using the current node
7770ae214c1e8e7febbbce4fb8b5ac67287e7652
<ide><path>script/lib/generate-startup-snapshot.js <ide> module.exports = function (packagedAppPath) { <ide> ) <ide> <ide> console.log('Generating startup blob with mksnapshot') <del> childProcess.execFileSync( <del> path.join(CONFIG.repositoryRootPath, 'script', 'node_modules', 'electron-mksnapshot', 'mksnapshot.js'), <del> [snapshotScriptPath, '--output_dir', CONFIG.buildOutputPath] <add> childProcess.spawnSync( <add> process.execPath, [ <add> path.join(CONFIG.repositoryRootPath, 'script', 'node_modules', 'electron-mksnapshot', 'mksnapshot.js'), <add> snapshotScriptPath, <add> '--output_dir', <add> CONFIG.buildOutputPath <add> ] <ide> ) <ide> <ide> let startupBlobDestinationPath
1
PHP
PHP
create a data_fill helper function
38d5f726bfb669962094acc54a25f9d83da8768a
<ide><path>src/Illuminate/Support/helpers.php <ide> function collect($value = null) <ide> } <ide> } <ide> <add>if (! function_exists('data_fill')) { <add> /** <add> * Fill in data where it's missing. <add> * <add> * @param mixed $target <add> * @param string|array $key <add> * @param mixed $value <add> * @return mixed <add> */ <add> function data_fill(&$target, $key, $value) <add> { <add> return data_set($target, $key, $value, false); <add> } <add>} <add> <ide> if (! function_exists('data_get')) { <ide> /** <ide> * Get an item from an array or object using "dot" notation. <ide><path>tests/Support/SupportHelpersTest.php <ide> public function testDataGetWithDoubleNestedArraysCollapsesResult() <ide> $this->assertEquals([], data_get($array, 'posts.*.users.*.name')); <ide> } <ide> <add> public function testDataFill() <add> { <add> $data = ['foo' => 'bar']; <add> <add> $this->assertEquals(['foo' => 'bar', 'baz' => 'boom'], data_fill($data, 'baz', 'boom')); <add> $this->assertEquals(['foo' => 'bar', 'baz' => 'boom'], data_fill($data, 'baz', 'noop')); <add> $this->assertEquals(['foo' => [], 'baz' => 'boom'], data_fill($data, 'foo.*', 'noop')); <add> $this->assertEquals( <add> ['foo' => ['bar' => 'kaboom'], 'baz' => 'boom'], <add> data_fill($data, 'foo.bar', 'kaboom') <add> ); <add> } <add> <add> public function testDataFillWithStar() <add> { <add> $data = ['foo' => 'bar']; <add> <add> $this->assertEquals( <add> ['foo' => []], <add> data_fill($data, 'foo.*.bar', 'noop') <add> ); <add> <add> $this->assertEquals( <add> ['foo' => [], 'bar' => [['baz' => 'original'], []]], <add> data_fill($data, 'bar', [['baz' => 'original'], []]) <add> ); <add> <add> $this->assertEquals( <add> ['foo' => [], 'bar' => [['baz' => 'original'], ['baz' => 'boom']]], <add> data_fill($data, 'bar.*.baz', 'boom') <add> ); <add> } <add> <add> public function testDataFillWithDoubleStar() <add> { <add> $data = [ <add> 'posts' => [ <add> (object) [ <add> 'comments' => [ <add> (object) ['name' => 'First'], <add> (object) [], <add> ], <add> ], <add> (object) [ <add> 'comments' => [ <add> (object) [], <add> (object) ['name' => 'Second'], <add> ], <add> ], <add> ], <add> ]; <add> <add> data_fill($data, 'posts.*.comments.*.name', 'Filled'); <add> <add> $this->assertEquals([ <add> 'posts' => [ <add> (object) [ <add> 'comments' => [ <add> (object) ['name' => 'First'], <add> (object) ['name' => 'Filled'], <add> ], <add> ], <add> (object) [ <add> 'comments' => [ <add> (object) ['name' => 'Filled'], <add> (object) ['name' => 'Second'], <add> ], <add> ], <add> ], <add> ], $data); <add> } <add> <ide> public function testDataSet() <ide> { <ide> $data = ['foo' => 'bar'];
2
Javascript
Javascript
improve idle benchmarks
aeb9bed63e3521088aef3b919ac5129a9822e83c
<ide><path>benchmark/idle_clients.js <ide> net = require('net'); <ide> <ide> var errors = 0, connections = 0; <ide> <add>var lastClose = 0; <add> <add>function maybeConnect (s) { <add> var now = new Date(); <add> if (now - lastClose > 5000) { <add> // Just connect immediately <add> connect(); <add> } else { <add> // Otherwise wait a little - see if this one is connected still. Just to <add> // avoid spinning at 100% cpu when the server totally rejects our <add> // connections. <add> setTimeout(function () { <add> if (s.writable && s.readable) connect(); <add> }, 100); <add> } <add>} <add> <ide> function connect () { <ide> process.nextTick(function () { <ide> var s = net.Stream(); <ide> var gotConnected = false; <ide> s.connect(9000); <add> <ide> s.on('connect', function () { <ide> gotConnected = true; <ide> connections++; <del> connect(); <add> maybeConnect(s); <ide> }); <ide> <del> var haderror = false; <del> <ide> s.on('close', function () { <ide> if (gotConnected) connections--; <del> //if (!haderror) connect(); <del> }); <del> <del> s.on('end', function () { <del> s.end(); <add> lastClose = new Date(); <ide> }); <ide> <ide> s.on('error', function () { <del> haderror = true; <ide> errors++; <ide> }); <ide> }); <ide><path>benchmark/idle_server.js <ide> var errors = 0; <ide> <ide> server = net.Server(function (socket) { <ide> <del> socket.on('end', function () { <del> socket.end(); <del> }); <del> <ide> socket.on('error', function () { <ide> errors++; <ide> });
2
PHP
PHP
add unit test
ef8603e1a7c8584914e39001b8926d1b263f0e80
<ide><path>lib/Cake/Test/Case/Model/ModelReadTest.php <ide> public function testNotInArrayWithOneValue() { <ide> $this->assertTrue(is_array($result) && !empty($result)); <ide> } <ide> <add>/** <add> * test to assert that != in key together with a single element array will work <add> * <add> * @return void <add> */ <add> public function testNotEqualsInArrayWithOneValue() { <add> $this->loadFixtures('Article'); <add> $Article = new Article(); <add> $Article->recursive = -1; <add> <add> $result = $Article->find( <add> 'all', <add> array( <add> 'conditions' => array( <add> 'Article.id !=' => array(1) <add> ) <add> ) <add> ); <add> $this->assertTrue(is_array($result) && !empty($result)); <add> } <add> <ide> /** <ide> * test custom find method <ide> *
1
Javascript
Javascript
ensure language redirects for chinese traditional
5cb3465a1dad9c5b7fad9c1683c322a04b5680be
<ide><path>client/src/components/createExternalRedirects.js <ide> import envData from '../../../config/env.json'; <ide> const { forumLocation } = envData; <ide> <ide> const createExternalRedirect = (page, { clientLocale }) => { <del> const isNotEnglish = clientLocale !== 'english'; <del> if (clientLocale === 'chinese') { <add> // Handle Chinese <add> if (clientLocale === 'chinese' || clientLocale === 'chinese-traditional') { <ide> return `https://chinese.freecodecamp.org/${page}`; <ide> } <add> <add> // Handle Others <add> const isNotEnglish = clientLocale !== 'english'; <ide> if (page === 'forum') { <ide> return `${forumLocation}/${isNotEnglish ? 'c/' + clientLocale + '/' : ''}`; <ide> } <ide><path>client/src/components/createExternalRedirects.test.js <ide> describe('createExternalRedirects', () => { <ide> clientLocale: 'english' <ide> }; <ide> <del> const englishForumUrl = 'https://forum.freecodecamp.org/'; <del> const englishNewsUrl = 'https://www.freecodecamp.org/news'; <add> const forumURL = 'https://forum.freecodecamp.org/'; <add> const newsURL = 'https://www.freecodecamp.org/news'; <ide> <ide> it('should generate correct forum link', () => { <ide> const receivedUrl = createExternalRedirect('forum', { ...envVars }); <del> expect(receivedUrl).toBe(englishForumUrl); <add> expect(receivedUrl).toBe(forumURL); <ide> }); <ide> <ide> it('should generate correct news link', () => { <ide> const receivedUrl = createExternalRedirect('news', { ...envVars }); <del> expect(receivedUrl).toBe(englishNewsUrl); <add> expect(receivedUrl).toBe(newsURL); <ide> }); <ide> }); <ide> <ide> describe('createExternalRedirects', () => { <ide> clientLocale: 'chinese' <ide> }; <ide> <del> const englishForumUrl = 'https://chinese.freecodecamp.org/forum'; <del> const englishNewsUrl = 'https://chinese.freecodecamp.org/news'; <add> const forumURL = 'https://chinese.freecodecamp.org/forum'; <add> const newsURL = 'https://chinese.freecodecamp.org/news'; <ide> <ide> it('should generate correct forum link', () => { <ide> const receivedUrl = createExternalRedirect('forum', { ...envVars }); <del> expect(receivedUrl).toBe(englishForumUrl); <add> expect(receivedUrl).toBe(forumURL); <ide> }); <ide> <ide> it('should generate correct news link', () => { <ide> const receivedUrl = createExternalRedirect('news', { ...envVars }); <del> expect(receivedUrl).toBe(englishNewsUrl); <add> expect(receivedUrl).toBe(newsURL); <ide> }); <ide> }); <ide> <ide> describe('createExternalRedirects', () => { <ide> clientLocale: 'espanol' <ide> }; <ide> <del> const englishForumUrl = 'https://forum.freecodecamp.org/c/espanol/'; <del> const englishNewsUrl = 'https://www.freecodecamp.org/espanol/news'; <add> const forumURL = 'https://forum.freecodecamp.org/c/espanol/'; <add> const newsURL = 'https://www.freecodecamp.org/espanol/news'; <ide> <ide> it('should generate correct forum link', () => { <ide> const receivedUrl = createExternalRedirect('forum', { ...envVars }); <del> expect(receivedUrl).toBe(englishForumUrl); <add> expect(receivedUrl).toBe(forumURL); <ide> }); <ide> <ide> it('should generate correct news link', () => { <ide> const receivedUrl = createExternalRedirect('news', { ...envVars }); <del> expect(receivedUrl).toBe(englishNewsUrl); <add> expect(receivedUrl).toBe(newsURL); <ide> }); <ide> }); <ide> <ide> describe('createExternalRedirects', () => { <ide> clientLocale: 'francais' <ide> }; <ide> <del> const englishForumUrl = 'https://forum.freecodecamp.org/c/francais/'; <del> const englishNewsUrl = 'https://www.freecodecamp.org/francais/news'; <add> const forumURL = 'https://forum.freecodecamp.org/c/francais/'; <add> const newsURL = 'https://www.freecodecamp.org/francais/news'; <ide> <ide> it('should generate correct forum link', () => { <ide> const receivedUrl = createExternalRedirect('forum', { ...envVars }); <del> expect(receivedUrl).toBe(englishForumUrl); <add> expect(receivedUrl).toBe(forumURL); <ide> }); <ide> <ide> it('should generate correct news link', () => { <ide> const receivedUrl = createExternalRedirect('news', { ...envVars }); <del> expect(receivedUrl).toBe(englishNewsUrl); <add> expect(receivedUrl).toBe(newsURL); <add> }); <add> }); <add> <add> describe('chinese-traditional redirects', () => { <add> const envVars = { <add> clientLocale: 'chinese-traditional' <add> }; <add> <add> const forumURL = 'https://chinese.freecodecamp.org/forum'; <add> const newsURL = 'https://chinese.freecodecamp.org/news'; <add> <add> it('should generate correct forum link', () => { <add> const receivedUrl = createExternalRedirect('forum', { ...envVars }); <add> expect(receivedUrl).toBe(forumURL); <add> }); <add> <add> it('should generate correct news link', () => { <add> const receivedUrl = createExternalRedirect('news', { ...envVars }); <add> expect(receivedUrl).toBe(newsURL); <ide> }); <ide> }); <ide> }); <ide><path>client/src/components/createLanguageRedirect.test.js <ide> describe('createLanguageRedirect for clientLocale === english', () => { <ide> 'https://chinese.freecodecamp.org/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <ide> const espanolPageURL = <ide> 'https://www.freecodecamp.org/espanol/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <del> const francaisPageURL = <del> 'https://www.freecodecamp.org/francais/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <add> const chineseTraditionalPageURL = <add> 'https://www.freecodecamp.org/chinese-traditional/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <add> const dothrakiPageURL = <add> 'https://www.freecodecamp.org/dothraki/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <ide> <ide> const originalLocation = window.location; <ide> <ide> describe('createLanguageRedirect for clientLocale === english', () => { <ide> expect(receivedPageURL).toBe(espanolPageURL); <ide> }); <ide> <del> it('should redirect to francais version of page', () => { <add> it('should redirect to chinese-traditional version of page', () => { <ide> const receivedPageURL = createLanguageRedirect({ <ide> ...envVars, <del> lang: 'francais' <add> lang: 'chinese-traditional' <ide> }); <del> expect(receivedPageURL).toBe(francaisPageURL); <add> expect(receivedPageURL).toBe(chineseTraditionalPageURL); <add> }); <add> <add> it('should redirect to dothraki version of page', () => { <add> const receivedPageURL = createLanguageRedirect({ <add> ...envVars, <add> lang: 'dothraki' <add> }); <add> expect(receivedPageURL).toBe(dothrakiPageURL); <ide> }); <ide> }); <ide> <ide> describe('settings page', () => { <ide> const currentPageURL = 'https://www.freecodecamp.org/settings'; <ide> const chinesePageURL = 'https://chinese.freecodecamp.org/settings'; <ide> const espanolPageURL = 'https://www.freecodecamp.org/espanol/settings'; <del> const francaisPageURL = 'https://www.freecodecamp.org/francais/settings'; <add> const chineseTraditionalPageURL = <add> 'https://www.freecodecamp.org/chinese-traditional/settings'; <add> const dothrakiPageURL = 'https://www.freecodecamp.org/dothraki/settings'; <ide> <ide> const originalLocation = window.location; <ide> <ide> describe('createLanguageRedirect for clientLocale === english', () => { <ide> expect(receivedPageURL).toBe(espanolPageURL); <ide> }); <ide> <del> it('should redirect to francais version of page', () => { <add> it('should redirect to chinese-traditional version of page', () => { <add> const receivedPageURL = createLanguageRedirect({ <add> ...envVars, <add> lang: 'chinese-traditional' <add> }); <add> expect(receivedPageURL).toBe(chineseTraditionalPageURL); <add> }); <add> <add> it('should redirect to dothraki version of page', () => { <ide> const receivedPageURL = createLanguageRedirect({ <ide> ...envVars, <del> lang: 'francais' <add> lang: 'dothraki' <ide> }); <del> expect(receivedPageURL).toBe(francaisPageURL); <add> expect(receivedPageURL).toBe(dothrakiPageURL); <ide> }); <ide> }); <ide> }); <ide> describe('createLanguageRedirect for clientLocale === chinese', () => { <ide> 'https://www.freecodecamp.org/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <ide> const espanolPageURL = <ide> 'https://www.freecodecamp.org/espanol/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <del> const francaisPageURL = <del> 'https://www.freecodecamp.org/francais/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <add> const chineseTraditionalPageURL = <add> 'https://www.freecodecamp.org/chinese-traditional/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <add> const dothrakiPageURL = <add> 'https://www.freecodecamp.org/dothraki/learn/responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element'; <ide> <ide> const originalLocation = window.location; <ide> <ide> describe('createLanguageRedirect for clientLocale === chinese', () => { <ide> expect(receivedPageURL).toBe(espanolPageURL); <ide> }); <ide> <del> it('should redirect to francais version of page', () => { <add> it('should redirect to chinese-traditional version of page', () => { <ide> const receivedPageURL = createLanguageRedirect({ <ide> ...envVars, <del> lang: 'francais' <add> lang: 'chinese-traditional' <ide> }); <del> expect(receivedPageURL).toBe(francaisPageURL); <add> expect(receivedPageURL).toBe(chineseTraditionalPageURL); <add> }); <add> <add> it('should redirect to dothraki version of page', () => { <add> const receivedPageURL = createLanguageRedirect({ <add> ...envVars, <add> lang: 'dothraki' <add> }); <add> expect(receivedPageURL).toBe(dothrakiPageURL); <ide> }); <ide> }); <ide> <ide> describe('settings page', () => { <ide> const currentPageURL = 'https://chinese.freecodecamp.org/settings'; <ide> const englishPageURL = 'https://www.freecodecamp.org/settings'; <ide> const espanolPageURL = 'https://www.freecodecamp.org/espanol/settings'; <del> const francaisPageURL = 'https://www.freecodecamp.org/francais/settings'; <add> const chineseTraditionalPageURL = <add> 'https://www.freecodecamp.org/chinese-traditional/settings'; <add> const dothrakiPageURL = 'https://www.freecodecamp.org/dothraki/settings'; <ide> <ide> const originalLocation = window.location; <ide> <ide> describe('createLanguageRedirect for clientLocale === chinese', () => { <ide> expect(receivedPageURL).toBe(espanolPageURL); <ide> }); <ide> <del> it('should redirect to francais version of page', () => { <add> it('should redirect to chinese-traditional version of page', () => { <add> const receivedPageURL = createLanguageRedirect({ <add> ...envVars, <add> lang: 'chinese-traditional' <add> }); <add> expect(receivedPageURL).toBe(chineseTraditionalPageURL); <add> }); <add> <add> it('should redirect to dothraki version of page', () => { <ide> const receivedPageURL = createLanguageRedirect({ <ide> ...envVars, <del> lang: 'francais' <add> lang: 'dothraki' <ide> }); <del> expect(receivedPageURL).toBe(francaisPageURL); <add> expect(receivedPageURL).toBe(dothrakiPageURL); <ide> }); <ide> }); <ide> });
3
Ruby
Ruby
remove uneeded methods
ec0973c2abeb80eb3c93c5df070592da56ef5b7c
<ide><path>actionpack/lib/action_controller/metal/http_authentication.rb <ide> def request_http_basic_authentication(realm = "Application") <ide> end <ide> <ide> def authenticate(request, &login_procedure) <del> unless authorization(request).blank? <add> unless request.authorization.blank? <ide> login_procedure.call(*user_name_and_password(request)) <ide> end <ide> end <ide> def user_name_and_password(request) <ide> decode_credentials(request).split(/:/, 2) <ide> end <ide> <del> def authorization(request) <del> request.env['HTTP_AUTHORIZATION'] || <del> request.env['X-HTTP_AUTHORIZATION'] || <del> request.env['X_HTTP_AUTHORIZATION'] || <del> request.env['REDIRECT_X_HTTP_AUTHORIZATION'] <del> end <del> <ide> def decode_credentials(request) <del> ActiveSupport::Base64.decode64(authorization(request).split(' ', 2).last || '') <add> ActiveSupport::Base64.decode64(request.authorization.split(' ', 2).last || '') <ide> end <ide> <ide> def encode_credentials(user_name, password) <ide> def request_http_digest_authentication(realm = "Application", message = nil) <ide> <ide> # Returns false on a valid response, true otherwise <ide> def authenticate(secret_key, request, realm, &password_procedure) <del> authorization(request) && validate_digest_response(secret_key, request, realm, &password_procedure) <del> end <del> <del> def authorization(request) <del> request.env['HTTP_AUTHORIZATION'] || <del> request.env['X-HTTP_AUTHORIZATION'] || <del> request.env['X_HTTP_AUTHORIZATION'] || <del> request.env['REDIRECT_X_HTTP_AUTHORIZATION'] <add> request.authorization && validate_digest_response(secret_key, request, realm, &password_procedure) <ide> end <ide> <ide> # Returns false unless the request credentials response value matches the expected value. <ide> def encode_credentials(http_method, credentials, password, password_is_ha1) <ide> end <ide> <ide> def decode_credentials_header(request) <del> decode_credentials(authorization(request)) <add> decode_credentials(request.authorization) <ide> end <ide> <ide> def decode_credentials(header) <ide><path>actionpack/lib/action_dispatch/http/mime_negotiation.rb <ide> def format=(extension) <ide> @env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])] <ide> end <ide> <del> # Returns a symbolized version of the <tt>:format</tt> parameter of the request. <del> # If no \format is given it returns <tt>:js</tt>for Ajax requests and <tt>:html</tt> <del> # otherwise. <del> def template_format <del> parameter_format = parameters[:format] <del> <del> if parameter_format <del> parameter_format <del> elsif xhr? <del> :js <del> else <del> :html <del> end <del> end <del> <ide> # Receives an array of mimes and return the first user sent mime that <ide> # matches the order array. <ide> #
2
Java
Java
avoid payload conversion if unnecessary
b88aad6b39f23bb0dd67b69be9a1104049eadf3c
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/converter/MappingJackson2MessageConverter.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @ <ide> return this.objectMapper.readValue((byte[]) payload, javaType); <ide> } <ide> } <add> else if (targetClass.isInstance(payload)) { <add> return payload; <add> } <ide> else { <ide> if (view != null) { <ide> return this.objectMapper.readerWithView(view).forType(javaType).readValue(payload.toString()); <ide><path>spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void fromMessageUntyped() { <ide> assertEquals("AQI=", actual.get("bytes")); <ide> } <ide> <add> @Test // gh-22386 <add> public void fromMessageMatchingInstance() { <add> MyBean myBean = new MyBean(); <add> MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); <add> Message<?> message = MessageBuilder.withPayload(myBean).build(); <add> assertSame(myBean, converter.fromMessage(message, MyBean.class)); <add> } <add> <ide> @Test(expected = MessageConversionException.class) <ide> public void fromMessageInvalidJson() { <ide> MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
2
Java
Java
implement removeclippedsubviews for nodes
5f162ca1192fa4ee275f07d3756d134317facfc9
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawView.java <ide> <ide> /* package */ final class DrawView extends AbstractClippingDrawCommand { <ide> <del> /* package */ static final DrawView INSTANCE = new DrawView(0, 0, 0, 0); <add> /* package */ final int reactTag; <add> /* package */ boolean isViewGroupClipped; <ide> <del> public DrawView(float clipLeft, float clipTop, float clipRight, float clipBottom) { <add> public DrawView(int reactTag, float clipLeft, float clipTop, float clipRight, float clipBottom) { <add> this.reactTag = reactTag; <ide> setClipBounds(clipLeft, clipTop, clipRight, clipBottom); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatShadowNode.java <ide> import com.facebook.react.uimanager.ReactStylesDiffMap; <ide> import com.facebook.react.uimanager.ViewProps; <ide> import com.facebook.react.uimanager.annotations.ReactProp; <add>import com.facebook.react.views.view.ReactClippingViewGroupHelper; <ide> <ide> /** <ide> * FlatShadowNode is a base class for all shadow node used in FlatUIImplementation. It extends <ide> private static final String PROP_IMPORTANT_FOR_ACCESSIBILITY = "importantForAccessibility"; <ide> private static final String PROP_TEST_ID = "testID"; <ide> private static final String PROP_TRANSFORM = "transform"; <add> private static final String PROP_REMOVE_CLIPPED_SUBVIEWS = <add> ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS; <ide> <ide> private DrawCommand[] mDrawCommands = DrawCommand.EMPTY_ARRAY; <ide> private AttachDetachListener[] mAttachDetachListeners = AttachDetachListener.EMPTY_ARRAY; <ide> styles.hasKey(PROP_ACCESSIBILITY_COMPONENT_TYPE) || <ide> styles.hasKey(PROP_ACCESSIBILITY_LIVE_REGION) || <ide> styles.hasKey(PROP_TRANSFORM) || <del> styles.hasKey(PROP_IMPORTANT_FOR_ACCESSIBILITY)) { <add> styles.hasKey(PROP_IMPORTANT_FOR_ACCESSIBILITY) || <add> styles.hasKey(PROP_REMOVE_CLIPPED_SUBVIEWS)) { <ide> forceMountToView(); <ide> } <ide> } <ide> protected final void setNodeRegion(NodeRegion nodeRegion) { <ide> } <ide> <ide> if (mDrawView == null) { <del> mDrawView = DrawView.INSTANCE; <add> mDrawView = new DrawView(getReactTag(), 0, 0, 0, 0); <ide> invalidate(); <ide> <ide> // reset NodeRegion to allow it getting garbage-collected <ide> protected final void setNodeRegion(NodeRegion nodeRegion) { <ide> <ide> /* package */ final DrawView collectDrawView(float left, float top, float right, float bottom) { <ide> if (!Assertions.assumeNotNull(mDrawView).clipBoundsMatch(left, top, right, bottom)) { <del> mDrawView = new DrawView(left, top, right, bottom); <add> mDrawView = new DrawView(getReactTag(), left, top, right, bottom); <ide> } <ide> <ide> return mDrawView; <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIViewOperationQueue.java <ide> <ide> import com.facebook.react.bridge.Callback; <ide> import com.facebook.react.bridge.ReactApplicationContext; <add>import com.facebook.react.uimanager.NoSuchNativeViewException; <ide> import com.facebook.react.uimanager.PixelUtil; <ide> import com.facebook.react.uimanager.UIViewOperationQueue; <ide> <ide> private MeasureVirtualView( <ide> <ide> @Override <ide> public void execute() { <del> // Measure native View <del> mNativeViewHierarchyManager.measure(mReactTag, MEASURE_BUFFER); <add> try { <add> // Measure native View <add> mNativeViewHierarchyManager.measure(mReactTag, MEASURE_BUFFER); <add> } catch (NoSuchNativeViewException noSuchNativeViewException) { <add> // Invoke with no args to signal failure and to allow JS to clean up the callback <add> // handle. <add> mCallback.invoke(); <add> return; <add> } <ide> <ide> float nativeViewX = MEASURE_BUFFER[0]; <ide> float nativeViewY = MEASURE_BUFFER[1]; <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatViewGroup.java <ide> <ide> import java.lang.ref.WeakReference; <ide> import java.util.ArrayList; <add>import java.util.HashMap; <add>import java.util.Map; <ide> <ide> import android.content.Context; <ide> import android.graphics.Canvas; <ide> import android.view.View; <ide> import android.view.ViewGroup; <ide> import android.view.ViewParent; <add>import android.view.animation.Animation; <ide> <add>import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.react.bridge.ReactContext; <ide> import com.facebook.react.bridge.SoftAssertions; <ide> import com.facebook.react.common.SystemClock; <ide> import com.facebook.react.uimanager.ReactPointerEventsView; <ide> import com.facebook.react.uimanager.UIManagerModule; <ide> import com.facebook.react.views.image.ImageLoadEvent; <add>import com.facebook.react.views.view.ReactClippingViewGroup; <add>import com.facebook.react.views.view.ReactClippingViewGroupHelper; <ide> <ide> /** <ide> * A view that FlatShadowNode hierarchy maps to. Performs drawing by iterating over <ide> * array of DrawCommands, executing them one by one. <ide> */ <ide> /* package */ final class FlatViewGroup extends ViewGroup <del> implements ReactInterceptingViewGroup, ReactCompoundViewGroup, ReactPointerEventsView { <add> implements ReactInterceptingViewGroup, ReactClippingViewGroup, <add> ReactCompoundViewGroup, ReactPointerEventsView { <ide> /** <ide> * Helper class that allows AttachDetachListener to invalidate the hosting View. <ide> */ <ide> public void dispatchImageLoadEvent(int reactTag, int imageLoadEvent) { <ide> private long mLastTouchDownTime; <ide> private @Nullable OnInterceptTouchEventListener mOnInterceptTouchEventListener; <ide> <add> private boolean mRemoveClippedSubviews; <add> private @Nullable Rect mClippingRect; <add> // lookups in o(1) instead of o(log n) - trade space for time <add> private final Map<Integer, DrawView> mDrawViewMap = new HashMap<>(); <add> private final Map<Integer, FlatViewGroup> mClippedSubviews = new HashMap<>(); <add> <ide> /* package */ FlatViewGroup(Context context) { <ide> super(context); <ide> setClipChildren(false); <ide> public boolean interceptsTouchEvent(float touchX, float touchY) { <ide> public void dispatchDraw(Canvas canvas) { <ide> super.dispatchDraw(canvas); <ide> <del> for (DrawCommand drawCommand : mDrawCommands) { <del> drawCommand.draw(this, canvas); <add> if (mRemoveClippedSubviews) { <add> for (DrawCommand drawCommand : mDrawCommands) { <add> if (drawCommand instanceof DrawView) { <add> if (!((DrawView) drawCommand).isViewGroupClipped) { <add> drawCommand.draw(this, canvas); <add> } <add> // else, don't draw, and don't increment index <add> } else { <add> drawCommand.draw(this, canvas); <add> } <add> } <add> } else { <add> for (DrawCommand drawCommand : mDrawCommands) { <add> drawCommand.draw(this, canvas); <add> } <ide> } <ide> <ide> if (mDrawChildIndex != getChildCount()) { <ide> protected void onAttachedToWindow() { <ide> <ide> super.onAttachedToWindow(); <ide> dispatchOnAttached(mAttachDetachListeners); <add> <add> if (mRemoveClippedSubviews) { <add> updateClippingRect(); <add> } <ide> } <ide> <ide> @Override <ide> protected void onSizeChanged(int w, int h, int oldw, int oldh) { <ide> mHotspot.setBounds(0, 0, w, h); <ide> invalidate(); <ide> } <add> <add> if (mRemoveClippedSubviews) { <add> updateClippingRect(); <add> } <ide> } <ide> <ide> @Override <ide> public PointerEvents getPointerEvents() { <ide> <ide> /* package */ void mountDrawCommands(DrawCommand[] drawCommands) { <ide> mDrawCommands = drawCommands; <add> if (mRemoveClippedSubviews) { <add> mDrawViewMap.clear(); <add> for (DrawCommand drawCommand : mDrawCommands) { <add> if (drawCommand instanceof DrawView) { <add> DrawView drawView = (DrawView) drawCommand; <add> mDrawViewMap.put(drawView.reactTag, drawView); <add> } <add> } <add> } <ide> invalidate(); <ide> } <ide> <ide> public PointerEvents getPointerEvents() { <ide> } else { <ide> View view = ensureViewHasNoParent(viewResolver.getView(-viewToAdd)); <ide> attachViewToParent(view, -1, ensureLayoutParams(view.getLayoutParams())); <add> if (mRemoveClippedSubviews) { <add> mClippedSubviews.remove(-viewToAdd); <add> DrawView drawView = mDrawViewMap.get(-viewToAdd); <add> if (drawView != null) { <add> drawView.isViewGroupClipped = false; <add> } <add> } <ide> } <ide> } <ide> <ide> for (int viewToDetach : viewsToDetach) { <del> removeDetachedView(viewResolver.getView(viewToDetach), false); <add> View view = viewResolver.getView(viewToDetach); <add> if (view.getParent() != null) { <add> removeViewInLayout(view); <add> } else { <add> removeDetachedView(view, false); <add> } <add> <add> if (mRemoveClippedSubviews) { <add> mClippedSubviews.remove(viewToDetach); <add> } <ide> } <ide> <ide> invalidate(); <ide> private ViewGroup.LayoutParams ensureLayoutParams(ViewGroup.LayoutParams lp) { <ide> } <ide> return generateDefaultLayoutParams(); <ide> } <add> <add> @Override <add> public void updateClippingRect() { <add> if (!mRemoveClippedSubviews) { <add> return; <add> } <add> <add> Assertions.assertNotNull(mClippingRect); <add> ReactClippingViewGroupHelper.calculateClippingRect(this, mClippingRect); <add> if (getParent() != null && mClippingRect.top != mClippingRect.bottom) { <add> updateClippingToRect(mClippingRect); <add> } <add> } <add> <add> private void updateClippingToRect(Rect clippingRect) { <add> int index = 0; <add> boolean needsInvalidate = false; <add> for (DrawCommand drawCommand : mDrawCommands) { <add> if (drawCommand instanceof DrawView) { <add> DrawView drawView = (DrawView) drawCommand; <add> FlatViewGroup flatViewGroup = mClippedSubviews.get(drawView.reactTag); <add> if (flatViewGroup != null) { <add> // invisible <add> if (clippingRect.intersects( <add> flatViewGroup.getLeft(), <add> flatViewGroup.getTop(), <add> flatViewGroup.getRight(), <add> flatViewGroup.getBottom())) { <add> // now on the screen <add> attachViewToParent( <add> flatViewGroup, <add> index++, <add> ensureLayoutParams(flatViewGroup.getLayoutParams())); <add> mClippedSubviews.remove(flatViewGroup.getId()); <add> drawView.isViewGroupClipped = false; <add> needsInvalidate = true; <add> } <add> } else { <add> // visible <add> View view = getChildAt(index++); <add> if (view instanceof FlatViewGroup) { <add> FlatViewGroup flatChildView = (FlatViewGroup) view; <add> Animation animation = flatChildView.getAnimation(); <add> boolean isAnimating = animation != null && !animation.hasEnded(); <add> if (!isAnimating && <add> !clippingRect.intersects( <add> view.getLeft(), <add> view.getTop(), <add> view.getRight(), <add> view.getBottom())) { <add> // now off the screen <add> mClippedSubviews.put(view.getId(), flatChildView); <add> detachViewFromParent(view); <add> drawView.isViewGroupClipped = true; <add> index--; <add> needsInvalidate = true; <add> } <add> } <add> } <add> } <add> } <add> <add> if (needsInvalidate) { <add> invalidate(); <add> } <add> } <add> <add> @Override <add> public void getClippingRect(Rect outClippingRect) { <add> outClippingRect.set(mClippingRect); <add> } <add> <add> @Override <add> public void setRemoveClippedSubviews(boolean removeClippedSubviews) { <add> if (removeClippedSubviews == mRemoveClippedSubviews) { <add> return; <add> } <add> mRemoveClippedSubviews = removeClippedSubviews; <add> if (removeClippedSubviews) { <add> mClippingRect = new Rect(); <add> updateClippingRect(); <add> } else { <add> // Add all clipped views back, deallocate additional arrays, remove layoutChangeListener <add> Assertions.assertNotNull(mClippingRect); <add> getDrawingRect(mClippingRect); <add> updateClippingToRect(mClippingRect); <add> mClippingRect = null; <add> } <add> } <add> <add> @Override <add> public boolean getRemoveClippedSubviews() { <add> return mRemoveClippedSubviews; <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTViewManager.java <ide> import com.facebook.react.common.MapBuilder; <ide> import com.facebook.react.uimanager.PixelUtil; <ide> import com.facebook.react.uimanager.PointerEvents; <del>import com.facebook.react.uimanager.annotations.ReactProp; <ide> import com.facebook.react.uimanager.ViewProps; <add>import com.facebook.react.uimanager.annotations.ReactProp; <add>import com.facebook.react.views.view.ReactClippingViewGroupHelper; <ide> import com.facebook.react.views.view.ReactDrawableHelper; <ide> <ide> /** <ide> public void setPointerEvents(FlatViewGroup view, @Nullable String pointerEventsS <ide> view.setPointerEvents(parsePointerEvents(pointerEventsStr)); <ide> } <ide> <add> @ReactProp(name = ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS) <add> public void setRemoveClippedSubviews(FlatViewGroup view, boolean removeClippedSubviews) { <add> view.setRemoveClippedSubviews(removeClippedSubviews); <add> } <add> <ide> private static PointerEvents parsePointerEvents(@Nullable String pointerEventsStr) { <ide> if (pointerEventsStr != null) { <ide> switch (pointerEventsStr) {
5
Javascript
Javascript
detect ipados as is_ipad
a11f3fa574048b4f73aa0c6586990c1945aa928c
<ide><path>src/js/utils/browser.js <ide> const USER_AGENT = window.navigator && window.navigator.userAgent || ''; <ide> const webkitVersionMap = (/AppleWebKit\/([\d.]+)/i).exec(USER_AGENT); <ide> const appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null; <ide> <del>/** <del> * Whether or not this device is an iPad. <del> * <del> * @static <del> * @const <del> * @type {Boolean} <del> */ <del>export const IS_IPAD = (/iPad/i).test(USER_AGENT); <del> <del>/** <del> * Whether or not this device is an iPhone. <del> * <del> * @static <del> * @const <del> * @type {Boolean} <del> */ <del>// The Facebook app's UIWebView identifies as both an iPhone and iPad, so <del>// to identify iPhones, we need to exclude iPads. <del>// http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/ <del>export const IS_IPHONE = (/iPhone/i).test(USER_AGENT) && !IS_IPAD; <del> <ide> /** <ide> * Whether or not this device is an iPod. <ide> * <ide> export const IS_IPHONE = (/iPhone/i).test(USER_AGENT) && !IS_IPAD; <ide> */ <ide> export const IS_IPOD = (/iPod/i).test(USER_AGENT); <ide> <del>/** <del> * Whether or not this is an iOS device. <del> * <del> * @static <del> * @const <del> * @type {Boolean} <del> */ <del>export const IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; <del> <ide> /** <ide> * The detected iOS version - or `null`. <ide> * <ide> export const IE_VERSION = (function() { <ide> */ <ide> export const IS_SAFARI = (/Safari/i).test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE; <ide> <del>/** <del> * Whether or not this is any flavor of Safari - including iOS. <del> * <del> * @static <del> * @const <del> * @type {Boolean} <del> */ <del>export const IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME; <del> <ide> /** <ide> * Whether or not this is a Windows machine. <ide> * <ide> export const TOUCH_ENABLED = Dom.isReal() && ( <ide> 'ontouchstart' in window || <ide> window.navigator.maxTouchPoints || <ide> window.DocumentTouch && window.document instanceof window.DocumentTouch); <add> <add>/** <add> * Whether or not this device is an iPad. <add> * <add> * @static <add> * @const <add> * @type {Boolean} <add> */ <add>export const IS_IPAD = (/iPad/i).test(USER_AGENT) || (IS_SAFARI && TOUCH_ENABLED); <add> <add>/** <add> * Whether or not this device is an iPhone. <add> * <add> * @static <add> * @const <add> * @type {Boolean} <add> */ <add>// The Facebook app's UIWebView identifies as both an iPhone and iPad, so <add>// to identify iPhones, we need to exclude iPads. <add>// http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/ <add>export const IS_IPHONE = (/iPhone/i).test(USER_AGENT) && !IS_IPAD; <add> <add>/** <add> * Whether or not this is an iOS device. <add> * <add> * @static <add> * @const <add> * @type {Boolean} <add> */ <add>export const IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; <add> <add>/** <add> * Whether or not this is any flavor of Safari - including iOS. <add> * <add> * @static <add> * @const <add> * @type {Boolean} <add> */ <add>export const IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
1
Python
Python
check array dimensionality in cov function
fa107fe361520ceac09131f96a8715473078801e
<ide><path>numpy/lib/function_base.py <ide> def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, <ide> <ide> # Handles complex arrays too <ide> m = np.asarray(m) <add> if m.ndim > 2: <add> raise ValueError("m has more than 2 dimensions") <add> <ide> if y is None: <ide> dtype = np.result_type(m, np.float64) <ide> else: <ide> y = np.asarray(y) <add> if y.ndim > 2: <add> raise ValueError("y has more than 2 dimensions") <ide> dtype = np.result_type(m, y, np.float64) <add> <ide> X = array(m, ndmin=2, dtype=dtype) <ide> if rowvar == 0 and X.shape[0] != 1: <ide> X = X.T
1
PHP
PHP
create tests for some asserts methods
58da15941e019e9d9742358e22cc7f68eb7146b0
<ide><path>tests/Foundation/FoundationTestResponseTest.php <ide> public function testAssertSeeTextInOrderCanFail2() <ide> $response->assertSeeTextInOrder(['foobar', 'qux', 'baz']); <ide> } <ide> <add> public function testAssertOk() <add> { <add> $statusCode = 500; <add> <add> $this->expectException(AssertionFailedError::class); <add> <add> $this->expectExceptionMessage('Response status code ['.$statusCode.'] does not match expected 200 status code.'); <add> <add> $baseResponse = tap(new Response, function ($response) use ($statusCode) { <add> $response->setStatusCode($statusCode); <add> }); <add> <add> $response = TestResponse::fromBaseResponse($baseResponse); <add> $response->assertOk(); <add> } <add> <ide> public function testAssertNotFound() <ide> { <ide> $statusCode = 500; <ide> public function testAssertNotFound() <ide> $response->assertNotFound(); <ide> } <ide> <add> public function testAssertForbidden() <add> { <add> $statusCode = 500; <add> <add> $this->expectException(AssertionFailedError::class); <add> <add> $this->expectExceptionMessage('Response status code ['.$statusCode.'] is not a forbidden status code.'); <add> <add> $baseResponse = tap(new Response, function ($response) use ($statusCode) { <add> $response->setStatusCode($statusCode); <add> }); <add> <add> $response = TestResponse::fromBaseResponse($baseResponse); <add> $response->assertForbidden(); <add> } <add> <add> public function testAssertUnauthorized() <add> { <add> $statusCode = 500; <add> <add> $this->expectException(AssertionFailedError::class); <add> <add> $this->expectExceptionMessage('Response status code ['.$statusCode.'] is not an unauthorized status code.'); <add> <add> $baseResponse = tap(new Response, function ($response) use ($statusCode) { <add> $response->setStatusCode($statusCode); <add> }); <add> <add> $response = TestResponse::fromBaseResponse($baseResponse); <add> $response->assertUnauthorized(); <add> } <add> <add> public function testAssertStatus() <add> { <add> $statusCode = 500; <add> $expectedStatusCode = 401; <add> <add> $this->expectException(AssertionFailedError::class); <add> <add> $this->expectExceptionMessage("Expected status code {$expectedStatusCode} but received {$statusCode}"); <add> <add> $baseResponse = tap(new Response, function ($response) use ($statusCode) { <add> $response->setStatusCode($statusCode); <add> }); <add> <add> $response = TestResponse::fromBaseResponse($baseResponse); <add> $response->assertStatus($expectedStatusCode); <add> } <add> <ide> public function testAssertHeader() <ide> { <ide> $this->expectException(AssertionFailedError::class);
1
PHP
PHP
update doc blocks for logging + scopes
a59db11e4eaa02d8e9fdbdd9aa30dbce7297b397
<ide><path>lib/Cake/Log/CakeLog.php <ide> * application. By using scopes you can control logging for each part <ide> * of your application and still keep standard log levels. <ide> * <add> * <ide> * See CakeLog::config() and CakeLog::write() for more information <ide> * on scopes <ide> * <ide> protected static function _init() { <ide> * <ide> * The above logger will only capture log entries made in the <ide> * `payment` and `order` scopes. All other scopes including the <del> * undefined scope will be ignored. <add> * undefined scope will be ignored. Its important to remember that <add> * when using scopes you must also define the `types` of log messages <add> * that a logger will handle. Failing to do so will result in the logger <add> * catching all log messages even if the scope is incorrect. <ide> * <ide> * @param string $key The keyname for this logger, used to remove the <ide> * logger later.
1
Ruby
Ruby
fix code example in generator test case
cf03daa5f509e48cf03897163471f3064cf2f5eb
<ide><path>railties/lib/rails/generators/test_case.rb <ide> def assert_migration(relative, *contents, &block) <ide> # Asserts a given migration does not exist. You need to supply an absolute path or a <ide> # path relative to the configured destination: <ide> # <del> # assert_no_file "config/random.rb" <add> # assert_no_migration "db/migrate/create_products.rb" <ide> # <ide> def assert_no_migration(relative) <ide> file_name = migration_file_name(relative) <ide> def assert_field_type(attribute_type, field_type) <ide> <ide> # Asserts the given attribute type gets a proper default value: <ide> # <del> # assert_field_type :string, "MyString" <add> # assert_field_default_value :string, "MyString" <ide> # <ide> def assert_field_default_value(attribute_type, value) <ide> assert_equal(value, create_generated_attribute(attribute_type).default)
1
Javascript
Javascript
improve pmrem handling of background color
8e3d91ff52f163b56f0931c1915e8d0429e31ff7
<ide><path>src/extras/PMREMGenerator.js <ide> const ENCODINGS = { <ide> const _flatCamera = /*@__PURE__*/ new OrthographicCamera(); <ide> const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes(); <ide> const _clearColor = /*@__PURE__*/ new Color(); <add>const _backgroundColor = /*@__PURE__*/ new Color(); <ide> let _oldTarget = null; <ide> <ide> // Golden Ratio <ide> class PMREMGenerator { <ide> const toneMapping = renderer.toneMapping; <ide> renderer.getClearColor( _clearColor ); <ide> const clearAlpha = renderer.getClearAlpha(); <add> const originalBackground = scene.background; <ide> <ide> renderer.toneMapping = NoToneMapping; <ide> renderer.outputEncoding = LinearEncoding; <ide> <del> let background = scene.background; <add> const background = scene.background; <ide> if ( background && background.isColor ) { <ide> <del> background.convertSRGBToLinear(); <del> // Convert linear to RGBE <del> const maxComponent = Math.max( background.r, background.g, background.b ); <del> const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 ); <del> background = background.multiplyScalar( Math.pow( 2.0, - fExp ) ); <del> const alpha = ( fExp + 128.0 ) / 255.0; <del> renderer.setClearColor( background, alpha ); <del> scene.background = null; <add> _backgroundColor.copy( background ); <add> <add> } else { <add> <add> _backgroundColor.copy( _clearColor ); <ide> <ide> } <ide> <add> <add> _backgroundColor.convertSRGBToLinear(); <add> <add> // Convert linear to RGBE <add> const maxComponent = Math.max( _backgroundColor.r, _backgroundColor.g, _backgroundColor.b ); <add> const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 ); <add> _backgroundColor.multiplyScalar( Math.pow( 2.0, - fExp ) ); <add> const alpha = ( fExp + 128.0 ) / 255.0; <add> renderer.setClearColor( _backgroundColor, alpha ); <add> scene.background = null; <add> <add> <ide> for ( let i = 0; i < 6; i ++ ) { <ide> <ide> const col = i % 3; <ide> class PMREMGenerator { <ide> renderer.toneMapping = toneMapping; <ide> renderer.outputEncoding = outputEncoding; <ide> renderer.setClearColor( _clearColor, clearAlpha ); <add> scene.background = originalBackground; <ide> <ide> } <ide>
1
Text
Text
add link to blog post
efdb46b6e2a53f9126d447260f916cac33de58c3
<ide><path>notebooks/README.md <ide> Pull Request and we'll review it so it can be included here. <ide> | [Getting Started Transformers](02-transformers.ipynb) | How to easily start using transformers | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/transformers/blob/master/notebooks/02-transformers.ipynb) | <ide> | [How to use Pipelines](03-pipelines.ipynb) | Simple and efficient way to use State-of-the-Art models on downstream tasks through transformers | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/transformers/blob/master/notebooks/03-pipelines.ipynb) | <ide> | [How to train a language model](https://github.com/huggingface/blog/blob/master/notebooks/01_how_to_train.ipynb)| Highlight all the steps to effectively train Transformer model on custom data | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/01_how_to_train.ipynb)| <add>| [How to generate text](https://github.com/huggingface/blog/blob/master/notebooks/01_how_to_train.ipynb)| How to use different decoding methods for language generation with transformers | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/blog/blob/master/notebooks/02_how_to_generate.ipynb)|
1
Text
Text
crypto esm examples
bfa6e37204f1343c8a340f44c923858833da55b8
<ide><path>doc/api/crypto.md <ide> The `crypto` module provides cryptographic functionality that includes a set of <ide> wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. <ide> <del>Use `require('crypto')` to access this module. <add>```mjs <add>import { createHmac } from 'crypto'; <ide> <del>```js <add>const secret = 'abcdefg'; <add>const hash = createHmac('sha256', secret) <add> .update('I love cupcakes') <add> .digest('hex'); <add>console.log(hash); <add>// Prints: <add>// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e <add>``` <add> <add>```cjs <ide> const crypto = require('crypto'); <ide> <ide> const secret = 'abcdefg'; <ide> console.log(hash); <ide> ## Determining if crypto support is unavailable <ide> <ide> It is possible for Node.js to be built without including support for the <del>`crypto` module. In such cases, calling `require('crypto')` will result in an <del>error being thrown. <add>`crypto` module. In such cases, attempting to `import` from `crypto` or <add>calling `require('crypto')` will result in an error being thrown. <ide> <del>```js <add>When using CommonJS, the error thrown can be caught using try/catch: <add> <add>```cjs <ide> let crypto; <ide> try { <ide> crypto = require('crypto'); <ide> try { <ide> } <ide> ``` <ide> <add>When using the lexical ESM `import` keyword, the error can only be <add>caught if a handler for `process.on('uncaughtException')` is registered <add>*before* any attempt to load the module is made -- using, for instance, <add>a preload module. <add> <add>When using ESM, if there is a chance that the code may be run on a build <add>of Node.js where crypto support is not enabled, consider using the <add>`import()` function instead of the lexical `import` keyword: <add> <add>```mjs <add>let crypto; <add>try { <add> crypto = await import('crypto'); <add>} catch (err) { <add> console.log('crypto support is disabled!'); <add>} <add>``` <add> <ide> ## Class: `Certificate` <ide> <!-- YAML <ide> added: v0.11.8 <ide> changes: <ide> * Returns: {Buffer} The challenge component of the `spkac` data structure, which <ide> includes a public key and a challenge. <ide> <del>```js <add>```mjs <add>const { Certificate } = await import('crypto'); <add>const spkac = getSpkacSomehow(); <add>const challenge = Certificate.exportChallenge(spkac); <add>console.log(challenge.toString('utf8')); <add>// Prints: the challenge as a UTF8 string <add>``` <add> <add>```cjs <ide> const { Certificate } = require('crypto'); <ide> const spkac = getSpkacSomehow(); <ide> const challenge = Certificate.exportChallenge(spkac); <ide> changes: <ide> * Returns: {Buffer} The public key component of the `spkac` data structure, <ide> which includes a public key and a challenge. <ide> <del>```js <add>```mjs <add>const { Certificate } = await import('crypto'); <add>const spkac = getSpkacSomehow(); <add>const publicKey = Certificate.exportPublicKey(spkac); <add>console.log(publicKey); <add>// Prints: the public key as <Buffer ...> <add>``` <add> <add>```cjs <ide> const { Certificate } = require('crypto'); <ide> const spkac = getSpkacSomehow(); <ide> const publicKey = Certificate.exportPublicKey(spkac); <ide> changes: <ide> * Returns: {boolean} `true` if the given `spkac` data structure is valid, <ide> `false` otherwise. <ide> <del>```js <add>```mjs <add>const { Certificate } = await import('crypto'); <add>const spkac = getSpkacSomehow(); <add>console.log(Certificate.verifySpkac(Buffer.from(spkac))); <add>// Prints: true or false <add>``` <add> <add>```cjs <ide> const { Certificate } = require('crypto'); <ide> const spkac = getSpkacSomehow(); <ide> console.log(Certificate.verifySpkac(Buffer.from(spkac))); <ide> the `crypto.Certificate` class as illustrated in the examples below. <ide> Instances of the `Certificate` class can be created using the `new` keyword <ide> or by calling `crypto.Certificate()` as a function: <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { Certificate } = await import('crypto'); <add> <add>const cert1 = new Certificate(); <add>const cert2 = Certificate(); <add>``` <ide> <del>const cert1 = new crypto.Certificate(); <del>const cert2 = crypto.Certificate(); <add>```cjs <add>const { Certificate } = require('crypto'); <add> <add>const cert1 = new Certificate(); <add>const cert2 = Certificate(); <ide> ``` <ide> <ide> #### `certificate.exportChallenge(spkac[, encoding])` <ide> added: v0.11.8 <ide> * Returns: {Buffer} The challenge component of the `spkac` data structure, which <ide> includes a public key and a challenge. <ide> <del>```js <del>const cert = require('crypto').Certificate(); <add>```mjs <add>const { Certificate } = await import('crypto'); <add>const cert = Certificate(); <add>const spkac = getSpkacSomehow(); <add>const challenge = cert.exportChallenge(spkac); <add>console.log(challenge.toString('utf8')); <add>// Prints: the challenge as a UTF8 string <add>``` <add> <add>```cjs <add>const { Certificate } = require('crypto'); <add>const cert = Certificate(); <ide> const spkac = getSpkacSomehow(); <ide> const challenge = cert.exportChallenge(spkac); <ide> console.log(challenge.toString('utf8')); <ide> added: v0.11.8 <ide> * Returns: {Buffer} The public key component of the `spkac` data structure, <ide> which includes a public key and a challenge. <ide> <del>```js <del>const cert = require('crypto').Certificate(); <add>```mjs <add>const { Certificate } = await import('crypto'); <add>const cert = Certificate(); <add>const spkac = getSpkacSomehow(); <add>const publicKey = cert.exportPublicKey(spkac); <add>console.log(publicKey); <add>// Prints: the public key as <Buffer ...> <add>``` <add> <add>```cjs <add>const { Certificate } = require('crypto'); <add>const cert = Certificate(); <ide> const spkac = getSpkacSomehow(); <ide> const publicKey = cert.exportPublicKey(spkac); <ide> console.log(publicKey); <ide> added: v0.11.8 <ide> * Returns: {boolean} `true` if the given `spkac` data structure is valid, <ide> `false` otherwise. <ide> <del>```js <del>const cert = require('crypto').Certificate(); <add>```mjs <add>const { Certificate } = await import('crypto'); <add>const cert = Certificate(); <add>const spkac = getSpkacSomehow(); <add>console.log(cert.verifySpkac(Buffer.from(spkac))); <add>// Prints: true or false <add>``` <add> <add>```cjs <add>const { Certificate } = require('crypto'); <add>const cert = Certificate(); <ide> const spkac = getSpkacSomehow(); <ide> console.log(cert.verifySpkac(Buffer.from(spkac))); <ide> // Prints: true or false <ide> directly using the `new` keyword. <ide> <ide> Example: Using `Cipher` objects as streams: <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { <add> scrypt, <add> randomFill, <add> createCipheriv <add>} = await import('crypto'); <ide> <ide> const algorithm = 'aes-192-cbc'; <ide> const password = 'Password used to generate key'; <ide> <ide> // First, we'll generate the key. The key length is dependent on the algorithm. <ide> // In this case for aes192, it is 24 bytes (192 bits). <del>crypto.scrypt(password, 'salt', 24, (err, key) => { <add>scrypt(password, 'salt', 24, (err, key) => { <ide> if (err) throw err; <ide> // Then, we'll generate a random initialization vector <del> crypto.randomFill(new Uint8Array(16), (err, iv) => { <add> randomFill(new Uint8Array(16), (err, iv) => { <ide> if (err) throw err; <ide> <ide> // Once we have the key and iv, we can create and use the cipher... <del> const cipher = crypto.createCipheriv(algorithm, key, iv); <add> const cipher = createCipheriv(algorithm, key, iv); <add> <add> let encrypted = ''; <add> cipher.setEncoding('hex'); <add> <add> cipher.on('data', (chunk) => encrypted += chunk); <add> cipher.on('end', () => console.log(encrypted)); <add> <add> cipher.write('some clear text data'); <add> cipher.end(); <add> }); <add>}); <add>``` <add> <add>```cjs <add>const { <add> scrypt, <add> randomFill, <add> createCipheriv <add>} = require('crypto'); <add> <add>const algorithm = 'aes-192-cbc'; <add>const password = 'Password used to generate key'; <add> <add>// First, we'll generate the key. The key length is dependent on the algorithm. <add>// In this case for aes192, it is 24 bytes (192 bits). <add>scrypt(password, 'salt', 24, (err, key) => { <add> if (err) throw err; <add> // Then, we'll generate a random initialization vector <add> randomFill(new Uint8Array(16), (err, iv) => { <add> if (err) throw err; <add> <add> // Once we have the key and iv, we can create and use the cipher... <add> const cipher = createCipheriv(algorithm, key, iv); <ide> <ide> let encrypted = ''; <ide> cipher.setEncoding('hex'); <ide> crypto.scrypt(password, 'salt', 24, (err, key) => { <ide> <ide> Example: Using `Cipher` and piped streams: <ide> <del>```js <del>const crypto = require('crypto'); <del>const fs = require('fs'); <del>const { pipeline } = require('stream'); <add>```mjs <add>import { <add> createReadStream, <add> createWriteStream, <add>} from 'fs'; <add> <add>import { <add> pipeline <add>} from 'stream'; <add> <add>const { <add> scrypt, <add> randomFill, <add> createCipheriv, <add>} = await import('crypto'); <ide> <ide> const algorithm = 'aes-192-cbc'; <ide> const password = 'Password used to generate key'; <ide> <ide> // First, we'll generate the key. The key length is dependent on the algorithm. <ide> // In this case for aes192, it is 24 bytes (192 bits). <del>crypto.scrypt(password, 'salt', 24, (err, key) => { <add>scrypt(password, 'salt', 24, (err, key) => { <ide> if (err) throw err; <ide> // Then, we'll generate a random initialization vector <del> crypto.randomFill(new Uint8Array(16), (err, iv) => { <add> randomFill(new Uint8Array(16), (err, iv) => { <ide> if (err) throw err; <ide> <del> const cipher = crypto.createCipheriv(algorithm, key, iv); <add> const cipher = createCipheriv(algorithm, key, iv); <ide> <del> const input = fs.createReadStream('test.js'); <del> const output = fs.createWriteStream('test.enc'); <add> const input = createReadStream('test.js'); <add> const output = createWriteStream('test.enc'); <add> <add> pipeline(input, cipher, output, (err) => { <add> if (err) throw err; <add> }); <add> }); <add>}); <add>``` <add> <add>```cjs <add>const { <add> createReadStream, <add> createWriteStream, <add>} = require('fs'); <add> <add>const { <add> pipeline <add>} = require('stream'); <add> <add>const { <add> scrypt, <add> randomFill, <add> createCipheriv, <add>} = require('crypto'); <add> <add>const algorithm = 'aes-192-cbc'; <add>const password = 'Password used to generate key'; <add> <add>// First, we'll generate the key. The key length is dependent on the algorithm. <add>// In this case for aes192, it is 24 bytes (192 bits). <add>scrypt(password, 'salt', 24, (err, key) => { <add> if (err) throw err; <add> // Then, we'll generate a random initialization vector <add> randomFill(new Uint8Array(16), (err, iv) => { <add> if (err) throw err; <add> <add> const cipher = createCipheriv(algorithm, key, iv); <add> <add> const input = createReadStream('test.js'); <add> const output = createWriteStream('test.enc'); <ide> <ide> pipeline(input, cipher, output, (err) => { <ide> if (err) throw err; <ide> crypto.scrypt(password, 'salt', 24, (err, key) => { <ide> <ide> Example: Using the [`cipher.update()`][] and [`cipher.final()`][] methods: <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { <add> scrypt, <add> randomFill, <add> createCipheriv, <add>} = await import('crypto'); <add> <add>const algorithm = 'aes-192-cbc'; <add>const password = 'Password used to generate key'; <add> <add>// First, we'll generate the key. The key length is dependent on the algorithm. <add>// In this case for aes192, it is 24 bytes (192 bits). <add>scrypt(password, 'salt', 24, (err, key) => { <add> if (err) throw err; <add> // Then, we'll generate a random initialization vector <add> randomFill(new Uint8Array(16), (err, iv) => { <add> if (err) throw err; <add> <add> const cipher = createCipheriv(algorithm, key, iv); <add> <add> let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); <add> encrypted += cipher.final('hex'); <add> console.log(encrypted); <add> }); <add>}); <add>``` <add> <add>```cjs <add>const { <add> scrypt, <add> randomFill, <add> createCipheriv, <add>} = require('crypto'); <ide> <ide> const algorithm = 'aes-192-cbc'; <ide> const password = 'Password used to generate key'; <ide> <ide> // First, we'll generate the key. The key length is dependent on the algorithm. <ide> // In this case for aes192, it is 24 bytes (192 bits). <del>crypto.scrypt(password, 'salt', 24, (err, key) => { <add>scrypt(password, 'salt', 24, (err, key) => { <ide> if (err) throw err; <ide> // Then, we'll generate a random initialization vector <del> crypto.randomFill(new Uint8Array(16), (err, iv) => { <add> randomFill(new Uint8Array(16), (err, iv) => { <ide> if (err) throw err; <ide> <del> const cipher = crypto.createCipheriv(algorithm, key, iv); <add> const cipher = createCipheriv(algorithm, key, iv); <ide> <ide> let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); <ide> encrypted += cipher.final('hex'); <ide> directly using the `new` keyword. <ide> <ide> Example: Using `Decipher` objects as streams: <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { <add> scryptSync, <add> createDecipheriv, <add>} = await import('crypto'); <ide> <ide> const algorithm = 'aes-192-cbc'; <ide> const password = 'Password used to generate key'; <ide> // Key length is dependent on the algorithm. In this case for aes192, it is <ide> // 24 bytes (192 bits). <ide> // Use the async `crypto.scrypt()` instead. <del>const key = crypto.scryptSync(password, 'salt', 24); <add>const key = scryptSync(password, 'salt', 24); <ide> // The IV is usually passed along with the ciphertext. <ide> const iv = Buffer.alloc(16, 0); // Initialization vector. <ide> <del>const decipher = crypto.createDecipheriv(algorithm, key, iv); <add>const decipher = createDecipheriv(algorithm, key, iv); <add> <add>let decrypted = ''; <add>decipher.on('readable', () => { <add> while (null !== (chunk = decipher.read())) { <add> decrypted += chunk.toString('utf8'); <add> } <add>}); <add>decipher.on('end', () => { <add> console.log(decrypted); <add> // Prints: some clear text data <add>}); <add> <add>// Encrypted with same algorithm, key and iv. <add>const encrypted = <add> 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; <add>decipher.write(encrypted, 'hex'); <add>decipher.end(); <add>``` <add> <add>```cjs <add>const { <add> scryptSync, <add> createDecipheriv, <add>} = require('crypto'); <add> <add>const algorithm = 'aes-192-cbc'; <add>const password = 'Password used to generate key'; <add>// Key length is dependent on the algorithm. In this case for aes192, it is <add>// 24 bytes (192 bits). <add>// Use the async `crypto.scrypt()` instead. <add>const key = scryptSync(password, 'salt', 24); <add>// The IV is usually passed along with the ciphertext. <add>const iv = Buffer.alloc(16, 0); // Initialization vector. <add> <add>const decipher = createDecipheriv(algorithm, key, iv); <ide> <ide> let decrypted = ''; <ide> decipher.on('readable', () => { <ide> decipher.end(); <ide> <ide> Example: Using `Decipher` and piped streams: <ide> <del>```js <del>const crypto = require('crypto'); <del>const fs = require('fs'); <add>```mjs <add>import { <add> createReadStream, <add> createWriteStream, <add>} from 'fs'; <add> <add>const { <add> scryptSync, <add> createDecipheriv, <add>} = await import('crypto'); <ide> <ide> const algorithm = 'aes-192-cbc'; <ide> const password = 'Password used to generate key'; <ide> // Use the async `crypto.scrypt()` instead. <del>const key = crypto.scryptSync(password, 'salt', 24); <add>const key = scryptSync(password, 'salt', 24); <ide> // The IV is usually passed along with the ciphertext. <ide> const iv = Buffer.alloc(16, 0); // Initialization vector. <ide> <del>const decipher = crypto.createDecipheriv(algorithm, key, iv); <add>const decipher = createDecipheriv(algorithm, key, iv); <ide> <del>const input = fs.createReadStream('test.enc'); <del>const output = fs.createWriteStream('test.js'); <add>const input = createReadStream('test.enc'); <add>const output = createWriteStream('test.js'); <add> <add>input.pipe(decipher).pipe(output); <add>``` <add> <add>```cjs <add>const { <add> createReadStream, <add> createWriteStream, <add>} = require('fs'); <add> <add>const { <add> scryptSync, <add> createDecipheriv, <add>} = require('crypto'); <add> <add>const algorithm = 'aes-192-cbc'; <add>const password = 'Password used to generate key'; <add>// Use the async `crypto.scrypt()` instead. <add>const key = scryptSync(password, 'salt', 24); <add>// The IV is usually passed along with the ciphertext. <add>const iv = Buffer.alloc(16, 0); // Initialization vector. <add> <add>const decipher = createDecipheriv(algorithm, key, iv); <add> <add>const input = createReadStream('test.enc'); <add>const output = createWriteStream('test.js'); <ide> <ide> input.pipe(decipher).pipe(output); <ide> ``` <ide> <ide> Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods: <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { <add> scryptSync, <add> createDecipheriv, <add>} = await import('crypto'); <ide> <ide> const algorithm = 'aes-192-cbc'; <ide> const password = 'Password used to generate key'; <ide> // Use the async `crypto.scrypt()` instead. <del>const key = crypto.scryptSync(password, 'salt', 24); <add>const key = scryptSync(password, 'salt', 24); <ide> // The IV is usually passed along with the ciphertext. <ide> const iv = Buffer.alloc(16, 0); // Initialization vector. <ide> <del>const decipher = crypto.createDecipheriv(algorithm, key, iv); <add>const decipher = createDecipheriv(algorithm, key, iv); <add> <add>// Encrypted using same algorithm, key and iv. <add>const encrypted = <add> 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; <add>let decrypted = decipher.update(encrypted, 'hex', 'utf8'); <add>decrypted += decipher.final('utf8'); <add>console.log(decrypted); <add>// Prints: some clear text data <add>``` <add> <add>```cjs <add>const { <add> scryptSync, <add> createDecipheriv, <add>} = require('crypto'); <add> <add>const algorithm = 'aes-192-cbc'; <add>const password = 'Password used to generate key'; <add>// Use the async `crypto.scrypt()` instead. <add>const key = scryptSync(password, 'salt', 24); <add>// The IV is usually passed along with the ciphertext. <add>const iv = Buffer.alloc(16, 0); // Initialization vector. <add> <add>const decipher = createDecipheriv(algorithm, key, iv); <ide> <ide> // Encrypted using same algorithm, key and iv. <ide> const encrypted = <ide> exchanges. <ide> Instances of the `DiffieHellman` class can be created using the <ide> [`crypto.createDiffieHellman()`][] function. <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>import assert from 'assert'; <add> <add>const { <add> createDiffieHellman, <add>} = await import('crypto'); <add> <add>// Generate Alice's keys... <add>const alice = createDiffieHellman(2048); <add>const aliceKey = alice.generateKeys(); <add> <add>// Generate Bob's keys... <add>const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); <add>const bobKey = bob.generateKeys(); <add> <add>// Exchange and generate the secret... <add>const aliceSecret = alice.computeSecret(bobKey); <add>const bobSecret = bob.computeSecret(aliceKey); <add> <add>// OK <add>assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); <add>``` <add> <add>```cjs <ide> const assert = require('assert'); <ide> <add>const { <add> createDiffieHellman, <add>} = require('crypto'); <add> <ide> // Generate Alice's keys... <del>const alice = crypto.createDiffieHellman(2048); <add>const alice = createDiffieHellman(2048); <ide> const aliceKey = alice.generateKeys(); <ide> <ide> // Generate Bob's keys... <del>const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator()); <add>const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); <ide> const bobKey = bob.generateKeys(); <ide> <ide> // Exchange and generate the secret... <ide> added: v0.7.5 <ide> The `DiffieHellmanGroup` class takes a well-known modp group as its argument but <ide> otherwise works the same as `DiffieHellman`. <ide> <del>```js <del>const name = 'modp1'; <del>const dh = crypto.createDiffieHellmanGroup(name); <add>```mjs <add>const { createDiffieHellmanGroup } = await import('crypto'); <add>const dh = createDiffieHellmanGroup('modp1'); <add>``` <add> <add>```cjs <add>const { createDiffieHellmanGroup } = require('crypto'); <add>const dh = createDiffieHellmanGroup('modp1'); <ide> ``` <ide> <del>`name` is taken from [RFC 2412][] (modp1 and 2) and [RFC 3526][]: <add>The name (e.g. `'modp1'`) is taken from [RFC 2412][] (modp1 and 2) and <add>[RFC 3526][]: <ide> <ide> ```console <ide> $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h <ide> key exchanges. <ide> Instances of the `ECDH` class can be created using the <ide> [`crypto.createECDH()`][] function. <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>import assert from 'assert'; <add> <add>const { <add> createECDH, <add>} = await import('crypto'); <add> <add>// Generate Alice's keys... <add>const alice = createECDH('secp521r1'); <add>const aliceKey = alice.generateKeys(); <add> <add>// Generate Bob's keys... <add>const bob = createECDH('secp521r1'); <add>const bobKey = bob.generateKeys(); <add> <add>// Exchange and generate the secret... <add>const aliceSecret = alice.computeSecret(bobKey); <add>const bobSecret = bob.computeSecret(aliceKey); <add> <add>assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); <add>// OK <add>``` <add> <add>```cjs <ide> const assert = require('assert'); <ide> <add>const { <add> createECDH, <add>} = require('crypto'); <add> <ide> // Generate Alice's keys... <del>const alice = crypto.createECDH('secp521r1'); <add>const alice = createECDH('secp521r1'); <ide> const aliceKey = alice.generateKeys(); <ide> <ide> // Generate Bob's keys... <del>const bob = crypto.createECDH('secp521r1'); <add>const bob = createECDH('secp521r1'); <ide> const bobKey = bob.generateKeys(); <ide> <ide> // Exchange and generate the secret... <ide> If the `inputEncoding` is not provided, `key` is expected to be a [`Buffer`][], <ide> <ide> Example (uncompressing a key): <ide> <del>```js <del>const { createECDH, ECDH } = require('crypto'); <add>```mjs <add>const { <add> createECDH, <add> ECDH, <add>} = await import('crypto'); <add> <add>const ecdh = createECDH('secp256k1'); <add>ecdh.generateKeys(); <add> <add>const compressedKey = ecdh.getPublicKey('hex', 'compressed'); <add> <add>const uncompressedKey = ECDH.convertKey(compressedKey, <add> 'secp256k1', <add> 'hex', <add> 'hex', <add> 'uncompressed'); <add> <add>// The converted key and the uncompressed public key should be the same <add>console.log(uncompressedKey === ecdh.getPublicKey('hex')); <add>``` <add> <add>```cjs <add>const { <add> createECDH, <add> ECDH, <add>} = require('crypto'); <ide> <ide> const ecdh = createECDH('secp256k1'); <ide> ecdh.generateKeys(); <ide> set. <ide> <ide> Example (obtaining a shared secret): <ide> <del>```js <del>const crypto = require('crypto'); <del>const alice = crypto.createECDH('secp256k1'); <del>const bob = crypto.createECDH('secp256k1'); <add>```mjs <add>const { <add> createECDH, <add> createHash, <add>} = await crypto('crypto'); <add> <add>const alice = createECDH('secp256k1'); <add>const bob = createECDH('secp256k1'); <ide> <ide> // This is a shortcut way of specifying one of Alice's previous private <ide> // keys. It would be unwise to use such a predictable private key in a real <ide> // application. <ide> alice.setPrivateKey( <del> crypto.createHash('sha256').update('alice', 'utf8').digest() <add> createHash('sha256').update('alice', 'utf8').digest() <add>); <add> <add>// Bob uses a newly generated cryptographically strong <add>// pseudorandom key pair <add>bob.generateKeys(); <add> <add>const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); <add>const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); <add> <add>// aliceSecret and bobSecret should be the same shared secret value <add>console.log(aliceSecret === bobSecret); <add>``` <add> <add>```cjs <add>const { <add> createECDH, <add> createHash, <add>} = require('crypto'); <add> <add>const alice = createECDH('secp256k1'); <add>const bob = createECDH('secp256k1'); <add> <add>// This is a shortcut way of specifying one of Alice's previous private <add>// keys. It would be unwise to use such a predictable private key in a real <add>// application. <add>alice.setPrivateKey( <add> createHash('sha256').update('alice', 'utf8').digest() <ide> ); <ide> <ide> // Bob uses a newly generated cryptographically strong <ide> objects are not to be created directly using the `new` keyword. <ide> <ide> Example: Using `Hash` objects as streams: <ide> <del>```js <del>const crypto = require('crypto'); <del>const hash = crypto.createHash('sha256'); <add>```mjs <add>const { <add> createHash, <add>} = await import('crypto'); <add> <add>const hash = createHash('sha256'); <add> <add>hash.on('readable', () => { <add> // Only one element is going to be produced by the <add> // hash stream. <add> const data = hash.read(); <add> if (data) { <add> console.log(data.toString('hex')); <add> // Prints: <add> // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 <add> } <add>}); <add> <add>hash.write('some data to hash'); <add>hash.end(); <add>``` <add> <add>```cjs <add>const { <add> createHash, <add>} = require('crypto'); <add> <add>const hash = createHash('sha256'); <ide> <ide> hash.on('readable', () => { <ide> // Only one element is going to be produced by the <ide> hash.end(); <ide> <ide> Example: Using `Hash` and piped streams: <ide> <del>```js <del>const crypto = require('crypto'); <del>const fs = require('fs'); <del>const hash = crypto.createHash('sha256'); <add>```mjs <add>const { <add> createReadStream, <add>} = require('fs'); <add> <add>const { <add> createHash, <add>} = await import('crypto'); <add>const hash = createHash('sha256'); <add> <add>const input = createReadStream('test.js'); <add>input.pipe(hash).setEncoding('hex').pipe(process.stdout); <add>``` <add> <add>```cjs <add>const { <add> createReadStream, <add>} = require('fs'); <add> <add>const { <add> createHash, <add>} = require('crypto'); <ide> <del>const input = fs.createReadStream('test.js'); <add>const hash = createHash('sha256'); <add> <add>const input = createReadStream('test.js'); <ide> input.pipe(hash).setEncoding('hex').pipe(process.stdout); <ide> ``` <ide> <ide> Example: Using the [`hash.update()`][] and [`hash.digest()`][] methods: <ide> <del>```js <del>const crypto = require('crypto'); <del>const hash = crypto.createHash('sha256'); <add>```mjs <add>const { <add> createHash, <add>} = require('crypto'); <add> <add>const hash = createHash('sha256'); <add> <add>hash.update('some data to hash'); <add>console.log(hash.digest('hex')); <add>// Prints: <add>// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 <add>``` <add> <add>```cjs <add>const { <add> createHash, <add>} = require('crypto'); <add> <add>const hash = createHash('sha256'); <ide> <ide> hash.update('some data to hash'); <ide> console.log(hash.digest('hex')); <ide> specify the desired output length in bytes. <ide> An error is thrown when an attempt is made to copy the `Hash` object after <ide> its [`hash.digest()`][] method has been called. <ide> <del>```js <add>```mjs <ide> // Calculate a rolling hash. <del>const crypto = require('crypto'); <del>const hash = crypto.createHash('sha256'); <add>const { <add> createHash, <add>} = require('crypto'); <add> <add>const hash = createHash('sha256'); <add> <add>hash.update('one'); <add>console.log(hash.copy().digest('hex')); <add> <add>hash.update('two'); <add>console.log(hash.copy().digest('hex')); <add> <add>hash.update('three'); <add>console.log(hash.copy().digest('hex')); <add> <add>// Etc. <add>``` <add> <add>```cjs <add>// Calculate a rolling hash. <add>const { <add> createHash, <add>} = require('crypto'); <add> <add>const hash = createHash('sha256'); <ide> <ide> hash.update('one'); <ide> console.log(hash.copy().digest('hex')); <ide> objects are not to be created directly using the `new` keyword. <ide> <ide> Example: Using `Hmac` objects as streams: <ide> <del>```js <del>const crypto = require('crypto'); <del>const hmac = crypto.createHmac('sha256', 'a secret'); <add>```mjs <add>const { <add> createHmac, <add>} = require('crypto'); <add> <add>const hmac = createHmac('sha256', 'a secret'); <add> <add>hmac.on('readable', () => { <add> // Only one element is going to be produced by the <add> // hash stream. <add> const data = hmac.read(); <add> if (data) { <add> console.log(data.toString('hex')); <add> // Prints: <add> // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e <add> } <add>}); <add> <add>hmac.write('some data to hash'); <add>hmac.end(); <add>``` <add> <add>```cjs <add>const { <add> createHmac, <add>} = require('crypto'); <add> <add>const hmac = createHmac('sha256', 'a secret'); <ide> <ide> hmac.on('readable', () => { <ide> // Only one element is going to be produced by the <ide> hmac.end(); <ide> <ide> Example: Using `Hmac` and piped streams: <ide> <del>```js <del>const crypto = require('crypto'); <del>const fs = require('fs'); <del>const hmac = crypto.createHmac('sha256', 'a secret'); <add>```mjs <add>import { createReadStream } from 'fs'; <add> <add>const { <add> createHmac, <add>} = await import('crypto'); <add> <add>const hmac = createHmac('sha256', 'a secret'); <add> <add>const input = createReadStream('test.js'); <add>input.pipe(hmac).pipe(process.stdout); <add>``` <ide> <del>const input = fs.createReadStream('test.js'); <add>```cjs <add>const { <add> createReadStream, <add>} = require('fs'); <add> <add>const { <add> createHmac, <add>} = require('crypto'); <add> <add>const hmac = createHmac('sha256', 'a secret'); <add> <add>const input = createReadStream('test.js'); <ide> input.pipe(hmac).pipe(process.stdout); <ide> ``` <ide> <ide> Example: Using the [`hmac.update()`][] and [`hmac.digest()`][] methods: <ide> <del>```js <del>const crypto = require('crypto'); <del>const hmac = crypto.createHmac('sha256', 'a secret'); <add>```mjs <add>const { <add> createHmac, <add>} = await import('crypto'); <add> <add>const hmac = createHmac('sha256', 'a secret'); <add> <add>hmac.update('some data to hash'); <add>console.log(hmac.digest('hex')); <add>// Prints: <add>// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e <add>``` <add> <add>```cjs <add>const { <add> createHmac, <add>} = require('crypto'); <add> <add>const hmac = createHmac('sha256', 'a secret'); <ide> <ide> hmac.update('some data to hash'); <ide> console.log(hmac.digest('hex')); <ide> added: v15.0.0 <ide> <ide> Example: Converting a `CryptoKey` instance to a `KeyObject`: <ide> <del>```js <del>const { webcrypto: { subtle }, KeyObject } = require('crypto'); <add>```mjs <add>const { <add> webcrypto: { <add> subtle, <add> }, <add> KeyObject, <add>} = await import('crypto'); <add> <add>const key = await subtle.generateKey({ <add> name: 'HMAC', <add> hash: 'SHA-256', <add> length: 256 <add>}, true, ['sign', 'verify']); <add> <add>const keyObject = KeyObject.from(key); <add>console.log(keyObject.symmetricKeySize); <add>// Prints: 32 (symmetric key size in bytes) <add>``` <add> <add>```cjs <add>const { <add> webcrypto: { <add> subtle, <add> }, <add> KeyObject, <add>} = require('crypto'); <ide> <ide> (async function() { <ide> const key = await subtle.generateKey({ <ide> to be created directly using the `new` keyword. <ide> <ide> Example: Using `Sign` and [`Verify`][] objects as streams: <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { <add> generateKeyPairSync, <add> createSign, <add> createVerify, <add>} = await import('crypto'); <ide> <del>const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { <add>const { privateKey, publicKey } = generateKeyPairSync('ec', { <ide> namedCurve: 'sect239k1' <ide> }); <ide> <del>const sign = crypto.createSign('SHA256'); <add>const sign = createSign('SHA256'); <ide> sign.write('some data to sign'); <ide> sign.end(); <ide> const signature = sign.sign(privateKey, 'hex'); <ide> <del>const verify = crypto.createVerify('SHA256'); <add>const verify = createVerify('SHA256'); <add>verify.write('some data to sign'); <add>verify.end(); <add>console.log(verify.verify(publicKey, signature, 'hex')); <add>// Prints: true <add>``` <add> <add>```cjs <add>const { <add> generateKeyPairSync, <add> createSign, <add> createVerify, <add>} = require('crypto'); <add> <add>const { privateKey, publicKey } = generateKeyPairSync('ec', { <add> namedCurve: 'sect239k1' <add>}); <add> <add>const sign = createSign('SHA256'); <add>sign.write('some data to sign'); <add>sign.end(); <add>const signature = sign.sign(privateKey, 'hex'); <add> <add>const verify = createVerify('SHA256'); <ide> verify.write('some data to sign'); <ide> verify.end(); <ide> console.log(verify.verify(publicKey, signature, 'hex')); <ide> console.log(verify.verify(publicKey, signature, 'hex')); <ide> <ide> Example: Using the [`sign.update()`][] and [`verify.update()`][] methods: <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { <add> generateKeyPairSync, <add> createSign, <add> createVerify, <add>} = await import('crypto'); <add> <add>const { privateKey, publicKey } = generateKeyPairSync('rsa', { <add> modulusLength: 2048, <add>}); <add> <add>const sign = createSign('SHA256'); <add>sign.update('some data to sign'); <add>sign.end(); <add>const signature = sign.sign(privateKey); <add> <add>const verify = createVerify('SHA256'); <add>verify.update('some data to sign'); <add>verify.end(); <add>console.log(verify.verify(publicKey, signature)); <add>// Prints: true <add>``` <add> <add>```cjs <add>const { <add> generateKeyPairSync, <add> createSign, <add> createVerify, <add>} = require('crypto'); <ide> <del>const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { <add>const { privateKey, publicKey } = generateKeyPairSync('rsa', { <ide> modulusLength: 2048, <ide> }); <ide> <del>const sign = crypto.createSign('SHA256'); <add>const sign = createSign('SHA256'); <ide> sign.update('some data to sign'); <ide> sign.end(); <ide> const signature = sign.sign(privateKey); <ide> <del>const verify = crypto.createVerify('SHA256'); <add>const verify = createVerify('SHA256'); <ide> verify.update('some data to sign'); <ide> verify.end(); <ide> console.log(verify.verify(publicKey, signature)); <ide> added: v15.6.0 <ide> Encapsulates an X509 certificate and provides read-only access to <ide> its information. <ide> <del>```js <add>```mjs <add>const { X509Certificate } = await import('crypto'); <add> <add>const x509 = new X509Certificate('{... pem encoded cert ...}'); <add> <add>console.log(x509.subject); <add>``` <add> <add>```cjs <ide> const { X509Certificate } = require('crypto'); <ide> <ide> const x509 = new X509Certificate('{... pem encoded cert ...}'); <ide> display the available digest algorithms. <ide> <ide> Example: generating the sha256 sum of a file <ide> <del>```js <add>```mjs <add>import { <add> createReadStream <add>} from 'fs'; <add> <add>const { <add> createHash, <add>} = await import('crypto'); <add> <ide> const filename = process.argv[2]; <del>const crypto = require('crypto'); <del>const fs = require('fs'); <ide> <del>const hash = crypto.createHash('sha256'); <add>const hash = createHash('sha256'); <add> <add>const input = createReadStream(filename); <add>input.on('readable', () => { <add> // Only one element is going to be produced by the <add> // hash stream. <add> const data = input.read(); <add> if (data) <add> hash.update(data); <add> else { <add> console.log(`${hash.digest('hex')} ${filename}`); <add> } <add>}); <add>``` <add> <add>```cjs <add>const { <add> createReadStream, <add>} = require('fs'); <add> <add>const { <add> createHash, <add>} = require('crypto'); <add> <add>const filename = process.argv[2]; <ide> <del>const input = fs.createReadStream(filename); <add>const hash = createHash('sha256'); <add> <add>const input = createReadStream(filename); <ide> input.on('readable', () => { <ide> // Only one element is going to be produced by the <ide> // hash stream. <ide> a [`KeyObject`][], its type must be `secret`. <ide> <ide> Example: generating the sha256 HMAC of a file <ide> <del>```js <add>```mjs <add>import { <add> createReadStream <add>} from 'fs'; <add> <add>const { <add> createHmac, <add>} = await import('crypto'); <add> <ide> const filename = process.argv[2]; <del>const crypto = require('crypto'); <del>const fs = require('fs'); <ide> <del>const hmac = crypto.createHmac('sha256', 'a secret'); <add>const hmac = createHmac('sha256', 'a secret'); <ide> <del>const input = fs.createReadStream(filename); <add>const input = createReadStream(filename); <add>input.on('readable', () => { <add> // Only one element is going to be produced by the <add> // hash stream. <add> const data = input.read(); <add> if (data) <add> hmac.update(data); <add> else { <add> console.log(`${hmac.digest('hex')} ${filename}`); <add> } <add>}); <add>``` <add> <add>```cjs <add>const { <add> createReadStream, <add>} = require('fs'); <add> <add>const { <add> createHmac, <add>} = require('crypto'); <add> <add>const filename = process.argv[2]; <add> <add>const hmac = createHmac('sha256', 'a secret'); <add> <add>const input = createReadStream(filename); <ide> input.on('readable', () => { <ide> // Only one element is going to be produced by the <ide> // hash stream. <ide> added: v15.0.0 <ide> Asynchronously generates a new random secret key of the given `length`. The <ide> `type` will determine which validations will be performed on the `length`. <ide> <del>```js <del>const { generateKey } = require('crypto'); <add>```mjs <add>const { <add> generateKey, <add>} = await import('crypto'); <add> <add>generateKey('hmac', { length: 64 }, (err, key) => { <add> if (err) throw err; <add> console.log(key.export().toString('hex')); // 46e..........620 <add>}); <add>``` <add> <add>```cjs <add>const { <add> generateKey, <add>} = require('crypto'); <ide> <ide> generateKey('hmac', { length: 64 }, (err, key) => { <ide> if (err) throw err; <ide> If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function <ide> behaves as if [`keyObject.export()`][] had been called on its result. Otherwise, <ide> the respective part of the key is returned as a [`KeyObject`][]. <ide> <del>It is recommended to encode public keys as `'spki'` and private keys as <del>`'pkcs8'` with encryption for long-term storage: <add>It is recommended to encode public keys as `'spki'` and private keys as <add>`'pkcs8'` with encryption for long-term storage: <add> <add>```mjs <add>const { <add> generateKeyPair, <add>} = await import('crypto'); <add> <add>generateKeyPair('rsa', { <add> modulusLength: 4096, <add> publicKeyEncoding: { <add> type: 'spki', <add> format: 'pem' <add> }, <add> privateKeyEncoding: { <add> type: 'pkcs8', <add> format: 'pem', <add> cipher: 'aes-256-cbc', <add> passphrase: 'top secret' <add> } <add>}, (err, publicKey, privateKey) => { <add> // Handle errors and use the generated key pair. <add>}); <add>``` <add> <add>```cjs <add>const { <add> generateKeyPair, <add>} = require('crypto'); <ide> <del>```js <del>const { generateKeyPair } = require('crypto'); <ide> generateKeyPair('rsa', { <ide> modulusLength: 4096, <ide> publicKeyEncoding: { <ide> When encoding public keys, it is recommended to use `'spki'`. When encoding <ide> private keys, it is recommended to use `'pkcs8'` with a strong passphrase, <ide> and to keep the passphrase confidential. <ide> <del>```js <del>const { generateKeyPairSync } = require('crypto'); <del>const { publicKey, privateKey } = generateKeyPairSync('rsa', { <add>```mjs <add>const { <add> generateKeyPairSync, <add>} = await import('crypto'); <add> <add>const { <add> publicKey, <add> privateKey, <add>} = generateKeyPairSync('rsa', { <add> modulusLength: 4096, <add> publicKeyEncoding: { <add> type: 'spki', <add> format: 'pem' <add> }, <add> privateKeyEncoding: { <add> type: 'pkcs8', <add> format: 'pem', <add> cipher: 'aes-256-cbc', <add> passphrase: 'top secret' <add> } <add>}); <add>``` <add> <add>```cjs <add>const { <add> generateKeyPairSync, <add>} = require('crypto'); <add> <add>const { <add> publicKey, <add> privateKey, <add>} = generateKeyPairSync('rsa', { <ide> modulusLength: 4096, <ide> publicKeyEncoding: { <ide> type: 'spki', <ide> added: v15.0.0 <ide> Synchronously generates a new random secret key of the given `length`. The <ide> `type` will determine which validations will be performed on the `length`. <ide> <del>```js <del>const { generateKeySync } = require('crypto'); <add>```mjs <add>const { <add> generateKeySync, <add>} = await import('crypto'); <add> <add>const key = generateKeySync('hmac', 64); <add>console.log(key.export().toString('hex')); // e89..........41e <add>``` <add> <add>```cjs <add>const { <add> generateKeySync, <add>} = require('crypto'); <ide> <ide> const key = generateKeySync('hmac', 64); <ide> console.log(key.export().toString('hex')); // e89..........41e <ide> added: v0.9.3 <ide> * Returns: {string[]} An array with the names of the supported cipher <ide> algorithms. <ide> <del>```js <del>const ciphers = crypto.getCiphers(); <del>console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...] <add>```mjs <add>const { <add> getCiphers, <add>} = await import('crypto'); <add> <add>console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] <add>``` <add> <add>```cjs <add>const { <add> getCiphers, <add>} = require('crypto'); <add> <add>console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] <ide> ``` <ide> <ide> ### `crypto.getCurves()` <ide> added: v2.3.0 <ide> <ide> * Returns: {string[]} An array with the names of the supported elliptic curves. <ide> <del>```js <del>const curves = crypto.getCurves(); <del>console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] <add>```mjs <add>const { <add> getCurves, <add>} = await import('crypto'); <add> <add>console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] <add>``` <add> <add>```cjs <add>const { <add> getCurves, <add>} = require('crypto'); <add> <add>console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] <ide> ``` <ide> <ide> ### `crypto.getDiffieHellman(groupName)` <ide> and communication time. <ide> <ide> Example (obtaining a shared secret): <ide> <del>```js <del>const crypto = require('crypto'); <del>const alice = crypto.getDiffieHellman('modp14'); <del>const bob = crypto.getDiffieHellman('modp14'); <add>```mjs <add>const { <add> getDiffieHellman, <add>} = await import('crypto'); <add>const alice = getDiffieHellman('modp14'); <add>const bob = getDiffieHellman('modp14'); <add> <add>alice.generateKeys(); <add>bob.generateKeys(); <add> <add>const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); <add>const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); <add> <add>/* aliceSecret and bobSecret should be the same */ <add>console.log(aliceSecret === bobSecret); <add>``` <add> <add>```cjs <add>const { <add> getDiffieHellman, <add>} = require('crypto'); <add> <add>const alice = getDiffieHellman('modp14'); <add>const bob = getDiffieHellman('modp14'); <ide> <ide> alice.generateKeys(); <ide> bob.generateKeys(); <ide> added: v0.9.3 <ide> * Returns: {string[]} An array of the names of the supported hash algorithms, <ide> such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. <ide> <del>```js <del>const hashes = crypto.getHashes(); <del>console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] <add>```mjs <add>const { <add> getHashes, <add>} = await import('crypto'); <add> <add>console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] <add>``` <add> <add>```cjs <add>const { <add> getHashes, <add>} = require('crypto'); <add> <add>console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] <ide> ``` <ide> <ide> ### `crypto.hkdf(digest, key, salt, info, keylen, callback)` <ide> otherwise `err` will be `null`. The successfully generated `derivedKey` will <ide> be passed to the callback as an {ArrayBuffer}. An error will be thrown if any <ide> of the input aguments specify invalid values or types. <ide> <del>```js <del>const crypto = require('crypto'); <del>crypto.hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { <add>```mjs <add>const { <add> hkdf, <add>} = await import('crypto'); <add> <add>hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { <add> if (err) throw err; <add> console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' <add>}); <add>``` <add> <add>```cjs <add>const { <add> hkdf, <add>} = require('crypto'); <add> <add>hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { <ide> if (err) throw err; <ide> console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' <ide> }); <ide> The successfully generated `derivedKey` will be returned as an {ArrayBuffer}. <ide> An error will be thrown if any of the input aguments specify invalid values or <ide> types, or if the derived key cannot be generated. <ide> <del>```js <del>const crypto = require('crypto'); <del>const derivedKey = crypto.hkdfSync('sha512', 'key', 'salt', 'info', 64); <add>```mjs <add>const { <add> hkdfSync, <add>} = await import('crypto'); <add> <add>const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); <add>console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' <add>``` <add> <add>```cjs <add>const { <add> hkdfSync, <add>} = require('crypto'); <add> <add>const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); <ide> console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' <ide> ``` <ide> <ide> random and at least 16 bytes long. See [NIST SP 800-132][] for details. <ide> When passing strings for `password` or `salt`, please consider <ide> [caveats when using strings as inputs to cryptographic APIs][]. <ide> <del>```js <del>const crypto = require('crypto'); <del>crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { <add>```mjs <add>const { <add> pbkdf2, <add>} = await import('crypto'); <add> <add>pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { <add> if (err) throw err; <add> console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' <add>}); <add>``` <add> <add>```cjs <add>const { <add> pbkdf2, <add>} = require('crypto'); <add> <add>pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { <ide> if (err) throw err; <ide> console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' <ide> }); <ide> The `crypto.DEFAULT_ENCODING` property can be used to change the way the <ide> `derivedKey` is passed to the callback. This property, however, has been <ide> deprecated and use should be avoided. <ide> <del>```js <add>```mjs <add>const crypto = await import('crypto'); <add>crypto.DEFAULT_ENCODING = 'hex'; <add>crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { <add> if (err) throw err; <add> console.log(derivedKey); // '3745e48...aa39b34' <add>}); <add>``` <add> <add>```cjs <ide> const crypto = require('crypto'); <ide> crypto.DEFAULT_ENCODING = 'hex'; <ide> crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { <ide> random and at least 16 bytes long. See [NIST SP 800-132][] for details. <ide> When passing strings for `password` or `salt`, please consider <ide> [caveats when using strings as inputs to cryptographic APIs][]. <ide> <del>```js <del>const crypto = require('crypto'); <del>const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); <add>```mjs <add>const { <add> pbkdf2Sync, <add>} = await import('crypto'); <add> <add>const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); <add>console.log(key.toString('hex')); // '3745e48...08d59ae' <add>``` <add> <add>```cjs <add>const { <add> pbkdf2Sync, <add>} = require('crypto'); <add> <add>const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); <ide> console.log(key.toString('hex')); // '3745e48...08d59ae' <ide> ``` <ide> <ide> The `crypto.DEFAULT_ENCODING` property may be used to change the way the <ide> `derivedKey` is returned. This property, however, is deprecated and use <ide> should be avoided. <ide> <del>```js <add>```mjs <add>const crypto = await import('crypto'); <add>crypto.DEFAULT_ENCODING = 'hex'; <add>const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); <add>console.log(key); // '3745e48...aa39b34' <add>``` <add> <add>```cjs <ide> const crypto = require('crypto'); <ide> crypto.DEFAULT_ENCODING = 'hex'; <ide> const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); <ide> and the `callback` function is invoked with two arguments: `err` and `buf`. <ide> If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The <ide> `buf` argument is a [`Buffer`][] containing the generated bytes. <ide> <del>```js <add>```mjs <ide> // Asynchronous <del>const crypto = require('crypto'); <del>crypto.randomBytes(256, (err, buf) => { <add>const { <add> randomBytes, <add>} = await import('crypto'); <add> <add>randomBytes(256, (err, buf) => { <add> if (err) throw err; <add> console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); <add>}); <add>``` <add> <add>```cjs <add>// Asynchronous <add>const { <add> randomBytes, <add>} = require('crypto'); <add> <add>randomBytes(256, (err, buf) => { <ide> if (err) throw err; <ide> console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); <ide> }); <ide> If the `callback` function is not provided, the random bytes are generated <ide> synchronously and returned as a [`Buffer`][]. An error will be thrown if <ide> there is a problem generating the bytes. <ide> <del>```js <add>```mjs <ide> // Synchronous <del>const buf = crypto.randomBytes(256); <add>const { <add> randomBytes, <add>} = await import('crypto'); <add> <add>const buf = randomBytes(256); <add>console.log( <add> `${buf.length} bytes of random data: ${buf.toString('hex')}`); <add>``` <add> <add>```cjs <add>// Synchronous <add>const { <add> randomBytes, <add>} = require('crypto'); <add> <add>const buf = randomBytes(256); <ide> console.log( <ide> `${buf.length} bytes of random data: ${buf.toString('hex')}`); <ide> ``` <ide> changes: <ide> <ide> Synchronous version of [`crypto.randomFill()`][]. <ide> <del>```js <add>```mjs <add>const { <add> randomFillSync, <add>} = await import('crypto'); <add> <ide> const buf = Buffer.alloc(10); <del>console.log(crypto.randomFillSync(buf).toString('hex')); <add>console.log(randomFillSync(buf).toString('hex')); <ide> <del>crypto.randomFillSync(buf, 5); <add>randomFillSync(buf, 5); <ide> console.log(buf.toString('hex')); <ide> <ide> // The above is equivalent to the following: <del>crypto.randomFillSync(buf, 5, 5); <add>randomFillSync(buf, 5, 5); <add>console.log(buf.toString('hex')); <add>``` <add> <add>```cjs <add>const { <add> randomFillSync, <add>} = require('crypto'); <add> <add>const buf = Buffer.alloc(10); <add>console.log(randomFillSync(buf).toString('hex')); <add> <add>randomFillSync(buf, 5); <add>console.log(buf.toString('hex')); <add> <add>// The above is equivalent to the following: <add>randomFillSync(buf, 5, 5); <ide> console.log(buf.toString('hex')); <ide> ``` <ide> <ide> Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as <ide> `buffer`. <ide> <del>```js <add>```mjs <add>const { <add> randomFillSync, <add>} = await import('crypto'); <add> <add>const a = new Uint32Array(10); <add>console.log(Buffer.from(randomFillSync(a).buffer, <add> a.byteOffset, a.byteLength).toString('hex')); <add> <add>const b = new Float64Array(10); <add>console.log(Buffer.from(randomFillSync(b).buffer, <add> b.byteOffset, b.byteLength).toString('hex')); <add> <add>const c = new DataView(new ArrayBuffer(10)); <add>console.log(Buffer.from(randomFillSync(c).buffer, <add> c.byteOffset, c.byteLength).toString('hex')); <add> <add>const d = new ArrayBuffer(10); <add>console.log(Buffer.from(randomFillSync(d)).toString('hex')); <add>``` <add> <add>```cjs <add>const { <add> randomFillSync, <add>} = require('crypto'); <add> <ide> const a = new Uint32Array(10); <del>console.log(Buffer.from(crypto.randomFillSync(a).buffer, <add>console.log(Buffer.from(randomFillSync(a).buffer, <ide> a.byteOffset, a.byteLength).toString('hex')); <ide> <ide> const b = new Float64Array(10); <del>console.log(Buffer.from(crypto.randomFillSync(b).buffer, <add>console.log(Buffer.from(randomFillSync(b).buffer, <ide> b.byteOffset, b.byteLength).toString('hex')); <ide> <ide> const c = new DataView(new ArrayBuffer(10)); <del>console.log(Buffer.from(crypto.randomFillSync(c).buffer, <add>console.log(Buffer.from(randomFillSync(c).buffer, <ide> c.byteOffset, c.byteLength).toString('hex')); <ide> <ide> const d = new ArrayBuffer(10); <del>console.log(Buffer.from(crypto.randomFillSync(d)).toString('hex')); <add>console.log(Buffer.from(randomFillSync(d)).toString('hex')); <ide> ``` <ide> <ide> ### `crypto.randomFill(buffer[, offset][, size], callback)` <ide> requires that a callback is passed in. <ide> <ide> If the `callback` function is not provided, an error will be thrown. <ide> <del>```js <add>```mjs <add>const { <add> randomFill, <add>} = await import('crypto'); <add> <add>const buf = Buffer.alloc(10); <add>randomFill(buf, (err, buf) => { <add> if (err) throw err; <add> console.log(buf.toString('hex')); <add>}); <add> <add>randomFill(buf, 5, (err, buf) => { <add> if (err) throw err; <add> console.log(buf.toString('hex')); <add>}); <add> <add>// The above is equivalent to the following: <add>randomFill(buf, 5, 5, (err, buf) => { <add> if (err) throw err; <add> console.log(buf.toString('hex')); <add>}); <add>``` <add> <add>```cjs <add>const { <add> randomFill, <add>} = require('crypto'); <add> <ide> const buf = Buffer.alloc(10); <del>crypto.randomFill(buf, (err, buf) => { <add>randomFill(buf, (err, buf) => { <ide> if (err) throw err; <ide> console.log(buf.toString('hex')); <ide> }); <ide> <del>crypto.randomFill(buf, 5, (err, buf) => { <add>randomFill(buf, 5, (err, buf) => { <ide> if (err) throw err; <ide> console.log(buf.toString('hex')); <ide> }); <ide> <ide> // The above is equivalent to the following: <del>crypto.randomFill(buf, 5, 5, (err, buf) => { <add>randomFill(buf, 5, 5, (err, buf) => { <ide> if (err) throw err; <ide> console.log(buf.toString('hex')); <ide> }); <ide> crypto.randomFill(buf, 5, 5, (err, buf) => { <ide> Any `ArrayBuffer` `TypedArray` or `DataView` instance may be passed as <ide> `buffer`. <ide> <del>```js <add>```mjs <add>const { <add> randomFill, <add>} = await import('crypto'); <add> <add>const a = new Uint32Array(10); <add>randomFill(a, (err, buf) => { <add> if (err) throw err; <add> console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) <add> .toString('hex')); <add>}); <add> <add>const b = new Float64Array(10); <add>randomFill(b, (err, buf) => { <add> if (err) throw err; <add> console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) <add> .toString('hex')); <add>}); <add> <add>const c = new DataView(new ArrayBuffer(10)); <add>randomFill(c, (err, buf) => { <add> if (err) throw err; <add> console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) <add> .toString('hex')); <add>}); <add> <add>const d = new ArrayBuffer(10); <add>randomFill(d, (err, buf) => { <add> if (err) throw err; <add> console.log(Buffer.from(buf).toString('hex')); <add>}); <add>``` <add> <add>```cjs <add>const { <add> randomFill, <add>} = require('crypto'); <add> <ide> const a = new Uint32Array(10); <del>crypto.randomFill(a, (err, buf) => { <add>randomFill(a, (err, buf) => { <ide> if (err) throw err; <ide> console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) <ide> .toString('hex')); <ide> }); <ide> <ide> const b = new Float64Array(10); <del>crypto.randomFill(b, (err, buf) => { <add>randomFill(b, (err, buf) => { <ide> if (err) throw err; <ide> console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) <ide> .toString('hex')); <ide> }); <ide> <ide> const c = new DataView(new ArrayBuffer(10)); <del>crypto.randomFill(c, (err, buf) => { <add>randomFill(c, (err, buf) => { <ide> if (err) throw err; <ide> console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) <ide> .toString('hex')); <ide> }); <ide> <ide> const d = new ArrayBuffer(10); <del>crypto.randomFill(d, (err, buf) => { <add>randomFill(d, (err, buf) => { <ide> if (err) throw err; <ide> console.log(Buffer.from(buf).toString('hex')); <ide> }); <ide> be [safe integers][]. <ide> If the `callback` function is not provided, the random integer is <ide> generated synchronously. <ide> <del>```js <add>```mjs <add>// Asynchronous <add>const { <add> randomInt, <add>} = await import('crypto'); <add> <add>randomInt(3, (err, n) => { <add> if (err) throw err; <add> console.log(`Random number chosen from (0, 1, 2): ${n}`); <add>}); <add>``` <add> <add>```cjs <ide> // Asynchronous <del>crypto.randomInt(3, (err, n) => { <add>const { <add> randomInt, <add>} = require('crypto'); <add> <add>randomInt(3, (err, n) => { <ide> if (err) throw err; <ide> console.log(`Random number chosen from (0, 1, 2): ${n}`); <ide> }); <ide> ``` <ide> <del>```js <add>```mjs <add>// Synchronous <add>const { <add> randomInt, <add>} = await import('crypto'); <add> <add>const n = randomInt(3); <add>console.log(`Random number chosen from (0, 1, 2): ${n}`); <add>``` <add> <add>```cjs <ide> // Synchronous <del>const n = crypto.randomInt(3); <add>const { <add> randomInt, <add>} = require('crypto'); <add> <add>const n = randomInt(3); <ide> console.log(`Random number chosen from (0, 1, 2): ${n}`); <ide> ``` <ide> <del>```js <add>```mjs <ide> // With `min` argument <del>const n = crypto.randomInt(1, 7); <add>const { <add> randomInt, <add>} = await import('crypto'); <add> <add>const n = randomInt(1, 7); <add>console.log(`The dice rolled: ${n}`); <add>``` <add> <add>```cjs <add>// With `min` argument <add>const { <add> randomInt, <add>} = require('crypto'); <add> <add>const n = randomInt(1, 7); <ide> console.log(`The dice rolled: ${n}`); <ide> ``` <ide> <ide> The `callback` function is called with two arguments: `err` and `derivedKey`. <ide> An exception is thrown when any of the input arguments specify invalid values <ide> or types. <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { <add> scrypt, <add>} = await import('crypto'); <add> <add>// Using the factory defaults. <add>scrypt('password', 'salt', 64, (err, derivedKey) => { <add> if (err) throw err; <add> console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' <add>}); <add>// Using a custom N parameter. Must be a power of two. <add>scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { <add> if (err) throw err; <add> console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' <add>}); <add>``` <add> <add>```cjs <add>const { <add> scrypt, <add>} = require('crypto'); <add> <ide> // Using the factory defaults. <del>crypto.scrypt('password', 'salt', 64, (err, derivedKey) => { <add>scrypt('password', 'salt', 64, (err, derivedKey) => { <ide> if (err) throw err; <ide> console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' <ide> }); <ide> // Using a custom N parameter. Must be a power of two. <del>crypto.scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { <add>scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { <ide> if (err) throw err; <ide> console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' <ide> }); <ide> returned as a [`Buffer`][]. <ide> An exception is thrown when any of the input arguments specify invalid values <ide> or types. <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { <add> scryptSync, <add>} = await import('crypto'); <add>// Using the factory defaults. <add> <add>const key1 = scryptSync('password', 'salt', 64); <add>console.log(key1.toString('hex')); // '3745e48...08d59ae' <add>// Using a custom N parameter. Must be a power of two. <add>const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); <add>console.log(key2.toString('hex')); // '3745e48...aa39b34' <add>``` <add> <add>```cjs <add>const { <add> scryptSync, <add>} = require('crypto'); <ide> // Using the factory defaults. <del>const key1 = crypto.scryptSync('password', 'salt', 64); <add> <add>const key1 = scryptSync('password', 'salt', 64); <ide> console.log(key1.toString('hex')); // '3745e48...08d59ae' <ide> // Using a custom N parameter. Must be a power of two. <del>const key2 = crypto.scryptSync('password', 'salt', 64, { N: 1024 }); <add>const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); <ide> console.log(key2.toString('hex')); // '3745e48...aa39b34' <ide> ``` <ide> <ide> mode must adhere to certain restrictions when using the cipher API: <ide> applications *must* call `final()` to compute or verify the <ide> authentication tag. <ide> <del>```js <del>const crypto = require('crypto'); <add>```mjs <add>const { <add> createCipheriv, <add> createDecipheriv, <add> randomBytes, <add>} = await import('crypto'); <add> <add>const key = 'keykeykeykeykeykeykeykey'; <add>const nonce = randomBytes(12); <add> <add>const aad = Buffer.from('0123456789', 'hex'); <add> <add>const cipher = createCipheriv('aes-192-ccm', key, nonce, { <add> authTagLength: 16 <add>}); <add>const plaintext = 'Hello world'; <add>cipher.setAAD(aad, { <add> plaintextLength: Buffer.byteLength(plaintext) <add>}); <add>const ciphertext = cipher.update(plaintext, 'utf8'); <add>cipher.final(); <add>const tag = cipher.getAuthTag(); <add> <add>// Now transmit { ciphertext, nonce, tag }. <add> <add>const decipher = createDecipheriv('aes-192-ccm', key, nonce, { <add> authTagLength: 16 <add>}); <add>decipher.setAuthTag(tag); <add>decipher.setAAD(aad, { <add> plaintextLength: ciphertext.length <add>}); <add>const receivedPlaintext = decipher.update(ciphertext, null, 'utf8'); <add> <add>try { <add> decipher.final(); <add>} catch (err) { <add> console.error('Authentication failed!'); <add> return; <add>} <add> <add>console.log(receivedPlaintext); <add>``` <add> <add>```cjs <add>const { <add> createCipheriv, <add> createDecipheriv, <add> randomBytes, <add>} = require('crypto'); <ide> <ide> const key = 'keykeykeykeykeykeykeykey'; <del>const nonce = crypto.randomBytes(12); <add>const nonce = randomBytes(12); <ide> <ide> const aad = Buffer.from('0123456789', 'hex'); <ide> <del>const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, { <add>const cipher = createCipheriv('aes-192-ccm', key, nonce, { <ide> authTagLength: 16 <ide> }); <ide> const plaintext = 'Hello world'; <ide> const tag = cipher.getAuthTag(); <ide> <ide> // Now transmit { ciphertext, nonce, tag }. <ide> <del>const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, { <add>const decipher = createDecipheriv('aes-192-ccm', key, nonce, { <ide> authTagLength: 16 <ide> }); <ide> decipher.setAuthTag(tag);
1
Javascript
Javascript
add deprecation for the ember global
04f28b234bd990e56bd3a93d7bb0485719f065e4
<ide><path>packages/@ember/-internals/bootstrap/index.js <ide> import require from 'require'; <ide> import { context } from '@ember/-internals/environment'; <add>import { deprecate } from '@ember/debug'; <ide> <ide> (function () { <ide> let Ember; <ide> import { context } from '@ember/-internals/environment'; <ide> Ember = require('ember').default; <ide> } <ide> <add> deprecate( <add> 'Usage of the Ember Global is deprecated. You should import the Ember module or the specific API instead.', <add> false, <add> { <add> id: 'ember-global', <add> until: '4.0.0', <add> url: 'https://deprecations.emberjs.com/v3.x/#toc_ember-global', <add> for: 'ember-source', <add> since: { <add> enabled: '3.27.0', <add> }, <add> } <add> ); <add> <ide> return Ember; <ide> }, <ide> }); <ide><path>packages/internal-test-helpers/lib/test-cases/default-resolver-application.js <ide> export default class DefaultResolverApplicationTestCase extends AbstractApplicat <ide> let application; <ide> expectDeprecation(() => { <ide> application = this.application = Application.create(this.applicationOptions); <del> }, /Using the globals resolver is deprecated/); <add> }, /(Using the globals resolver is deprecated|Usage of the Ember Global is deprecated)/); <ide> <ide> // If the test expects a certain number of assertions, increment that number <ide> let { assert } = QUnit.config.current;
2
Ruby
Ruby
add mocked disable_cache for fixturefinder
9f677bf043eb359a91d346bb5a1e6ee81cef6665
<ide><path>actionview/test/template/digestor_test.rb <ide> def find(name, prefixes = [], partial = false, keys = [], options = {}) <ide> <ide> FixtureTemplate.new("digestor/#{partial_name}.#{format}.erb") <ide> end <add> <add> def disable_cache(&block) <add> yield <add> end <ide> end <ide> <ide> class TemplateDigestorTest < ActionView::TestCase
1
PHP
PHP
fix auth adapter loading without app.namespace
7b17f37d5882c678f49bdaceeec51d8deaa1a37f
<ide><path>src/Core/App.php <ide> public static function className(string $class, string $type = '', string $suffi <ide> } <ide> <ide> [$plugin, $name] = pluginSplit($class); <del> $base = $plugin ?: Configure::read('App.namespace'); <del> $base = str_replace('/', '\\', rtrim($base, '\\')); <ide> $fullname = '\\' . str_replace('/', '\\', $type . '\\' . $name) . $suffix; <ide> <del> if (static::_classExistsInBase($fullname, $base)) { <del> /** @var class-string */ <del> return $base . $fullname; <add> $base = $plugin ?: Configure::read('App.namespace'); <add> if ($base !== null) { <add> $base = str_replace('/', '\\', rtrim($base, '\\')); <add> <add> if (static::_classExistsInBase($fullname, $base)) { <add> /** @var class-string */ <add> return $base . $fullname; <add> } <ide> } <ide> <ide> if ($plugin || !static::_classExistsInBase($fullname, 'Cake')) { <ide><path>tests/TestCase/Core/AppTest.php <ide> public function testClassNameWithFqcn(): void <ide> $this->assertNull(App::className('\Foo')); <ide> } <ide> <add> /** <add> * @link https://github.com/cakephp/cakephp/issues/16258 <add> */ <add> public function testClassNameWithAppNamespaceUnset(): void <add> { <add> Configure::delete('App.namespace'); <add> <add> $result = App::className('Mysql', 'Database/Driver'); <add> $this->assertSame(Mysql::class, $result); <add> } <add> <ide> /** <ide> * testShortName <ide> *
2
PHP
PHP
remove the extra space
60f1b62e8209350e8ceaa0407e5e2cfc0ea79f5c
<ide><path>src/Illuminate/Foundation/Support/Providers/RouteServiceProvider.php <ide> public function boot() <ide> { <ide> $this->loadRoutes(); <ide> } <del> <ide> } <ide> <ide> /**
1
Text
Text
add activejob to "welcome to rails" section
8d66866450783ea90b3415c644fee92d5e124c85
<ide><path>README.md <ide> You can read more about Action View in its [README](actionview/README.rdoc). <ide> <ide> Active Record, Action Pack, and Action View can each be used independently outside Rails. <ide> In addition to them, Rails also comes with Action Mailer ([README](actionmailer/README.rdoc)), a library <del>to generate and send emails; and Active Support ([README](activesupport/README.rdoc)), a collection of <del>utility classes and standard library extensions that are useful for Rails, and may also be used <del>independently outside Rails. <add>to generate and send emails; Active Job ([README](activejob/README.md)), a <add>framework for declaring jobs and making them run on a variety of queueing <add>backends; and Active Support ([README](activesupport/README.rdoc)), a collection <add>of utility classes and standard library extensions that are useful for Rails, <add>and may also be used independently outside Rails. <ide> <ide> ## Getting Started <ide>
1
Ruby
Ruby
add support for self-extracting `.exe` archives
82482f4787e61bfb5a9dd0551b8941aef25b9ff0
<ide><path>Library/Homebrew/cask/lib/hbc/container.rb <ide> require "hbc/container/cab" <ide> require "hbc/container/criteria" <ide> require "hbc/container/dmg" <add>require "hbc/container/self_extracting_executable" <ide> require "hbc/container/executable" <ide> require "hbc/container/generic_unar" <ide> require "hbc/container/gpg" <ide> def self.autodetect_containers <ide> Ttf, <ide> Otf, <ide> Air, <add> SelfExtractingExecutable, <ide> Cab, <ide> Dmg, <ide> SevenZip, <ide><path>Library/Homebrew/cask/lib/hbc/container/self_extracting_executable.rb <add>require "hbc/container/generic_unar" <add> <add>module Hbc <add> class Container <add> class SelfExtractingExecutable < GenericUnar <add> def self.can_extract?(path:, magic_number:) <add> return false unless magic_number.match?(/\AMZ/n) <add> <add> SystemCommand.run("file", <add> args: [path], <add> print_stderr: false).stdout.include?("self-extracting") <add> end <add> end <add> end <add>end
2
Text
Text
add note for fs.watch virtualized env
ae0f68d6e150cbfe18d34b5345c27099df1e7b8b
<ide><path>doc/api/fs.md <ide> to be notified of filesystem changes. <ide> * On Windows systems, this feature depends on `ReadDirectoryChangesW`. <ide> <ide> If the underlying functionality is not available for some reason, then <del>`fs.watch` will not be able to function. For example, watching files or <del>directories on network file systems (NFS, SMB, etc.) often doesn't work <del>reliably or at all. <add>`fs.watch` will not be able to function. For example, watching files or <add>directories can be unreliable, and in some cases impossible, on network file <add>systems (NFS, SMB, etc), or host file systems when using virtualization software <add>such as Vagrant, Docker, etc. <ide> <ide> You can still use `fs.watchFile`, which uses stat polling, but it is slower and <ide> less reliable.
1
Text
Text
update resnet readme
19d930c326134bda9d03ebc6ea67050991b35746
<ide><path>official/vision/image_classification/README.md <ide> For more information about other types of models, please refer to this <ide> Similar to the [estimator implementation](../../r1/resnet), the Keras <ide> implementation has code for the ImageNet dataset. The ImageNet <ide> version uses a ResNet50 model implemented in <del>[`resnet_model.py`](./resnet_model.py). <add>[`resnet_model.py`](./resnet/resnet_model.py). <ide> <ide> Please make sure that you have the latest version of TensorFlow <ide> installed and <ide> provide a few options. <ide> Once your dataset is ready, you can begin training the model as follows: <ide> <ide> ```bash <del>python resnet_imagenet_main.py <add>python resnet/resnet_imagenet_main.py <ide> ``` <ide> <ide> Again, if you did not download the data to the default directory, specify the <ide> location with the `--data_dir` flag: <ide> <ide> ```bash <del>python resnet_imagenet_main.py --data_dir=/path/to/imagenet <add>python resnet/resnet_imagenet_main.py --data_dir=/path/to/imagenet <ide> ``` <ide> <ide> There are more flag options you can specify. Here are some examples: <ide> For example, this is a typical command line to run with ImageNet data with <ide> batch size 128 per GPU: <ide> <ide> ```bash <del>python -m resnet_imagenet_main \ <add>python -m resnet/resnet_imagenet_main.py \ <ide> --model_dir=/tmp/model_dir/something \ <ide> --num_gpus=2 \ <ide> --batch_size=128 \ <ide> From a GCE VM, you can run the following command to train ResNet for one epoch <ide> on a v2-8 or v3-8 TPU: <ide> <ide> ```bash <del>python resnet_ctl_imagenet_main.py \ <add>python resnet/resnet_ctl_imagenet_main.py \ <ide> --tpu=$TPU_NAME \ <ide> --model_dir=$MODEL_DIR \ <ide> --data_dir=$DATA_DIR \ <ide> python resnet_ctl_imagenet_main.py \ <ide> To train the ResNet to convergence, run it for 90 epochs: <ide> <ide> ```bash <del>python resnet_ctl_imagenet_main.py \ <add>python resnet/resnet_ctl_imagenet_main.py \ <ide> --tpu=$TPU_NAME \ <ide> --model_dir=$MODEL_DIR \ <ide> --data_dir=$DATA_DIR \
1
Javascript
Javascript
add validation to profile image url
914ff44f747670ab53b3d2ba1853fa8e032f4313
<ide><path>client/src/components/settings/About.js <ide> import PropTypes from 'prop-types'; <ide> import { <ide> FormGroup, <ide> ControlLabel, <del> FormControl <add> FormControl, <add> HelpBlock, <add> Alert <ide> } from '@freecodecamp/react-bootstrap'; <ide> <ide> import { FullWidthRow, Spacer } from '../helpers'; <ide> const propTypes = { <ide> class AboutSettings extends Component { <ide> constructor(props) { <ide> super(props); <del> <add> this.validationImage = new Image(); <ide> const { name = '', location = '', picture = '', about = '' } = props; <ide> const values = { <ide> name, <ide> class AboutSettings extends Component { <ide> this.state = { <ide> formValues: { ...values }, <ide> originalValues: { ...values }, <del> formClicked: false <add> formClicked: false, <add> isPictureUrlValid: true <ide> }; <ide> } <ide> <ide> class AboutSettings extends Component { <ide> <ide> isFormPristine = () => { <ide> const { formValues, originalValues } = this.state; <del> return Object.keys(originalValues) <del> .map(key => originalValues[key] === formValues[key]) <del> .every(bool => bool); <add> return ( <add> this.state.isPictureUrlValid === false || <add> Object.keys(originalValues) <add> .map(key => originalValues[key] === formValues[key]) <add> .every(bool => bool) <add> ); <ide> }; <ide> <ide> handleSubmit = e => { <ide> e.preventDefault(); <ide> const { formValues } = this.state; <ide> const { submitNewAbout } = this.props; <del> return this.setState({ formClicked: true }, () => <del> submitNewAbout(formValues) <del> ); <add> if (this.state.isPictureUrlValid === true) { <add> return this.setState({ formClicked: true }, () => <add> submitNewAbout(formValues) <add> ); <add> } else { <add> return false; <add> } <ide> }; <ide> <ide> handleNameChange = e => { <ide> class AboutSettings extends Component { <ide> })); <ide> }; <ide> <add> componentDidMount() { <add> this.validationImage.addEventListener('error', this.errorEvent); <add> this.validationImage.addEventListener('load', this.loadEvent); <add> } <add> <add> componentWillUnmount() { <add> this.validationImage.removeEventListener('load', this.loadEvent); <add> this.validationImage.removeEventListener('error', this.errorEvent); <add> } <add> <add> loadEvent = () => this.setState({ isPictureUrlValid: true }); <add> errorEvent = () => this.setState({ isPictureUrlValid: false }); <add> <ide> handlePictureChange = e => { <ide> const value = e.target.value.slice(0); <add> this.validationImage.src = value; <ide> return this.setState(state => ({ <ide> formValues: { <ide> ...state.formValues, <ide> class AboutSettings extends Component { <ide> })); <ide> }; <ide> <add> showImageValidationWarning = () => { <add> const { t } = this.props; <add> if (this.state.isPictureUrlValid === false) { <add> return ( <add> <HelpBlock> <add> <Alert bsStyle='info'>{t('validation.url-not-image')}</Alert> <add> </HelpBlock> <add> ); <add> } else { <add> return true; <add> } <add> }; <add> <ide> handleAboutChange = e => { <ide> const value = e.target.value.slice(0); <ide> return this.setState(state => ({ <ide> class AboutSettings extends Component { <ide> type='url' <ide> value={picture} <ide> /> <add> {this.showImageValidationWarning()} <ide> </FormGroup> <ide> <FormGroup controlId='about-about'> <ide> <ControlLabel> <ide><path>cypress/integration/settings/image-picture-check.js <add>/* global cy */ <add> <add>describe('Picture input field', () => { <add> beforeEach(() => { <add> cy.login(); <add> cy.visit('/settings'); <add> // Setting aliases here <add> cy.get('input#about-picture').as('pictureInput'); <add> }); <add> <add> it('Should be possible to type', () => { <add> cy.get('@pictureInput') <add> .clear({ force: true }) <add> .type('twaha', { force: true }) <add> .should('have.attr', 'value', 'twaha'); <add> }); <add> it('Show an error message if an incorrect url was submitted', () => { <add> cy.get('@pictureInput') <add> .clear({ force: true }) <add> .type('https://s3.amazonaws.com/freecodecamp/camper-image', { <add> force: true <add> }) <add> .then(() => { <add> cy.contains('URL must link directly to an image file'); <add> }); <add> }); <add> it('Can submit a correct URL', () => { <add> cy.get('@pictureInput') <add> .clear({ force: true }) <add> .type( <add> 'https://s3.amazonaws.com/freecodecamp/camper-image-placeholder.png', <add> { <add> force: true <add> } <add> ); <add> cy.wait(500); <add> cy.get('#camper-identity > .btn').should('not.be.disabled'); <add> }); <add>});
2
Ruby
Ruby
remove warning from big integer test
c33c03e80cbe9f27274b45fe55f93bad3af988fb
<ide><path>activemodel/test/cases/type/big_integer_test.rb <ide> def test_type_cast_big_integer <ide> <ide> def test_small_values <ide> type = Type::BigInteger.new <del> assert_equal -9999999999999999999999999999999, type.serialize(-9999999999999999999999999999999) <add> assert_equal(-9999999999999999999999999999999, type.serialize(-9999999999999999999999999999999)) <ide> end <ide> <ide> def test_large_values
1
Ruby
Ruby
keep preloader#preload api the same as before
9c423e0c85eb99e133fe45dd631f0eecb3adec2d
<ide><path>activerecord/lib/active_record/associations/preloader.rb <ide> def call <ide> build_preloaders <ide> end <ide> <del> def preload(records, associations, preload_scope) <add> def preload(records, associations, preload_scope = nil) <ide> ActiveSupport::Deprecation.warn("`preload` is deprecated and will be removed in Rails 7.0. Call `Preloader.new(kwargs).call` instead.") <ide> <ide> Preloader.new(records: records, associations: associations, scope: preload_scope).call
1
Javascript
Javascript
check turbomodules first in turbomoduleregistry
20102ef5b149f322347d87e4c310036704ef1a50
<ide><path>Libraries/TurboModule/TurboModuleRegistry.js <ide> import invariant from 'invariant'; <ide> const turboModuleProxy = global.__turboModuleProxy; <ide> <ide> export function get<T: TurboModule>(name: string): ?T { <add> if (turboModuleProxy != null) { <add> const module: ?T = turboModuleProxy(name); <add> if (module != null) { <add> return module; <add> } <add> } <add> <ide> // Backward compatibility layer during migration. <ide> const legacyModule = NativeModules[name]; <ide> if (legacyModule != null) { <ide> return ((legacyModule: any): T); <ide> } <ide> <del> if (turboModuleProxy != null) { <del> const module: ?T = turboModuleProxy(name); <del> return module; <del> } <del> <ide> return null; <ide> } <ide>
1
Javascript
Javascript
update the version for building release notes
3cd651669cc1668720465231fcafd848784d6640
<ide><path>build/release-notes.js <ide> var fs = require("fs"), <ide> extract = /<a href="\/ticket\/(\d+)" title="View ticket">(.*?)<[^"]+"component">\s*(\S+)/g; <ide> <ide> var opts = { <del> version: "1.6.3 RC 1", <del> short_version: "1.6.3rc1", <del> final_version: "1.6.3", <add> version: "1.7", <add> short_version: "1.7", <add> final_version: "1.7", <ide> categories: [] <ide> }; <ide>
1
PHP
PHP
remove helpers constant
e63f0aa28f55c5126a4fd797193a5ba904c86e11
<ide><path>lib/Cake/bootstrap.php <ide> */ <ide> define('APPLIBS', APP.'Lib'.DS); <ide> <del>/** <del> * Path to the application's helpers directory. <del> */ <del> define('HELPERS', VIEWS.'Helper'.DS); <del> <ide> /** <ide> * Path to the application's view's layouts directory. <ide> */
1
PHP
PHP
add event transactioncommitting
3b26f7a1ef2f04a3c1dfd6454eed4385e2399152
<ide><path>src/Illuminate/Database/Concerns/ManagesTransactions.php <ide> public function transaction(Closure $callback, $attempts = 1) <ide> <ide> try { <ide> if ($this->transactions == 1) { <add> $this->fireConnectionEvent('committing'); <ide> $this->getPdo()->commit(); <ide> } <ide> <ide> protected function handleBeginTransactionException(Throwable $e) <ide> */ <ide> public function commit() <ide> { <del> if ($this->transactions == 1) { <add> if ($this->transactionLevel() == 1) { <add> $this->fireConnectionEvent('committing'); <ide> $this->getPdo()->commit(); <ide> } <ide> <ide><path>src/Illuminate/Database/Connection.php <ide> use Illuminate\Database\Events\StatementPrepared; <ide> use Illuminate\Database\Events\TransactionBeginning; <ide> use Illuminate\Database\Events\TransactionCommitted; <add>use Illuminate\Database\Events\TransactionCommitting; <ide> use Illuminate\Database\Events\TransactionRolledBack; <ide> use Illuminate\Database\Query\Builder as QueryBuilder; <ide> use Illuminate\Database\Query\Expression; <ide> protected function fireConnectionEvent($event) <ide> return $this->events?->dispatch(match ($event) { <ide> 'beganTransaction' => new TransactionBeginning($this), <ide> 'committed' => new TransactionCommitted($this), <add> 'committing' => new TransactionCommitting($this), <ide> 'rollingBack' => new TransactionRolledBack($this), <ide> default => null, <ide> }); <ide><path>src/Illuminate/Database/Events/TransactionCommitting.php <add><?php <add> <add>namespace Illuminate\Database\Events; <add> <add>class TransactionCommitting extends ConnectionEvent <add>{ <add> // <add>} <ide><path>tests/Database/DatabaseConnectionTest.php <ide> use Illuminate\Database\Events\QueryExecuted; <ide> use Illuminate\Database\Events\TransactionBeginning; <ide> use Illuminate\Database\Events\TransactionCommitted; <add>use Illuminate\Database\Events\TransactionCommitting; <ide> use Illuminate\Database\Events\TransactionRolledBack; <ide> use Illuminate\Database\MultipleColumnsSelectedException; <ide> use Illuminate\Database\Query\Builder as BaseBuilder; <ide> public function testCommittedFiresEventsIfSet() <ide> $connection->commit(); <ide> } <ide> <add> public function testCommittingFiresEventsIfSet() <add> { <add> $pdo = $this->createMock(DatabaseConnectionTestMockPDO::class); <add> $connection = $this->getMockConnection(['getName', 'transactionLevel'], $pdo); <add> $connection->expects($this->any())->method('getName')->willReturn('name'); <add> $connection->expects($this->any())->method('transactionLevel')->willReturn(1); <add> $connection->setEventDispatcher($events = m::mock(Dispatcher::class)); <add> $events->shouldReceive('dispatch')->once()->with(m::type(TransactionCommitting::class)); <add> $events->shouldReceive('dispatch')->once()->with(m::type(TransactionCommitted::class)); <add> $connection->commit(); <add> } <add> <ide> public function testRollBackedFiresEventsIfSet() <ide> { <ide> $pdo = $this->createMock(DatabaseConnectionTestMockPDO::class);
4
Javascript
Javascript
make ember.checkbox extend from ember.component
e271685e96f0137e3042a480c33c23896b483acc
<ide><path>packages/ember-views/lib/views/checkbox.js <ide> import { get } from "ember-metal/property_get"; <ide> import { set } from "ember-metal/property_set"; <del>import View from "ember-views/views/view"; <add>import EmberComponent from "ember-views/views/component"; <ide> <ide> /** <ide> @module ember <ide> import View from "ember-views/views/view"; <ide> <ide> @class Checkbox <ide> @namespace Ember <del> @extends Ember.View <add> @extends Ember.Component <ide> @public <ide> */ <del>// 2.0TODO: Subclass Component rather than View <del>export default View.extend({ <add>export default EmberComponent.extend({ <ide> instrumentDisplay: '{{input type="checkbox"}}', <ide> <ide> classNames: ['ember-checkbox'], <ide><path>packages/ember-views/tests/views/checkbox_test.js <ide> function set(obj, key, value) { <ide> <ide> function append() { <ide> run(function() { <del> checkboxView.appendTo('#qunit-fixture'); <add> checkboxComponent.appendTo('#qunit-fixture'); <ide> }); <ide> } <ide> <del> <del>var checkboxView, dispatcher; <add>var checkboxComponent, dispatcher; <ide> <ide> QUnit.module("Ember.Checkbox", { <ide> setup() { <ide> QUnit.module("Ember.Checkbox", { <ide> teardown() { <ide> run(function() { <ide> dispatcher.destroy(); <del> checkboxView.destroy(); <add> checkboxComponent.destroy(); <ide> }); <ide> } <ide> }); <ide> <ide> QUnit.test("should begin disabled if the disabled attribute is true", function() { <del> checkboxView = Checkbox.create({}); <add> checkboxComponent = Checkbox.create({}); <ide> <del> checkboxView.set('disabled', true); <add> checkboxComponent.set('disabled', true); <ide> append(); <ide> <del> ok(checkboxView.$().is(":disabled")); <add> ok(checkboxComponent.$().is(":disabled")); <ide> }); <ide> <ide> QUnit.test("should become disabled if the disabled attribute is changed", function() { <del> checkboxView = Checkbox.create({}); <add> checkboxComponent = Checkbox.create({}); <ide> <ide> append(); <del> ok(checkboxView.$().is(":not(:disabled)")); <add> ok(checkboxComponent.$().is(":not(:disabled)")); <ide> <del> run(function() { checkboxView.set('disabled', true); }); <del> ok(checkboxView.$().is(":disabled")); <add> run(function() { checkboxComponent.set('disabled', true); }); <add> ok(checkboxComponent.$().is(":disabled")); <ide> <del> run(function() { checkboxView.set('disabled', false); }); <del> ok(checkboxView.$().is(":not(:disabled)")); <add> run(function() { checkboxComponent.set('disabled', false); }); <add> ok(checkboxComponent.$().is(":not(:disabled)")); <ide> }); <ide> <ide> QUnit.test("should begin indeterminate if the indeterminate attribute is true", function() { <del> checkboxView = Checkbox.create({}); <add> checkboxComponent = Checkbox.create({}); <ide> <del> checkboxView.set('indeterminate', true); <add> checkboxComponent.set('indeterminate', true); <ide> append(); <ide> <del> equal(checkboxView.$().prop('indeterminate'), true, "Checkbox should be indeterminate"); <add> equal(checkboxComponent.$().prop('indeterminate'), true, "Checkbox should be indeterminate"); <ide> }); <ide> <ide> QUnit.test("should become indeterminate if the indeterminate attribute is changed", function() { <del> checkboxView = Checkbox.create({}); <add> checkboxComponent = Checkbox.create({}); <ide> <ide> append(); <ide> <del> equal(checkboxView.$().prop('indeterminate'), false, "Checkbox should not be indeterminate"); <add> equal(checkboxComponent.$().prop('indeterminate'), false, "Checkbox should not be indeterminate"); <ide> <del> run(function() { checkboxView.set('indeterminate', true); }); <del> equal(checkboxView.$().prop('indeterminate'), true, "Checkbox should be indeterminate"); <add> run(function() { checkboxComponent.set('indeterminate', true); }); <add> equal(checkboxComponent.$().prop('indeterminate'), true, "Checkbox should be indeterminate"); <ide> <del> run(function() { checkboxView.set('indeterminate', false); }); <del> equal(checkboxView.$().prop('indeterminate'), false, "Checkbox should not be indeterminate"); <add> run(function() { checkboxComponent.set('indeterminate', false); }); <add> equal(checkboxComponent.$().prop('indeterminate'), false, "Checkbox should not be indeterminate"); <ide> }); <ide> <ide> QUnit.test("should support the tabindex property", function() { <del> checkboxView = Checkbox.create({}); <add> checkboxComponent = Checkbox.create({}); <ide> <del> run(function() { checkboxView.set('tabindex', 6); }); <add> run(function() { checkboxComponent.set('tabindex', 6); }); <ide> append(); <ide> <del> equal(checkboxView.$().prop('tabindex'), '6', 'the initial checkbox tabindex is set in the DOM'); <add> equal(checkboxComponent.$().prop('tabindex'), '6', 'the initial checkbox tabindex is set in the DOM'); <ide> <del> run(function() { checkboxView.set('tabindex', 3); }); <del> equal(checkboxView.$().prop('tabindex'), '3', 'the checkbox tabindex changes when it is changed in the view'); <add> run(function() { checkboxComponent.set('tabindex', 3); }); <add> equal(checkboxComponent.$().prop('tabindex'), '3', 'the checkbox tabindex changes when it is changed in the component'); <ide> }); <ide> <ide> QUnit.test("checkbox name is updated when setting name property of view", function() { <del> checkboxView = Checkbox.create({}); <add> checkboxComponent = Checkbox.create({}); <ide> <del> run(function() { checkboxView.set('name', 'foo'); }); <add> run(function() { checkboxComponent.set('name', 'foo'); }); <ide> append(); <ide> <del> equal(checkboxView.$().attr('name'), "foo", "renders checkbox with the name"); <add> equal(checkboxComponent.$().attr('name'), "foo", "renders checkbox with the name"); <ide> <del> run(function() { checkboxView.set('name', 'bar'); }); <add> run(function() { checkboxComponent.set('name', 'bar'); }); <ide> <del> equal(checkboxView.$().attr('name'), "bar", "updates checkbox after name changes"); <add> equal(checkboxComponent.$().attr('name'), "bar", "updates checkbox after name changes"); <ide> }); <ide> <ide> QUnit.test("checked property mirrors input value", function() { <del> checkboxView = Checkbox.create({}); <del> run(function() { checkboxView.append(); }); <add> checkboxComponent = Checkbox.create({}); <add> run(function() { checkboxComponent.append(); }); <ide> <del> equal(get(checkboxView, 'checked'), false, "initially starts with a false value"); <del> equal(!!checkboxView.$().prop('checked'), false, "the initial checked property is false"); <add> equal(get(checkboxComponent, 'checked'), false, "initially starts with a false value"); <add> equal(!!checkboxComponent.$().prop('checked'), false, "the initial checked property is false"); <ide> <del> set(checkboxView, 'checked', true); <add> set(checkboxComponent, 'checked', true); <ide> <del> equal(checkboxView.$().prop('checked'), true, "changing the value property changes the DOM"); <add> equal(checkboxComponent.$().prop('checked'), true, "changing the value property changes the DOM"); <ide> <del> run(function() { checkboxView.remove(); }); <del> run(function() { checkboxView.append(); }); <add> run(function() { checkboxComponent.remove(); }); <add> run(function() { checkboxComponent.append(); }); <ide> <del> equal(checkboxView.$().prop('checked'), true, "changing the value property changes the DOM"); <add> equal(checkboxComponent.$().prop('checked'), true, "changing the value property changes the DOM"); <ide> <del> run(function() { checkboxView.remove(); }); <del> run(function() { set(checkboxView, 'checked', false); }); <del> run(function() { checkboxView.append(); }); <add> run(function() { checkboxComponent.remove(); }); <add> run(function() { set(checkboxComponent, 'checked', false); }); <add> run(function() { checkboxComponent.append(); }); <ide> <del> equal(checkboxView.$().prop('checked'), false, "changing the value property changes the DOM"); <add> equal(checkboxComponent.$().prop('checked'), false, "changing the value property changes the DOM"); <ide> }); <ide> <ide> QUnit.test("checking the checkbox updates the value", function() { <del> checkboxView = Checkbox.create({ checked: true }); <add> checkboxComponent = Checkbox.create({ checked: true }); <ide> append(); <ide> <del> equal(get(checkboxView, 'checked'), true, "precond - initially starts with a true value"); <del> equal(!!checkboxView.$().prop('checked'), true, "precond - the initial checked property is true"); <add> equal(get(checkboxComponent, 'checked'), true, "precond - initially starts with a true value"); <add> equal(!!checkboxComponent.$().prop('checked'), true, "precond - the initial checked property is true"); <ide> <ide> // IE fires 'change' event on blur. <del> checkboxView.$()[0].focus(); <del> checkboxView.$()[0].click(); <del> checkboxView.$()[0].blur(); <add> checkboxComponent.$()[0].focus(); <add> checkboxComponent.$()[0].click(); <add> checkboxComponent.$()[0].blur(); <ide> <del> equal(!!checkboxView.$().prop('checked'), false, "after clicking a checkbox, the checked property changed"); <del> equal(get(checkboxView, 'checked'), false, "changing the checkbox causes the view's value to get updated"); <add> equal(!!checkboxComponent.$().prop('checked'), false, "after clicking a checkbox, the checked property changed"); <add> equal(get(checkboxComponent, 'checked'), false, "changing the checkbox causes the view's value to get updated"); <ide> });
2
Ruby
Ruby
add env to allow unlinked deps
efc1f1c7da50e77e96a4324c9380e19848dcf03d
<ide><path>Library/Homebrew/formula_installer.rb <ide> def check_install_sanity <ide> end <ide> end <ide> <del> unlinked_deps = recursive_formulae.select do |dep| <del> dep.installed? && !dep.keg_only? && !dep.linked_keg.directory? <del> end <add> unless ENV["HOMEBREW_NO_CHECK_UNLINKED_DEPENDENCIES"] <add> unlinked_deps = recursive_formulae.select do |dep| <add> dep.installed? && !dep.keg_only? && !dep.linked_keg.directory? <add> end <ide> <del> unless unlinked_deps.empty? <del> raise CannotInstallFormulaError, "You must `brew link #{unlinked_deps*" "}` before #{formula.full_name} can be installed" <add> unless unlinked_deps.empty? <add> raise CannotInstallFormulaError, "You must `brew link #{unlinked_deps*" "}` before #{formula.full_name} can be installed" <add> end <ide> end <ide> <ide> pinned_unsatisfied_deps = recursive_deps.select do |dep|
1
Python
Python
test xla examples
0533cf470659b97c6279bd04f65536a1ec88404a
<ide><path>examples/test_xla_examples.py <add># coding=utf-8 <add># Copyright 2018 HuggingFace Inc.. <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>import argparse <add>import logging <add>import sys <add>import unittest <add>from time import time <add>from unittest.mock import patch <add> <add>from transformers.testing_utils import require_torch_tpu <add> <add> <add>logging.basicConfig(level=logging.DEBUG) <add> <add>logger = logging.getLogger() <add> <add> <add>def get_setup_file(): <add> parser = argparse.ArgumentParser() <add> parser.add_argument("-f") <add> args = parser.parse_args() <add> return args.f <add> <add> <add>@require_torch_tpu <add>class TorchXLAExamplesTests(unittest.TestCase): <add> def test_run_glue(self): <add> import xla_spawn <add> <add> stream_handler = logging.StreamHandler(sys.stdout) <add> logger.addHandler(stream_handler) <add> <add> output_directory = "run_glue_output" <add> <add> testargs = f""" <add> text-classification/run_glue.py <add> --num_cores=8 <add> text-classification/run_glue.py <add> --do_train <add> --do_eval <add> --task_name=MRPC <add> --data_dir=../glue_data/MRPC <add> --cache_dir=./cache_dir <add> --num_train_epochs=1 <add> --max_seq_length=128 <add> --learning_rate=3e-5 <add> --output_dir={output_directory} <add> --overwrite_output_dir <add> --logging_steps=5 <add> --save_steps=5 <add> --overwrite_cache <add> --tpu_metrics_debug <add> --model_name_or_path=bert-base-cased <add> --per_device_train_batch_size=64 <add> --per_device_eval_batch_size=64 <add> --evaluate_during_training <add> --overwrite_cache <add> """.split() <add> with patch.object(sys, "argv", testargs): <add> start = time() <add> xla_spawn.main() <add> end = time() <add> <add> result = {} <add> with open(f"{output_directory}/eval_results_mrpc.txt") as f: <add> lines = f.readlines() <add> for line in lines: <add> key, value = line.split(" = ") <add> result[key] = float(value) <add> <add> del result["eval_loss"] <add> for value in result.values(): <add> # Assert that the model trains <add> self.assertGreaterEqual(value, 0.70) <add> <add> # Assert that the script takes less than 100 seconds to make sure it doesn't hang. <add> self.assertLess(end - start, 100) <ide><path>src/transformers/testing_utils.py <ide> import unittest <ide> from distutils.util import strtobool <ide> <del>from transformers.file_utils import _tf_available, _torch_available <add>from transformers.file_utils import _tf_available, _torch_available, _torch_tpu_available <ide> <ide> <ide> SMALL_MODEL_IDENTIFIER = "julien-c/bert-xsmall-dummy" <ide> def require_multigpu(test_case): <ide> return test_case <ide> <ide> <add>def require_torch_tpu(test_case): <add> """ <add> Decorator marking a test that requires a TPU (in PyTorch). <add> """ <add> if not _torch_tpu_available: <add> return unittest.skip("test requires PyTorch TPU") <add> <add> return test_case <add> <add> <ide> if _torch_available: <ide> # Set the USE_CUDA environment variable to select a GPU. <ide> torch_device = "cuda" if parse_flag_from_env("USE_CUDA") else "cpu"
2
Javascript
Javascript
add onerror to reactdomimg to complement onload
cda1d8c779f589639fa8d33dbb63b6ec1b0edfce
<ide><path>src/browser/dom/components/ReactDOMImg.js <ide> var ReactDOMImg = ReactCompositeComponent.createClass({ <ide> }, <ide> <ide> componentDidMount: function() { <add> var node = this.getDOMNode(); <ide> ReactEventEmitter.trapBubbledEvent( <ide> EventConstants.topLevelTypes.topLoad, <ide> 'load', <del> this.getDOMNode() <add> node <add> ); <add> ReactEventEmitter.trapBubbledEvent( <add> EventConstants.topLevelTypes.topError, <add> 'error', <add> node <ide> ); <ide> } <ide> }); <ide><path>src/browser/eventPlugins/SimpleEventPlugin.js <ide> var eventTypes = { <ide> captured: keyOf({onLoadCapture: true}) <ide> } <ide> }, <add> error: { <add> phasedRegistrationNames: { <add> bubbled: keyOf({onError: true}), <add> captured: keyOf({onErrorCapture: true}) <add> } <add> }, <ide> // Note: We do not allow listening to mouseOver events. Instead, use the <ide> // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. <ide> mouseDown: { <ide> var topLevelEventsToDispatchConfig = { <ide> topDragOver: eventTypes.dragOver, <ide> topDragStart: eventTypes.dragStart, <ide> topDrop: eventTypes.drop, <add> topError: eventTypes.error, <ide> topFocus: eventTypes.focus, <ide> topInput: eventTypes.input, <ide> topKeyDown: eventTypes.keyDown, <ide> var SimpleEventPlugin = { <ide> switch (topLevelType) { <ide> case topLevelTypes.topInput: <ide> case topLevelTypes.topLoad: <add> case topLevelTypes.topError: <ide> case topLevelTypes.topReset: <ide> case topLevelTypes.topSubmit: <ide> // HTML Events <ide><path>src/event/EventConstants.js <ide> var topLevelTypes = keyMirror({ <ide> topDragOver: null, <ide> topDragStart: null, <ide> topDrop: null, <add> topError: null, <ide> topFocus: null, <ide> topInput: null, <ide> topKeyDown: null,
3
PHP
PHP
remove php 5 and file names from docblocks
b3d00446dcf796d9eff079cfd71cb4e81d45560f
<ide><path>src/Console/Error/ConsoleException.php <ide> <?php <ide> /** <del> * ConsoleException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Console/Error/MissingShellException.php <ide> <?php <ide> /** <del> * MissingShellException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Console/Error/MissingShellMethodException.php <ide> <?php <ide> /** <del> * MissingShellMethodException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Console/Error/MissingTaskException.php <ide> <?php <ide> /** <del> * MissingTaskException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Controller/Error/MissingActionException.php <ide> <?php <ide> /** <del> * MissingActionException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Controller/Error/MissingComponentException.php <ide> <?php <ide> /** <del> * MissingComponentException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Controller/Error/MissingControllerException.php <ide> <?php <ide> /** <del> * MissingControllerException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Core/App.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Core/ClassLoader.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Core/Error/MissingPluginException.php <ide> <?php <ide> /** <del> * MissingPluginException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Datasource/ConnectionRegistry.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Datasource/Error/MissingDatasourceConfigException.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Datasource/Error/MissingDatasourceException.php <ide> <?php <ide> /** <del> * MissingDatasourceException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/BadRequestException.php <ide> <?php <ide> /** <del> * BadRequestException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/BaseException.php <ide> <?php <ide> /** <del> * BaseException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/Exception.php <ide> <?php <ide> /** <del> * Exception class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/FatalErrorException.php <ide> <?php <ide> /** <del> * FatalErrorException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/ForbiddenException.php <ide> <?php <ide> /** <del> * ForbiddenException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/HttpException.php <ide> <?php <ide> /** <del> * HttpException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/InternalErrorException.php <ide> <?php <ide> /** <del> * InternalErrorException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/MethodNotAllowedException.php <ide> <?php <ide> /** <del> * MethodNotAllowedException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/NotFoundException.php <ide> <?php <ide> /** <del> * NotFoundException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/NotImplementedException.php <ide> <?php <ide> /** <del> * NotImplementedException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Error/UnauthorizedException.php <ide> <?php <ide> /** <del> * UnauthorizedException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Network/Error/SocketException.php <ide> <?php <ide> /** <del> * SocketException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/ORM/Error/MissingBehaviorException.php <ide> <?php <ide> /** <del> * MissingBehaviorException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Routing/Error/MissingDispatcherFilterException.php <ide> <?php <ide> /** <del> * MissingDispatcherFilterException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/Utility/Error/XmlException.php <ide> <?php <ide> /** <del> * XmlException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/View/Error/MissingHelperException.php <ide> <?php <ide> /** <del> * MissingHelperException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/View/Error/MissingLayoutException.php <ide> <?php <ide> /** <del> * MissingLayoutException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>src/View/Error/MissingViewException.php <ide> <?php <ide> /** <del> * MissingViewException class <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/ArticleFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/TestCase/Cache/Engine/MemcachedEngineTest.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/TestCase/Controller/ComponentTest.php <ide> <?php <ide> /** <del> * ComponentTest file <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing> <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/TestCase/Core/AppTest.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/TestCase/Datasource/ConnectionManagerTest.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * Licensed under The MIT License <ide> * For full copyright and license information, please see the LICENSE.txt <ide> * Redistributions of files must retain the above copyright notice <ide><path>tests/TestCase/Log/Engine/ConsoleLogTest.php <ide> <?php <ide> /** <del> * ConsoleLogTest file <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/TestCase/Routing/DispatcherTest.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/TestCase/Utility/StringTest.php <ide> <?php <ide> /** <del> * StringTest file <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/TestCase/Validation/ValidationRuleTest.php <ide> <?php <ide> /** <del> * ValidationRuleTest file <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> <?php <ide> /** <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/Plugin/Company/TestPluginThree/Utility/Hello.php <ide> <?php <ide> /** <del> * Test class for plugins with multiple namespace levels <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/Plugin/TestPlugin/View/Helper/OtherHelperHelper.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/AjaxAuthController.php <ide> <?php <ide> /** <del> * AjaxAuthController <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/AuthTestController.php <ide> <?php <ide> /** <del> * AuthTestController <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/Component/AppleComponent.php <ide> <?php <ide> /** <del> * AppleComponent <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/Component/BananaComponent.php <ide> <?php <ide> /** <del> * BananaComponent <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/Component/MergeVarComponent.php <ide> <?php <ide> /** <del> * MergeVarComponent <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/Component/MutuallyReferencingOneComponent.php <ide> <?php <ide> /** <del> * MutuallyReferencingOneComponent <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/Component/MutuallyReferencingTwoComponent.php <ide> <?php <ide> /** <del> * MutuallyReferencingTwoComponent <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/Component/ParamTestComponent.php <ide> <?php <ide> /** <del> * ParamTestComponent <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/Component/SomethingWithCookieComponent.php <ide> <?php <ide> /** <del> * SomethingWithCookieComponent <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/Component/TestAuthComponent.php <ide> <?php <ide> /** <del> * TestAuthComponent <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/ComponentTestController.php <ide> <?php <ide> /** <del> * ComponentTestController <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/OrangeSessionTestController.php <ide> <?php <ide> /** <del> * OrangeSessionTestController <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/Controller/RequestActionController.php <ide> <?php <ide> /** <del> * RequestActionController file <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing> <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/test_app/TestApp/View/CustomJsonView.php <ide> <?php <ide> /** <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> *
57
PHP
PHP
fix missing namespace
90591369bf6ee1d3d40c61fb1f264b680613abf8
<ide><path>lib/Cake/Controller/Component/PaginatorComponent.php <ide> <ide> use Cake\Controller\Component; <ide> use Cake\Controller\ComponentCollection; <add>use Cake\Model\Model; <ide> use Cake\Error; <ide> use Cake\Utility\Hash; <ide>
1
Java
Java
translate ioexception to httpmessagenotreadableex
ffd9c62fc8b7cbeb5fbbc9a4fd487b1284a0b264
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java <ide> protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, Me <ide> } <ide> <ide> HttpMethod httpMethod = ((HttpRequest) inputMessage).getMethod(); <del> inputMessage = new EmptyBodyCheckingHttpInputMessage(inputMessage); <ide> Object body = NO_VALUE; <ide> <del> for (HttpMessageConverter<?> converter : this.messageConverters) { <del> Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass(); <del> if (converter instanceof GenericHttpMessageConverter) { <del> GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter; <del> if (genericConverter.canRead(targetType, contextClass, contentType)) { <del> if (logger.isDebugEnabled()) { <del> logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]"); <del> } <del> if (inputMessage.getBody() != null) { <del> inputMessage = getAdvice().beforeBodyRead(inputMessage, param, targetType, converterType); <del> body = genericConverter.read(targetType, contextClass, inputMessage); <del> body = getAdvice().afterBodyRead(body, inputMessage, param, targetType, converterType); <del> } <del> else { <del> body = null; <del> body = getAdvice().handleEmptyBody(body, inputMessage, param, targetType, converterType); <add> try { <add> inputMessage = new EmptyBodyCheckingHttpInputMessage(inputMessage); <add> <add> for (HttpMessageConverter<?> converter : this.messageConverters) { <add> Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass(); <add> if (converter instanceof GenericHttpMessageConverter) { <add> GenericHttpMessageConverter<?> genericConverter = (GenericHttpMessageConverter<?>) converter; <add> if (genericConverter.canRead(targetType, contextClass, contentType)) { <add> if (logger.isDebugEnabled()) { <add> logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]"); <add> } <add> if (inputMessage.getBody() != null) { <add> inputMessage = getAdvice().beforeBodyRead(inputMessage, param, targetType, converterType); <add> body = genericConverter.read(targetType, contextClass, inputMessage); <add> body = getAdvice().afterBodyRead(body, inputMessage, param, targetType, converterType); <add> } <add> else { <add> body = null; <add> body = getAdvice().handleEmptyBody(body, inputMessage, param, targetType, converterType); <add> } <add> break; <ide> } <del> break; <ide> } <del> } <del> else if (targetClass != null) { <del> if (converter.canRead(targetClass, contentType)) { <del> if (logger.isDebugEnabled()) { <del> logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]"); <add> else if (targetClass != null) { <add> if (converter.canRead(targetClass, contentType)) { <add> if (logger.isDebugEnabled()) { <add> logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]"); <add> } <add> if (inputMessage.getBody() != null) { <add> inputMessage = getAdvice().beforeBodyRead(inputMessage, param, targetType, converterType); <add> body = ((HttpMessageConverter<T>) converter).read(targetClass, inputMessage); <add> body = getAdvice().afterBodyRead(body, inputMessage, param, targetType, converterType); <add> } <add> else { <add> body = null; <add> body = getAdvice().handleEmptyBody(body, inputMessage, param, targetType, converterType); <add> } <add> break; <ide> } <del> if (inputMessage.getBody() != null) { <del> inputMessage = getAdvice().beforeBodyRead(inputMessage, param, targetType, converterType); <del> body = ((HttpMessageConverter<T>) converter).read(targetClass, inputMessage); <del> body = getAdvice().afterBodyRead(body, inputMessage, param, targetType, converterType); <del> } <del> else { <del> body = null; <del> body = getAdvice().handleEmptyBody(body, inputMessage, param, targetType, converterType); <del> } <del> break; <ide> } <ide> } <ide> } <add> catch (IOException ex) { <add> throw new HttpMessageNotReadableException("Could not read document: " + ex.getMessage(), ex); <add> } <ide> <ide> if (body == NO_VALUE) { <ide> if (!SUPPORTED_METHODS.contains(httpMethod)
1
Mixed
Javascript
use comma instead of space
fe001307e579be4f898913c0c1d0501e461b412d
<ide><path>examples/css/README.md <ide> module.exports = "" + __webpack_require__.p + "89a353e9c515885abd8e.png"; <ide> /******/ data = data.getPropertyValue("--webpack-" + chunkId); <ide> /******/ for(; i < data.length; i++) { <ide> /******/ var cc = data.charCodeAt(i); <del>/******/ if(cc == 32) { tokens.push(token); token = ""; } <add>/******/ if(cc == 44) { tokens.push(token); token = ""; } <ide> /******/ else if(cc == 92) { token += data[++i] } <ide> /******/ else { token += data[i]; } <ide> /******/ } <ide> body { <ide> background: red; <ide> } <ide> <del>head{--webpack-0:_4 _2 _1 _5;} <add>head{--webpack-0:_4,_2,_1,_5;} <ide> ``` <ide> <ide> # dist/1.output.css <ide><path>lib/css/CssLoadingRuntimeModule.js <ide> class CssLoadingRuntimeModule extends RuntimeModule { <ide> "for(; i < data.length; i++) {", <ide> Template.indent([ <ide> "var cc = data.charCodeAt(i);", <del> 'if(cc == 32) { tokens.push(token); token = ""; }', <add> 'if(cc == 44) { tokens.push(token); token = ""; }', <ide> "else if(cc == 92) { token += data[++i] }", <ide> "else { token += data[i]; }" <ide> ]), <ide> class CssLoadingRuntimeModule extends RuntimeModule { <ide> `tokens.forEach(${runtimeTemplate.basicFunction("token", [ <ide> `${ <ide> RuntimeGlobals.moduleFactories <del> }[token.slice(1)] = ${runtimeTemplate.basicFunction( <add> }[token.replace(/^_/, "")] = ${runtimeTemplate.basicFunction( <ide> "module, exports", <ide> [`${RuntimeGlobals.makeNamespaceObject}(exports);`] <ide> )};` <ide><path>lib/css/CssModulesPlugin.js <ide> const validateParserOptions = createSchemaValidation( <ide> } <ide> ); <ide> <del>const escapeCssIdentifierPart = str => { <del> // cspell:word uffff <del> return `${str}`.replace(/[^a-zA-Z0-9_\u0081-\uffff-]/g, s => `\\${s}`); <add>const escapeCssIdentifierPart = (str, useOptionalUnderscore) => { <add> const escaped = `${str}`.replace( <add> // cspell:word uffff <add> /[^a-zA-Z0-9_\u0081-\uffff-]/g, <add> s => `\\${s}` <add> ); <add> return useOptionalUnderscore && /^[0-9_]/.test(escaped) <add> ? `_${escaped}` <add> : escaped; <ide> }; <ide> <ide> const plugin = "CssModulesPlugin"; <ide> class CssModulesPlugin { <ide> source.add( <ide> `head{--webpack-${escapeCssIdentifierPart(chunk.id)}:${Array.from( <ide> modules, <del> m => `_${escapeCssIdentifierPart(chunkGraph.getModuleId(m))}` <del> ).join(" ")};}` <add> m => `${escapeCssIdentifierPart(chunkGraph.getModuleId(m), true)}` <add> ).join(",")};}` <ide> ); <ide> return source; <ide> } <ide><path>test/configCases/css/basic/test.config.js <ide> module.exports = { <ide> moduleScope(scope) { <ide> const link = scope.window.document.createElement("link"); <ide> link.rel = "stylesheet"; <del> link.href = "179.bundle0.css"; <add> link.href = "main.bundle0.css"; <ide> scope.window.document.head.appendChild(link); <ide> } <ide> }; <ide><path>test/configCases/css/basic/webpack.config.js <ide> /** @type {import("../../../../").Configuration} */ <ide> module.exports = { <ide> target: "web", <add> mode: "development", <ide> experiments: { <ide> css: true <ide> }
5
Python
Python
patch token classification pipeline
850afb422d13a4b77bb51cccce49c32641de0339
<ide><path>src/transformers/pipelines.py <ide> class TokenClassificationArgumentHandler(ArgumentHandler): <ide> def __call__(self, *args, **kwargs): <ide> <ide> if args is not None and len(args) > 0: <del> if isinstance(args, str): <del> inputs = [args] <del> else: <del> inputs = args <add> inputs = list(args) <ide> batch_size = len(inputs) <add> else: <add> raise ValueError("At least one input is required.") <ide> <del> offset_mapping = kwargs.get("offset_mapping", None) <add> offset_mapping = kwargs.get("offset_mapping") <ide> if offset_mapping: <ide> if isinstance(offset_mapping, list) and isinstance(offset_mapping[0], tuple): <ide> offset_mapping = [offset_mapping] <ide> if len(offset_mapping) != batch_size: <del> raise ("offset_mapping should have the same batch size as the input") <add> raise ValueError("offset_mapping should have the same batch size as the input") <ide> return inputs, offset_mapping <ide> <ide> <ide> def __init__( <ide> tokenizer: PreTrainedTokenizer, <ide> modelcard: Optional[ModelCard] = None, <ide> framework: Optional[str] = None, <del> args_parser: ArgumentHandler = None, <add> args_parser: ArgumentHandler = TokenClassificationArgumentHandler(), <ide> device: int = -1, <ide> binary_output: bool = False, <ide> ignore_labels=["O"], <ide> task: str = "", <ide> grouped_entities: bool = False, <del> ignore_subwords: bool = True, <add> ignore_subwords: bool = False, <ide> ): <ide> super().__init__( <ide> model=model, <ide> tokenizer=tokenizer, <ide> modelcard=modelcard, <ide> framework=framework, <del> args_parser=TokenClassificationArgumentHandler(), <ide> device=device, <ide> binary_output=binary_output, <ide> task=task, <ide> def __init__( <ide> ) <ide> <ide> self._basic_tokenizer = BasicTokenizer(do_lower_case=False) <add> self._args_parser = args_parser <ide> self.ignore_labels = ignore_labels <ide> self.grouped_entities = grouped_entities <ide> self.ignore_subwords = ignore_subwords <ide> <add> if self.ignore_subwords and not self.tokenizer.is_fast: <add> raise ValueError( <add> "Slow tokenizers cannot ignore subwords. Please set the `ignore_subwords` option" <add> "to `False` or use a fast tokenizer." <add> ) <add> <ide> def __call__(self, inputs: Union[str, List[str]], **kwargs): <ide> """ <ide> Classify each token of the text(s) given as inputs. <ide> def __call__(self, inputs: Union[str, List[str]], **kwargs): <ide> corresponding token in the sentence. <ide> """ <ide> <del> if isinstance(inputs, str): <del> inputs = [inputs] <del> <del> offset_mappings = kwargs.get("offset_mappings") <add> inputs, offset_mappings = self._args_parser(inputs, **kwargs) <ide> <ide> answers = [] <ide> <ide> def __call__(self, inputs: Union[str, List[str]], **kwargs): <ide> return_offsets_mapping=self.tokenizer.is_fast, <ide> ) <ide> if self.tokenizer.is_fast: <del> offset_mapping = tokens["offset_mapping"].cpu().numpy()[0] <del> del tokens["offset_mapping"] <add> offset_mapping = tokens.pop("offset_mapping").cpu().numpy()[0] <ide> elif offset_mappings: <ide> offset_mapping = offset_mappings[i] <ide> else: <del> raise Exception("To decode [UNK] tokens use a fast tokenizer or provide offset_mapping parameter") <del> special_tokens_mask = tokens["special_tokens_mask"].cpu().numpy()[0] <del> del tokens["special_tokens_mask"] <add> offset_mapping = None <add> <add> special_tokens_mask = tokens.pop("special_tokens_mask").cpu().numpy()[0] <ide> <ide> # Forward <ide> if self.framework == "tf": <ide> def __call__(self, inputs: Union[str, List[str]], **kwargs): <ide> ] <ide> <ide> for idx, label_idx in filtered_labels_idx: <del> start_ind, end_ind = offset_mapping[idx] <del> word_ref = sentence[start_ind:end_ind] <del> word = self.tokenizer.convert_ids_to_tokens([int(input_ids[idx])])[0] <del> is_subword = len(word_ref) != len(word) <del> <del> if int(input_ids[idx]) == self.tokenizer.unk_token_id: <del> word = word_ref <del> is_subword = False <add> if offset_mapping is not None: <add> start_ind, end_ind = offset_mapping[idx] <add> word_ref = sentence[start_ind:end_ind] <add> word = self.tokenizer.convert_ids_to_tokens([int(input_ids[idx])])[0] <add> is_subword = len(word_ref) != len(word) <add> <add> if int(input_ids[idx]) == self.tokenizer.unk_token_id: <add> word = word_ref <add> is_subword = False <add> else: <add> word = self.tokenizer.convert_ids_to_tokens(int(input_ids[idx])) <ide> <ide> entity = { <ide> "word": word, <ide><path>tests/test_pipelines_ner.py <ide> import unittest <ide> <ide> from transformers import AutoTokenizer, pipeline <del>from transformers.pipelines import Pipeline <add>from transformers.pipelines import Pipeline, TokenClassificationArgumentHandler <ide> from transformers.testing_utils import require_tf, require_torch <ide> <ide> from .test_pipelines_common import CustomInputPipelineCommonMixin <ide> def _test_pipeline(self, nlp: Pipeline): <ide> def test_tf_only(self): <ide> model_name = "Narsil/small" # This model only has a TensorFlow version <ide> # We test that if we don't specificy framework='tf', it gets detected automatically <del> tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) <del> nlp = pipeline(task="ner", model=model_name, tokenizer=tokenizer) <add> nlp = pipeline(task="ner", model=model_name) <ide> self._test_pipeline(nlp) <ide> <del> # offset=tokenizer(VALID_INPUTS[0],return_offsets_mapping=True)['offset_mapping'] <del> # pipeline_running_kwargs = {"offset_mapping"} # Additional kwargs to run the pipeline with <del> <ide> @require_tf <ide> def test_tf_defaults(self): <ide> for model_name in self.small_models: <ide> def test_tf_defaults(self): <ide> self._test_pipeline(nlp) <ide> <ide> @require_tf <del> def test_tf_small(self): <add> def test_tf_small_ignore_subwords_available_for_fast_tokenizers(self): <ide> for model_name in self.small_models: <del> print(model_name) <ide> tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) <ide> nlp = pipeline( <ide> task="ner", <ide> def test_tf_small(self): <ide> ) <ide> self._test_pipeline(nlp) <ide> <del> for model_name in self.small_models: <del> tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) <del> nlp = pipeline( <del> task="ner", <del> model=model_name, <del> tokenizer=tokenizer, <del> framework="tf", <del> grouped_entities=True, <del> ignore_subwords=False, <del> ) <del> self._test_pipeline(nlp) <add> for model_name in self.small_models: <add> tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) <add> nlp = pipeline( <add> task="ner", <add> model=model_name, <add> tokenizer=tokenizer, <add> framework="tf", <add> grouped_entities=True, <add> ignore_subwords=False, <add> ) <add> self._test_pipeline(nlp) <ide> <ide> @require_torch <del> def test_pt_defaults(self): <add> def test_pt_ignore_subwords_slow_tokenizer_raises(self): <ide> for model_name in self.small_models: <del> tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) <add> tokenizer = AutoTokenizer.from_pretrained(model_name) <add> <add> with self.assertRaises(ValueError): <add> pipeline(task="ner", model=model_name, tokenizer=tokenizer, ignore_subwords=True) <add> <add> @require_torch <add> def test_pt_defaults_slow_tokenizer(self): <add> for model_name in self.small_models: <add> tokenizer = AutoTokenizer.from_pretrained(model_name) <ide> nlp = pipeline(task="ner", model=model_name, tokenizer=tokenizer) <ide> self._test_pipeline(nlp) <ide> <ide> @require_torch <del> def test_torch_small(self): <add> def test_pt_defaults(self): <add> for model_name in self.small_models: <add> nlp = pipeline(task="ner", model=model_name) <add> self._test_pipeline(nlp) <add> <add> @require_torch <add> def test_pt_small_ignore_subwords_available_for_fast_tokenizers(self): <ide> for model_name in self.small_models: <ide> tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True) <ide> nlp = pipeline( <ide> def test_torch_small(self): <ide> task="ner", model=model_name, tokenizer=tokenizer, grouped_entities=True, ignore_subwords=False <ide> ) <ide> self._test_pipeline(nlp) <add> <add> <add>class TokenClassificationArgumentHandlerTestCase(unittest.TestCase): <add> def setUp(self): <add> self.args_parser = TokenClassificationArgumentHandler() <add> <add> def test_simple(self): <add> string = "This is a simple input" <add> <add> inputs, offset_mapping = self.args_parser(string) <add> self.assertEqual(inputs, [string]) <add> self.assertEqual(offset_mapping, None) <add> <add> inputs, offset_mapping = self.args_parser(string, string) <add> self.assertEqual(inputs, [string, string]) <add> self.assertEqual(offset_mapping, None) <add> <add> inputs, offset_mapping = self.args_parser(string, offset_mapping=[(0, 1), (1, 2)]) <add> self.assertEqual(inputs, [string]) <add> self.assertEqual(offset_mapping, [[(0, 1), (1, 2)]]) <add> <add> inputs, offset_mapping = self.args_parser(string, string, offset_mapping=[[(0, 1), (1, 2)], [(0, 2), (2, 3)]]) <add> self.assertEqual(inputs, [string, string]) <add> self.assertEqual(offset_mapping, [[(0, 1), (1, 2)], [(0, 2), (2, 3)]]) <add> <add> def test_errors(self): <add> string = "This is a simple input" <add> <add> # 2 sentences, 1 offset_mapping <add> with self.assertRaises(ValueError): <add> self.args_parser(string, string, offset_mapping=[[(0, 1), (1, 2)]]) <add> <add> # 2 sentences, 1 offset_mapping <add> with self.assertRaises(ValueError): <add> self.args_parser(string, string, offset_mapping=[(0, 1), (1, 2)]) <add> <add> # 1 sentences, 2 offset_mapping <add> with self.assertRaises(ValueError): <add> self.args_parser(string, offset_mapping=[[(0, 1), (1, 2)], [(0, 2), (2, 3)]]) <add> <add> # 0 sentences, 1 offset_mapping <add> with self.assertRaises(ValueError): <add> self.args_parser(offset_mapping=[[(0, 1), (1, 2)]])
2
Javascript
Javascript
fix crash on rc while toggling object status
1fd27dae5e498efb5a12e5eb6350540b25c48696
<ide><path>Libraries/Components/SwitchAndroid/SwitchAndroid.android.js <ide> var SwitchAndroid = React.createClass({ <ide> }, <ide> <ide> _onChange: function(event) { <del> this.props.onChange && this.props.onChange(event); <del> this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value); <del> <ide> // The underlying switch might have changed, but we're controlled, <ide> // and so want to ensure it represents our value. <ide> this.refs[SWITCH].setNativeProps({on: this.props.value}); <add> <add> if (this.props.value === event.nativeEvent.value || this.props.disabled) { <add> return; <add> } <add> <add> this.props.onChange && this.props.onChange(event); <add> this.props.onValueChange && this.props.onValueChange(event.nativeEvent.value); <ide> }, <ide> <ide> render: function() {
1
PHP
PHP
fix plugin path in i18n class
3b1bea830fa70727fcce77b60f5bd80333eb6c57
<ide><path>src/I18n/I18n.php <ide> protected function _bindTextDomain($domain) { <ide> foreach ($plugins as $plugin) { <ide> $pluginDomain = Inflector::underscore($plugin); <ide> if ($pluginDomain === $domain) { <del> $searchPaths[] = Plugin::path($plugin) . 'Locale/'; <add> $searchPaths[] = Plugin::path($plugin) . 'src' . DS . 'Locale/'; <ide> $searchPaths = array_reverse($searchPaths); <ide> break; <ide> }
1
Java
Java
use root locale when converting string case
5341ad896245c40a00b6faead1b90d01aac58f8c
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerBase.java <ide> public void onReceive(Context context, Intent intent) { <ide> final String bundleFile = subclassTag + "ReactNativeDevBundle.js"; <ide> mJSBundleDownloadedFile = new File(applicationContext.getFilesDir(), bundleFile); <ide> <del> final String splitBundlesDir = subclassTag.toLowerCase() + "_dev_js_split_bundles"; <add> final String splitBundlesDir = subclassTag.toLowerCase(Locale.ROOT) + "_dev_js_split_bundles"; <ide> mJSSplitBundlesDir = mApplicationContext.getDir(splitBundlesDir, Context.MODE_PRIVATE); <ide> <ide> mDefaultNativeModuleCallExceptionHandler = new DefaultNativeModuleCallExceptionHandler(); <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java <ide> import java.util.ArrayList; <ide> import java.util.HashSet; <ide> import java.util.List; <add>import java.util.Locale; <ide> import java.util.Set; <ide> import java.util.concurrent.TimeUnit; <ide> import okhttp3.Call; <ide> public void onProgress( <ide> } <ide> <ide> RequestBody requestBody; <del> if (data == null || method.toLowerCase().equals("get") || method.toLowerCase().equals("head")) { <add> if (data == null <add> || method.toLowerCase(Locale.ROOT).equals("get") <add> || method.toLowerCase(Locale.ROOT).equals("head")) { <ide> requestBody = RequestBodyUtil.getEmptyBody(method); <ide> } else if (handler != null) { <ide> requestBody = handler.toRequestBody(data, contentType); <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/ResourceDrawableIdHelper.java <ide> import android.net.Uri; <ide> import androidx.annotation.Nullable; <ide> import java.util.HashMap; <add>import java.util.Locale; <ide> import java.util.Map; <ide> import javax.annotation.concurrent.ThreadSafe; <ide> <ide> public int getResourceDrawableId(Context context, @Nullable String name) { <ide> if (name == null || name.isEmpty()) { <ide> return 0; <ide> } <del> name = name.toLowerCase().replace("-", "_"); <add> name = name.toLowerCase(Locale.ROOT).replace("-", "_"); <ide> <ide> // name could be a resource id. <ide> try { <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java <ide> import java.lang.reflect.Field; <ide> import java.util.HashMap; <ide> import java.util.LinkedList; <add>import java.util.Locale; <ide> import java.util.Map; <ide> <ide> /** Manages instances of TextInput. */ <ide> public void setCursorColor(ReactEditText view, @Nullable Integer color) { <ide> } <ide> <ide> private static boolean shouldHideCursorForEmailTextInput() { <del> String manufacturer = Build.MANUFACTURER.toLowerCase(); <add> String manufacturer = Build.MANUFACTURER.toLowerCase(Locale.ROOT); <ide> return (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q && manufacturer.contains("xiaomi")); <ide> } <ide>
4
PHP
PHP
apply fixes from styleci
a7f60ccfde8a06319050873c54f5597e496b8424
<ide><path>src/Illuminate/Routing/Route.php <ide> <ide> use Closure; <ide> use LogicException; <del>use ReflectionMethod; <ide> use ReflectionFunction; <ide> use Illuminate\Support\Arr; <del>use Illuminate\Support\Str; <ide> use Illuminate\Http\Request; <del>use UnexpectedValueException; <ide> use Illuminate\Container\Container; <ide> use Illuminate\Routing\Matching\UriValidator; <ide> use Illuminate\Routing\Matching\HostValidator;
1
PHP
PHP
use data attribute for custom validity message
df8302c48f06848f39ea0f6f3314a5953e29baa9
<ide><path>src/View/Helper/FormHelper.php <ide> protected function setRequiredAndCustomValidity(string $fieldName, array $option <ide> $options['templateVars']['customValidityMessage'] = $message; <ide> <ide> if ($this->getConfig('autoSetCustomValidity')) { <add> $options['data-validity-message'] = $message; <ide> $options['oninvalid'] = "this.setCustomValidity(''); " <del> . "if (!this.value) this.setCustomValidity('$message')"; <add> . "if (!this.value) this.setCustomValidity(this.dataset.validityMessage)"; <ide> $options['oninput'] = "this.setCustomValidity('')"; <ide> } <ide> } <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testControlErrorMessage() <ide> 'type' => 'text', 'name' => 'title', <ide> 'id' => 'title', 'class' => 'form-error', <ide> 'required' => 'required', <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> ['div' => ['class' => 'error-message']], <ide> public function testControlErrorMessage() <ide> 'id' => 'title', <ide> 'class' => 'form-error', <ide> 'required' => 'required', <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> ['div' => ['class' => 'error-message']], <ide> public function testControlLabelFalse() <ide> 'required' => 'required', <ide> 'id' => 'title', <ide> 'name' => 'title', <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> '/div', <ide> public function testMultiRecordForm() <ide> 'required' => 'required', <ide> 'id' => '0-comments-1-comment', <ide> 'rows' => 5, <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> '/textarea', <ide> public function testHtml5ErrorMessage() <ide> 'type' => 'password', <ide> 'value' => '', <ide> 'required' => 'required', <add> 'data-validity-message' => 'This field cannot be left empty', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> ], <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> public function testHtml5ErrorMessage() <ide> 'value' => '', <ide> 'maxlength' => 255, <ide> 'required' => 'required', <add> 'data-validity-message' => 'This field cannot be left empty', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> ], <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> public function testHtml5ErrorMessage() <ide> 'value' => '', <ide> 'maxlength' => 255, <ide> 'required' => 'required', <add> 'data-validity-message' => 'Custom error message', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;Custom error message&#039;)', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> ], <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> public function testRequiredAttribute() <ide> 'name' => 'title', <ide> 'id' => 'title', <ide> 'required' => 'required', <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> '/div', <ide> public function testControlMaxLengthArrayContext() <ide> 'type' => 'text', <ide> 'required' => 'required', <ide> 'maxlength' => 10, <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> '/div', <ide> public function testControlMaxLengthEntityContext() <ide> 'type' => 'text', <ide> 'required' => 'required', <ide> 'maxlength' => 10, <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> '/div', <ide> public function testControlMaxLengthEntityContext() <ide> 'type' => 'text', <ide> 'required' => 'required', <ide> 'maxlength' => 55, // Length set in validator should take precedence over schema. <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> '/div', <ide> public function testControlMaxLengthEntityContext() <ide> 'type' => 'text', <ide> 'required' => 'required', <ide> 'maxlength' => 10, // Length set in options should take highest precedence. <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> '/div', <ide> public function testControlMinMaxLengthEntityContext() <ide> 'type' => 'text', <ide> 'required' => 'required', <ide> 'maxlength' => 10, <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> '/div', <ide> public function testControlMaxLengthFormContext() <ide> 'type' => 'text', <ide> 'required' => 'required', <ide> 'maxlength' => 10, <del> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(&#039;This field cannot be left empty&#039;)', <add> 'data-validity-message' => 'This field cannot be left empty', <add> 'oninvalid' => 'this.setCustomValidity(&#039;&#039;); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)', <ide> 'oninput' => 'this.setCustomValidity(&#039;&#039;)', <ide> ], <ide> '/div',
2
PHP
PHP
update encrypter interface
956fece317ada86ce2f205d5619e80a7d677f661
<ide><path>src/Illuminate/Contracts/Encryption/Encrypter.php <ide> interface Encrypter <ide> * @param mixed $value <ide> * @param bool $serialize <ide> * @return mixed <add> * <add> * @throws \Illuminate\Contracts\Encryption\EncryptException <ide> */ <ide> public function encrypt($value, $serialize = true); <ide> <ide> public function encrypt($value, $serialize = true); <ide> * @param mixed $payload <ide> * @param bool $unserialize <ide> * @return mixed <add> * <add> * @throws \Illuminate\Contracts\Encryption\DecryptException <ide> */ <ide> public function decrypt($payload, $unserialize = true); <ide> }
1
Mixed
Javascript
support abortsignal in server.listen
51b43675067fafaad0abd7d4f62a6a5097db5044
<ide><path>doc/api/net.md <ide> Listening on a file descriptor is not supported on Windows. <ide> <!-- YAML <ide> added: v0.11.14 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/36623 <add> description: AbortSignal support was added. <ide> - version: v11.4.0 <ide> pr-url: https://github.com/nodejs/node/pull/23798 <ide> description: The `ipv6Only` option is supported. <ide> changes: <ide> * `ipv6Only` {boolean} For TCP servers, setting `ipv6Only` to `true` will <ide> disable dual-stack support, i.e., binding to host `::` won't make <ide> `0.0.0.0` be bound. **Default:** `false`. <add> * `signal` {AbortSignal} An AbortSignal that may be used to close a listening server. <ide> * `callback` {Function} <ide> functions. <ide> * Returns: {net.Server} <ide> Starting an IPC server as root may cause the server path to be inaccessible for <ide> unprivileged users. Using `readableAll` and `writableAll` will make the server <ide> accessible for all users. <ide> <add>If the `signal` option is enabled, calling `.abort()` on the corresponding <add>`AbortController` is similar to calling `.close()` on the server: <add> <add>```js <add>const controller = new AbortController(); <add>server.listen({ <add> host: 'localhost', <add> port: 80, <add> signal: controller.signal <add>}); <add>// Later, when you want to close the server. <add>controller.abort(); <add>``` <add> <ide> #### `server.listen(path[, backlog][, callback])` <ide> <!-- YAML <ide> added: v0.1.90 <ide><path>lib/internal/streams/add-abort-signal.js <ide> const eos = require('internal/streams/end-of-stream'); <ide> const { ERR_INVALID_ARG_TYPE } = codes; <ide> <ide> // This method is inlined here for readable-stream <del>// It also does not allow for signal to not exist on the steam <add>// It also does not allow for signal to not exist on the stream <ide> // https://github.com/nodejs/node/pull/36061#discussion_r533718029 <ide> const validateAbortSignal = (signal, name) => { <ide> if (typeof signal !== 'object' || <ide><path>lib/net.js <ide> const { <ide> } = require('internal/errors'); <ide> const { isUint8Array } = require('internal/util/types'); <ide> const { <add> validateAbortSignal, <ide> validateInt32, <ide> validatePort, <ide> validateString <ide> function afterConnect(status, handle, req, readable, writable) { <ide> } <ide> } <ide> <add>function addAbortSignalOption(self, options) { <add> if (options?.signal === undefined) { <add> return; <add> } <add> validateAbortSignal(options.signal, 'options.signal'); <add> const { signal } = options; <add> const onAborted = () => { <add> self.close(); <add> }; <add> if (signal.aborted) { <add> process.nextTick(onAborted); <add> } else { <add> signal.addEventListener('abort', onAborted); <add> self.once('close', () => signal.removeEventListener('abort', onAborted)); <add> } <add>} <ide> <ide> function Server(options, connectionListener) { <ide> if (!(this instanceof Server)) <ide> Server.prototype.listen = function(...args) { <ide> listenInCluster(this, null, -1, -1, backlogFromArgs); <ide> return this; <ide> } <add> addAbortSignalOption(this, options); <ide> // (handle[, backlog][, cb]) where handle is an object with a fd <ide> if (typeof options.fd === 'number' && options.fd >= 0) { <ide> listenInCluster(this, null, null, null, backlogFromArgs, options.fd); <ide><path>test/parallel/test-net-server-listen-options-signal.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const net = require('net'); <add> <add>{ <add> // Test bad signal. <add> const server = net.createServer(); <add> assert.throws( <add> () => server.listen({ port: 0, signal: 'INVALID_SIGNAL' }), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError' <add> }); <add>} <add> <add>{ <add> // Test close. <add> const server = net.createServer(); <add> const controller = new AbortController(); <add> server.on('close', common.mustCall()); <add> server.listen({ port: 0, signal: controller.signal }); <add> controller.abort(); <add>} <add> <add>{ <add> // Test close with pre-aborted signal. <add> const server = net.createServer(); <add> const controller = new AbortController(); <add> controller.abort(); <add> server.on('close', common.mustCall()); <add> server.listen({ port: 0, signal: controller.signal }); <add>}
4
Javascript
Javascript
adapt jest transform for node-only files
ff0eb47dbd0866e210d10621480528733ebdc74c
<ide><path>jestSupport/preprocessor.js <ide> */ <ide> 'use strict'; <ide> <add>const babel = require('babel-core'); <add>const babelRegisterOnly = require('../packager/babelRegisterOnly'); <ide> const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction'); <ide> const path = require('path'); <ide> const transformer = require('../packager/transformer.js'); <ide> <add>const nodeFiles = RegExp([ <add> '/local-cli/', <add> '/packager/(?!react-packager/src/Resolver/polyfills/)', <add>].join('|')); <add>const nodeOptions = babelRegisterOnly.config([nodeFiles]); <add> <ide> module.exports = { <ide> process(src, file) { <ide> // Don't transform node_modules, except react-tools which includes the <ide> // untransformed copy of React <ide> if (file.match(/node_modules\/(?!react-tools\/)/)) { <ide> return src; <add> } else if (nodeFiles.test(file)) { // node specific transforms only <add> return babel.transform( <add> src, Object.assign({filename: file}, nodeOptions)).code; <ide> } <ide> <ide> return transformer.transform(src, file, {inlineRequires: true}).code; <ide><path>packager/babelRegisterOnly.js <ide> Object.values || require('core-js/fn/object/values'); <ide> <ide> var _only = []; <ide> <del>module.exports = function(onlyList) { <del> _only = _only.concat(onlyList); <add>function registerOnly(onlyList) { <add> require('babel-register')(config(onlyList)); <add>} <ide> <del> require('babel-register')({ <add>function config(onlyList) { <add> _only = _only.concat(onlyList); <add> return { <ide> presets: ['es2015-node'], <ide> plugins: [ <ide> 'transform-flow-strip-types', <ide> 'syntax-trailing-function-commas', <ide> 'transform-object-rest-spread', <ide> ], <ide> only: _only, <add> retainLines: true, <ide> sourceMaps: 'inline', <del> }); <del>}; <add> babelrc: false, <add> }; <add>} <add> <add>module.exports = exports = registerOnly; <add>exports.config = config; <ide><path>packager/react-packager/src/JSTransformer/worker/__tests__/worker-test.js <ide> jest.mock('../extract-dependencies'); <ide> jest.mock('../inline'); <ide> jest.mock('../minify'); <ide> <del>const {transformCode} = require('..'); <ide> const {any, objectContaining} = jasmine; <ide> <ide> describe('code transformation worker:', () => { <add> let transformCode; <add> <ide> let extractDependencies, transform; <ide> beforeEach(() => { <add> ({transformCode} = require('..')); <ide> extractDependencies = <ide> require('../extract-dependencies').mockReturnValue({}); <ide> transform = jest.fn(); <ide> describe('code transformation worker:', () => { <ide> done(); <ide> }); <ide> }); <del> <add> <ide> it('removes shebang when present', done => { <ide> const shebang = '#!/usr/bin/env node'; <ide> const result = { <ide> describe('code transformation worker:', () => { <ide> done(); <ide> }); <ide> }); <del> <add> <ide> it('calls back with any error yielded by the transform', done => { <ide> const error = Error('arbitrary error'); <ide> transform.mockImplementation((_, callback) => callback(error)); <ide><path>packager/react-packager/src/Resolver/__tests__/Resolver-test.js <ide> jest.unmock('../'); <ide> jest.mock('path'); <ide> <del>const Promise = require('promise'); <del>const Resolver = require('../'); <ide> <del>const path = require('path'); <del> <del>let DependencyGraph = jest.fn(); <add>const DependencyGraph = jest.fn(); <ide> jest.setMock('node-haste', DependencyGraph); <ide> let Module; <ide> let Polyfill; <ide> <ide> describe('Resolver', function() { <add> let Resolver, path; <add> <ide> beforeEach(function() { <add> Resolver = require('../'); <add> path = require('path'); <ide> DependencyGraph.mockClear(); <ide> Module = jest.fn(function() { <ide> this.getName = jest.fn(); <ide> describe('Resolver', function() { <ide> ).then(function(result) { <ide> expect(result.mainModuleId).toEqual('index'); <ide> expect(result.dependencies[result.dependencies.length - 1]).toBe(module); <del> expect(DependencyGraph.prototype.createPolyfill.mock.calls.map((call) => call[0])).toEqual([ <add> expect( <add> DependencyGraph <add> .prototype <add> .createPolyfill <add> .mock <add> .calls <add> .map((call) => call[0])) <add> .toEqual([ <ide> { id: 'polyfills/polyfills.js', <ide> file: 'polyfills/polyfills.js', <ide> dependencies: [] <ide><path>packager/react-packager/src/Server/__tests__/Server-test.js <ide> jest.setMock('worker-farm', function() { return () => {}; }) <ide> .setMock('timers', { setImmediate: (fn) => setTimeout(fn, 0) }) <ide> .setMock('uglify-js') <ide> .setMock('crypto') <del> .setMock('source-map', { SourceMapConsumer: (fn) => {}}) <add> .setMock('source-map', { SourceMapConsumer: function(fn) {}}) <ide> .mock('../../Bundler') <ide> .mock('../../AssetServer') <ide> .mock('../../lib/declareOpts') <ide> .mock('node-haste') <ide> .mock('../../Activity'); <ide> <del>const Promise = require('promise'); <del>const SourceMapConsumer = require('source-map').SourceMapConsumer; <del> <del>const Bundler = require('../../Bundler'); <del>const Server = require('../'); <del>const AssetServer = require('../../AssetServer'); <del> <ide> let FileWatcher; <ide> <ide> describe('processRequest', () => { <add> let SourceMapConsumer, Bundler, Server, AssetServer, Promise; <add> beforeEach(() => { <add> SourceMapConsumer = require('source-map').SourceMapConsumer; <add> Bundler = require('../../Bundler'); <add> Server = require('../'); <add> AssetServer = require('../../AssetServer'); <add> Promise = require('promise'); <add> }); <add> <ide> let server; <ide> <ide> const options = {
5
Ruby
Ruby
use full paths to gcc versions
2fb6d2fdbed66439de458932b89edb9222dc2ac1
<ide><path>Library/Homebrew/extend/ENV/std.rb <ide> def gcc <ide> GNU_GCC_VERSIONS.each do |n| <ide> define_method(:"gcc-4.#{n}") do <ide> gcc = "gcc-4.#{n}" <del> self.cc = gcc <del> self.cxx = gcc.gsub('c', '+') <add> gxx = gcc.gsub('c', '+') <add> self.cc = MacOS.locate(gcc) <add> self.cxx = MacOS.locate(gxx) <ide> set_cpu_cflags <ide> @compiler = gcc <ide> end
1
Text
Text
update local development guide
10314c1c84b5b7db20668a50d68c4a19300efb3f
<ide><path>guides/source/development_dependencies_install.md <ide> After reading this guide, you will know: <ide> <ide> -------------------------------------------------------------------------------- <ide> <del>The Easy Way <del>------------ <add>Other Ways to Set Up Your Environment <add>------------------------------------- <ide> <del>The easiest and recommended way to get a development environment ready to hack is to use the [Rails development box](https://github.com/rails/rails-dev-box). <add>If you don't want to set up Rails for development on your local machine you can use Codespaces, the VS Code Remote Plugin, or rails-dev-box. Learn more about these options [here](https://guides.rubyonrails.org/contributing_to_ruby_on_rails.html#setting-up-a-development-environment). <ide> <del>The Hard Way <del>------------ <add>Local Development <add>----------------- <ide> <del>In case you can't use the Rails development box, see the steps below to manually <del>build a development box for Ruby on Rails core development. <add>If you want to develop Ruby on Rails locally on your machine see the steps below. <ide> <ide> ### Install Git <ide> <del>Ruby on Rails uses Git for source code control. The [Git homepage](https://git-scm.com/) has installation instructions. There are a variety of resources on the net that will help you get familiar with Git: <del> <del>* [Try Git course](https://try.github.io/) is an interactive course that will teach you the basics. <del>* The [official Documentation](https://git-scm.com/documentation) is pretty comprehensive and also contains some videos with the basics of Git. <del>* [Everyday Git](https://schacon.github.io/git/everyday.html) will teach you just enough about Git to get by. <del>* [GitHub](https://help.github.com/) offers links to a variety of Git resources. <del>* [Pro Git](https://git-scm.com/book) is an entire book about Git with a Creative Commons license. <add>Ruby on Rails uses Git for source code control. The [Git homepage](https://git-scm.com/) has installation instructions. There are a variety of resources online that will help you get familiar with Git. <ide> <ide> ### Clone the Ruby on Rails Repository <ide> <del>Navigate to the folder where you want the Ruby on Rails source code (it will create its own `rails` subdirectory) and run: <add>Navigate to the folder where you want to download the Ruby on Rails source code (it will create its own `rails` subdirectory) and run: <ide> <ide> ```bash <ide> $ git clone https://github.com/rails/rails.git <ide> Here's the list of each gems' additional dependencies: <ide> [Node.js](https://nodejs.org/) installed. <ide> <ide> Install all the services you need to properly test the full gem you'll be <del>making changes to. <add>making changes to. How to install these services for macOS, Ubuntu, Fedora/CentOS, <add>and FreeBSD are detailed below. <ide> <del>NOTE: Redis' documentation discourage installations with package managers as those are usually outdated. Installing from source and bringing the server up is straight forward and well documented on [Redis' documentation](https://redis.io/download#installation). <add>NOTE: Redis' documentation discourages installations with package managers as those are usually outdated. Installing from source and bringing the server up is straight forward and well documented on [Redis' documentation](https://redis.io/download#installation). <ide> <del>NOTE: Active Record tests _must_ pass for at least MySQL, PostgreSQL, and SQLite3. Subtle differences between the various adapters have been behind the rejection of many patches that looked OK when tested only against single adapter. <add>NOTE: Active Record tests _must_ pass for at least MySQL, PostgreSQL, and SQLite3. Your patch will be rejected if tested against a single adapter, unless the change and tests are adapter specific. <ide> <ide> Below you can find instructions on how to install all of the additional <del>tools for different OSes. <add>tools for different operating systems. <ide> <ide> #### macOS <ide> <ide> $ brew services start mysql <ide> <ide> Replace `mysql` with the name of the service you want to start. <ide> <add>##### Potential Issues <add> <add>This section details some of the potential issues you may run into with native extensions on macOS, particularly when bundling the mysql2 gem in local development. This documentation is subject to change and may be incorrect as Apple makes changes to the developer environment on Rails. <add> <add>In order to compile the `mysql2` gem on macOS you will need the following: <add> <add>1) `[email protected]` installed (not `openssl@3`) <add>2) Ruby compiled with `[email protected]` <add>3) Set compiler flags in the bundle config for `mysql2`. <add> <add>If both `[email protected]` and `openssl@3` are installed you will need to tell Ruby to use `[email protected]` in order for Rails to bundle `mysql2`. <add> <add>In your `.bash_profile` set the `PATH` and `RUBY_CONFIGURE_OPTS` to point to `[email protected]`: <add> <add>``` <add>export PATH="/usr/local/opt/[email protected]/bin:$PATH" <add>export RUBY_CONFIGURE_OPTS="--with-openssl-dir=$(brew --prefix [email protected])" <add>``` <add> <add>In your `~/.bundle/config` set the following for `mysql2`. Be sure to delete any other entries for `BUNDLE_BUILD__MYSQL2`: <add> <add>``` <add>BUNDLE_BUILD__MYSQL2: "--with-ldflags=-L/usr/local/opt/[email protected]/lib --with-cppflags=-L/usr/local/opt/[email protected]/include" <add>``` <add> <add>By setting these flags before installing Ruby and bundling Rails you should be able to get your local macOS development environment working. <add> <ide> #### Ubuntu <ide> <ide> To install all run: <ide> $ pkg install sqlite3 mysql80-client mysql80-server postgresql11-client postgres <ide> Or install everything through ports (these packages are located under the <ide> `databases` folder). <ide> <del>NOTE: If you run into troubles during the installation of MySQL, please see <add>NOTE: If you run into problems during the installation of MySQL, please see <ide> [the MySQL documentation](https://dev.mysql.com/doc/refman/en/freebsd-installation.html). <ide> <ide> ### Database Configuration <ide> <ide> There are couple of additional steps required to configure database engines <ide> required for running Active Record tests. <ide> <del>In order to be able to run the test suite against MySQL you need to create a user named `rails` with privileges on the test databases: <del> <del>```sql <del>$ mysql -uroot -p <del> <del>mysql> CREATE USER 'rails'@'localhost'; <del>mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.* <del> to 'rails'@'localhost'; <del>mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.* <del> to 'rails'@'localhost'; <del>mysql> GRANT ALL PRIVILEGES ON inexistent_activerecord_unittest.* <del> to 'rails'@'localhost'; <del>``` <del> <ide> PostgreSQL's authentication works differently. To set up the development environment <ide> with your development account, on Linux or BSD, you just have to run: <ide> <ide> and for macOS: <ide> $ createuser --superuser $USER <ide> ``` <ide> <add>MySQL will create the users when the databases are created. The task assumes your user is `root` with no password. <add> <ide> Then, you need to create the test databases for both MySQL and PostgreSQL with: <ide> <ide> ```bash <ide> $ cd activerecord <ide> $ bundle exec rake db:create <ide> ``` <ide> <del>NOTE: You'll see the following warning (or localized warning) during activating HStore extension in PostgreSQL 9.1.x or earlier: "WARNING: => is deprecated as an operator". <del> <ide> You can also create test databases for each database engine separately: <ide> <ide> ```bash <ide> $ bundle exec rake db:drop <ide> <ide> NOTE: Using the Rake task to create the test databases ensures they have the correct character set and collation. <ide> <del>If you're using another database, check the file `activerecord/test/config.yml` or `activerecord/test/config.example.yml` for default connection information. You can edit `activerecord/test/config.yml` to provide different credentials on your machine if you must, but obviously you should not push any such changes back to Rails. <add>If you're using another database, check the file `activerecord/test/config.yml` or `activerecord/test/config.example.yml` for default connection information. You can edit `activerecord/test/config.yml` to provide different credentials on your machine, but you should not push any of those changes back to Rails. <ide> <ide> ### Install JavaScript dependencies <ide> <ide> If you installed Yarn, you will need to install the JavaScript dependencies: <ide> $ yarn install <ide> ``` <ide> <del>### Install Bundler gem <del> <del>Get a recent version of [Bundler](https://bundler.io/) <add>### Installing gem dependencies <ide> <del>```bash <del>$ gem install bundler <del>$ gem update bundler <del>``` <add>Gems are installed with [Bundler](https://bundler.io/) which ships by default with Ruby. <ide> <del>and run: <add>To install the Gemfile for Rails run: <ide> <ide> ```bash <ide> $ bundle install <ide> ``` <ide> <del>or: <add>If you don't need to run Active Record tests you can run: <ide> <ide> ```bash <ide> $ bundle install --without db <ide> ``` <ide> <del>if you don't need to run Active Record tests. <del> <ide> ### Contribute to Rails <ide> <ide> After you've set up everything, read how you can start [contributing](contributing_to_ruby_on_rails.html#running-an-application-against-your-local-branch).
1
Text
Text
add missing changes entry
e00639e57f86f4707f665975ca7aea5ca8799399
<ide><path>doc/api/util.md <ide> changes: <ide> pr-url: https://github.com/nodejs/node/pull/17907 <ide> description: The `%o` specifier's `depth` option will now fall back to the <ide> default depth. <add> - version: v10.12.0 <add> pr-url: https://github.com/nodejs/node/pull/22097 <add> description: The `%d` and `%i` specifiers now support BigInt. <ide> - version: v8.4.0 <ide> pr-url: https://github.com/nodejs/node/pull/14558 <ide> description: The `%o` and `%O` specifiers are supported now.
1
Java
Java
add atomic registersegment method to test
f207cfddf37c01b5ff2c2f53b4d44a4cc7ad2484
<ide><path>ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java <ide> public class ReactFeatureFlags { <ide> <ide> /** Temporary flag to allow execution of mount items up to 15ms earlier than normal. */ <ide> public static boolean enableEarlyScheduledMountItemExecution = false; <add> <add> // TODO (T136375139): Remove this once finish testing <add> public static boolean enableAtomicRegisterSegment = false; <ide> }
1
Javascript
Javascript
escape chunk names for webworkers
0aa9aa61b154f87141f817025133e0aa2b529920
<ide><path>lib/webworker/WebWorkerMainTemplatePlugin.js <ide> class WebWorkerMainTemplatePlugin { <ide> "// object to store loaded chunks", <ide> '// "1" means "already loaded"', <ide> "var installedChunks = {", <del> Template.indent(chunk.ids.map(id => `${id}: 1`).join(",\n")), <add> Template.indent(chunk.ids.map(id => `${JSON.stringify(id)}: 1`).join(",\n")), <ide> "};" <ide> ]); <ide> }
1
Ruby
Ruby
fix weird omission
832a08abcdf2256c140d9f81d8753d8bddd323c2
<ide><path>Library/Homebrew/extend/os/mac/keg_relocate.rb <ide> def mach_o_files <ide> def self.file_linked_libraries(file, string) <ide> # Check dynamic library linkage. Importantly, do not run otool on static <ide> # libraries, which will falsely report "linkage" to themselves. <del> if file.mach_o_executable? || file.dylib? || file.mach_o_bund <add> if file.mach_o_executable? || file.dylib? || file.mach_o_bundle? <ide> file.dynamically_linked_libraries.select { |lib| lib.include? string } <ide> else <ide> []
1
PHP
PHP
use undeprecated methods for adding cookies
5034140325f5ea1882a2b032ea0ae2f06fdb4229
<ide><path>src/Http/Client.php <ide> protected function _createRequest($method, $url, $data, $options) <ide> } <ide> <ide> $request = new Request($url, $method, $headers, $data); <add> $request = $this->_cookies->addToRequest($request); <ide> $request->cookie($this->_cookies->get($url)); <ide> if (isset($options['cookies'])) { <ide> $request->cookie($options['cookies']); <ide><path>src/Http/Client/Adapter/Stream.php <ide> protected function _buildHeaders(Request $request, $options) <ide> { <ide> $headers = []; <ide> foreach ($request->getHeaders() as $name => $values) { <del> $headers[] = sprintf('%s: %s', $name, implode(", ", $values)); <add> if ($name !== 'Cookie') { <add> $headers[] = sprintf('%s: %s', $name, implode(", ", $values)); <add> } <ide> } <ide> <add> $cookieHeader = $request->getHeaderLine('Cookie'); <ide> $cookies = []; <ide> foreach ($request->cookies() as $name => $value) { <ide> $cookies[] = "$name=$value"; <ide> } <del> if ($cookies) { <del> $headers[] = 'Cookie: ' . implode('; ', $cookies); <add> $cookieData = implode('; ', $cookies); <add> if ($cookieData || $cookieHeader) { <add> $headers[] = 'Cookie: ' . implode('; ', [$cookieHeader, $cookieData]); <ide> } <ide> $this->_contextOptions['header'] = implode("\r\n", $headers); <ide> } <ide><path>tests/TestCase/Http/Client/Adapter/StreamTest.php <ide> public function testBuildingContextHeader() <ide> $request->url('http://localhost') <ide> ->header([ <ide> 'User-Agent' => 'CakePHP TestSuite', <del> 'Content-Type' => 'application/json' <add> 'Content-Type' => 'application/json', <add> 'Cookie' => 'a=b; c=d', <ide> ]) <ide> ->cookie([ <ide> 'testing' => 'value', <ide> public function testBuildingContextHeader() <ide> 'Connection: close', <ide> 'User-Agent: CakePHP TestSuite', <ide> 'Content-Type: application/json', <del> 'Cookie: testing=value; utm_src=awesome', <add> 'Cookie: a=b; c=d; testing=value; utm_src=awesome', <ide> ]; <ide> $this->assertEquals(implode("\r\n", $expected), $result['header']); <ide> $this->assertEquals($options['redirect'], $result['max_redirects']); <ide><path>tests/TestCase/Http/ClientTest.php <ide> public function testCookieStorage() <ide> $http = new Client([ <ide> 'host' => 'cakephp.org', <ide> 'adapter' => $adapter, <del> 'cookieJar' => $cookieJar <ide> ]); <ide> <ide> $http->get('/projects');
4
Python
Python
fix testconversion.test_to_int_scalar() on python
48020e87513c8632655dc0939cae802aab07616e
<ide><path>numpy/core/tests/test_multiarray.py <ide> def test_to_int_scalar(self): <ide> assert_equal(5, int_func(np.bytes_(b'5'))) <ide> assert_equal(6, int_func(np.unicode_(u'6'))) <ide> <del> class HasTrunc: <del> def __trunc__(self): <del> return 3 <del> assert_equal(3, int_func(np.array(HasTrunc()))) <del> assert_equal(3, int_func(np.array([HasTrunc()]))) <add> # The delegation of int() to __trunc__ was deprecated in <add> # Python 3.11. <add> if sys.version_info < (3, 11): <add> class HasTrunc: <add> def __trunc__(self): <add> return 3 <add> assert_equal(3, int_func(np.array(HasTrunc()))) <add> assert_equal(3, int_func(np.array([HasTrunc()]))) <add> else: <add> pass <ide> <ide> class NotConvertible: <ide> def __int__(self):
1
PHP
PHP
restore original tabs and spaces in code
6eaa4f9414d8beb011b1dcac74d710b1e4c0230f
<ide><path>src/Cache/Engine/MemcachedEngine.php <ide> */ <ide> class MemcachedEngine extends CacheEngine { <ide> <del> /** <del> * memcached wrapper. <del> * <del> * @var Memcache <del> */ <del> protected $_Memcached = null; <del> <del> /** <del> * The default config used unless overriden by runtime configuration <del> * <del> * - `compress` Whether to compress data <del> * - `duration` Specify how long items in this cache configuration last. <del> * - `groups` List of groups or 'tags' associated to every key stored in this config. <del> * handy for deleting a complete group from cache. <del> * - `login` Login to access the Memcache server <del> * - `password` Password to access the Memcache server <del> * - `persistent` The name of the persistent connection. All configurations using <del> * the same persistent value will share a single underlying connection. <del> * - `prefix` Prepended to all entries. Good for when you need to share a keyspace <del> * with either another cache config or another application. <del> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable <del> * cache::gc from ever being called automatically. <del> * - `serialize` The serializer engine used to serialize data. Available engines are php, <del> * igbinary and json. Beside php, the memcached extension must be compiled with the <del> * appropriate serializer support. <del> * - `servers` String or array of memcached servers. If an array MemcacheEngine will use <del> * them as a pool. <del> * - `options` - Additional options for the memcached client. Should be an array of option => value. <del> * Use the \Memcached::OPT_* constants as keys. <del> * <del> * @var array <del> */ <del> protected $_defaultConfig = [ <del> 'compress' => false, <del> 'duration' => 3600, <del> 'groups' => [], <del> 'login' => null, <del> 'password' => null, <del> 'persistent' => false, <del> 'prefix' => 'cake_', <del> 'probability' => 100, <del> 'serialize' => 'php', <del> 'servers' => ['127.0.0.1'], <del> 'options' => [], <del> ]; <del> <del> /** <del> * List of available serializer engines <del> * <del> * Memcached must be compiled with json and igbinary support to use these engines <del> * <del> * @var array <del> */ <del> protected $_serializers = []; <del> <del> /** <del> * Initialize the Cache Engine <del> * <del> * Called automatically by the cache frontend <del> * <del> * @param array $config array of setting for the engine <del> * @return bool True if the engine has been successfully initialized, false if not <del> * @throws \Cake\Error\Exception when you try use authentication without Memcached compiled with SASL support <del> */ <del> public function init(array $config = []) { <del> if (!class_exists('Memcached')) { <del> return false; <del> } <del> <del> if (!isset($config['prefix'])) { <del> $config['prefix'] = Inflector::slug(APP_DIR) . '_'; <del> } <del> <del> $this->_serializers = [ <del> 'igbinary' => \Memcached::SERIALIZER_IGBINARY, <del> 'json' => \Memcached::SERIALIZER_JSON, <del> 'php' => \Memcached::SERIALIZER_PHP <del> ]; <del> if (defined('Memcached::HAVE_MSGPACK') && \Memcached::HAVE_MSGPACK) { <del> $this->_serializers['msgpack'] = \Memcached::SERIALIZER_MSGPACK; <del> } <del> <del> parent::init($config); <del> <del> if (isset($config['servers'])) { <del> $this->config('servers', $config['servers'], false); <del> } <del> <del> if (!is_array($this->_config['servers'])) { <del> $this->_config['servers'] = [$this->_config['servers']]; <del> } <del> <del> if (isset($this->_Memcached)) { <del> return true; <del> } <del> <del> $this->_Memcached = new \Memcached($this->_config['persistent'] ? (string)$this->_config['persistent'] : null); <del> $this->_setOptions(); <del> <del> if (count($this->_Memcached->getServerList())) { <del> return true; <del> } <del> <del> $servers = []; <del> foreach ($this->_config['servers'] as $server) { <del> $servers[] = $this->_parseServerString($server); <del> } <del> <del> if (!$this->_Memcached->addServers($servers)) { <del> return false; <del> } <del> <del> if (is_array($this->_config['options'])) { <del> foreach ($this->_config['options'] as $opt => $value) { <del> $this->_Memcached->setOption($opt, $value); <del> } <del> } <del> <del> if ($this->_config['login'] !== null && $this->_config['password'] !== null) { <del> if (!method_exists($this->_Memcached, 'setSaslAuthData')) { <del> throw new Error\Exception( <del> 'Memcached extension is not build with SASL support' <del> ); <del> } <del> $this->_Memcached->setSaslAuthData($this->_config['login'], $this->_config['password']); <del> } <del> <del> return true; <del> } <del> <del> /** <del> * Settings the memcached instance <del> * <del> * @return void <del> * @throws \Cake\Error\Exception when the Memcached extension is not built with the desired serializer engine <del> */ <del> protected function _setOptions() { <del> $this->_Memcached->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true); <del> <del> $serializer = strtolower($this->_config['serialize']); <del> if (!isset($this->_serializers[$serializer])) { <del> throw new Error\Exception( <del> sprintf('%s is not a valid serializer engine for Memcached', $serializer) <del> ); <del> } <del> <del> if ($serializer !== 'php' && !constant('Memcached::HAVE_' . strtoupper($serializer))) { <del> throw new Error\Exception( <del> sprintf('Memcached extension is not compiled with %s support', $serializer) <del> ); <del> } <del> <del> $this->_Memcached->setOption(\Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]); <del> <del> // Check for Amazon ElastiCache instance <del> if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) { <del> $this->_Memcached->setOption(\Memcached::OPT_CLIENT_MODE, \Memcached::DYNAMIC_CLIENT_MODE); <del> } <del> <del> $this->_Memcached->setOption(\Memcached::OPT_COMPRESSION, (bool)$this->_config['compress']); <del> } <del> <del> /** <del> * Parses the server address into the host/port. Handles both IPv6 and IPv4 <del> * addresses and Unix sockets <del> * <del> * @param string $server The server address string. <del> * @return array Array containing host, port <del> */ <del> protected function _parseServerString($server) { <del> if ($server[0] === 'u') { <del> return [$server, 0]; <del> } <del> if (substr($server, 0, 1) === '[') { <del> $position = strpos($server, ']:'); <del> if ($position !== false) { <del> $position++; <del> } <del> } else { <del> $position = strpos($server, ':'); <del> } <del> $port = 11211; <del> $host = $server; <del> if ($position !== false) { <del> $host = substr($server, 0, $position); <del> $port = substr($server, $position + 1); <del> } <del> return [$host, (int)$port]; <del> } <del> <del> /** <del> * Write data for key into cache. When using memcached as your cache engine <del> * remember that the Memcached pecl extension does not support cache expiry times greater <del> * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring. <del> * <del> * @param string $key Identifier for the data <del> * @param mixed $value Data to be cached <del> * @return bool True if the data was successfully cached, false on failure <del> * @see http://php.net/manual/en/memcache.set.php <del> */ <del> public function write($key, $value) { <del> $duration = $this->_config['duration']; <del> if ($duration > 30 * DAY) { <del> $duration = 0; <del> } <del> <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->set($key, $value, $duration); <del> } <del> <del> /** <del> * Write many cache entries to the cache at once <del> * <del> * @param array $data An array of data to be stored in the cache <del> * @return array of bools for each key provided, true if the data was successfully cached, false on failure <del> */ <del> public function writeMany($data) { <del> $cacheData = array(); <del> foreach ($data as $key => $value) { <del> $cacheData[$this->_key($key)] = $value; <del> } <del> <del> $success = $this->_Memcached->setMulti($cacheData); <del> <del> $return = array(); <del> foreach (array_keys($data) as $key) { <del> $return[$key] = $success; <del> } <del> return $return; <del> } <del> <del> /** <del> * Read a key from the cache <del> * <del> * @param string $key Identifier for the data <del> * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it <del> */ <del> public function read($key) { <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->get($key); <del> } <del> <del> /** <del> * Read many keys from the cache at once <del> * <del> * @param array $keys An array of identifiers for the data <del> * @return An array containing, for each of the given $keys, the cached data or false if cached data could not be <del> * retreived <del> */ <del> public function readMany($keys) { <del> $cacheKeys = array(); <del> foreach ($keys as $key) { <del> $cacheKeys[] = $this->_key($key); <del> } <del> <del> $values = $this->_Memcached->getMulti($cacheKeys); <del> $return = array(); <del> foreach ($keys as &$key) { <del> $return[$key] = array_key_exists($this->_key($key), $values) ? $values[$this->_key($key)] : false; <del> } <del> return $return; <del> } <del> <del> /** <del> * Increments the value of an integer cached key <del> * <del> * @param string $key Identifier for the data <del> * @param int $offset How much to increment <del> * @return bool|int New incremented value, false otherwise <del> * @throws \Cake\Error\Exception when you try to increment with compress = true <del> */ <del> public function increment($key, $offset = 1) { <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->increment($key, $offset); <del> } <del> <del> /** <del> * Decrements the value of an integer cached key <del> * <del> * @param string $key Identifier for the data <del> * @param int $offset How much to subtract <del> * @return bool|int New decremented value, false otherwise <del> * @throws \Cake\Error\Exception when you try to decrement with compress = true <del> */ <del> public function decrement($key, $offset = 1) { <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->decrement($key, $offset); <del> } <del> <del> /** <del> * Delete a key from the cache <del> * <del> * @param string $key Identifier for the data <del> * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed <del> */ <del> public function delete($key) { <del> $key = $this->_key($key); <del> <del> return $this->_Memcached->delete($key); <del> } <del> <del> /** <del> * Delete many keys from the cache at once <del> * <del> * @param array $keys An array of identifiers for the data <del> * @return array of boolean values that are true if the key was successfully deleted, false if it didn't exist or <del> * couldn't be removed <del> */ <del> public function deleteMany($keys) { <del> $cacheKeys = array(); <del> foreach ($keys as $key) { <del> $cacheKeys[] = $this->_key($key); <del> } <del> <del> $success = $this->_Memcached->deleteMulti($cacheKeys); <del> <del> $return = array(); <del> foreach ($keys as $key) { <del> $return[$key] = $success; <del> } <del> return $return; <del> } <del> <del> /** <del> * Delete all keys from the cache <del> * <del> * @param bool $check If true will check expiration, otherwise delete all. <del> * @return bool True if the cache was successfully cleared, false otherwise <del> */ <del> public function clear($check) { <del> if ($check) { <del> return true; <del> } <del> <del> $keys = $this->_Memcached->getAllKeys(); <del> <del> foreach ($keys as $key) { <del> if (strpos($key, $this->_config['prefix']) === 0) { <del> $this->_Memcached->delete($key); <del> } <del> } <del> <del> return true; <del> } <del> <del> /** <del> * Returns the `group value` for each of the configured groups <del> * If the group initial value was not found, then it initializes <del> * the group accordingly. <del> * <del> * @return array <del> */ <del> public function groups() { <del> if (empty($this->_compiledGroupNames)) { <del> foreach ($this->_config['groups'] as $group) { <del> $this->_compiledGroupNames[] = $this->_config['prefix'] . $group; <del> } <del> } <del> <del> $groups = $this->_Memcached->getMulti($this->_compiledGroupNames); <del> if (count($groups) !== count($this->_config['groups'])) { <del> foreach ($this->_compiledGroupNames as $group) { <del> if (!isset($groups[$group])) { <del> $this->_Memcached->set($group, 1, 0); <del> $groups[$group] = 1; <del> } <del> } <del> ksort($groups); <del> } <del> <del> $result = []; <del> $groups = array_values($groups); <del> foreach ($this->_config['groups'] as $i => $group) { <del> $result[] = $group . $groups[$i]; <del> } <del> <del> return $result; <del> } <del> <del> /** <del> * Increments the group value to simulate deletion of all keys under a group <del> * old values will remain in storage until they expire. <del> * <del> * @param string $group name of the group to be cleared <del> * @return bool success <del> */ <del> public function clearGroup($group) { <del> return (bool)$this->_Memcached->increment($this->_config['prefix'] . $group); <del> } <del>} <ide>\ No newline at end of file <add>/** <add> * memcached wrapper. <add> * <add> * @var Memcache <add> */ <add> protected $_Memcached = null; <add> <add>/** <add> * The default config used unless overriden by runtime configuration <add> * <add> * - `compress` Whether to compress data <add> * - `duration` Specify how long items in this cache configuration last. <add> * - `groups` List of groups or 'tags' associated to every key stored in this config. <add> * handy for deleting a complete group from cache. <add> * - `login` Login to access the Memcache server <add> * - `password` Password to access the Memcache server <add> * - `persistent` The name of the persistent connection. All configurations using <add> * the same persistent value will share a single underlying connection. <add> * - `prefix` Prepended to all entries. Good for when you need to share a keyspace <add> * with either another cache config or another application. <add> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable <add> * cache::gc from ever being called automatically. <add> * - `serialize` The serializer engine used to serialize data. Available engines are php, <add> * igbinary and json. Beside php, the memcached extension must be compiled with the <add> * appropriate serializer support. <add> * - `servers` String or array of memcached servers. If an array MemcacheEngine will use <add> * them as a pool. <add> * - `options` - Additional options for the memcached client. Should be an array of option => value. <add> * Use the \Memcached::OPT_* constants as keys. <add> * <add> * @var array <add> */ <add> protected $_defaultConfig = [ <add> 'compress' => false, <add> 'duration' => 3600, <add> 'groups' => [], <add> 'login' => null, <add> 'password' => null, <add> 'persistent' => false, <add> 'prefix' => 'cake_', <add> 'probability' => 100, <add> 'serialize' => 'php', <add> 'servers' => ['127.0.0.1'], <add> 'options' => [], <add> ]; <add> <add>/** <add> * List of available serializer engines <add> * <add> * Memcached must be compiled with json and igbinary support to use these engines <add> * <add> * @var array <add> */ <add> protected $_serializers = []; <add> <add>/** <add> * Initialize the Cache Engine <add> * <add> * Called automatically by the cache frontend <add> * <add> * @param array $config array of setting for the engine <add> * @return bool True if the engine has been successfully initialized, false if not <add> * @throws \Cake\Error\Exception when you try use authentication without Memcached compiled with SASL support <add> */ <add> public function init(array $config = []) { <add> if (!class_exists('Memcached')) { <add> return false; <add> } <add> <add> if (!isset($config['prefix'])) { <add> $config['prefix'] = Inflector::slug(APP_DIR) . '_'; <add> } <add> <add> $this->_serializers = [ <add> 'igbinary' => \Memcached::SERIALIZER_IGBINARY, <add> 'json' => \Memcached::SERIALIZER_JSON, <add> 'php' => \Memcached::SERIALIZER_PHP <add> ]; <add> if (defined('\\Memcached::HAVE_MSGPACK') && \Memcached::HAVE_MSGPACK) { <add> $this->_serializers['msgpack'] = \Memcached::SERIALIZER_MSGPACK; <add> } <add> <add> parent::init($config); <add> <add> if (isset($config['servers'])) { <add> $this->config('servers', $config['servers'], false); <add> } <add> <add> if (!is_array($this->_config['servers'])) { <add> $this->_config['servers'] = [$this->_config['servers']]; <add> } <add> <add> if (isset($this->_Memcached)) { <add> return true; <add> } <add> <add> $this->_Memcached = new \Memcached($this->_config['persistent'] ? (string)$this->_config['persistent'] : null); <add> $this->_setOptions(); <add> <add> if (count($this->_Memcached->getServerList())) { <add> return true; <add> } <add> <add> $servers = []; <add> foreach ($this->_config['servers'] as $server) { <add> $servers[] = $this->_parseServerString($server); <add> } <add> <add> if (!$this->_Memcached->addServers($servers)) { <add> return false; <add> } <add> <add> if (is_array($this->_config['options'])) { <add> foreach ($this->_config['options'] as $opt => $value) { <add> $this->_Memcached->setOption($opt, $value); <add> } <add> } <add> <add> if ($this->_config['login'] !== null && $this->_config['password'] !== null) { <add> if (!method_exists($this->_Memcached, 'setSaslAuthData')) { <add> throw new Error\Exception( <add> 'Memcached extension is not build with SASL support' <add> ); <add> } <add> $this->_Memcached->setSaslAuthData($this->_config['login'], $this->_config['password']); <add> } <add> <add> return true; <add> } <add> <add>/** <add> * Settings the memcached instance <add> * <add> * @return void <add> * @throws \Cake\Error\Exception when the Memcached extension is not built with the desired serializer engine <add> */ <add> protected function _setOptions() { <add> $this->_Memcached->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true); <add> <add> $serializer = strtolower($this->_config['serialize']); <add> if (!isset($this->_serializers[$serializer])) { <add> throw new Error\Exception( <add> sprintf('%s is not a valid serializer engine for Memcached', $serializer) <add> ); <add> } <add> <add> if ($serializer !== 'php' && !constant('\\Memcached::HAVE_' . strtoupper($serializer))) { <add> throw new Error\Exception( <add> sprintf('Memcached extension is not compiled with %s support', $serializer) <add> ); <add> } <add> <add> $this->_Memcached->setOption(\Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]); <add> <add> // Check for Amazon ElastiCache instance <add> if (defined('\\Memcached::OPT_CLIENT_MODE') && defined('\\Memcached::DYNAMIC_CLIENT_MODE')) { <add> $this->_Memcached->setOption(\Memcached::OPT_CLIENT_MODE, \Memcached::DYNAMIC_CLIENT_MODE); <add> } <add> <add> $this->_Memcached->setOption(\Memcached::OPT_COMPRESSION, (bool)$this->_config['compress']); <add> } <add> <add>/** <add> * Parses the server address into the host/port. Handles both IPv6 and IPv4 <add> * addresses and Unix sockets <add> * <add> * @param string $server The server address string. <add> * @return array Array containing host, port <add> */ <add> protected function _parseServerString($server) { <add> if ($server[0] === 'u') { <add> return [$server, 0]; <add> } <add> if (substr($server, 0, 1) === '[') { <add> $position = strpos($server, ']:'); <add> if ($position !== false) { <add> $position++; <add> } <add> } else { <add> $position = strpos($server, ':'); <add> } <add> $port = 11211; <add> $host = $server; <add> if ($position !== false) { <add> $host = substr($server, 0, $position); <add> $port = substr($server, $position + 1); <add> } <add> return [$host, (int)$port]; <add> } <add> <add>/** <add> * Write data for key into cache. When using memcached as your cache engine <add> * remember that the Memcached pecl extension does not support cache expiry times greater <add> * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring. <add> * <add> * @param string $key Identifier for the data <add> * @param mixed $value Data to be cached <add> * @return bool True if the data was successfully cached, false on failure <add> * @see http://php.net/manual/en/memcache.set.php <add> */ <add> public function write($key, $value) { <add> $duration = $this->_config['duration']; <add> if ($duration > 30 * DAY) { <add> $duration = 0; <add> } <add> <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->set($key, $value, $duration); <add> } <add> <add>/** <add> * Write many cache entries to the cache at once <add> * <add> * @param array $data An array of data to be stored in the cache <add> * @return array of bools for each key provided, true if the data was successfully cached, false on failure <add> */ <add> public function writeMany($data) { <add> $cacheData = array(); <add> foreach ($data as $key => $value) { <add> $cacheData[$this->_key($key)] = $value; <add> } <add> <add> $success = $this->_Memcached->setMulti($cacheData); <add> <add> $return = array(); <add> foreach (array_keys($data) as $key) { <add> $return[$key] = $success; <add> } <add> return $return; <add> } <add> <add>/** <add> * Read a key from the cache <add> * <add> * @param string $key Identifier for the data <add> * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it <add> */ <add> public function read($key) { <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->get($key); <add> } <add> <add>/** <add> * Read many keys from the cache at once <add> * <add> * @param array $keys An array of identifiers for the data <add> * @return An array containing, for each of the given $keys, the cached data or false if cached data could not be <add> * retreived <add> */ <add> public function readMany($keys) { <add> $cacheKeys = array(); <add> foreach ($keys as $key) { <add> $cacheKeys[] = $this->_key($key); <add> } <add> <add> $values = $this->_Memcached->getMulti($cacheKeys); <add> $return = array(); <add> foreach ($keys as &$key) { <add> $return[$key] = array_key_exists($this->_key($key), $values) ? $values[$this->_key($key)] : false; <add> } <add> return $return; <add> } <add> <add>/** <add> * Increments the value of an integer cached key <add> * <add> * @param string $key Identifier for the data <add> * @param int $offset How much to increment <add> * @return bool|int New incremented value, false otherwise <add> * @throws \Cake\Error\Exception when you try to increment with compress = true <add> */ <add> public function increment($key, $offset = 1) { <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->increment($key, $offset); <add> } <add> <add>/** <add> * Decrements the value of an integer cached key <add> * <add> * @param string $key Identifier for the data <add> * @param int $offset How much to subtract <add> * @return bool|int New decremented value, false otherwise <add> * @throws \Cake\Error\Exception when you try to decrement with compress = true <add> */ <add> public function decrement($key, $offset = 1) { <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->decrement($key, $offset); <add> } <add> <add>/** <add> * Delete a key from the cache <add> * <add> * @param string $key Identifier for the data <add> * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed <add> */ <add> public function delete($key) { <add> $key = $this->_key($key); <add> <add> return $this->_Memcached->delete($key); <add> } <add> <add>/** <add> * Delete many keys from the cache at once <add> * <add> * @param array $keys An array of identifiers for the data <add> * @return array of boolean values that are true if the key was successfully deleted, false if it didn't exist or <add> * couldn't be removed <add> */ <add> public function deleteMany($keys) { <add> $cacheKeys = array(); <add> foreach ($keys as $key) { <add> $cacheKeys[] = $this->_key($key); <add> } <add> <add> $success = $this->_Memcached->deleteMulti($cacheKeys); <add> <add> $return = array(); <add> foreach ($keys as $key) { <add> $return[$key] = $success; <add> } <add> return $return; <add> } <add> <add>/** <add> * Delete all keys from the cache <add> * <add> * @param bool $check If true will check expiration, otherwise delete all. <add> * @return bool True if the cache was successfully cleared, false otherwise <add> */ <add> public function clear($check) { <add> if ($check) { <add> return true; <add> } <add> <add> $keys = $this->_Memcached->getAllKeys(); <add> <add> foreach ($keys as $key) { <add> if (strpos($key, $this->_config['prefix']) === 0) { <add> $this->_Memcached->delete($key); <add> } <add> } <add> <add> return true; <add> } <add> <add>/** <add> * Returns the `group value` for each of the configured groups <add> * If the group initial value was not found, then it initializes <add> * the group accordingly. <add> * <add> * @return array <add> */ <add> public function groups() { <add> if (empty($this->_compiledGroupNames)) { <add> foreach ($this->_config['groups'] as $group) { <add> $this->_compiledGroupNames[] = $this->_config['prefix'] . $group; <add> } <add> } <add> <add> $groups = $this->_Memcached->getMulti($this->_compiledGroupNames); <add> if (count($groups) !== count($this->_config['groups'])) { <add> foreach ($this->_compiledGroupNames as $group) { <add> if (!isset($groups[$group])) { <add> $this->_Memcached->set($group, 1, 0); <add> $groups[$group] = 1; <add> } <add> } <add> ksort($groups); <add> } <add> <add> $result = []; <add> $groups = array_values($groups); <add> foreach ($this->_config['groups'] as $i => $group) { <add> $result[] = $group . $groups[$i]; <add> } <add> <add> return $result; <add> } <add> <add>/** <add> * Increments the group value to simulate deletion of all keys under a group <add> * old values will remain in storage until they expire. <add> * <add> * @param string $group name of the group to be cleared <add> * @return bool success <add> */ <add> public function clearGroup($group) { <add> return (bool)$this->_Memcached->increment($this->_config['prefix'] . $group); <add> } <add>}
1
Python
Python
fix a bug with data encoding
d173f21b896452f9921e7debc19ee54c00c0edf4
<ide><path>libcloud/common/base.py <ide> def request(self, action, params=None, data=None, headers=None, <ide> else: <ide> headers.update({'Host': self.host}) <ide> <del> # Encode data if necessary <del> if data is not None: <add> # Encode data if provided <add> if data: <ide> data = self.encode_data(data) <del> # Only send Content-Length 0 with POST and PUT request <add> <add> # Only send Content-Length 0 with POST and PUT request <add> if data is not None: <ide> if len(data) > 0 or (len(data) == 0 and method in ['POST', 'PUT']): <ide> headers.update({'Content-Length': str(len(data))}) <ide>
1
Ruby
Ruby
remove need for array extension
c2faf2a0cadc162741f4083178dc35864fcee035
<ide><path>Library/Homebrew/cmd/deps.rb <ide> def deps <ide> puts_deps_tree ARGV.formulae <ide> else <ide> raise FormulaUnspecifiedError if ARGV.named.empty? <del> all_deps = ARGV.formulae.map do |f| <del> ARGV.one? ? f.deps.default : f.recursive_dependencies <del> end.intersection.map(&:name) <add> all_deps = deps_for_formulae ARGV.formulae <ide> all_deps.sort! unless ARGV.include? "-n" <ide> puts all_deps <ide> end <ide> end <ide> <add> def deps_for_formulae(formulae) <add> formulae.map do |f| <add> ARGV.one? ? f.deps.default : f.recursive_dependencies <add> end.inject(&:&).map(&:name) <add> end <add> <ide> def puts_deps(formulae) <ide> formulae.each { |f| puts "#{f.name}: #{f.deps*' '}" } <ide> end <ide> def recursive_deps_tree f, level <ide> end <ide> end <ide> end <del> <del>class Array <del> def intersection <del> a = [] <del> each{ |b| a |= b } <del> each{ |c| a &= c } <del> a <del> end <del>end
1
Java
Java
add ipv6 support in resttemplate
2dd4480103716fd1f68c56efd519cbc20210740d
<ide><path>spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java <ide> public HierarchicalUriComponents encode(String encoding) throws UnsupportedEncod <ide> } <ide> String encodedScheme = encodeUriComponent(this.getScheme(), encoding, Type.SCHEME); <ide> String encodedUserInfo = encodeUriComponent(this.userInfo, encoding, Type.USER_INFO); <del> String encodedHost = encodeUriComponent(this.host, encoding, Type.HOST); <add> String encodedHost; <add> if(StringUtils.hasLength(this.host) && this.host.startsWith("[")) { <add> encodedHost = encodeUriComponent(this.host, encoding, Type.HOST_IPV6); <add> } else { <add> encodedHost = encodeUriComponent(this.host, encoding, Type.HOST); <add> } <add> <ide> PathComponent encodedPath = this.path.encode(encoding); <ide> MultiValueMap<String, String> encodedQueryParams = <ide> new LinkedMultiValueMap<String, String>(this.queryParams.size()); <ide> public boolean isAllowed(int c) { <ide> return isUnreserved(c) || isSubDelimiter(c); <ide> } <ide> }, <add> HOST_IPV6 { <add> @Override <add> public boolean isAllowed(int c) { <add> return isUnreserved(c) || isSubDelimiter(c) || '[' == c || ']' == c || ':' == c; <add> } <add> }, <ide> PORT { <ide> @Override <ide> public boolean isAllowed(int c) { <ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java <ide> public class UriComponentsBuilder { <ide> <ide> private static final String USERINFO_PATTERN = "([^@/]*)"; <ide> <del> private static final String HOST_PATTERN = "([^/?#:]*)"; <add> private static final String HOST_IPv4_PATTERN = "[^\\[/?#:]*"; <add> <add> private static final String HOST_IPV6_PATTERN = "\\[[\\p{XDigit}\\:\\.]*[%\\p{Alnum}]*\\]"; <add> <add> private static final String HOST_PATTERN = "("+HOST_IPV6_PATTERN + "|" + HOST_IPv4_PATTERN + ")"; <ide> <ide> private static final String PORT_PATTERN = "(\\d*)"; <ide> <ide> public static UriComponentsBuilder fromHttpUrl(String httpUrl) { <ide> String scheme = m.group(1); <ide> builder.scheme((scheme != null) ? scheme.toLowerCase() : scheme); <ide> builder.userInfo(m.group(4)); <del> builder.host(m.group(5)); <add> String host = m.group(5); <add> if(StringUtils.hasLength(scheme) && !StringUtils.hasLength(host)) { <add> throw new IllegalArgumentException("[" + httpUrl + "] is not a valid HTTP URL"); <add> } <add> builder.host(host); <ide> String port = m.group(7); <ide> if (StringUtils.hasLength(port)) { <ide> builder.port(Integer.parseInt(port)); <ide><path>spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java <ide> public void fromHttpUrlStringCaseInsesitiveScheme() { <ide> assertEquals("https", UriComponentsBuilder.fromHttpUrl("HTTPS://www.google.com").build().getScheme()); <ide> } <ide> <add> // SPR-10539 <add> <add> @Test(expected = IllegalArgumentException.class) <add> public void fromHttpUrlStringInvalidIPv6Host() throws URISyntaxException { <add> UriComponents result = UriComponentsBuilder <add> .fromHttpUrl("http://[1abc:2abc:3abc::5ABC:6abc:8080/resource").build().encode(); <add> } <add> <add> // SPR-10539 <add> <add> @Test <add> public void fromUriStringIPv6Host() throws URISyntaxException { <add> UriComponents result = UriComponentsBuilder <add> .fromUriString("http://[1abc:2abc:3abc::5ABC:6abc]:8080/resource").build().encode(); <add> assertEquals("[1abc:2abc:3abc::5ABC:6abc]",result.getHost()); <add> <add> UriComponents resultWithScopeId = UriComponentsBuilder <add> .fromUriString("http://[1abc:2abc:3abc::5ABC:6abc%eth0]:8080/resource").build().encode(); <add> assertEquals("[1abc:2abc:3abc::5ABC:6abc%25eth0]",resultWithScopeId.getHost()); <add> <add> UriComponents resultIPv4compatible = UriComponentsBuilder <add> .fromUriString("http://[::192.168.1.1]:8080/resource").build().encode(); <add> assertEquals("[::192.168.1.1]",resultIPv4compatible.getHost()); <add> } <add> <ide> @Test <ide> public void path() throws URISyntaxException { <ide> UriComponentsBuilder builder = UriComponentsBuilder.fromPath("/foo/bar");
3
Ruby
Ruby
fix documentation [ci skip]
8e314160a40c32abeab889777661b1a9bb6ae815
<ide><path>activesupport/lib/active_support/message_encryptor.rb <ide> module ActiveSupport <ide> # Though if both the secret and the cipher was changed at the same time, <ide> # the above should be combined into: <ide> # <del> # verifier.rotate old_secret, cipher: "aes-256-cbc" <add> # crypt.rotate old_secret, cipher: "aes-256-cbc" <ide> class MessageEncryptor <ide> prepend Messages::Rotator::Encryptor <ide>
1
PHP
PHP
add some fixed orders
9e0778951a45efebed0e2d3ef9eb79273fa7a799
<ide><path>lib/Cake/Test/Case/Controller/Component/PaginatorComponentTest.php <ide> public function testPaginate() { <ide> $Controller->request->query = array(); <ide> $Controller->constructClasses(); <ide> <del> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); <del> $this->assertEquals(array(1, 2, 3), $results); <del> <add> $Controller->Paginator->settings = array( <add> 'order' => array('PaginatorControllerComment.id' => 'ASC') <add> ); <ide> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerComment'), '{n}.PaginatorControllerComment.id'); <ide> $this->assertEquals(array(1, 2, 3, 4, 5, 6), $results); <ide> <add> $Controller->Paginator->settings = array( <add> 'order' => array('PaginatorControllerPost.id' => 'ASC') <add> ); <add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id'); <add> $this->assertEquals(array(1, 2, 3), $results); <add> <ide> $Controller->modelClass = null; <ide> <ide> $Controller->uses[0] = 'Plugin.PaginatorControllerPost'; <ide> public function testPaginateExtraParams() { <ide> $Controller->constructClasses(); <ide> <ide> $Controller->request->params['named'] = array('page' => '-1', 'contain' => array('PaginatorControllerComment')); <add> $Controller->Paginator->settings = array( <add> 'order' => array('PaginatorControllerPost.id' => 'ASC') <add> ); <ide> $result = $Controller->Paginator->paginate('PaginatorControllerPost'); <ide> $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']); <ide> $this->assertEquals(array(1, 2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id')); <ide><path>lib/Cake/Test/Case/Model/ModelReadTest.php <ide> public function testUnBindMultipleTimesWithDifferentResetSettings() { <ide> public function testAssociationAfterFind() { <ide> $this->loadFixtures('Post', 'Author', 'Comment'); <ide> $TestModel = new Post(); <del> $result = $TestModel->find('all'); <add> $result = $TestModel->find('all', array( <add> 'order' => array('Post.id' => 'ASC') <add> )); <ide> $expected = array( <ide> array( <ide> 'Post' => array( <ide> public function testNonNumericHabtmJoinKey() { <ide> )); <ide> $Post->Tag->primaryKey = 'tag'; <ide> <del> $result = $Post->find('all'); <add> $result = $Post->find('all', array( <add> 'order' => array('Post.id' => 'ASC') <add> )); <ide> $expected = array( <ide> array( <ide> 'Post' => array(
2
Python
Python
fix docs of past_key_values
185122ef221371964245850e47fcb547637e72ce
<ide><path>src/transformers/models/bart/modeling_bart.py <ide> def __init_subclass__(self): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two <add> additional tensors are only required when the model is used as a decoder in a Sequence to Sequence <add> model. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last ``decoder_input_ids`` <ide><path>src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py <ide> def dummy_inputs(self): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two <add> additional tensors are only required when the model is used as a decoder in a Sequence to Sequence <add> model. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last ``decoder_input_ids`` <ide><path>src/transformers/models/blenderbot/modeling_blenderbot.py <ide> def dummy_inputs(self): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two <add> additional tensors are only required when the model is used as a decoder in a Sequence to Sequence <add> model. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last ``decoder_input_ids`` <ide><path>src/transformers/models/blenderbot_small/modeling_blenderbot_small.py <ide> def dummy_inputs(self): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two <add> additional tensors are only required when the model is used as a decoder in a Sequence to Sequence <add> model. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last ``decoder_input_ids`` <ide><path>src/transformers/models/led/modeling_led.py <ide> class LEDSeq2SeqQuestionAnsweringModelOutput(ModelOutput): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide><path>src/transformers/models/m2m_100/modeling_m2m_100.py <ide> def _init_weights(self, module): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide><path>src/transformers/models/marian/modeling_marian.py <ide> def dummy_inputs(self): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two <add> additional tensors are only required when the model is used as a decoder in a Sequence to Sequence <add> model. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last ``decoder_input_ids`` <ide><path>src/transformers/models/mbart/modeling_mbart.py <ide> def dummy_inputs(self): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two <add> additional tensors are only required when the model is used as a decoder in a Sequence to Sequence <add> model. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last ``decoder_input_ids`` <ide><path>src/transformers/models/pegasus/modeling_pegasus.py <ide> def dummy_inputs(self): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two <add> additional tensors are only required when the model is used as a decoder in a Sequence to Sequence <add> model. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last ``decoder_input_ids`` <ide><path>src/transformers/models/speech_to_text/modeling_speech_to_text.py <ide> def _get_subsampled_encoder_attn_mask(self, attention_mask): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last <ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py <ide> def forward( <ide> <ide> - 1 for tokens that are **not masked**, <ide> - 0 for tokens that are **masked**. <del> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. <del> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two <add> additional tensors are only required when the model is used as a decoder in a Sequence to Sequence <add> model. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <add> decoding. <add> <add> If :obj:`past_key_values` are used, the user can optionally input only the last ``decoder_input_ids`` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <del> instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`. <add> instead of all ``decoder_input_ids`` of shape :obj:`(batch_size, sequence_length)`. <ide> labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): <ide> Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in <ide> ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are <ide> def dummy_inputs(self): <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> `optional`) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the <ide> cross-attention of the decoder. <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding. <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 tensors <add> of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of <add> shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention <add> blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids` <ide> (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)` <ide> def forward( <ide> - 1 indicates the head is **not masked**, <ide> - 0 indicates the head is **masked**. <ide> <del> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <del> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <add> past_key_values (:obj:`tuple(tuple(torch.FloatTensor))`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``): <add> Tuple of :obj:`tuple(torch.FloatTensor)` of length :obj:`config.n_layers`, with each tuple having 2 <add> tensors of shape :obj:`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional <add> tensors of shape :obj:`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. <add> <add> Contains pre-computed hidden-states (key and values in the self-attention blocks and in the <add> cross-attention blocks) that can be used (see :obj:`past_key_values` input) to speed up sequential <ide> decoding. <ide> <ide> If :obj:`past_key_values` are used, the user can optionally input only the last
11
Python
Python
use correct namespace when fqn are given
7721ac592274c16f7c2d512f74d5dd0b26e93e98
<ide><path>celery/bin/multi.py <ide> def _args_for_node(p, name, prefix, suffix, cmd, append, options): <ide> name, nodename, expand = _get_nodename( <ide> name, prefix, suffix, options) <ide> <add> if nodename in p.namespaces: <add> ns = nodename <add> else: <add> ns = name <add> <ide> argv = ([expand(cmd)] + <ide> [format_opt(opt, expand(value)) <del> for opt, value in items(p.optmerge(name, options))] + <add> for opt, value in items(p.optmerge(ns, options))] + <ide> [p.passthrough]) <ide> if append: <ide> argv.append(expand(append)) <ide><path>celery/tests/bin/test_multi.py <ide> def assert_line_in(name, args): <ide> ['COMMAND', '-n foo@', '-c 5', '']), <ide> ) <ide> <add> p4 = NamespacedOptionParser(['foo', '-Q:1', 'test']) <add> names6 = list(multi_args(p4, cmd='COMMAND', suffix='""')) <add> self.assertEqual( <add> names6[0][0:2], <add> ('foo@', <add> ['COMMAND', '-n foo@', '-Q test', '']), <add> ) <add> <add> p5 = NamespacedOptionParser(['foo@bar', '-Q:1', 'test']) <add> names7 = list(multi_args(p5, cmd='COMMAND', suffix='""')) <add> self.assertEqual( <add> names7[0][0:2], <add> ('foo@bar', <add> ['COMMAND', '-n foo@bar', '-Q test', '']), <add> ) <add> <ide> <ide> class test_MultiTool(AppCase): <ide>
2
Javascript
Javascript
fix jsdoc tag in reactelement.js
621bb09cd7e8f52bcc27fd1b0a3fc3a57b3de336
<ide><path>src/core/ReactElement.js <ide> function defineMutationMembrane(prototype) { <ide> * @param {*} type <ide> * @param {string|object} ref <ide> * @param {*} key <del> * @params {*} props <add> * @param {*} props <ide> * @internal <ide> */ <ide> var ReactElement = function(type, key, ref, owner, context, props) {
1
Python
Python
add missing return to g.setdefault
a4df0fbb397e13bd7c6475dbde5f44727474c3c7
<ide><path>flask/ctx.py <ide> def pop(self, name, default=_sentinel): <ide> return self.__dict__.pop(name, default) <ide> <ide> def setdefault(self, name, default=None): <del> self.__dict__.setdefault(name, default) <add> return self.__dict__.setdefault(name, default) <ide> <ide> def __contains__(self, item): <ide> return item in self.__dict__
1
Ruby
Ruby
remove remainder of argv stubs
1e1de8c111b5c3a36e4bdf886d6f2e736890ba56
<ide><path>Library/Homebrew/test/sandbox_test.rb <ide> def test_formula? <ide> f2 = formula { url "bar-1.0" } <ide> f2.stubs(:tap).returns(Tap.fetch("test/tap")) <ide> <del> ARGV.stubs(:sandbox?).returns true <add> ENV["HOMEBREW_SANDBOX"] = "1" <ide> assert Sandbox.formula?(f), <ide> "Formulae should be sandboxed if --sandbox was passed." <ide> <del> ARGV.stubs(:sandbox?).returns false <add> ENV.delete("HOMEBREW_SANDBOX") <ide> assert Sandbox.formula?(f), <ide> "Formulae should be sandboxed if in a sandboxed tap." <ide> refute Sandbox.formula?(f2), <ide> "Formulae should not be sandboxed if not in a sandboxed tap." <ide> end <ide> <ide> def test_test? <del> ARGV.stubs(:no_sandbox?).returns false <add> ENV.delete("HOMEBREW_NO_SANDBOX") <ide> assert Sandbox.test?, <ide> "Tests should be sandboxed unless --no-sandbox was passed." <ide> end
1
PHP
PHP
create method for import html
42aab01e71c3e1c5aec8dcb4dff8233146b275a5
<ide><path>src/Utility/Xml.php <ide> protected static function _loadXml($input, $options) <ide> { <ide> $hasDisable = function_exists('libxml_disable_entity_loader'); <ide> $internalErrors = libxml_use_internal_errors(true); <del> if ($hasDisable && !$options['loadEntities']) { <add> if ($hasDisable && empty($options['loadEntities'])) { <ide> libxml_disable_entity_loader(true); <ide> } <ide> $flags = 0; <ide> protected static function _loadXml($input, $options) <ide> } catch (Exception $e) { <ide> throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e); <ide> } finally { <del> if ($hasDisable && !$options['loadEntities']) { <add> if ($hasDisable && empty($options['loadEntities'])) { <add> libxml_disable_entity_loader(false); <add> } <add> libxml_use_internal_errors($internalErrors); <add> } <add> } <add> <add> /** <add> * Parse the input html string and create either a SimpleXmlElement object or a DOMDocument. <add> * <add> * @param string $input The input html string to load. <add> * @param array $options The options to use. See Xml::build() <add> * @return \SimpleXMLElement|\DOMDocument <add> * @throws \Cake\Utility\Exception\XmlException <add> */ <add> public static function loadHtml($input, $options) <add> { <add> $hasDisable = function_exists('libxml_disable_entity_loader'); <add> $internalErrors = libxml_use_internal_errors(true); <add> if ($hasDisable && empty($options['loadEntities'])) { <add> libxml_disable_entity_loader(true); <add> } <add> $flags = 0; <add> if (!empty($options['parseHuge'])) { <add> $flags |= LIBXML_PARSEHUGE; <add> } <add> try { <add> $xml = new DOMDocument(); <add> $xml->loadHTML($input, $flags); <add> <add> if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') { <add> $flags |= LIBXML_NOCDATA; <add> $xml = simplexml_import_dom($xml); <add> } <add> <add> return $xml; <add> } catch (Exception $e) { <add> throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e); <add> } finally { <add> if ($hasDisable && empty($options['loadEntities'])) { <ide> libxml_disable_entity_loader(false); <ide> } <ide> libxml_use_internal_errors($internalErrors);
1
PHP
PHP
load app classes automatically for plugins
08c3008874089c836e1361c556f95019f800aa9f
<ide><path>lib/Cake/Console/Command/Task/TestTask.php <ide> public function typeCanDetectFixtures($type) { <ide> */ <ide> public function isLoadableClass($package, $class) { <ide> App::uses($class, $package); <add> list($plugin, $ns) = pluginSplit($package); <add> if ($plugin) { <add> App::uses("{$plugin}AppController", $package); <add> App::uses("{$plugin}AppModel", $package); <add> App::uses("{$plugin}AppHelper", $package); <add> } <ide> return class_exists($class); <ide> } <ide>
1
Go
Go
add debug and simplify docker logs
1b0fd7ead33722d8782634d54cbd797f284aa085
<ide><path>commands.go <ide> func (cli *DockerCli) CmdLogs(args ...string) error { <ide> return nil <ide> } <ide> <del> if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1", false, nil, cli.out); err != nil { <del> return err <del> } <del> if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stderr=1", false, nil, cli.err); err != nil { <add> if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1&stderr=1", false, nil, cli.out); err != nil { <ide> return err <ide> } <ide> return nil <ide><path>server.go <ide> func (srv *Server) ContainerAttach(name string, logs, stream, stdin, stdout, std <ide> cLog, err := container.ReadLog("json") <ide> if err != nil && os.IsNotExist(err) { <ide> // Legacy logs <add> utils.Debugf("Old logs format") <ide> if stdout { <ide> cLog, err := container.ReadLog("stdout") <ide> if err != nil {
2
Javascript
Javascript
fix paths with leading periods
bf9400510f00a2962bb36162eae642c56731a34a
<ide><path>packages/ember-handlebars/lib/ext.js <ide> var normalizePath = Ember.Handlebars.normalizePath = function(root, path, data) <ide> } else { <ide> // Strip the keyword from the path and look up <ide> // the remainder from the newly found root. <del> path = path.substr(keyword.length); <add> path = path.substr(keyword.length+1); <ide> } <ide> } <ide> <ide><path>packages/ember-handlebars/tests/handlebars_test.js <ide> test("child views can be inserted using the {{view}} Handlebars helper", functio <ide> <ide> test("should accept relative paths to views", function() { <ide> view = Ember.View.create({ <del> template: Ember.Handlebars.compile('Hey look, at {{view ".myCool.view"}}'), <add> template: Ember.Handlebars.compile('Hey look, at {{view "myCool.view"}}'), <ide> <ide> myCool: Ember.Object.create({ <ide> view: Ember.View.extend({
2
Text
Text
remove superfluous mdn link in assert.md
a013aa0f5eba9915e2c996e32281433f72d495ae
<ide><path>doc/api/assert.md <ide> The `assert` module provides a set of assertion functions for verifying <ide> invariants. The module provides a recommended [`strict` mode][] and a more <ide> lenient legacy mode. <ide> <del>For more information about the used equality comparisons see <del>[MDN's guide on equality comparisons and sameness][mdn-equality-guide]. <del> <ide> ## Class: assert.AssertionError <ide> <ide> A subclass of `Error` that indicates the failure of an assertion. All errors <ide> second argument. This might lead to difficult-to-spot errors. <ide> [SameValue Comparison]: https://tc39.github.io/ecma262/#sec-samevalue <ide> [Strict Equality Comparison]: https://tc39.github.io/ecma262/#sec-strict-equality-comparison <ide> [enumerable "own" properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties <del>[mdn-equality-guide]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness <ide> [prototype-spec]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
1
Ruby
Ruby
add action cable test adapter
f7dd2d67d6a8b74f2762be51dff4f96983175aee
<ide><path>actioncable/lib/action_cable/subscription_adapter.rb <ide> module SubscriptionAdapter <ide> extend ActiveSupport::Autoload <ide> <ide> autoload :Base <add> autoload :Test <ide> autoload :SubscriberMap <ide> autoload :ChannelPrefix <ide> end <ide><path>actioncable/lib/action_cable/subscription_adapter/test.rb <add># frozen_string_literal: true <add> <add>require_relative "async" <add> <add>module ActionCable <add> module SubscriptionAdapter <add> # == Test adapter for Action Cable <add> # <add> # The test adapter should be used only in testing. Along with <add> # <tt>ActionCable::TestHelper</tt> it makes a great tool to test your Rails application. <add> # <add> # To use the test adapter set adapter value to +test+ in your +cable.yml+. <add> # <add> # NOTE: Test adapter extends the <tt>ActionCable::SubscriptionsAdapter::Async</tt> adapter, <add> # so it could be used in system tests too. <add> class Test < Async <add> def broadcast(channel, payload) <add> broadcasts(channel) << payload <add> super <add> end <add> <add> def broadcasts(channel) <add> channels_data[channel] ||= [] <add> end <add> <add> def clear_messages(channel) <add> channels_data[channel] = [] <add> end <add> <add> def clear <add> @channels_data = nil <add> end <add> <add> private <add> def channels_data <add> @channels_data ||= {} <add> end <add> end <add> end <add>end <ide><path>actioncable/test/subscription_adapter/test_adapter_test.rb <add># frozen_string_literal: true <add> <add>require "test_helper" <add>require_relative "common" <add> <add>class ActionCable::SubscriptionAdapter::TestTest < ActionCable::TestCase <add> include CommonSubscriptionAdapterTest <add> <add> def setup <add> super <add> <add> @tx_adapter.shutdown <add> @tx_adapter = @rx_adapter <add> end <add> <add> def cable_config <add> { adapter: "test" } <add> end <add> <add> test "#broadcast stores messages for streams" do <add> @tx_adapter.broadcast("channel", "payload") <add> @tx_adapter.broadcast("channel2", "payload2") <add> <add> assert_equal ["payload"], @tx_adapter.broadcasts("channel") <add> assert_equal ["payload2"], @tx_adapter.broadcasts("channel2") <add> end <add> <add> test "#clear_messages deletes recorded broadcasts for the channel" do <add> @tx_adapter.broadcast("channel", "payload") <add> @tx_adapter.broadcast("channel2", "payload2") <add> <add> @tx_adapter.clear_messages("channel") <add> <add> assert_equal [], @tx_adapter.broadcasts("channel") <add> assert_equal ["payload2"], @tx_adapter.broadcasts("channel2") <add> end <add> <add> test "#clear deletes all recorded broadcasts" do <add> @tx_adapter.broadcast("channel", "payload") <add> @tx_adapter.broadcast("channel2", "payload2") <add> <add> @tx_adapter.clear <add> <add> assert_equal [], @tx_adapter.broadcasts("channel") <add> assert_equal [], @tx_adapter.broadcasts("channel2") <add> end <add>end
3
Java
Java
add committed flag to reactivehttpoutputmessage
9142427c4d898db174aa895494269ff6d2372556
<ide><path>spring-web/src/main/java/org/springframework/http/ReactiveHttpOutputMessage.java <ide> /** <ide> * A "reactive" HTTP output message that accepts output as a {@link Publisher}. <ide> * <del> * <p>Typically implemented by an HTTP request on the client-side or a response <del> * on the server-side. <add> * <p>Typically implemented by an HTTP request on the client-side or an <add> * HTTP response on the server-side. <ide> * <ide> * @author Arjen Poutsma <ide> * @author Sebastien Deleuze <ide> public interface ReactiveHttpOutputMessage extends HttpMessage { <ide> <ide> /** <del> * Return a {@link DataBufferFactory} that can be used for creating the body. <add> * Return a {@link DataBufferFactory} that can be used to create the body. <ide> * @return a buffer factory <ide> * @see #writeWith(Publisher) <ide> */ <ide> DataBufferFactory bufferFactory(); <ide> <ide> /** <del> * Register an action to be applied just before the message is committed. <del> * @param action the action <add> * Register an action to apply just before the HttpOutputMessage is committed. <add> * @param action the action to apply <ide> */ <ide> void beforeCommit(Supplier<? extends Mono<Void>> action); <ide> <ide> /** <del> * Use the given {@link Publisher} to write the body of the message to the underlying <del> * HTTP layer. <add> * Whether the HttpOutputMessage is committed. <add> */ <add> boolean isCommitted(); <add> <add> /** <add> * Use the given {@link Publisher} to write the body of the message to the <add> * underlying HTTP layer. <ide> * @param body the body content publisher <ide> * @return a {@link Mono} that indicates completion or error <ide> */ <ide> Mono<Void> writeWith(Publisher<? extends DataBuffer> body); <ide> <ide> /** <del> * Use the given {@link Publisher} of {@code Publishers} to write the body of the <del> * message to the underlying HTTP layer, flushing after each <del> * {@code Publisher<DataBuffer>}. <add> * Use the given {@link Publisher} of {@code Publishers} to write the body <add> * of the HttpOutputMessage to the underlying HTTP layer, flushing after <add> * each {@code Publisher<DataBuffer>}. <ide> * @param body the body content publisher <ide> * @return a {@link Mono} that indicates completion or error <ide> */ <ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/AbstractClientHttpRequest.java <ide> public MultiValueMap<String, HttpCookie> getCookies() { <ide> return this.cookies; <ide> } <ide> <add> @Override <add> public void beforeCommit(Supplier<? extends Mono<Void>> action) { <add> Assert.notNull(action, "Action must not be null"); <add> this.commitActions.add(action); <add> } <add> <add> @Override <add> public boolean isCommitted() { <add> return this.state.get() != State.NEW; <add> } <add> <ide> /** <ide> * A variant of {@link #doCommit(Supplier)} for a request without body. <ide> * @return a completion publisher <ide> */ <ide> protected Mono<Void> doCommit() { <del> return (this.state.get() == State.NEW ? doCommit(null) : Mono.empty()); <add> return doCommit(null); <ide> } <ide> <ide> /** <ide> protected Mono<Void> doCommit() { <ide> */ <ide> protected Mono<Void> doCommit(Supplier<? extends Mono<Void>> writeAction) { <ide> <del> if (!this.state.compareAndSet(AbstractClientHttpRequest.State.NEW, AbstractClientHttpRequest.State.COMMITTING)) { <add> if (!this.state.compareAndSet(State.NEW, State.COMMITTING)) { <ide> return Mono.empty(); <ide> } <ide> <ide> this.commitActions.add(() -> { <ide> applyHeaders(); <ide> applyCookies(); <del> this.state.set(AbstractClientHttpRequest.State.COMMITTED); <add> this.state.set(State.COMMITTED); <ide> return Mono.empty(); <ide> }); <ide> <ide> protected Mono<Void> doCommit(Supplier<? extends Mono<Void>> writeAction) { <ide> return Flux.concat(actions).next(); <ide> } <ide> <del> @Override <del> public void beforeCommit(Supplier<? extends Mono<Void>> action) { <del> Assert.notNull(action, "Action must not be null"); <del> this.commitActions.add(action); <del> } <del> <ide> /** <ide> * Implement this method to apply header changes from {@link #getHeaders()} <ide> * to the underlying response. This method is called once only. <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java <ide> public abstract class AbstractServerHttpResponse implements ServerHttpResponse { <ide> * response during which time pre-commit actions can still make changes to <ide> * the response status and headers. <ide> */ <del> private enum State {NEW, COMMITTING, COMMITTED}; <add> private enum State {NEW, COMMITTING, COMMITTED} <ide> <ide> <ide> private final Log logger = LogFactory.getLog(getClass()); <ide> public void beforeCommit(Supplier<? extends Mono<Void>> action) { <ide> } <ide> } <ide> <add> @Override <add> public boolean isCommitted() { <add> return this.state.get() != State.NEW; <add> } <add> <ide> @Override <ide> public final Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { <ide> return new ChannelSendOperator<>(body, <ide> public final Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extend <ide> <ide> @Override <ide> public Mono<Void> setComplete() { <del> return doCommit(); <add> return doCommit(null); <ide> } <ide> <ide> /** <ide> * A variant of {@link #doCommit(Supplier)} for a response without no body. <ide> * @return a completion publisher <ide> */ <ide> protected Mono<Void> doCommit() { <del> return (this.state.get() == State.NEW ? doCommit(null) : Mono.empty()); <add> return doCommit(null); <ide> } <ide> <ide> /** <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServerHttpResponseDecorator.java <ide> public void beforeCommit(Supplier<? extends Mono<Void>> action) { <ide> getDelegate().beforeCommit(action); <ide> } <ide> <add> @Override <add> public boolean isCommitted() { <add> return getDelegate().isCommitted(); <add> } <add> <ide> @Override <ide> public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) { <ide> return getDelegate().writeWith(body);
4
Python
Python
add two functions for more dry reverse fk tests
2910bfb5275c88d30aa73e580a35a46684177d38
<ide><path>rest_framework/tests/nested_relations.py <ide> def setUp(self): <ide> self.new_target_data = {'id': 2, 'name': u'target-2', 'sources': []} <ide> self.data = [self.target_data, self.new_target_data] <ide> <del> def test_reverse_foreign_key_retrieve(self): <add> def save_serialized_target(self, instance, data): <add> serializer = ForeignKeyTargetSerializer(instance, data=data) <add> self.assertTrue(serializer.is_valid()) <add> self.assertEquals(serializer.data, data) <add> serializer.save() <add> <add> def check_serialized_targets(self, data): <ide> queryset = ForeignKeyTarget.objects.all() <ide> serializer = ForeignKeyTargetSerializer(queryset) <del> self.assertEquals(serializer.data, self.data) <add> self.assertEquals(serializer.data, data) <add> <add> def test_reverse_foreign_key_retrieve(self): <add> self.check_serialized_targets(self.data) <ide> <ide> def test_reverse_foreign_key_create(self): <ide> data = deepcopy(self.new_target_data) <ide> data['sources'].append({'name': u'source-4', 'target': 2}) <ide> instance = ForeignKeyTarget.objects.get(pk=2) <del> serializer = ForeignKeyTargetSerializer(instance, data=data) <del> self.assertTrue(serializer.is_valid()) <del> self.assertEquals(serializer.data, data) <del> serializer.save() <add> self.save_serialized_target(instance, data) <ide> <ide> # Ensure target 2 has new source and everything else is as expected <del> queryset = ForeignKeyTarget.objects.all() <del> serializer = ForeignKeyTargetSerializer(queryset) <ide> expected = deepcopy(self.data) <ide> expected[1]['sources'].append({'id': 4, 'name': 'source-4', 'target': 2}) <del> self.assertEquals(serializer.data, expected) <add> self.check_serialized_targets(expected) <ide> <ide> def test_reverse_foreign_key_update(self): <ide> data = deepcopy(self.target_data) <ide> data['sources'][0]['name'] = 'source-1-changed' <ide> data['sources'][2]['name'] = 'source-3-changed' <ide> instance = ForeignKeyTarget.objects.get(pk=1) <del> serializer = ForeignKeyTargetSerializer(instance, data=data) <del> self.assertTrue(serializer.is_valid()) <del> self.assertEquals(serializer.data, data) <del> serializer.save() <add> self.save_serialized_target(instance, data) <ide> <ide> # Ensure target 1 is updated, and everything else is as expected <del> queryset = ForeignKeyTarget.objects.all() <del> serializer = ForeignKeyTargetSerializer(queryset) <ide> expected = deepcopy(self.data) <ide> expected[0]['sources'][0]['name'] = 'source-1-changed' <ide> expected[0]['sources'][2]['name'] = 'source-3-changed' <del> self.assertEquals(serializer.data, expected) <add> self.check_serialized_targets(expected) <ide> <ide> def test_reverse_foreign_key_delete(self): <ide> data = deepcopy(self.target_data) <ide> del data['sources'][2] <ide> instance = ForeignKeyTarget.objects.get(pk=1) <del> serializer = ForeignKeyTargetSerializer(instance, data=data) <del> self.assertTrue(serializer.is_valid()) <del> self.assertEquals(serializer.data, data) <del> serializer.save() <add> self.save_serialized_target(instance, data) <ide> <ide> # Ensure target 1 has 2 sources and everything else is as expected <del> queryset = ForeignKeyTarget.objects.all() <del> serializer = ForeignKeyTargetSerializer(queryset) <ide> expected = deepcopy(self.data) <ide> del expected[0]['sources'][2] <del> self.assertEquals(serializer.data, expected) <add> self.check_serialized_targets(expected)
1
Go
Go
port a docker diff test
5cab19a08b9a29a22ee956de4520fceab2be5e3b
<ide><path>integration-cli/docker_cli_diff_test.go <ide> package main <ide> <ide> import ( <ide> "strings" <add> "time" <ide> <ide> "github.com/docker/docker/pkg/integration/checker" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> // ensure that an added file shows up in docker diff <ide> func (s *DockerSuite) TestDiffFilenameShownInOutput(c *check.C) { <del> testRequires(c, DaemonIsLinux) <del> containerCmd := `echo foo > /root/bar` <add> containerCmd := `mkdir /foo; echo xyzzy > /foo/bar` <ide> out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", containerCmd) <ide> <add> // Wait for it to exit as cannot diff a running container on Windows, and <add> // it will take a few seconds to exit. Also there's no way in Windows to <add> // differentiate between an Add or a Modify, and all files are under <add> // a "Files/" prefix. <add> containerID := strings.TrimSpace(out) <add> lookingFor := "A /foo/bar" <add> if daemonPlatform == "windows" { <add> err := waitExited(containerID, 60*time.Second) <add> c.Assert(err, check.IsNil) <add> lookingFor = "C Files/foo/bar" <add> } <add> <ide> cleanCID := strings.TrimSpace(out) <ide> out, _ = dockerCmd(c, "diff", cleanCID) <ide> <ide> found := false <ide> for _, line := range strings.Split(out, "\n") { <del> if strings.Contains("A /root/bar", line) { <add> if strings.Contains(line, lookingFor) { <ide> found = true <ide> break <ide> }
1
Java
Java
remove unused logger field
b2cf2b9d4879636d9aa3843175bff7cc8a8745fe
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/BindingReflectionHintsRegistrar.java <ide> <ide> import kotlin.jvm.JvmClassMappingKt; <ide> import kotlin.reflect.KClass; <del>import org.apache.commons.logging.Log; <del>import org.apache.commons.logging.LogFactory; <ide> <ide> import org.springframework.core.KotlinDetector; <ide> import org.springframework.core.MethodParameter; <ide> */ <ide> public class BindingReflectionHintsRegistrar { <ide> <del> private static final Log logger = LogFactory.getLog(BindingReflectionHintsRegistrar.class); <del> <ide> private static final String KOTLIN_COMPANION_SUFFIX = "$Companion"; <ide> <ide> /**
1
Python
Python
fix flavaforpretrainingintegrationtest ci test
3fb82f74fd67cbae4a5a7e83168dc161e33c97c7
<ide><path>tests/models/flava/test_modeling_flava.py <ide> def test_inference(self): <ide> <ide> expected_logits = torch.tensor([[16.1291, 8.4033], [16.1291, 8.4033]], device=torch_device) <ide> self.assertTrue(torch.allclose(outputs.contrastive_logits_per_image, expected_logits, atol=1e-3)) <del> self.assertAlmostEqual(outputs.loss_info.mmm_text.item(), 1.75533199) <add> self.assertAlmostEqual(outputs.loss_info.mmm_text.item(), 1.75533199, places=4) <ide> self.assertAlmostEqual(outputs.loss_info.mmm_image.item(), 7.0290069, places=4) <ide> self.assertAlmostEqual(outputs.loss.item(), 11.0626, places=4)
1
Javascript
Javascript
fix node tests to use new apis
5fca89003b46eba529cc7d9e05cf8cb32451309e
<ide><path>tests/node/helpers/app-module.js <ide> module.exports = function(moduleName) { <ide> QUnit.module(moduleName, { <ide> beforeEach: function() { <ide> var Ember = this.Ember = require(emberPath); <del> var DOMHelper = Ember.HTMLBars.DOMHelper; <add> <ide> Ember.testing = true; <ide> <ide> this.compile = require(templateCompilerPath).compile; <del> this.domHelper = createDOMHelper(DOMHelper); <ide> this.run = Ember.run; <ide> this.all = Ember.RSVP.all; <ide> <ide> module.exports = function(moduleName) { <ide> this.view = registerView; <ide> this.routes = registerRoutes; <ide> this.registry = {}; <del> this.renderToElement = renderToElement; <ide> this.renderToHTML = renderToHTML; <add> <add> // TODO: REMOVE ME <add> <add> // Patch DOMHelper <add> Ember.HTMLBars.DOMHelper.prototype.zomg = "ZOMG"; <add> <add> Ember.HTMLBars.DOMHelper.prototype.protocolForURL = function(url) { <add> var protocol = URL.parse(url).protocol; <add> return (protocol == null) ? ':' : protocol; <add> }; <add> <add> Ember.HTMLBars.DOMHelper.prototype.setMorphHTML = function(morph, html) { <add> var section = this.document.createRawHTMLSection(html); <add> morph.setNode(section); <add> }; <ide> }, <ide> <ide> afterEach: function() { <ide> module.exports = function(moduleName) { <ide> module.exports.canRunTests = canRunTests; <ide> <ide> function createApplication() { <add> if (this.app) return this.app; <add> <ide> var app = this.Ember.Application.extend().create({ <ide> autoboot: false <ide> }); <ide> function createApplication() { <ide> app.Router.map(this.routesCallback); <ide> } <ide> <del> registerDOMHelper(this.Ember, app, this.domHelper); <ide> registerApplicationClasses(app, this.registry); <ide> <del> this.run(function() { <del> app.boot(); <del> }); <add> // Run application initializers <add> this.run(app, 'boot'); <add> <ide> this.app = app; <ide> <ide> return app; <ide> function register(containerKey, klass) { <ide> } <ide> <ide> function visit(url) { <del> if (!this.app) { this.createApplication(); } <add> var app = this.createApplication(); <add> var dom = new SimpleDOM.Document(); <ide> <del> var promise; <del> this.run(this, function() { <del> promise = this.app.visit(url); <del> }); <del> <del> return promise; <del>} <del> <del>function registerDOMHelper(Ember, app, domHelper) { <del> app.initializer({ <del> name: 'register-dom-helper', <del> initialize: function(app) { <del> app.register('renderer:-dom', { <del> create: function() { <del> return new Ember._Renderer(domHelper, false); <del> } <del> }); <del> } <add> return this.run(app, 'visit', url, { <add> isBrowser: false, <add> document: dom, <add> rootElement: dom.body <ide> }); <ide> } <ide> <del>function createDOMHelper(DOMHelper) { <del> var document = new SimpleDOM.Document(); <del> var domHelper = new DOMHelper(document); <del> <del> domHelper.protocolForURL = function(url) { <del> var protocol = URL.parse(url).protocol; <del> return (protocol == null) ? ':' : protocol; <del> }; <del> <del> domHelper.setMorphHTML = function(morph, html) { <del> var section = this.document.createRawHTMLSection(html); <del> morph.setNode(section); <del> }; <add>function renderToHTML(url) { <add> var app = this.createApplication(); <add> var dom = new SimpleDOM.Document(); <add> var root = dom.body; <add> <add> return this.run(app, 'visit', url, { <add> isBrowser: false, <add> document: dom, <add> rootElement: root <add> }).then(function() { <add> var element = root; <add> var serializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap); <add> var serialized = serializer.serialize(root); <ide> <del> return domHelper; <add> return serialized; <add> }); <ide> } <ide> <ide> function registerApplicationClasses(app, registry) { <ide> function registerView(name, viewProps) { <ide> function registerRoutes(cb) { <ide> this.routesCallback = cb; <ide> } <del> <del>function renderToElement(instance) { <del> var element; <del> this.run(function() { <del> element = instance.view.renderToElement(); <del> }); <del> <del> return element; <del>} <del> <del>function renderToHTML(route) { <del> var self = this; <del> return this.visit(route).then(function(instance) { <del> var element = self.renderToElement(instance); <del> var serializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap); <del> var serialized = serializer.serialize(element); <del> <del> return serialized; <del> }); <del>}
1
Python
Python
fix integrityerror during webserver startup
8f99c793ec4289f7fc28d890b6c2887f0951e09b
<ide><path>airflow/cli/commands/webserver_command.py <ide> def webserver(args): <ide> <ide> run_args += ["airflow.www.app:cached_app()"] <ide> <add> # To prevent different workers creating the web app and <add> # all writing to the database at the same time, we use the --preload option. <add> # With the preload option, the app is loaded before the workers are forked, and each worker will <add> # then have a copy of the app <add> run_args += ['--preload'] <add> <ide> gunicorn_master_proc = None <ide> <ide> def kill_proc(signum, _): <ide><path>tests/cli/commands/test_webserver_command.py <ide> def test_cli_webserver_args(self): <ide> "--access-logformat", <ide> "custom_log_format", <ide> "airflow.www.app:cached_app()", <add> "--preload", <ide> ], <ide> close_fds=True, <ide> )
2
Go
Go
remove kernelmemory tests
2f0d6664a11f70a27ff5835f60e6d4408681bd75
<ide><path>integration-cli/docker_cli_run_unix_test.go <ide> func (s *DockerSuite) TestRunWithInvalidCpuPeriod(c *testing.T) { <ide> assert.Assert(c, strings.Contains(out, expected)) <ide> } <ide> <del>func (s *DockerSuite) TestRunWithKernelMemory(c *testing.T) { <del> testRequires(c, DaemonIsLinux, kernelMemorySupport) <del> <del> file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes" <del> cli.DockerCmd(c, "run", "--kernel-memory", "50M", "--name", "test1", "busybox", "cat", file).Assert(c, icmd.Expected{ <del> Out: "52428800", <del> }) <del> <del> cli.InspectCmd(c, "test1", cli.Format(".HostConfig.KernelMemory")).Assert(c, icmd.Expected{ <del> Out: "52428800", <del> }) <del>} <del> <del>func (s *DockerSuite) TestRunWithInvalidKernelMemory(c *testing.T) { <del> testRequires(c, DaemonIsLinux, kernelMemorySupport) <del> <del> out, _, err := dockerCmdWithError("run", "--kernel-memory", "2M", "busybox", "true") <del> assert.ErrorContains(c, err, "") <del> expected := "Minimum kernel memory limit allowed is 4MB" <del> assert.Assert(c, strings.Contains(out, expected)) <del> <del> out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test") <del> assert.ErrorContains(c, err, "") <del> expected = "invalid size" <del> assert.Assert(c, strings.Contains(out, expected)) <del>} <del> <ide> func (s *DockerSuite) TestRunWithCPUShares(c *testing.T) { <ide> testRequires(c, cpuShare) <ide> <ide><path>integration-cli/docker_cli_update_unix_test.go <ide> import ( <ide> "github.com/creack/pty" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/client" <del> "github.com/docker/docker/pkg/parsers/kernel" <ide> "github.com/docker/docker/testutil/request" <ide> "gotest.tools/v3/assert" <ide> ) <ide> func (s *DockerSuite) TestUpdateContainerWithoutFlags(c *testing.T) { <ide> assert.ErrorContains(c, err, "") <ide> } <ide> <del>func (s *DockerSuite) TestUpdateKernelMemory(c *testing.T) { <del> testRequires(c, DaemonIsLinux, kernelMemorySupport) <del> <del> name := "test-update-container" <del> dockerCmd(c, "run", "-d", "--name", name, "--kernel-memory", "50M", "busybox", "top") <del> dockerCmd(c, "update", "--kernel-memory", "100M", name) <del> <del> assert.Equal(c, inspectField(c, name, "HostConfig.KernelMemory"), "104857600") <del> <del> file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes" <del> out, _ := dockerCmd(c, "exec", name, "cat", file) <del> assert.Equal(c, strings.TrimSpace(out), "104857600") <del>} <del> <del>func (s *DockerSuite) TestUpdateKernelMemoryUninitialized(c *testing.T) { <del> testRequires(c, DaemonIsLinux, kernelMemorySupport) <del> <del> isNewKernel := CheckKernelVersion(4, 6, 0) <del> name := "test-update-container" <del> dockerCmd(c, "run", "-d", "--name", name, "busybox", "top") <del> _, _, err := dockerCmdWithError("update", "--kernel-memory", "100M", name) <del> // Update kernel memory to a running container without kernel memory initialized <del> // is not allowed before kernel version 4.6. <del> if !isNewKernel { <del> assert.ErrorContains(c, err, "") <del> } else { <del> assert.NilError(c, err) <del> } <del> <del> dockerCmd(c, "pause", name) <del> _, _, err = dockerCmdWithError("update", "--kernel-memory", "200M", name) <del> if !isNewKernel { <del> assert.ErrorContains(c, err, "") <del> } else { <del> assert.NilError(c, err) <del> } <del> dockerCmd(c, "unpause", name) <del> <del> dockerCmd(c, "stop", name) <del> dockerCmd(c, "update", "--kernel-memory", "300M", name) <del> dockerCmd(c, "start", name) <del> <del> assert.Equal(c, inspectField(c, name, "HostConfig.KernelMemory"), "314572800") <del> <del> file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes" <del> out, _ := dockerCmd(c, "exec", name, "cat", file) <del> assert.Equal(c, strings.TrimSpace(out), "314572800") <del>} <del> <del>// GetKernelVersion gets the current kernel version. <del>func GetKernelVersion() *kernel.VersionInfo { <del> v, _ := kernel.ParseRelease(testEnv.DaemonInfo.KernelVersion) <del> return v <del>} <del> <del>// CheckKernelVersion checks if current kernel is newer than (or equal to) <del>// the given version. <del>func CheckKernelVersion(k, major, minor int) bool { <del> return kernel.CompareKernelVersion(*GetKernelVersion(), kernel.VersionInfo{Kernel: k, Major: major, Minor: minor}) >= 0 <del>} <del> <ide> func (s *DockerSuite) TestUpdateSwapMemoryOnly(c *testing.T) { <ide> testRequires(c, DaemonIsLinux) <ide> testRequires(c, memoryLimitSupport) <ide><path>integration-cli/requirements_unix_test.go <ide> import ( <ide> "os/exec" <ide> "strings" <ide> <del> "github.com/docker/docker/pkg/parsers/kernel" <ide> "github.com/docker/docker/pkg/sysinfo" <ide> ) <ide> <ide> func pidsLimit() bool { <ide> return SysInfo.PidsLimit <ide> } <ide> <del>func kernelMemorySupport() bool { <del> // TODO remove this once kmem support in RHEL kernels is fixed. See https://github.com/opencontainers/runc/pull/1921 <del> daemonV, err := kernel.ParseRelease(testEnv.DaemonInfo.KernelVersion) <del> if err != nil { <del> return false <del> } <del> requiredV := kernel.VersionInfo{Kernel: 3, Major: 10} <del> if kernel.CompareKernelVersion(*daemonV, requiredV) < 1 { <del> // On Kernel 3.10 and under, don't consider kernel memory to be supported, <del> // even if the kernel (and thus the daemon) reports it as being supported <del> return false <del> } <del> return testEnv.DaemonInfo.KernelMemory <del>} <del> <ide> func memoryLimitSupport() bool { <ide> return testEnv.DaemonInfo.MemoryLimit <ide> } <ide><path>integration/container/run_linux_test.go <ide> package container // import "github.com/docker/docker/integration/container" <ide> <ide> import ( <ide> "context" <del> "strconv" <ide> "strings" <ide> "testing" <ide> "time" <ide> import ( <ide> "gotest.tools/v3/skip" <ide> ) <ide> <del>func TestKernelTCPMemory(t *testing.T) { <del> skip.If(t, testEnv.DaemonInfo.OSType != "linux") <del> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "skip test from new feature") <del> skip.If(t, testEnv.DaemonInfo.CgroupDriver == "none") <del> skip.If(t, !testEnv.DaemonInfo.KernelMemoryTCP) <del> <del> defer setupTest(t)() <del> client := testEnv.APIClient() <del> ctx := context.Background() <del> <del> const ( <del> kernelMemoryTCP int64 = 200 * 1024 * 1024 <del> ) <del> <del> cID := container.Run(ctx, t, client, func(c *container.TestContainerConfig) { <del> c.HostConfig.Resources = containertypes.Resources{ <del> KernelMemoryTCP: kernelMemoryTCP, <del> } <del> }) <del> <del> poll.WaitOn(t, container.IsInState(ctx, client, cID, "running"), poll.WithDelay(100*time.Millisecond)) <del> <del> inspect, err := client.ContainerInspect(ctx, cID) <del> assert.NilError(t, err) <del> assert.Check(t, is.Equal(kernelMemoryTCP, inspect.HostConfig.KernelMemoryTCP)) <del> <del> res, err := container.Exec(ctx, client, cID, <del> []string{"cat", "/sys/fs/cgroup/memory/memory.kmem.tcp.limit_in_bytes"}) <del> assert.NilError(t, err) <del> assert.Assert(t, is.Len(res.Stderr(), 0)) <del> assert.Equal(t, 0, res.ExitCode) <del> assert.Check(t, is.Equal(strconv.FormatInt(kernelMemoryTCP, 10), strings.TrimSpace(res.Stdout()))) <del>} <del> <ide> func TestNISDomainname(t *testing.T) { <ide> // Older versions of the daemon would concatenate hostname and domainname, <ide> // so hostname "foobar" and domainname "baz.cyphar.com" would produce
4
Ruby
Ruby
walk entire keg to find object files to relocate
54d0043771c0f577554f19a81fc4e251531f5ff4
<ide><path>Library/Homebrew/keg_fix_install_names.rb <ide> def find_dylib name <ide> <ide> def mach_o_files <ide> mach_o_files = [] <del> dirs = %w{bin sbin lib Frameworks} <del> dirs.map! { |dir| path.join(dir) } <del> dirs.reject! { |dir| not dir.directory? } <del> <del> dirs.each do |dir| <del> dir.find do |pn| <del> next if pn.symlink? or pn.directory? <del> mach_o_files << pn if pn.dylib? or pn.mach_o_bundle? or pn.mach_o_executable? <del> end <add> path.find do |pn| <add> next if pn.symlink? or pn.directory? <add> mach_o_files << pn if pn.dylib? or pn.mach_o_bundle? or pn.mach_o_executable? <ide> end <ide> <ide> mach_o_files
1
PHP
PHP
add test for incrementing forever cache item
e3c381570a239c2d8d96607eeef5173a760af50d
<ide><path>tests/Cache/CacheFileStoreTest.php <ide> public function testForeversAreStoredWithHighTimestamp() <ide> $store->forever('foo', 'Hello World', 10); <ide> } <ide> <add> public function testForeversAreNotRemovedOnIncrement() <add> { <add> $files = $this->mockFilesystem(); <add> $contents = '9999999999'.serialize('Hello World'); <add> $store = new FileStore($files, __DIR__); <add> $store->forever('foo', 'Hello World'); <add> $store->increment('foo'); <add> $files->expects($this->once())->method('get')->will($this->returnValue($contents)); <add> $this->assertEquals('Hello World', $store->get('foo')); <add> } <add> <ide> public function testRemoveDeletesFileDoesntExist() <ide> { <ide> $files = $this->mockFilesystem();
1
Javascript
Javascript
add capitalize function to ember.string
c0207ba0a0948f70ed65f5e3095ec7ea40463259
<ide><path>packages/ember-runtime/lib/ext/string.js <ide> var fmt = Ember.String.fmt, <ide> decamelize = Ember.String.decamelize, <ide> dasherize = Ember.String.dasherize, <ide> underscore = Ember.String.underscore, <add> capitalize = Ember.String.capitalize, <ide> classify = Ember.String.classify; <ide> <ide> if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { <ide> if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { <ide> String.prototype.classify = function() { <ide> return classify(this); <ide> }; <add> <add> /** <add> See {{#crossLink "Ember.String/capitalize"}}{{/crossLink}} <add> <add> @method capitalize <add> @for String <add> */ <add> String.prototype.capitalize = function() { <add> return capitalize(this); <add> }; <add> <ide> } <ide> <ide><path>packages/ember-runtime/lib/system/string.js <ide> Ember.String = { <ide> underscore: function(str) { <ide> return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2'). <ide> replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase(); <add> }, <add> <add> /** <add> Returns the Capitalized form of a string <add> <add> 'innerHTML'.capitalize() => 'InnerHTML' <add> 'action_name'.capitalize() => 'Action_name' <add> 'css-class-name'.capitalize() => 'Css-class-name' <add> 'my favorite items'.capitalize() => 'My favorite items' <add> <add> @param {String} str <add> <add> @returns {String} <add> */ <add> capitalize: function(str) { <add> return str.charAt(0).toUpperCase() + str.substr(1); <ide> } <add> <ide> }; <ide><path>packages/ember-runtime/tests/system/string/capitalize.js <add>// ========================================================================== <add>// Project: Ember Runtime <add>// Copyright: ©2006-2011 Strobe Inc. and contributors. <add>// ©2008-2011 Apple Inc. All rights reserved. <add>// License: Licensed under MIT license (see license.js) <add>// ========================================================================== <add> <add>module('Ember.String.capitalize'); <add> <add>test("capitalize normal string", function() { <add> deepEqual(Ember.String.capitalize('my favorite items'), 'My favorite items'); <add> if (Ember.EXTEND_PROTOTYPES) { <add> deepEqual('my favorite items'.capitalize(), 'My favorite items'); <add> } <add>}); <add> <add>test("capitalize dasherized string", function() { <add> deepEqual(Ember.String.capitalize('css-class-name'), 'Css-class-name'); <add> if (Ember.EXTEND_PROTOTYPES) { <add> deepEqual('css-class-name'.capitalize(), 'Css-class-name'); <add> } <add>}); <add> <add>test("capitalize underscored string", function() { <add> deepEqual(Ember.String.capitalize('action_name'), 'Action_name'); <add> if (Ember.EXTEND_PROTOTYPES) { <add> deepEqual('action_name'.capitalize(), 'Action_name'); <add> } <add>}); <add> <add>test("capitalize camelcased string", function() { <add> deepEqual(Ember.String.capitalize('innerHTML'), 'InnerHTML'); <add> if (Ember.EXTEND_PROTOTYPES) { <add> deepEqual('innerHTML'.capitalize(), 'InnerHTML'); <add> } <add>}); <add> <add>test("does nothing with capitalized string", function() { <add> deepEqual(Ember.String.capitalize('Capitalized string'), 'Capitalized string'); <add> if (Ember.EXTEND_PROTOTYPES) { <add> deepEqual('Capitalized string'.capitalize(), 'Capitalized string'); <add> } <add>}); <add>
3
Text
Text
add example of null to assert.iferror
08ada72cc692163979f574ee00de81cbfd730994
<ide><path>doc/api/assert.md <ide> argument in callbacks. <ide> ```js <ide> const assert = require('assert').strict; <ide> <add>assert.ifError(null); <add>// OK <ide> assert.ifError(0); <ide> // OK <ide> assert.ifError(1);
1
Text
Text
review russian translation of the article
21dc67040b81f9a2381690a647914eed591236f7
<ide><path>guide/russian/javascript/advantages-and-disadvantages-of-javascript/index.md <ide> localeTitle: Преимущества и недостатки JavaScript <ide> --- <ide> # Преимущества и недостатки JavaScript <ide> <del>Как и все языки компьютера, JavaScript имеет определенные преимущества и недостатки. Многие из плюсов и минусов связаны с JavaScript, выполняемым часто в браузере клиента, но есть и другие способы использования JavaScript, которые позволяют ему иметь те же преимущества на серверных языках. <add>Как и все языки программирования, JavaScript имеет определенные преимущества и недостатки. Многие из плюсов и минусов JavaScript связаны с тем, что чаще всего он выполняется в браузере на стороне клиента. Но сейчас есть и другие способы использования JavaScript, которые позволяют ему иметь те же преимущества, что и серверные языки программирования. <ide> <ide> ## Преимущества JavaScript <ide> <del>* **Скорость** . Клиентский JavaScript очень быстрый, потому что его можно запустить сразу же в клиентском браузере. Если внешние ресурсы не требуются, JavaScript не требует сетевых вызовов на серверный сервер. Он также не нуждается в компиляции на стороне клиента, что дает ему определенные преимущества скорости (предоставляется, добавляя некоторый риск, зависящий от этого качества разработанного кода). <del>* **Простота** . JavaScript относительно прост в освоении и реализации. <del>* **Популярность** . JavaScript используется везде в Интернете. Ресурсов для изучения JavaScript много. В StackOverflow и GitHub есть много проектов, которые используют Javascript, и в целом в последние годы язык в целом приобрел большую популярность в отрасли. <add>* **Скорость** . Клиентский JavaScript очень быстрый, потому что его можно запустить сразу же в браузере. Если внешние ресурсы не требуются, JavaScript не делает запросов по сети на сервер. Он также не нуждается в компиляции на стороне клиента, что дает ему определенные преимущества в скорости (есть определенный дополнительный риск, зависящий от этого качества разработанного кода). <add>* **Простота** . JavaScript относительно низких порог вхождения. <add>* **Популярность** . JavaScript используется во всех клиентских частях веб приложений. Ресурсов для изучения JavaScript много. В StackOverflow и GitHub есть много проектов, которые используют Javascript, и в целом в последние годы язык приобрел большую популярность в отрасли. <ide> * **Взаимодействие** . JavaScript отлично работает с другими языками и может использоваться в самых разных приложениях. В отличие от скриптов PHP или [SSI](https://en.wikipedia.org/wiki/Server_Side_Includes) , JavaScript можно вставлять на любую веб-страницу независимо от расширения файла. JavaScript также можно использовать внутри скриптов, написанных на других языках, таких как Perl и PHP. <del>* **Загрузка сервера** . Клиентская сторона снижает спрос на сервере веб-сайта. <del>* **Богатые интерфейсы** . Перетаскивание компонентов или слайдер может дать богатый интерфейс вашему сайту. <del>* **Расширенная функциональность** . Сторонние дополнения, такие как Greasemonkey, позволяют разработчикам JavaScript писать фрагменты JavaScript, которые могут выполняться на желаемых веб-страницах для расширения его функциональности. <del>* **Универсальность** . В настоящее время существует множество способов использования JavaScript через серверы Node.js. Если вы загрузили node.js с помощью Express, используйте базу данных документов, такую ​​как mongodb, и используйте JavaScript в интерфейсе для клиентов, вы можете создать приложение JavaScript полностью из одного окна вперед, используя только JavaScript. <del>* **Обновления** . С момента появления EcmaScript 5 (спецификация скриптов, на которую опирается Javascript), Ecma International ежегодно занимается обновлением JavaScript. До сих пор мы получили поддержку браузера для ES6 в 2017 году и надеемся, что ES7 будет поддерживаться в будущем. <add>* **Загрузка сервера** . Реализация логики на клиенте снижает требования к серверу. <add>* **Пользовательский интерфейс с широким функционалом** . Drag and drop компоненты или слайдеры могут существенно расширить функционал вашего сайта. <add>* **Расширение функциональности** . Сторонние расширения для браузеров, такие как Greasemonkey, позволяют добавить пользовательский JavaScript на любую веб-страницу для расширения ее функциональности. <add>* **Универсальность** . В настоящее время, благодаря Node.js, можно использовать JavaScript и на серверной части приложений. Если вы используете фреймворк Express.js для Node.js и, напрмер, MongoDB в качестве базы данных, то вы можете полностью постороить клиент-серверное приложение на JavaScript. <add>* **Обновления** . С момента появления EcmaScript 5 (спецификация Javascript), Ecma International ежегодно занимается обновлением JavaScript. Мы уже получили поддержку ES6 в браузерах с 2017 года и надеемся, что ES7 будет поддерживаться в будущем. <ide> <ide> ## Недостатки JavaScript <ide> <del>* **Безопасность на стороне клиента** . Поскольку код выполняется на компьютере пользователя, в некоторых случаях он может быть использован для вредоносных целей. Это одна из причин, по которой некоторые люди могут отключить Javascript. <del>* **Поддержка браузера** . JavaScript иногда интерпретируется по-разному разными браузерами. В то время как серверные сценарии всегда будут производить одинаковый вывод, клиентские скрипты могут быть немного непредсказуемыми. Не будьте слишком обеспокоены этим, хотя - пока вы тестируете свой скрипт во всех основных браузерах, вы должны быть в безопасности. Кроме того, есть службы, которые позволят вам проверить свой код автоматически при проверке обновления, чтобы убедиться, что все браузеры поддерживают ваш код. <ide>\ No newline at end of file <add>* **Безопасность на стороне клиента** . Поскольку код выполняется на компьютере пользователя, в некоторых случаях он может быть использован для вредоносных целей. Это одна из причин, по которой некоторые люди отключают Javascript. <add>* **Поддержка браузерами** . JavaScript иногда интерпретируется по-разному разными браузерами. В то время как сервеная часть приложения всегда обеспечивает одинаковые данные, клиентская часть может обрабатывать их по-разному в зависимости от браузера. Не стоит слишком беспокоиться об этом - если вы тестируете свой код во всех основных браузерах, вы будете в безопасности. Кроме того, есть сервисы, позволяющие проверить код автоматически при его обновлении, чтобы убедиться, что он поддерживается всеми браузерами.
1
Javascript
Javascript
remove unused/useless function sortitemsbeforeids
c3845c0731c60dafe676a50fa1d53e9fd51ce3ec
<ide><path>lib/Compilation.js <ide> class Compilation extends Tapable { <ide> <ide> const shouldRecord = self.applyPluginsBailResult("should-record") !== false; <ide> <del> self.sortItemsBeforeIds(); <del> <ide> self.applyPlugins2("revive-modules", self.modules, self.records); <ide> self.applyPlugins1("optimize-module-order", self.modules); <ide> self.applyPlugins1("advanced-optimize-module-order", self.modules); <ide> class Compilation extends Tapable { <ide> }); <ide> } <ide> <del> sortItemsBeforeIds() { <del> <del> } <del> <ide> sortItemsWithModuleIds() { <ide> this.modules.sort(byId); <ide> this.modules.forEach(module => module.sortItems());
1
Ruby
Ruby
add missing end
274607708c010a18d1d6a4fe1df1c04c88130158
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def exists? <ide> # def test_create <ide> # json = {:book => { :title => "Love Hina" }}.to_json <ide> # post :create, json <add> # end <ide> # <ide> # == Special instance variables <ide> #
1
Ruby
Ruby
add pkg-config check
06745aa6d198ec3374d620afc3a9457edea8c5d3
<ide><path>Library/Homebrew/brew_doctor.rb <ide> def check_user_path <ide> end <ide> end <ide> <add>def check_pkg_config <add> binary = `which pkg-config`.chomp <add> return if binary.empty? <add> <add> unless binary == "#{HOMEBREW_PREFIX}/bin/pkg-config" <add> puts <<-EOS.undent <add> You have a non-brew 'pkg-config' in your PATH: <add> #{binary} <add> <add> `./configure` may have problems finding brew-installed packages using <add> this other pkg-config. <add> EOS <add> end <add>end <add> <ide> def brew_doctor <ide> read, write = IO.pipe <ide> <ide> def brew_doctor <ide> check_for_x11 <ide> check_share_locale <ide> check_user_path <add> check_pkg_config <ide> <ide> exit! 0 <ide> else
1
Go
Go
move daemon stuff to its own file
9a9e2bb61d2c0a5bda75ea5679919162f53f3297
<ide><path>integration-cli/daemon.go <add>package main <add> <add>import ( <add> "encoding/json" <add> "errors" <add> "fmt" <add> "io" <add> "net/http" <add> "os" <add> "os/exec" <add> "path/filepath" <add> "strconv" <add> "strings" <add> "time" <add> <add> "github.com/docker/docker/opts" <add> "github.com/docker/docker/pkg/integration/checker" <add> "github.com/docker/docker/pkg/ioutils" <add> "github.com/docker/docker/pkg/tlsconfig" <add> "github.com/docker/go-connections/sockets" <add> "github.com/go-check/check" <add>) <add> <add>// Daemon represents a Docker daemon for the testing framework. <add>type Daemon struct { <add> // Defaults to "daemon" <add> // Useful to set to --daemon or -d for checking backwards compatibility <add> Command string <add> GlobalFlags []string <add> <add> id string <add> c *check.C <add> logFile *os.File <add> folder string <add> root string <add> stdin io.WriteCloser <add> stdout, stderr io.ReadCloser <add> cmd *exec.Cmd <add> storageDriver string <add> wait chan error <add> userlandProxy bool <add> useDefaultHost bool <add> useDefaultTLSHost bool <add>} <add> <add>type clientConfig struct { <add> transport *http.Transport <add> scheme string <add> addr string <add>} <add> <add>// NewDaemon returns a Daemon instance to be used for testing. <add>// This will create a directory such as d123456789 in the folder specified by $DEST. <add>// The daemon will not automatically start. <add>func NewDaemon(c *check.C) *Daemon { <add> dest := os.Getenv("DEST") <add> c.Assert(dest, check.Not(check.Equals), "", check.Commentf("Please set the DEST environment variable")) <add> <add> id := fmt.Sprintf("d%d", time.Now().UnixNano()%100000000) <add> dir := filepath.Join(dest, id) <add> daemonFolder, err := filepath.Abs(dir) <add> c.Assert(err, check.IsNil, check.Commentf("Could not make %q an absolute path", dir)) <add> daemonRoot := filepath.Join(daemonFolder, "root") <add> <add> c.Assert(os.MkdirAll(daemonRoot, 0755), check.IsNil, check.Commentf("Could not create daemon root %q", dir)) <add> <add> userlandProxy := true <add> if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" { <add> if val, err := strconv.ParseBool(env); err != nil { <add> userlandProxy = val <add> } <add> } <add> <add> return &Daemon{ <add> Command: "daemon", <add> id: id, <add> c: c, <add> folder: daemonFolder, <add> root: daemonRoot, <add> storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"), <add> userlandProxy: userlandProxy, <add> } <add>} <add> <add>func (d *Daemon) getClientConfig() (*clientConfig, error) { <add> var ( <add> transport *http.Transport <add> scheme string <add> addr string <add> proto string <add> ) <add> if d.useDefaultTLSHost { <add> option := &tlsconfig.Options{ <add> CAFile: "fixtures/https/ca.pem", <add> CertFile: "fixtures/https/client-cert.pem", <add> KeyFile: "fixtures/https/client-key.pem", <add> } <add> tlsConfig, err := tlsconfig.Client(*option) <add> if err != nil { <add> return nil, err <add> } <add> transport = &http.Transport{ <add> TLSClientConfig: tlsConfig, <add> } <add> addr = fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort) <add> scheme = "https" <add> proto = "tcp" <add> } else if d.useDefaultHost { <add> addr = opts.DefaultUnixSocket <add> proto = "unix" <add> scheme = "http" <add> transport = &http.Transport{} <add> } else { <add> addr = filepath.Join(d.folder, "docker.sock") <add> proto = "unix" <add> scheme = "http" <add> transport = &http.Transport{} <add> } <add> <add> d.c.Assert(sockets.ConfigureTransport(transport, proto, addr), check.IsNil) <add> <add> return &clientConfig{ <add> transport: transport, <add> scheme: scheme, <add> addr: addr, <add> }, nil <add>} <add> <add>// Start will start the daemon and return once it is ready to receive requests. <add>// You can specify additional daemon flags. <add>func (d *Daemon) Start(args ...string) error { <add> logFile, err := os.OpenFile(filepath.Join(d.folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600) <add> d.c.Assert(err, check.IsNil, check.Commentf("[%s] Could not create %s/docker.log", d.id, d.folder)) <add> <add> return d.StartWithLogFile(logFile, args...) <add>} <add> <add>// StartWithLogFile will start the daemon and attach its streams to a given file. <add>func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error { <add> dockerBinary, err := exec.LookPath(dockerBinary) <add> d.c.Assert(err, check.IsNil, check.Commentf("[%s] could not find docker binary in $PATH", d.id)) <add> <add> args := append(d.GlobalFlags, <add> d.Command, <add> "--graph", d.root, <add> "--pidfile", fmt.Sprintf("%s/docker.pid", d.folder), <add> fmt.Sprintf("--userland-proxy=%t", d.userlandProxy), <add> ) <add> if !(d.useDefaultHost || d.useDefaultTLSHost) { <add> args = append(args, []string{"--host", d.sock()}...) <add> } <add> if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" { <add> args = append(args, []string{"--userns-remap", root}...) <add> } <add> <add> // If we don't explicitly set the log-level or debug flag(-D) then <add> // turn on debug mode <add> foundLog := false <add> foundSd := false <add> for _, a := range providedArgs { <add> if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") || strings.Contains(a, "--debug") { <add> foundLog = true <add> } <add> if strings.Contains(a, "--storage-driver") { <add> foundSd = true <add> } <add> } <add> if !foundLog { <add> args = append(args, "--debug") <add> } <add> if d.storageDriver != "" && !foundSd { <add> args = append(args, "--storage-driver", d.storageDriver) <add> } <add> <add> args = append(args, providedArgs...) <add> d.cmd = exec.Command(dockerBinary, args...) <add> <add> d.cmd.Stdout = out <add> d.cmd.Stderr = out <add> d.logFile = out <add> <add> if err := d.cmd.Start(); err != nil { <add> return fmt.Errorf("[%s] could not start daemon container: %v", d.id, err) <add> } <add> <add> wait := make(chan error) <add> <add> go func() { <add> wait <- d.cmd.Wait() <add> d.c.Logf("[%s] exiting daemon", d.id) <add> close(wait) <add> }() <add> <add> d.wait = wait <add> <add> tick := time.Tick(500 * time.Millisecond) <add> // make sure daemon is ready to receive requests <add> startTime := time.Now().Unix() <add> for { <add> d.c.Logf("[%s] waiting for daemon to start", d.id) <add> if time.Now().Unix()-startTime > 5 { <add> // After 5 seconds, give up <add> return fmt.Errorf("[%s] Daemon exited and never started", d.id) <add> } <add> select { <add> case <-time.After(2 * time.Second): <add> return fmt.Errorf("[%s] timeout: daemon does not respond", d.id) <add> case <-tick: <add> clientConfig, err := d.getClientConfig() <add> if err != nil { <add> return err <add> } <add> <add> client := &http.Client{ <add> Transport: clientConfig.transport, <add> } <add> <add> req, err := http.NewRequest("GET", "/_ping", nil) <add> d.c.Assert(err, check.IsNil, check.Commentf("[%s] could not create new request", d.id)) <add> req.URL.Host = clientConfig.addr <add> req.URL.Scheme = clientConfig.scheme <add> resp, err := client.Do(req) <add> if err != nil { <add> continue <add> } <add> if resp.StatusCode != http.StatusOK { <add> d.c.Logf("[%s] received status != 200 OK: %s", d.id, resp.Status) <add> } <add> d.c.Logf("[%s] daemon started", d.id) <add> d.root, err = d.queryRootDir() <add> if err != nil { <add> return fmt.Errorf("[%s] error querying daemon for root directory: %v", d.id, err) <add> } <add> return nil <add> } <add> } <add>} <add> <add>// StartWithBusybox will first start the daemon with Daemon.Start() <add>// then save the busybox image from the main daemon and load it into this Daemon instance. <add>func (d *Daemon) StartWithBusybox(arg ...string) error { <add> if err := d.Start(arg...); err != nil { <add> return err <add> } <add> return d.LoadBusybox() <add>} <add> <add>// Stop will send a SIGINT every second and wait for the daemon to stop. <add>// If it timeouts, a SIGKILL is sent. <add>// Stop will not delete the daemon directory. If a purged daemon is needed, <add>// instantiate a new one with NewDaemon. <add>func (d *Daemon) Stop() error { <add> if d.cmd == nil || d.wait == nil { <add> return errors.New("daemon not started") <add> } <add> <add> defer func() { <add> d.logFile.Close() <add> d.cmd = nil <add> }() <add> <add> i := 1 <add> tick := time.Tick(time.Second) <add> <add> if err := d.cmd.Process.Signal(os.Interrupt); err != nil { <add> return fmt.Errorf("could not send signal: %v", err) <add> } <add>out1: <add> for { <add> select { <add> case err := <-d.wait: <add> return err <add> case <-time.After(15 * time.Second): <add> // time for stopping jobs and run onShutdown hooks <add> d.c.Log("timeout") <add> break out1 <add> } <add> } <add> <add>out2: <add> for { <add> select { <add> case err := <-d.wait: <add> return err <add> case <-tick: <add> i++ <add> if i > 4 { <add> d.c.Logf("tried to interrupt daemon for %d times, now try to kill it", i) <add> break out2 <add> } <add> d.c.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid) <add> if err := d.cmd.Process.Signal(os.Interrupt); err != nil { <add> return fmt.Errorf("could not send signal: %v", err) <add> } <add> } <add> } <add> <add> if err := d.cmd.Process.Kill(); err != nil { <add> d.c.Logf("Could not kill daemon: %v", err) <add> return err <add> } <add> <add> return nil <add>} <add> <add>// Restart will restart the daemon by first stopping it and then starting it. <add>func (d *Daemon) Restart(arg ...string) error { <add> d.Stop() <add> // in the case of tests running a user namespace-enabled daemon, we have resolved <add> // d.root to be the actual final path of the graph dir after the "uid.gid" of <add> // remapped root is added--we need to subtract it from the path before calling <add> // start or else we will continue making subdirectories rather than truly restarting <add> // with the same location/root: <add> if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" { <add> d.root = filepath.Dir(d.root) <add> } <add> return d.Start(arg...) <add>} <add> <add>// LoadBusybox will load the stored busybox into a newly started daemon <add>func (d *Daemon) LoadBusybox() error { <add> bb := filepath.Join(d.folder, "busybox.tar") <add> if _, err := os.Stat(bb); err != nil { <add> if !os.IsNotExist(err) { <add> return fmt.Errorf("unexpected error on busybox.tar stat: %v", err) <add> } <add> // saving busybox image from main daemon <add> if err := exec.Command(dockerBinary, "save", "--output", bb, "busybox:latest").Run(); err != nil { <add> return fmt.Errorf("could not save busybox image: %v", err) <add> } <add> } <add> // loading busybox image to this daemon <add> if out, err := d.Cmd("load", "--input", bb); err != nil { <add> return fmt.Errorf("could not load busybox image: %s", out) <add> } <add> if err := os.Remove(bb); err != nil { <add> d.c.Logf("could not remove %s: %v", bb, err) <add> } <add> return nil <add>} <add> <add>func (d *Daemon) queryRootDir() (string, error) { <add> // update daemon root by asking /info endpoint (to support user <add> // namespaced daemon with root remapped uid.gid directory) <add> clientConfig, err := d.getClientConfig() <add> if err != nil { <add> return "", err <add> } <add> <add> client := &http.Client{ <add> Transport: clientConfig.transport, <add> } <add> <add> req, err := http.NewRequest("GET", "/info", nil) <add> if err != nil { <add> return "", err <add> } <add> req.Header.Set("Content-Type", "application/json") <add> req.URL.Host = clientConfig.addr <add> req.URL.Scheme = clientConfig.scheme <add> <add> resp, err := client.Do(req) <add> if err != nil { <add> return "", err <add> } <add> body := ioutils.NewReadCloserWrapper(resp.Body, func() error { <add> return resp.Body.Close() <add> }) <add> <add> type Info struct { <add> DockerRootDir string <add> } <add> var b []byte <add> var i Info <add> b, err = readBody(body) <add> if err == nil && resp.StatusCode == 200 { <add> // read the docker root dir <add> if err = json.Unmarshal(b, &i); err == nil { <add> return i.DockerRootDir, nil <add> } <add> } <add> return "", err <add>} <add> <add>func (d *Daemon) sock() string { <add> return fmt.Sprintf("unix://%s/docker.sock", d.folder) <add>} <add> <add>func (d *Daemon) waitRun(contID string) error { <add> args := []string{"--host", d.sock()} <add> return waitInspectWithArgs(contID, "{{.State.Running}}", "true", 10*time.Second, args...) <add>} <add> <add>func (d *Daemon) getBaseDeviceSize(c *check.C) int64 { <add> infoCmdOutput, _, err := runCommandPipelineWithOutput( <add> exec.Command(dockerBinary, "-H", d.sock(), "info"), <add> exec.Command("grep", "Base Device Size"), <add> ) <add> c.Assert(err, checker.IsNil) <add> basesizeSlice := strings.Split(infoCmdOutput, ":") <add> basesize := strings.Trim(basesizeSlice[1], " ") <add> basesize = strings.Trim(basesize, "\n")[:len(basesize)-3] <add> basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64) <add> c.Assert(err, checker.IsNil) <add> basesizeBytes := int64(basesizeFloat) * (1024 * 1024 * 1024) <add> return basesizeBytes <add>} <add> <add>// Cmd will execute a docker CLI command against this Daemon. <add>// Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version <add>func (d *Daemon) Cmd(name string, arg ...string) (string, error) { <add> args := []string{"--host", d.sock(), name} <add> args = append(args, arg...) <add> c := exec.Command(dockerBinary, args...) <add> b, err := c.CombinedOutput() <add> return string(b), err <add>} <add> <add>// CmdWithArgs will execute a docker CLI command against a daemon with the <add>// given additional arguments <add>func (d *Daemon) CmdWithArgs(daemonArgs []string, name string, arg ...string) (string, error) { <add> args := append(daemonArgs, name) <add> args = append(args, arg...) <add> c := exec.Command(dockerBinary, args...) <add> b, err := c.CombinedOutput() <add> return string(b), err <add>} <add> <add>// LogFileName returns the path the the daemon's log file <add>func (d *Daemon) LogFileName() string { <add> return d.logFile.Name() <add>} <add> <add>func (d *Daemon) getIDByName(name string) (string, error) { <add> return d.inspectFieldWithError(name, "Id") <add>} <add> <add>func (d *Daemon) inspectFilter(name, filter string) (string, error) { <add> format := fmt.Sprintf("{{%s}}", filter) <add> out, err := d.Cmd("inspect", "-f", format, name) <add> if err != nil { <add> return "", fmt.Errorf("failed to inspect %s: %s", name, out) <add> } <add> return strings.TrimSpace(out), nil <add>} <add> <add>func (d *Daemon) inspectFieldWithError(name, field string) (string, error) { <add> return d.inspectFilter(name, fmt.Sprintf(".%s", field)) <add>} <add> <add>func (d *Daemon) findContainerIP(id string) string { <add> out, err := d.Cmd("inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'"), id) <add> if err != nil { <add> d.c.Log(err) <add> } <add> return strings.Trim(out, " \r\n'") <add>} <ide><path>integration-cli/docker_utils.go <ide> import ( <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/httputils" <ide> "github.com/docker/docker/pkg/integration" <del> "github.com/docker/docker/pkg/integration/checker" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/stringutils" <ide> "github.com/docker/engine-api/types" <del> "github.com/docker/go-connections/sockets" <ide> "github.com/docker/go-connections/tlsconfig" <ide> "github.com/docker/go-units" <ide> "github.com/go-check/check" <ide> func init() { <ide> } <ide> } <ide> <del>// Daemon represents a Docker daemon for the testing framework. <del>type Daemon struct { <del> // Defaults to "daemon" <del> // Useful to set to --daemon or -d for checking backwards compatibility <del> Command string <del> GlobalFlags []string <del> <del> id string <del> c *check.C <del> logFile *os.File <del> folder string <del> root string <del> stdin io.WriteCloser <del> stdout, stderr io.ReadCloser <del> cmd *exec.Cmd <del> storageDriver string <del> wait chan error <del> userlandProxy bool <del> useDefaultHost bool <del> useDefaultTLSHost bool <del>} <del> <del>type clientConfig struct { <del> transport *http.Transport <del> scheme string <del> addr string <del>} <del> <del>// NewDaemon returns a Daemon instance to be used for testing. <del>// This will create a directory such as d123456789 in the folder specified by $DEST. <del>// The daemon will not automatically start. <del>func NewDaemon(c *check.C) *Daemon { <del> dest := os.Getenv("DEST") <del> c.Assert(dest, check.Not(check.Equals), "", check.Commentf("Please set the DEST environment variable")) <del> <del> id := fmt.Sprintf("d%d", time.Now().UnixNano()%100000000) <del> dir := filepath.Join(dest, id) <del> daemonFolder, err := filepath.Abs(dir) <del> c.Assert(err, check.IsNil, check.Commentf("Could not make %q an absolute path", dir)) <del> daemonRoot := filepath.Join(daemonFolder, "root") <del> <del> c.Assert(os.MkdirAll(daemonRoot, 0755), check.IsNil, check.Commentf("Could not create daemon root %q", dir)) <del> <del> userlandProxy := true <del> if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" { <del> if val, err := strconv.ParseBool(env); err != nil { <del> userlandProxy = val <del> } <del> } <del> <del> return &Daemon{ <del> Command: "daemon", <del> id: id, <del> c: c, <del> folder: daemonFolder, <del> root: daemonRoot, <del> storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"), <del> userlandProxy: userlandProxy, <del> } <del>} <del> <del>func (d *Daemon) getClientConfig() (*clientConfig, error) { <del> var ( <del> transport *http.Transport <del> scheme string <del> addr string <del> proto string <del> ) <del> if d.useDefaultTLSHost { <del> option := &tlsconfig.Options{ <del> CAFile: "fixtures/https/ca.pem", <del> CertFile: "fixtures/https/client-cert.pem", <del> KeyFile: "fixtures/https/client-key.pem", <del> } <del> tlsConfig, err := tlsconfig.Client(*option) <del> if err != nil { <del> return nil, err <del> } <del> transport = &http.Transport{ <del> TLSClientConfig: tlsConfig, <del> } <del> addr = fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort) <del> scheme = "https" <del> proto = "tcp" <del> } else if d.useDefaultHost { <del> addr = opts.DefaultUnixSocket <del> proto = "unix" <del> scheme = "http" <del> transport = &http.Transport{} <del> } else { <del> addr = filepath.Join(d.folder, "docker.sock") <del> proto = "unix" <del> scheme = "http" <del> transport = &http.Transport{} <del> } <del> <del> d.c.Assert(sockets.ConfigureTransport(transport, proto, addr), check.IsNil) <del> <del> return &clientConfig{ <del> transport: transport, <del> scheme: scheme, <del> addr: addr, <del> }, nil <del>} <del> <del>// Start will start the daemon and return once it is ready to receive requests. <del>// You can specify additional daemon flags. <del>func (d *Daemon) Start(args ...string) error { <del> logFile, err := os.OpenFile(filepath.Join(d.folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600) <del> d.c.Assert(err, check.IsNil, check.Commentf("[%s] Could not create %s/docker.log", d.id, d.folder)) <del> <del> return d.StartWithLogFile(logFile, args...) <del>} <del> <del>// StartWithLogFile will start the daemon and attach its streams to a given file. <del>func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error { <del> dockerBinary, err := exec.LookPath(dockerBinary) <del> d.c.Assert(err, check.IsNil, check.Commentf("[%s] could not find docker binary in $PATH", d.id)) <del> <del> args := append(d.GlobalFlags, <del> d.Command, <del> "--graph", d.root, <del> "--pidfile", fmt.Sprintf("%s/docker.pid", d.folder), <del> fmt.Sprintf("--userland-proxy=%t", d.userlandProxy), <del> ) <del> if !(d.useDefaultHost || d.useDefaultTLSHost) { <del> args = append(args, []string{"--host", d.sock()}...) <del> } <del> if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" { <del> args = append(args, []string{"--userns-remap", root}...) <del> } <del> <del> // If we don't explicitly set the log-level or debug flag(-D) then <del> // turn on debug mode <del> foundLog := false <del> foundSd := false <del> for _, a := range providedArgs { <del> if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") || strings.Contains(a, "--debug") { <del> foundLog = true <del> } <del> if strings.Contains(a, "--storage-driver") { <del> foundSd = true <del> } <del> } <del> if !foundLog { <del> args = append(args, "--debug") <del> } <del> if d.storageDriver != "" && !foundSd { <del> args = append(args, "--storage-driver", d.storageDriver) <del> } <del> <del> args = append(args, providedArgs...) <del> d.cmd = exec.Command(dockerBinary, args...) <del> <del> d.cmd.Stdout = out <del> d.cmd.Stderr = out <del> d.logFile = out <del> <del> if err := d.cmd.Start(); err != nil { <del> return fmt.Errorf("[%s] could not start daemon container: %v", d.id, err) <del> } <del> <del> wait := make(chan error) <del> <del> go func() { <del> wait <- d.cmd.Wait() <del> d.c.Logf("[%s] exiting daemon", d.id) <del> close(wait) <del> }() <del> <del> d.wait = wait <del> <del> tick := time.Tick(500 * time.Millisecond) <del> // make sure daemon is ready to receive requests <del> startTime := time.Now().Unix() <del> for { <del> d.c.Logf("[%s] waiting for daemon to start", d.id) <del> if time.Now().Unix()-startTime > 5 { <del> // After 5 seconds, give up <del> return fmt.Errorf("[%s] Daemon exited and never started", d.id) <del> } <del> select { <del> case <-time.After(2 * time.Second): <del> return fmt.Errorf("[%s] timeout: daemon does not respond", d.id) <del> case <-tick: <del> clientConfig, err := d.getClientConfig() <del> if err != nil { <del> return err <del> } <del> <del> client := &http.Client{ <del> Transport: clientConfig.transport, <del> } <del> <del> req, err := http.NewRequest("GET", "/_ping", nil) <del> d.c.Assert(err, check.IsNil, check.Commentf("[%s] could not create new request", d.id)) <del> req.URL.Host = clientConfig.addr <del> req.URL.Scheme = clientConfig.scheme <del> resp, err := client.Do(req) <del> if err != nil { <del> continue <del> } <del> if resp.StatusCode != http.StatusOK { <del> d.c.Logf("[%s] received status != 200 OK: %s", d.id, resp.Status) <del> } <del> d.c.Logf("[%s] daemon started", d.id) <del> d.root, err = d.queryRootDir() <del> if err != nil { <del> return fmt.Errorf("[%s] error querying daemon for root directory: %v", d.id, err) <del> } <del> return nil <del> } <del> } <del>} <del> <del>// StartWithBusybox will first start the daemon with Daemon.Start() <del>// then save the busybox image from the main daemon and load it into this Daemon instance. <del>func (d *Daemon) StartWithBusybox(arg ...string) error { <del> if err := d.Start(arg...); err != nil { <del> return err <del> } <del> return d.LoadBusybox() <del>} <del> <del>// Stop will send a SIGINT every second and wait for the daemon to stop. <del>// If it timeouts, a SIGKILL is sent. <del>// Stop will not delete the daemon directory. If a purged daemon is needed, <del>// instantiate a new one with NewDaemon. <del>func (d *Daemon) Stop() error { <del> if d.cmd == nil || d.wait == nil { <del> return errors.New("daemon not started") <del> } <del> <del> defer func() { <del> d.logFile.Close() <del> d.cmd = nil <del> }() <del> <del> i := 1 <del> tick := time.Tick(time.Second) <del> <del> if err := d.cmd.Process.Signal(os.Interrupt); err != nil { <del> return fmt.Errorf("could not send signal: %v", err) <del> } <del>out1: <del> for { <del> select { <del> case err := <-d.wait: <del> return err <del> case <-time.After(15 * time.Second): <del> // time for stopping jobs and run onShutdown hooks <del> d.c.Log("timeout") <del> break out1 <del> } <del> } <del> <del>out2: <del> for { <del> select { <del> case err := <-d.wait: <del> return err <del> case <-tick: <del> i++ <del> if i > 4 { <del> d.c.Logf("tried to interrupt daemon for %d times, now try to kill it", i) <del> break out2 <del> } <del> d.c.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid) <del> if err := d.cmd.Process.Signal(os.Interrupt); err != nil { <del> return fmt.Errorf("could not send signal: %v", err) <del> } <del> } <del> } <del> <del> if err := d.cmd.Process.Kill(); err != nil { <del> d.c.Logf("Could not kill daemon: %v", err) <del> return err <del> } <del> <del> return nil <del>} <del> <del>// Restart will restart the daemon by first stopping it and then starting it. <del>func (d *Daemon) Restart(arg ...string) error { <del> d.Stop() <del> // in the case of tests running a user namespace-enabled daemon, we have resolved <del> // d.root to be the actual final path of the graph dir after the "uid.gid" of <del> // remapped root is added--we need to subtract it from the path before calling <del> // start or else we will continue making subdirectories rather than truly restarting <del> // with the same location/root: <del> if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" { <del> d.root = filepath.Dir(d.root) <del> } <del> return d.Start(arg...) <del>} <del> <del>// LoadBusybox will load the stored busybox into a newly started daemon <del>func (d *Daemon) LoadBusybox() error { <del> bb := filepath.Join(d.folder, "busybox.tar") <del> if _, err := os.Stat(bb); err != nil { <del> if !os.IsNotExist(err) { <del> return fmt.Errorf("unexpected error on busybox.tar stat: %v", err) <del> } <del> // saving busybox image from main daemon <del> if err := exec.Command(dockerBinary, "save", "--output", bb, "busybox:latest").Run(); err != nil { <del> return fmt.Errorf("could not save busybox image: %v", err) <del> } <del> } <del> // loading busybox image to this daemon <del> if out, err := d.Cmd("load", "--input", bb); err != nil { <del> return fmt.Errorf("could not load busybox image: %s", out) <del> } <del> if err := os.Remove(bb); err != nil { <del> d.c.Logf("could not remove %s: %v", bb, err) <del> } <del> return nil <del>} <del> <del>func (d *Daemon) queryRootDir() (string, error) { <del> // update daemon root by asking /info endpoint (to support user <del> // namespaced daemon with root remapped uid.gid directory) <del> clientConfig, err := d.getClientConfig() <del> if err != nil { <del> return "", err <del> } <del> <del> client := &http.Client{ <del> Transport: clientConfig.transport, <del> } <del> <del> req, err := http.NewRequest("GET", "/info", nil) <del> if err != nil { <del> return "", err <del> } <del> req.Header.Set("Content-Type", "application/json") <del> req.URL.Host = clientConfig.addr <del> req.URL.Scheme = clientConfig.scheme <del> <del> resp, err := client.Do(req) <del> if err != nil { <del> return "", err <del> } <del> body := ioutils.NewReadCloserWrapper(resp.Body, func() error { <del> return resp.Body.Close() <del> }) <del> <del> type Info struct { <del> DockerRootDir string <del> } <del> var b []byte <del> var i Info <del> b, err = readBody(body) <del> if err == nil && resp.StatusCode == 200 { <del> // read the docker root dir <del> if err = json.Unmarshal(b, &i); err == nil { <del> return i.DockerRootDir, nil <del> } <del> } <del> return "", err <del>} <del> <del>func (d *Daemon) sock() string { <del> return fmt.Sprintf("unix://%s/docker.sock", d.folder) <del>} <del> <del>func (d *Daemon) waitRun(contID string) error { <del> args := []string{"--host", d.sock()} <del> return waitInspectWithArgs(contID, "{{.State.Running}}", "true", 10*time.Second, args...) <del>} <del> <del>func (d *Daemon) getBaseDeviceSize(c *check.C) int64 { <del> infoCmdOutput, _, err := runCommandPipelineWithOutput( <del> exec.Command(dockerBinary, "-H", d.sock(), "info"), <del> exec.Command("grep", "Base Device Size"), <del> ) <del> c.Assert(err, checker.IsNil) <del> basesizeSlice := strings.Split(infoCmdOutput, ":") <del> basesize := strings.Trim(basesizeSlice[1], " ") <del> basesize = strings.Trim(basesize, "\n")[:len(basesize)-3] <del> basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64) <del> c.Assert(err, checker.IsNil) <del> basesizeBytes := int64(basesizeFloat) * (1024 * 1024 * 1024) <del> return basesizeBytes <del>} <del> <ide> func convertBasesize(basesizeBytes int64) (int64, error) { <ide> basesize := units.HumanSize(float64(basesizeBytes)) <ide> basesize = strings.Trim(basesize, " ")[:len(basesize)-3] <ide> func convertBasesize(basesizeBytes int64) (int64, error) { <ide> return int64(basesizeFloat) * 1024 * 1024 * 1024, nil <ide> } <ide> <del>// Cmd will execute a docker CLI command against this Daemon. <del>// Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version <del>func (d *Daemon) Cmd(name string, arg ...string) (string, error) { <del> args := []string{"--host", d.sock(), name} <del> args = append(args, arg...) <del> c := exec.Command(dockerBinary, args...) <del> b, err := c.CombinedOutput() <del> return string(b), err <del>} <del> <del>// CmdWithArgs will execute a docker CLI command against a daemon with the <del>// given additional arguments <del>func (d *Daemon) CmdWithArgs(daemonArgs []string, name string, arg ...string) (string, error) { <del> args := append(daemonArgs, name) <del> args = append(args, arg...) <del> c := exec.Command(dockerBinary, args...) <del> b, err := c.CombinedOutput() <del> return string(b), err <del>} <del> <del>// LogFileName returns the path the the daemon's log file <del>func (d *Daemon) LogFileName() string { <del> return d.logFile.Name() <del>} <del> <del>func (d *Daemon) getIDByName(name string) (string, error) { <del> return d.inspectFieldWithError(name, "Id") <del>} <del> <del>func (d *Daemon) inspectFilter(name, filter string) (string, error) { <del> format := fmt.Sprintf("{{%s}}", filter) <del> out, err := d.Cmd("inspect", "-f", format, name) <del> if err != nil { <del> return "", fmt.Errorf("failed to inspect %s: %s", name, out) <del> } <del> return strings.TrimSpace(out), nil <del>} <del> <del>func (d *Daemon) inspectFieldWithError(name, field string) (string, error) { <del> return d.inspectFilter(name, fmt.Sprintf(".%s", field)) <del>} <del> <ide> func daemonHost() string { <ide> daemonURLStr := "unix://" + opts.DefaultUnixSocket <ide> if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" { <ide> func findContainerIP(c *check.C, id string, network string) string { <ide> return strings.Trim(out, " \r\n'") <ide> } <ide> <del>func (d *Daemon) findContainerIP(id string) string { <del> out, err := d.Cmd("inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.bridge.IPAddress }}'"), id) <del> if err != nil { <del> d.c.Log(err) <del> } <del> return strings.Trim(out, " \r\n'") <del>} <del> <ide> func getContainerCount() (int, error) { <ide> const containers = "Containers:" <ide>
2
PHP
PHP
apply fixes from styleci
fa62732859f6e13cfa94ef25f0d54a2246945084
<ide><path>src/Illuminate/Database/DatabaseServiceProvider.php <ide> protected function registerEloquentFactory() <ide> $locale = $parameters['locale'] ?? $app['config']->get('app.faker_locale', 'en_US'); <ide> <ide> if (! isset(static::$fakers[$locale])) { <del> static::$fakers[$locale] = FakerFactory::create($locale);; <add> static::$fakers[$locale] = FakerFactory::create($locale); <ide> } <ide> <ide> return static::$fakers[$locale];
1
Python
Python
add tests for dimension data partner drivers
aae37ae77c20650c4c5f39ae252a9018cb7d60ed
<ide><path>libcloud/test/compute/test_bsnl.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. 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>import unittest <add> <add>from libcloud.compute.drivers.bsnl import BSNLNodeDriver <add>from libcloud.test.compute.test_dimensiondata_v2_3 import DimensionDataMockHttp, DimensionData_v2_3_Tests <add> <add> <add>class BSNLTests(DimensionData_v2_3_Tests, unittest.TestCase): <add> <add> def setUp(self): <add> BSNLNodeDriver.connectionCls.conn_class = DimensionDataMockHttp <add> BSNLNodeDriver.connectionCls.active_api_version = '2.3' <add> DimensionDataMockHttp.type = None <add> self.driver = BSNLNodeDriver('user', 'password') <ide><path>libcloud/test/compute/test_medone.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. 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>import unittest <add> <add>from libcloud.compute.drivers.medone import MedOneNodeDriver <add>from libcloud.test.compute.test_dimensiondata_v2_3 import DimensionDataMockHttp, DimensionData_v2_3_Tests <add> <add> <add>class MedOneTests(DimensionData_v2_3_Tests, unittest.TestCase): <add> <add> def setUp(self): <add> MedOneNodeDriver.connectionCls.conn_class = DimensionDataMockHttp <add> MedOneNodeDriver.connectionCls.active_api_version = '2.3' <add> DimensionDataMockHttp.type = None <add> self.driver = MedOneNodeDriver('user', 'password') <ide><path>libcloud/test/compute/test_ntta.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. 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>import unittest <add> <add>from libcloud.compute.drivers.ntta import NTTAmericaNodeDriver <add>from libcloud.test.compute.test_dimensiondata_v2_3 import DimensionDataMockHttp, DimensionData_v2_3_Tests <add> <add> <add>class NTTAmericaNodeDriverTests(DimensionData_v2_3_Tests, unittest.TestCase): <add> <add> def setUp(self): <add> NTTAmericaNodeDriver.connectionCls.conn_class = DimensionDataMockHttp <add> NTTAmericaNodeDriver.connectionCls.active_api_version = '2.3' <add> DimensionDataMockHttp.type = None <add> self.driver = NTTAmericaNodeDriver('user', 'password')
3
Python
Python
fix two bugs with --logging_first_step
8f1c960ee75b0ebce4e94881ee2d5409a26a6239
<ide><path>src/transformers/trainer.py <ide> def train(self, model_path: Optional[str] = None, trial: Union["optuna.Trial", D <ide> <ide> tr_loss = torch.tensor(0.0).to(self.args.device) <ide> self._logging_loss_scalar = 0 <add> self._globalstep_last_logged = 0 <ide> self._total_flos = self.state.total_flos <ide> model.zero_grad() <ide> <ide> def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch): <ide> if self.control.should_log: <ide> logs: Dict[str, float] = {} <ide> tr_loss_scalar = tr_loss.item() <del> logs["loss"] = (tr_loss_scalar - self._logging_loss_scalar) / self.args.logging_steps <add> logs["loss"] = (tr_loss_scalar - self._logging_loss_scalar) / ( <add> self.state.global_step - self._globalstep_last_logged <add> ) <ide> # backward compatibility for pytorch schedulers <ide> logs["learning_rate"] = ( <ide> self.lr_scheduler.get_last_lr()[0] <ide> if version.parse(torch.__version__) >= version.parse("1.4") <ide> else self.lr_scheduler.get_lr()[0] <ide> ) <ide> self._logging_loss_scalar = tr_loss_scalar <add> self._globalstep_last_logged = self.state.global_step <ide> <ide> self.log(logs) <ide> <ide><path>src/transformers/training_args.py <ide> class TrainingArguments: <ide> warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."}) <ide> <ide> logging_dir: Optional[str] = field(default_factory=default_logdir, metadata={"help": "Tensorboard log dir."}) <del> logging_first_step: bool = field(default=False, metadata={"help": "Log and eval the first global_step"}) <add> logging_first_step: bool = field(default=False, metadata={"help": "Log the first global_step"}) <ide> logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."}) <ide> save_steps: int = field(default=500, metadata={"help": "Save checkpoint every X updates steps."}) <ide> save_total_limit: Optional[int] = field(
2
Text
Text
fix broken links
8792c3feb8e4852e44924fb059955a150ed863e6
<ide><path>src/README.md <ide> such as `std::string` and track their memory usage. <ide> <ide> This can be useful for debugging memory leaks. <ide> <del>The [`memory_retainer.h`][] header file explains how to use this class. <add>The [`memory_tracker.h`][] header file explains how to use this class. <ide> <ide> <a id="baseobject"></a> <ide> ### `BaseObject` <ide> static void GetUserInfo(const FunctionCallbackInfo<Value>& args) { <ide> [`async_wrap.h`]: async_wrap.h <ide> [`base_object.h`]: base_object.h <ide> [`handle_wrap.h`]: handle_wrap.h <del>[`memory_retainer.h`]: memory_retainer.h <add>[`memory_tracker.h`]: memory_tracker.h <ide> [`req_wrap.h`]: req_wrap.h <ide> [`util.h`]: util.h <ide> [`v8.h` in Code Search]: https://cs.chromium.org/chromium/src/v8/include/v8.h <ide> static void GetUserInfo(const FunctionCallbackInfo<Value>& args) { <ide> [cleanup hooks]: #cleanup-hooks <ide> [event loop]: #event-loop <ide> [exception handling]: #exception-handling <del>[internal field]: #internal-field <add>[internal field]: #internal-fields <ide> [introduction for V8 embedders]: https://v8.dev/docs/embed <ide> [libuv handles]: #libuv-handles-and-requests <ide> [libuv requests]: #libuv-handles-and-requests
1
Python
Python
fix importerror in runtests.py (fixes )
0f171d9273a3a86c7d4a434d7f4df491a42ca3ca
<ide><path>numpy/testing/__init__.py <ide> from unittest import TestCase <ide> <ide> from . import decorators as dec <add>from .nosetester import run_module_suite, NoseTester as Tester <ide> from .utils import * <del>from .nosetester import NoseTester as Tester <del>from .nosetester import run_module_suite <ide> test = Tester().test
1