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 |
|---|---|---|---|---|---|
Ruby | Ruby | add `internal` attribute to routes | cd8bb8b6ce96cbfbade45cd5845e5862adf21125 | <ide><path>actionmailer/lib/action_mailer/railtie.rb
<ide> class Railtie < Rails::Railtie # :nodoc:
<ide>
<ide> if options.show_previews
<ide> app.routes.prepend do
<del> get '/rails/mailers' => "rails/mailers#index"
<del> get '/rails/mailers/*path' => "rails/mailers#preview"
<add> get '/rails/mailers' => "rails/mailers#index", internal: true
<add> get '/rails/mailers/*path' => "rails/mailers#preview", internal: true
<ide> end
<ide> end
<ide>
<ide><path>actionpack/lib/action_dispatch/journey/route.rb
<ide> module Journey # :nodoc:
<ide> class Route # :nodoc:
<ide> attr_reader :app, :path, :defaults, :name, :precedence
<ide>
<del> attr_reader :constraints
<add> attr_reader :constraints, :internal
<ide> alias :conditions :constraints
<ide>
<ide> module VerbMatchers
<ide> def self.build(name, app, path, constraints, required_defaults, defaults)
<ide> ##
<ide> # +path+ is a path constraint.
<ide> # +constraints+ is a hash of constraints to be applied to this route.
<del> def initialize(name, app, path, constraints, required_defaults, defaults, request_method_match, precedence)
<add> def initialize(name, app, path, constraints, required_defaults, defaults, request_method_match, precedence, internal = false)
<ide> @name = name
<ide> @app = app
<ide> @path = path
<ide> def initialize(name, app, path, constraints, required_defaults, defaults, reques
<ide> @decorated_ast = nil
<ide> @precedence = precedence
<ide> @path_formatter = @path.build_formatter
<add> @internal = internal
<ide> end
<ide>
<ide> def ast
<ide><path>actionpack/lib/action_dispatch/routing/inspector.rb
<ide> def action
<ide> end
<ide>
<ide> def internal?
<del> controller.to_s =~ %r{\Arails/(info|mailers|welcome)}
<add> internal
<ide> end
<ide>
<ide> def engine?
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def initialize(set, ast, defaults, controller, default_action, modyoule, to, for
<ide> @ast = ast
<ide> @anchor = anchor
<ide> @via = via
<add> @internal = options[:internal]
<ide>
<ide> path_params = ast.find_all(&:symbol?).map(&:to_sym)
<ide>
<ide> def make_route(name, precedence)
<ide> required_defaults,
<ide> defaults,
<ide> request_method,
<del> precedence)
<add> precedence,
<add> @internal)
<ide>
<ide> route
<ide> end
<ide><path>actionpack/test/dispatch/routing/inspector_test.rb
<ide> def test_no_routes_were_defined
<ide> ], output
<ide> end
<ide>
<add> def test_displaying_routes_for_internal_engines
<add> engine = Class.new(Rails::Engine) do
<add> def self.inspect
<add> "Blog::Engine"
<add> end
<add> end
<add> engine.routes.draw do
<add> get '/cart', to: 'cart#show'
<add> post '/cart', to: 'cart#create'
<add> patch '/cart', to: 'cart#update'
<add> end
<add>
<add> output = draw do
<add> get '/custom/assets', to: 'custom_assets#show'
<add> mount engine => "/blog", as: "blog", internal: true
<add> end
<add>
<add> assert_equal [
<add> " Prefix Verb URI Pattern Controller#Action",
<add> "custom_assets GET /custom/assets(.:format) custom_assets#show",
<add> ], output
<add> end
<add>
<ide> end
<ide> end
<ide> end
<ide><path>railties/lib/rails/application/finisher.rb
<ide> module Finisher
<ide> initializer :add_builtin_route do |app|
<ide> if Rails.env.development?
<ide> app.routes.append do
<del> get '/rails/info/properties' => "rails/info#properties"
<del> get '/rails/info/routes' => "rails/info#routes"
<del> get '/rails/info' => "rails/info#index"
<del> get '/' => "rails/welcome#index"
<add> get '/rails/info/properties' => "rails/info#properties", internal: true
<add> get '/rails/info/routes' => "rails/info#routes", internal: true
<add> get '/rails/info' => "rails/info#index", internal: true
<add> get '/' => "rails/welcome#index", internal: true
<ide> end
<ide> end
<ide> end | 6 |
Javascript | Javascript | fix parsing of jp2 images | 583ca3b16286b9fc6da002758c8cdbac7db8a922 | <ide><path>src/core/jpx.js
<ide> var JpxImage = (function JpxImageClosure() {
<ide> n = n * 256 + (data[offset + i] & 0xFF);
<ide> return n;
<ide> }
<add>
<add> var head = readUint(data, 0, 2);
<add> // No box header, immediate start of codestream (SOC)
<add> if (head === 0xFF4F) {
<add> this.parseCodestream(data, 0, data.length);
<add> return;
<add> }
<add>
<ide> var position = 0, length = data.length;
<ide> while (position < length) {
<ide> var headerSize = 8;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> cod.segmentationSymbolUsed = !!(blockStyle & 32);
<ide> cod.transformation = data[j++];
<ide> if (cod.entropyCoderWithCustomPrecincts) {
<del> var precinctsSizes = {};
<add> var precinctsSizes = [];
<ide> while (j < length + position) {
<del> var precinctsSize = data[j];
<add> var precinctsSize = data[j++];
<ide> precinctsSizes.push({
<ide> PPx: precinctsSize & 0xF,
<ide> PPy: precinctsSize >> 4
<ide> var JpxImage = (function JpxImageClosure() {
<ide> var codeblocks = subband.codeblocks;
<ide> for (var j = 0, jj = codeblocks.length; j < jj; j++) {
<ide> var codeblock = codeblocks[j];
<del> if (codeblock.precinctNumber != precinctNumber)
<add> if (codeblock.precinctNumber != precinctNumber) {
<ide> continue;
<add> }
<ide> precinctCodeblocks.push(codeblock);
<ide> }
<ide> }
<ide> var JpxImage = (function JpxImageClosure() {
<ide> }
<ide> function readCodingpasses() {
<ide> var value = readBits(1);
<del> if (value === 0)
<add> if (value === 0) {
<ide> return 1;
<add> }
<ide> value = (value << 1) | readBits(1);
<del> if (value == 0x02)
<add> if (value == 0x02) {
<ide> return 2;
<add> }
<ide> value = (value << 2) | readBits(2);
<del> if (value <= 0x0E)
<add> if (value <= 0x0E) {
<ide> return (value & 0x03) + 3;
<add> }
<ide> value = (value << 5) | readBits(5);
<del> if (value <= 0x1FE)
<add> if (value <= 0x1FE) {
<ide> return (value & 0x1F) + 6;
<add> }
<ide> value = (value << 7) | readBits(7);
<ide> return (value & 0x7F) + 37;
<ide> }
<ide> var JpxImage = (function JpxImageClosure() {
<ide> }
<ide> }
<ide> }
<del> if (!codeblockIncluded)
<add> if (!codeblockIncluded) {
<ide> continue;
<add> }
<ide> if (firstTimeInclusion) {
<ide> zeroBitPlanesTree = precinct.zeroBitPlanesTree;
<ide> zeroBitPlanesTree.reset(codeblockColumn, codeblockRow);
<ide> while (true) {
<ide> if (readBits(1)) {
<ide> var valueReady = !zeroBitPlanesTree.nextLevel();
<del> if (valueReady)
<add> if (valueReady) {
<ide> break;
<del> } else
<add> }
<add> } else {
<ide> zeroBitPlanesTree.incrementValue();
<add> }
<ide> }
<ide> codeblock.zeroBitPlanes = zeroBitPlanesTree.value;
<ide> }
<ide> var codingpasses = readCodingpasses();
<del> while (readBits(1))
<add> while (readBits(1)) {
<ide> codeblock.Lblock++;
<add> }
<ide> var codingpassesLog2 = log2(codingpasses);
<ide> // rounding down log2
<ide> var bits = ((codingpasses < (1 << codingpassesLog2)) ?
<ide> var JpxImage = (function JpxImageClosure() {
<ide> while (queue.length > 0) {
<ide> var packetItem = queue.shift();
<ide> var codeblock = packetItem.codeblock;
<del> if (!('data' in codeblock))
<add> if (!('data' in codeblock)) {
<ide> codeblock.data = [];
<add> }
<ide> codeblock.data.push({
<ide> data: data,
<ide> start: offset + position,
<ide> var JpxImage = (function JpxImageClosure() {
<ide> var codeblock = codeblocks[i];
<ide> var blockWidth = codeblock.tbx1_ - codeblock.tbx0_;
<ide> var blockHeight = codeblock.tby1_ - codeblock.tby0_;
<del> if (blockWidth === 0 || blockHeight === 0)
<add> if (blockWidth === 0 || blockHeight === 0) {
<ide> continue;
<del> if (!('data' in codeblock))
<add> }
<add> if (!('data' in codeblock)) {
<ide> continue;
<add> }
<ide>
<ide> var bitModel, currentCodingpassType;
<ide> bitModel = new BitModel(blockWidth, blockHeight, codeblock.subbandType,
<ide> var JpxImage = (function JpxImageClosure() {
<ide> break;
<ide> case 2:
<ide> bitModel.runCleanupPass();
<del> if (segmentationSymbolUsed)
<add> if (segmentationSymbolUsed) {
<ide> bitModel.checkSegmentationSymbol();
<add> }
<ide> break;
<ide> }
<ide> currentCodingpassType = (currentCodingpassType + 1) % 3;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> // not all bitplanes were decoded for reversible transformation
<ide> n += n < 0 ? n - r : n > 0 ? n + r : 0;
<ide> correction = 1 << (mb - nb);
<del> } else
<add> } else {
<ide> correction = 1;
<add> }
<ide> coefficients[offset++] = n * correction * delta;
<ide> position++;
<ide> }
<ide> var JpxImage = (function JpxImageClosure() {
<ide> // Section G.1 DC level shifting to unsigned component values
<ide> for (var c = 0; c < componentsCount; c++) {
<ide> var component = components[c];
<del> if (component.isSigned)
<add> if (component.isSigned) {
<ide> continue;
<add> }
<ide>
<ide> var offset = 1 << (component.precision - 1);
<ide> var tileImage = result[c];
<ide> var items = tileImage.items;
<del> for (var j = 0, jj = items.length; j < jj; j++)
<add> for (var j = 0, jj = items.length; j < jj; j++) {
<ide> items[j] += offset;
<add> }
<ide> }
<ide>
<ide> // To simplify things: shift and clamp output to 8 bit unsigned
<ide> var JpxImage = (function JpxImageClosure() {
<ide> this.levels = [];
<ide> for (var i = 0; i < levelsLength; i++) {
<ide> var items = new Uint8Array(width * height);
<del> for (var j = 0, jj = items.length; j < jj; j++)
<add> for (var j = 0, jj = items.length; j < jj; j++) {
<ide> items[j] = defaultValue;
<add> }
<ide>
<ide> var level = {
<ide> width: width,
<ide> var JpxImage = (function JpxImageClosure() {
<ide> level.index = index;
<ide> var value = level.items[index];
<ide>
<del> if (value == 0xFF)
<add> if (value == 0xFF) {
<ide> break;
<add> }
<ide>
<ide> if (value > stopValue) {
<ide> this.currentLevel = currentLevel;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> var value = level.items[level.index];
<ide> level.items[level.index] = 0xFF;
<ide> currentLevel--;
<del> if (currentLevel < 0)
<add> if (currentLevel < 0) {
<ide> return false;
<add> }
<ide>
<ide> this.currentLevel = currentLevel;
<ide> var level = this.levels[currentLevel];
<ide> var JpxImage = (function JpxImageClosure() {
<ide> },
<ide> renormD: function ArithmeticDecoder_renormD() {
<ide> do {
<del> if (this.ct === 0)
<add> if (this.ct === 0) {
<ide> this.byteIn();
<add> }
<ide>
<ide> this.a <<= 1;
<ide> this.chigh = ((this.chigh << 1) & 0xFFFF) | ((this.clow >> 15) & 1);
<ide> var JpxImage = (function JpxImageClosure() {
<ide> // Table D-2
<ide> function calcSignContribution(significance0, sign0, significance1, sign1) {
<ide> if (significance1) {
<del> if (!sign1)
<add> if (!sign1) {
<ide> return significance0 ? (!sign0 ? 1 : 0) : 1;
<del> else
<add> } else {
<ide> return significance0 ? (!sign0 ? 0 : -1) : -1;
<del> } else
<add> }
<add> } else {
<ide> return significance0 ? (!sign0 ? 1 : -1) : 0;
<add> }
<ide> }
<ide> // Table D-3
<ide> var SignContextLabels = [
<ide> var JpxImage = (function JpxImageClosure() {
<ide> this.runLengthContext = {index: 3, mps: 0};
<ide> this.contexts = [];
<ide> this.contexts.push({index: 4, mps: 0});
<del> for (var i = 1; i <= 16; i++)
<add> for (var i = 1; i <= 16; i++) {
<ide> this.contexts.push({index: 0, mps: 0});
<add> }
<ide> },
<ide> setNeighborsSignificance:
<ide> function BitModel_setNeighborsSignificance(row, column) {
<ide> var neighborsSignificance = this.neighborsSignificance;
<ide> var width = this.width, height = this.height;
<ide> var index = row * width + column;
<ide> if (row > 0) {
<del> if (column > 0)
<add> if (column > 0) {
<ide> neighborsSignificance[index - width - 1] += 0x10;
<del> if (column + 1 < width)
<add> }
<add> if (column + 1 < width) {
<ide> neighborsSignificance[index - width + 1] += 0x10;
<add> }
<ide> neighborsSignificance[index - width] += 0x04;
<ide> }
<ide> if (row + 1 < height) {
<del> if (column > 0)
<add> if (column > 0) {
<ide> neighborsSignificance[index + width - 1] += 0x10;
<del> if (column + 1 < width)
<add> }
<add> if (column + 1 < width) {
<ide> neighborsSignificance[index + width + 1] += 0x10;
<add> }
<ide> neighborsSignificance[index + width] += 0x04;
<ide> }
<del> if (column > 0)
<add> if (column > 0) {
<ide> neighborsSignificance[index - 1] += 0x01;
<del> if (column + 1 < width)
<add> }
<add> if (column + 1 < width) {
<ide> neighborsSignificance[index + 1] += 0x01;
<add> }
<ide> neighborsSignificance[index] |= 0x80;
<ide> },
<ide> runSignificancePropogationPass:
<ide> var JpxImage = (function JpxImageClosure() {
<ide> var processedInverseMask = ~1;
<ide> var processedMask = 1;
<ide> var firstMagnitudeBitMask = 2;
<del> for (var q = 0, qq = width * height; q < qq; q++)
<add> for (var q = 0, qq = width * height; q < qq; q++) {
<ide> processingFlags[q] &= processedInverseMask;
<add> }
<ide>
<ide> for (var i0 = 0; i0 < height; i0 += 4) {
<ide> for (var j = 0; j < width; j++) {
<ide> var index = i0 * width + j;
<ide> for (var i1 = 0; i1 < 4; i1++, index += width) {
<ide> var i = i0 + i1;
<del> if (i >= height)
<add> if (i >= height) {
<ide> break;
<add> }
<ide>
<ide> if (coefficentsMagnitude[index] || !neighborsSignificance[index])
<ide> continue;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> for (var j = 0; j < width; j++) {
<ide> for (var i1 = 0; i1 < 4; i1++) {
<ide> var i = i0 + i1;
<del> if (i >= height)
<add> if (i >= height) {
<ide> break;
<add> }
<ide> var index = i * width + j;
<ide>
<ide> // significant but not those that have just become
<ide> if (!coefficentsMagnitude[index] ||
<del> (processingFlags[index] & processedMask) !== 0)
<add> (processingFlags[index] & processedMask) !== 0) {
<ide> continue;
<add> }
<ide>
<ide> var contextLabel = 16;
<ide> if ((processingFlags[index] &
<ide> var JpxImage = (function JpxImageClosure() {
<ide> processingFlags[index] |= firstMagnitudeBitMask;
<ide>
<ide> index = index0;
<del> for (var i2 = i0; i2 <= i; i2++, index += width)
<add> for (var i2 = i0; i2 <= i; i2++, index += width) {
<ide> bitsDecoded[index]++;
<add> }
<ide>
<ide> i1++;
<ide> }
<ide> for (; i1 < 4; i1++, index += width) {
<ide> i = i0 + i1;
<del> if (i >= height)
<add> if (i >= height) {
<ide> break;
<add> }
<ide>
<ide> if (coefficentsMagnitude[index] ||
<del> (processingFlags[index] & processedMask) !== 0)
<add> (processingFlags[index] & processedMask) !== 0) {
<ide> continue;
<add> }
<ide>
<ide> var contextLabel = labels[neighborsSignificance[index]];
<ide> cx = contexts[contextLabel];
<ide> var JpxImage = (function JpxImageClosure() {
<ide> var cx = this.uniformContext;
<ide> var symbol = (decoder.readBit(cx) << 3) | (decoder.readBit(cx) << 2) |
<ide> (decoder.readBit(cx) << 1) | decoder.readBit(cx);
<del> if (symbol != 0xA)
<add> if (symbol != 0xA) {
<ide> throw 'Invalid segmentation symbol';
<add> }
<ide> }
<ide> };
<ide> | 1 |
Javascript | Javascript | fix indentation in required-modules.js | 491f838511a8c7b848fb0affcc3661ee45edbdc5 | <ide><path>tools/eslint-rules/required-modules.js
<ide> module.exports = function(context) {
<ide> function(module) {
<ide> return foundModules.indexOf(module === -1);
<ide> }
<del> );
<add> );
<ide> missingModules.forEach(function(moduleName) {
<ide> context.report(
<ide> node,
<ide> 'Mandatory module "{{moduleName}}" must be loaded.',
<ide> { moduleName: moduleName }
<del> );
<add> );
<ide> });
<ide> }
<ide> } | 1 |
Ruby | Ruby | enable coverage on travis | 51efa46fcc91f4cc635ed8b7bd77a0a35f7656b6 | <ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def homebrew
<ide> if @tap
<ide> test "brew", "readall", @tap.name
<ide> else
<del> test "brew", "tests", "--no-compat"
<add> tests_args = ["--no-compat"]
<ide> readall_args = ["--aliases"]
<del> readall_args << "--syntax" if RUBY_VERSION.split(".").first.to_i >= 2
<add> if RUBY_VERSION.split(".").first.to_i >= 2
<add> tests_args << "--coverage" if ENV["TRAVIS"]
<add> readall_args << "--syntax"
<add> end
<add> test "brew", "tests", *tests_args
<ide> test "brew", "readall", *readall_args
<ide> test "brew", "update-test"
<ide> end | 1 |
Java | Java | move testcompiler from generator to generate | 6e93f1187c31a37448ca937b4c824657e6fc071c | <ide><path>spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyBeanRegistrationAotProcessorTests.java
<ide> import org.springframework.aop.framework.AopInfrastructureBean;
<ide> import org.springframework.aot.generate.MethodReference;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.factory.BeanCreationException;
<ide> import org.springframework.beans.factory.aot.AotServices;
<ide> import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanRegistrationAotContributionTests.java
<ide> import org.springframework.aot.generate.MethodReference;
<ide> import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.CompileWithTargetClassAccess;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.CompileWithTargetClassAccess;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
<ide> import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.beans.factory.support.RegisteredBean;
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorTests.java
<ide> import org.springframework.aot.generate.GenerationContext;
<ide> import org.springframework.aot.generate.MethodReference;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.CompileWithTargetClassAccess;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<del>import org.springframework.aot.test.generator.file.SourceFile;
<add>import org.springframework.aot.test.generate.compile.CompileWithTargetClassAccess;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.file.SourceFile;
<ide> import org.springframework.beans.factory.config.BeanDefinition;
<ide> import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder;
<ide> import org.springframework.beans.factory.support.BeanDefinitionBuilder;
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGeneratorTests.java
<ide> import org.springframework.aot.generate.GeneratedClass;
<ide> import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.factory.FactoryBean;
<ide> import org.springframework.beans.factory.config.BeanDefinition;
<ide> import org.springframework.beans.factory.config.BeanReference;
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionPropertyValueCodeGeneratorTests.java
<ide>
<ide> import org.springframework.aot.generate.GeneratedClass;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.factory.config.BeanReference;
<ide> import org.springframework.beans.factory.config.RuntimeBeanNameReference;
<ide> import org.springframework.beans.factory.config.RuntimeBeanReference;
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanRegistrationsAotContributionTests.java
<ide> import org.springframework.aot.generate.MethodReference;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<ide> import org.springframework.aot.test.generate.TestTarget;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<del>import org.springframework.aot.test.generator.file.SourceFile;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.file.SourceFile;
<ide> import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.beans.factory.support.RegisteredBean;
<ide> import org.springframework.beans.factory.support.RootBeanDefinition;
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/InstanceSupplierCodeGeneratorTests.java
<ide> import org.springframework.aot.hint.ReflectionHints;
<ide> import org.springframework.aot.hint.TypeHint;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.factory.config.BeanDefinition;
<ide> import org.springframework.beans.factory.support.BeanDefinitionBuilder;
<ide> import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorAotContributionTests.java
<ide> import org.springframework.aot.generate.MethodReference;
<ide> import org.springframework.aot.hint.ResourcePatternHint;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
<ide><path>spring-context/src/test/java/org/springframework/context/aot/ApplicationContextAotGeneratorTests.java
<ide> import org.springframework.aot.hint.TypeReference;
<ide> import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
<ide> import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
<ide><path>spring-context/src/test/java/org/springframework/context/generator/ApplicationContextAotGeneratorRuntimeHintsTests.java
<ide> import org.springframework.aot.test.agent.RuntimeHintsInvocations;
<ide> import org.springframework.aot.test.agent.RuntimeHintsRecorder;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.factory.support.BeanDefinitionBuilder;
<ide> import org.springframework.beans.factory.support.RootBeanDefinition;
<ide> import org.springframework.context.ApplicationContextInitializer;
<ide><path>spring-core-test/src/main/java/org/springframework/aot/agent/InvocationsRecorderClassTransformer.java
<ide> class InvocationsRecorderClassTransformer implements ClassFileTransformer {
<ide>
<ide> private static final String AGENT_PACKAGE = InvocationsRecorderClassTransformer.class.getPackageName().replace('.', '/');
<ide>
<del> private static final String AOT_DYNAMIC_CLASSLOADER = "org/springframework/aot/test/generator/compile/DynamicClassLoader";
<add> private static final String AOT_DYNAMIC_CLASSLOADER = "org/springframework/aot/test/generate/compile/DynamicClassLoader";
<ide>
<ide> private final String[] instrumentedPackages;
<ide>
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/CompilationException.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/CompilationException.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<del>import org.springframework.aot.test.generator.file.ResourceFile;
<del>import org.springframework.aot.test.generator.file.ResourceFiles;
<del>import org.springframework.aot.test.generator.file.SourceFile;
<del>import org.springframework.aot.test.generator.file.SourceFiles;
<add>import org.springframework.aot.test.generate.file.ResourceFile;
<add>import org.springframework.aot.test.generate.file.ResourceFiles;
<add>import org.springframework.aot.test.generate.file.SourceFile;
<add>import org.springframework.aot.test.generate.file.SourceFiles;
<ide>
<ide> /**
<ide> * Exception thrown when code cannot compile.
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/CompileWithTargetClassAccess.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/CompileWithTargetClassAccess.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.lang.annotation.Documented;
<ide> import java.lang.annotation.ElementType;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/CompileWithTargetClassAccessClassLoader.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/CompileWithTargetClassAccessClassLoader.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/CompileWithTargetClassAccessExtension.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/CompileWithTargetClassAccessExtension.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.lang.reflect.Method;
<ide>
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/Compiled.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/Compiled.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.lang.reflect.Constructor;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide>
<del>import org.springframework.aot.test.generator.file.ResourceFile;
<del>import org.springframework.aot.test.generator.file.ResourceFiles;
<del>import org.springframework.aot.test.generator.file.SourceFile;
<del>import org.springframework.aot.test.generator.file.SourceFiles;
<add>import org.springframework.aot.test.generate.file.ResourceFile;
<add>import org.springframework.aot.test.generate.file.ResourceFiles;
<add>import org.springframework.aot.test.generate.file.SourceFile;
<add>import org.springframework.aot.test.generate.file.SourceFiles;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide>
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/DynamicClassFileObject.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/DynamicClassFileObject.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.io.ByteArrayOutputStream;
<ide> import java.io.OutputStream;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/DynamicClassLoader.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/DynamicClassLoader.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.io.ByteArrayInputStream;
<ide> import java.io.IOException;
<ide> import java.util.Enumeration;
<ide> import java.util.Map;
<ide>
<del>import org.springframework.aot.test.generator.file.ResourceFile;
<del>import org.springframework.aot.test.generator.file.ResourceFiles;
<add>import org.springframework.aot.test.generate.file.ResourceFile;
<add>import org.springframework.aot.test.generate.file.ResourceFiles;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ReflectionUtils;
<ide>
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/DynamicJavaFileManager.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/DynamicJavaFileManager.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.io.IOException;
<ide> import java.util.Collections;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/DynamicJavaFileObject.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/DynamicJavaFileObject.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.net.URI;
<ide>
<ide> import javax.tools.JavaFileObject;
<ide> import javax.tools.SimpleJavaFileObject;
<ide>
<del>import org.springframework.aot.test.generator.file.SourceFile;
<add>import org.springframework.aot.test.generate.file.SourceFile;
<ide>
<ide> /**
<ide> * Adapts a {@link SourceFile} instance to a {@link JavaFileObject}.
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/TestCompiler.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/TestCompiler.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.io.PrintStream;
<ide> import java.util.ArrayList;
<ide>
<ide> import org.springframework.aot.generate.GeneratedFiles.Kind;
<ide> import org.springframework.aot.generate.InMemoryGeneratedFiles;
<del>import org.springframework.aot.test.generator.file.ResourceFile;
<del>import org.springframework.aot.test.generator.file.ResourceFiles;
<del>import org.springframework.aot.test.generator.file.SourceFile;
<del>import org.springframework.aot.test.generator.file.SourceFiles;
<del>import org.springframework.aot.test.generator.file.WritableContent;
<add>import org.springframework.aot.test.generate.file.ResourceFile;
<add>import org.springframework.aot.test.generate.file.ResourceFiles;
<add>import org.springframework.aot.test.generate.file.SourceFile;
<add>import org.springframework.aot.test.generate.file.SourceFiles;
<add>import org.springframework.aot.test.generate.file.WritableContent;
<ide> import org.springframework.lang.Nullable;
<ide>
<ide> /**
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/compile/package-info.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/compile/package-info.java
<ide> */
<ide> @NonNullApi
<ide> @NonNullFields
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import org.springframework.lang.NonNullApi;
<ide> import org.springframework.lang.NonNullFields;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/DynamicFile.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/DynamicFile.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.io.IOException;
<ide> import java.util.Objects;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/DynamicFileAssert.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/DynamicFileAssert.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import org.assertj.core.api.AbstractAssert;
<ide>
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/DynamicFiles.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/DynamicFiles.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/ResourceFile.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/ResourceFile.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.io.InputStreamReader;
<ide> import java.nio.charset.StandardCharsets;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/ResourceFileAssert.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/ResourceFileAssert.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> /**
<ide> * Assertion methods for {@code ResourceFile} instances.
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/ResourceFiles.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/ResourceFiles.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.util.Iterator;
<ide> import java.util.stream.Stream;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/SourceFile.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/SourceFile.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.io.IOException;
<ide> import java.io.InputStreamReader;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/SourceFileAssert.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/SourceFileAssert.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> /**
<ide> * Assertion methods for {@code SourceFile} instances.
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/SourceFiles.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/SourceFiles.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.util.Iterator;
<ide> import java.util.Objects;
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/WritableContent.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/WritableContent.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.io.IOException;
<ide>
<add><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/file/package-info.java
<del><path>spring-core-test/src/main/java/org/springframework/aot/test/generator/file/package-info.java
<ide> */
<ide> @NonNullApi
<ide> @NonNullFields
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import org.springframework.lang.NonNullApi;
<ide> import org.springframework.lang.NonNullFields;
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/compile/CompilationExceptionTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/compile/CompilationExceptionTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.aot.test.generator.file.ResourceFiles;
<del>import org.springframework.aot.test.generator.file.SourceFiles;
<add>import org.springframework.aot.test.generate.file.ResourceFiles;
<add>import org.springframework.aot.test.generate.file.SourceFiles;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/compile/CompiledTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/compile/CompiledTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.util.List;
<ide> import java.util.concurrent.Callable;
<ide> import java.util.function.Supplier;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.aot.test.generator.file.ResourceFile;
<del>import org.springframework.aot.test.generator.file.ResourceFiles;
<del>import org.springframework.aot.test.generator.file.SourceFile;
<del>import org.springframework.aot.test.generator.file.SourceFiles;
<add>import org.springframework.aot.test.generate.file.ResourceFile;
<add>import org.springframework.aot.test.generate.file.ResourceFiles;
<add>import org.springframework.aot.test.generate.file.SourceFile;
<add>import org.springframework.aot.test.generate.file.SourceFiles;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/compile/DynamicClassFileObjectTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/compile/DynamicClassFileObjectTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.io.ByteArrayInputStream;
<ide> import java.io.OutputStream;
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/compile/DynamicJavaFileManagerTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/compile/DynamicJavaFileManagerTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import javax.tools.JavaFileManager;
<ide> import javax.tools.JavaFileManager.Location;
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/compile/DynamicJavaFileObjectTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/compile/DynamicJavaFileObjectTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.aot.test.generator.file.SourceFile;
<add>import org.springframework.aot.test.generate.file.SourceFile;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/compile/TestCompilerTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/compile/TestCompilerTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.compile;
<add>package org.springframework.aot.test.generate.compile;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import com.example.PublicInterface;
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.aot.test.generator.file.ResourceFile;
<del>import org.springframework.aot.test.generator.file.ResourceFiles;
<del>import org.springframework.aot.test.generator.file.SourceFile;
<del>import org.springframework.aot.test.generator.file.SourceFiles;
<del>import org.springframework.aot.test.generator.file.WritableContent;
<add>import org.springframework.aot.test.generate.file.ResourceFile;
<add>import org.springframework.aot.test.generate.file.ResourceFiles;
<add>import org.springframework.aot.test.generate.file.SourceFile;
<add>import org.springframework.aot.test.generate.file.SourceFiles;
<add>import org.springframework.aot.test.generate.file.WritableContent;
<ide> import org.springframework.util.ClassUtils;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/file/ResourceFileTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/file/ResourceFileTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/file/ResourceFilesTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/file/ResourceFilesTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.util.Iterator;
<ide>
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/file/SourceFileAssertTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/file/SourceFileAssertTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/file/SourceFileTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/file/SourceFileTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.io.IOException;
<ide>
<add><path>spring-core-test/src/test/java/org/springframework/aot/test/generate/file/SourceFilesTests.java
<del><path>spring-core-test/src/test/java/org/springframework/aot/test/generator/file/SourceFilesTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.aot.test.generator.file;
<add>package org.springframework.aot.test.generate.file;
<ide>
<ide> import java.util.Iterator;
<ide>
<ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/persistenceunit/PersistenceManagedTypesBeanRegistrationAotProcessorTests.java
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.context.ApplicationContextInitializer;
<ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<ide> import org.springframework.context.annotation.Bean;
<ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/support/InjectionCodeGeneratorTests.java
<ide>
<ide> import org.springframework.aot.hint.RuntimeHints;
<ide> import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.testfixture.beans.TestBean;
<ide> import org.springframework.beans.testfixture.beans.TestBeanWithPrivateMethod;
<ide> import org.springframework.beans.testfixture.beans.TestBeanWithPublicField;
<ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessorAotContributionTests.java
<ide> import org.springframework.aot.hint.FieldMode;
<ide> import org.springframework.aot.hint.TypeReference;
<ide> import org.springframework.aot.test.generate.TestGenerationContext;
<del>import org.springframework.aot.test.generator.compile.CompileWithTargetClassAccess;
<del>import org.springframework.aot.test.generator.compile.Compiled;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.CompileWithTargetClassAccess;
<add>import org.springframework.aot.test.generate.compile.Compiled;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
<ide> import org.springframework.beans.factory.aot.BeanRegistrationCode;
<ide> import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide><path>spring-test/src/test/java/org/springframework/test/context/aot/AotIntegrationTests.java
<ide> import org.springframework.aot.AotDetector;
<ide> import org.springframework.aot.generate.GeneratedFiles.Kind;
<ide> import org.springframework.aot.generate.InMemoryGeneratedFiles;
<del>import org.springframework.aot.test.generator.compile.CompileWithTargetClassAccess;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.CompileWithTargetClassAccess;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterSharedConfigTests;
<ide> import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterTests;
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/context/aot/TestContextAotGeneratorTests.java
<ide> import org.springframework.aot.hint.MemberCategory;
<ide> import org.springframework.aot.hint.RuntimeHints;
<ide> import org.springframework.aot.hint.TypeReference;
<del>import org.springframework.aot.test.generator.compile.CompileWithTargetClassAccess;
<del>import org.springframework.aot.test.generator.compile.TestCompiler;
<add>import org.springframework.aot.test.generate.compile.CompileWithTargetClassAccess;
<add>import org.springframework.aot.test.generate.compile.TestCompiler;
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.ApplicationContextInitializer;
<ide> import org.springframework.context.ConfigurableApplicationContext; | 49 |
PHP | PHP | fix cs issue | e1526242e52e61eb5a0f8a4d46920a7afae8b72f | <ide><path>src/ORM/Table.php
<ide> protected function _saveMany(iterable $entities, $options = []): iterable
<ide>
<ide> throw new PersistenceFailedException($failed, ['saveMany']);
<ide> }
<del>
<add>
<ide> if ($this->_transactionCommitted($options['atomic'], $options['_primary'])) {
<ide> foreach ($entities as $entity) {
<ide> $this->dispatchEvent('Model.afterSaveCommit', compact('entity', 'options'));
<ide> }
<ide> }
<del>
<add>
<ide> return $entities;
<ide> }
<ide> | 1 |
Ruby | Ruby | convert argv audit to negative look ahead | fb85ed01bc170e389dd62a2a2872d962b7dad5a6 | <ide><path>Library/Homebrew/rubocops/extend/formula_cop.rb
<ide> def find_instance_method_call(node, instance, method_name)
<ide> end
<ide> end
<ide>
<add> # Matches receiver part of method,
<add> # EX: to match `ARGV.<whatever>()`
<add> # call `find_instance_call(node, "ARGV")`
<add> # yields to a block with parent node of receiver
<add> def find_instance_call(node, name)
<add> node.each_descendant(:send) do |method_node|
<add> next if method_node.receiver.nil?
<add> next if method_node.receiver.const_name != name &&
<add> method_node.receiver.method_name != name
<add> @offense_source_range = method_node.receiver.source_range
<add> @offensive_node = method_node.receiver
<add> return true unless block_given?
<add> yield method_node
<add> end
<add> end
<add>
<ide> # Returns nil if does not depend on dependency_name
<ide> # args: node - dependency_name - dependency's name
<ide> def depends_on?(dependency_name, *types)
<ide><path>Library/Homebrew/rubocops/lines_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> end
<ide> end
<ide>
<del> [:debug?, :verbose?, :value].each do |method_name|
<del> find_instance_method_call(body_node, "ARGV", method_name) do
<del> problem "Use build instead of ARGV to check options"
<del> end
<add> find_instance_call(body_node, "ARGV") do |method_node|
<add> next if [:debug?, :verbose?, :value].index(method_node.method_name)
<add> problem "Use build instead of ARGV to check options"
<ide> end
<ide>
<ide> find_instance_method_call(body_node, :man, :+) do |method|
<ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb
<ide> class Foo < Formula
<ide> end
<ide>
<ide> it "Using ARGV to check options" do
<del> expect_offense(<<~RUBY)
<add> expect_no_offenses(<<~RUBY)
<ide> class Foo < Formula
<ide> desc "foo"
<ide> url 'http://example.com/foo-1.0.tgz'
<ide> def install
<ide> verbose = ARGV.verbose?
<del> ^^^^^^^^^^^^^ Use build instead of ARGV to check options
<ide> end
<ide> end
<ide> RUBY
<ide> class Foo < Formula
<ide> test do
<ide> head = ARGV.include? "--HEAD"
<ide> ^^^^^^ Use "if build.head?" instead
<add> ^^^^ Use build instead of ARGV to check options
<ide> end
<ide> end
<ide> RUBY | 3 |
PHP | PHP | implement withuri() and tests for geturi() as well | bc19b3a2dcf19e066b802c569aa6a3123a9139de | <ide><path>src/Network/Request.php
<ide> public function getUri()
<ide> return $this->uri;
<ide> }
<ide>
<add> /**
<add> * Return an instance with the specified uri
<add> *
<add> * *Warning* Replacing the Uri will not update the `base`, `webroot`,
<add> * and `url` attributes.
<add> *
<add> * @param \Psr\Http\Message\UriInterface $uri The new request uri
<add> * @return static
<add> */
<add> public function withUri(UriInterface $uri)
<add> {
<add> $new = clone $this;
<add> $new->uri = $uri;
<add>
<add> return $new;
<add> }
<add>
<ide> /**
<ide> * Array access read implementation
<ide> *
<ide><path>tests/TestCase/Network/RequestTest.php
<ide> public function testWithBody()
<ide> $this->assertSame($body, $new->getBody());
<ide> }
<ide>
<add> /**
<add> * Test getUri
<add> *
<add> * @return void
<add> */
<add> public function testGetUri()
<add> {
<add> $request = new Request(['url' => 'articles/view/3']);
<add> $this->assertEquals('articles/view/3', $request->url);
<add>
<add> $result = $request->getUri();
<add> $this->assertInstanceOf('Psr\Http\Message\UriInterface', $result);
<add> $this->assertEquals('/articles/view/3', $result->getPath());
<add> }
<add>
<add> /**
<add> * Test withUri
<add> *
<add> * @return void
<add> */
<add> public function testWithUri()
<add> {
<add> $request = new Request([
<add> 'url' => 'articles/view/3'
<add> ]);
<add> $uri = $this->getMockBuilder('Psr\Http\Message\UriInterface')->getMock();
<add> $new = $request->withUri($uri);
<add> $this->assertNotSame($new, $request);
<add> $this->assertNotSame($uri, $request->getUri());
<add> $this->assertSame($uri, $new->getUri());
<add> $this->assertSame('articles/view/3', $new->url);
<add> $this->assertSame('articles/view/3', $request->url);
<add> }
<add>
<ide> /**
<ide> * Test is('requested') and isRequested()
<ide> * | 2 |
Ruby | Ruby | fix failing tests | 848cba13bd8a1fd7445458160a15dbf175c4c61d | <ide><path>activerecord/test/cases/relation/where_chain_test.rb
<ide> def test_not_eq
<ide> end
<ide>
<ide> def test_not_null
<del> expected = Post.arel_table[@name].not_eq(Arel::Nodes::Quoted.new(nil))
<add> expected = Post.arel_table[@name].not_eq(nil)
<ide> relation = Post.where.not(title: nil)
<ide> assert_equal([expected], relation.where_values)
<ide> end
<ide> def test_not_with_nil
<ide> end
<ide>
<ide> def test_not_in
<del> values = %w[hello goodbye].map { |v| Arel::Nodes::Quoted.new(v) }
<del> expected = Post.arel_table[@name].not_in(values)
<add> expected = Post.arel_table[@name].not_in(%w[hello goodbye])
<ide> relation = Post.where.not(title: %w[hello goodbye])
<ide> assert_equal([expected], relation.where_values)
<ide> end
<ide>
<ide> def test_association_not_eq
<del> expected = Comment.arel_table[@name].not_eq(Arel::Nodes::Quoted.new('hello'))
<add> expected = Comment.arel_table[@name].not_eq('hello')
<ide> relation = Post.joins(:comments).where.not(comments: {title: 'hello'})
<ide> assert_equal(expected.to_sql, relation.where_values.first.to_sql)
<ide> end
<ide> def test_not_eq_with_array_parameter
<ide> def test_chaining_multiple
<ide> relation = Post.where.not(author_id: [1, 2]).where.not(title: 'ruby on rails')
<ide>
<del> expected = Post.arel_table['author_id'].not_in([
<del> Arel::Nodes::Quoted.new(1),
<del> Arel::Nodes::Quoted.new(2),
<del> ])
<add> expected = Post.arel_table['author_id'].not_in([1, 2])
<ide> assert_equal(expected, relation.where_values[0])
<ide>
<ide> value = relation.where_values[1] | 1 |
Text | Text | remove chinese files from sidebar | 7fef673f93e93bc759f6391c0e8527489da7e497 | <ide><path>docs/_sidebar.md
<ide>
<ide> ---
<ide>
<del><!-- The section below should not use relative linking -->
<del>
<del>- **中文社区贡献指南**
<del> - [成为专栏作者](/i18n/Chinese/news-author-application.md)
<del> - [文章翻译计划](/i18n/Chinese/news-translations.md)
<del> - [视频翻译计划](/i18n/Chinese/video-translations.md)
<del>
<del><!-- The section above should not use relative linking -->
<del>
<del>---
<del>
<ide> - **Flight Manuals** (for Staff & Mods)
<ide> - [Moderator Handbook](moderator-handbook.md)
<ide> - [DevOps Handbook](devops.md) | 1 |
Python | Python | add monte carlo estimation of pi | 1bc84e1fa0b3bbd75c73b0b1b25f573c241e1c9b | <ide><path>maths/pi_monte_carlo_estimation.py
<add>import random
<add>
<add>
<add>class Point:
<add> def __init__(self, x: float, y: float) -> None:
<add> self.x = x
<add> self.y = y
<add>
<add> def is_in_unit_circle(self) -> bool:
<add> """
<add> True, if the point lies in the unit circle
<add> False, otherwise
<add> """
<add> return (self.x ** 2 + self.y ** 2) <= 1
<add>
<add> @classmethod
<add> def random_unit_square(cls):
<add> """
<add> Generates a point randomly drawn from the unit square [0, 1) x [0, 1).
<add> """
<add> return cls(x = random.random(), y = random.random())
<add>
<add>def estimate_pi(number_of_simulations: int) -> float:
<add> """
<add> Generates an estimate of the mathematical constant PI (see https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview).
<add>
<add> The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is:
<add>
<add> P[U in unit circle] = 1/4 PI
<add>
<add> and therefore
<add>
<add> PI = 4 * P[U in unit circle]
<add>
<add> We can get an estimate of the probability P[U in unit circle] (see https://en.wikipedia.org/wiki/Empirical_probability) by:
<add>
<add> 1. Draw a point uniformly from the unit square.
<add> 2. Repeat the first step n times and count the number of points in the unit circle, which is called m.
<add> 3. An estimate of P[U in unit circle] is m/n
<add> """
<add> if number_of_simulations < 1:
<add> raise ValueError("At least one simulation is necessary to estimate PI.")
<add>
<add> number_in_unit_circle = 0
<add> for simulation_index in range(number_of_simulations):
<add> random_point = Point.random_unit_square()
<add>
<add> if random_point.is_in_unit_circle():
<add> number_in_unit_circle += 1
<add>
<add> return 4 * number_in_unit_circle / number_of_simulations
<add>
<add>
<add>if __name__ == "__main__":
<add> # import doctest
<add>
<add> # doctest.testmod()
<add> from math import pi
<add> prompt = "Please enter the desired number of Monte Carlo simulations: "
<add> my_pi = estimate_pi(int(input(prompt).strip()))
<add> print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}") | 1 |
Javascript | Javascript | allow parsing of empty geometry nodes | 96d5134090427f72004627e96c4a96cc96f99445 | <ide><path>examples/js/loaders/FBXLoader.js
<ide> // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
<ide> function genGeometry( FBXTree, relationships, geometryNode, skeleton, preTransform ) {
<ide>
<del> var vertexPositions = geometryNode.Vertices.a;
<del> var vertexIndices = geometryNode.PolygonVertexIndex.a;
<add> var vertexPositions = ( geometryNode.Vertices !== undefined ) ? geometryNode.Vertices.a : [];
<add> var vertexIndices = ( geometryNode.PolygonVertexIndex !== undefined ) ? geometryNode.PolygonVertexIndex.a : [];
<ide>
<ide> // create arrays to hold the final data used to build the buffergeometry
<ide> var vertexBuffer = []; | 1 |
PHP | PHP | build prototype of running requests | ef79fd4dc7b9cf9f25dc9c12e471b8ea28ca97bd | <ide><path>lib/Cake/Network/Http/Adapter/Stream.php
<ide> */
<ide> namespace Cake\Network\Http\Adapter;
<ide>
<add>use Cake\Error;
<ide> use Cake\Network\Http\Request;
<ide> use Cake\Network\Http\Response;
<ide> use Cake\Network\Http\FormData;
<ide> class Stream {
<ide> */
<ide> protected $_stream;
<ide>
<add>/**
<add> * Connection error list.
<add> *
<add> * @var array
<add> */
<add> protected $_connectionErrors = [];
<add>
<ide> /**
<ide> * Send a request and get a response back.
<ide> *
<ide> class Stream {
<ide> * @return Cake\Network\Http\Response
<ide> */
<ide> public function send(Request $request, $options) {
<del> $this->_context = array();
<add> $this->_stream = null;
<add> $this->_context = [];
<add> $this->_connectionErrors = [];
<ide>
<ide> $this->_buildContext($request, $options);
<del> return $this->_send();
<add> return $this->_send($request);
<ide> }
<ide>
<ide> /**
<ide> protected function _buildContent(Request $request, $options) {
<ide> $type = 'multipart/form-data; boundary="' . $formData->boundary() . '"';
<ide> $request->header('Content-Type', $type);
<ide> $this->_contextOptions['content'] = (string)$formData;
<add> return;
<ide> }
<add> $this->_contextOptions['content'] = $content;
<ide> }
<ide>
<ide> /**
<ide> protected function _buildSslContext(Request $request, $options) {
<ide> }
<ide> }
<ide>
<del> protected function _send() {
<add>/**
<add> * Open the stream and send the request.
<add> *
<add> * @return void
<add> * @throws Cake\Error\Exception
<add> */
<add> protected function _send($request) {
<add> $url = $request->url();
<add> $this->_open($url);
<add> $content = '';
<add> while (!feof($this->_stream)) {
<add> $content .= fread($this->_stream, 8192);
<add> }
<add> $meta = stream_get_meta_data($this->_stream);
<add> fclose($this->_stream);
<add>
<add> if ($meta['timed_out']) {
<add> throw Error\Exception('Connection timed out ' . $url);
<add> }
<add> $headers = $meta['wrapper_data'];
<add> if (isset($meta['wrapper_type']) && $meta['wrapper_type'] === 'curl') {
<add> $headers = $meta['wrapper_data']['headers'];
<add> }
<add> return new Response($headers, $content);
<add> }
<add>
<add>/**
<add> * Open the socket and handle any connection errors.
<add> *
<add> * @param string $url The url to connect to.
<add> * @return void
<add> * @throws Cake\Error\Exception
<add> */
<add> protected function _open($url) {
<add> set_error_handler([$this, '_connectionErrorHandler']);
<add> $this->_stream = fopen($url, 'rb', false, $this->_context);
<add> restore_error_handler();
<add>
<add> if (!$this->_stream || !empty($this->_connectionErrors)) {
<add> throw new Error\Exception(implode("\n", $this->_connectionErrors));
<add> }
<add> }
<add>
<add>/**
<add> * Local error handler to capture errors triggered during
<add> * stream connection.
<add> *
<add> * @param int $code
<add> * @param string $message
<add> * @return void
<add> */
<add> protected function _connectionErrorHandler($code, $message) {
<add> $this->_connectionErrors[] = $message;
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Network/Http/Response.php
<ide> */
<ide> class Response {
<ide>
<del> public function __construct() {
<add> protected $_headers;
<add> protected $_content;
<add>
<add> public function headers($headers = null) {
<add> if ($headers === null) {
<add> return $this->_headers;
<add> }
<add> $this->_headers = $headers;
<add> return $this;
<add> }
<add>
<add> public function content($content) {
<add> if ($content === null) {
<add> return $this->_content;
<add> }
<add> $this->_content = $content;
<add> return $this;
<ide> }
<ide>
<ide> } | 2 |
Ruby | Ruby | get modules back into integration tests | 0e15f07b75d04ddc349a93ad7fdfcbc502ef535d | <ide><path>actionpack/lib/action_controller/test_case.rb
<ide> require 'rack/session/abstract/id'
<del>require 'action_view/test_case'
<ide>
<ide> module ActionController
<ide> module TemplateAssertions
<ide><path>actionpack/lib/action_dispatch/testing/integration.rb
<ide> def process(method, path, parameters = nil, rack_environment = nil)
<ide> end
<ide>
<ide> module Runner
<add> include ActionDispatch::Assertions
<add>
<ide> def app
<ide> @app
<ide> end
<ide> def method_missing(sym, *args, &block)
<ide> # end
<ide> class IntegrationTest < ActiveSupport::TestCase
<ide> include Integration::Runner
<add> include ActionController::TemplateAssertions
<ide>
<ide> @@app = nil
<ide> | 2 |
Ruby | Ruby | use ohai to print messages | 0fe532c242d73c73eeb2b87a15a46ec9602685df | <ide><path>Library/Homebrew/dev-cmd/boneyard-formula-pr.rb
<ide> def boneyard_formula_pr
<ide> boneyard_tap = Tap.fetch("homebrew", "boneyard")
<ide> tap_migrations_path = formula.tap.path/"tap_migrations.json"
<ide> if ARGV.dry_run?
<del> puts "brew update"
<del> puts "brew tap #{boneyard_tap.name}"
<del> puts "cd #{formula.tap.path}"
<add> ohai "brew update"
<add> ohai "brew tap #{boneyard_tap.name}"
<add> ohai "cd #{formula.tap.path}"
<ide> cd formula.tap.path
<del> puts "cp #{formula_relpath} #{boneyard_tap.path}"
<del> puts "git rm #{formula_relpath}"
<add> ohai "cp #{formula_relpath} #{boneyard_tap.path}"
<add> ohai "git rm #{formula_relpath}"
<ide> unless File.exist? tap_migrations_path
<del> puts "Creating tap_migrations.json for #{formula.tap.name}"
<del> puts "git add #{tap_migrations_path}"
<add> ohai "Creating tap_migrations.json for #{formula.tap.name}"
<add> ohai "git add #{tap_migrations_path}"
<ide> end
<del> puts "Loading tap_migrations.json"
<del> puts "Adding #{formula.name} to tap_migrations.json"
<add> ohai "Loading tap_migrations.json"
<add> ohai "Adding #{formula.name} to tap_migrations.json"
<ide> else
<ide> safe_system HOMEBREW_BREW_FILE, "update"
<ide> safe_system HOMEBREW_BREW_FILE, "tap", boneyard_tap.name
<ide> def boneyard_formula_pr
<ide> end
<ide> unless which("hub") || local_only
<ide> if ARGV.dry_run?
<del> puts "brew install hub"
<add> ohai "brew install hub"
<ide> else
<ide> safe_system HOMEBREW_BREW_FILE, "install", "hub"
<ide> end
<ide> def boneyard_formula_pr
<ide> reason = " because #{reason}" if reason
<ide>
<ide> if ARGV.dry_run?
<del> puts "cd #{formula.tap.path}"
<del> puts "git checkout --no-track -b #{branch} origin/master"
<del> puts "git commit --no-edit --verbose --message=\"#{formula.name}: migrate to boneyard\" -- #{formula_relpath} #{tap_migrations_path.basename}"
<add> ohai "cd #{formula.tap.path}"
<add> ohai "git checkout --no-track -b #{branch} origin/master"
<add> ohai "git commit --no-edit --verbose --message=\"#{formula.name}: migrate to boneyard\" -- #{formula_relpath} #{tap_migrations_path.basename}"
<ide>
<ide> unless local_only
<del> puts "hub fork --no-remote"
<del> puts "hub fork"
<del> puts "hub fork (to read $HUB_REMOTE)"
<del> puts "git push $HUB_REMOTE #{branch}:#{branch}"
<del> puts "hub pull-request -m $'#{formula.name}: migrate to boneyard\\n\\nCreated with `brew boneyard-formula-pr`#{reason}.'"
<add> ohai "hub fork --no-remote"
<add> ohai "hub fork"
<add> ohai "hub fork (to read $HUB_REMOTE)"
<add> ohai "git push $HUB_REMOTE #{branch}:#{branch}"
<add> ohai "hub pull-request -m $'#{formula.name}: migrate to boneyard\\n\\nCreated with `brew boneyard-formula-pr`#{reason}.'"
<ide> end
<ide> else
<ide> cd formula.tap.path
<ide> def boneyard_formula_pr
<ide> end
<ide>
<ide> if ARGV.dry_run?
<del> puts "cd #{boneyard_tap.path}"
<del> puts "git checkout --no-track -b #{branch} origin/master"
<add> ohai "cd #{boneyard_tap.path}"
<add> ohai "git checkout --no-track -b #{branch} origin/master"
<ide> if bottle_block
<del> puts "Removing bottle block"
<add> ohai "Removing bottle block"
<ide> else
<del> puts "No bottle block to remove"
<add> ohai "No bottle block to remove"
<ide> end
<del> puts "git add #{formula_file}"
<del> puts "git commit --no-edit --verbose --message=\"#{formula.name}: migrate from #{formula.tap.repo}\" -- #{formula_file}"
<add> ohai "git add #{formula_file}"
<add> ohai "git commit --no-edit --verbose --message=\"#{formula.name}: migrate from #{formula.tap.repo}\" -- #{formula_file}"
<ide>
<ide> unless local_only
<del> puts "hub fork --no-remote"
<del> puts "hub fork"
<del> puts "hub fork (to read $HUB_REMOTE)"
<del> puts "git push $HUB_REMOTE #{branch}:#{branch}"
<del> puts "hub pull-request --browse -m $'#{formula.name}: migrate from #{formula.tap.repo}\\n\\nGoes together with $PR_URL\\n\\nCreated with `brew boneyard-formula-pr`#{reason}.'"
<add> ohai "hub fork --no-remote"
<add> ohai "hub fork"
<add> ohai "hub fork (to read $HUB_REMOTE)"
<add> ohai "git push $HUB_REMOTE #{branch}:#{branch}"
<add> ohai "hub pull-request --browse -m $'#{formula.name}: migrate from #{formula.tap.repo}\\n\\nGoes together with $PR_URL\\n\\nCreated with `brew boneyard-formula-pr`#{reason}.'"
<ide> end
<ide> else
<ide> cd boneyard_tap.formula_dir | 1 |
PHP | PHP | move method around | a3c47d6209d7a0889c03c7670d499d41b5d42d94 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> protected function createRequest(Request $request = null)
<ide> return $request ?: static::onRequest('createFromGlobals');
<ide> }
<ide>
<del> /**
<del> * Set the application request for the console environment.
<del> *
<del> * @return void
<del> */
<del> public function setRequestForConsoleEnvironment()
<del> {
<del> $url = $this['config']->get('app.url', 'http://localhost');
<del>
<del> $parameters = array($url, 'GET', array(), array(), array(), $_SERVER);
<del>
<del> $this->instance('request', static::onRequest('create', $parameters));
<del> }
<del>
<ide> /**
<ide> * Redirect the request if it has a trailing slash.
<ide> *
<ide> public static function requestClass($class = null)
<ide> return static::$requestClass;
<ide> }
<ide>
<add> /**
<add> * Set the application request for the console environment.
<add> *
<add> * @return void
<add> */
<add> public function setRequestForConsoleEnvironment()
<add> {
<add> $url = $this['config']->get('app.url', 'http://localhost');
<add>
<add> $parameters = array($url, 'GET', array(), array(), array(), $_SERVER);
<add>
<add> $this->instance('request', static::onRequest('create', $parameters));
<add> }
<add>
<ide> /**
<ide> * Call a method on the default request class.
<ide> * | 1 |
Javascript | Javascript | use correct fontweight value in thememanager spec | 9921e18e5a3c8050044b903dbd97e891a670198e | <ide><path>spec/theme-manager-spec.js
<ide> h2 {
<ide> it('returns a disposable allowing styles applied by the given path to be removed', function () {
<ide> const cssPath = require.resolve('./fixtures/css.css')
<ide>
<del> expect(getComputedStyle(document.body).fontWeight).not.toBe('bold')
<add> expect(getComputedStyle(document.body).fontWeight).not.toBe('700')
<ide> const disposable = atom.themes.requireStylesheet(cssPath)
<del> expect(getComputedStyle(document.body).fontWeight).toBe('bold')
<add> expect(getComputedStyle(document.body).fontWeight).toBe('700')
<ide>
<ide> let styleElementRemovedHandler
<ide> atom.styles.onDidRemoveStyleElement( | 1 |
Text | Text | update api version-history for 1.35 | 8a9d926b553345be530ddc51374c9817fcbea784 | <ide><path>docs/api/version-history.md
<ide> keywords: "API, Docker, rcli, REST, documentation"
<ide> configuration is only used for Windows containers.
<ide> * `GET /containers/(name)/logs` now supports an additional query parameter: `until`,
<ide> which returns log lines that occurred before the specified timestamp.
<add>* `POST /containers/{id}/exec` now accepts a `WorkingDir` property to set the
<add> work-dir for the exec process, independent of the container's work-dir.
<add>* `Get /version` now returns a `Platform.Name` field, which can be used by products
<add> using Moby as a foundation to return information about the platform.
<add>* `Get /version` now returns a `Components` field, which can be used to return
<add> information about the components used. Information about the engine itself is
<add> now included as a "Component" version, and contains all information from the
<add> top-level `Version`, `GitCommit`, `APIVersion`, `MinAPIVersion`, `GoVersion`,
<add> `Os`, `Arch`, `BuildTime`, `KernelVersion`, and `Experimental` fields. Going
<add> forward, the information from the `Components` section is preferred over their
<add> top-level counterparts.
<add>
<ide>
<ide> ## v1.34 API changes
<ide> | 1 |
PHP | PHP | fix styleci issue | 50c35401f53e695d9b708700666248d481b9db8a | <ide><path>src/Illuminate/Database/Schema/ColumnDefinition.php
<ide>
<ide> namespace Illuminate\Database\Schema;
<ide>
<del>use Illuminate\Database\Query\Expression;
<ide> use Illuminate\Support\Fluent;
<add>use Illuminate\Database\Query\Expression;
<ide>
<ide> /**
<ide> * @method ColumnDefinition after(string $column) Place the column "after" another column (MySQL) | 1 |
Go | Go | turn ipc unmount errors into warnings | a54d5932e3a644317c77d59bc5aee562841d5c20 | <ide><path>daemon/container.go
<ide> func (streamConfig *streamConfig) StderrPipe() io.ReadCloser {
<ide> func (container *Container) cleanup() {
<ide> container.releaseNetwork()
<ide>
<del> if err := container.unmountIpcMounts(detachMounted); err != nil {
<del> logrus.Errorf("%s: Failed to umount ipc filesystems: %v", container.ID, err)
<del> }
<add> container.unmountIpcMounts(detachMounted)
<ide>
<ide> container.conditionalUnmountOnCleanup()
<ide>
<ide><path>daemon/container_unix.go
<ide> func (container *Container) setupIpcDirs() error {
<ide> return nil
<ide> }
<ide>
<del>func (container *Container) unmountIpcMounts(unmount func(pth string) error) error {
<add>func (container *Container) unmountIpcMounts(unmount func(pth string) error) {
<ide> if container.hostConfig.IpcMode.IsContainer() || container.hostConfig.IpcMode.IsHost() {
<del> return nil
<add> return
<ide> }
<ide>
<del> var errors []string
<add> var warnings []string
<ide>
<ide> if !container.hasMountFor("/dev/shm") {
<ide> shmPath, err := container.shmPath()
<ide> if err != nil {
<ide> logrus.Error(err)
<del> errors = append(errors, err.Error())
<del> } else {
<add> warnings = append(warnings, err.Error())
<add> } else if shmPath != "" {
<ide> if err := unmount(shmPath); err != nil {
<del> logrus.Errorf("failed to umount %s: %v", shmPath, err)
<del> errors = append(errors, err.Error())
<add> warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
<ide> }
<ide>
<ide> }
<ide> func (container *Container) unmountIpcMounts(unmount func(pth string) error) err
<ide> mqueuePath, err := container.mqueuePath()
<ide> if err != nil {
<ide> logrus.Error(err)
<del> errors = append(errors, err.Error())
<del> } else {
<add> warnings = append(warnings, err.Error())
<add> } else if mqueuePath != "" {
<ide> if err := unmount(mqueuePath); err != nil {
<del> logrus.Errorf("failed to umount %s: %v", mqueuePath, err)
<del> errors = append(errors, err.Error())
<add> warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", mqueuePath, err))
<ide> }
<ide> }
<ide> }
<ide>
<del> if len(errors) > 0 {
<del> return fmt.Errorf("failed to cleanup ipc mounts:\n%v", strings.Join(errors, "\n"))
<add> if len(warnings) > 0 {
<add> logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
<ide> }
<del>
<del> return nil
<ide> }
<ide>
<ide> func (container *Container) ipcMounts() []execdriver.Mount {
<ide><path>daemon/container_windows.go
<ide> func (container *Container) setupIpcDirs() error {
<ide> return nil
<ide> }
<ide>
<del>func (container *Container) unmountIpcMounts(unmount func(pth string) error) error {
<del> return nil
<add>func (container *Container) unmountIpcMounts(unmount func(pth string) error) {
<ide> }
<ide>
<ide> func detachMounted(path string) error {
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Register(container *Container) error {
<ide> }
<ide> daemon.execDriver.Terminate(cmd)
<ide>
<del> if err := container.unmountIpcMounts(mount.Unmount); err != nil {
<del> logrus.Errorf("%s: Failed to umount ipc filesystems: %v", container.ID, err)
<del> }
<add> container.unmountIpcMounts(mount.Unmount)
<add>
<ide> if err := container.Unmount(); err != nil {
<ide> logrus.Debugf("unmount error %s", err)
<ide> } | 4 |
Python | Python | add colorconsole for platform windows | 3f4259eaa67d740e4ac7f7ebcc8630ec6d59652c | <ide><path>setup.py
<ide> for mo in glob.glob('i18n/*/LC_MESSAGES/*.mo'):
<ide> data_files.append((os.path.dirname(mo).replace('i18n/', 'share/locale/'), [mo]))
<ide>
<add>if sys.platform.startswith('win'):
<add> requires = ['psutil>=0.5.1', 'colorconsole==0.6']
<add>else:
<add> requires = ['psutil>=0.5.1']
<add>
<ide> setup(
<ide> name='Glances',
<ide> version='1.7.1',
<ide> # Alternative download_url='https://s3.amazonaws.com/glances/glances-1.7.1.tar.gz',
<ide> license="LGPL",
<ide> keywords="cli curses monitoring system",
<del> install_requires=['psutil>=0.5.1'],
<add> install_requires=requires,
<ide> extras_require={
<ide> 'HTML': ['jinja2'],
<ide> 'SENSORS': ['pysensors'], | 1 |
Javascript | Javascript | increase coverage for internal/module.js | 83ebb6d8989ea08fdeb25353c42d20d0c0c285db | <ide><path>test/parallel/test-internal-modules-strip-shebang.js
<add>// Flags: --expose-internals
<add>'use strict';
<add>require('../common');
<add>
<add>const assert = require('assert');
<add>const stripShebang = require('internal/module').stripShebang;
<add>
<add>[
<add> ['', ''],
<add> ['aa', 'aa'],
<add> ['#!', ''],
<add> ['#!bin/bash', ''],
<add> ['#!bin/bash\naa', '\naa'],
<add>].forEach((i) => assert.strictEqual(stripShebang(i[0]), i[1])); | 1 |
Python | Python | raise an error if a pool doesn't exist | 9fe611498ccc837e18c227a4276c14905f007953 | <ide><path>airflow/models.py
<ide> def pool_full(self, session):
<ide> .first()
<ide> )
<ide> if not pool:
<del> return False
<add> raise ValueError('Task specified a pool ({}) but the pool '
<add> 'doesn\'t exist!').format(self.task.pool)
<ide> open_slots = pool.open_slots(session=session)
<ide>
<ide> return open_slots <= 0 | 1 |
Javascript | Javascript | remove manual adding of x-csrf-token header | aa74fcb38f9f318159657ba5050eda62ec043b11 | <ide><path>resources/js/bootstrap.js
<ide> window.axios = require('axios');
<ide>
<ide> window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
<ide>
<del>/**
<del> * Next we will register the CSRF Token as a common header with Axios so that
<del> * all outgoing HTTP requests automatically have it attached. This is just
<del> * a simple convenience so we don't have to attach every token manually.
<del> */
<del>
<del>let token = document.head.querySelector('meta[name="csrf-token"]');
<del>
<del>if (token) {
<del> window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
<del>} else {
<del> console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
<del>}
<del>
<ide> /**
<ide> * Echo exposes an expressive API for subscribing to channels and listening
<ide> * for events that are broadcast by Laravel. Echo and event broadcasting | 1 |
Go | Go | restore ref count | 009ee16beff4f6d3607fa251019908cc72ce0a34 | <ide><path>daemon/graphdriver/counter.go
<ide> package graphdriver
<ide>
<del>import "sync"
<add>import (
<add> "sync"
<add>
<add> "github.com/docker/docker/pkg/mount"
<add>)
<add>
<add>type minfo struct {
<add> check bool
<add> count int
<add>}
<ide>
<ide> // RefCounter is a generic counter for use by graphdriver Get/Put calls
<ide> type RefCounter struct {
<del> counts map[string]int
<add> counts map[string]*minfo
<ide> mu sync.Mutex
<ide> }
<ide>
<ide> // NewRefCounter returns a new RefCounter
<ide> func NewRefCounter() *RefCounter {
<del> return &RefCounter{counts: make(map[string]int)}
<add> return &RefCounter{counts: make(map[string]*minfo)}
<ide> }
<ide>
<ide> // Increment increaes the ref count for the given id and returns the current count
<del>func (c *RefCounter) Increment(id string) int {
<add>func (c *RefCounter) Increment(path string) int {
<ide> c.mu.Lock()
<del> c.counts[id]++
<del> count := c.counts[id]
<add> m := c.counts[path]
<add> if m == nil {
<add> m = &minfo{check: true}
<add> c.counts[path] = m
<add> }
<add> // if we are checking this path for the first time check to make sure
<add> // if it was already mounted on the system and make sure we have a correct ref
<add> // count if it is mounted as it is in use.
<add> if !m.check {
<add> m.check = true
<add> mntd, _ := mount.Mounted(path)
<add> if mntd {
<add> m.count++
<add> }
<add> }
<add> m.count++
<ide> c.mu.Unlock()
<del> return count
<add> return m.count
<ide> }
<ide>
<ide> // Decrement decreases the ref count for the given id and returns the current count
<del>func (c *RefCounter) Decrement(id string) int {
<add>func (c *RefCounter) Decrement(path string) int {
<ide> c.mu.Lock()
<del> c.counts[id]--
<del> count := c.counts[id]
<add> m := c.counts[path]
<add> if m == nil {
<add> m = &minfo{check: true}
<add> c.counts[path] = m
<add> }
<add> // if we are checking this path for the first time check to make sure
<add> // if it was already mounted on the system and make sure we have a correct ref
<add> // count if it is mounted as it is in use.
<add> if !m.check {
<add> m.check = true
<add> mntd, _ := mount.Mounted(path)
<add> if mntd {
<add> m.count++
<add> }
<add> }
<add> m.count--
<ide> c.mu.Unlock()
<del> return count
<add> return m.count
<ide> }
<ide><path>daemon/graphdriver/devmapper/driver.go
<ide> func (d *Driver) Remove(id string) error {
<ide> // Get mounts a device with given id into the root filesystem
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide> mp := path.Join(d.home, "mnt", id)
<del> if count := d.ctr.Increment(id); count > 1 {
<add> if count := d.ctr.Increment(mp); count > 1 {
<ide> return mp, nil
<ide> }
<ide>
<ide> uid, gid, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
<ide> if err != nil {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mp)
<ide> return "", err
<ide> }
<ide>
<ide> // Create the target directories if they don't exist
<ide> if err := idtools.MkdirAllAs(path.Join(d.home, "mnt"), 0755, uid, gid); err != nil && !os.IsExist(err) {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mp)
<ide> return "", err
<ide> }
<ide> if err := idtools.MkdirAs(mp, 0755, uid, gid); err != nil && !os.IsExist(err) {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mp)
<ide> return "", err
<ide> }
<ide>
<ide> // Mount the device
<ide> if err := d.DeviceSet.MountDevice(id, mp, mountLabel); err != nil {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mp)
<ide> return "", err
<ide> }
<ide>
<ide> rootFs := path.Join(mp, "rootfs")
<ide> if err := idtools.MkdirAllAs(rootFs, 0755, uid, gid); err != nil && !os.IsExist(err) {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mp)
<ide> d.DeviceSet.UnmountDevice(id, mp)
<ide> return "", err
<ide> }
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide> // Create an "id" file with the container/image id in it to help reconstruct this in case
<ide> // of later problems
<ide> if err := ioutil.WriteFile(idFile, []byte(id), 0600); err != nil {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mp)
<ide> d.DeviceSet.UnmountDevice(id, mp)
<ide> return "", err
<ide> }
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide>
<ide> // Put unmounts a device and removes it.
<ide> func (d *Driver) Put(id string) error {
<del> if count := d.ctr.Decrement(id); count > 0 {
<add> mp := path.Join(d.home, "mnt", id)
<add> if count := d.ctr.Decrement(mp); count > 0 {
<ide> return nil
<ide> }
<del> mp := path.Join(d.home, "mnt", id)
<ide> err := d.DeviceSet.UnmountDevice(id, mp)
<ide> if err != nil {
<ide> logrus.Errorf("devmapper: Error unmounting device %s: %s", id, err)
<ide><path>daemon/graphdriver/overlay/overlay.go
<ide> func (d *Driver) Get(id string, mountLabel string) (string, error) {
<ide> if _, err := os.Stat(dir); err != nil {
<ide> return "", err
<ide> }
<add> mergedDir := path.Join(dir, "merged")
<add> if count := d.ctr.Increment(mergedDir); count > 1 {
<add> return mergedDir, nil
<add> }
<ide>
<ide> // If id has a root, just return it
<ide> rootDir := path.Join(dir, "root")
<ide> func (d *Driver) Get(id string, mountLabel string) (string, error) {
<ide> lowerDir := path.Join(d.dir(string(lowerID)), "root")
<ide> upperDir := path.Join(dir, "upper")
<ide> workDir := path.Join(dir, "work")
<del> mergedDir := path.Join(dir, "merged")
<del>
<del> if count := d.ctr.Increment(id); count > 1 {
<del> return mergedDir, nil
<del> }
<ide>
<ide> opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir)
<ide>
<del> // if it's mounted already, just return
<del> mounted, err := d.mounted(mergedDir)
<del> if err != nil {
<del> d.ctr.Decrement(id)
<del> return "", err
<del> }
<del> if mounted {
<del> d.ctr.Decrement(id)
<del> return mergedDir, nil
<del> }
<del>
<ide> if err := syscall.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mergedDir)
<ide> return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err)
<ide> }
<ide> // chown "workdir/work" to the remapped root UID/GID. Overlay fs inside a
<ide> // user namespace requires this to move a directory from lower to upper.
<ide> rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
<ide> if err != nil {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mergedDir)
<ide> syscall.Unmount(mergedDir, 0)
<ide> return "", err
<ide> }
<ide>
<ide> if err := os.Chown(path.Join(workDir, "work"), rootUID, rootGID); err != nil {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mergedDir)
<ide> syscall.Unmount(mergedDir, 0)
<ide> return "", err
<ide> }
<ide> func (d *Driver) mounted(dir string) (bool, error) {
<ide>
<ide> // Put unmounts the mount path created for the give id.
<ide> func (d *Driver) Put(id string) error {
<del> if count := d.ctr.Decrement(id); count > 0 {
<del> return nil
<del> }
<ide> d.pathCacheLock.Lock()
<ide> mountpoint, exists := d.pathCache[id]
<ide> d.pathCacheLock.Unlock()
<ide>
<add> if count := d.ctr.Decrement(mountpoint); count > 0 {
<add> return nil
<add> }
<add>
<ide> if !exists {
<ide> logrus.Debugf("Put on a non-mounted device %s", id)
<ide> // but it might be still here
<ide><path>daemon/graphdriver/zfs/zfs.go
<ide> func (d *Driver) Remove(id string) error {
<ide> // Get returns the mountpoint for the given id after creating the target directories if necessary.
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide> mountpoint := d.mountPath(id)
<del> if count := d.ctr.Increment(id); count > 1 {
<add> if count := d.ctr.Increment(mountpoint); count > 1 {
<ide> return mountpoint, nil
<ide> }
<ide>
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide>
<ide> rootUID, rootGID, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
<ide> if err != nil {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mountpoint)
<ide> return "", err
<ide> }
<ide> // Create the target directories if they don't exist
<ide> if err := idtools.MkdirAllAs(mountpoint, 0755, rootUID, rootGID); err != nil {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mountpoint)
<ide> return "", err
<ide> }
<ide>
<ide> if err := mount.Mount(filesystem, mountpoint, "zfs", options); err != nil {
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mountpoint)
<ide> return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
<ide> }
<ide>
<ide> // this could be our first mount after creation of the filesystem, and the root dir may still have root
<ide> // permissions instead of the remapped root uid:gid (if user namespaces are enabled):
<ide> if err := os.Chown(mountpoint, rootUID, rootGID); err != nil {
<ide> mount.Unmount(mountpoint)
<del> d.ctr.Decrement(id)
<add> d.ctr.Decrement(mountpoint)
<ide> return "", fmt.Errorf("error modifying zfs mountpoint (%s) directory ownership: %v", mountpoint, err)
<ide> }
<ide>
<ide> func (d *Driver) Get(id, mountLabel string) (string, error) {
<ide>
<ide> // Put removes the existing mountpoint for the given id if it exists.
<ide> func (d *Driver) Put(id string) error {
<del> if count := d.ctr.Decrement(id); count > 0 {
<add> mountpoint := d.mountPath(id)
<add> if count := d.ctr.Decrement(mountpoint); count > 0 {
<ide> return nil
<ide> }
<del> mountpoint := d.mountPath(id)
<ide> mounted, err := graphdriver.Mounted(graphdriver.FsMagicZfs, mountpoint)
<ide> if err != nil || !mounted {
<ide> return err
<ide><path>libcontainerd/client_liverestore_linux.go
<del>// +build experimental
<del>
<ide> package libcontainerd
<ide>
<ide> import (
<ide><path>libcontainerd/client_shutdownrestore_linux.go
<del>// +build !experimental
<del>
<del>package libcontainerd
<del>
<del>import (
<del> "syscall"
<del> "time"
<del>
<del> "github.com/Sirupsen/logrus"
<del>)
<del>
<del>func (clnt *client) Restore(containerID string, options ...CreateOption) error {
<del> w := clnt.getOrCreateExitNotifier(containerID)
<del> defer w.close()
<del> cont, err := clnt.getContainerdContainer(containerID)
<del> if err == nil && cont.Status != "stopped" {
<del> clnt.lock(cont.Id)
<del> container := clnt.newContainer(cont.BundlePath)
<del> container.systemPid = systemPid(cont)
<del> clnt.appendContainer(container)
<del> clnt.unlock(cont.Id)
<del>
<del> if err := clnt.Signal(containerID, int(syscall.SIGTERM)); err != nil {
<del> logrus.Errorf("error sending sigterm to %v: %v", containerID, err)
<del> }
<del> select {
<del> case <-time.After(10 * time.Second):
<del> if err := clnt.Signal(containerID, int(syscall.SIGKILL)); err != nil {
<del> logrus.Errorf("error sending sigkill to %v: %v", containerID, err)
<del> }
<del> select {
<del> case <-time.After(2 * time.Second):
<del> case <-w.wait():
<del> return nil
<del> }
<del> case <-w.wait():
<del> return nil
<del> }
<del> }
<del> return clnt.setExited(containerID)
<del>} | 6 |
Javascript | Javascript | add test for `.removeat` | 5f5407c589fb5a6b00109e55900b681c3f251e96 | <ide><path>packages/ember-runtime/lib/mixins/mutable_array.js
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> ```javascript
<ide> let colors = ['red', 'green', 'blue', 'yellow', 'orange'];
<ide>
<del> removeAt(colors, 0); // ['green', 'blue', 'yellow', 'orange']
<del> removeAt(colors, 2, 2); // ['green', 'blue']
<del> removeAt(colors, 4, 2); // Error: Index out of range
<add> colors.removeAt(0); // ['green', 'blue', 'yellow', 'orange']
<add> colors.removeAt(2, 2); // ['green', 'blue']
<add> colors.removeAt(4, 2); // Error: Index out of range
<ide> ```
<ide>
<ide> @method removeAt
<ide><path>packages/ember-runtime/lib/system/array_proxy.js
<ide> const EMPTY = [];
<ide>
<ide> function K() { return this; }
<ide>
<del>export function removeAt(array, start, len) {
<del> if ('number' === typeof start) {
<del> let content = get(array, 'content');
<del> let arrangedContent = get(array, 'arrangedContent');
<del> let indices = [];
<del>
<del> if ((start < 0) || (start >= get(array, 'length'))) {
<del> throw new EmberError(OUT_OF_RANGE_EXCEPTION);
<del> }
<del>
<del> if (len === undefined) {
<del> len = 1;
<del> }
<del>
<del> // Get a list of indices in original content to remove
<del> for (let i = start; i < start + len; i++) {
<del> // Use arrangedContent here so we avoid confusion with objects transformed by objectAtContent
<del> indices.push(content.indexOf(objectAt(arrangedContent, i)));
<del> }
<del>
<del> // Replace in reverse order since indices will change
<del> indices.sort((a, b) => b - a);
<del>
<del> beginPropertyChanges();
<del> for (let i = 0; i < indices.length; i++) {
<del> array._replace(indices[i], 1, EMPTY);
<del> }
<del> endPropertyChanges();
<del> }
<del>
<del> return array;
<del>}
<ide>
<ide> /**
<ide> An ArrayProxy wraps any other object that implements `Ember.Array` and/or
<ide> export default EmberObject.extend(MutableArray, {
<ide> },
<ide>
<ide> removeAt(start, len) {
<del> return removeAt(this, start, len);
<add> if ('number' === typeof start) {
<add> let content = get(this, 'content');
<add> let arrangedContent = get(this, 'arrangedContent');
<add> let indices = [];
<add>
<add> if ((start < 0) || (start >= get(this, 'length'))) {
<add> throw new EmberError(OUT_OF_RANGE_EXCEPTION);
<add> }
<add>
<add> if (len === undefined) {
<add> len = 1;
<add> }
<add>
<add> // Get a list of indices in original content to remove
<add> for (let i = start; i < start + len; i++) {
<add> // Use arrangedContent here so we avoid confusion with objects transformed by objectAtContent
<add> indices.push(content.indexOf(objectAt(arrangedContent, i)));
<add> }
<add>
<add> // Replace in reverse order since indices will change
<add> indices.sort((a, b) => b - a);
<add>
<add> beginPropertyChanges();
<add> for (let i = 0; i < indices.length; i++) {
<add> this._replace(indices[i], 1, EMPTY);
<add> }
<add> endPropertyChanges();
<add> }
<add>
<add> return this;
<ide> },
<ide>
<ide> pushObject(obj) {
<ide><path>packages/ember-runtime/tests/suites/mutable_array/removeAt.js
<ide> suite.test('removeAt([X], 0) => [] + notify', function() {
<ide> equal(observer.timesCalled('lastObject'), 1, 'should have notified lastObject once');
<ide> });
<ide>
<del><<<<<<< f34dbabccfaa97c5d8989ce3ce4ec196e2450bbf
<ide> suite.test('removeAt([], 200) => OUT_OF_RANGE_EXCEPTION exception', function() {
<ide> let obj = this.newObject([]);
<ide> throws(() => removeAt(obj, 200), Error);
<ide> suite.test('removeAt([A,B,C,D], 1,2) => [A,D] + notify', function() {
<ide> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<ide> });
<ide>
<add>suite.test('[A,B,C,D].removeAt(1,2) => [A,D] + notify', function() {
<add> var obj, before, after, observer;
<add>
<add> before = this.newFixture(4);
<add> after = [before[0], before[3]];
<add> obj = this.newObject(before);
<add> observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
<add> obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
<add>
<add> equal(obj.removeAt(1, 2), obj, 'return self');
<add>
<add> deepEqual(this.toArray(obj), after, 'post item results');
<add> equal(get(obj, 'length'), after.length, 'length');
<add>
<add> equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
<add> equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
<add> equal(observer.timesCalled('length'), 1, 'should have notified length once');
<add>
<add> equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
<add> equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
<add>});
<add>
<ide> export default suite;
<ide><path>packages/ember-runtime/tests/system/array_proxy/arranged_content_test.js
<ide> import run from 'ember-metal/run_loop';
<ide> import { computed } from 'ember-metal/computed';
<del>import ArrayProxy, { removeAt } from 'ember-runtime/system/array_proxy';
<add>import ArrayProxy from 'ember-runtime/system/array_proxy';
<ide> import { A as emberA } from 'ember-runtime/system/native_array';
<ide> import { objectAt } from 'ember-runtime/mixins/array';
<ide>
<ide> QUnit.test('pushObjects - adds multiple to end of content even if it already exi
<ide> });
<ide>
<ide> QUnit.test('removeAt - removes from index in arrangedContent', function() {
<del> run(() => removeAt(array, 1, 2));
<add> run(() => array.removeAt(1, 2));
<ide> deepEqual(array.get('content'), [1, 5]);
<ide> });
<ide> | 4 |
Javascript | Javascript | remove extra change | 4e643be0d78f2f6b010d71fd1583c5e4a0f92258 | <ide><path>lib/dependencies/WorkerPlugin.js
<ide> class WorkerPlugin {
<ide> } else {
<ide> Object.assign(
<ide> entryOptions,
<del> JSON.parse(
<del> JSON.stringify(importOptions.webpackEntryOptions)
<del> )
<add> importOptions.webpackEntryOptions
<ide> );
<ide> }
<ide> } | 1 |
Javascript | Javascript | inline encode function | cf3f7be8d194d4e1ffb01c80ade2720c03b7e9e9 | <ide><path>lib/asset/AssetGenerator.js
<ide> const prepareOptions = (options = {}) => {
<ide> };
<ide> };
<ide>
<del>/**
<del> * @param {NormalModule} module a module to encode
<del> * @param {AssetModulesPluginOptions} options the options to the encoder
<del> * @returns {string|null} encoded source
<del> */
<del>const encode = (module, options) => {
<del> if (shouldEmitAsset(module, options)) {
<del> return null;
<del> }
<del>
<del> const originalSource = module.originalSource();
<del> let content = originalSource.source();
<del>
<del> if (typeof options.dataUrl === "function") {
<del> return options.dataUrl.call(null, content, module.nameForCondition());
<del> }
<del>
<del> // @ts-ignore non-false dataUrl ensures in shouldEmitAsset above
<del> const encoding = options.dataUrl.encoding;
<del> const extname = path.extname(module.nameForCondition());
<del> // @ts-ignore non-false dataUrl ensures in shouldEmitAsset above
<del> const mimeType = options.dataUrl.mimetype || mime.getType(extname);
<del>
<del> if (encoding === "base64") {
<del> if (typeof content === "string") {
<del> content = Buffer.from(content);
<del> }
<del>
<del> content = content.toString("base64");
<del> }
<del>
<del> return `data:${mimeType}${encoding ? `;${encoding}` : ""},${content}`;
<del>};
<del>
<ide> const JS_TYPES = new Set(["javascript"]);
<ide> const JS_AND_ASSET_TYPES = new Set(["javascript", "asset"]);
<ide>
<ide> class AssetGenerator extends Generator {
<ide> runtimeRequirements.add(RuntimeGlobals.module);
<ide>
<ide> if (!shouldEmitAsset(module, this.options)) {
<del> const encodedSource = encode(module, this.options);
<add> const originalSource = module.originalSource();
<add> let content = originalSource.source();
<add>
<add> let encodedSource;
<add> if (typeof this.options.dataUrl === "function") {
<add> encodedSource = this.options.dataUrl.call(
<add> null,
<add> content,
<add> module.nameForCondition()
<add> );
<add> } else {
<add> // @ts-ignore non-false dataUrl ensures in shouldEmitAsset above
<add> const encoding = this.options.dataUrl.encoding;
<add> const extname = path.extname(module.nameForCondition());
<add> // @ts-ignore non-false dataUrl ensures in shouldEmitAsset above
<add> const mimeType = this.options.dataUrl.mimetype || mime.getType(extname);
<add>
<add> if (encoding === "base64") {
<add> if (typeof content === "string") {
<add> content = Buffer.from(content);
<add> }
<add>
<add> content = content.toString("base64");
<add> }
<add>
<add> encodedSource = `data:${mimeType}${
<add> encoding ? `;${encoding}` : ""
<add> },${content}`;
<add> }
<ide> return new RawSource(
<ide> `${RuntimeGlobals.module}.exports = ${JSON.stringify(encodedSource)};`
<ide> ); | 1 |
Ruby | Ruby | remove unused 'usage' method | c6536066dc39da653d265640c6ba6046bb5def98 | <ide><path>Library/Homebrew/cmd/help.rb
<ide> def help(cmd = nil, empty_argv = false)
<ide> exit 0
<ide> end
<ide>
<del> def help_s
<del> HOMEBREW_HELP
<del> end
<del>
<ide> private
<ide>
<ide> def help_for_command(cmd)
<ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def switch?(char)
<ide> options_only.any? { |arg| arg.scan("-").size == 1 && arg.include?(char) }
<ide> end
<ide>
<del> def usage
<del> require "cmd/help"
<del> Homebrew.help_s
<del> end
<del>
<ide> def cc
<ide> value "cc"
<ide> end | 2 |
Javascript | Javascript | address timing issues in simple http tests | 67987d9d83517e8d812f13dc5e9eca1d1b9d21ac | <ide><path>test/parallel/test-http-default-encoding.js
<ide> var server = http.Server(function(req, res) {
<ide> req.on('data', function(chunk) {
<ide> result += chunk;
<ide> }).on('end', function() {
<del> clearTimeout(timeout);
<ide> server.close();
<add> res.writeHead(200);
<add> res.end('hello world\n');
<ide> });
<ide>
<del> var timeout = setTimeout(function() {
<del> process.exit(1);
<del> }, 100);
<del>
<del> res.writeHead(200);
<del> res.end('hello world\n');
<ide> });
<ide>
<ide> server.listen(common.PORT, function() {
<ide><path>test/parallel/test-http-request-end.js
<ide> var server = http.Server(function(req, res) {
<ide>
<ide> req.on('end', function() {
<ide> server.close();
<add> res.writeHead(200);
<add> res.end('hello world\n');
<ide> });
<ide>
<del> res.writeHead(200);
<del> res.end('hello world\n');
<ide> });
<ide>
<ide> server.listen(common.PORT, function() { | 2 |
Java | Java | restore serializability of httpstatuscodeexception | 2ff43726be693f32b7bf2a6d237ab65f8ce84ba6 | <ide><path>spring-web/src/main/java/org/springframework/web/client/HttpClientErrorException.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2012 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> */
<ide> public class HttpClientErrorException extends HttpStatusCodeException {
<ide>
<add> private static final long serialVersionUID = 6777393766937023392L;
<add>
<ide> /**
<ide> * Construct a new instance of {@code HttpClientErrorException} based on a {@link HttpStatus}.
<ide> * @param statusCode the status code
<ide><path>spring-web/src/main/java/org/springframework/web/client/HttpServerErrorException.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2012 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> */
<ide> public class HttpServerErrorException extends HttpStatusCodeException {
<ide>
<add> private static final long serialVersionUID = -2565832100451369997L;
<add>
<ide> /**
<ide> * Construct a new instance of {@code HttpServerErrorException} based on a {@link HttpStatus}.
<ide> *
<ide><path>spring-web/src/main/java/org/springframework/web/client/HttpStatusCodeException.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2012 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> * Abstract base class for exceptions based on an {@link HttpStatus}.
<ide> *
<ide> * @author Arjen Poutsma
<add> * @author Chris Beams
<ide> * @since 3.0
<ide> */
<ide> public abstract class HttpStatusCodeException extends RestClientException {
<ide>
<del> private static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
<add> private static final long serialVersionUID = 1549626836533638803L;
<add>
<add> private static final String DEFAULT_CHARSET = "ISO-8859-1";
<ide>
<ide> private final HttpStatus statusCode;
<ide>
<ide> private final String statusText;
<ide>
<ide> private final byte[] responseBody;
<ide>
<del> private final Charset responseCharset;
<add> private final String responseCharset;
<ide>
<ide> /**
<ide> * Construct a new instance of {@code HttpStatusCodeException} based on a {@link HttpStatus}.
<ide> protected HttpStatusCodeException(HttpStatus statusCode,
<ide> this.statusCode = statusCode;
<ide> this.statusText = statusText;
<ide> this.responseBody = responseBody != null ? responseBody : new byte[0];
<del> this.responseCharset = responseCharset != null ? responseCharset : DEFAULT_CHARSET;
<add> this.responseCharset = responseCharset != null ? responseCharset.name() : DEFAULT_CHARSET;
<ide> }
<ide>
<ide> /**
<ide> public byte[] getResponseBodyAsByteArray() {
<ide> */
<ide> public String getResponseBodyAsString() {
<ide> try {
<del> return new String(responseBody, responseCharset.name());
<add> return new String(responseBody, responseCharset);
<ide> }
<ide> catch (UnsupportedEncodingException ex) {
<ide> // should not occur
<ide><path>spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java
<add>/*
<add> * Copyright 2002-2012 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.client;
<add>
<add>import java.io.ByteArrayInputStream;
<add>import java.io.ByteArrayOutputStream;
<add>import java.io.IOException;
<add>import java.io.ObjectInputStream;
<add>import java.io.ObjectOutputStream;
<add>import java.nio.charset.Charset;
<add>
<add>import org.junit.Test;
<add>import org.springframework.http.HttpStatus;
<add>
<add>import static org.hamcrest.CoreMatchers.*;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Unit tests for {@link HttpStatusCodeException} and subclasses.
<add> *
<add> * @author Chris Beams
<add> */
<add>public class HttpStatusCodeExceptionTests {
<add>
<add> /**
<add> * Corners bug SPR-9273, which reported the fact that following the changes made in
<add> * SPR-7591, {@link HttpStatusCodeException} and subtypes became no longer
<add> * serializable due to the addition of a non-serializable {@link Charset} field.
<add> */
<add> @Test
<add> public void testSerializability() throws IOException, ClassNotFoundException {
<add> HttpStatusCodeException ex1 = new HttpClientErrorException(
<add> HttpStatus.BAD_REQUEST, null, null, Charset.forName("US-ASCII"));
<add> ByteArrayOutputStream out = new ByteArrayOutputStream();
<add> new ObjectOutputStream(out).writeObject(ex1);
<add> ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
<add> HttpStatusCodeException ex2 =
<add> (HttpStatusCodeException) new ObjectInputStream(in).readObject();
<add> assertThat(ex2.getResponseBodyAsString(), equalTo(ex1.getResponseBodyAsString()));
<add> }
<add>
<add>} | 4 |
PHP | PHP | add api docs for accessiblefields option | 2f12dbbd6d9ab07f78a5aa6278838a55afaed469 | <ide><path>src/ORM/Table.php
<ide> public function entityValidator() {
<ide> * using the options parameter:
<ide> *
<ide> * {{{
<del> * $articles = $this->Articles->newEntity(
<add> * $article = $this->Articles->newEntity(
<ide> * $this->request->data(),
<ide> * ['associated' => ['Tags', 'Comments.Users']]
<ide> * );
<ide> public function entityValidator() {
<ide> * passing the `fieldList` option, which is also accepted for associations:
<ide> *
<ide> * {{{
<del> * $articles = $this->Articles->newEntity($this->request->data(), [
<del> * 'fieldList' => ['title', 'body'],
<del> * 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']]
<del> * ]
<add> * $article = $this->Articles->newEntity($this->request->data(), [
<add> * 'fieldList' => ['title', 'body'],
<add> * 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']]
<add> * ]
<ide> * );
<ide> * }}}
<ide> *
<add> * The `fieldList` option lets remove or restrict input data from ending up in
<add> * the entity. If you'd like to relax the entity's default accessible fields,
<add> * you can use the `accessibleFields` option:
<add> *
<add> * {{{
<add> * $article = $this->Articles->newEntity(
<add> * $this->request->data(),
<add> * ['accessibleFields' => ['protected_field' => true]]
<add> * );
<add> * }}}
<ide> */
<ide> public function newEntity(array $data = [], array $options = []) {
<ide> if (!isset($options['associated'])) { | 1 |
Text | Text | add note to upgrade log | 42780b4b91ab30f5f8e9be71feb2cf32412c93fc | <ide><path>upgrade.md
<ide> - Edit `app/controllers/BaseController.php` change `use Illuminate\Routing\Controllers\Controller;` to `use Illuminate\Routing\Controller;
<ide> `
<ide> - If you are overriding `missingMethod` in your controllers, add $method as the first parameter.
<add>- If you are registering model observers in a "start" file, move them to the `App::booted` handler. | 1 |
Text | Text | add `stability` class to legacy status description | eb3ca87a87283c5d7968f980ac3b126ac0c0495e | <ide><path>doc/api/documentation.md
<ide> The stability indices are as follows:
<ide>
<ide> <!-- separator -->
<ide>
<del>> Stability 3 - Legacy. Although this feature is unlikely to be removed and is
<add>> Stability: 3 - Legacy. Although this feature is unlikely to be removed and is
<ide> > still covered by semantic versioning guarantees, it is no longer actively
<ide> > maintained, and other alternatives are available.
<ide> | 1 |
PHP | PHP | add test for assertredirectequals | 6024d57c46d7b44ae94a65ebc506d658a22bb2e8 | <ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php
<ide> public function testAssertRedirect()
<ide> $this->assertResponseEmpty();
<ide> }
<ide>
<add> /**
<add> * Test the location header assertion.
<add> *
<add> * @return void
<add> */
<add> public function testAssertRedirectEquals()
<add> {
<add> $this->_response = new Response();
<add> $this->_response = $this->_response->withHeader('Location', '/get/tasks/index');
<add>
<add> $this->assertRedirect();
<add> $this->assertRedirectEquals('/get/tasks/index');
<add> $this->assertRedirectEquals(['controller' => 'Tasks', 'action' => 'index']);
<add>
<add> $this->assertResponseEmpty();
<add> }
<add>
<ide> /**
<ide> * Test the location header assertion string not contains
<ide> * | 1 |
PHP | PHP | fix failing tests with sqlserver | d69c3f3db661c12e5d0aa6867bd89dee2ef8940e | <ide><path>lib/Cake/Utility/Sanitize.php
<ide> public static function escape($string, $connection = 'default') {
<ide> if (is_numeric($string) || $string === null || is_bool($string)) {
<ide> return $string;
<ide> }
<del> $string = substr($db->value($string), 1);
<add> $string = $db->value($string, 'string');
<add> if ($string[0] === 'N') {
<add> $string = substr($string, 2);
<add> }
<ide> $string = substr($string, 0, -1);
<ide> return $string;
<ide> } | 1 |
Python | Python | add shape inference to graph containers | e8e56d9013da401fc6260a6f7675c70ce03fba28 | <ide><path>examples/kaggle_otto_nn.py
<ide> def make_submission(y_prob, ids, encoder, fname):
<ide> model = Sequential()
<ide> model.add(Dense(512, input_shape=(dims,)))
<ide> model.add(PReLU())
<del>model.add(BatchNormalization((512,)))
<add>model.add(BatchNormalization())
<ide> model.add(Dropout(0.5))
<ide>
<ide> model.add(Dense(512))
<ide><path>keras/layers/containers.py
<ide> def get_output(self, train=False):
<ide> else:
<ide> return dict([(k, v.get_output(train)) for k, v in self.outputs.items()])
<ide>
<del> def add_input(self, name, ndim=2, dtype='float'):
<add> def add_input(self, name, input_shape, dtype='float'):
<ide> if name in self.namespace:
<ide> raise Exception('Duplicate node identifier: ' + name)
<ide> self.namespace.add(name)
<ide> self.input_order.append(name)
<ide> layer = Layer() # empty layer
<add> layer.set_input_shape(input_shape)
<add> ndim = len(input_shape) + 1
<ide> if dtype == 'float':
<ide> layer.input = ndim_tensor(ndim)
<ide> else:
<ide> def add_input(self, name, ndim=2, dtype='float'):
<ide> raise Exception('Type "int" can only be used with ndim==2 (Embedding).')
<ide> layer.input.name = name
<ide> self.inputs[name] = layer
<del> self.input_config.append({'name': name, 'ndim': ndim, 'dtype': dtype})
<add> self.input_config.append({'name': name,
<add> 'input_shape': input_shape,
<add> 'dtype': dtype})
<ide>
<ide> def add_node(self, layer, name, input=None, inputs=[],
<ide> merge_mode='concat', concat_axis=-1, create_output=False):
<ide><path>tests/auto/test_graph_model.py
<ide> class TestGraph(unittest.TestCase):
<ide> def test_1o_1i(self):
<ide> print('test a non-sequential graph with 1 input and 1 output')
<ide> graph = Graph()
<del> graph.add_input(name='input1', ndim=2)
<add> graph.add_input(name='input1', input_shape=(32,))
<ide>
<del> graph.add_node(Dense(16, input_shape=(32,)), name='dense1', input='input1')
<add> graph.add_node(Dense(16), name='dense1', input='input1')
<ide> graph.add_node(Dense(4), name='dense2', input='input1')
<ide> graph.add_node(Dense(4), name='dense3', input='dense1')
<ide>
<ide> def test_1o_1i(self):
<ide> def test_1o_1i_2(self):
<ide> print('test a more complex non-sequential graph with 1 input and 1 output')
<ide> graph = Graph()
<del> graph.add_input(name='input1', ndim=2)
<add> graph.add_input(name='input1', input_shape=(32,))
<ide>
<del> graph.add_node(Dense(16, input_shape=(32,)), name='dense1', input='input1')
<add> graph.add_node(Dense(16), name='dense1', input='input1')
<ide> graph.add_node(Dense(4), name='dense2-0', input='input1')
<ide> graph.add_node(Activation('relu'), name='dense2', input='dense2-0')
<ide>
<ide> def test_1o_1i_2(self):
<ide> def test_1o_2i(self):
<ide> print('test a non-sequential graph with 2 inputs and 1 output')
<ide> graph = Graph()
<del> graph.add_input(name='input1', ndim=2)
<del> graph.add_input(name='input2', ndim=2)
<add> graph.add_input(name='input1', input_shape=(32,))
<add> graph.add_input(name='input2', input_shape=(32,))
<ide>
<del> graph.add_node(Dense(16, input_shape=(32,)), name='dense1', input='input1')
<add> graph.add_node(Dense(16), name='dense1', input='input1')
<ide> graph.add_node(Dense(4), name='dense2', input='input2')
<ide> graph.add_node(Dense(4), name='dense3', input='dense1')
<ide>
<ide> def test_1o_2i(self):
<ide> def test_2o_1i_weights(self):
<ide> print('test a non-sequential graph with 1 input and 2 outputs')
<ide> graph = Graph()
<del> graph.add_input(name='input1', ndim=2)
<add> graph.add_input(name='input1', input_shape=(32,))
<ide>
<del> graph.add_node(Dense(16, input_shape=(32,)), name='dense1', input='input1')
<add> graph.add_node(Dense(16), name='dense1', input='input1')
<ide> graph.add_node(Dense(4), name='dense2', input='input1')
<ide> graph.add_node(Dense(1), name='dense3', input='dense1')
<ide>
<ide> def test_2o_1i_weights(self):
<ide> print('test weight saving')
<ide> graph.save_weights('temp.h5', overwrite=True)
<ide> graph = Graph()
<del> graph.add_input(name='input1', ndim=2)
<del> graph.add_node(Dense(16, input_shape=(32,)), name='dense1', input='input1')
<add> graph.add_input(name='input1', input_shape=(32,))
<add> graph.add_node(Dense(16), name='dense1', input='input1')
<ide> graph.add_node(Dense(4), name='dense2', input='input1')
<ide> graph.add_node(Dense(1), name='dense3', input='dense1')
<ide> graph.add_output(name='output1', input='dense2')
<ide> def test_2o_1i_weights(self):
<ide> def test_2o_1i_sample_weights(self):
<ide> print('test a non-sequential graph with 1 input and 2 outputs with sample weights')
<ide> graph = Graph()
<del> graph.add_input(name='input1', ndim=2)
<add> graph.add_input(name='input1', input_shape=(32,))
<ide>
<del> graph.add_node(Dense(16, input_shape=(32,)), name='dense1', input='input1')
<add> graph.add_node(Dense(16), name='dense1', input='input1')
<ide> graph.add_node(Dense(4), name='dense2', input='input1')
<ide> graph.add_node(Dense(1), name='dense3', input='dense1')
<ide>
<ide> def test_recursive(self):
<ide> print('test layer-like API')
<ide>
<ide> graph = containers.Graph()
<del> graph.add_input(name='input1', ndim=2)
<del> graph.add_node(Dense(16, input_shape=(32,)), name='dense1', input='input1')
<add> graph.add_input(name='input1', input_shape=(32,))
<add> graph.add_node(Dense(16), name='dense1', input='input1')
<ide> graph.add_node(Dense(4), name='dense2', input='input1')
<ide> graph.add_node(Dense(4), name='dense3', input='dense1')
<ide> graph.add_output(name='output1', inputs=['dense2', 'dense3'], merge_mode='sum')
<ide> def test_recursive(self):
<ide> def test_create_output(self):
<ide> print('test create_output argument')
<ide> graph = Graph()
<del> graph.add_input(name='input1', ndim=2)
<add> graph.add_input(name='input1', input_shape=(32,))
<ide>
<del> graph.add_node(Dense(16, input_shape=(32,)), name='dense1', input='input1')
<add> graph.add_node(Dense(16), name='dense1', input='input1')
<ide> graph.add_node(Dense(4), name='dense2', input='input1')
<ide> graph.add_node(Dense(4), name='dense3', input='dense1')
<ide> graph.add_node(Dense(4), name='output1', inputs=['dense2', 'dense3'], merge_mode='sum', create_output=True)
<ide> def test_count_params(self):
<ide> nb_classes = 2
<ide>
<ide> graph = Graph()
<del> graph.add_input(name='input1', ndim=2)
<del> graph.add_input(name='input2', ndim=2)
<del> graph.add_node(Dense(nb_units, input_shape=(nb_units,)),
<add> graph.add_input(name='input1', input_shape=(32,))
<add> graph.add_input(name='input2', input_shape=(32,))
<add> graph.add_node(Dense(nb_units),
<ide> name='dense1', input='input1')
<del> graph.add_node(Dense(nb_classes, input_shape=(nb_units,)),
<add> graph.add_node(Dense(nb_classes),
<ide> name='dense2', input='input2')
<ide> graph.add_node(Dense(nb_classes),
<ide> name='dense3', input='dense1')
<ide> graph.add_output(name='output', inputs=['dense2', 'dense3'],
<ide> merge_mode='sum')
<ide>
<del> n = nb_units * nb_units + nb_units
<del> n += nb_units * nb_classes + nb_classes
<add> n = 32 * nb_units + nb_units
<add> n += 32 * nb_classes + nb_classes
<ide> n += nb_units * nb_classes + nb_classes
<ide>
<ide> self.assertEqual(n, graph.count_params())
<ide><path>tests/auto/test_loss_weighting.py
<ide> def create_sequential_model():
<ide>
<ide> def create_graph_model():
<ide> model = Graph()
<del> model.add_input(name='input')
<del> model.add_node(Dense(50, activation='relu', input_shape=(784,)), name='d1', input='input')
<add> model.add_input(name='input', input_shape=(784,))
<add> model.add_node(Dense(50, activation='relu'), name='d1', input='input')
<ide> model.add_node(Dense(10, activation='softmax'), name='d2', input='d1')
<ide> model.add_output(name='output', input='d2')
<ide> return model | 4 |
Ruby | Ruby | remove custom minimum version | 8b9ac2b2e030a70bd6ee99ac8b0c9b9f92fd621b | <ide><path>Library/Homebrew/os/mac/xquartz.rb
<ide> def detect_version
<ide> end
<ide> end
<ide>
<add> def minimum_version
<add> version = guess_system_version
<add> return version unless version == "dunno"
<add>
<add> # Update this a little later than latest_version to give people
<add> # time to upgrade.
<add> "2.7.11"
<add> end
<add>
<ide> # https://xquartz.macosforge.org/trac/wiki
<ide> # https://xquartz.macosforge.org/trac/wiki/Releases
<ide> def latest_version
<ide><path>Library/Homebrew/requirements/x11_requirement.rb
<ide>
<ide> class X11Requirement < Requirement
<ide> include Comparable
<del> attr_reader :min_version
<ide>
<ide> fatal true
<ide> cask "xquartz"
<ide> class X11Requirement < Requirement
<ide>
<ide> def initialize(name = "x11", tags = [])
<ide> @name = name
<del> if /(\d\.)+\d/ =~ tags.first
<del> @min_version = Version.create(tags.shift)
<del> @min_version_string = " #{@min_version}"
<del> else
<del> @min_version = Version.create("0.0.0")
<del> @min_version_string = ""
<del> end
<add> # no-op on version specified as a tag argument
<add> tags.shift if /(\d\.)+\d/ =~ tags.first
<ide> super(tags)
<ide> end
<ide>
<add> def min_version
<add> # TODO: remove in https://github.com/Homebrew/brew/pull/3483
<add> return Version::NULL unless OS.mac?
<add>
<add> MacOS::XQuartz.minimum_version
<add> end
<add>
<ide> satisfy build_env: false do
<del> MacOS::XQuartz.installed? && min_version <= Version.create(MacOS::XQuartz.version)
<add> # TODO: remove in https://github.com/Homebrew/brew/pull/3483
<add> next false unless OS.mac?
<add>
<add> next false unless MacOS::XQuartz.installed?
<add> min_version <= MacOS::XQuartz.version
<ide> end
<ide>
<ide> def message
<del> s = "XQuartz#{@min_version_string} is required to install this formula."
<add> s = "XQuartz #{min_version} (or newer) is required to install this formula."
<ide> s += super
<ide> s
<ide> end
<ide>
<ide> def <=>(other)
<ide> return unless other.is_a? X11Requirement
<del> min_version <=> other.min_version
<del> end
<del>
<del> def eql?(other)
<del> super && min_version == other.min_version
<add> 0
<ide> end
<ide>
<ide> def inspect
<del> "#<#{self.class.name}: #{name.inspect} #{tags.inspect} min_version=#{min_version}>"
<add> "#<#{self.class.name}: #{name.inspect} #{tags.inspect}>"
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/dependency_collector_spec.rb
<ide> def find_requirement(klass)
<ide> expect(find_requirement(X11Requirement).tags).to be_empty
<ide> end
<ide>
<del> specify "x11 with minimum version" do
<add> specify "x11 with (ignored) minimum version" do
<ide> subject.add x11: "2.5.1"
<del> expect(find_requirement(X11Requirement).min_version.to_s).to eq("2.5.1")
<add> expect(find_requirement(X11Requirement).min_version.to_s).to_not eq("2.5.1")
<ide> end
<ide>
<ide> specify "x11 with tag" do
<ide> subject.add x11: :optional
<ide> expect(find_requirement(X11Requirement)).to be_optional
<ide> end
<ide>
<del> specify "x11 with minimum version and tag" do
<add> specify "x11 with (ignored) minimum version and tag" do
<ide> subject.add x11: ["2.5.1", :optional]
<ide> dep = find_requirement(X11Requirement)
<del> expect(dep.min_version.to_s).to eq("2.5.1")
<add> expect(dep.min_version.to_s).to_not eq("2.5.1")
<ide> expect(dep).to be_optional
<ide> end
<ide>
<ide><path>Library/Homebrew/test/x11_requirement_spec.rb
<ide> other = described_class.new("foo")
<ide> expect(subject).not_to eql(other)
<ide> end
<del>
<del> it "returns false if the minimum version differs" do
<del> other = described_class.new(default_name, ["2.5"])
<del> expect(subject).not_to eql(other)
<del> end
<ide> end
<ide>
<ide> describe "#modify_build_environment" do | 4 |
Python | Python | prepare optimizer only when args.do_train is true | 74dbba64bc9a44cd6757413b720d0ff4ca33137a | <ide><path>examples/lm_finetuning/simple_lm_finetuning.py
<ide> def main():
<ide> model = torch.nn.DataParallel(model)
<ide>
<ide> # Prepare optimizer
<del> param_optimizer = list(model.named_parameters())
<del> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<del> optimizer_grouped_parameters = [
<del> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<del> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<del> ]
<del>
<del> if args.fp16:
<del> try:
<del> from apex.optimizers import FP16_Optimizer
<del> from apex.optimizers import FusedAdam
<del> except ImportError:
<del> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
<add> if args.do_train:
<add> param_optimizer = list(model.named_parameters())
<add> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<add> optimizer_grouped_parameters = [
<add> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<add> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<add> ]
<add>
<add> if args.fp16:
<add> try:
<add> from apex.optimizers import FP16_Optimizer
<add> from apex.optimizers import FusedAdam
<add> except ImportError:
<add> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
<add>
<add> optimizer = FusedAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> bias_correction=False,
<add> max_grad_norm=1.0)
<add> if args.loss_scale == 0:
<add> optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
<add> else:
<add> optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
<add> warmup_linear = WarmupLinearSchedule(warmup=args.warmup_proportion,
<add> t_total=num_train_optimization_steps)
<ide>
<del> optimizer = FusedAdam(optimizer_grouped_parameters,
<del> lr=args.learning_rate,
<del> bias_correction=False,
<del> max_grad_norm=1.0)
<del> if args.loss_scale == 0:
<del> optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
<ide> else:
<del> optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
<del> warmup_linear = WarmupLinearSchedule(warmup=args.warmup_proportion,
<del> t_total=num_train_optimization_steps)
<del>
<del> else:
<del> optimizer = BertAdam(optimizer_grouped_parameters,
<del> lr=args.learning_rate,
<del> warmup=args.warmup_proportion,
<del> t_total=num_train_optimization_steps)
<add> optimizer = BertAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> warmup=args.warmup_proportion,
<add> t_total=num_train_optimization_steps)
<ide>
<ide> global_step = 0
<ide> if args.do_train:
<ide><path>examples/run_classifier.py
<ide> def main():
<ide> model = torch.nn.DataParallel(model)
<ide>
<ide> # Prepare optimizer
<del> param_optimizer = list(model.named_parameters())
<del> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<del> optimizer_grouped_parameters = [
<del> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<del> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<del> ]
<del> if args.fp16:
<del> try:
<del> from apex.optimizers import FP16_Optimizer
<del> from apex.optimizers import FusedAdam
<del> except ImportError:
<del> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
<add> if args.do_train:
<add> param_optimizer = list(model.named_parameters())
<add> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<add> optimizer_grouped_parameters = [
<add> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<add> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<add> ]
<add> if args.fp16:
<add> try:
<add> from apex.optimizers import FP16_Optimizer
<add> from apex.optimizers import FusedAdam
<add> except ImportError:
<add> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
<add>
<add> optimizer = FusedAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> bias_correction=False,
<add> max_grad_norm=1.0)
<add> if args.loss_scale == 0:
<add> optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
<add> else:
<add> optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
<add> warmup_linear = WarmupLinearSchedule(warmup=args.warmup_proportion,
<add> t_total=num_train_optimization_steps)
<ide>
<del> optimizer = FusedAdam(optimizer_grouped_parameters,
<del> lr=args.learning_rate,
<del> bias_correction=False,
<del> max_grad_norm=1.0)
<del> if args.loss_scale == 0:
<del> optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
<ide> else:
<del> optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
<del> warmup_linear = WarmupLinearSchedule(warmup=args.warmup_proportion,
<del> t_total=num_train_optimization_steps)
<del>
<del> else:
<del> optimizer = BertAdam(optimizer_grouped_parameters,
<del> lr=args.learning_rate,
<del> warmup=args.warmup_proportion,
<del> t_total=num_train_optimization_steps)
<add> optimizer = BertAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> warmup=args.warmup_proportion,
<add> t_total=num_train_optimization_steps)
<ide>
<ide> global_step = 0
<ide> nb_tr_steps = 0
<ide><path>examples/run_openai_gpt.py
<ide> def tokenize_and_encode(obj):
<ide> eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)
<ide>
<ide> # Prepare optimizer
<del> param_optimizer = list(model.named_parameters())
<del> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<del> optimizer_grouped_parameters = [
<del> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<del> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<del> ]
<del> num_train_optimization_steps = len(train_data) * args.num_train_epochs // args.train_batch_size
<del> optimizer = OpenAIAdam(optimizer_grouped_parameters,
<del> lr=args.learning_rate,
<del> warmup=args.warmup_proportion,
<del> max_grad_norm=args.max_grad_norm,
<del> weight_decay=args.weight_decay,
<del> t_total=num_train_optimization_steps)
<add> if args.do_train:
<add> param_optimizer = list(model.named_parameters())
<add> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<add> optimizer_grouped_parameters = [
<add> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<add> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<add> ]
<add> num_train_optimization_steps = len(train_data) * args.num_train_epochs // args.train_batch_size
<add> optimizer = OpenAIAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> warmup=args.warmup_proportion,
<add> max_grad_norm=args.max_grad_norm,
<add> weight_decay=args.weight_decay,
<add> t_total=num_train_optimization_steps)
<ide>
<ide> if args.do_train:
<ide> nb_tr_steps, tr_loss, exp_average_loss = 0, 0, None
<ide><path>examples/run_squad.py
<ide> def main():
<ide> model = torch.nn.DataParallel(model)
<ide>
<ide> # Prepare optimizer
<del> param_optimizer = list(model.named_parameters())
<del>
<del> # hack to remove pooler, which is not used
<del> # thus it produce None grad that break apex
<del> param_optimizer = [n for n in param_optimizer if 'pooler' not in n[0]]
<del>
<del> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<del> optimizer_grouped_parameters = [
<del> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<del> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<del> ]
<del>
<del> if args.fp16:
<del> try:
<del> from apex.optimizers import FP16_Optimizer
<del> from apex.optimizers import FusedAdam
<del> except ImportError:
<del> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
<del>
<del> optimizer = FusedAdam(optimizer_grouped_parameters,
<del> lr=args.learning_rate,
<del> bias_correction=False,
<del> max_grad_norm=1.0)
<del> if args.loss_scale == 0:
<del> optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
<add> if args.do_train:
<add> param_optimizer = list(model.named_parameters())
<add>
<add> # hack to remove pooler, which is not used
<add> # thus it produce None grad that break apex
<add> param_optimizer = [n for n in param_optimizer if 'pooler' not in n[0]]
<add>
<add> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<add> optimizer_grouped_parameters = [
<add> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<add> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<add> ]
<add>
<add> if args.fp16:
<add> try:
<add> from apex.optimizers import FP16_Optimizer
<add> from apex.optimizers import FusedAdam
<add> except ImportError:
<add> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
<add>
<add> optimizer = FusedAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> bias_correction=False,
<add> max_grad_norm=1.0)
<add> if args.loss_scale == 0:
<add> optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
<add> else:
<add> optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
<add> warmup_linear = WarmupLinearSchedule(warmup=args.warmup_proportion,
<add> t_total=num_train_optimization_steps)
<ide> else:
<del> optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
<del> warmup_linear = WarmupLinearSchedule(warmup=args.warmup_proportion,
<del> t_total=num_train_optimization_steps)
<del> else:
<del> optimizer = BertAdam(optimizer_grouped_parameters,
<del> lr=args.learning_rate,
<del> warmup=args.warmup_proportion,
<del> t_total=num_train_optimization_steps)
<add> optimizer = BertAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> warmup=args.warmup_proportion,
<add> t_total=num_train_optimization_steps)
<ide>
<ide> global_step = 0
<ide> if args.do_train:
<ide><path>examples/run_swag.py
<ide> def main():
<ide> model = torch.nn.DataParallel(model)
<ide>
<ide> # Prepare optimizer
<del> param_optimizer = list(model.named_parameters())
<del>
<del> # hack to remove pooler, which is not used
<del> # thus it produce None grad that break apex
<del> param_optimizer = [n for n in param_optimizer if 'pooler' not in n[0]]
<del>
<del> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<del> optimizer_grouped_parameters = [
<del> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<del> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<del> ]
<del> if args.fp16:
<del> try:
<del> from apex.optimizers import FP16_Optimizer
<del> from apex.optimizers import FusedAdam
<del> except ImportError:
<del> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
<del>
<del> optimizer = FusedAdam(optimizer_grouped_parameters,
<del> lr=args.learning_rate,
<del> bias_correction=False,
<del> max_grad_norm=1.0)
<del> if args.loss_scale == 0:
<del> optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
<add> if args.do_train:
<add> param_optimizer = list(model.named_parameters())
<add>
<add> # hack to remove pooler, which is not used
<add> # thus it produce None grad that break apex
<add> param_optimizer = [n for n in param_optimizer if 'pooler' not in n[0]]
<add>
<add> no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
<add> optimizer_grouped_parameters = [
<add> {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
<add> {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
<add> ]
<add> if args.fp16:
<add> try:
<add> from apex.optimizers import FP16_Optimizer
<add> from apex.optimizers import FusedAdam
<add> except ImportError:
<add> raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
<add>
<add> optimizer = FusedAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> bias_correction=False,
<add> max_grad_norm=1.0)
<add> if args.loss_scale == 0:
<add> optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
<add> else:
<add> optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
<add> warmup_linear = WarmupLinearSchedule(warmup=args.warmup_proportion,
<add> t_total=num_train_optimization_steps)
<ide> else:
<del> optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)
<del> warmup_linear = WarmupLinearSchedule(warmup=args.warmup_proportion,
<del> t_total=num_train_optimization_steps)
<del> else:
<del> optimizer = BertAdam(optimizer_grouped_parameters,
<del> lr=args.learning_rate,
<del> warmup=args.warmup_proportion,
<del> t_total=num_train_optimization_steps)
<add> optimizer = BertAdam(optimizer_grouped_parameters,
<add> lr=args.learning_rate,
<add> warmup=args.warmup_proportion,
<add> t_total=num_train_optimization_steps)
<ide>
<ide> global_step = 0
<ide> if args.do_train: | 5 |
Ruby | Ruby | use .each, not .all? to enumerate formulae | c4cdd2b7ac2b55ffcba227e43e67a7462229ecf4 | <ide><path>Library/Homebrew/cmd/versions.rb
<ide> def versions
<ide> Please use the homebrew-versions tap instead:
<ide> https://github.com/Homebrew/homebrew-versions
<ide> EOS
<del> ARGV.formulae.all? do |f|
<add> ARGV.formulae.each do |f|
<ide> versions = FormulaVersions.new(f)
<ide> path = versions.repository_path
<ide> versions.each do |version, rev| | 1 |
Javascript | Javascript | remove aliasing of react and react-dom | efe9afb2be3059f97ac06b8fe105d8d9e30368a5 | <ide><path>server/build/webpack.js
<ide> export default async function getBaseWebpackConfig (dir, {dev = false, isServer
<ide> ],
<ide> alias: {
<ide> next: nextDir,
<del> // This bypasses React's check for production mode. Since we know it is in production this way.
<del> // This allows us to exclude React from being uglified. Saving multiple seconds per build.
<del> react: dev ? 'react/cjs/react.development.js' : 'react/cjs/react.production.min.js',
<del> 'react-dom': dev ? 'react-dom/cjs/react-dom.development.js' : 'react-dom/cjs/react-dom.production.min.js'
<add> // React already does something similar to this.
<add> // But if the user has react-devtools, it'll throw an error showing that
<add> // we haven't done dead code elimination (via uglifyjs).
<add> // We purposly do not uglify React code to save the build time.
<add> // (But it didn't increase the overall build size)
<add> // Here we are doing an exact match with '$'
<add> // So, you can still require nested modules like `react-dom/server`
<add> react$: dev ? 'react/cjs/react.development.js' : 'react/cjs/react.production.min.js',
<add> 'react-dom$': dev ? 'react-dom/cjs/react-dom.development.js' : 'react-dom/cjs/react-dom.production.min.js'
<ide> }
<ide> },
<ide> resolveLoader: { | 1 |
Java | Java | improve performance of generatekey | 67f184293b94c076b0474231f739a74f42d5ffa8 | <ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
<ide> private boolean isConditionPassing(CacheOperationContext context, Object result)
<ide>
<ide> private Object generateKey(CacheOperationContext context, Object result) {
<ide> Object key = context.generateKey(result);
<del> Assert.notNull(key, "Null key returned for cache operation (maybe you are using named params " +
<del> "on classes without debug info?) " + context.metadata.operation);
<add> if (key == null) {
<add> throw new IllegalArgumentException("Null key returned for cache operation (maybe you are " +
<add> "using named params on classes without debug info?) " + context.metadata.operation);
<add> }
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace("Computed cache key " + key + " for operation " + context.metadata.operation);
<ide> } | 1 |
Javascript | Javascript | remove prefetch attributes from examples | a9325f123aa9aa9d8d0ee280d11b1c0e305c9901 | <ide><path>examples/data-fetch/pages/index.js
<ide> export default class Index extends React.Component {
<ide> return (
<ide> <div>
<ide> <p>Next.js has {this.props.stars} ⭐️</p>
<del> <Link prefetch href='/preact'>
<add> <Link href='/preact'>
<ide> <a>How about preact?</a>
<ide> </Link>
<ide> </div>
<ide><path>examples/data-fetch/pages/preact.js
<ide> export default class Preact extends React.Component {
<ide> return (
<ide> <div>
<ide> <p>Preact has {this.props.stars} ⭝</p>
<del> <Link prefetch href='/'>
<add> <Link href='/'>
<ide> <a>I bet next has more stars (?)</a>
<ide> </Link>
<ide> </div>
<ide><path>examples/using-inferno/pages/index.js
<ide> import Link from 'next/link'
<ide> export default () => (
<ide> <div>
<ide> Hello World.{' '}
<del> <Link prefetch href='/about'>
<add> <Link href='/about'>
<ide> <a>About</a>
<ide> </Link>
<ide> </div>
<ide><path>examples/with-apollo-and-redux-saga/components/Header.js
<ide> import { withRouter } from 'next/router'
<ide>
<ide> const Header = ({ router: { pathname } }) => (
<ide> <header>
<del> <Link prefetch href='/'>
<add> <Link href='/'>
<ide> <a className={pathname === '/' ? 'is-active' : ''}>Home</a>
<ide> </Link>
<del> <Link prefetch href='/about'>
<add> <Link href='/about'>
<ide> <a className={pathname === '/about' ? 'is-active' : ''}>About</a>
<ide> </Link>
<del> <Link prefetch href='/blog'>
<add> <Link href='/blog'>
<ide> <a className={pathname === '/blog' ? 'is-active' : ''}>Blog</a>
<ide> </Link>
<ide> <style jsx>{`
<ide><path>examples/with-apollo-and-redux/components/Header.js
<ide> import { withRouter } from 'next/router'
<ide>
<ide> const Header = ({ router: { pathname } }) => (
<ide> <header>
<del> <Link prefetch href='/'>
<add> <Link href='/'>
<ide> <a className={pathname === '/' ? 'is-active' : ''}>Home</a>
<ide> </Link>
<del> <Link prefetch href='/apollo'>
<add> <Link href='/apollo'>
<ide> <a className={pathname === '/apollo' ? 'is-active' : ''}>Apollo</a>
<ide> </Link>
<del> <Link prefetch href='/redux'>
<add> <Link href='/redux'>
<ide> <a className={pathname === '/redux' ? 'is-active' : ''}>Redux</a>
<ide> </Link>
<ide> <style jsx>{`
<ide><path>examples/with-apollo-auth/pages/create-account.js
<ide> export default class CreateAccount extends React.Component {
<ide> <RegisterBox />
<ide> <hr />
<ide> Already have an account?{' '}
<del> <Link prefetch href='/signin'>
<add> <Link href='/signin'>
<ide> <a>Sign in</a>
<ide> </Link>
<ide> </>
<ide><path>examples/with-apollo-auth/pages/signin.js
<ide> export default class Signin extends React.Component {
<ide> <SigninBox />
<ide> <hr />
<ide> New?{' '}
<del> <Link prefetch href='/create-account'>
<add> <Link href='/create-account'>
<ide> <a>Create account</a>
<ide> </Link>
<ide> </React.Fragment>
<ide><path>examples/with-graphql-hooks/components/header.js
<ide> import { withRouter } from 'next/router'
<ide>
<ide> const Header = ({ router: { pathname } }) => (
<ide> <header>
<del> <Link prefetch href='/'>
<add> <Link href='/'>
<ide> <a className={pathname === '/' ? 'is-active' : ''}>Home</a>
<ide> </Link>
<del> <Link prefetch href='/about'>
<add> <Link href='/about'>
<ide> <a className={pathname === '/about' ? 'is-active' : ''}>About</a>
<ide> </Link>
<ide> <style jsx>{`
<ide><path>examples/with-tailwindcss/components/nav.js
<ide> export default function Nav () {
<ide> <nav>
<ide> <ul className='flex justify-between items-center p-8'>
<ide> <li>
<del> <Link prefetch href='/'>
<add> <Link href='/'>
<ide> <a className='text-blue-500 no-underline'>Home</a>
<ide> </Link>
<ide> </li> | 9 |
Ruby | Ruby | fix documentation style | 4c41e87e3ae548c44810b66437b2f0f6e73b2106 | <ide><path>actionpack/lib/abstract_controller/helpers.rb
<ide> def clear_helpers
<ide> # helpers with the following behavior:
<ide> #
<ide> # String or Symbol:: :FooBar or "FooBar" becomes "foo_bar_helper",
<del> # and "foo_bar_helper.rb" is loaded using require_dependency.
<add> # and "foo_bar_helper.rb" is loaded using require_dependency.
<ide> #
<ide> # Module:: No further processing
<ide> # | 1 |
Go | Go | update daemon code for containerd api changes | aa3ce07c41e0da9331f0659f28fed7f35846556c | <ide><path>container/container.go
<ide> import (
<ide> "syscall"
<ide> "time"
<ide>
<del> "github.com/containerd/containerd"
<add> "github.com/containerd/containerd/cio"
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> mounttypes "github.com/docker/docker/api/types/mount"
<ide> networktypes "github.com/docker/docker/api/types/network"
<ide> func (container *Container) CloseStreams() error {
<ide> }
<ide>
<ide> // InitializeStdio is called by libcontainerd to connect the stdio.
<del>func (container *Container) InitializeStdio(iop *libcontainerd.IOPipe) (containerd.IO, error) {
<add>func (container *Container) InitializeStdio(iop *libcontainerd.IOPipe) (cio.IO, error) {
<ide> if err := container.startLogging(); err != nil {
<ide> container.Reset(false)
<ide> return nil, err
<ide> func (container *Container) InitializeStdio(iop *libcontainerd.IOPipe) (containe
<ide> }
<ide> }
<ide>
<del> return &cio{IO: iop, sc: container.StreamConfig}, nil
<add> return &rio{IO: iop, sc: container.StreamConfig}, nil
<ide> }
<ide>
<ide> // SecretMountPath returns the path of the secret mount for the container
<ide> func (container *Container) CreateDaemonEnvironment(tty bool, linkedEnv []string
<ide> return env
<ide> }
<ide>
<del>type cio struct {
<del> containerd.IO
<add>type rio struct {
<add> cio.IO
<ide>
<ide> sc *stream.Config
<ide> }
<ide>
<del>func (i *cio) Close() error {
<add>func (i *rio) Close() error {
<ide> i.IO.Close()
<ide>
<ide> return i.sc.CloseStreams()
<ide> }
<ide>
<del>func (i *cio) Wait() {
<add>func (i *rio) Wait() {
<ide> i.sc.Wait()
<ide>
<ide> i.IO.Wait()
<ide><path>daemon/exec/exec.go
<ide> import (
<ide> "runtime"
<ide> "sync"
<ide>
<del> "github.com/containerd/containerd"
<add> "github.com/containerd/containerd/cio"
<ide> "github.com/docker/docker/container/stream"
<ide> "github.com/docker/docker/libcontainerd"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> func NewConfig() *Config {
<ide> }
<ide> }
<ide>
<del>type cio struct {
<del> containerd.IO
<add>type rio struct {
<add> cio.IO
<ide>
<ide> sc *stream.Config
<ide> }
<ide>
<del>func (i *cio) Close() error {
<add>func (i *rio) Close() error {
<ide> i.IO.Close()
<ide>
<ide> return i.sc.CloseStreams()
<ide> }
<ide>
<del>func (i *cio) Wait() {
<add>func (i *rio) Wait() {
<ide> i.sc.Wait()
<ide>
<ide> i.IO.Wait()
<ide> }
<ide>
<ide> // InitializeStdio is called by libcontainerd to connect the stdio.
<del>func (c *Config) InitializeStdio(iop *libcontainerd.IOPipe) (containerd.IO, error) {
<add>func (c *Config) InitializeStdio(iop *libcontainerd.IOPipe) (cio.IO, error) {
<ide> c.StreamConfig.CopyToPipe(iop)
<ide>
<ide> if c.StreamConfig.Stdin() == nil && !c.Tty && runtime.GOOS == "windows" {
<ide> func (c *Config) InitializeStdio(iop *libcontainerd.IOPipe) (containerd.IO, erro
<ide> }
<ide> }
<ide>
<del> return &cio{IO: iop, sc: c.StreamConfig}, nil
<add> return &rio{IO: iop, sc: c.StreamConfig}, nil
<ide> }
<ide>
<ide> // CloseStreams closes the stdio streams for the exec
<ide><path>daemon/start_unix.go
<ide> import (
<ide> "os/exec"
<ide> "path/filepath"
<ide>
<del> "github.com/containerd/containerd/linux/runcopts"
<add> "github.com/containerd/containerd/linux/runctypes"
<ide> "github.com/docker/docker/container"
<ide> "github.com/pkg/errors"
<ide> )
<ide> func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Contain
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> opts := &runcopts.RuncOptions{
<add> opts := &runctypes.RuncOptions{
<ide> Runtime: path,
<ide> RuntimeRoot: filepath.Join(daemon.configStore.ExecRoot,
<ide> fmt.Sprintf("runtime-%s", container.HostConfig.Runtime)),
<ide><path>libcontainerd/client_daemon.go
<ide> import (
<ide> "google.golang.org/grpc/status"
<ide>
<ide> "github.com/containerd/containerd"
<add> "github.com/containerd/containerd/api/events"
<ide> eventsapi "github.com/containerd/containerd/api/services/events/v1"
<ide> "github.com/containerd/containerd/api/types"
<ide> "github.com/containerd/containerd/archive"
<add> "github.com/containerd/containerd/cio"
<ide> "github.com/containerd/containerd/content"
<ide> "github.com/containerd/containerd/images"
<del> "github.com/containerd/containerd/linux/runcopts"
<add> "github.com/containerd/containerd/linux/runctypes"
<ide> "github.com/containerd/typeurl"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/opencontainers/image-spec/specs-go/v1"
<ide> func (c *client) Restore(ctx context.Context, id string, attachStdio StdioCallba
<ide> c.Lock()
<ide> defer c.Unlock()
<ide>
<del> var cio containerd.IO
<add> var rio cio.IO
<ide> defer func() {
<ide> err = wrapError(err)
<ide> }()
<ide> func (c *client) Restore(ctx context.Context, id string, attachStdio StdioCallba
<ide> }
<ide>
<ide> defer func() {
<del> if err != nil && cio != nil {
<del> cio.Cancel()
<del> cio.Close()
<add> if err != nil && rio != nil {
<add> rio.Cancel()
<add> rio.Close()
<ide> }
<ide> }()
<ide>
<del> t, err := ctr.Task(ctx, func(fifos *containerd.FIFOSet) (containerd.IO, error) {
<add> t, err := ctr.Task(ctx, func(fifos *cio.FIFOSet) (cio.IO, error) {
<ide> io, err := newIOPipe(fifos)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide>
<del> cio, err = attachStdio(io)
<del> return cio, err
<add> rio, err = attachStdio(io)
<add> return rio, err
<ide> })
<ide> if err != nil && !strings.Contains(err.Error(), "no running task found") {
<ide> return false, -1, err
<ide> func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin
<ide> var (
<ide> cp *types.Descriptor
<ide> t containerd.Task
<del> cio containerd.IO
<add> rio cio.IO
<ide> err error
<ide> stdinCloseSync = make(chan struct{})
<ide> )
<ide> func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin
<ide> }
<ide> uid, gid := getSpecUser(spec)
<ide> t, err = ctr.ctr.NewTask(ctx,
<del> func(id string) (containerd.IO, error) {
<add> func(id string) (cio.IO, error) {
<ide> fifos := newFIFOSet(ctr.bundleDir, id, InitProcessName, withStdin, spec.Process.Terminal)
<del> cio, err = c.createIO(fifos, id, InitProcessName, stdinCloseSync, attachStdio)
<del> return cio, err
<add> rio, err = c.createIO(fifos, id, InitProcessName, stdinCloseSync, attachStdio)
<add> return rio, err
<ide> },
<ide> func(_ context.Context, _ *containerd.Client, info *containerd.TaskInfo) error {
<ide> info.Checkpoint = cp
<del> info.Options = &runcopts.CreateOptions{
<add> info.Options = &runctypes.CreateOptions{
<ide> IoUid: uint32(uid),
<ide> IoGid: uint32(gid),
<ide> }
<ide> return nil
<ide> })
<ide> if err != nil {
<ide> close(stdinCloseSync)
<del> if cio != nil {
<del> cio.Cancel()
<del> cio.Close()
<add> if rio != nil {
<add> rio.Cancel()
<add> rio.Close()
<ide> }
<ide> return -1, err
<ide> }
<ide> func (c *client) Exec(ctx context.Context, containerID, processID string, spec *
<ide>
<ide> var (
<ide> p containerd.Process
<del> cio containerd.IO
<add> rio cio.IO
<ide> err error
<ide> stdinCloseSync = make(chan struct{})
<ide> )
<ide> func (c *client) Exec(ctx context.Context, containerID, processID string, spec *
<ide>
<ide> defer func() {
<ide> if err != nil {
<del> if cio != nil {
<del> cio.Cancel()
<del> cio.Close()
<add> if rio != nil {
<add> rio.Cancel()
<add> rio.Close()
<ide> }
<ide> rmFIFOSet(fifos)
<ide> }
<ide> }()
<ide>
<del> p, err = ctr.task.Exec(ctx, processID, spec, func(id string) (containerd.IO, error) {
<del> cio, err = c.createIO(fifos, containerID, processID, stdinCloseSync, attachStdio)
<del> return cio, err
<add> p, err = ctr.task.Exec(ctx, processID, spec, func(id string) (cio.IO, error) {
<add> rio, err = c.createIO(fifos, containerID, processID, stdinCloseSync, attachStdio)
<add> return rio, err
<ide> })
<ide> if err != nil {
<ide> close(stdinCloseSync)
<del> if cio != nil {
<del> cio.Cancel()
<del> cio.Close()
<add> if rio != nil {
<add> rio.Cancel()
<add> rio.Close()
<ide> }
<ide> return -1, err
<ide> }
<ide> func (c *client) getProcess(containerID, processID string) (containerd.Process,
<ide>
<ide> // createIO creates the io to be used by a process
<ide> // This needs to get a pointer to interface as upon closure the process may not have yet been registered
<del>func (c *client) createIO(fifos *containerd.FIFOSet, containerID, processID string, stdinCloseSync chan struct{}, attachStdio StdioCallback) (containerd.IO, error) {
<add>func (c *client) createIO(fifos *cio.FIFOSet, containerID, processID string, stdinCloseSync chan struct{}, attachStdio StdioCallback) (cio.IO, error) {
<ide> io, err := newIOPipe(fifos)
<ide> if err != nil {
<ide> return nil, err
<ide> func (c *client) createIO(fifos *containerd.FIFOSet, containerID, processID stri
<ide> })
<ide> }
<ide>
<del> cio, err := attachStdio(io)
<add> rio, err := attachStdio(io)
<ide> if err != nil {
<ide> io.Cancel()
<ide> io.Close()
<ide> }
<del> return cio, err
<add> return rio, err
<ide> }
<ide>
<ide> func (c *client) processEvent(ctr *container, et EventType, ei EventInfo) {
<ide> func (c *client) processEventStream(ctx context.Context) {
<ide> c.logger.WithField("topic", ev.Topic).Debug("event")
<ide>
<ide> switch t := v.(type) {
<del> case *eventsapi.TaskCreate:
<add> case *events.TaskCreate:
<ide> et = EventCreate
<ide> ei = EventInfo{
<ide> ContainerID: t.ContainerID,
<ide> ProcessID: t.ContainerID,
<ide> Pid: t.Pid,
<ide> }
<del> case *eventsapi.TaskStart:
<add> case *events.TaskStart:
<ide> et = EventStart
<ide> ei = EventInfo{
<ide> ContainerID: t.ContainerID,
<ide> ProcessID: t.ContainerID,
<ide> Pid: t.Pid,
<ide> }
<del> case *eventsapi.TaskExit:
<add> case *events.TaskExit:
<ide> et = EventExit
<ide> ei = EventInfo{
<ide> ContainerID: t.ContainerID,
<ide> func (c *client) processEventStream(ctx context.Context) {
<ide> ExitCode: t.ExitStatus,
<ide> ExitedAt: t.ExitedAt,
<ide> }
<del> case *eventsapi.TaskOOM:
<add> case *events.TaskOOM:
<ide> et = EventOOM
<ide> ei = EventInfo{
<ide> ContainerID: t.ContainerID,
<ide> OOMKilled: true,
<ide> }
<ide> oomKilled = true
<del> case *eventsapi.TaskExecAdded:
<add> case *events.TaskExecAdded:
<ide> et = EventExecAdded
<ide> ei = EventInfo{
<ide> ContainerID: t.ContainerID,
<ide> ProcessID: t.ExecID,
<ide> }
<del> case *eventsapi.TaskExecStarted:
<add> case *events.TaskExecStarted:
<ide> et = EventExecStarted
<ide> ei = EventInfo{
<ide> ContainerID: t.ContainerID,
<ide> ProcessID: t.ExecID,
<ide> Pid: t.Pid,
<ide> }
<del> case *eventsapi.TaskPaused:
<add> case *events.TaskPaused:
<ide> et = EventPaused
<ide> ei = EventInfo{
<ide> ContainerID: t.ContainerID,
<ide> }
<del> case *eventsapi.TaskResumed:
<add> case *events.TaskResumed:
<ide> et = EventResumed
<ide> ei = EventInfo{
<ide> ContainerID: t.ContainerID,
<ide><path>libcontainerd/client_daemon_linux.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/containerd/containerd"
<add> "github.com/containerd/containerd/cio"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> specs "github.com/opencontainers/runtime-spec/specs-go"
<ide> "github.com/sirupsen/logrus"
<ide> func prepareBundleDir(bundleDir string, ociSpec *specs.Spec) (string, error) {
<ide> return p, nil
<ide> }
<ide>
<del>func newFIFOSet(bundleDir, containerID, processID string, withStdin, withTerminal bool) *containerd.FIFOSet {
<del> fifos := &containerd.FIFOSet{
<add>func newFIFOSet(bundleDir, containerID, processID string, withStdin, withTerminal bool) *cio.FIFOSet {
<add> fifos := &cio.FIFOSet{
<ide> Terminal: withTerminal,
<ide> Out: filepath.Join(bundleDir, processID+"-stdout"),
<ide> }
<ide> func newFIFOSet(bundleDir, containerID, processID string, withStdin, withTermina
<ide> return fifos
<ide> }
<ide>
<del>func rmFIFOSet(fset *containerd.FIFOSet) {
<add>func rmFIFOSet(fset *cio.FIFOSet) {
<ide> for _, fn := range []string{fset.Out, fset.In, fset.Err} {
<ide> if fn != "" {
<ide> if err := os.RemoveAll(fn); err != nil {
<ide><path>libcontainerd/client_daemon_windows.go
<ide> package libcontainerd
<ide> import (
<ide> "fmt"
<ide>
<del> "github.com/containerd/containerd"
<add> "github.com/containerd/containerd/cio"
<ide> "github.com/containerd/containerd/windows/hcsshimtypes"
<ide> specs "github.com/opencontainers/runtime-spec/specs-go"
<ide> "github.com/pkg/errors"
<ide> func pipeName(containerID, processID, name string) string {
<ide> return fmt.Sprintf(`\\.\pipe\containerd-%s-%s-%s`, containerID, processID, name)
<ide> }
<ide>
<del>func newFIFOSet(bundleDir, containerID, processID string, withStdin, withTerminal bool) *containerd.FIFOSet {
<del> fifos := &containerd.FIFOSet{
<add>func newFIFOSet(bundleDir, containerID, processID string, withStdin, withTerminal bool) *cio.FIFOSet {
<add> fifos := &cio.FIFOSet{
<ide> Terminal: withTerminal,
<ide> Out: pipeName(containerID, processID, "stdout"),
<ide> }
<ide><path>libcontainerd/io.go
<ide> package libcontainerd
<ide>
<del>import "github.com/containerd/containerd"
<add>import "github.com/containerd/containerd/cio"
<ide>
<ide> // Config returns the containerd.IOConfig of this pipe set
<del>func (p *IOPipe) Config() containerd.IOConfig {
<add>func (p *IOPipe) Config() cio.Config {
<ide> return p.config
<ide> }
<ide>
<ide><path>libcontainerd/io_unix.go
<ide> import (
<ide> "io"
<ide> "syscall"
<ide>
<del> "github.com/containerd/containerd"
<add> "github.com/containerd/containerd/cio"
<ide> "github.com/containerd/fifo"
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<del>func newIOPipe(fifos *containerd.FIFOSet) (*IOPipe, error) {
<add>func newIOPipe(fifos *cio.FIFOSet) (*IOPipe, error) {
<ide> var (
<ide> err error
<ide> ctx, cancel = context.WithCancel(context.Background())
<ide> f io.ReadWriteCloser
<ide> iop = &IOPipe{
<ide> Terminal: fifos.Terminal,
<ide> cancel: cancel,
<del> config: containerd.IOConfig{
<add> config: cio.Config{
<ide> Terminal: fifos.Terminal,
<ide> Stdin: fifos.In,
<ide> Stdout: fifos.Out,
<ide><path>libcontainerd/io_windows.go
<ide> import (
<ide> "sync"
<ide>
<ide> winio "github.com/Microsoft/go-winio"
<del> "github.com/containerd/containerd"
<add> "github.com/containerd/containerd/cio"
<ide> "github.com/pkg/errors"
<ide> )
<ide>
<ide> func (wp *winpipe) Close() error {
<ide> }
<ide> }
<ide>
<del>func newIOPipe(fifos *containerd.FIFOSet) (*IOPipe, error) {
<add>func newIOPipe(fifos *cio.FIFOSet) (*IOPipe, error) {
<ide> var (
<ide> err error
<ide> ctx, cancel = context.WithCancel(context.Background())
<ide> p io.ReadWriteCloser
<ide> iop = &IOPipe{
<ide> Terminal: fifos.Terminal,
<ide> cancel: cancel,
<del> config: containerd.IOConfig{
<add> config: cio.Config{
<ide> Terminal: fifos.Terminal,
<ide> Stdin: fifos.In,
<ide> Stdout: fifos.Out,
<ide><path>libcontainerd/remote_daemon_options_linux.go
<ide> type subreaper bool
<ide>
<ide> func (s subreaper) Apply(r Remote) error {
<ide> if remote, ok := r.(*remote); ok {
<del> remote.Subreaper = bool(s)
<add> remote.NoSubreaper = !bool(s)
<ide> return nil
<ide> }
<ide> return fmt.Errorf("WithSubreaper option not supported for this remote")
<ide><path>libcontainerd/types.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/containerd/containerd"
<add> "github.com/containerd/containerd/cio"
<ide> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<ide> type Client interface {
<ide> }
<ide>
<ide> // StdioCallback is called to connect a container or process stdio.
<del>type StdioCallback func(*IOPipe) (containerd.IO, error)
<add>type StdioCallback func(*IOPipe) (cio.IO, error)
<ide>
<ide> // IOPipe contains the stdio streams.
<ide> type IOPipe struct {
<ide> type IOPipe struct {
<ide> Terminal bool // Whether stderr is connected on Windows
<ide>
<ide> cancel context.CancelFunc
<del> config containerd.IOConfig
<add> config cio.Config
<ide> }
<ide>
<ide> // ServerVersion contains version information as retrieved from the
<ide><path>plugin/executor/containerd/containerd.go
<ide> import (
<ide> "path/filepath"
<ide> "sync"
<ide>
<del> "github.com/containerd/containerd"
<del> "github.com/containerd/containerd/linux/runcopts"
<add> "github.com/containerd/containerd/cio"
<add> "github.com/containerd/containerd/linux/runctypes"
<ide> "github.com/docker/docker/api/errdefs"
<ide> "github.com/docker/docker/libcontainerd"
<ide> "github.com/opencontainers/runtime-spec/specs-go"
<ide> type Executor struct {
<ide>
<ide> // Create creates a new container
<ide> func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error {
<del> opts := runcopts.RuncOptions{
<add> opts := runctypes.RuncOptions{
<ide> RuntimeRoot: filepath.Join(e.rootDir, "runtime-root"),
<ide> }
<ide> ctx := context.Background()
<ide> func (e *Executor) ProcessEvent(id string, et libcontainerd.EventType, ei libcon
<ide> return nil
<ide> }
<ide>
<del>type cio struct {
<del> containerd.IO
<add>type rio struct {
<add> cio.IO
<ide>
<ide> wg sync.WaitGroup
<ide> }
<ide>
<del>func (c *cio) Wait() {
<add>func (c *rio) Wait() {
<ide> c.wg.Wait()
<ide> c.IO.Wait()
<ide> }
<ide>
<ide> func attachStreamsFunc(stdout, stderr io.WriteCloser) libcontainerd.StdioCallback {
<del> return func(iop *libcontainerd.IOPipe) (containerd.IO, error) {
<add> return func(iop *libcontainerd.IOPipe) (cio.IO, error) {
<ide> if iop.Stdin != nil {
<ide> iop.Stdin.Close()
<ide> // closing stdin shouldn't be needed here, it should never be open
<ide> panic("plugin stdin shouldn't have been created!")
<ide> }
<ide>
<del> cio := &cio{IO: iop}
<del> cio.wg.Add(2)
<add> rio := &rio{IO: iop}
<add> rio.wg.Add(2)
<ide> go func() {
<ide> io.Copy(stdout, iop.Stdout)
<ide> stdout.Close()
<del> cio.wg.Done()
<add> rio.wg.Done()
<ide> }()
<ide> go func() {
<ide> io.Copy(stderr, iop.Stderr)
<ide> stderr.Close()
<del> cio.wg.Done()
<add> rio.wg.Done()
<ide> }()
<del> return cio, nil
<add> return rio, nil
<ide> }
<ide> } | 12 |
Text | Text | add readme for blender plugin | 92bb07914581f7ac33f2378eee88ce034dda39a4 | <ide><path>utils/exporters/blender/README.md
<add># Three.js Blender Import/Export
<add>
<add>Imports and exports Three.js' ASCII JSON format.
<add>
<add>Assumes Blender version 2.60.
<add>
<add>## Installation
<add>
<add>Copy the io_mesh_threejs folder to the scripts/addons folder. The full path is OS-dependent (see below).
<add>
<add>Once that is done, you need to activate the plugin. Open Blender preferences, look for
<add>Addons, search for `three`, enable the checkbox next to the `Import-Export: three.js format` entry.
<add>
<add>Goto Usage.
<add>
<add>### Windows
<add>
<add>Should look like this:
<add>
<add> C:\Users\USERNAME\AppData\Roaming\Blender Foundation\Blender\2.60\scripts\addons
<add>
<add>### OSX
<add>
<add>Depends on where blender.app is. Assuming you copied it to your Applications folder:
<add>
<add> /Applications/Blender/blender.app/Contents/MacOS/2.60/scripts/addons
<add>
<add>## Usage
<add>
<add>Use the regular Import and Export menu within Blender, select `Three.js (js)`.
<add> | 1 |
Python | Python | improve documentation of training_args.py | 6a064447f2f74cd4e3fdaff31f2a7f7c8db4aa77 | <ide><path>src/transformers/training_args.py
<ide> class TrainingArguments:
<ide> If :obj:`True`, overwrite the content of the output directory. Use this to continue training if
<ide> :obj:`output_dir` points to a checkpoint directory.
<ide> do_train (:obj:`bool`, `optional`, defaults to :obj:`False`):
<del> Whether to run training or not.
<add> Whether to run training or not. This argument is not directly used by :class:`~transformers.Trainer`, it's
<add> intended to be used by your training/evaluation scripts instead. See the `example scripts
<add> <https://github.com/huggingface/transformers/tree/master/examples>`__ for more details.
<ide> do_eval (:obj:`bool`, `optional`):
<del> Whether to run evaluation on the dev set or not. Will default to :obj:`evaluation_strategy` different from
<del> :obj:`"no"`.
<add> Whether to run evaluation on the dev set or not. Will be set to :obj:`True` if :obj:`evaluation_strategy`
<add> is different from :obj:`"no"`. This argument is not directly used by :class:`~transformers.Trainer`, it's
<add> intended to be used by your training/evaluation scripts instead. See the `example scripts
<add> <https://github.com/huggingface/transformers/tree/master/examples>`__ for more details.
<ide> do_predict (:obj:`bool`, `optional`, defaults to :obj:`False`):
<del> Whether to run predictions on the test set or not.
<add> Whether to run predictions on the test set or not. This argument is not directly used by
<add> :class:`~transformers.Trainer`, it's intended to be used by your training/evaluation scripts instead. See
<add> the `example scripts <https://github.com/huggingface/transformers/tree/master/examples>`__ for more
<add> details.
<ide> evaluation_strategy (:obj:`str` or :class:`~transformers.trainer_utils.EvaluationStrategy`, `optional`, defaults to :obj:`"no"`):
<ide> The evaluation strategy to adopt during training. Possible values are:
<ide> | 1 |
Python | Python | update version to 4.2.0 | 028dbe4a4d6786d56ed30ea49971cc5415fffb4b | <ide><path>celery/__init__.py
<ide>
<ide> SERIES = 'latentcall'
<ide>
<del>__version__ = '4.1.0'
<add>__version__ = '4.2.0'
<ide> __author__ = 'Ask Solem'
<ide> __contact__ = 'ask@celeryproject.org'
<ide> __homepage__ = 'http://celeryproject.org' | 1 |
PHP | PHP | flush the registry before generating fixtures | 5e6925bfdf7efe44324de500e54163de3e914af7 | <ide><path>tests/TestCase/Shell/Task/TestTaskTest.php
<ide> public function testFixtureArrayGenerationFromModel() {
<ide> * @return void
<ide> */
<ide> public function testFixtureArrayGenerationIgnoreSelfAssociation() {
<add> TableRegistry::clear();
<ide> $subject = new CategoryThreadsTable();
<ide> $result = $this->Task->generateFixtureList($subject);
<ide> $expected = [ | 1 |
PHP | PHP | fix possible bug in session keep | 74dad49cd0e8334c78474655161a19ad296243a8 | <ide><path>src/Illuminate/Session/Store.php
<ide> public function keep($keys = null)
<ide> */
<ide> protected function mergeNewFlashes(array $keys)
<ide> {
<del> $values = array_unique(array_merge($this->get('flash.new'), $keys));
<add> $values = array_unique(array_merge($this->get('flash.new', array()), $keys));
<ide>
<ide> $this->put('flash.new', $values);
<ide> } | 1 |
Javascript | Javascript | remove user data in cleandata | 5fe76c663f8a4986af62edb434a1708c006d0b21 | <ide><path>src/manipulation.js
<ide> jQuery.extend({
<ide> i = 0;
<ide>
<ide> for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
<del> if ( jQuery.acceptData( elem ) && (data = elem[ dataPriv.expando ])) {
<del> if ( data.events ) {
<del> for ( type in data.events ) {
<del> if ( special[ type ] ) {
<del> jQuery.event.remove( elem, type );
<del>
<del> // This is a shortcut to avoid jQuery.event.remove's overhead
<del> } else {
<del> jQuery.removeEvent( elem, type, data.handle );
<add> if ( jQuery.acceptData( elem ) ) {
<add> if ( (data = elem[ dataPriv.expando ] ) ) {
<add> if ( data.events ) {
<add> for ( type in data.events ) {
<add> if ( special[ type ] ) {
<add> jQuery.event.remove( elem, type );
<add>
<add> // This is a shortcut to avoid jQuery.event.remove's overhead
<add> } else {
<add> jQuery.removeEvent( elem, type, data.handle );
<add> }
<ide> }
<ide> }
<add> delete elem[ dataPriv.expando ];
<add> }
<add> if ( elem[ dataUser.expando ] ) {
<add> delete elem[ dataUser.expando ];
<ide> }
<del> delete elem[ dataPriv.expando ];
<ide> }
<ide> }
<ide> }
<ide><path>test/unit/manipulation.js
<ide> test( "jQuery.cleanData", function() {
<ide> });
<ide>
<ide> test( "jQuery.cleanData eliminates all private data (gh-2127)", function() {
<del> expect( 2 );
<add> expect( 3 );
<ide>
<ide> var div = jQuery( "<div/>" ).appendTo( "#qunit-fixture" );
<ide>
<ide> test( "jQuery.cleanData eliminates all private data (gh-2127)", function() {
<ide>
<ide> div.remove();
<ide>
<add> ok( !jQuery.hasData( div[ 0 ] ), "Removed element hasData should return false" );
<add>
<ide> ok( jQuery.isEmptyObject( jQuery._data( div[ 0 ] ) ),
<ide> "Private data is empty after node is removed" );
<ide>
<ide> div.remove();
<ide> });
<ide>
<add>test( "jQuery.cleanData eliminates all public data", function() {
<add> expect( 2 );
<add>
<add> var key,
<add> div = jQuery( "<div/>" );
<add> div.data( "some", "data" );
<add> ok( !jQuery.isEmptyObject( jQuery.data( div[ 0 ] ) ), "Ensure some public data exists" );
<add>
<add> div.remove();
<add>
<add> ok( !jQuery.hasData( div[ 0 ] ), "Removed element hasData should return false" );
<add>
<add> // Make sure the expando is gone
<add> for ( key in div[ 0 ] ) {
<add> if ( /^jQuery/.test( key ) ) {
<add> ok( false, "Expando was not removed when there was no more data" );
<add> }
<add> }
<add>});
<add>
<ide> test( "domManip plain-text caching (trac-6779)", function() {
<ide>
<ide> expect( 1 ); | 2 |
Go | Go | avoid alignment of reapnetwork and tableentries | a4e64d05c1073022f43c606d2eb8d0fa4d3e947d | <ide><path>libnetwork/networkdb/cluster.go
<ide> import (
<ide> )
<ide>
<ide> const (
<del> reapInterval = 30 * time.Minute
<del> reapPeriod = 5 * time.Second
<del> retryInterval = 1 * time.Second
<del> nodeReapInterval = 24 * time.Hour
<del> nodeReapPeriod = 2 * time.Hour
<add> // The garbage collection logic for entries leverage the presence of the network.
<add> // For this reason the expiration time of the network is put slightly higher than the entry expiration so that
<add> // there is at least 5 extra cycle to make sure that all the entries are properly deleted before deleting the network.
<add> reapEntryInterval = 30 * time.Minute
<add> reapNetworkInterval = reapEntryInterval + 5*reapPeriod
<add> reapPeriod = 5 * time.Second
<add> retryInterval = 1 * time.Second
<add> nodeReapInterval = 24 * time.Hour
<add> nodeReapPeriod = 2 * time.Hour
<ide> )
<ide>
<ide> type logWriter struct{}
<ide> func (nDB *NetworkDB) reconnectNode() {
<ide> // the reaper runs. NOTE nDB.reapTableEntries updates the reapTime with a readlock. This
<ide> // is safe as long as no other concurrent path touches the reapTime field.
<ide> func (nDB *NetworkDB) reapState() {
<del> nDB.reapNetworks()
<add> // The reapTableEntries leverage the presence of the network so garbage collect entries first
<ide> nDB.reapTableEntries()
<add> nDB.reapNetworks()
<ide> }
<ide>
<ide> func (nDB *NetworkDB) reapNetworks() {
<ide> func (nDB *NetworkDB) gossip() {
<ide> // Collect stats and print the queue info, note this code is here also to have a view of the queues empty
<ide> network.qMessagesSent += len(msgs)
<ide> if printStats {
<del> logrus.Infof("NetworkDB stats - net:%s Entries:%d Queue qLen:%d netPeers:%d netMsg/s:%d",
<del> nid, network.entriesNumber, broadcastQ.NumQueued(), broadcastQ.NumNodes(),
<add> logrus.Infof("NetworkDB stats - netID:%s leaving:%t netPeers:%d entries:%d Queue qLen:%d netMsg/s:%d",
<add> nid, network.leaving, broadcastQ.NumNodes(), network.entriesNumber, broadcastQ.NumQueued(),
<ide> network.qMessagesSent/int((nDB.config.StatsPrintPeriod/time.Second)))
<ide> network.qMessagesSent = 0
<ide> }
<ide><path>libnetwork/networkdb/delegate.go
<ide> func (nDB *NetworkDB) handleNetworkEvent(nEvent *NetworkEvent) bool {
<ide> n.ltime = nEvent.LTime
<ide> n.leaving = nEvent.Type == NetworkEventTypeLeave
<ide> if n.leaving {
<del> n.reapTime = reapInterval
<add> n.reapTime = reapNetworkInterval
<ide>
<ide> // The remote node is leaving the network, but not the gossip cluster.
<ide> // Mark all its entries in deleted state, this will guarantee that
<ide> func (nDB *NetworkDB) handleTableEvent(tEvent *TableEvent) bool {
<ide> // field. If that is not the case, this can be a BUG
<ide> if e.deleting && e.reapTime == 0 {
<ide> logrus.Warnf("handleTableEvent object %+v has a 0 reapTime, is the cluster running the same docker engine version?", tEvent)
<del> e.reapTime = reapInterval
<add> e.reapTime = reapEntryInterval
<ide> }
<ide>
<ide> nDB.Lock()
<ide><path>libnetwork/networkdb/networkdb.go
<ide> func (nDB *NetworkDB) DeleteEntry(tname, nid, key string) error {
<ide> node: nDB.config.NodeName,
<ide> value: value,
<ide> deleting: true,
<del> reapTime: reapInterval,
<add> reapTime: reapEntryInterval,
<ide> }
<ide>
<ide> if err := nDB.sendTableEvent(TableEventTypeDelete, nid, tname, key, entry); err != nil {
<ide> func (nDB *NetworkDB) deleteNodeNetworkEntries(nid, node string) {
<ide> node: oldEntry.node,
<ide> value: oldEntry.value,
<ide> deleting: true,
<del> reapTime: reapInterval,
<add> reapTime: reapEntryInterval,
<ide> }
<ide>
<ide> // we arrived at this point in 2 cases:
<ide> func (nDB *NetworkDB) LeaveNetwork(nid string) error {
<ide> return fmt.Errorf("could not find network %s while trying to leave", nid)
<ide> }
<ide>
<add> logrus.Debugf("%s: leaving network %s", nDB.config.NodeName, nid)
<ide> n.ltime = ltime
<del> n.reapTime = reapInterval
<add> n.reapTime = reapNetworkInterval
<ide> n.leaving = true
<ide> return nil
<ide> } | 3 |
Javascript | Javascript | upgrade automaticprefetchplugin to es6 | e52702050a4bed88a7fb3e89ab4414810362a177 | <ide><path>lib/AutomaticPrefetchPlugin.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var async = require("async");
<del>var PrefetchDependency = require("./dependencies/PrefetchDependency");
<del>var NormalModule = require("./NormalModule");
<add>"use strict";
<ide>
<del>function AutomaticPrefetchPlugin() {}
<del>module.exports = AutomaticPrefetchPlugin;
<del>AutomaticPrefetchPlugin.prototype.apply = function(compiler) {
<del> compiler.plugin("compilation", function(compilation, params) {
<del> var normalModuleFactory = params.normalModuleFactory;
<add>const async = require("async");
<add>const PrefetchDependency = require("./dependencies/PrefetchDependency");
<add>const NormalModule = require("./NormalModule");
<add>
<add>class AutomaticPrefetchPlugin {
<add> apply(compiler) {
<add> compiler.plugin("compilation", (compilation, params) => {
<add> const normalModuleFactory = params.normalModuleFactory;
<ide>
<del> compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory);
<del> });
<del> var lastModules = null;
<del> compiler.plugin("after-compile", function(compilation, callback) {
<del> lastModules = compilation.modules.filter(function(m) {
<del> return m instanceof NormalModule;
<del> }).map(function(m) {
<del> return {
<del> context: m.context,
<del> request: m.request
<del> };
<add> compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory);
<add> });
<add> let lastModules = null;
<add> compiler.plugin("after-compile", (compilation, callback) => {
<add> lastModules = compilation.modules
<add> .filter(m => m instanceof NormalModule)
<add> .map(m => ({
<add> context: m.context,
<add> request: m.request
<add> }));
<add> callback();
<ide> });
<del> callback();
<del> });
<del> compiler.plugin("make", function(compilation, callback) {
<del> if(!lastModules) return callback();
<del> async.forEach(lastModules, function(m, callback) {
<del> compilation.prefetch(m.context || compiler.context, new PrefetchDependency(m.request), callback);
<del> }, callback);
<del> });
<del>};
<add> compiler.plugin("make", (compilation, callback) => {
<add> if(!lastModules) return callback();
<add> async.forEach(lastModules, (m, callback) => {
<add> compilation.prefetch(m.context || compiler.context, new PrefetchDependency(m.request), callback);
<add> }, callback);
<add> });
<add> }
<add>}
<add>module.exports = AutomaticPrefetchPlugin; | 1 |
PHP | PHP | simplify update query bindings | 0708161b2079b55a44112fba94500340a1b56792 | <ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php
<ide> public function compileUpdate(Builder $query, $values)
<ide> */
<ide> public function prepareBindingsForUpdate(array $bindings, array $values)
<ide> {
<del> $cleanBindings = Arr::except($bindings, ['join', 'select']);
<add> $cleanBindings = Arr::except($bindings, ['select', 'join']);
<ide>
<ide> return array_values(
<ide> array_merge($bindings['join'], $values, Arr::flatten($cleanBindings))
<ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php
<ide> public function prepareBindingsForUpdate(array $bindings, array $values)
<ide> : $value;
<ide> })->all();
<ide>
<del> // Update statements with "joins" in Postgres use an interesting syntax. We need to
<del> // take all of the bindings and put them on the end of this array since they are
<del> // added to the end of the "where" clause statements as typical where clauses.
<del> $bindingsWithoutJoin = Arr::except($bindings, ['select', 'join']);
<add> $cleanBindings = Arr::except($bindings, 'select');
<ide>
<ide> return array_values(
<del> array_merge($values, $bindings['join'], Arr::flatten($bindingsWithoutJoin))
<add> array_merge($values, Arr::flatten($cleanBindings))
<ide> );
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php
<ide> public function compileUpdate(Builder $query, $values)
<ide> */
<ide> public function prepareBindingsForUpdate(array $bindings, array $values)
<ide> {
<del> $cleanBindings = Arr::except($bindings, ['select', 'join']);
<add> $cleanBindings = Arr::except($bindings, 'select');
<ide>
<ide> return array_values(
<del> array_merge($values, $bindings['join'], Arr::flatten($cleanBindings))
<add> array_merge($values, Arr::flatten($cleanBindings))
<ide> );
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php
<ide> protected function parseUpdateTable($table)
<ide> */
<ide> public function prepareBindingsForUpdate(array $bindings, array $values)
<ide> {
<del> // Update statements with joins in SQL Servers utilize an unique syntax. We need to
<del> // take all of the bindings and put them on the end of this array since they are
<del> // added to the end of the "where" clause statements as typical where clauses.
<del> $bindingsWithoutJoin = Arr::except($bindings, 'join');
<add> $cleanBindings = Arr::except($bindings, 'select');
<ide>
<ide> return array_values(
<del> array_merge($values, $bindings['join'], Arr::flatten($bindingsWithoutJoin))
<add> array_merge($values, Arr::flatten($cleanBindings))
<ide> );
<ide> }
<ide> | 4 |
Go | Go | fix docker rename with linked containers | 3f6e3a0885124a00c7f915af8f9181e6a275d828 | <ide><path>daemon/rename.go
<ide> import (
<ide> "strings"
<ide>
<ide> "github.com/Sirupsen/logrus"
<add> dockercontainer "github.com/docker/docker/container"
<ide> "github.com/docker/libnetwork"
<ide> )
<ide>
<ide> func (daemon *Daemon) ContainerRename(oldName, newName string) error {
<ide> container.Lock()
<ide> defer container.Unlock()
<ide>
<add> links := map[string]*dockercontainer.Container{}
<add> for k, v := range daemon.linkIndex.children(container) {
<add> if !strings.HasPrefix(k, oldName) {
<add> return fmt.Errorf("Linked container %s does not match parent %s", k, oldName)
<add> }
<add> links[strings.TrimPrefix(k, oldName)] = v
<add> }
<add>
<ide> if newName, err = daemon.reserveName(container.ID, newName); err != nil {
<ide> return fmt.Errorf("Error when allocating new name: %v", err)
<ide> }
<ide>
<add> for k, v := range links {
<add> daemon.nameIndex.Reserve(newName+k, v.ID)
<add> daemon.linkIndex.link(container, v, newName+k)
<add> }
<add>
<ide> container.Name = newName
<ide> container.NetworkSettings.IsAnonymousEndpoint = false
<ide>
<ide> func (daemon *Daemon) ContainerRename(oldName, newName string) error {
<ide> container.Name = oldName
<ide> container.NetworkSettings.IsAnonymousEndpoint = oldIsAnonymousEndpoint
<ide> daemon.reserveName(container.ID, oldName)
<add> for k, v := range links {
<add> daemon.nameIndex.Reserve(oldName+k, v.ID)
<add> daemon.linkIndex.link(container, v, oldName+k)
<add> daemon.linkIndex.unlink(newName+k, v, container)
<add> daemon.nameIndex.Release(newName + k)
<add> }
<ide> daemon.releaseName(newName)
<ide> }
<ide> }()
<ide>
<add> for k, v := range links {
<add> daemon.linkIndex.unlink(oldName+k, v, container)
<add> daemon.nameIndex.Release(oldName + k)
<add> }
<ide> daemon.releaseName(oldName)
<ide> if err = container.ToDisk(); err != nil {
<ide> return err
<ide><path>integration-cli/docker_cli_rename_test.go
<ide> func (s *DockerSuite) TestRenameContainerWithSameName(c *check.C) {
<ide> c.Assert(err, checker.NotNil, check.Commentf("Renaming a container with the same name should have failed"))
<ide> c.Assert(out, checker.Contains, "Renaming a container with the same name", check.Commentf("%v", err))
<ide> }
<add>
<add>// Test case for #23973
<add>func (s *DockerSuite) TestRenameContainerWithLinkedContainer(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> db1, _ := dockerCmd(c, "run", "--name", "db1", "-d", "busybox", "top")
<add> dockerCmd(c, "run", "--name", "app1", "-d", "--link", "db1:/mysql", "busybox", "top")
<add> dockerCmd(c, "rename", "app1", "app2")
<add> out, _, err := dockerCmdWithError("inspect", "--format='{{ .Id }}'", "app2/mysql")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(strings.TrimSpace(out), checker.Equals, strings.TrimSpace(db1))
<add>} | 2 |
Java | Java | implement axialgradientview in fabric android | da44010b5904303452f0b03086619474d4b5f5ca | <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
<ide> public class FabricUIManager implements UIManager, LifecycleEventListener {
<ide> sComponentNames.put("ActivityIndicatorView", "AndroidProgressBar");
<ide> sComponentNames.put("ShimmeringView", "RKShimmeringView");
<ide> sComponentNames.put("TemplateView", "RCTTemplateView");
<add> sComponentNames.put("AxialGradientView", "RCTAxialGradientView");
<ide> }
<ide>
<ide> private Binding mBinding; | 1 |
Python | Python | fix init and remove .dvc/plots | 1d2c646e579f0e018e2eed363cc0a0240dde8d47 | <ide><path>spacy/cli/project.py
<ide>
<ide> CONFIG_FILE = "project.yml"
<ide> DVC_CONFIG = "dvc.yaml"
<add>DVC_DIR = ".dvc"
<ide> DIRS = [
<ide> "assets",
<ide> "metas",
<ide> def project_clone_cli(
<ide> def project_init_cli(
<ide> path: Path = Arg(..., help="Path to cloned project", exists=True, file_okay=False),
<ide> git: bool = Opt(False, "--git", "-G", help="Initialize project as a Git repo"),
<add> force: bool = Opt(False, "--force", "-F", help="Force initiziation"),
<ide> ):
<ide> """Initialize a project directory with DVC and optionally Git. This should
<ide> typically be taken care of automatically when you run the "project clone"
<ide> command, but you can also run it separately. If the project is intended to
<ide> be a Git repo, it should be initialized with Git first, before initializing
<ide> DVC. This allows DVC to integrate with Git.
<ide> """
<del> project_init(path, git=git, silent=True)
<add> project_init(path, git=git, force=force, silent=True)
<ide>
<ide>
<ide> @project_cli.command("assets")
<ide> def project_clone(
<ide> if not dir_path.exists():
<ide> dir_path.mkdir(parents=True)
<ide> if not no_init:
<del> project_init(project_dir, git=git, silent=True)
<add> project_init(project_dir, git=git, force=True, silent=True)
<ide> msg.good(f"Your project is now ready!", dest)
<ide> print(f"To fetch the assets, run:\n{COMMAND} project assets {dest}")
<ide>
<ide> def project_init(
<ide> project_dir: Path,
<ide> *,
<ide> git: bool = False,
<add> force: bool = False,
<ide> silent: bool = False,
<ide> analytics: bool = False,
<ide> ):
<ide> def project_init(
<ide> silent (bool): Don't print any output (via DVC).
<ide> analytics (bool): Opt-in to DVC analytics (defaults to False).
<ide> """
<add> project_dir = project_dir.resolve()
<ide> with working_dir(project_dir):
<add> if git:
<add> run_command(["git", "init"])
<ide> init_cmd = ["dvc", "init"]
<ide> if silent:
<ide> init_cmd.append("--quiet")
<ide> if not git:
<ide> init_cmd.append("--no-scm")
<del> if git:
<del> run_command(["git", "init"])
<add> if force:
<add> init_cmd.append("--force")
<ide> run_command(init_cmd)
<ide> # We don't want to have analytics on by default – our users should
<ide> # opt-in explicitly. If they want it, they can always enable it.
<ide> if not analytics:
<ide> run_command(["dvc", "config", "core.analytics", "false"])
<add> # Remove unused and confusing plot templates from .dvc directory
<add> # TODO: maybe we shouldn't do this, but it's otherwise super confusing
<add> # once you commit your changes via Git and it creates a bunch of files
<add> # that have no purpose
<add> plots_dir = project_dir / DVC_DIR / "plots"
<add> if plots_dir.exists():
<add> shutil.rmtree(str(plots_dir))
<ide> config = load_project_config(project_dir)
<ide> setup_check_dvc(project_dir, config)
<ide> | 1 |
Text | Text | add missing examples to examples/readme.md | e2531cb8302b2842c0d3b505f6f619e685c3f4b4 | <ide><path>examples/README.md
<ide> Trains a simple convnet on the MNIST dataset.
<ide> [cifar10_cnn.py](cifar10_cnn.py)
<ide> Trains a simple deep CNN on the CIFAR10 small images dataset.
<ide>
<add>[cifar10_cnn_capsule.py](cifar10_cnn_capsule.py)
<add>Trains a simple CNN-Capsule Network on the CIFAR10 small images dataset.
<add>
<ide> [cifar10_resnet.py](cifar10_resnet.py)
<ide> Trains a ResNet on the CIFAR10 small images dataset.
<ide>
<ide> Trains a Siamese multi-layer perceptron on pairs of digits from the MNIST datase
<ide> Trains a Stacked What-Where AutoEncoder built on residual blocks on the MNIST dataset.
<ide>
<ide> [mnist_transfer_cnn.py](mnist_transfer_cnn.py)
<del>Transfer learning toy example.
<add>Transfer learning toy example on the MNIST dataset.
<add>
<add>[mnist_denoising_autoencoder.py](mnist_denoising_autoencoder.py)
<add>Trains a denoising autoencoder on the MNIST dataset.
<ide>
<ide> ----
<ide>
<ide> Trains an LSTM model on the IMDB sentiment classification task.
<ide> [lstm_stateful.py](lstm_stateful.py)
<ide> Demonstrates how to use stateful RNNs to model long sequences efficiently.
<ide>
<add>[lstm_seq2seq.py](lstm_seq2seq.py)
<add>Trains a basic character-level sequence-to-sequence model.
<add>
<add>[lstm_seq2seq_restore.py](lstm_seq2seq_restore.py)
<add>Restores a character-level sequence to sequence model from disk (saved by [lstm_seq2seq.py](lstm_seq2seq.py)) and uses it to generate predictions.
<add>
<ide> [pretrained_word_embeddings.py](pretrained_word_embeddings.py)
<ide> Loads pre-trained word embeddings (GloVe embeddings) into a frozen Keras Embedding layer, and uses it to train a text classification model on the 20 Newsgroup dataset.
<ide>
<ide> Compares self-normalizing MLPs with regular MLPs.
<ide> MNIST dataset with TFRecords, the standard TensorFlow data format.
<ide>
<ide> [mnist_dataset_api.py](mnist_dataset_api.py)
<del>MNIST dataset with TensorFlow's Dataset API.
<ide>\ No newline at end of file
<add>MNIST dataset with TensorFlow's Dataset API.
<add>
<add>[cifar10_cnn_tfaugment2d.py](cifar10_cnn_tfaugment2d.py)
<add>Trains a simple deep CNN on the CIFAR10 small images dataset using Tensorflow internal augmentation APIs.
<add>
<add>[tensorboard_embeddings_mnist.py](tensorboard_embeddings_mnist.py)
<add>Trains a simple convnet on the MNIST dataset and embeds test data which can be later visualized using TensorBoard's Embedding Projector.
<ide>\ No newline at end of file | 1 |
Python | Python | handle mapped tasks in task duration chart | 8829c079a675a60b78a4bc3a00f91ebe33b27eb6 | <ide><path>airflow/www/views.py
<ide> def duration(self, dag_id, session=None):
<ide>
<ide> y_points = defaultdict(list)
<ide> x_points = defaultdict(list)
<del> cumulative_y = defaultdict(list)
<ide>
<ide> task_instances = dag.get_task_instances_before(base_date, num_runs, session=session)
<ide> if task_instances:
<ide> def duration(self, dag_id, session=None):
<ide> )
<ide> if dag.partial:
<ide> ti_fails = ti_fails.filter(TaskFail.task_id.in_([t.task_id for t in dag.tasks]))
<del>
<ide> fails_totals = defaultdict(int)
<ide> for failed_task_instance in ti_fails:
<ide> dict_key = (
<ide> def duration(self, dag_id, session=None):
<ide> if failed_task_instance.duration:
<ide> fails_totals[dict_key] += failed_task_instance.duration
<ide>
<del> for task_instance in task_instances:
<del> if task_instance.duration:
<del> date_time = wwwutils.epoch(task_instance.execution_date)
<del> x_points[task_instance.task_id].append(date_time)
<del> fails_dict_key = (task_instance.dag_id, task_instance.task_id, task_instance.run_id)
<add> # we must group any mapped TIs by dag_id, task_id, run_id
<add> mapped_tis = set()
<add> tis_grouped = itertools.groupby(task_instances, lambda x: (x.dag_id, x.task_id, x.run_id))
<add> for key, tis in tis_grouped:
<add> tis = list(tis)
<add> duration = sum(x.duration for x in tis if x.duration)
<add> if duration:
<add> first_ti = tis[0]
<add> if first_ti.map_index >= 0:
<add> mapped_tis.add(first_ti.task_id)
<add> date_time = wwwutils.epoch(first_ti.execution_date)
<add> x_points[first_ti.task_id].append(date_time)
<add> fails_dict_key = (first_ti.dag_id, first_ti.task_id, first_ti.run_id)
<ide> fails_total = fails_totals[fails_dict_key]
<del> y_points[task_instance.task_id].append(float(task_instance.duration + fails_total))
<add> y_points[first_ti.task_id].append(float(duration + fails_total))
<ide>
<ide> cumulative_y = {k: list(itertools.accumulate(v)) for k, v in y_points.items()}
<ide>
<ide> def duration(self, dag_id, session=None):
<ide>
<ide> for task_id in x_points:
<ide> chart.add_serie(
<del> name=task_id,
<add> name=task_id + '[]' if task_id in mapped_tis else task_id,
<ide> x=x_points[task_id],
<ide> y=scale_time_units(y_points[task_id], y_unit),
<ide> )
<ide> cum_chart.add_serie(
<del> name=task_id,
<add> name=task_id + '[]' if task_id in mapped_tis else task_id,
<ide> x=x_points[task_id],
<ide> y=scale_time_units(cumulative_y[task_id], cum_y_unit),
<ide> ) | 1 |
Go | Go | remove redundant logs from cp utils | 3ddb4100a052aa556e78fefdf955cf0b7c374d43 | <ide><path>integration-cli/docker_cli_cp_utils_test.go
<ide> func containerCpPathTrailingSep(containerID string, pathElements ...string) stri
<ide>
<ide> func runDockerCp(c *testing.T, src, dst string) error {
<ide> c.Helper()
<del> c.Logf("running `docker cp %s %s`", src, dst)
<ide>
<ide> args := []string{"cp", src, dst}
<ide> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, args...)); err != nil {
<ide> func runDockerCp(c *testing.T, src, dst string) error {
<ide>
<ide> func startContainerGetOutput(c *testing.T, containerID string) (out string, err error) {
<ide> c.Helper()
<del> c.Logf("running `docker start -a %s`", containerID)
<ide>
<ide> args := []string{"start", "-a", containerID}
<ide>
<ide> func isCpCannotCopyReadOnly(err error) bool {
<ide>
<ide> func fileContentEquals(c *testing.T, filename, contents string) error {
<ide> c.Helper()
<del> c.Logf("checking that file %q contains %q\n", filename, contents)
<ide>
<ide> fileBytes, err := ioutil.ReadFile(filename)
<ide> if err != nil {
<ide> func fileContentEquals(c *testing.T, filename, contents string) error {
<ide>
<ide> func symlinkTargetEquals(c *testing.T, symlink, expectedTarget string) error {
<ide> c.Helper()
<del> c.Logf("checking that the symlink %q points to %q\n", symlink, expectedTarget)
<ide>
<ide> actualTarget, err := os.Readlink(symlink)
<ide> if err != nil {
<ide> func symlinkTargetEquals(c *testing.T, symlink, expectedTarget string) error {
<ide>
<ide> func containerStartOutputEquals(c *testing.T, containerID, contents string) error {
<ide> c.Helper()
<del> c.Logf("checking that container %q start output contains %q\n", containerID, contents)
<ide>
<ide> out, err := startContainerGetOutput(c, containerID)
<ide> if err != nil { | 1 |
Python | Python | add test to ensure models can take int64 inputs | f04257fdbcb6ecb5a9bef75f4c2a8d2e8b5a6209 | <ide><path>src/transformers/models/blenderbot/modeling_tf_blenderbot.py
<ide> def call(
<ide> if labels is not None:
<ide> labels = tf.where(
<ide> labels == self.config.pad_token_id,
<del> tf.fill(shape_list(labels), -100),
<add> tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
<ide> labels,
<ide> )
<ide> use_cache = False
<ide><path>src/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py
<ide> def call(
<ide> if labels is not None:
<ide> labels = tf.where(
<ide> labels == self.config.pad_token_id,
<del> tf.fill(shape_list(labels), -100),
<add> tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
<ide> labels,
<ide> )
<ide> use_cache = False
<ide><path>src/transformers/models/flaubert/modeling_tf_flaubert.py
<ide> def get_masks(slen, lengths, causal, padding_mask=None):
<ide> mask = padding_mask
<ide> else:
<ide> # assert lengths.max().item() <= slen
<del> alen = tf.range(slen)
<del> mask = tf.math.less(alen, tf.expand_dims(lengths, axis=1))
<add> alen = tf.range(slen, dtype=lengths.dtype)
<add> mask = alen < tf.expand_dims(lengths, axis=1)
<ide>
<ide> # attention mask is the same as mask, or triangular inferior attention (causal)
<ide> if causal:
<ide><path>src/transformers/models/mbart/modeling_tf_mbart.py
<ide> def call(
<ide> if labels is not None:
<ide> labels = tf.where(
<ide> labels == self.config.pad_token_id,
<del> tf.fill(shape_list(labels), -100),
<add> tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
<ide> labels,
<ide> )
<ide> use_cache = False
<ide><path>src/transformers/models/pegasus/modeling_tf_pegasus.py
<ide> def call(
<ide> if labels is not None:
<ide> labels = tf.where(
<ide> labels == self.config.pad_token_id,
<del> tf.fill(shape_list(labels), -100),
<add> tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
<ide> labels,
<ide> )
<ide> use_cache = False
<ide><path>src/transformers/models/tapas/modeling_tf_tapas.py
<ide> def __init__(self, outer_index, inner_index):
<ide> raise ValueError("outer_index.batch_dims and inner_index.batch_dims " "must be the same.")
<ide>
<ide> super(ProductIndexMap, self).__init__(
<del> indices=(inner_index.indices + outer_index.indices * inner_index.num_segments),
<add> indices=(
<add> inner_index.indices
<add> + outer_index.indices * tf.cast(inner_index.num_segments, inner_index.indices.dtype)
<add> ),
<ide> num_segments=inner_index.num_segments * outer_index.num_segments,
<ide> batch_dims=inner_index.batch_dims,
<ide> )
<ide> def flatten(index, name="segmented_flatten"):
<ide> for _ in range(index.batch_dims, index.indices.shape.rank):
<ide> offset = tf.expand_dims(offset, -1)
<ide>
<del> indices = offset + index.indices
<add> indices = tf.cast(offset, index.indices.dtype) + index.indices
<ide> return IndexMap(indices=tf.reshape(indices, [-1]), num_segments=index.num_segments * batch_size, batch_dims=0)
<ide>
<ide>
<ide><path>src/transformers/models/transfo_xl/modeling_tf_transfo_xl_utilities.py
<ide> def _logit(x, W, b, proj=None):
<ide> @staticmethod
<ide> def _gather_logprob(logprob, target):
<ide> lp_size = shape_list(logprob)
<del> r = tf.range(lp_size[0])
<add> r = tf.range(lp_size[0], dtype=target.dtype)
<ide> idx = tf.stack([r, target], 1)
<ide> return tf.gather_nd(logprob, idx)
<ide>
<ide><path>src/transformers/models/xlm/modeling_tf_xlm.py
<ide> def get_masks(slen, lengths, causal, padding_mask=None):
<ide> mask = padding_mask
<ide> else:
<ide> # assert lengths.max().item() <= slen
<del> alen = tf.range(slen)
<del> mask = tf.math.less(alen, tf.expand_dims(lengths, axis=1))
<add> alen = tf.range(slen, dtype=lengths.dtype)
<add> mask = alen < tf.expand_dims(lengths, axis=1)
<ide>
<ide> # attention mask is the same as mask, or triangular inferior attention (causal)
<ide> if causal:
<ide><path>tests/test_modeling_tf_common.py
<ide> def test_keras_fit(self):
<ide> val_loss2 = history2.history["val_loss"][0]
<ide> self.assertTrue(np.allclose(val_loss1, val_loss2, atol=1e-2, rtol=1e-3))
<ide>
<add> def test_int64_inputs(self):
<add> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
<add> for model_class in self.all_model_classes:
<add> prepared_for_class = self._prepare_for_class(
<add> inputs_dict.copy(),
<add> model_class,
<add> return_labels=True if "labels" in inspect.signature(model_class.call).parameters.keys() else False,
<add> )
<add> if not any(
<add> [tensor.dtype.is_integer for tensor in prepared_for_class.values() if isinstance(tensor, tf.Tensor)]
<add> ):
<add> return # No integer inputs means no need for this test
<add>
<add> prepared_for_class = {
<add> key: tf.cast(tensor, tf.int64) if isinstance(tensor, tf.Tensor) and tensor.dtype.is_integer else tensor
<add> for key, tensor in prepared_for_class.items()
<add> }
<add> model = model_class(config)
<add> model(**prepared_for_class) # No assertion, we're just checking this doesn't throw an error
<add>
<ide> def test_generate_with_headmasking(self):
<ide> attention_names = ["encoder_attentions", "decoder_attentions", "cross_attentions"]
<ide> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() | 9 |
Ruby | Ruby | expect xcode 9.1 on sierra & high sierra | 50c09f8c5737336b124ac53d4996b4f61af1590f | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def latest_version
<ide> when "10.9" then "6.2"
<ide> when "10.10" then "7.2.1"
<ide> when "10.11" then "8.2.1"
<del> when "10.12" then "9.0.1"
<del> when "10.13" then "9.0.1"
<add> when "10.12" then "9.1"
<add> when "10.13" then "9.1"
<ide> else
<ide> raise "macOS '#{MacOS.version}' is invalid" unless OS::Mac.prerelease?
<ide>
<ide> # Default to newest known version of Xcode for unreleased macOS versions.
<del> "9.0.1"
<add> "9.1"
<ide> end
<ide> end
<ide> | 1 |
Text | Text | add info about esm into migration guide. | 80a931ebd3299387e4fdb9b2a80ec2139477fbfc | <ide><path>docs/migration/v4-migration.md
<ide> A number of changes were made to the configuration options passed to the `Chart`
<ide> * The order of the `ChartMeta` parameters have been changed from `<Element, DatasetElement, Type>` to `<Type, Element, DatasetElement>`.
<ide>
<ide> ### General
<add>* Chart.js becomes an [ESM-only package](https://nodejs.org/api/esm.html) ([the UMD bundle is still available](../getting-started/installation.md#cdn)). To use Chart.js, your project should also be an ES module. Make sure to have this in your `package.json`:
<add> ```json
<add> {
<add> "type": "module"
<add> }
<add> ```
<add> If you are experiencing problems with [Jest](https://jestjs.io), follow its [documentation](https://jestjs.io/docs/ecmascript-modules) to enable the ESM support. Or, we can recommend you migrating to [Vitest](https://vitest.dev/). Vitest has the ESM support out of the box and [almost the same API as Jest](https://vitest.dev/guide/migration.html#migrating-from-jest). See an [example of migration](https://github.com/reactchartjs/react-chartjs-2/commit/7f3ec96101d21e43cae8cbfe5e09a46a17cff1ef).
<ide> * Removed fallback to `fontColor` for the legend text and strikethrough color.
<ide> * Removed `config._chart` fallback for `this.chart` in the filler plugin.
<ide> * Removed `this._chart` in the filler plugin. | 1 |
Ruby | Ruby | make application work without tmp directory | 0187053109f62ea0188a76aee53aeee396f76632 | <ide><path>railties/lib/rails/application.rb
<ide> def generate_development_secret
<ide>
<ide> if !File.exist?(key_file)
<ide> random_key = SecureRandom.hex(64)
<add> FileUtils.mkdir_p(key_file.dirname)
<ide> File.binwrite(key_file, random_key)
<ide> end
<ide>
<ide><path>railties/test/application/configuration_test.rb
<ide> def index
<ide> Rails.application.credentials.secret_key_base = nil
<ide> RUBY
<ide>
<add> # For test that works even if tmp dir does not exist.
<add> Dir.chdir(app_path) { FileUtils.remove_dir("tmp") }
<add>
<ide> app "development"
<ide>
<ide> assert_not_nil app.secrets.secret_key_base | 2 |
PHP | PHP | add requested whitespace | c6d4e6a026f087c7a8478753f848a000ea1bb612 | <ide><path>src/Illuminate/Database/Concerns/ManagesTransactions.php
<ide> public function transaction(Closure $callback, $attempts = 1)
<ide> $this->handleTransactionException(
<ide> $e, $currentAttempt, $attempts
<ide> );
<add>
<ide> continue;
<ide> } catch (Throwable $e) {
<ide> $this->rollBack();
<ide> public function transaction(Closure $callback, $attempts = 1)
<ide> $this->handleCommitTransactionException(
<ide> $e, $currentAttempt, $attempts
<ide> );
<add>
<ide> continue;
<ide> }
<ide> | 1 |
Text | Text | fix a typo | 899381575a6038f550a064261ed5c6ba0655211b | <ide><path>docs/api-guide/routers.md
<ide> This behavior can be modified by setting the `trailing_slash` argument to `False
<ide>
<ide> Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.
<ide>
<del>The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_field_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs:
<add>The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs:
<ide>
<ide> class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
<ide> lookup_field = 'my_model_id' | 1 |
PHP | PHP | fix docblock for variadic parameter | 94e7945517387b9bef0851a506436639e4fbbb5c | <ide><path>app/Http/Middleware/RedirectIfAuthenticated.php
<ide> class RedirectIfAuthenticated
<ide> *
<ide> * @param \Illuminate\Http\Request $request
<ide> * @param \Closure $next
<del> * @param string[]|null ...$guards
<add> * @param string|null ...$guards
<ide> * @return mixed
<ide> */
<ide> public function handle($request, Closure $next, ...$guards) | 1 |
Javascript | Javascript | fix removeelclass test in safari 10. | 996507744f064ac7d7747d5059152c624616cfb1 | <ide><path>test/unit/utils/dom.test.js
<ide> QUnit.test('addElClass()', function(assert) {
<ide> QUnit.test('removeElClass()', function(assert) {
<ide> const el = document.createElement('div');
<ide>
<del> el.className = 'test-class foo foo test2_className FOO bar';
<add> el.className = 'test-class test2_className FOO bar';
<ide>
<del> assert.expect(5);
<add> assert.expect(4);
<ide>
<ide> Dom.removeElClass(el, 'test-class');
<del> assert.strictEqual(el.className, 'foo foo test2_className FOO bar', 'removes one class');
<del>
<del> Dom.removeElClass(el, 'foo');
<del> assert.strictEqual(el.className,
<del> 'test2_className FOO bar',
<del> 'removes all instances of a class');
<add> assert.strictEqual(el.className, 'test2_className FOO bar', 'removes one class');
<ide>
<ide> assert.throws(function() {
<ide> Dom.removeElClass(el, 'test2_className bar'); | 1 |
Text | Text | fix links in readme.md | dd3e34e8328b0281186ed74376a3dda8be9bffb6 | <ide><path>README.md
<ide> You'll notice that we used an HTML-like syntax; [we call it JSX](https://reactjs
<ide>
<ide> ## Installation
<ide>
<del>React is available as the `react` package on [npm](https://www.npmjs.com/). It is also available on a [CDN](https://reactjs.org/docs/installation.html#using-a-cdn).
<add>React is available as the `react` package on [npm](https://www.npmjs.com/). It is also available on a [CDN](https://reactjs.org/docs/cdn-links.html).
<ide>
<ide> React is flexible and can be used in a variety of projects. You can create new apps with it, but you can also gradually introduce it into an existing codebase without doing a rewrite.
<ide>
<ide> The recommended way to install React depends on your project. Here you can find short guides for the most common scenarios:
<ide>
<del>* [Trying Out React](https://reactjs.org/docs/installation.html#trying-out-react)
<del>* [Creating a New Application](https://reactjs.org/docs/installation.html#creating-a-new-application)
<del>* [Adding React to an Existing Application](https://reactjs.org/docs/installation.html#adding-react-to-an-existing-application)
<add>* [Trying Out React](https://reactjs.org/docs/try-react.html)
<add>* [Creating a New Application](https://reactjs.org/docs/add-react-to-a-new-app.html)
<add>* [Adding React to an Existing Application](https://reactjs.org/docs/add-react-to-an-existing-app.html)
<ide>
<ide> ## Contributing
<ide> | 1 |
Python | Python | move task tracing to celery.execute.trace | f65ffc17930f52ea2e20757626ac449907eeeb49 | <add><path>celery/execute/__init__.py
<del><path>celery/execute.py
<del>import sys
<del>import inspect
<del>import traceback
<ide> from datetime import datetime, timedelta
<ide>
<del>from billiard.utils.functional import curry
<del>
<ide> from celery import conf
<del>from celery import signals
<del>from celery.utils import gen_unique_id, noop, fun_takes_kwargs, mattrgetter
<add>from celery.utils import gen_unique_id, fun_takes_kwargs, mattrgetter
<ide> from celery.result import AsyncResult, EagerResult
<add>from celery.execute.trace import TaskTrace
<ide> from celery.registry import tasks
<ide> from celery.messaging import TaskPublisher, with_connection
<del>from celery.exceptions import RetryTaskError
<del>from celery.datastructures import ExceptionInfo
<ide>
<ide> extract_exec_options = mattrgetter("routing_key", "exchange",
<del> "immediate", "mandatory",
<del> "priority", "serializer")
<add> "immediate", "mandatory",
<add> "priority", "serializer")
<ide>
<ide>
<ide> @with_connection
<ide> def apply(task, args, kwargs, **options):
<ide> task_id = gen_unique_id()
<ide> retries = options.get("retries", 0)
<ide>
<del> # If it's a Task class we need to instantiate it, so it's callable.
<del> task = inspect.isclass(task) and task() or task
<add> task = tasks[task.name] # Make sure we get the instance, not class.
<ide>
<ide> default_kwargs = {"task_name": task.name,
<ide> "task_id": task_id,
<ide> def apply(task, args, kwargs, **options):
<ide>
<ide> trace = TaskTrace(task.name, task_id, args, kwargs, task=task)
<ide> retval = trace.execute()
<del>
<del> return EagerResult(task_id, retval, trace.status,
<del> traceback=trace.strtb)
<del>
<del>
<del>class TraceInfo(object):
<del> def __init__(self, status="PENDING", retval=None, exc_info=None):
<del> self.status = status
<del> self.retval = retval
<del> self.exc_info = exc_info
<del> self.exc_type = None
<del> self.exc_value = None
<del> self.tb = None
<del> self.strtb = None
<del> if self.exc_info:
<del> self.exc_type, self.exc_value, self.tb = exc_info
<del> self.strtb = "\n".join(traceback.format_exception(*exc_info))
<del>
<del> @classmethod
<del> def trace(cls, fun, args, kwargs):
<del> """Trace the execution of a function, calling the appropiate callback
<del> if the function raises retry, an failure or returned successfully."""
<del> try:
<del> return cls("SUCCESS", retval=fun(*args, **kwargs))
<del> except (SystemExit, KeyboardInterrupt):
<del> raise
<del> except RetryTaskError, exc:
<del> return cls("RETRY", retval=exc, exc_info=sys.exc_info())
<del> except Exception, exc:
<del> return cls("FAILURE", retval=exc, exc_info=sys.exc_info())
<del>
<del>
<del>class TaskTrace(object):
<del>
<del> def __init__(self, task_name, task_id, args, kwargs, task=None):
<del> self.task_id = task_id
<del> self.task_name = task_name
<del> self.args = args
<del> self.kwargs = kwargs
<del> self.task = task or tasks[self.task_name]
<del> self.status = "PENDING"
<del> self.strtb = None
<del> self._trace_handlers = {"FAILURE": self.handle_failure,
<del> "RETRY": self.handle_retry,
<del> "SUCCESS": self.handle_success}
<del>
<del> def __call__(self):
<del> return self.execute()
<del>
<del> def execute(self):
<del> signals.task_prerun.send(sender=self.task, task_id=self.task_id,
<del> task=self.task, args=self.args,
<del> kwargs=self.kwargs)
<del> retval = self._trace()
<del>
<del> signals.task_postrun.send(sender=self.task, task_id=self.task_id,
<del> task=self.task, args=self.args,
<del> kwargs=self.kwargs, retval=retval)
<del> return retval
<del>
<del> def _trace(self):
<del> trace = TraceInfo.trace(self.task, self.args, self.kwargs)
<del> self.status = trace.status
<del> self.strtb = trace.strtb
<del> handler = self._trace_handlers[trace.status]
<del> return handler(trace.retval, trace.exc_type, trace.tb, trace.strtb)
<del>
<del> def handle_success(self, retval, *args):
<del> """Handle successful execution."""
<del> self.task.on_success(retval, self.task_id, self.args, self.kwargs)
<del> return retval
<del>
<del> def handle_retry(self, exc, type_, tb, strtb):
<del> """Handle retry exception."""
<del> self.task.on_retry(exc, self.task_id, self.args, self.kwargs)
<del>
<del> # Create a simpler version of the RetryTaskError that stringifies
<del> # the original exception instead of including the exception instance.
<del> # This is for reporting the retry in logs, e-mail etc, while
<del> # guaranteeing pickleability.
<del> message, orig_exc = exc.args
<del> expanded_msg = "%s: %s" % (message, str(orig_exc))
<del> return ExceptionInfo((type_,
<del> type_(expanded_msg, None),
<del> tb))
<del>
<del> def handle_failure(self, exc, type_, tb, strtb):
<del> """Handle exception."""
<del> self.task.on_failure(exc, self.task_id, self.args, self.kwargs)
<del> return ExceptionInfo((type_, exc, tb))
<add> return EagerResult(task_id, retval, trace.status, traceback=trace.strtb)
<ide><path>celery/execute/trace.py
<add>import sys
<add>import traceback
<add>
<add>from celery import signals
<add>from celery.registry import tasks
<add>from celery.exceptions import RetryTaskError
<add>from celery.datastructures import ExceptionInfo
<add>
<add>
<add>class TraceInfo(object):
<add> def __init__(self, status="PENDING", retval=None, exc_info=None):
<add> self.status = status
<add> self.retval = retval
<add> self.exc_info = exc_info
<add> self.exc_type = None
<add> self.exc_value = None
<add> self.tb = None
<add> self.strtb = None
<add> if self.exc_info:
<add> self.exc_type, self.exc_value, self.tb = exc_info
<add> self.strtb = "\n".join(traceback.format_exception(*exc_info))
<add>
<add> @classmethod
<add> def trace(cls, fun, args, kwargs):
<add> """Trace the execution of a function, calling the appropiate callback
<add> if the function raises retry, an failure or returned successfully."""
<add> try:
<add> return cls("SUCCESS", retval=fun(*args, **kwargs))
<add> except (SystemExit, KeyboardInterrupt):
<add> raise
<add> except RetryTaskError, exc:
<add> return cls("RETRY", retval=exc, exc_info=sys.exc_info())
<add> except Exception, exc:
<add> return cls("FAILURE", retval=exc, exc_info=sys.exc_info())
<add>
<add>
<add>class TaskTrace(object):
<add>
<add> def __init__(self, task_name, task_id, args, kwargs, task=None):
<add> self.task_id = task_id
<add> self.task_name = task_name
<add> self.args = args
<add> self.kwargs = kwargs
<add> self.task = task or tasks[self.task_name]
<add> self.status = "PENDING"
<add> self.strtb = None
<add> self._trace_handlers = {"FAILURE": self.handle_failure,
<add> "RETRY": self.handle_retry,
<add> "SUCCESS": self.handle_success}
<add>
<add> def __call__(self):
<add> return self.execute()
<add>
<add> def execute(self):
<add> signals.task_prerun.send(sender=self.task, task_id=self.task_id,
<add> task=self.task, args=self.args,
<add> kwargs=self.kwargs)
<add> retval = self._trace()
<add>
<add> signals.task_postrun.send(sender=self.task, task_id=self.task_id,
<add> task=self.task, args=self.args,
<add> kwargs=self.kwargs, retval=retval)
<add> return retval
<add>
<add> def _trace(self):
<add> trace = TraceInfo.trace(self.task, self.args, self.kwargs)
<add> self.status = trace.status
<add> self.strtb = trace.strtb
<add> handler = self._trace_handlers[trace.status]
<add> return handler(trace.retval, trace.exc_type, trace.tb, trace.strtb)
<add>
<add> def handle_success(self, retval, *args):
<add> """Handle successful execution."""
<add> self.task.on_success(retval, self.task_id, self.args, self.kwargs)
<add> return retval
<add>
<add> def handle_retry(self, exc, type_, tb, strtb):
<add> """Handle retry exception."""
<add> self.task.on_retry(exc, self.task_id, self.args, self.kwargs)
<add>
<add> # Create a simpler version of the RetryTaskError that stringifies
<add> # the original exception instead of including the exception instance.
<add> # This is for reporting the retry in logs, e-mail etc, while
<add> # guaranteeing pickleability.
<add> message, orig_exc = exc.args
<add> expanded_msg = "%s: %s" % (message, str(orig_exc))
<add> return ExceptionInfo((type_,
<add> type_(expanded_msg, None),
<add> tb))
<add>
<add> def handle_failure(self, exc, type_, tb, strtb):
<add> """Handle exception."""
<add> self.task.on_failure(exc, self.task_id, self.args, self.kwargs)
<add> return ExceptionInfo((type_, exc, tb))
<ide><path>celery/worker/job.py
<ide> from celery.log import get_default_logger
<ide> from celery.utils import noop, fun_takes_kwargs
<ide> from celery.loaders import current_loader
<del>from celery.execute import TaskTrace
<add>from celery.execute.trace import TaskTrace
<ide> from celery.registry import tasks
<ide> from celery.datastructures import ExceptionInfo
<ide>
<ide> def __init__(self, *args, **kwargs):
<ide> self._store_errors = True
<ide> if self.task.ignore_result:
<ide> self._store_errors = conf.STORE_ERRORS_EVEN_IF_IGNORED
<add> self.super = super(WorkerTaskTrace, self)
<ide>
<ide> def execute_safe(self, *args, **kwargs):
<add> """Same as :meth:`execute`, but catches errors."""
<ide> try:
<ide> return self.execute(*args, **kwargs)
<ide> except Exception, exc:
<del> type_, value_, tb = sys.exc_info()
<del> exc = self.task.backend.prepare_exception(exc)
<del> warnings.warn("Exception happend outside of task body: %s: %s" % (
<del> str(exc.__class__), str(exc)))
<del> return ExceptionInfo((type_, exc, tb))
<add> exc_info = sys.exc_info()
<add> exc_info[1] = self.task_backend.prepare_exception(exc)
<add> exc_info = ExceptionInfo(exc_info)
<add> warnings.warn("Exception outside body: %s: %s\n%s" % tuple(
<add> map(str, (exc.__class__, exc, exc_info.traceback))))
<add> return exc_info
<ide>
<ide> def execute(self):
<del> # Run task loader init handler.
<add> """Execute, trace and store the result of the task."""
<ide> self.loader.on_task_init(self.task_id, self.task)
<del>
<del> # Backend process cleanup
<ide> self.task.backend.process_cleanup()
<del>
<ide> return self._trace()
<ide>
<ide> def handle_success(self, retval, *args):
<del> """Handle successful execution.
<del>
<del> Saves the result to the current result store (skipped if the task's
<del> ``ignore_result`` attribute is set to ``True``).
<del>
<del> """
<add> """Handle successful execution."""
<ide> if not self.task.ignore_result:
<ide> self.task.backend.mark_as_done(self.task_id, retval)
<del> return super(WorkerTaskTrace, self).handle_success(retval, *args)
<add> return self.super.handle_success(retval, *args)
<ide>
<ide> def handle_retry(self, exc, type_, tb, strtb):
<ide> """Handle retry exception."""
<ide> message, orig_exc = exc.args
<ide> if self._store_errors:
<ide> self.task.backend.mark_as_retry(self.task_id, orig_exc, strtb)
<del> return super(WorkerTaskTrace, self).handle_retry(exc, type_,
<del> tb, strtb)
<add> return self.super.handle_retry(exc, type_, tb, strtb)
<ide>
<ide> def handle_failure(self, exc, type_, tb, strtb):
<ide> """Handle exception."""
<ide> if self._store_errors:
<del> # mark_as_failure returns an exception that is guaranteed to
<del> # be pickleable.
<ide> exc = self.task.backend.mark_as_failure(self.task_id, exc, strtb)
<ide> else:
<ide> exc = self.task.backend.prepare_exception(exc)
<del>
<del> return super(WorkerTaskTrace, self).handle_failure(
<del> exc, type_, tb, strtb)
<add> return self.super.handle_failure(exc, type_, tb, strtb)
<ide>
<ide>
<ide> def execute_and_trace(task_name, *args, **kwargs): | 3 |
Go | Go | ensure mount in commit | f385f1860bdebe2434bb122bd5ac8fec85687970 | <ide><path>builder.go
<ide> func (builder *Builder) Create(config *Config) (*Container, error) {
<ide> func (builder *Builder) Commit(container *Container, repository, tag, comment, author string, config *Config) (*Image, error) {
<ide> // FIXME: freeze the container before copying it to avoid data corruption?
<ide> // FIXME: this shouldn't be in commands.
<add> if err := container.EnsureMounted(); err != nil {
<add> return nil, err
<add> }
<add>
<ide> rwTar, err := container.ExportRw()
<ide> if err != nil {
<ide> return nil, err | 1 |
PHP | PHP | add tests for type + method conditions | a203d67ee85ed2bf0c5fa494e6dd362b7ca0921b | <ide><path>lib/Cake/Routing/Route/Route.php
<ide> public function compiled() {
<ide> }
<ide>
<ide> /**
<del> * Compiles the route's regular expression. Modifies defaults property so all necessary keys are set
<del> * and populates $this->names with the named routing elements.
<add> * Compiles the route's regular expression. Modifies defaults property so all necessary
<add> * keys are set and populates $this->names with the named routing elements.
<ide> *
<ide> * @return array Returns a string regular expression of the compiled route.
<ide> */
<ide><path>lib/Cake/Test/TestCase/Routing/Route/RouteTest.php
<ide> public function testParseWithPassDefaults() {
<ide> */
<ide> public function testParseWithHttpHeaderConditions() {
<ide> $_SERVER['REQUEST_METHOD'] = 'GET';
<del> $route = new Route('/sample', array('controller' => 'posts', 'action' => 'index', '[method]' => 'POST'));
<add> $route = new Route('/sample', ['controller' => 'posts', 'action' => 'index', '[method]' => 'POST']);
<add> $this->assertFalse($route->parse('/sample'));
<add>
<add> $_SERVER['REQUEST_METHOD'] = 'POST';
<add> $expected = [
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> 'pass' => [],
<add> '[method]' => 'POST',
<add> ];
<add> $this->assertEquals($expected, $route->parse('/sample'));
<ide>
<add> }
<add>
<add>/**
<add> * test that http header conditions can cause route failures.
<add> *
<add> * @return void
<add> */
<add> public function testParseWithMultipleHttpMethodConditions() {
<add> $_SERVER['REQUEST_METHOD'] = 'GET';
<add> $route = new Route('/sample', [
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> '[method]' => ['PUT', 'POST']
<add> ]);
<ide> $this->assertFalse($route->parse('/sample'));
<add>
<add> $_SERVER['REQUEST_METHOD'] = 'POST';
<add> $expected = [
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> 'pass' => [],
<add> '[method]' => ['PUT', 'POST'],
<add> ];
<add> $this->assertEquals($expected, $route->parse('/sample'));
<add> }
<add>
<add>
<add>/**
<add> * Test that the [type] condition works.
<add> *
<add> * @return void
<add> */
<add> public function testParseWithContentTypeCondition() {
<add> $_SERVER['REQUEST_METHOD'] = 'POST';
<add> unset($_SERVER['CONTENT_TYPE']);
<add> $route = new Route('/sample', [
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> '[method]' => 'POST',
<add> '[type]' => 'application/xml'
<add> ]);
<add> $this->assertFalse($route->parse('/sample'), 'No content type set.');
<add>
<add> $_SERVER['REQUEST_METHOD'] = 'POST';
<add> $_SERVER['CONTENT_TYPE'] = 'application/json';
<add> $this->assertFalse($route->parse('/sample'), 'Wrong content type set.');
<add>
<add> $_SERVER['REQUEST_METHOD'] = 'POST';
<add> $_SERVER['CONTENT_TYPE'] = 'application/xml';
<add> $expected = [
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> 'pass' => [],
<add> '[method]' => 'POST',
<add> '[type]' => 'application/xml',
<add> ];
<add> $this->assertEquals($expected, $route->parse('/sample'));
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | improve code coverage for string decoder | 5673017c33c96a20c39cd5deb70714a41267d029 | <ide><path>test/parallel/test-string-decoder.js
<ide> common.expectsError(
<ide> }
<ide> );
<ide>
<add>common.expectsError(
<add> () => new StringDecoder('utf8').write(null),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "buf" argument must be one of type Buffer, Uint8Array, or' +
<add> ' ArrayBufferView. Received type object'
<add> }
<add>);
<add>
<ide> // test verifies that StringDecoder will correctly decode the given input
<ide> // buffer with the given encoding to the expected output. It will attempt all
<ide> // possible ways to write() the input buffer, see writeSequences(). The | 1 |
Text | Text | remove obsolete cc recommendations | 593212cd2ca52ee84b17de9b636a56262efed67a | <ide><path>doc/guides/maintaining-V8.md
<ide> fixed upstream first.
<ide> ### Backporting to active branches
<ide>
<ide> If the bug exists in any of the active V8 branches, we may need to get the fix
<del>backported. At any given time there are [two active branches][V8ActiveBranches]
<add>backported. At any given time, there are [two active branches][V8ActiveBranches]
<ide> (beta and stable) in addition to master. The following steps are needed to
<ide> backport the fix:
<ide>
<ide> backport the fix:
<ide> * If a bug already exists
<ide> * Add a reference to the GitHub issue.
<ide> * Attach *merge-request-x.x* labels to the bug for any active branches
<del> that still contain the bug. (e.g. merge-request-5.3,
<del> merge-request-5.4)
<del> * Add ofrobots-at-google.com to the cc list.
<add> that still contain the bug.
<ide> * Once the merge has been approved, it should be merged using the
<ide> [merge script documented in the V8 wiki][V8MergingPatching]. Merging requires
<ide> commit access to the V8 repository. If you don't have commit access you can
<ide> fix needed to be cherry-picked. To cherry-pick, here's an example workflow:
<ide> not apply cleanly. It may help to try to cherry-pick the merge to the oldest
<ide> branch that was done upstream in V8. In this example, this would be the patch
<ide> from the merge to 5.2. The hope is that this would be closer to the V8 5.1,
<del> and has a better chance of applying cleanly. If you're stuck, feel free to
<del> ping @ofrobots for help.
<add> and has a better chance of applying cleanly.
<ide> * Modify the commit message to match the format we use for V8 backports and
<ide> replace yourself as the author. `git commit --amend --reset-author`. You may
<ide> want to add extra description if necessary to indicate the impact of the fix | 1 |
Text | Text | add documentation for request.path | 32c7ad6c67dec241daf30201db757d14a4cd9ff6 | <ide><path>doc/api/http.md
<ide> const cookie = request.getHeader('Cookie');
<ide>
<ide> Limits maximum response headers count. If set to 0, no limit will be applied.
<ide>
<add>### request.path
<add><!-- YAML
<add>added: v0.4.0
<add>-->
<add>
<add>* {string} The request path. Read-only.
<add>
<ide> ### request.removeHeader(name)
<ide> <!-- YAML
<ide> added: v1.6.0 | 1 |
Text | Text | add metadata to be indexed properly | 25e29150a26383cc8ce9c5e73de3650f13407ba4 | <ide><path>model_cards/mrm8488/RuPERTa-base-finetuned-squadv1/README.md
<add>---
<add>language: es
<add>datasets:
<add>- squad
<add>--- | 1 |
Javascript | Javascript | fix manifest build order | dd4589dd6f28ce0953eb95a91c6839d4c590d298 | <ide><path>gulpfile.js
<ide> function delRev(dest, manifestName) {
<ide> });
<ide> }
<ide>
<del>gulp.task('serve', function(cb) {
<add>gulp.task('serve', ['build-manifest'], function(cb) {
<ide> var called = false;
<ide> nodemon({
<ide> script: paths.server,
<ide> function buildManifest() {
<ide> .pipe(gulp.dest('server/'));
<ide> }
<ide>
<del>var buildDependents = ['less', 'js', 'dependents'];
<add>var buildDependents = ['less', 'js', 'dependents', 'pack-watch-manifest'];
<ide>
<ide> gulp.task('build-manifest', buildDependents, function() {
<ide> return buildManifest();
<ide> var watchDependents = [
<ide> 'dependents',
<ide> 'serve',
<ide> 'sync',
<del> 'build-manifest',
<ide> 'pack-watch',
<del> 'pack-watch-manifest'
<add> 'pack-watch-manifest',
<add> 'build-manifest'
<ide> ];
<ide>
<ide> gulp.task('reload', function() {
<ide> gulp.task('default', [
<ide> 'serve',
<ide> 'pack-watch',
<ide> 'pack-watch-manifest',
<add> 'build-manifest-watch',
<ide> 'watch',
<ide> 'sync'
<ide> ]); | 1 |
PHP | PHP | remove unneeded variable assignment | 76a94cc966696c23b948d9d67286e879e16ba0d5 | <ide><path>src/Http/Client.php
<ide> protected function _mergeOptions(array $options): array
<ide> */
<ide> public function sendRequest(RequestInterface $request): ResponseInterface
<ide> {
<del> return $response = $this->send($request, $this->_config);
<add> return $this->send($request, $this->_config);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | remove useless debug | 8adce2eafa6878fdec15564b51085ef8fa5ad985 | <ide><path>glances/outputs/glances_curses.py
<ide> def __catch_key(self, return_to_browser=False):
<ide> self.args.disable_mem = False
<ide> self.args.disable_swap = False
<ide> elif self.pressedkey == ord('5'):
<del> logger.info("press 5")
<ide> # '5' > Enable/disable top menu
<ide> logger.info(self.args.disable_top )
<ide> self.args.disable_top = not self.args.disable_top | 1 |
Ruby | Ruby | remove dead file_watcher code | 6c9669e8f0553a6d5d67cf64ba2273f527a2072a | <ide><path>activesupport/lib/active_support/file_watcher.rb
<del>module ActiveSupport
<del> class FileWatcher
<del> class Backend
<del> def initialize(path, watcher)
<del> @watcher = watcher
<del> @path = path
<del> end
<del>
<del> def trigger(files)
<del> @watcher.trigger(files)
<del> end
<del> end
<del>
<del> def initialize
<del> @regex_matchers = {}
<del> end
<del>
<del> def watch(pattern, &block)
<del> @regex_matchers[pattern] = block
<del> end
<del>
<del> def trigger(files)
<del> trigger_files = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } }
<del>
<del> files.each do |file, state|
<del> @regex_matchers.each do |pattern, block|
<del> trigger_files[block][state] << file if pattern === file
<del> end
<del> end
<del>
<del> trigger_files.each do |block, payload|
<del> block.call payload
<del> end
<del> end
<del> end
<del>end | 1 |
Javascript | Javascript | restore enumeration behavior in isplainobject | 00575d4d8c7421c5119f181009374ff2e7736127 | <ide><path>src/core.js
<ide> jQuery.extend( {
<ide> },
<ide>
<ide> isPlainObject: function( obj ) {
<add> var key;
<ide>
<ide> // Not plain objects:
<ide> // - Any object or value whose internal [[Class]] property is not "[object Object]"
<ide> jQuery.extend( {
<ide> return false;
<ide> }
<ide>
<del> // If the function hasn't returned already, we're confident that
<del> // |obj| is a plain object, created by {} or constructed with new Object
<del> return true;
<add> // Own properties are enumerated firstly, so to speed up,
<add> // if last one is own, then all properties are own
<add> for ( key in obj ) {}
<add>
<add> return key === undefined || hasOwn.call( obj, key );
<ide> },
<ide>
<ide> isEmptyObject: function( obj ) {
<ide><path>test/unit/core.js
<ide> QUnit.test( "type for `Symbol`", function( assert ) {
<ide> });
<ide>
<ide> QUnit.asyncTest( "isPlainObject", function( assert ) {
<del> assert.expect( 15 );
<add> assert.expect( 19 );
<ide>
<del> var pass, iframe, doc,
<add> var pass, iframe, doc, parentObj, childObj, deep,
<ide> fn = function() {};
<ide>
<ide> // The use case that we want to match
<ide> assert.ok( jQuery.isPlainObject( {} ), "{}" );
<add> assert.ok( jQuery.isPlainObject( new window.Object() ), "new Object" );
<add>
<add> parentObj = { foo: "bar" };
<add> childObj = Object.create( parentObj );
<add>
<add> assert.ok( !jQuery.isPlainObject( childObj ), "isPlainObject(Object.create({}))" );
<add> childObj.bar = "foo";
<add> assert.ok( !jQuery.isPlainObject( childObj ), "isPlainObject(Object.create({}))" );
<ide>
<ide> // Not objects shouldn't be matched
<ide> assert.ok( !jQuery.isPlainObject( "" ), "string" );
<ide> QUnit.asyncTest( "isPlainObject", function( assert ) {
<ide> // Again, instantiated objects shouldn't be matched
<ide> assert.ok( !jQuery.isPlainObject( new fn() ), "new fn" );
<ide>
<add> // Deep object
<add> deep = { "foo": { "baz": true }, "foo2": document };
<add> assert.ok( jQuery.isPlainObject( deep ), "Object with objects is still plain" );
<add>
<ide> // DOM Element
<ide> assert.ok( !jQuery.isPlainObject( document.createElement( "div" ) ), "DOM Element" );
<ide> | 2 |
Ruby | Ruby | enforce https for *.sourceforge.io urls | a09169f248de707bf8121acfb6c5d5c2b92c58de | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_homepage
<ide> # People will run into mixed content sometimes, but we should enforce and then add
<ide> # exemptions as they are discovered. Treat mixed content on homepages as a bug.
<ide> # Justify each exemptions with a code comment so we can keep track here.
<del> if homepage =~ %r{^http://[^/]*github\.io/}
<add> case homepage
<add> when %r{^http://[^/]*github\.io/},
<add> %r{^http://[^/]*\.sourceforge\.io/}
<ide> problem "Please use https:// for #{homepage}"
<ide> end
<ide> | 1 |
Python | Python | implement spatial dropout | 458edeed9a9010f1ba6184ae40b474181a606502 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def tanh(x):
<ide> return tf.nn.tanh(x)
<ide>
<ide>
<del>def dropout(x, level, seed=None):
<add>def dropout(x, level, noise_shape=None, seed=None):
<ide> '''Sets entries in `x` to zero at random,
<ide> while scaling the entire tensor.
<ide>
<ide> # Arguments
<ide> x: tensor
<ide> level: fraction of the entries in the tensor
<del> that will be set to 0
<add> that will be set to 0.
<add> noise_shape: shape for randomly generated keep/drop flags,
<add> must be broadcastable to the shape of `x`
<ide> seed: random seed to ensure determinism.
<ide> '''
<ide> retain_prob = 1. - level
<ide> if seed is None:
<ide> seed = np.random.randint(10e6)
<ide> # the dummy 1. works around a TF bug
<ide> # (float32_ref vs. float32 incomptability)
<del> return tf.nn.dropout(x * 1., retain_prob, seed=seed)
<add> return tf.nn.dropout(x * 1., retain_prob, noise_shape, seed=seed)
<ide>
<ide>
<ide> def l2_normalize(x, axis):
<ide><path>keras/backend/theano_backend.py
<ide> def tanh(x):
<ide> return T.tanh(x)
<ide>
<ide>
<del>def dropout(x, level, seed=None):
<add>def dropout(x, level, noise_shape=None, seed=None):
<add> '''Sets entries in `x` to zero at random,
<add> while scaling the entire tensor.
<add>
<add> # Arguments
<add> x: tensor
<add> level: fraction of the entries in the tensor
<add> that will be set to 0.
<add> noise_shape: shape for randomly generated keep/drop flags,
<add> must be broadcastable to the shape of `x`
<add> seed: random seed to ensure determinism.
<add> '''
<ide> if level < 0. or level >= 1:
<ide> raise Exception('Dropout level must be in interval [0, 1[.')
<ide> if seed is None:
<ide> seed = np.random.randint(1, 10e6)
<add>
<ide> rng = RandomStreams(seed=seed)
<ide> retain_prob = 1. - level
<del> x *= rng.binomial(x.shape, p=retain_prob, dtype=x.dtype)
<add>
<add> if noise_shape is None:
<add> random_tensor = rng.binomial(x.shape, p=retain_prob, dtype=x.dtype)
<add> else:
<add> random_tensor = rng.binomial(noise_shape, p=retain_prob, dtype=x.dtype)
<add> random_tensor = T.patternbroadcast(random_tensor, [dim == 1 for dim in noise_shape])
<add>
<add> x *= random_tensor
<ide> x /= retain_prob
<ide> return x
<ide>
<ide><path>keras/layers/core.py
<ide> def __init__(self, p, **kwargs):
<ide> self.supports_masking = True
<ide> super(Dropout, self).__init__(**kwargs)
<ide>
<add> def _get_noise_shape(self, x):
<add> return None
<add>
<ide> def call(self, x, mask=None):
<ide> if 0. < self.p < 1.:
<del> x = K.in_train_phase(K.dropout(x, level=self.p), x)
<add> noise_shape = self._get_noise_shape(x)
<add> x = K.in_train_phase(K.dropout(x, self.p, noise_shape), x)
<ide> return x
<ide>
<ide> def get_config(self):
<ide> def get_config(self):
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide>
<add>class SpatialDropout2D(Dropout):
<add> '''This version performs the same function as Dropout, however it drops
<add> entire 2D feature maps instead of individual elements. If adjacent pixels
<add> within feature maps are strongly correlated (as is normally the case in
<add> early convolution layers) then regular dropout will not regularize the
<add> activations and will otherwise just result in an effective learning rate
<add> decrease. In this case, SpatialDropout2D will help promote independence
<add> between feature maps and should be used instead.
<add>
<add> # Arguments
<add> p: float between 0 and 1. Fraction of the input units to drop.
<add> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<add> (the depth) is at index 1, in 'tf' mode is it at index 3.
<add> It defaults to the `image_dim_ordering` value found in your
<add> Keras config file at `~/.keras/keras.json`.
<add> If you never set it, then it will be "th".
<add>
<add> # Input shape
<add> 4D tensor with shape:
<add> `(samples, channels, rows, cols)` if dim_ordering='th'
<add> or 4D tensor with shape:
<add> `(samples, rows, cols, channels)` if dim_ordering='tf'.
<add>
<add> # Output shape
<add> Same as input
<add>
<add> # References
<add> - [Efficient Object Localization Using Convolutional Networks](https://arxiv.org/pdf/1411.4280.pdf)
<add> '''
<add> def __init__(self, p, dim_ordering='default', **kwargs):
<add> if dim_ordering == 'default':
<add> dim_ordering = K.image_dim_ordering()
<add> assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}'
<add> self.dim_ordering = dim_ordering
<add> super(SpatialDropout2D, self).__init__(p, **kwargs)
<add>
<add> def _get_noise_shape(self, x):
<add> input_shape = K.shape(x)
<add> if self.dim_ordering == 'th':
<add> noise_shape = (input_shape[0], input_shape[1], 1, 1)
<add> elif self.dim_ordering == 'tf':
<add> noise_shape = (input_shape[0], 1, 1, input_shape[3])
<add> else:
<add> raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
<add>
<add> return noise_shape
<add>
<add>class SpatialDropout3D(Dropout):
<add> '''This version performs the same function as Dropout, however it drops
<add> entire 3D feature maps instead of individual elements. If adjacent voxels
<add> within feature maps are strongly correlated (as is normally the case in
<add> early convolution layers) then regular dropout will not regularize the
<add> activations and will otherwise just result in an effective learning rate
<add> decrease. In this case, SpatialDropout3D will help promote independence
<add> between feature maps and should be used instead.
<add>
<add> # Arguments
<add> p: float between 0 and 1. Fraction of the input units to drop.
<add> dim_ordering: 'th' or 'tf'.
<add> In 'th' mode, the channels dimension (the depth)
<add> is at index 1, in 'tf' mode is it at index 4.
<add> It defaults to the `image_dim_ordering` value found in your
<add> Keras config file at `~/.keras/keras.json`.
<add> If you never set it, then it will be "th".
<add>
<add> # Input shape
<add> 5D tensor with shape:
<add> `(samples, channels, dim1, dim2, dim3)` if dim_ordering='th'
<add> or 5D tensor with shape:
<add> `(samples, dim1, dim2, dim3, channels)` if dim_ordering='tf'.
<add>
<add> # Output shape
<add> Same as input
<add>
<add> # References
<add> - [Efficient Object Localization Using Convolutional Networks](https://arxiv.org/pdf/1411.4280.pdf)
<add> '''
<add> def __init__(self, p, dim_ordering='default', **kwargs):
<add> if dim_ordering == 'default':
<add> dim_ordering = K.image_dim_ordering()
<add> assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}'
<add> self.dim_ordering = dim_ordering
<add> super(SpatialDropout3D, self).__init__(p, **kwargs)
<add>
<add> def _get_noise_shape(self, x):
<add> input_shape = K.shape(x)
<add> if self.dim_ordering == 'th':
<add> noise_shape = (input_shape[0], input_shape[1], 1, 1, 1)
<add> elif self.dim_ordering == 'tf':
<add> noise_shape = (input_shape[0], 1, 1, 1, input_shape[4])
<add> else:
<add> raise Exception('Invalid dim_ordering: ' + self.dim_ordering)
<add>
<add> return noise_shape
<add>
<add>
<ide> class Activation(Layer):
<ide> '''Applies an activation function to an output.
<ide>
<ide><path>tests/keras/layers/test_core.py
<ide> def test_merge_mask_2d():
<ide> # test concatenation with masked and non-masked inputs
<ide> model_concat = Model([input_a, input_b], [merged_concat_mixed])
<ide> model_concat.compile(loss='mse', optimizer='sgd')
<del> model_concat.fit([rand(2,3), rand(2,3)], [rand(2,6)], nb_epoch=1)
<add> model_concat.fit([rand(2, 3), rand(2, 3)], [rand(2, 6)], nb_epoch=1)
<add>
<ide>
<ide> @keras_test
<ide> def test_merge_mask_3d():
<ide> def test_dropout():
<ide> kwargs={'p': 0.5},
<ide> input_shape=(3, 2))
<ide>
<add> layer_test(core.SpatialDropout2D,
<add> kwargs={'p': 0.5},
<add> input_shape=(2, 3, 4, 5))
<add>
<add> layer_test(core.SpatialDropout3D,
<add> kwargs={'p': 0.5},
<add> input_shape=(2, 3, 4, 5, 6))
<add>
<ide>
<ide> @keras_test
<ide> def test_activation(): | 4 |
Ruby | Ruby | move pathname.starts_with? into pathname | 013fe4bf38d0ae950fe6a14e8b70ee74370fc3eb | <ide><path>Library/Contributions/examples/brew-which.rb
<ide> REAL_CELLAR = HOMEBREW_CELLAR.realpath
<ide>
<ide> class String
<del> def starts_with?(prefix)
<add> def starts_with? prefix
<ide> prefix = prefix.to_s
<ide> self[0, prefix.length] == prefix
<ide> end
<ide> end
<ide>
<del>class Pathname
<del> def starts_with?(prefix)
<del> prefix = prefix.to_s
<del> self.to_s[0, prefix.length] == prefix
<del> end
<del>end
<del>
<ide>
<ide> def audit
<ide> brew_links = Array.new
<ide><path>Library/Homebrew/extend/pathname.rb
<ide> def resolved_path
<ide> def resolved_path_exists?
<ide> (dirname+readlink).exist?
<ide> end
<add>
<add> def starts_with? prefix
<add> prefix = prefix.to_s
<add> self.to_s[0, prefix.length] == prefix
<add> end
<ide> end
<ide>
<ide> # sets $n and $d so you can observe creation of stuff | 2 |
Text | Text | expand fs.access() mode parameter docs | 91b9052c4ea4643ebdc94e35445d258855e4ee76 | <ide><path>doc/api/fs.md
<ide> added: v10.0.0
<ide>
<ide> Tests a user's permissions for the file or directory specified by `path`.
<ide> The `mode` argument is an optional integer that specifies the accessibility
<del>checks to be performed. Check [File access constants][] for possible values
<del>of `mode`. It is possible to create a mask consisting of the bitwise OR of
<del>two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
<add>checks to be performed. `mode` should be either the value `fs.constants.F_OK`
<add>or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,
<add>`fs.constants.W_OK`, and `fs.constants.X_OK` (e.g.
<add>`fs.constants.W_OK | fs.constants.R_OK`). Check [File access constants][] for
<add>possible values of `mode`.
<ide>
<ide> If the accessibility check is successful, the promise is resolved with no
<ide> value. If any of the accessibility checks fail, the promise is rejected
<ide> changes:
<ide>
<ide> Tests a user's permissions for the file or directory specified by `path`.
<ide> The `mode` argument is an optional integer that specifies the accessibility
<del>checks to be performed. Check [File access constants][] for possible values
<del>of `mode`. It is possible to create a mask consisting of the bitwise OR of
<del>two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
<add>checks to be performed. `mode` should be either the value `fs.constants.F_OK`
<add>or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`,
<add>`fs.constants.W_OK`, and `fs.constants.X_OK` (e.g.
<add>`fs.constants.W_OK | fs.constants.R_OK`). Check [File access constants][] for
<add>possible values of `mode`.
<ide>
<ide> The final argument, `callback`, is a callback function that is invoked with
<ide> a possible error argument. If any of the accessibility checks fail, the error
<ide> access(file, constants.W_OK, (err) => {
<ide> console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
<ide> });
<ide>
<del>// Check if the file exists in the current directory, and if it is writable.
<del>access(file, constants.F_OK | constants.W_OK, (err) => {
<del> if (err) {
<del> console.error(
<del> `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
<del> } else {
<del> console.log(`${file} exists, and it is writable`);
<del> }
<add>// Check if the file is readable and writable.
<add>access(file, constants.R_OK | constants.W_OK, (err) => {
<add> console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
<ide> });
<ide> ```
<ide>
<ide> changes:
<ide>
<ide> Synchronously tests a user's permissions for the file or directory specified
<ide> by `path`. The `mode` argument is an optional integer that specifies the
<del>accessibility checks to be performed. Check [File access constants][] for
<del>possible values of `mode`. It is possible to create a mask consisting of
<del>the bitwise OR of two or more values
<del>(e.g. `fs.constants.W_OK | fs.constants.R_OK`).
<add>accessibility checks to be performed. `mode` should be either the value
<add>`fs.constants.F_OK` or a mask consisting of the bitwise OR of any of
<add>`fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` (e.g.
<add>`fs.constants.W_OK | fs.constants.R_OK`). Check [File access constants][] for
<add>possible values of `mode`.
<ide>
<ide> If any of the accessibility checks fail, an `Error` will be thrown. Otherwise,
<ide> the method will return `undefined`.
<ide> open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {
<ide>
<ide> ##### File access constants
<ide>
<del>The following constants are meant for use with [`fs.access()`][].
<add>The following constants are meant for use as the `mode` parameter passed to
<add>[`fsPromises.access()`][], [`fs.access()`][], and [`fs.accessSync()`][].
<ide>
<ide> <table>
<ide> <tr>
<ide> the file contents.
<ide> [`event ports`]: https://illumos.org/man/port_create
<ide> [`filehandle.writeFile()`]: #filehandlewritefiledata-options
<ide> [`fs.access()`]: #fsaccesspath-mode-callback
<add>[`fs.accessSync()`]: #fsaccesssyncpath-mode
<ide> [`fs.chmod()`]: #fschmodpath-mode-callback
<ide> [`fs.chown()`]: #fschownpath-uid-gid-callback
<ide> [`fs.copyFile()`]: #fscopyfilesrc-dest-mode-callback
<ide> the file contents.
<ide> [`fs.write(fd, string...)`]: #fswritefd-string-position-encoding-callback
<ide> [`fs.writeFile()`]: #fswritefilefile-data-options-callback
<ide> [`fs.writev()`]: #fswritevfd-buffers-position-callback
<add>[`fsPromises.access()`]: #fspromisesaccesspath-mode
<ide> [`fsPromises.open()`]: #fspromisesopenpath-flags-mode
<ide> [`fsPromises.opendir()`]: #fspromisesopendirpath-options
<ide> [`fsPromises.rm()`]: #fspromisesrmpath-options | 1 |
Javascript | Javascript | fix broken link to point to correct sample file | ecac839f68791788d1d5a88fe8eb4d007c8f6fbd | <ide><path>samples/samples.js
<ide> path: 'scales/time/line.html'
<ide> }, {
<ide> title: 'Line (point data)',
<del> path: 'scales/time/line.html'
<add> path: 'scales/time/line-point-data.html'
<ide> }, {
<ide> title: 'Combo',
<ide> path: 'scales/time/combo.html' | 1 |
Javascript | Javascript | use main document for gettestdocument | 8857e12c9ee79384b56d7a08abda1abe23cda49c | <ide><path>src/test/getTestDocument.js
<ide> 'use strict';
<ide>
<ide> function getTestDocument(markup) {
<del> var iframe = document.createElement('iframe');
<del> iframe.style.display = 'none';
<del> document.body.appendChild(iframe);
<del>
<del> var testDocument = iframe.contentDocument || iframe.contentWindow.document;
<del> testDocument.open();
<del> testDocument.write(
<add> document.open();
<add> document.write(
<ide> markup || '<!doctype html><html><meta charset=utf-8><title>test doc</title>'
<ide> );
<del> testDocument.close();
<del>
<del> iframe.parentNode.removeChild(iframe);
<del> return testDocument;
<add> document.close();
<add> return document;
<ide> }
<ide>
<ide> module.exports = getTestDocument; | 1 |
Javascript | Javascript | add benchmark for object properties | ad6e778c4a903a7d484125c4737ad4816331e457 | <ide><path>benchmark/misc/object-property-bench.js
<add>'use strict';
<add>
<add>const common = require('../common.js');
<add>
<add>const bench = common.createBenchmark(main, {
<add> method: ['property', 'string', 'variable', 'symbol'],
<add> millions: [1000]
<add>});
<add>
<add>function runProperty(n) {
<add> const object = {};
<add> var i = 0;
<add> bench.start();
<add> for (; i < n; i++) {
<add> object.p1 = 21;
<add> object.p2 = 21;
<add> object.p1 += object.p2;
<add> }
<add> bench.end(n / 1e6);
<add>}
<add>
<add>function runString(n) {
<add> const object = {};
<add> var i = 0;
<add> bench.start();
<add> for (; i < n; i++) {
<add> object['p1'] = 21;
<add> object['p2'] = 21;
<add> object['p1'] += object['p2'];
<add> }
<add> bench.end(n / 1e6);
<add>}
<add>
<add>function runVariable(n) {
<add> const object = {};
<add> const var1 = 'p1';
<add> const var2 = 'p2';
<add> var i = 0;
<add> bench.start();
<add> for (; i < n; i++) {
<add> object[var1] = 21;
<add> object[var2] = 21;
<add> object[var1] += object[var2];
<add> }
<add> bench.end(n / 1e6);
<add>}
<add>
<add>function runSymbol(n) {
<add> const object = {};
<add> const symbol1 = Symbol('p1');
<add> const symbol2 = Symbol('p2');
<add> var i = 0;
<add> bench.start();
<add> for (; i < n; i++) {
<add> object[symbol1] = 21;
<add> object[symbol2] = 21;
<add> object[symbol1] += object[symbol2];
<add> }
<add> bench.end(n / 1e6);
<add>}
<add>
<add>function main(conf) {
<add> const n = +conf.millions * 1e6;
<add>
<add> switch (conf.method) {
<add> case 'property':
<add> runProperty(n);
<add> break;
<add> case 'string':
<add> runString(n);
<add> break;
<add> case 'variable':
<add> runVariable(n);
<add> break;
<add> case 'symbol':
<add> runSymbol(n);
<add> break;
<add> default:
<add> throw new Error('Unexpected method');
<add> }
<add>} | 1 |
Javascript | Javascript | add missing properties to texture.tojson() | 1f3207f15754e5af8df480b8cd5a5fe6b54f1ee9 | <ide><path>src/textures/Texture.js
<ide> Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
<ide> wrap: [ this.wrapS, this.wrapT ],
<ide>
<ide> format: this.format,
<add> type: this.type,
<add> encoding: this.encoding,
<add>
<ide> minFilter: this.minFilter,
<ide> magFilter: this.magFilter,
<ide> anisotropy: this.anisotropy,
<add> mipmaps: this.mipmaps.slice(),
<add>
<add> flipY: this.flipY,
<ide>
<del> flipY: this.flipY
<add> premultiplyAlpha: this.premultiplyAlpha,
<add> unpackAlignment: this.unpackAlignment
<ide>
<ide> };
<ide> | 1 |
Text | Text | fix typo in `onboarding.md` | f92af5210526afedc272a9ca66ea7aef32099852 | <ide><path>onboarding.md
<ide> needs to be pointed out separately during the onboarding.
<ide> * Example:
<ide> <https://github.com/nodejs/node/commit/b58fe52692659c0bc25ddbe6afa7f4ae2c7f14a8>
<ide> * For raw commit message:
<del> `git show --format=%Bb58fe52692659c0bc25ddbe6afa7f4ae2c7f14a8`
<add> `git show --format=%B b58fe52692659c0bc25ddbe6afa7f4ae2c7f14a8`
<ide> * Collaborators are in alphabetical order by GitHub username.
<ide> * Optionally, include your personal pronouns.
<ide> * Add the `Fixes: <collaborator-nomination-issue-url>` to the commit message | 1 |
Python | Python | support pep 563 for hfargumentparser | 81643edda55dcf9e050612dec285f2fd8d8833e2 | <ide><path>src/transformers/hf_argparser.py
<ide>
<ide> import dataclasses
<ide> import json
<del>import re
<ide> import sys
<ide> from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
<ide> from copy import copy
<ide> from enum import Enum
<add>from inspect import isclass
<ide> from pathlib import Path
<del>from typing import Any, Iterable, List, NewType, Optional, Tuple, Union
<add>from typing import Any, Dict, Iterable, NewType, Optional, Tuple, Union, get_type_hints
<ide>
<ide>
<ide> DataClass = NewType("DataClass", Any)
<ide> def __init__(self, dataclass_types: Union[DataClassType, Iterable[DataClassType]
<ide> for dtype in self.dataclass_types:
<ide> self._add_dataclass_arguments(dtype)
<ide>
<add> @staticmethod
<add> def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field):
<add> field_name = f"--{field.name}"
<add> kwargs = field.metadata.copy()
<add> # field.metadata is not used at all by Data Classes,
<add> # it is provided as a third-party extension mechanism.
<add> if isinstance(field.type, str):
<add> raise RuntimeError(
<add> "Unresolved type detected, which should have been done with the help of "
<add> "`typing.get_type_hints` method by default"
<add> )
<add>
<add> origin_type = getattr(field.type, "__origin__", field.type)
<add> if origin_type is Union:
<add> if len(field.type.__args__) != 2 or type(None) not in field.type.__args__:
<add> raise ValueError("Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union`")
<add> if bool not in field.type.__args__:
<add> # filter `NoneType` in Union (except for `Union[bool, NoneType]`)
<add> field.type = (
<add> field.type.__args__[0] if isinstance(None, field.type.__args__[1]) else field.type.__args__[1]
<add> )
<add> origin_type = getattr(field.type, "__origin__", field.type)
<add>
<add> # A variable to store kwargs for a boolean field, if needed
<add> # so that we can init a `no_*` complement argument (see below)
<add> bool_kwargs = {}
<add> if isinstance(field.type, type) and issubclass(field.type, Enum):
<add> kwargs["choices"] = [x.value for x in field.type]
<add> kwargs["type"] = type(kwargs["choices"][0])
<add> if field.default is not dataclasses.MISSING:
<add> kwargs["default"] = field.default
<add> else:
<add> kwargs["required"] = True
<add> elif field.type is bool or field.type is Optional[bool]:
<add> # Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
<add> # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
<add> bool_kwargs = copy(kwargs)
<add>
<add> # Hack because type=bool in argparse does not behave as we want.
<add> kwargs["type"] = string_to_bool
<add> if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
<add> # Default value is False if we have no default when of type bool.
<add> default = False if field.default is dataclasses.MISSING else field.default
<add> # This is the value that will get picked if we don't include --field_name in any way
<add> kwargs["default"] = default
<add> # This tells argparse we accept 0 or 1 value after --field_name
<add> kwargs["nargs"] = "?"
<add> # This is the value that will get picked if we do --field_name (without value)
<add> kwargs["const"] = True
<add> elif isclass(origin_type) and issubclass(origin_type, list):
<add> kwargs["type"] = field.type.__args__[0]
<add> kwargs["nargs"] = "+"
<add> if field.default_factory is not dataclasses.MISSING:
<add> kwargs["default"] = field.default_factory()
<add> elif field.default is dataclasses.MISSING:
<add> kwargs["required"] = True
<add> else:
<add> kwargs["type"] = field.type
<add> if field.default is not dataclasses.MISSING:
<add> kwargs["default"] = field.default
<add> elif field.default_factory is not dataclasses.MISSING:
<add> kwargs["default"] = field.default_factory()
<add> else:
<add> kwargs["required"] = True
<add> parser.add_argument(field_name, **kwargs)
<add>
<add> # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
<add> # Order is important for arguments with the same destination!
<add> # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
<add> # here and we do not need those changes/additional keys.
<add> if field.default is True and (field.type is bool or field.type is Optional[bool]):
<add> bool_kwargs["default"] = False
<add> parser.add_argument(f"--no_{field.name}", action="store_false", dest=field.name, **bool_kwargs)
<add>
<ide> def _add_dataclass_arguments(self, dtype: DataClassType):
<ide> if hasattr(dtype, "_argument_group_name"):
<ide> parser = self.add_argument_group(dtype._argument_group_name)
<ide> else:
<ide> parser = self
<add>
<add> try:
<add> type_hints: Dict[str, type] = get_type_hints(dtype)
<add> except NameError:
<add> raise RuntimeError(
<add> f"Type resolution failed for f{dtype}. Try declaring the class in global scope or "
<add> f"removing line of `from __future__ import annotations` which opts in Postponed "
<add> f"Evaluation of Annotations (PEP 563)"
<add> )
<add>
<ide> for field in dataclasses.fields(dtype):
<ide> if not field.init:
<ide> continue
<del> field_name = f"--{field.name}"
<del> kwargs = field.metadata.copy()
<del> # field.metadata is not used at all by Data Classes,
<del> # it is provided as a third-party extension mechanism.
<del> if isinstance(field.type, str):
<del> raise ImportError(
<del> "This implementation is not compatible with Postponed Evaluation of Annotations (PEP 563), "
<del> "which can be opted in from Python 3.7 with `from __future__ import annotations`. "
<del> "We will add compatibility when Python 3.9 is released."
<del> )
<del> typestring = str(field.type)
<del> for prim_type in (int, float, str):
<del> for collection in (List,):
<del> if (
<del> typestring == f"typing.Union[{collection[prim_type]}, NoneType]"
<del> or typestring == f"typing.Optional[{collection[prim_type]}]"
<del> ):
<del> field.type = collection[prim_type]
<del> if (
<del> typestring == f"typing.Union[{prim_type.__name__}, NoneType]"
<del> or typestring == f"typing.Optional[{prim_type.__name__}]"
<del> ):
<del> field.type = prim_type
<del>
<del> # A variable to store kwargs for a boolean field, if needed
<del> # so that we can init a `no_*` complement argument (see below)
<del> bool_kwargs = {}
<del> if isinstance(field.type, type) and issubclass(field.type, Enum):
<del> kwargs["choices"] = [x.value for x in field.type]
<del> kwargs["type"] = type(kwargs["choices"][0])
<del> if field.default is not dataclasses.MISSING:
<del> kwargs["default"] = field.default
<del> else:
<del> kwargs["required"] = True
<del> elif field.type is bool or field.type == Optional[bool]:
<del> # Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
<del> # We do not init it here because the `no_*` alternative must be instantiated after the real argument
<del> bool_kwargs = copy(kwargs)
<del>
<del> # Hack because type=bool in argparse does not behave as we want.
<del> kwargs["type"] = string_to_bool
<del> if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
<del> # Default value is False if we have no default when of type bool.
<del> default = False if field.default is dataclasses.MISSING else field.default
<del> # This is the value that will get picked if we don't include --field_name in any way
<del> kwargs["default"] = default
<del> # This tells argparse we accept 0 or 1 value after --field_name
<del> kwargs["nargs"] = "?"
<del> # This is the value that will get picked if we do --field_name (without value)
<del> kwargs["const"] = True
<del> elif (
<del> hasattr(field.type, "__origin__")
<del> and re.search(r"^(typing\.List|list)\[(.*)\]$", str(field.type)) is not None
<del> ):
<del> kwargs["nargs"] = "+"
<del> kwargs["type"] = field.type.__args__[0]
<del> if not all(x == kwargs["type"] for x in field.type.__args__):
<del> raise ValueError(f"{field.name} cannot be a List of mixed types")
<del> if field.default_factory is not dataclasses.MISSING:
<del> kwargs["default"] = field.default_factory()
<del> elif field.default is dataclasses.MISSING:
<del> kwargs["required"] = True
<del> else:
<del> kwargs["type"] = field.type
<del> if field.default is not dataclasses.MISSING:
<del> kwargs["default"] = field.default
<del> elif field.default_factory is not dataclasses.MISSING:
<del> kwargs["default"] = field.default_factory()
<del> else:
<del> kwargs["required"] = True
<del> parser.add_argument(field_name, **kwargs)
<del>
<del> # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
<del> # Order is important for arguments with the same destination!
<del> # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
<del> # here and we do not need those changes/additional keys.
<del> if field.default is True and (field.type is bool or field.type == Optional[bool]):
<del> bool_kwargs["default"] = False
<del> parser.add_argument(f"--no_{field.name}", action="store_false", dest=field.name, **bool_kwargs)
<add> field.type = type_hints[field.name]
<add> self._parse_dataclass_field(parser, field)
<ide>
<ide> def parse_args_into_dataclasses(
<ide> self, args=None, return_remaining_strings=False, look_for_args_file=True, args_filename=None
<ide><path>tests/utils/test_hf_argparser.py
<ide> def __post_init__(self):
<ide> self.required_enum = BasicEnum(self.required_enum)
<ide>
<ide>
<add>@dataclass
<add>class StringLiteralAnnotationExample:
<add> foo: int
<add> required_enum: "BasicEnum" = field()
<add> opt: "Optional[bool]" = None
<add> baz: "str" = field(default="toto", metadata={"help": "help message"})
<add> foo_str: "List[str]" = list_field(default=["Hallo", "Bonjour", "Hello"])
<add>
<add>
<ide> class HfArgumentParserTest(unittest.TestCase):
<del> def argparsersEqual(self, a: argparse.ArgumentParser, b: argparse.ArgumentParser) -> bool:
<add> def argparsersEqual(self, a: argparse.ArgumentParser, b: argparse.ArgumentParser):
<ide> """
<ide> Small helper to check pseudo-equality of parsed arguments on `ArgumentParser` instances.
<ide> """
<ide> def test_with_required(self):
<ide> expected.add_argument("--required_enum", type=str, choices=["titi", "toto"], required=True)
<ide> self.argparsersEqual(parser, expected)
<ide>
<add> def test_with_string_literal_annotation(self):
<add> parser = HfArgumentParser(StringLiteralAnnotationExample)
<add>
<add> expected = argparse.ArgumentParser()
<add> expected.add_argument("--foo", type=int, required=True)
<add> expected.add_argument("--required_enum", type=str, choices=["titi", "toto"], required=True)
<add> expected.add_argument("--opt", type=string_to_bool, default=None)
<add> expected.add_argument("--baz", default="toto", type=str, help="help message")
<add> expected.add_argument("--foo_str", nargs="+", default=["Hallo", "Bonjour", "Hello"], type=str)
<add> self.argparsersEqual(parser, expected)
<add>
<ide> def test_parse_dict(self):
<ide> parser = HfArgumentParser(BasicExample)
<ide> | 2 |
Python | Python | make use of clongdouble and longdouble | a8218af306e7639f2136c8e915a5b9ea1f34356a | <ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_linear_nan_1D(self, dtype):
<ide> ] + [(np.float16, np.float64),
<ide> (np.float32, np.float64),
<ide> (np.float64, np.float64),
<del> (np.float128, np.float128),
<add> (np.longdouble, np.longdouble),
<ide> (np.complex64, np.complex128),
<ide> (np.complex128, np.complex128),
<del> (np.complex256, np.complex256),
<add> (np.clongdouble, np.clongdouble),
<ide> (np.dtype("O"), np.float64)]
<ide>
<ide> @pytest.mark.parametrize(["input_dtype", "expected_dtype"], H_F_TYPE_CODES) | 1 |
Ruby | Ruby | expose instrumenter id in notifications | 45462c5e41a77e600878f7b8b2e41babeef8fe8f | <ide><path>activesupport/lib/active_support/notifications/instrumenter.rb
<ide> module ActiveSupport
<ide> module Notifications
<ide> class Instrumenter
<add> attr_reader :id
<add>
<ide> def initialize(notifier)
<ide> @id = unique_id
<ide> @notifier = notifier
<ide><path>activesupport/test/notifications_test.rb
<ide> def test_instrument_returns_block_result
<ide> assert_equal 2, @notifier.instrument(:awesome) { 1 + 1 }
<ide> end
<ide>
<add> def test_instrumenter_exposes_its_id
<add> assert_equal 20, ActiveSupport::Notifications::Instrumenter.new(@notifier).id.size
<add> end
<add>
<ide> def test_nested_events_can_be_instrumented
<ide> @notifier.instrument(:awesome, :payload => "notifications") do
<ide> @notifier.instrument(:wot, :payload => "child") do | 2 |
Java | Java | refactor the usage of undertow bytebufferpool | 8d786e8bba86de45d486c0dd858522ca4190f0d1 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerReadPublisher.java
<ide> public final void onDataAvailable() {
<ide> * @see ReadListener#onAllDataRead()
<ide> * @see org.xnio.ChannelListener#handleEvent(Channel)
<ide> */
<del> public final void onAllDataRead() {
<add> public void onAllDataRead() {
<ide> if (this.logger.isTraceEnabled()) {
<ide> this.logger.trace(this.state + " onAllDataRead");
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowHttpHandlerAdapter.java
<ide> public void setDataBufferFactory(DataBufferFactory dataBufferFactory) {
<ide> @Override
<ide> public void handleRequest(HttpServerExchange exchange) throws Exception {
<ide>
<del> ServerHttpRequest request = new UndertowServerHttpRequest(exchange, this.dataBufferFactory);
<add> UndertowServerHttpRequest request = new UndertowServerHttpRequest(exchange, this.dataBufferFactory);
<ide> ServerHttpResponse response = new UndertowServerHttpResponse(exchange, this.dataBufferFactory);
<ide>
<ide> getHttpHandler().handle(request, response).subscribe(new Subscriber<Void>() {
<ide> public void onError(Throwable ex) {
<ide> if (!exchange.isResponseStarted() && exchange.getStatusCode() <= 500) {
<ide> exchange.setStatusCode(500);
<ide> }
<add> request.close();
<ide> exchange.endExchange();
<ide> }
<ide> @Override
<ide> public void onComplete() {
<ide> logger.debug("Successfully completed request");
<add> request.close();
<ide> exchange.endExchange();
<ide> }
<ide> });
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java
<ide> import java.net.URISyntaxException;
<ide> import java.nio.ByteBuffer;
<ide>
<add>import io.undertow.connector.ByteBufferPool;
<ide> import io.undertow.connector.PooledByteBuffer;
<ide> import io.undertow.server.HttpServerExchange;
<ide> import io.undertow.server.handlers.Cookie;
<ide> public Flux<DataBuffer> getBody() {
<ide> return Flux.from(this.body);
<ide> }
<ide>
<add> void close() {
<add> this.body.onAllDataRead();
<add> }
<add>
<ide> private static class RequestBodyPublisher extends AbstractListenerReadPublisher<DataBuffer> {
<ide>
<ide> private final ChannelListener<StreamSourceChannel> readListener =
<ide> private static class RequestBodyPublisher extends AbstractListenerReadPublisher<
<ide>
<ide> private final DataBufferFactory dataBufferFactory;
<ide>
<del> private final PooledByteBuffer pooledByteBuffer;
<add> private final ByteBufferPool byteBufferPool;
<add>
<add> private PooledByteBuffer pooledByteBuffer;
<ide>
<ide> public RequestBodyPublisher(HttpServerExchange exchange,
<ide> DataBufferFactory dataBufferFactory) {
<ide> this.requestChannel = exchange.getRequestChannel();
<del> this.pooledByteBuffer =
<del> exchange.getConnection().getByteBufferPool().allocate();
<add> this.byteBufferPool = exchange.getConnection().getByteBufferPool();
<ide> this.dataBufferFactory = dataBufferFactory;
<ide> }
<ide>
<ide> protected void checkOnDataAvailable() {
<ide>
<ide> @Override
<ide> protected DataBuffer read() throws IOException {
<add> if (this.pooledByteBuffer == null) {
<add> this.pooledByteBuffer = this.byteBufferPool.allocate();
<add> }
<ide> ByteBuffer byteBuffer = this.pooledByteBuffer.getBuffer();
<ide> int read = this.requestChannel.read(byteBuffer);
<ide> if (logger.isTraceEnabled()) {
<ide> else if (read == -1) {
<ide> return null;
<ide> }
<ide>
<add> @Override
<add> public void onAllDataRead() {
<add> if (this.pooledByteBuffer != null && this.pooledByteBuffer.isOpen()) {
<add> this.pooledByteBuffer.close();
<add> }
<add> super.onAllDataRead();
<add> }
<add>
<ide> private class ReadListener implements ChannelListener<StreamSourceChannel> {
<ide>
<ide> @Override | 3 |
PHP | PHP | fix missing skiplog block | 70b55d01610d59a6a4cc760695f567ffb53a3570 | <ide><path>src/Error/BaseErrorHandler.php
<ide> public function logException(Throwable $exception, ?ServerRequestInterface $requ
<ide> if (empty($this->_config['log'])) {
<ide> return false;
<ide> }
<add> foreach ($this->_config['skipLog'] as $class) {
<add> if ($exception instanceof $class) {
<add> return false;
<add> }
<add> }
<ide>
<ide> return $this->getLogger()->log($exception, $request ?? Router::getRequest());
<ide> }
<ide><path>src/Error/ErrorTrap.php
<ide> public function handleError(
<ide> $renderer = $this->renderer();
<ide> $logger = $this->logger();
<ide>
<del>
<ide> try {
<ide> // Log first incase rendering or event listeners fail
<ide> if ($this->_config['log']) { | 2 |
Python | Python | fix broken tests | 0659e5bd5994de769fa10878ea3dc3dd933cf492 | <ide><path>celery/tests/backends/test_mongodb.py
<ide> def test_restore_group(self, mock_get_database):
<ide> mock_get_database.assert_called_once_with()
<ide> mock_collection.find_one.assert_called_once_with(
<ide> {'_id': sentinel.taskset_id})
<del><<<<<<< HEAD
<del> self.assertEqual(
<del> list(sorted(['date_done', 'result', 'task_id'])),
<del> list(sorted(ret_val.keys())),
<del>=======
<ide> self.assertItemsEqual(
<ide> ['date_done', 'result', 'task_id'],
<ide> list(ret_val.keys()),
<del>>>>>>>> e758762... Fix for https://github.com/celery/celery/issues/2743
<ide> )
<ide>
<ide> @patch('celery.backends.mongodb.MongoBackend._get_database') | 1 |
PHP | PHP | add identifier quoting for fields with spaces | c51f6d11e31131ab47002a9d13f8e42b4a95d0f8 | <ide><path>src/Database/SqlDialectTrait.php
<ide> public function quoteIdentifier($identifier)
<ide> return $this->_startQuote . $identifier . $this->_endQuote;
<ide> }
<ide>
<add> // string.string
<ide> if (preg_match('/^[\w-]+\.[^ \*]*$/', $identifier)) {
<del>// string.string
<ide> $items = explode('.', $identifier);
<ide>
<ide> return $this->_startQuote . implode($this->_endQuote . '.' . $this->_startQuote, $items) . $this->_endQuote;
<ide> }
<ide>
<add> // string.*
<ide> if (preg_match('/^[\w-]+\.\*$/', $identifier)) {
<del>// string.*
<ide> return $this->_startQuote . str_replace('.*', $this->_endQuote . '.*', $identifier);
<ide> }
<ide>
<ide> if (preg_match('/^([\w-]+)\((.*)\)$/', $identifier, $matches)) {
<del>// Functions
<add> // Functions
<ide> return $matches[1] . '(' . $this->quoteIdentifier($matches[2]) . ')';
<ide> }
<ide>
<ide> // Alias.field AS thing
<del> if (preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+AS\s*([\w-]+)$/i', $identifier, $matches)) {
<add> if (preg_match('/^([\w-]+(\.[\w-\s]+|\(.*\))*)\s+AS\s*([\w-]+)$/i', $identifier, $matches)) {
<ide> return $this->quoteIdentifier($matches[1]) . ' AS ' . $this->quoteIdentifier($matches[3]);
<ide> }
<ide>
<add> // string.string with spaces
<add> if (preg_match('/^[\w-_]+\.[\w-_\s]+[\w_]*/', $identifier)) {
<add> $items = explode('.', $identifier);
<add>
<add> return $this->_startQuote . implode($this->_endQuote . '.' . $this->_startQuote, $items) . $this->_endQuote;
<add> }
<add>
<ide> if (preg_match('/^[\w-_\s]*[\w-_]+/', $identifier)) {
<ide> return $this->_startQuote . $identifier . $this->_endQuote;
<ide> }
<ide><path>tests/TestCase/Database/ConnectionTest.php
<ide> public function testQuoteIdentifier()
<ide> $expected = '"Model".*';
<ide> $this->assertEquals($expected, $result);
<ide>
<add> $result = $connection->quoteIdentifier('Items.No_ 2');
<add> $expected = '"Items"."No_ 2"';
<add> $this->assertEquals($expected, $result);
<add>
<add> $result = $connection->quoteIdentifier('Items.No_ 2 thing');
<add> $expected = '"Items"."No_ 2 thing"';
<add> $this->assertEquals($expected, $result);
<add>
<add> $result = $connection->quoteIdentifier('Items.No_ 2 thing AS thing');
<add> $expected = '"Items"."No_ 2 thing" AS "thing"';
<add> $this->assertEquals($expected, $result);
<add>
<ide> $result = $connection->quoteIdentifier('MTD()');
<ide> $expected = 'MTD()';
<ide> $this->assertEquals($expected, $result); | 2 |
PHP | PHP | fix issue with trim line ending and test content | 8b0567b26da7b4ddf9263ec7a2fdee57b93bd5d3 | <ide><path>tests/TestCase/Utility/TextTest.php
<ide> public function testWrap()
<ide> $this->assertTextEquals($expected, $result, 'Text not wrapped.');
<ide>
<ide> $result = Text::wrap($text, ['width' => 20, 'wordWrap' => false]);
<del> $expected = <<<TEXT
<del>This is the song th
<del>at never ends. This
<del> is the song that n
<del>ever ends. This is
<del>the song that never
<del> ends.
<del>TEXT;
<add> $expected = 'This is the song th' . "\n" .
<add> 'at never ends. This' . "\n" .
<add> ' is the song that n' . "\n" .
<add> 'ever ends. This is ' . "\n" .
<add> 'the song that never' . "\n" .
<add> ' ends.';
<ide> $this->assertTextEquals($expected, $result, 'Text not wrapped.');
<ide> }
<ide> | 1 |
Go | Go | implement docker push with standalone client lib | 42670e30eef7023d2df9c6c8900041bc9e1546e0 | <ide><path>api/client/client.go
<ide> type apiClient interface {
<ide> ImageList(options types.ImageListOptions) ([]types.Image, error)
<ide> ImageLoad(input io.Reader) (io.ReadCloser, error)
<ide> ImagePull(options types.ImagePullOptions, privilegeFunc lib.RequestPrivilegeFunc) (io.ReadCloser, error)
<add> ImagePush(options types.ImagePushOptions, privilegeFunc lib.RequestPrivilegeFunc) (io.ReadCloser, error)
<ide> ImageRemove(options types.ImageRemoveOptions) ([]types.ImageDelete, error)
<ide> ImageSave(imageIDs []string) (io.ReadCloser, error)
<ide> ImageTag(options types.ImageTagOptions) error
<ide><path>api/client/lib/image_push.go
<add>package lib
<add>
<add>import (
<add> "io"
<add> "net/http"
<add> "net/url"
<add>
<add> "github.com/docker/docker/api/types"
<add>)
<add>
<add>// ImagePush request the docker host to push an image to a remote registry.
<add>// It executes the privileged function if the operation is unauthorized
<add>// and it tries one more time.
<add>// It's up to the caller to handle the io.ReadCloser and close it properly.
<add>func (cli *Client) ImagePush(options types.ImagePushOptions, privilegeFunc RequestPrivilegeFunc) (io.ReadCloser, error) {
<add> query := url.Values{}
<add> query.Set("tag", options.Tag)
<add>
<add> resp, err := cli.tryImagePush(options.ImageID, query, options.RegistryAuth)
<add> if resp.statusCode == http.StatusUnauthorized {
<add> newAuthHeader, privilegeErr := privilegeFunc()
<add> if privilegeErr != nil {
<add> return nil, privilegeErr
<add> }
<add> resp, err = cli.tryImagePush(options.ImageID, query, newAuthHeader)
<add> }
<add> if err != nil {
<add> return nil, err
<add> }
<add> return resp.body, nil
<add>}
<add>
<add>func (cli *Client) tryImagePush(imageID string, query url.Values, registryAuth string) (*serverResponse, error) {
<add> headers := map[string][]string{"X-Registry-Auth": {registryAuth}}
<add> return cli.post("/images/"+imageID+"/push", query, nil, headers)
<add>}
<ide><path>api/client/push.go
<ide> package client
<ide> import (
<ide> "errors"
<ide> "fmt"
<del> "net/url"
<add> "io"
<ide>
<ide> "github.com/docker/distribution/reference"
<add> "github.com/docker/docker/api/client/lib"
<add> "github.com/docker/docker/api/types"
<ide> Cli "github.com/docker/docker/cli"
<add> "github.com/docker/docker/cliconfig"
<add> "github.com/docker/docker/pkg/jsonmessage"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/registry"
<ide> )
<ide> func (cli *DockerCli) CmdPush(args ...string) error {
<ide> return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository to <user>/<repo> (ex: %s/%s)", username, repoInfo.LocalName)
<ide> }
<ide>
<add> requestPrivilege := cli.registryAuthenticationPrivilegedFunc(repoInfo.Index, "push")
<ide> if isTrusted() {
<del> return cli.trustedPush(repoInfo, tag, authConfig)
<add> return cli.trustedPush(repoInfo, tag, authConfig, requestPrivilege)
<ide> }
<ide>
<del> v := url.Values{}
<del> v.Set("tag", tag)
<add> return cli.imagePushPrivileged(authConfig, ref.Name(), tag, cli.out, requestPrivilege)
<add>}
<add>
<add>func (cli *DockerCli) imagePushPrivileged(authConfig cliconfig.AuthConfig, imageID, tag string, outputStream io.Writer, requestPrivilege lib.RequestPrivilegeFunc) error {
<add> encodedAuth, err := authConfig.EncodeToBase64()
<add> if err != nil {
<add> return err
<add> }
<add> options := types.ImagePushOptions{
<add> ImageID: imageID,
<add> Tag: tag,
<add> RegistryAuth: encodedAuth,
<add> }
<add>
<add> responseBody, err := cli.client.ImagePush(options, requestPrivilege)
<add> if err != nil {
<add> return err
<add> }
<add> defer responseBody.Close()
<ide>
<del> _, _, err = cli.clientRequestAttemptLogin("POST", "/images/"+ref.Name()+"/push?"+v.Encode(), nil, cli.out, repoInfo.Index, "push")
<del> return err
<add> return jsonmessage.DisplayJSONMessagesStream(responseBody, outputStream, cli.outFd, cli.isTerminalOut)
<ide> }
<ide><path>api/client/trust.go
<ide> func targetStream(in io.Writer) (io.WriteCloser, <-chan []target) {
<ide> return ioutils.NewWriteCloserWrapper(out, w.Close), targetChan
<ide> }
<ide>
<del>func (cli *DockerCli) trustedPush(repoInfo *registry.RepositoryInfo, tag string, authConfig cliconfig.AuthConfig) error {
<add>func (cli *DockerCli) trustedPush(repoInfo *registry.RepositoryInfo, tag string, authConfig cliconfig.AuthConfig, requestPrivilege lib.RequestPrivilegeFunc) error {
<ide> streamOut, targetChan := targetStream(cli.out)
<ide>
<del> v := url.Values{}
<del> v.Set("tag", tag)
<add> reqError := cli.imagePushPrivileged(authConfig, repoInfo.LocalName.Name(), tag, streamOut, requestPrivilege)
<ide>
<del> _, _, err := cli.clientRequestAttemptLogin("POST", "/images/"+repoInfo.LocalName.Name()+"/push?"+v.Encode(), nil, streamOut, repoInfo.Index, "push")
<ide> // Close stream channel to finish target parsing
<ide> if err := streamOut.Close(); err != nil {
<ide> return err
<ide> }
<ide> // Check error from request
<del> if err != nil {
<del> return err
<add> if reqError != nil {
<add> return reqError
<ide> }
<ide>
<ide> // Get target results
<ide><path>api/types/client.go
<ide> type ImagePullOptions struct {
<ide> RegistryAuth string
<ide> }
<ide>
<add>//ImagePushOptions holds information to push images.
<add>type ImagePushOptions ImagePullOptions
<add>
<ide> // ImageRemoveOptions holds parameters to remove images.
<ide> type ImageRemoveOptions struct {
<ide> ImageID string | 5 |
Java | Java | remove unused linkedlist import | fef0e21d8b938d2a5bce0fe9b1f38332458e7f45 | <ide><path>spring-core/src/main/java/org/springframework/util/ReflectionUtils.java
<ide> import java.sql.SQLException;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<del>import java.util.LinkedList;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.