content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | return this for http2serverrequest#settimeout | ac80fed3b80cdda4cf68df67ba569f208b87922e | <ide><path>lib/internal/http2/compat.js
<ide> class Http2ServerRequest extends Readable {
<ide> }
<ide>
<ide> setTimeout(msecs, callback) {
<del> if (this[kState].closed)
<del> return;
<del> this[kStream].setTimeout(msecs, callback);
<add> if (!this[kState].closed)
<add> this[kStream].setTimeout(msecs, callback);
<add> return this;
<ide> }
<ide> }
<ide>
<ide><path>test/parallel/test-http2-compat-serverrequest-settimeout.js
<ide> const common = require('../common');
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<add>const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide> const msecs = common.platformTimeout(1);
<ide> const server = http2.createServer();
<ide>
<ide> server.on('request', (req, res) => {
<del> req.setTimeout(msecs, common.mustCall(() => {
<add> const request = req.setTimeout(msecs, common.mustCall(() => {
<ide> res.end();
<ide> }));
<add> assert.strictEqual(request, req);
<ide> req.on('timeout', common.mustCall());
<ide> res.on('finish', common.mustCall(() => {
<ide> req.setTimeout(msecs, common.mustNotCall()); | 2 |
Python | Python | fix typos in returndict and returnlist docstrings | 400078311bae2055a4d4ab6f5933439d6111e3cb | <ide><path>rest_framework/utils/serializer_helpers.py
<ide>
<ide> class ReturnDict(OrderedDict):
<ide> """
<del> Return object from `serialier.data` for the `Serializer` class.
<add> Return object from `serializer.data` for the `Serializer` class.
<ide> Includes a backlink to the serializer instance for renderers
<ide> to use if they need richer field information.
<ide> """
<ide> def __reduce__(self):
<ide>
<ide> class ReturnList(list):
<ide> """
<del> Return object from `serialier.data` for the `SerializerList` class.
<add> Return object from `serializer.data` for the `SerializerList` class.
<ide> Includes a backlink to the serializer instance for renderers
<ide> to use if they need richer field information.
<ide> """ | 1 |
Javascript | Javascript | remove deprecated function requirerepl | 4d6297fef05267e82dd653f7ad99c95f9a5e2cef | <ide><path>lib/module.js
<ide> const NativeModule = require('native_module');
<ide> const util = require('util');
<ide> const internalModule = require('internal/module');
<del>const internalUtil = require('internal/util');
<ide> const vm = require('vm');
<ide> const assert = require('assert').ok;
<ide> const fs = require('fs');
<ide> Module._initPaths = function() {
<ide> Module.globalPaths = modulePaths.slice(0);
<ide> };
<ide>
<del>// TODO(bnoordhuis) Unused, remove in the future.
<del>Module.requireRepl = internalUtil.deprecate(function() {
<del> return NativeModule.require('internal/repl');
<del>}, 'Module.requireRepl is deprecated.');
<del>
<ide> Module._preloadModules = function(requests) {
<ide> if (!Array.isArray(requests))
<ide> return; | 1 |
Mixed | Ruby | add authenticate_by when using has_secure_password | 9becc41df989bfccff091852d45925d41f0a13d8 | <ide><path>activerecord/CHANGELOG.md
<add>* Add `authenticate_by` when using `has_secure_password`.
<add>
<add> `authenticate_by` is intended to replace code like the following, which
<add> returns early when a user with a matching email is not found:
<add>
<add> ```ruby
<add> User.find_by(email: "...")&.authenticate("...")
<add> ```
<add>
<add> Such code is vulnerable to timing-based enumeration attacks, wherein an
<add> attacker can determine if a user account with a given email exists. After
<add> confirming that an account exists, the attacker can try passwords associated
<add> with that email address from other leaked databases, in case the user
<add> re-used a password across multiple sites (a common practice). Additionally,
<add> knowing an account email address allows the attacker to attempt a targeted
<add> phishing ("spear phishing") attack.
<add>
<add> `authenticate_by` addresses the vulnerability by taking the same amount of
<add> time regardless of whether a user with a matching email is found:
<add>
<add> ```ruby
<add> User.authenticate_by(email: "...", password: "...")
<add> ```
<add>
<add> *Jonathan Hefner*
<add>
<ide> * Remove deprecated `ActiveRecord::DatabaseConfigurations::DatabaseConfig#spec_name`.
<ide>
<ide> *Rafael Mendonça França*
<ide><path>activerecord/lib/active_record.rb
<ide> module ActiveRecord
<ide> autoload :SchemaDumper
<ide> autoload :SchemaMigration
<ide> autoload :Scoping
<add> autoload :SecurePassword
<ide> autoload :SecureToken
<ide> autoload :Serialization
<ide> autoload :SignedId
<ide><path>activerecord/lib/active_record/base.rb
<ide> class Base
<ide> include Callbacks
<ide> include Timestamp
<ide> include Associations
<del> include ActiveModel::SecurePassword
<add> include SecurePassword
<ide> include AutosaveAssociation
<ide> include NestedAttributes
<ide> include Transactions
<ide><path>activerecord/lib/active_record/secure_password.rb
<add># frozen_string_literal: true
<add>
<add>require "active_support/core_ext/hash/except"
<add>
<add>module ActiveRecord
<add> module SecurePassword
<add> extend ActiveSupport::Concern
<add>
<add> include ActiveModel::SecurePassword
<add>
<add> module ClassMethods
<add> # Given a set of attributes, finds a record using the non-password
<add> # attributes, and then authenticates that record using the password
<add> # attributes. Returns the record if authentication succeeds; otherwise,
<add> # returns +nil+.
<add> #
<add> # Regardless of whether a record is found or authentication succeeds,
<add> # +authenticate_by+ will take the same amount of time. This prevents
<add> # timing-based enumeration attacks, wherein an attacker can determine if a
<add> # passworded record exists even without knowing the password.
<add> #
<add> # Raises an ArgumentError if the set of attributes doesn't contain at
<add> # least one password and one non-password attribute.
<add> #
<add> # ==== Examples
<add> #
<add> # class User < ActiveRecord::Base
<add> # has_secure_password
<add> # end
<add> #
<add> # User.create(name: "John Doe", email: "jdoe@example.com", password: "abc123")
<add> #
<add> # User.authenticate_by(email: "jdoe@example.com", password: "abc123").name # => "John Doe" (in 373.4ms)
<add> # User.authenticate_by(email: "jdoe@example.com", password: "wrong") # => nil (in 373.9ms)
<add> # User.authenticate_by(email: "wrong@example.com", password: "abc123") # => nil (in 373.6ms)
<add> #
<add> # User.authenticate_by(email: "jdoe@example.com") # => ArgumentError
<add> # User.authenticate_by(password: "abc123") # => ArgumentError
<add> def authenticate_by(attributes)
<add> passwords = attributes.select { |name, value| !has_attribute?(name) && has_attribute?("#{name}_digest") }
<add>
<add> raise ArgumentError, "One or more password arguments are required" if passwords.empty?
<add> raise ArgumentError, "One or more finder arguments are required" if passwords.size == attributes.size
<add>
<add> if record = find_by(attributes.except(*passwords.keys))
<add> record if passwords.count { |name, value| record.public_send(:"authenticate_#{name}", value) } == passwords.size
<add> else
<add> self.new(passwords)
<add> nil
<add> end
<add> end
<add> end
<add> end
<add>end
<ide><path>activerecord/test/cases/secure_password_test.rb
<add># frozen_string_literal: true
<add>
<add>require "cases/helper"
<add>require "models/user"
<add>
<add>class SecurePasswordTest < ActiveRecord::TestCase
<add> setup do
<add> # Speed up tests
<add> @original_min_cost = ActiveModel::SecurePassword.min_cost
<add> ActiveModel::SecurePassword.min_cost = true
<add>
<add> @user = User.create(password: "abc123", recovery_password: "123abc")
<add> end
<add>
<add> teardown do
<add> ActiveModel::SecurePassword.min_cost = @original_min_cost
<add> end
<add>
<add> test "authenticate_by authenticates when password is correct" do
<add> assert_equal @user, User.authenticate_by(token: @user.token, password: @user.password)
<add> end
<add>
<add> test "authenticate_by does not authenticate when password is incorrect" do
<add> assert_nil User.authenticate_by(token: @user.token, password: "wrong")
<add> end
<add>
<add> test "authenticate_by takes the same amount of time regardless of whether record is found" do
<add> # Benchmark.realtime returns fractional seconds. Thus, summing over 1000
<add> # iterations is equivalent to averaging over 1000 iterations and then
<add> # multiplying by 1000 to convert to milliseconds.
<add> found_average_time_in_ms = 1000.times.sum do
<add> Benchmark.realtime do
<add> User.authenticate_by(token: @user.token, password: @user.password)
<add> end
<add> end
<add>
<add> not_found_average_time_in_ms = 1000.times.sum do
<add> Benchmark.realtime do
<add> User.authenticate_by(token: "wrong", password: @user.password)
<add> end
<add> end
<add>
<add> assert_in_delta found_average_time_in_ms, not_found_average_time_in_ms, 0.5
<add> end
<add>
<add> test "authenticate_by finds record using multiple attributes" do
<add> assert_equal @user, User.authenticate_by(token: @user.token, auth_token: @user.auth_token, password: @user.password)
<add> assert_nil User.authenticate_by(token: @user.token, auth_token: "wrong", password: @user.password)
<add> end
<add>
<add> test "authenticate_by authenticates using multiple passwords" do
<add> assert_equal @user, User.authenticate_by(token: @user.token, password: @user.password, recovery_password: @user.recovery_password)
<add> assert_nil User.authenticate_by(token: @user.token, password: @user.password, recovery_password: "wrong")
<add> end
<add>
<add> test "authenticate_by requires at least one password" do
<add> assert_raises ArgumentError do
<add> User.authenticate_by(token: @user.token)
<add> end
<add> end
<add>
<add> test "authenticate_by requires at least one attribute" do
<add> assert_raises ArgumentError do
<add> User.authenticate_by(password: @user.password)
<add> end
<add> end
<add>end
<ide><path>activerecord/test/models/user.rb
<ide> require "models/job"
<ide>
<ide> class User < ActiveRecord::Base
<add> has_secure_password validations: false
<add> has_secure_password :recovery_password, validations: false
<add>
<ide> has_secure_token
<ide> has_secure_token :auth_token, length: 36
<ide>
<ide><path>activerecord/test/schema/schema.rb
<ide> create_table :users, force: true do |t|
<ide> t.string :token
<ide> t.string :auth_token
<add> t.string :password_digest
<add> t.string :recovery_password_digest
<ide> end
<ide>
<ide> create_table :test_with_keyword_column_name, force: true do |t| | 7 |
Javascript | Javascript | remove unused catch bindings | 9d68e568569aa9b8ddf387b3d58adb6ae7e3cc22 | <ide><path>lib/fs.js
<ide> function exists(path, callback) {
<ide>
<ide> try {
<ide> fs.access(path, F_OK, suppressedCallback);
<del> } catch (err) {
<add> } catch {
<ide> return callback(false);
<ide> }
<ide> }
<ide> function existsSync(path) {
<ide> try {
<ide> path = toPathIfFileURL(path);
<ide> validatePath(path);
<del> } catch (e) {
<add> } catch {
<ide> return false;
<ide> }
<ide> const ctx = { path }; | 1 |
PHP | PHP | return entire string if search is not found | 1509e58ad15fc1a59b44d7804f29be00024e3eff | <ide><path>src/Illuminate/Support/Str.php
<ide> class Str
<ide> public static function after($subject, $search)
<ide> {
<ide> if (! static::contains($subject, $search)) {
<del> return '';
<add> return $subject;
<ide> }
<ide>
<ide> $searchEndPos = strpos($subject, $search) + static::length($search);
<ide><path>tests/Support/SupportHelpersTest.php
<ide> public function testStrAfter()
<ide> {
<ide> $this->assertEquals('nah', str_after('hannah', 'han'));
<ide> $this->assertEquals('nah', str_after('hannah', 'n'));
<del> $this->assertEmpty(str_after('hannah', 'xxxx'));
<add> $this->assertEquals('hannah', str_after('hannah', 'xxxx'));
<ide> }
<ide>
<ide> public function testStrContains()
<ide><path>tests/Support/SupportStrTest.php
<ide> public function testStrAfter()
<ide> {
<ide> $this->assertEquals('nah', Str::after('hannah', 'han'));
<ide> $this->assertEquals('nah', Str::after('hannah', 'n'));
<del> $this->assertEmpty(Str::after('hannah', 'xxxx'));
<add> $this->assertEquals('hannah', Str::after('hannah', 'xxxx'));
<ide> }
<ide>
<ide> public function testStrContains() | 3 |
Ruby | Ruby | use set.new instead of array#to_set | 9628a613cfe75669c180bf78d086f0372efce30e | <ide><path>Library/Homebrew/metafiles.rb
<ide>
<ide> class Metafiles
<ide> # https://github.com/github/markup#markups
<del> EXTENSIONS = %w[
<add> EXTENSIONS = Set.new %w[
<ide> .adoc .asc .asciidoc .creole .html .markdown .md .mdown .mediawiki .mkdn
<ide> .org .pod .rdoc .rst .rtf .textile .txt .wiki
<del> ].to_set.freeze
<del> BASENAMES = %w[
<add> ].freeze
<add> BASENAMES = Set.new %w[
<ide> about authors changelog changes copying copyright history license licence
<ide> news notes notice readme todo
<del> ].to_set.freeze
<add> ].freeze
<ide>
<ide> def self.list?(file)
<ide> return false if %w[.DS_Store INSTALL_RECEIPT.json].include?(file) | 1 |
Javascript | Javascript | unify stream utils | bb275ef2a4105c3a66920f64d32c5a024a14921f | <ide><path>lib/_http_client.js
<ide> const {
<ide> prepareError,
<ide> } = require('_http_common');
<ide> const { OutgoingMessage } = require('_http_outgoing');
<del>const { kDestroy } = require('internal/streams/destroy');
<ide> const Agent = require('_http_agent');
<ide> const { Buffer } = require('buffer');
<ide> const { defaultTriggerAsyncIdScope } = require('internal/async_hooks');
<ide> function parserOnIncomingClient(res, shouldKeepAlive) {
<ide> DTRACE_HTTP_CLIENT_RESPONSE(socket, req);
<ide> req.res = res;
<ide> res.req = req;
<del> res[kDestroy] = null;
<ide>
<ide> // Add our listener first, so that we guarantee socket cleanup
<ide> res.on('end', responseOnEnd);
<ide><path>lib/_http_incoming.js
<ide> const {
<ide> } = primordials;
<ide>
<ide> const { Readable, finished } = require('stream');
<del>const { kDestroy } = require('internal/streams/destroy');
<ide>
<ide> const kHeaders = Symbol('kHeaders');
<ide> const kHeadersCount = Symbol('kHeadersCount');
<ide> IncomingMessage.prototype._destroy = function _destroy(err, cb) {
<ide> }
<ide> };
<ide>
<del>IncomingMessage.prototype[kDestroy] = function(err) {
<del> this.socket = null;
<del> this.destroy(err);
<del>};
<del>
<ide> IncomingMessage.prototype._addHeaderLines = _addHeaderLines;
<ide> function _addHeaderLines(headers, n) {
<ide> if (headers && headers.length) {
<ide><path>lib/internal/streams/add-abort-signal.js
<ide> const validateAbortSignal = (signal, name) => {
<ide> }
<ide> };
<ide>
<del>function isStream(obj) {
<add>function isNodeStream(obj) {
<ide> return !!(obj && typeof obj.pipe === 'function');
<ide> }
<ide>
<ide> module.exports.addAbortSignal = function addAbortSignal(signal, stream) {
<ide> validateAbortSignal(signal, 'signal');
<del> if (!isStream(stream)) {
<add> if (!isNodeStream(stream)) {
<ide> throw new ERR_INVALID_ARG_TYPE('stream', 'stream.Stream', stream);
<ide> }
<ide> return module.exports.addAbortSignalNoValidate(signal, stream);
<ide><path>lib/internal/streams/destroy.js
<ide> const {
<ide> const {
<ide> Symbol,
<ide> } = primordials;
<add>const {
<add> kDestroyed,
<add> isDestroyed,
<add> isFinished,
<add> isServerRequest
<add>} = require('internal/streams/utils');
<ide>
<ide> const kDestroy = Symbol('kDestroy');
<ide> const kConstruct = Symbol('kConstruct');
<ide> function isRequest(stream) {
<ide> return stream && stream.setHeader && typeof stream.abort === 'function';
<ide> }
<ide>
<del>const kDestroyed = Symbol('kDestroyed');
<del>
<ide> function emitCloseLegacy(stream) {
<ide> stream.emit('close');
<ide> }
<ide> function emitErrorCloseLegacy(stream, err) {
<ide> process.nextTick(emitCloseLegacy, stream);
<ide> }
<ide>
<del>function isDestroyed(stream) {
<del> return stream.destroyed || stream[kDestroyed];
<del>}
<del>
<del>function isReadable(stream) {
<del> return stream.readable && !stream.readableEnded && !isDestroyed(stream);
<del>}
<del>
<del>function isWritable(stream) {
<del> return stream.writable && !stream.writableEnded && !isDestroyed(stream);
<del>}
<del>
<ide> // Normalize destroy for legacy.
<ide> function destroyer(stream, err) {
<ide> if (isDestroyed(stream)) {
<ide> return;
<ide> }
<ide>
<del> if (!err && (isReadable(stream) || isWritable(stream))) {
<add> if (!err && !isFinished(stream)) {
<ide> err = new AbortError();
<ide> }
<ide>
<ide> // TODO: Remove isRequest branches.
<del> if (typeof stream[kDestroy] === 'function') {
<del> stream[kDestroy](err);
<add> if (isServerRequest(stream)) {
<add> stream.socket = null;
<add> stream.destroy(err);
<ide> } else if (isRequest(stream)) {
<ide> stream.abort();
<ide> } else if (isRequest(stream.req)) {
<ide> function destroyer(stream, err) {
<ide> }
<ide>
<ide> module.exports = {
<del> kDestroy,
<del> isDestroyed,
<ide> construct,
<ide> destroyer,
<ide> destroy,
<ide><path>lib/internal/streams/end-of-stream.js
<ide> const {
<ide> validateObject,
<ide> } = require('internal/validators');
<ide>
<add>const {
<add> isClosed,
<add> isReadable,
<add> isReadableNodeStream,
<add> isReadableFinished,
<add> isWritable,
<add> isWritableNodeStream,
<add> isWritableFinished,
<add> willEmitClose: _willEmitClose,
<add>} = require('internal/streams/utils');
<add>
<ide> function isRequest(stream) {
<ide> return stream.setHeader && typeof stream.abort === 'function';
<ide> }
<ide>
<del>function isServerResponse(stream) {
<del> return (
<del> typeof stream._sent100 === 'boolean' &&
<del> typeof stream._removedConnection === 'boolean' &&
<del> typeof stream._removedContLen === 'boolean' &&
<del> typeof stream._removedTE === 'boolean' &&
<del> typeof stream._closed === 'boolean'
<del> );
<del>}
<del>
<del>function isReadable(stream) {
<del> return typeof stream.readable === 'boolean' ||
<del> typeof stream.readableEnded === 'boolean' ||
<del> !!stream._readableState;
<del>}
<del>
<del>function isWritable(stream) {
<del> return typeof stream.writable === 'boolean' ||
<del> typeof stream.writableEnded === 'boolean' ||
<del> !!stream._writableState;
<del>}
<del>
<del>function isWritableFinished(stream) {
<del> if (stream.writableFinished) return true;
<del> const wState = stream._writableState;
<del> if (!wState || wState.errored) return false;
<del> return wState.finished || (wState.ended && wState.length === 0);
<del>}
<del>
<ide> const nop = () => {};
<ide>
<del>function isReadableEnded(stream) {
<del> if (stream.readableEnded) return true;
<del> const rState = stream._readableState;
<del> if (!rState || rState.errored) return false;
<del> return rState.endEmitted || (rState.ended && rState.length === 0);
<del>}
<del>
<ide> function eos(stream, options, callback) {
<ide> if (arguments.length === 2) {
<ide> callback = options;
<ide> function eos(stream, options, callback) {
<ide> callback = once(callback);
<ide>
<ide> const readable = options.readable ||
<del> (options.readable !== false && isReadable(stream));
<add> (options.readable !== false && isReadableNodeStream(stream));
<ide> const writable = options.writable ||
<del> (options.writable !== false && isWritable(stream));
<add> (options.writable !== false && isWritableNodeStream(stream));
<ide>
<ide> const wState = stream._writableState;
<ide> const rState = stream._readableState;
<del> const state = wState || rState;
<ide>
<ide> const onlegacyfinish = () => {
<ide> if (!stream.writable) onfinish();
<ide> function eos(stream, options, callback) {
<ide> // TODO (ronag): Improve soft detection to include core modules and
<ide> // common ecosystem modules that do properly emit 'close' but fail
<ide> // this generic check.
<del> let willEmitClose = isServerResponse(stream) || (
<del> state &&
<del> state.autoDestroy &&
<del> state.emitClose &&
<del> state.closed === false &&
<del> isReadable(stream) === readable &&
<del> isWritable(stream) === writable
<add> let willEmitClose = (
<add> _willEmitClose(stream) &&
<add> isReadableNodeStream(stream) === readable &&
<add> isWritableNodeStream(stream) === writable
<ide> );
<ide>
<del> let writableFinished = stream.writableFinished || wState?.finished;
<add> let writableFinished = isWritableFinished(stream, false);
<ide> const onfinish = () => {
<ide> writableFinished = true;
<ide> // Stream should not be destroyed here. If it is that
<ide> function eos(stream, options, callback) {
<ide> if (stream.destroyed) willEmitClose = false;
<ide>
<ide> if (willEmitClose && (!stream.readable || readable)) return;
<del> if (!readable || readableEnded) callback.call(stream);
<add> if (!readable || readableFinished) callback.call(stream);
<ide> };
<ide>
<del> let readableEnded = stream.readableEnded || rState?.endEmitted;
<add> let readableFinished = isReadableFinished(stream, false);
<ide> const onend = () => {
<del> readableEnded = true;
<add> readableFinished = true;
<ide> // Stream should not be destroyed here. If it is that
<ide> // means that user space is doing something differently and
<ide> // we cannot trust willEmitClose.
<ide> function eos(stream, options, callback) {
<ide> callback.call(stream, err);
<ide> };
<ide>
<del> let closed = wState?.closed || rState?.closed;
<add> let closed = isClosed(stream);
<ide>
<ide> const onclose = () => {
<ide> closed = true;
<ide> function eos(stream, options, callback) {
<ide> return callback.call(stream, errored);
<ide> }
<ide>
<del> if (readable && !readableEnded) {
<del> if (!isReadableEnded(stream))
<add> if (readable && !readableFinished) {
<add> if (!isReadableFinished(stream, false))
<ide> return callback.call(stream,
<ide> new ERR_STREAM_PREMATURE_CLOSE());
<ide> }
<ide> if (writable && !writableFinished) {
<del> if (!isWritableFinished(stream))
<add> if (!isWritableFinished(stream, false))
<ide> return callback.call(stream,
<ide> new ERR_STREAM_PREMATURE_CLOSE());
<ide> }
<ide> function eos(stream, options, callback) {
<ide> }
<ide> } else if (
<ide> !readable &&
<del> (!willEmitClose || stream.readable) &&
<del> writableFinished
<add> (!willEmitClose || isReadable(stream)) &&
<add> (writableFinished || !isWritable(stream))
<ide> ) {
<ide> process.nextTick(onclose);
<ide> } else if (
<ide> !writable &&
<del> (!willEmitClose || stream.writable) &&
<del> readableEnded
<add> (!willEmitClose || isWritable(stream)) &&
<add> (readableFinished || !isReadable(stream))
<ide> ) {
<ide> process.nextTick(onclose);
<del> } else if (!wState && !rState && stream._closed === true) {
<del> // _closed is for OutgoingMessage which is not a proper Writable.
<del> process.nextTick(onclose);
<ide> } else if ((rState && stream.req && stream.aborted)) {
<ide> process.nextTick(onclose);
<ide> }
<ide><path>lib/internal/streams/pipeline.js
<ide> const { validateCallback } = require('internal/validators');
<ide>
<ide> const {
<ide> isIterable,
<del> isReadable,
<del> isStream,
<add> isReadableNodeStream,
<add> isNodeStream,
<ide> } = require('internal/streams/utils');
<ide>
<ide> let PassThrough;
<ide> function popCallback(streams) {
<ide> function makeAsyncIterable(val) {
<ide> if (isIterable(val)) {
<ide> return val;
<del> } else if (isReadable(val)) {
<add> } else if (isReadableNodeStream(val)) {
<ide> // Legacy streams are not Iterable.
<ide> return fromReadable(val);
<ide> }
<ide> function pipeline(...streams) {
<ide> const reading = i < streams.length - 1;
<ide> const writing = i > 0;
<ide>
<del> if (isStream(stream)) {
<add> if (isNodeStream(stream)) {
<ide> finishCount++;
<ide> destroys.push(destroyer(stream, reading, writing, finish));
<ide> }
<ide> function pipeline(...streams) {
<ide> throw new ERR_INVALID_RETURN_VALUE(
<ide> 'Iterable, AsyncIterable or Stream', 'source', ret);
<ide> }
<del> } else if (isIterable(stream) || isReadable(stream)) {
<add> } else if (isIterable(stream) || isReadableNodeStream(stream)) {
<ide> ret = stream;
<ide> } else {
<ide> throw new ERR_INVALID_ARG_TYPE(
<ide> function pipeline(...streams) {
<ide> finishCount++;
<ide> destroys.push(destroyer(ret, false, true, finish));
<ide> }
<del> } else if (isStream(stream)) {
<del> if (isReadable(ret)) {
<add> } else if (isNodeStream(stream)) {
<add> if (isReadableNodeStream(ret)) {
<ide> ret.pipe(stream);
<ide>
<ide> // Compat. Before node v10.12.0 stdio used to throw an error so
<ide><path>lib/internal/streams/utils.js
<ide> 'use strict';
<ide>
<ide> const {
<add> Symbol,
<ide> SymbolAsyncIterator,
<ide> SymbolIterator,
<ide> } = primordials;
<ide>
<del>function isReadable(obj) {
<del> return !!(obj && typeof obj.pipe === 'function' &&
<del> typeof obj.on === 'function');
<add>const kDestroyed = Symbol('kDestroyed');
<add>
<add>function isReadableNodeStream(obj) {
<add> return !!(
<add> obj &&
<add> typeof obj.pipe === 'function' &&
<add> typeof obj.on === 'function' &&
<add> (!obj._writableState || obj._readableState?.readable !== false) && // Duplex
<add> (!obj._writableState || obj._readableState) // Writable has .pipe.
<add> );
<ide> }
<ide>
<del>function isWritable(obj) {
<del> return !!(obj && typeof obj.write === 'function' &&
<del> typeof obj.on === 'function');
<add>function isWritableNodeStream(obj) {
<add> return !!(
<add> obj &&
<add> typeof obj.write === 'function' &&
<add> typeof obj.on === 'function' &&
<add> (!obj._readableState || obj._writableState?.writable !== false) // Duplex
<add> );
<ide> }
<ide>
<del>function isStream(obj) {
<del> return isReadable(obj) || isWritable(obj);
<add>function isNodeStream(obj) {
<add> return isReadableNodeStream(obj) || isWritableNodeStream(obj);
<ide> }
<ide>
<ide> function isIterable(obj, isAsync) {
<ide> function isIterable(obj, isAsync) {
<ide> typeof obj[SymbolIterator] === 'function';
<ide> }
<ide>
<add>function isDestroyed(stream) {
<add> if (!isNodeStream(stream)) return null;
<add> const wState = stream._writableState;
<add> const rState = stream._readableState;
<add> const state = wState || rState;
<add> return !!(stream.destroyed || stream[kDestroyed] || state?.destroyed);
<add>}
<add>
<add>// Have been end():d.
<add>function isWritableEnded(stream) {
<add> if (!isWritableNodeStream(stream)) return null;
<add> if (stream.writableEnded === true) return true;
<add> const wState = stream._writableState;
<add> if (wState?.errored) return false;
<add> if (typeof wState?.ended !== 'boolean') return null;
<add> return wState.ended;
<add>}
<add>
<add>// Have emitted 'finish'.
<add>function isWritableFinished(stream, strict) {
<add> if (!isWritableNodeStream(stream)) return null;
<add> if (stream.writableFinished === true) return true;
<add> const wState = stream._writableState;
<add> if (wState?.errored) return false;
<add> if (typeof wState?.finished !== 'boolean') return null;
<add> return !!(
<add> wState.finished ||
<add> (strict === false && wState.ended === true && wState.length === 0)
<add> );
<add>}
<add>
<add>// Have been push(null):d.
<add>function isReadableEnded(stream) {
<add> if (!isReadableNodeStream(stream)) return null;
<add> if (stream.readableEnded === true) return true;
<add> const rState = stream._readableState;
<add> if (!rState || rState.errored) return false;
<add> if (typeof rState?.ended !== 'boolean') return null;
<add> return rState.ended;
<add>}
<add>
<add>// Have emitted 'end'.
<add>function isReadableFinished(stream, strict) {
<add> if (!isReadableNodeStream(stream)) return null;
<add> const rState = stream._readableState;
<add> if (rState?.errored) return false;
<add> if (typeof rState?.endEmitted !== 'boolean') return null;
<add> return !!(
<add> rState.endEmitted ||
<add> (strict === false && rState.ended === true && rState.length === 0)
<add> );
<add>}
<add>
<add>function isReadable(stream) {
<add> const r = isReadableNodeStream(stream);
<add> if (r === null || typeof stream.readable !== 'boolean') return null;
<add> if (isDestroyed(stream)) return false;
<add> return r && stream.readable && !isReadableFinished(stream);
<add>}
<add>
<add>function isWritable(stream) {
<add> const r = isWritableNodeStream(stream);
<add> if (r === null || typeof stream.writable !== 'boolean') return null;
<add> if (isDestroyed(stream)) return false;
<add> return r && stream.writable && !isWritableEnded(stream);
<add>}
<add>
<add>function isFinished(stream, opts) {
<add> if (!isNodeStream(stream)) {
<add> return null;
<add> }
<add>
<add> if (isDestroyed(stream)) {
<add> return true;
<add> }
<add>
<add> if (opts?.readable !== false && isReadable(stream)) {
<add> return false;
<add> }
<add>
<add> if (opts?.writable !== false && isWritable(stream)) {
<add> return false;
<add> }
<add>
<add> return true;
<add>}
<add>
<add>function isClosed(stream) {
<add> if (!isNodeStream(stream)) {
<add> return null;
<add> }
<add>
<add> const wState = stream._writableState;
<add> const rState = stream._readableState;
<add>
<add> if (
<add> typeof wState?.closed === 'boolean' ||
<add> typeof rState?.closed === 'boolean'
<add> ) {
<add> return wState?.closed || rState?.closed;
<add> }
<add>
<add> if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) {
<add> return stream._closed;
<add> }
<add>
<add> return null;
<add>}
<add>
<add>function isOutgoingMessage(stream) {
<add> return (
<add> typeof stream._closed === 'boolean' &&
<add> typeof stream._defaultKeepAlive === 'boolean' &&
<add> typeof stream._removedConnection === 'boolean' &&
<add> typeof stream._removedContLen === 'boolean'
<add> );
<add>}
<add>
<add>function isServerResponse(stream) {
<add> return (
<add> typeof stream._sent100 === 'boolean' &&
<add> isOutgoingMessage(stream)
<add> );
<add>}
<add>
<add>function isServerRequest(stream) {
<add> return (
<add> typeof stream._consuming === 'boolean' &&
<add> typeof stream._dumped === 'boolean' &&
<add> stream.req?.upgradeOrConnect === undefined
<add> );
<add>}
<add>
<add>function willEmitClose(stream) {
<add> if (!isNodeStream(stream)) return null;
<add>
<add> const wState = stream._writableState;
<add> const rState = stream._readableState;
<add> const state = wState || rState;
<add>
<add> return (!state && isServerResponse(stream)) || !!(
<add> state &&
<add> state.autoDestroy &&
<add> state.emitClose &&
<add> state.closed === false
<add> );
<add>}
<add>
<ide> module.exports = {
<add> kDestroyed,
<add> isClosed,
<add> isDestroyed,
<add> isFinished,
<ide> isIterable,
<ide> isReadable,
<del> isStream,
<add> isReadableNodeStream,
<add> isReadableEnded,
<add> isReadableFinished,
<add> isNodeStream,
<add> isWritable,
<add> isWritableNodeStream,
<add> isWritableEnded,
<add> isWritableFinished,
<add> isServerRequest,
<add> isServerResponse,
<add> willEmitClose,
<ide> };
<ide><path>lib/stream/promises.js
<ide> const {
<ide>
<ide> const {
<ide> isIterable,
<del> isStream,
<add> isNodeStream,
<ide> } = require('internal/streams/utils');
<ide>
<ide> const pl = require('internal/streams/pipeline');
<ide> function pipeline(...streams) {
<ide> let signal;
<ide> const lastArg = streams[streams.length - 1];
<ide> if (lastArg && typeof lastArg === 'object' &&
<del> !isStream(lastArg) && !isIterable(lastArg)) {
<add> !isNodeStream(lastArg) && !isIterable(lastArg)) {
<ide> const options = ArrayPrototypePop(streams);
<ide> signal = options.signal;
<ide> validateAbortSignal(signal, 'options.signal');
<ide><path>test/parallel/test-stream-finished.js
<ide> testClosed((opts) => new Writable({ write() {}, ...opts }));
<ide> d._writableState = {};
<ide> d._writableState.finished = true;
<ide> finished(d, { readable: false, writable: true }, common.mustCall((err) => {
<del> assert.strictEqual(err, undefined);
<add> assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE');
<ide> }));
<ide> d._writableState.errored = true;
<ide> d.emit('close');
<ide> testClosed((opts) => new Writable({ write() {}, ...opts }));
<ide> });
<ide> }
<ide>
<del>
<ide> {
<ide> const w = new Writable({
<ide> write(chunk, encoding, callback) {
<ide><path>test/parallel/test-stream-pipeline.js
<ide> const net = require('net');
<ide> const dst = new PassThrough();
<ide> dst.readable = false;
<ide> pipeline(src, dst, common.mustSucceed(() => {
<del> assert.strictEqual(dst.destroyed, false);
<add> assert.strictEqual(dst.destroyed, true);
<ide> }));
<ide> src.end();
<ide> } | 10 |
Javascript | Javascript | avoid hostname spoofing w/ javascript protocol | b77f699a84219702ccef6387882c0fdcb58529bb | <ide><path>lib/url.js
<ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
<ide> if (slashesDenoteHost || proto || hostPattern.test(rest)) {
<ide> var slashes = rest.charCodeAt(0) === CHAR_FORWARD_SLASH &&
<ide> rest.charCodeAt(1) === CHAR_FORWARD_SLASH;
<del> if (slashes && !(proto && hostlessProtocol[proto])) {
<add> if (slashes && !(proto && hostlessProtocol[lowerProto])) {
<ide> rest = rest.slice(2);
<ide> this.slashes = true;
<ide> }
<ide> }
<ide>
<del> if (!hostlessProtocol[proto] &&
<add> if (!hostlessProtocol[lowerProto] &&
<ide> (slashes || (proto && !slashedProtocol[proto]))) {
<ide>
<ide> // there's a hostname.
<ide><path>test/parallel/test-url-parse-format.js
<ide> const parseTests = {
<ide> pathname: '/*',
<ide> path: '/*',
<ide> href: 'https:///*'
<add> },
<add>
<add> // The following two URLs are the same, but they differ for
<add> // a capital A: it is important that we verify that the protocol
<add> // is checked in a case-insensitive manner.
<add> 'javascript:alert(1);a=\x27@white-listed.com\x27': {
<add> protocol: 'javascript:',
<add> slashes: null,
<add> auth: null,
<add> host: null,
<add> port: null,
<add> hostname: null,
<add> hash: null,
<add> search: null,
<add> query: null,
<add> pathname: "alert(1);a='@white-listed.com'",
<add> path: "alert(1);a='@white-listed.com'",
<add> href: "javascript:alert(1);a='@white-listed.com'"
<add> },
<add>
<add> 'javAscript:alert(1);a=\x27@white-listed.com\x27': {
<add> protocol: 'javascript:',
<add> slashes: null,
<add> auth: null,
<add> host: null,
<add> port: null,
<add> hostname: null,
<add> hash: null,
<add> search: null,
<add> query: null,
<add> pathname: "alert(1);a='@white-listed.com'",
<add> path: "alert(1);a='@white-listed.com'",
<add> href: "javascript:alert(1);a='@white-listed.com'"
<ide> }
<ide> };
<ide>
<ide> for (const u in parseTests) {
<ide> assert.strictEqual(actual, expected,
<ide> `format(${u}) == ${u}\nactual:${actual}`);
<ide> }
<add>
<add>{
<add> const parsed = url.parse('http://nodejs.org/')
<add> .resolveObject('jAvascript:alert(1);a=\x27@white-listed.com\x27');
<add>
<add> const expected = Object.assign(new url.Url(), {
<add> protocol: 'javascript:',
<add> slashes: null,
<add> auth: null,
<add> host: null,
<add> port: null,
<add> hostname: null,
<add> hash: null,
<add> search: null,
<add> query: null,
<add> pathname: "alert(1);a='@white-listed.com'",
<add> path: "alert(1);a='@white-listed.com'",
<add> href: "javascript:alert(1);a='@white-listed.com'"
<add> });
<add>
<add> assert.deepStrictEqual(parsed, expected);
<add>} | 2 |
Python | Python | use the old clone loss name instead | 289b439308be829db258d5b1bb33a6de03769e57 | <ide><path>slim/deployment/model_deploy.py
<ide> def _gather_clone_loss(clone, num_clones, regularization_losses):
<ide> sum_loss = tf.add_n(all_losses)
<ide> # Add the summaries out of the clone device block.
<ide> if clone_loss is not None:
<del> tf.summary.scalar('clone_loss', clone_loss)
<add> tf.summary.scalar(clone.scope + '/clone_loss', clone_loss)
<ide> if regularization_loss is not None:
<ide> tf.summary.scalar('regularization_loss', regularization_loss)
<ide> return sum_loss | 1 |
Ruby | Ruby | add didyoumean for parametermissing | 5411565d44d9a60ed00ba3158abcb6ed80129b33 | <ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb
<ide> module ActionController
<ide> # params.require(:a)
<ide> # # => ActionController::ParameterMissing: param is missing or the value is empty: a
<ide> class ParameterMissing < KeyError
<del> attr_reader :param # :nodoc:
<add> attr_reader :param, :keys # :nodoc:
<ide>
<del> def initialize(param) # :nodoc:
<add> def initialize(param, keys = nil) # :nodoc:
<ide> @param = param
<add> @keys = keys
<ide> super("param is missing or the value is empty: #{param}")
<ide> end
<add>
<add> class Correction
<add> def initialize(error)
<add> @error = error
<add> end
<add>
<add> def corrections
<add> if @error.param && @error.keys
<add> maybe_these = @error.keys
<add>
<add> maybe_these.sort_by { |n|
<add> DidYouMean::Jaro.distance(@error.param.to_s, n)
<add> }.reverse.first(4)
<add> else
<add> []
<add> end
<add> end
<add> end
<add>
<add> # We may not have DYM, and DYM might not let us register error handlers
<add> if defined?(DidYouMean) && DidYouMean.respond_to?(:correct_error)
<add> DidYouMean.correct_error(self, Correction)
<add> end
<ide> end
<ide>
<ide> # Raised when a supplied parameter is not expected and
<ide> def require(key)
<ide> if value.present? || value == false
<ide> value
<ide> else
<del> raise ParameterMissing.new(key)
<add> raise ParameterMissing.new(key, @parameters.keys)
<ide> end
<ide> end
<ide>
<ide> def fetch(key, *args)
<ide> if block_given?
<ide> yield
<ide> else
<del> args.fetch(0) { raise ActionController::ParameterMissing.new(key) }
<add> args.fetch(0) { raise ActionController::ParameterMissing.new(key, @parameters.keys) }
<ide> end
<ide> }
<ide> )
<ide><path>actionpack/test/controller/required_params_test.rb
<ide> class ActionControllerRequiredParamsTest < ActionController::TestCase
<ide> end
<ide> end
<ide>
<add> if defined?(DidYouMean) && DidYouMean.respond_to?(:correct_error)
<add> test "exceptions have suggestions for fix" do
<add> error = assert_raise ActionController::ParameterMissing do
<add> post :create, params: { magazine: { name: "Mjallo!" } }
<add> end
<add> assert_match "Did you mean?", error.message
<add>
<add> error = assert_raise ActionController::ParameterMissing do
<add> post :create, params: { book: { title: "Mjallo!" } }
<add> end
<add> assert_match "Did you mean?", error.message
<add> end
<add> end
<add>
<ide> test "required parameters that are present will not raise" do
<ide> post :create, params: { book: { name: "Mjallo!" } }
<ide> assert_response :ok | 2 |
Javascript | Javascript | use relative imports in ember-htmlbars | 94d379d95f992c395ffae407d7df92589c7cc0a5 | <ide><path>packages/ember-htmlbars/lib/env.js
<ide> import { hooks } from 'htmlbars-runtime';
<ide> import assign from 'ember-metal/assign';
<ide> import isEnabled from 'ember-metal/features';
<ide>
<del>import subexpr from 'ember-htmlbars/hooks/subexpr';
<del>import concat from 'ember-htmlbars/hooks/concat';
<del>import linkRenderNode from 'ember-htmlbars/hooks/link-render-node';
<del>import createFreshScope, { createChildScope } from 'ember-htmlbars/hooks/create-fresh-scope';
<del>import bindShadowScope from 'ember-htmlbars/hooks/bind-shadow-scope';
<del>import bindSelf from 'ember-htmlbars/hooks/bind-self';
<del>import bindScope from 'ember-htmlbars/hooks/bind-scope';
<del>import bindLocal from 'ember-htmlbars/hooks/bind-local';
<del>import bindBlock from 'ember-htmlbars/hooks/bind-block';
<del>import updateSelf from 'ember-htmlbars/hooks/update-self';
<del>import getRoot from 'ember-htmlbars/hooks/get-root';
<del>import getChild from 'ember-htmlbars/hooks/get-child';
<del>import getBlock from 'ember-htmlbars/hooks/get-block';
<del>import getValue from 'ember-htmlbars/hooks/get-value';
<del>import getCellOrValue from 'ember-htmlbars/hooks/get-cell-or-value';
<del>import cleanupRenderNode from 'ember-htmlbars/hooks/cleanup-render-node';
<del>import destroyRenderNode from 'ember-htmlbars/hooks/destroy-render-node';
<del>import didRenderNode from 'ember-htmlbars/hooks/did-render-node';
<del>import willCleanupTree from 'ember-htmlbars/hooks/will-cleanup-tree';
<del>import didCleanupTree from 'ember-htmlbars/hooks/did-cleanup-tree';
<del>import classify from 'ember-htmlbars/hooks/classify';
<del>import component from 'ember-htmlbars/hooks/component';
<del>import lookupHelper from 'ember-htmlbars/hooks/lookup-helper';
<del>import hasHelper from 'ember-htmlbars/hooks/has-helper';
<del>import invokeHelper from 'ember-htmlbars/hooks/invoke-helper';
<del>import element from 'ember-htmlbars/hooks/element';
<add>import subexpr from './hooks/subexpr';
<add>import concat from './hooks/concat';
<add>import linkRenderNode from './hooks/link-render-node';
<add>import createFreshScope, { createChildScope } from './hooks/create-fresh-scope';
<add>import bindShadowScope from './hooks/bind-shadow-scope';
<add>import bindSelf from './hooks/bind-self';
<add>import bindScope from './hooks/bind-scope';
<add>import bindLocal from './hooks/bind-local';
<add>import bindBlock from './hooks/bind-block';
<add>import updateSelf from './hooks/update-self';
<add>import getRoot from './hooks/get-root';
<add>import getChild from './hooks/get-child';
<add>import getBlock from './hooks/get-block';
<add>import getValue from './hooks/get-value';
<add>import getCellOrValue from './hooks/get-cell-or-value';
<add>import cleanupRenderNode from './hooks/cleanup-render-node';
<add>import destroyRenderNode from './hooks/destroy-render-node';
<add>import didRenderNode from './hooks/did-render-node';
<add>import willCleanupTree from './hooks/will-cleanup-tree';
<add>import didCleanupTree from './hooks/did-cleanup-tree';
<add>import classify from './hooks/classify';
<add>import component from './hooks/component';
<add>import lookupHelper from './hooks/lookup-helper';
<add>import hasHelper from './hooks/has-helper';
<add>import invokeHelper from './hooks/invoke-helper';
<add>import element from './hooks/element';
<ide>
<del>import helpers from 'ember-htmlbars/helpers';
<del>import keywords, { registerKeyword } from 'ember-htmlbars/keywords';
<add>import helpers from './helpers';
<add>import keywords, { registerKeyword } from './keywords';
<ide>
<del>import DOMHelper from 'ember-htmlbars/system/dom-helper';
<add>import DOMHelper from './system/dom-helper';
<ide>
<ide> const emberHooks = assign({}, hooks);
<ide> emberHooks.keywords = keywords;
<ide> assign(emberHooks, {
<ide> element
<ide> });
<ide>
<del>import debuggerKeyword from 'ember-htmlbars/keywords/debugger';
<del>import withKeyword from 'ember-htmlbars/keywords/with';
<del>import outlet from 'ember-htmlbars/keywords/outlet';
<del>import unbound from 'ember-htmlbars/keywords/unbound';
<del>import componentKeyword from 'ember-htmlbars/keywords/component';
<del>import elementComponent from 'ember-htmlbars/keywords/element-component';
<del>import mount from 'ember-htmlbars/keywords/mount';
<del>import partial from 'ember-htmlbars/keywords/partial';
<del>import input from 'ember-htmlbars/keywords/input';
<del>import textarea from 'ember-htmlbars/keywords/textarea';
<del>import yieldKeyword from 'ember-htmlbars/keywords/yield';
<del>import mut, { privateMut } from 'ember-htmlbars/keywords/mut';
<del>import readonly from 'ember-htmlbars/keywords/readonly';
<del>import getKeyword from 'ember-htmlbars/keywords/get';
<del>import actionKeyword from 'ember-htmlbars/keywords/action';
<del>import renderKeyword from 'ember-htmlbars/keywords/render';
<del>import elementActionKeyword from 'ember-htmlbars/keywords/element-action';
<add>import debuggerKeyword from './keywords/debugger';
<add>import withKeyword from './keywords/with';
<add>import outlet from './keywords/outlet';
<add>import unbound from './keywords/unbound';
<add>import componentKeyword from './keywords/component';
<add>import elementComponent from './keywords/element-component';
<add>import mount from './keywords/mount';
<add>import partial from './keywords/partial';
<add>import input from './keywords/input';
<add>import textarea from './keywords/textarea';
<add>import yieldKeyword from './keywords/yield';
<add>import mut, { privateMut } from './keywords/mut';
<add>import readonly from './keywords/readonly';
<add>import getKeyword from './keywords/get';
<add>import actionKeyword from './keywords/action';
<add>import renderKeyword from './keywords/render';
<add>import elementActionKeyword from './keywords/element-action';
<ide>
<ide> registerKeyword('debugger', debuggerKeyword);
<ide> registerKeyword('with', withKeyword);
<ide><path>packages/ember-htmlbars/lib/helpers/each.js
<ide> */
<ide>
<ide> import shouldDisplay from '../streams/should_display';
<del>import decodeEachKey from 'ember-htmlbars/utils/decode-each-key';
<add>import decodeEachKey from '../utils/decode-each-key';
<ide>
<ide> /**
<ide> The `{{#each}}` helper loops over elements in a collection. It is an extension
<ide><path>packages/ember-htmlbars/lib/hooks/classify.js
<ide> @submodule ember-htmlbars
<ide> */
<ide>
<del>import isComponent from 'ember-htmlbars/utils/is-component';
<add>import isComponent from '../utils/is-component';
<ide>
<ide> export default function classify(env, scope, path) {
<ide> if (isComponent(env, scope, path)) {
<ide><path>packages/ember-htmlbars/lib/hooks/component.js
<ide> import { assert } from 'ember-metal/debug';
<del>import ComponentNodeManager from 'ember-htmlbars/node-managers/component-node-manager';
<add>import ComponentNodeManager from '../node-managers/component-node-manager';
<ide> import lookupComponent from 'ember-views/utils/lookup-component';
<ide> import assign from 'ember-metal/assign';
<ide> import EmptyObject from 'ember-metal/empty_object';
<ide> import {
<ide> CONTAINS_DOT_CACHE
<del>} from 'ember-htmlbars/system/lookup-helper';
<del>import extractPositionalParams from 'ember-htmlbars/utils/extract-positional-params';
<add>} from '../system/lookup-helper';
<add>import extractPositionalParams from '../utils/extract-positional-params';
<ide> import {
<ide> COMPONENT_HASH,
<ide> COMPONENT_PATH,
<ide> COMPONENT_POSITIONAL_PARAMS,
<ide> isComponentCell,
<ide> mergeInNewHash,
<ide> processPositionalParamsFromCell,
<del>} from 'ember-htmlbars/keywords/closure-component';
<add>} from '../keywords/closure-component';
<ide>
<ide> export default function componentHook(renderNode, env, scope, _tagName, params, _attrs, templates, visitor) {
<ide> let state = renderNode.getState();
<ide><path>packages/ember-htmlbars/lib/hooks/element.js
<ide> @submodule ember-htmlbars
<ide> */
<ide>
<del>import { findHelper } from 'ember-htmlbars/system/lookup-helper';
<add>import { findHelper } from '../system/lookup-helper';
<ide> import { handleRedirect } from 'htmlbars-runtime/hooks';
<del>import { buildHelperStream } from 'ember-htmlbars/system/invoke-helper';
<add>import { buildHelperStream } from '../system/invoke-helper';
<ide>
<ide> export default function emberElement(morph, env, scope, path, params, hash, visitor) {
<ide> if (handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) {
<ide><path>packages/ember-htmlbars/lib/hooks/get-cell-or-value.js
<ide> import { read } from '../streams/utils';
<del>import { MUTABLE_REFERENCE } from 'ember-htmlbars/keywords/mut';
<add>import { MUTABLE_REFERENCE } from '../keywords/mut';
<ide>
<ide> export default function getCellOrValue(ref) {
<ide> if (ref && ref[MUTABLE_REFERENCE]) {
<ide><path>packages/ember-htmlbars/lib/hooks/has-helper.js
<del>import { validateLazyHelperName } from 'ember-htmlbars/system/lookup-helper';
<add>import { validateLazyHelperName } from '../system/lookup-helper';
<ide>
<ide> export default function hasHelperHook(env, scope, helperName) {
<ide> if (env.helpers[helperName]) {
<ide><path>packages/ember-htmlbars/lib/hooks/invoke-helper.js
<del>import { buildHelperStream } from 'ember-htmlbars/system/invoke-helper';
<del>import subscribe from 'ember-htmlbars/utils/subscribe';
<add>import { buildHelperStream } from '../system/invoke-helper';
<add>import subscribe from '../utils/subscribe';
<ide>
<ide> export default function invokeHelper(morph, env, scope, visitor, params, hash, helper, templates, context) {
<ide> let helperStream = buildHelperStream(helper, params, hash, templates, env, scope);
<ide><path>packages/ember-htmlbars/lib/hooks/link-render-node.js
<ide> @submodule ember-htmlbars
<ide> */
<ide>
<del>import subscribe from 'ember-htmlbars/utils/subscribe';
<add>import subscribe from '../utils/subscribe';
<ide> import { isArray } from 'ember-runtime/utils';
<ide> import { chain, read, isStream, addDependency } from '../streams/utils';
<del>import { CONTAINS_DOT_CACHE } from 'ember-htmlbars/system/lookup-helper';
<add>import { CONTAINS_DOT_CACHE } from '../system/lookup-helper';
<ide> import {
<ide> COMPONENT_HASH,
<ide> isComponentCell,
<ide> mergeInNewHash
<del>} from 'ember-htmlbars/keywords/closure-component';
<add>} from '../keywords/closure-component';
<ide>
<ide> export default function linkRenderNode(renderNode, env, scope, path, params, hash) {
<ide> if (renderNode.streamUnsubscribers) {
<ide><path>packages/ember-htmlbars/lib/hooks/lookup-helper.js
<del>import lookupHelper from 'ember-htmlbars/system/lookup-helper';
<add>import lookupHelper from '../system/lookup-helper';
<ide>
<ide> export default function lookupHelperHook(env, scope, helperName) {
<ide> return lookupHelper(helperName, scope.getSelf(), env);
<ide><path>packages/ember-htmlbars/lib/hooks/subexpr.js
<ide> @submodule ember-htmlbars
<ide> */
<ide>
<del>import lookupHelper from 'ember-htmlbars/system/lookup-helper';
<del>import { buildHelperStream } from 'ember-htmlbars/system/invoke-helper';
<add>import lookupHelper from '../system/lookup-helper';
<add>import { buildHelperStream } from '../system/invoke-helper';
<ide> import {
<ide> labelsFor,
<ide> labelFor
<ide> } from '../streams/utils';
<del>import { linkParamsFor } from 'ember-htmlbars/hooks/link-render-node';
<add>import { linkParamsFor } from './link-render-node';
<ide>
<ide> export default function subexpr(env, scope, helperName, params, hash) {
<ide> // TODO: Keywords and helper invocation should be integrated into
<ide><path>packages/ember-htmlbars/lib/index.js
<ide> import Ember from 'ember-metal/core'; // exposing Ember.HTMLBars
<ide>
<ide> import {
<ide> registerHelper
<del>} from 'ember-htmlbars/helpers';
<add>} from './helpers';
<ide> import {
<ide> ifHelper,
<ide> unlessHelper
<del>} from 'ember-htmlbars/helpers/if_unless';
<del>import withHelper from 'ember-htmlbars/helpers/with';
<del>import locHelper from 'ember-htmlbars/helpers/loc';
<del>import logHelper from 'ember-htmlbars/helpers/log';
<del>import eachHelper from 'ember-htmlbars/helpers/each';
<del>import eachInHelper from 'ember-htmlbars/helpers/each-in';
<del>import normalizeClassHelper from 'ember-htmlbars/helpers/-normalize-class';
<del>import concatHelper from 'ember-htmlbars/helpers/concat';
<del>import joinClassesHelper from 'ember-htmlbars/helpers/-join-classes';
<del>import htmlSafeHelper from 'ember-htmlbars/helpers/-html-safe';
<del>import hashHelper from 'ember-htmlbars/helpers/hash';
<del>import queryParamsHelper from 'ember-htmlbars/helpers/query-params';
<del>import DOMHelper from 'ember-htmlbars/system/dom-helper';
<add>} from './helpers/if_unless';
<add>import withHelper from './helpers/with';
<add>import locHelper from './helpers/loc';
<add>import logHelper from './helpers/log';
<add>import eachHelper from './helpers/each';
<add>import eachInHelper from './helpers/each-in';
<add>import normalizeClassHelper from './helpers/-normalize-class';
<add>import concatHelper from './helpers/concat';
<add>import joinClassesHelper from './helpers/-join-classes';
<add>import htmlSafeHelper from './helpers/-html-safe';
<add>import hashHelper from './helpers/hash';
<add>import queryParamsHelper from './helpers/query-params';
<add>import DOMHelper from './system/dom-helper';
<ide>
<ide> export { default as template } from './system/template';
<ide>
<ide><path>packages/ember-htmlbars/lib/keywords/action.js
<ide> */
<ide>
<ide> import { keyword } from 'htmlbars-runtime/hooks';
<del>import closureAction from 'ember-htmlbars/keywords/closure-action';
<add>import closureAction from './closure-action';
<ide>
<ide> /**
<ide> The `{{action}}` helper provides a way to pass triggers for behavior (usually
<ide><path>packages/ember-htmlbars/lib/keywords/closure-action.js
<del>import { Stream } from 'ember-htmlbars/streams/stream';
<add>import { Stream } from '../streams/stream';
<ide> import {
<ide> read,
<ide> readArray,
<ide> labelFor
<del>} from 'ember-htmlbars/streams/utils';
<add>} from '../streams/utils';
<ide> import symbol from 'ember-metal/symbol';
<ide> import { get } from 'ember-metal/property_get';
<del>import { labelForSubexpr } from 'ember-htmlbars/hooks/subexpr';
<add>import { labelForSubexpr } from '../hooks/subexpr';
<ide> import EmberError from 'ember-metal/error';
<ide> import run from 'ember-metal/run_loop';
<ide> import { flaggedInstrument } from 'ember-metal/instrumentation';
<ide><path>packages/ember-htmlbars/lib/keywords/closure-component.js
<ide> import symbol from 'ember-metal/symbol';
<ide> import BasicStream from '../streams/stream';
<ide> import EmptyObject from 'ember-metal/empty_object';
<ide> import { read } from '../streams/utils';
<del>import { labelForSubexpr } from 'ember-htmlbars/hooks/subexpr';
<add>import { labelForSubexpr } from '../hooks/subexpr';
<ide> import assign from 'ember-metal/assign';
<del>import { isRestPositionalParams, processPositionalParams } from 'ember-htmlbars/utils/extract-positional-params';
<add>import { isRestPositionalParams, processPositionalParams } from '../utils/extract-positional-params';
<ide> import lookupComponent from 'ember-views/utils/lookup-component';
<ide>
<ide> export const COMPONENT_REFERENCE = symbol('COMPONENT_REFERENCE');
<ide><path>packages/ember-htmlbars/lib/keywords/component.js
<ide> @public
<ide> */
<ide> import { keyword } from 'htmlbars-runtime/hooks';
<del>import closureComponent from 'ember-htmlbars/keywords/closure-component';
<add>import closureComponent from './closure-component';
<ide> import EmptyObject from 'ember-metal/empty_object';
<ide> import assign from 'ember-metal/assign';
<ide>
<ide><path>packages/ember-htmlbars/lib/keywords/element-action.js
<ide> import { assert } from 'ember-metal/debug';
<ide> import { uuid } from 'ember-metal/utils';
<del>import { labelFor, read } from 'ember-htmlbars/streams/utils';
<add>import { labelFor, read } from '../streams/utils';
<ide> import run from 'ember-metal/run_loop';
<del>import { readUnwrappedModel } from 'ember-htmlbars/streams/utils';
<add>import { readUnwrappedModel } from '../streams/utils';
<ide> import { isSimpleClick } from 'ember-views/system/utils';
<ide> import ActionManager from 'ember-views/system/action_manager';
<ide> import { flaggedInstrument } from 'ember-metal/instrumentation';
<ide><path>packages/ember-htmlbars/lib/keywords/element-component.js
<ide> import {
<ide> processPositionalParamsFromCell,
<ide> } from './closure-component';
<ide> import lookupComponent from 'ember-views/utils/lookup-component';
<del>import extractPositionalParams from 'ember-htmlbars/utils/extract-positional-params';
<add>import extractPositionalParams from '../utils/extract-positional-params';
<ide>
<ide> export default {
<ide> setupState(lastState, env, scope, params, hash) {
<ide><path>packages/ember-htmlbars/lib/keywords/get.js
<ide> import { assert } from 'ember-metal/debug';
<ide> import BasicStream from '../streams/stream';
<ide> import { isStream } from '../streams/utils';
<del>import subscribe from 'ember-htmlbars/utils/subscribe';
<add>import subscribe from '../utils/subscribe';
<ide> import { get } from 'ember-metal/property_get';
<ide> import { set } from 'ember-metal/property_set';
<ide> import {
<ide><path>packages/ember-htmlbars/lib/keywords/mount.js
<ide> @submodule ember-templates
<ide> */
<ide>
<del>import ViewNodeManager from 'ember-htmlbars/node-managers/view-node-manager';
<del>import RenderEnv from 'ember-htmlbars/system/render-env';
<add>import ViewNodeManager from '../node-managers/view-node-manager';
<add>import RenderEnv from '../system/render-env';
<ide> import { assert } from 'ember-metal/debug';
<ide> import { getOwner, setOwner } from 'container/owner';
<ide> import { isOutletStable } from './outlet';
<ide><path>packages/ember-htmlbars/lib/keywords/mut.js
<ide> import ProxyStream from '../streams/proxy-stream';
<ide> import BasicStream from '../streams/stream';
<ide> import { isStream } from '../streams/utils';
<ide> import { MUTABLE_CELL } from 'ember-views/compat/attrs-proxy';
<del>import { INVOKE, ACTION } from 'ember-htmlbars/keywords/closure-action';
<add>import { INVOKE, ACTION } from './closure-action';
<ide>
<ide> export let MUTABLE_REFERENCE = symbol('MUTABLE_REFERENCE');
<ide>
<ide><path>packages/ember-htmlbars/lib/keywords/outlet.js
<ide> @submodule ember-templates
<ide> */
<ide>
<del>import ViewNodeManager from 'ember-htmlbars/node-managers/view-node-manager';
<del>import topLevelViewTemplate from 'ember-htmlbars/templates/top-level-view';
<add>import ViewNodeManager from '../node-managers/view-node-manager';
<add>import topLevelViewTemplate from '../templates/top-level-view';
<ide> import isEnabled from 'ember-metal/features';
<ide> import VERSION from 'ember/version';
<ide>
<ide><path>packages/ember-htmlbars/lib/keywords/readonly.js
<ide> @submodule ember-templates
<ide> */
<ide>
<del>import { MUTABLE_REFERENCE } from 'ember-htmlbars/keywords/mut';
<add>import { MUTABLE_REFERENCE } from './mut';
<ide>
<ide> export default function readonly(morph, env, scope, originalParams, hash, template, inverse) {
<ide> // If `morph` is `null` the keyword is being invoked as a subexpression.
<ide><path>packages/ember-htmlbars/lib/keywords/render.js
<ide> import { assert } from 'ember-metal/debug';
<ide> import EmptyObject from 'ember-metal/empty_object';
<ide> import EmberError from 'ember-metal/error';
<del>import { isStream, read } from 'ember-htmlbars/streams/utils';
<add>import { isStream, read } from '../streams/utils';
<ide> import generateController from 'ember-routing/system/generate_controller';
<ide> import { generateControllerFactory } from 'ember-routing/system/generate_controller';
<del>import ViewNodeManager from 'ember-htmlbars/node-managers/view-node-manager';
<add>import ViewNodeManager from '../node-managers/view-node-manager';
<ide>
<ide> /**
<ide> Calling ``{{render}}`` from within a template will insert another
<ide><path>packages/ember-htmlbars/lib/node-managers/component-node-manager.js
<ide> import { assert, warn } from 'ember-metal/debug';
<del>import buildComponentTemplate from 'ember-htmlbars/system/build-component-template';
<del>import getCellOrValue from 'ember-htmlbars/hooks/get-cell-or-value';
<add>import buildComponentTemplate from '../system/build-component-template';
<add>import getCellOrValue from '../hooks/get-cell-or-value';
<ide> import { get } from 'ember-metal/property_get';
<ide> import { MUTABLE_CELL } from 'ember-views/compat/attrs-proxy';
<del>import { instrument } from 'ember-htmlbars/system/instrumentation-support';
<del>import EmberComponent, { HAS_BLOCK } from 'ember-htmlbars/component';
<del>import extractPositionalParams from 'ember-htmlbars/utils/extract-positional-params';
<add>import { instrument } from '../system/instrumentation-support';
<add>import EmberComponent, { HAS_BLOCK } from '../component';
<add>import extractPositionalParams from '../utils/extract-positional-params';
<ide> import { setOwner, getOwner } from 'container/owner';
<ide>
<ide> // In theory this should come through the env, but it should
<ide> // be safe to import this until we make the hook system public
<ide> // and it gets actively used in addons or other downstream
<ide> // libraries.
<del>import getValue from 'ember-htmlbars/hooks/get-value';
<add>import getValue from '../hooks/get-value';
<ide>
<ide> export default function ComponentNodeManager(component, scope, renderNode, attrs, block, expectElement) {
<ide> this.component = component;
<ide><path>packages/ember-htmlbars/lib/node-managers/view-node-manager.js
<ide> import assign from 'ember-metal/assign';
<ide> import { assert, warn } from 'ember-metal/debug';
<del>import buildComponentTemplate from 'ember-htmlbars/system/build-component-template';
<add>import buildComponentTemplate from '../system/build-component-template';
<ide> import { get } from 'ember-metal/property_get';
<ide> import setProperties from 'ember-metal/set_properties';
<ide> import { MUTABLE_CELL } from 'ember-views/compat/attrs-proxy';
<del>import getCellOrValue from 'ember-htmlbars/hooks/get-cell-or-value';
<del>import { instrument } from 'ember-htmlbars/system/instrumentation-support';
<del>import { takeLegacySnapshot } from 'ember-htmlbars/node-managers/component-node-manager';
<add>import getCellOrValue from '../hooks/get-cell-or-value';
<add>import { instrument } from '../system/instrumentation-support';
<add>import { takeLegacySnapshot } from './component-node-manager';
<ide> import { setOwner } from 'container/owner';
<ide>
<ide> // In theory this should come through the env, but it should
<ide> // be safe to import this until we make the hook system public
<ide> // and it gets actively used in addons or other downstream
<ide> // libraries.
<del>import getValue from 'ember-htmlbars/hooks/get-value';
<add>import getValue from '../hooks/get-value';
<ide>
<ide> export default function ViewNodeManager(component, scope, renderNode, block, expectElement) {
<ide> this.component = component;
<ide><path>packages/ember-htmlbars/lib/renderer.js
<ide> import { get } from 'ember-metal/property_get';
<ide> import { set } from 'ember-metal/property_set';
<ide> import assign from 'ember-metal/assign';
<ide> import setProperties from 'ember-metal/set_properties';
<del>import buildComponentTemplate from 'ember-htmlbars/system/build-component-template';
<add>import buildComponentTemplate from './system/build-component-template';
<ide> import { environment } from 'ember-environment';
<ide> import { internal } from 'htmlbars-runtime';
<del>import { renderHTMLBarsBlock } from 'ember-htmlbars/system/render-view';
<add>import { renderHTMLBarsBlock } from './system/render-view';
<ide> import fallbackViewRegistry from 'ember-views/compat/fallback-view-registry';
<ide> import { getViewId } from 'ember-views/system/utils';
<ide> import { assert } from 'ember-metal/debug';
<ide><path>packages/ember-htmlbars/lib/setup-registry.js
<ide> import { privatize as P } from 'container/registry';
<del>import { InteractiveRenderer, InertRenderer } from 'ember-htmlbars/renderer';
<del>import HTMLBarsDOMHelper from 'ember-htmlbars/system/dom-helper';
<del>import topLevelViewTemplate from 'ember-htmlbars/templates/top-level-view';
<del>import { OutletView as HTMLBarsOutletView } from 'ember-htmlbars/views/outlet';
<add>import { InteractiveRenderer, InertRenderer } from './renderer';
<add>import HTMLBarsDOMHelper from './system/dom-helper';
<add>import topLevelViewTemplate from './templates/top-level-view';
<add>import { OutletView as HTMLBarsOutletView } from './views/outlet';
<ide> import EmberView from 'ember-views/views/view';
<del>import Component from 'ember-htmlbars/component';
<del>import TextField from 'ember-htmlbars/components/text_field';
<del>import TextArea from 'ember-htmlbars/components/text_area';
<del>import Checkbox from 'ember-htmlbars/components/checkbox';
<del>import LinkToComponent from 'ember-htmlbars/components/link-to';
<add>import Component from './component';
<add>import TextField from './components/text_field';
<add>import TextArea from './components/text_area';
<add>import Checkbox from './components/checkbox';
<add>import LinkToComponent from './components/link-to';
<ide> import TemplateSupport from 'ember-views/mixins/template_support';
<ide>
<ide> export function setupApplicationRegistry(registry) {
<ide><path>packages/ember-htmlbars/lib/streams/utils.js
<del>import getValue from 'ember-htmlbars/hooks/get-value';
<add>import getValue from '../hooks/get-value';
<ide> import { assert } from 'ember-metal/debug';
<ide> import { Stream, IS_STREAM } from './stream';
<ide> import { get } from 'ember-metal/property_get';
<ide><path>packages/ember-htmlbars/lib/system/build-component-template.js
<ide> import { assert } from 'ember-metal/debug';
<ide> import { get } from 'ember-metal/property_get';
<ide> import { internal, render } from 'htmlbars-runtime';
<ide> import { buildStatement } from 'htmlbars-util/template-utils';
<del>import getValue from 'ember-htmlbars/hooks/get-value';
<add>import getValue from '../hooks/get-value';
<ide> import { isStream } from '../streams/utils';
<ide>
<ide> export default function buildComponentTemplate({ component, tagName, layout, outerAttrs }, attrs, content) {
<ide><path>packages/ember-htmlbars/lib/system/dom-helper.js
<ide> import DOMHelper from 'dom-helper';
<del>import EmberMorph from 'ember-htmlbars/morphs/morph';
<del>import EmberAttrMorph from 'ember-htmlbars/morphs/attr-morph';
<add>import EmberMorph from '../morphs/morph';
<add>import EmberAttrMorph from '../morphs/attr-morph';
<ide>
<ide> export default function EmberDOMHelper(_document) {
<ide> DOMHelper.call(this, _document);
<ide><path>packages/ember-htmlbars/lib/system/invoke-helper.js
<ide> import { assert } from 'ember-metal/debug';
<del>import HelperInstanceStream from 'ember-htmlbars/streams/helper-instance';
<del>import HelperFactoryStream from 'ember-htmlbars/streams/helper-factory';
<del>import BuiltInHelperStream from 'ember-htmlbars/streams/built-in-helper';
<add>import HelperInstanceStream from '../streams/helper-instance';
<add>import HelperFactoryStream from '../streams/helper-factory';
<add>import BuiltInHelperStream from '../streams/built-in-helper';
<ide>
<ide> export function buildHelperStream(helper, params, hash, templates, env, scope, label) {
<ide> let isAnyKindOfHelper = helper.isHelperInstance || helper.isHelperFactory;
<ide><path>packages/ember-htmlbars/lib/system/render-env.js
<del>import defaultEnv from 'ember-htmlbars/env';
<del>import { MorphSet } from 'ember-htmlbars/renderer';
<add>import defaultEnv from '../env';
<add>import { MorphSet } from '../renderer';
<ide> import { getOwner } from 'container/owner';
<ide>
<ide> export default function RenderEnv(options) {
<ide><path>packages/ember-htmlbars/lib/system/render-view.js
<del>import ViewNodeManager, { createOrUpdateComponent } from 'ember-htmlbars/node-managers/view-node-manager';
<del>import RenderEnv from 'ember-htmlbars/system/render-env';
<add>import ViewNodeManager, { createOrUpdateComponent } from '../node-managers/view-node-manager';
<add>import RenderEnv from './render-env';
<ide>
<ide> // This function only gets called once per render of a "root view" (`appendTo`). Otherwise,
<ide> // HTMLBars propagates the existing env and renders templates for a given render node.
<ide><path>packages/ember-htmlbars/lib/utils/is-component.js
<ide> import {
<ide> CONTAINS_DASH_CACHE,
<ide> CONTAINS_DOT_CACHE
<del>} from 'ember-htmlbars/system/lookup-helper';
<del>import { isComponentCell } from 'ember-htmlbars/keywords/closure-component';
<add>} from '../system/lookup-helper';
<add>import { isComponentCell } from '../keywords/closure-component';
<ide> import { isStream } from '../streams/utils';
<ide>
<ide> function hasComponentOrTemplate(owner, path, options) {
<ide><path>packages/ember-htmlbars/lib/utils/new-stream.js
<ide> import ProxyStream from '../streams/proxy-stream';
<del>import subscribe from 'ember-htmlbars/utils/subscribe';
<add>import subscribe from './subscribe';
<ide>
<ide> export default function newStream(scope, key, newValue, renderNode, isSelf) {
<ide> let stream = new ProxyStream(newValue, isSelf ? '' : key);
<ide><path>packages/ember-htmlbars/lib/utils/update-scope.js
<ide> import ProxyStream from '../streams/proxy-stream';
<del>import subscribe from 'ember-htmlbars/utils/subscribe';
<add>import subscribe from './subscribe';
<ide>
<ide> export default function updateScope(scope, key, newValue, renderNode, isSelf) {
<ide> let existing = scope[key];
<ide><path>packages/ember-htmlbars/lib/views/outlet.js
<ide> */
<ide>
<ide> import View from 'ember-views/views/view';
<del>import topLevelViewTemplate from 'ember-htmlbars/templates/top-level-view';
<add>import topLevelViewTemplate from '../templates/top-level-view';
<ide> import TemplateSupport from 'ember-views/mixins/template_support';
<ide>
<ide> export let CoreOutletView = View.extend(TemplateSupport, { | 38 |
Ruby | Ruby | mailgun copes with a 204 response status | 96f8ca37fb47062e0cdc9e3a2765dfe58dcb6770 | <ide><path>app/controllers/action_mailbox/ingresses/mailgun/inbound_emails_controller.rb
<ide> class ActionMailbox::Ingresses::Mailgun::InboundEmailsController < ActionMailbox
<ide>
<ide> def create
<ide> ActionMailbox::InboundEmail.create_and_extract_message_id! params.require("body-mime")
<del> head :ok
<ide> end
<ide>
<ide> private | 1 |
Text | Text | use dashes instead of asterisks | 9ca4ab13171f2148a986062ac564161a1f6e124f | <ide><path>doc/guides/writing-tests.md
<ide> const freelist = require('internal/freelist');
<ide>
<ide> When writing assertions, prefer the strict versions:
<ide>
<del>* `assert.strictEqual()` over `assert.equal()`
<del>* `assert.deepStrictEqual()` over `assert.deepEqual()`
<add>- `assert.strictEqual()` over `assert.equal()`
<add>- `assert.deepStrictEqual()` over `assert.deepEqual()`
<ide>
<ide> When using `assert.throws()`, if possible, provide the full error message:
<ide>
<ide> in each release.
<ide>
<ide> For example:
<ide>
<del>* `let` and `const` over `var`
<del>* Template literals over string concatenation
<del>* Arrow functions when appropriate
<add>- `let` and `const` over `var`
<add>- Template literals over string concatenation
<add>- Arrow functions when appropriate
<ide>
<ide> ## Naming Test Files
<ide>
<ide><path>doc/releases.md
<ide> $ git push <remote> <vx.y.z>
<ide>
<ide> On release proposal branch, edit `src/node_version.h` again and:
<ide>
<del>* Increment `NODE_PATCH_VERSION` by one
<del>* Change `NODE_VERSION_IS_RELEASE` back to `0`
<add>- Increment `NODE_PATCH_VERSION` by one
<add>- Change `NODE_VERSION_IS_RELEASE` back to `0`
<ide>
<ide> Commit this change with the following commit message format:
<ide> | 2 |
Javascript | Javascript | support null titles in alertios | d726c2c8ca328f51d345c71608f9259b51d3e95e | <ide><path>Libraries/Alert/AlertIOS.js
<ide> class AlertIOS {
<ide> * Create and display a popup alert.
<ide> * @static
<ide> * @method alert
<del> * @param title The dialog's title.
<del> *
<del> * An empty string hides the title.
<add> * @param title The dialog's title. Passing null or '' will hide the title.
<ide> * @param message An optional message that appears below
<ide> * the dialog's title.
<ide> * @param callbackOrButtons This optional argument should
<ide> class AlertIOS {
<ide> var callback = type;
<ide> var defaultValue = message;
<ide> RCTAlertManager.alertWithArgs({
<del> title: title,
<add> title: title || '',
<ide> type: 'plain-text',
<ide> defaultValue,
<ide> }, (id, value) => {
<ide> class AlertIOS {
<ide> }
<ide>
<ide> RCTAlertManager.alertWithArgs({
<del> title: title,
<add> title: title || '',
<ide> message: message || undefined,
<ide> buttons,
<ide> type: type || undefined, | 1 |
Javascript | Javascript | remove `previouspagenumber` from the b2g viewer | e65606d271a097ec81c6a14b0c751fc9cc81835d | <ide><path>extensions/b2g/viewer.js
<ide> var PDFViewerApplication = {
<ide>
<ide> container.addEventListener('pagechange', function (evt) {
<ide> var page = evt.pageNumber;
<del> if (evt.previousPageNumber !== page) {
<del> document.getElementById('pageNumber').value = page;
<del> }
<ide> var numPages = PDFViewerApplication.pagesCount;
<ide>
<add> document.getElementById('pageNumber').value = page;
<ide> document.getElementById('previous').disabled = (page <= 1);
<ide> document.getElementById('next').disabled = (page >= numPages);
<ide> }, true); | 1 |
Javascript | Javascript | resolve merge conflict in handlebars unit tests | e5b8957890820f2bac7b8cb551d6cd90207cd278 | <ide><path>packages/sproutcore-handlebars/lib/helpers/binding.js
<ide> var get = SC.get, getPath = SC.getPath, fmt = SC.String.fmt;
<ide> inverseTemplate: inverse,
<ide> property: property,
<ide> previousContext: ctx,
<del> isEscaped: options.hash.escaped
<add> isEscaped: options.hash.escaped,
<add> tagName: options.hash.tagName || 'span'
<ide> });
<ide>
<ide> var observer, invoker;
<ide><path>packages/sproutcore-handlebars/tests/handlebars_test.js
<ide> test("should be able to output a property without binding", function(){
<ide> equals(view.$('div').html(), "No spans here, son.");
<ide> });
<ide>
<add>test("should be able to choose a tagName other than span", function(){
<add> var template = SC.Handlebars.compile('{{#if content.underwater tagName="abbr"}}Hold your breath.{{/if}}');
<add> var content = SC.Object.create({
<add> underwater: true
<add> });
<add>
<add> var view = SC.View.create({
<add> template: template,
<add> content: content
<add> });
<add>
<add> view.createElement();
<add>
<add> equals(view.$('abbr').length, 1);
<add>});
<add>
<add>test("should still get a span by default if tagName isn't specified", function(){
<add> var template = SC.Handlebars.compile('{{#if content.underwater}}Hold your breath.{{/if}}');
<add> var content = SC.Object.create({
<add> underwater: true
<add> });
<add>
<add> var view = SC.View.create({
<add> template: template,
<add> content: content
<add> });
<add>
<add> view.createElement();
<add>
<add> equals(view.$('span').length, 1);
<add>});
<add>
<ide> module("Templates redrawing and bindings", {
<ide> setup: function(){
<ide> MyApp = SC.Object.create({});
<ide> },
<ide> teardown: function(){
<ide> window.MyApp = null;
<ide> }
<del>})
<add>});
<add>
<ide> test("should be able to update when bound property updates", function(){
<ide> MyApp.set('controller', SC.Object.create({name: 'first'}))
<ide>
<ide> test("should be able to update when bound property updates", function(){
<ide> equals(view.get('computed'), "second - computed", "view computed properties correctly update");
<ide> equals(view.$('i').text(), 'second, second - computed', "view rerenders when bound properties change");
<ide>
<del>})
<add>});
<ide> | 2 |
Java | Java | fix regression in abstractjackson2encoder | 1afc1fc90d4f4b6df80c5aa384c2a47e01da6345 | <ide><path>spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide> bufferFactory.join(Arrays.asList(bufferFactory.wrap(prefix), dataBuffer)) :
<ide> dataBuffer);
<ide> })
<add> .switchIfEmpty(Mono.fromCallable(() -> bufferFactory.wrap(helper.getPrefix())))
<ide> .concatWith(Mono.fromCallable(() -> bufferFactory.wrap(helper.getSuffix())));
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2JsonEncoderTests.java
<ide> public void encodeNonStream() {
<ide> .verifyComplete());
<ide> }
<ide>
<add> @Test
<add> public void encodeNonStreamEmpty() {
<add> testEncode(Flux.empty(), Pojo.class, step -> step
<add> .consumeNextWith(expectString("["))
<add> .consumeNextWith(expectString("]"))
<add> .verifyComplete());
<add> }
<add>
<ide> @Test // gh-29038
<ide> void encodeNonStreamWithErrorAsFirstSignal() {
<ide> String message = "I'm a teapot"; | 2 |
Java | Java | enforce jdk version on ci server | 6fe50b502fa2a564692be3419d7f21d96b6c5f64 | <ide><path>spring-core/src/test/java/org/springframework/tests/BuildTests.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.tests;
<add>
<add>import org.junit.Test;
<add>
<add>import static org.hamcrest.Matchers.*;
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * General build related tests. Part of spring-core to ensure that they run early in the
<add> * build process.
<add> */
<add>public class BuildTests {
<add>
<add> @Test
<add> public void javaVersion() throws Exception {
<add> Assume.group(TestGroup.CI);
<add> assertThat("Java Version", JavaVersion.runningVersion(), equalTo(JavaVersion.JAVA_18));
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/tests/TestGroup.java
<ide> public enum TestGroup {
<ide> * Tests requiring the presence of jmxremote_optional.jar in jre/lib/ext in order to
<ide> * avoid "Unsupported protocol: jmxmp" errors.
<ide> */
<del> JMXMP;
<add> JMXMP,
<add>
<add> /**
<add> * Tests that should only be run on the continuous integration server.
<add> */
<add> CI;
<ide>
<ide>
<ide> /**
<ide><path>spring-core/src/test/java/org/springframework/tests/TestGroupTests.java
<ide> public void parseMissing() throws Exception {
<ide> thrown.expect(IllegalArgumentException.class);
<ide> thrown.expectMessage("Unable to find test group 'missing' when parsing " +
<ide> "testGroups value: 'performance, missing'. Available groups include: " +
<del> "[LONG_RUNNING,PERFORMANCE,JMXMP]");
<add> "[LONG_RUNNING,PERFORMANCE,JMXMP,CI]");
<ide> TestGroup.parse("performance, missing");
<ide> }
<ide> | 3 |
Javascript | Javascript | improve getstringwidth performance | 2e82982984a595af24ffb260ff22eb0a73b075c7 | <ide><path>lib/internal/util/inspect.js
<ide> function formatWithOptionsInternal(inspectOptions, ...args) {
<ide> return str;
<ide> }
<ide>
<del>function prepareStringForGetStringWidth(str, removeControlChars) {
<del> str = str.normalize('NFC');
<del> if (removeControlChars)
<del> str = stripVTControlCharacters(str);
<del> return str;
<del>}
<del>
<ide> if (internalBinding('config').hasIntl) {
<ide> const icu = internalBinding('icu');
<ide> // icu.getStringWidth(string, ambiguousAsFullWidth, expandEmojiSequence)
<ide> if (internalBinding('config').hasIntl) {
<ide> getStringWidth = function getStringWidth(str, removeControlChars = true) {
<ide> let width = 0;
<ide>
<del> str = prepareStringForGetStringWidth(str, removeControlChars);
<add> if (removeControlChars)
<add> str = stripVTControlCharacters(str);
<ide> for (let i = 0; i < str.length; i++) {
<ide> // Try to avoid calling into C++ by first handling the ASCII portion of
<ide> // the string. If it is fully ASCII, we skip the C++ part.
<ide> const code = str.charCodeAt(i);
<ide> if (code >= 127) {
<del> width += icu.getStringWidth(str.slice(i));
<add> width += icu.getStringWidth(str.slice(i).normalize('NFC'));
<ide> break;
<ide> }
<ide> width += code >= 32 ? 1 : 0;
<ide> if (internalBinding('config').hasIntl) {
<ide> getStringWidth = function getStringWidth(str, removeControlChars = true) {
<ide> let width = 0;
<ide>
<del> str = prepareStringForGetStringWidth(str, removeControlChars);
<add> if (removeControlChars)
<add> str = stripVTControlCharacters(str);
<add> str = str.normalize('NFC');
<ide> for (const char of str) {
<ide> const code = char.codePointAt(0);
<ide> if (isFullWidthCodePoint(code)) { | 1 |
Text | Text | update callbacks documentation | 59406a7148bac8c88ebb59a8c404d12016d926d5 | <ide><path>docs/sources/callbacks.md
<ide> keras.callbacks.Callback()
<ide> - __on_batch_end__(batch, logs={}): Method called at the end of batch `batch`.
<ide>
<ide> The `logs` dictionary will contain keys for quantities relevant to the current batch or epoch. Currently, the `.fit()` method of the `Sequential` model class will include the following quantities in the `logs` that it passes to its callbacks:
<del>- __on_epoch_end__: logs optionally include `val_loss` (if validation is enabled in `fit`), and `val_accuracy` (if validation and accuracy monitoring are enabled).
<add>- __on_epoch_end__: logs optionally include `val_loss` (if validation is enabled in `fit`), and `val_acc` (if validation and accuracy monitoring are enabled).
<ide> - __on_batch_begin__: logs include `size`, the number of samples in the current batch.
<del>- __on_batch_end__: logs include `loss`, and optionally `accuracy` (if accuracy monitoring is enabled).
<add>- __on_batch_end__: logs include `loss`, and optionally `acc` (if accuracy monitoring is enabled).
<ide>
<ide> ---
<ide> | 1 |
PHP | PHP | use json_throw_on_error for php 7.3+ | 1d16890cdc61d47169d38dc5735039e8a94b8aab | <ide><path>src/View/JsonView.php
<ide> protected function _serialize($serialize): string
<ide> $jsonOptions |= JSON_PRETTY_PRINT;
<ide> }
<ide>
<add> if (defined('JSON_THROW_ON_ERROR')) {
<add> $jsonOptions |= JSON_THROW_ON_ERROR;
<add> }
<add>
<ide> $return = json_encode($data, $jsonOptions);
<ide> if ($return === false) {
<ide> throw new RuntimeException(json_last_error_msg(), json_last_error()); | 1 |
Javascript | Javascript | fix future relativetime altering unrelated strings | 303882604f988a47080838c3e5d16bc6b5ac5456 | <ide><path>src/locale/ka.js
<ide> export default moment.defineLocale('ka', {
<ide> },
<ide> relativeTime: {
<ide> future: function (s) {
<del> return /(წამი|წუთი|საათი|წელი)/.test(s)
<del> ? s.replace(/ი$/, 'ში')
<del> : s + 'ში';
<add> return s.replace(/(წამ|წუთ|საათ|წელ|დღ|თვ)(ი|ე)/, function (
<add> $0,
<add> $1,
<add> $2
<add> ) {
<add> return $2 === 'ი' ? $1 + 'ში' : $1 + $2 + 'ში';
<add> });
<ide> },
<ide> past: function (s) {
<ide> if (/(წამი|წუთი|საათი|დღე|თვე)/.test(s)) {
<ide> export default moment.defineLocale('ka', {
<ide> if (/წელი/.test(s)) {
<ide> return s.replace(/წელი$/, 'წლის წინ');
<ide> }
<add> return s;
<ide> },
<ide> s: 'რამდენიმე წამი',
<ide> ss: '%d წამი', | 1 |
Ruby | Ruby | prevent minitest from printing a --seed run option | c15862ae0cb876d745609170f0f90a9bb9b5e0ae | <ide><path>activesupport/lib/active_support/test_case.rb
<ide> rescue LoadError
<ide> end
<ide>
<add># FIXME: We force sorted test order below, but minitest includes --seed SEED in
<add># the printed run options, which could be misleading, since users could assume
<add># from that trace that tests are being randomized.
<add>MiniTest::Unit.class_eval do
<add> alias original_help help
<add> def help
<add> original_help.sub(/--seed\s+\d+\s*/, '')
<add> end
<add>end
<add>
<ide> module ActiveSupport
<ide> class TestCase < ::MiniTest::Unit::TestCase
<ide> Assertion = MiniTest::Assertion
<ide> def self.for_tag(tag)
<ide> yield if $tags[tag]
<ide> end
<ide>
<del> # FIXME: we have tests that depend on run order, we should fix that and
<del> # remove this method.
<add> # FIXME: We have tests that depend on run order, we should fix that and
<add> # remove this method (and remove the MiniTest::Unit help hack above).
<ide> def self.test_order # :nodoc:
<ide> :sorted
<ide> end | 1 |
PHP | PHP | add some methods for manipulating middleware | 6f33feba124d4a7ff2af4f3ed18583d67fb68f7c | <ide><path>src/Illuminate/Foundation/Http/Kernel.php
<ide> use Illuminate\Routing\Pipeline;
<ide> use Illuminate\Routing\Router;
<ide> use Illuminate\Support\Facades\Facade;
<add>use InvalidArgumentException;
<ide> use Symfony\Component\Debug\Exception\FatalThrowableError;
<ide> use Throwable;
<ide>
<ide> public function pushMiddleware($middleware)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Prepend the given middleware to the given middleware group.
<add> *
<add> * @param string $group
<add> * @param string $middleware
<add> * @return $this
<add> */
<add> public function prependMiddlewareToGroup($group, $middleware)
<add> {
<add> if (! isset($this->middlewareGroups[$group])) {
<add> throw new InvalidArgumentException("The [{$group}] middleware group has not been defined.");
<add> }
<add>
<add> if (array_search($middleware, $this->middlewareGroups[$group]) === false) {
<add> array_unshift($this->middlewareGroups[$group], $middleware);
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Append the given middleware to the given middleware group.
<add> *
<add> * @param string $group
<add> * @param string $middleware
<add> * @return $this
<add> */
<add> public function appendMiddlewareToGroup($group, $middleware)
<add> {
<add> if (! isset($this->middlewareGroups[$group])) {
<add> throw new InvalidArgumentException("The [{$group}] middleware group has not been defined.");
<add> }
<add>
<add> if (array_search($middleware, $this->middlewareGroups[$group]) === false) {
<add> $this->middlewareGroups[$group][] = $middleware;
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Prepend the given middleware to the middleware priority list.
<add> *
<add> * @param string $middleware
<add> * @return $this
<add> */
<add> public function prependToMiddlewarePriority($middleware)
<add> {
<add> if (! in_array($middleware, $this->middlewarePriority)) {
<add> array_unshift($this->middlewarePriority, $middleware);
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Append the given middleware to the middleware priority list.
<add> *
<add> * @param string $middleware
<add> * @return $this
<add> */
<add> public function appendToMiddlewarePriority($middleware)
<add> {
<add> if (! in_array($middleware, $this->middlewarePriority)) {
<add> $this->middlewarePriority[] = $middleware;
<add> }
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Get the bootstrap classes for the application.
<ide> * | 1 |
Go | Go | fix compilation on darwin | 2b55874584f034b5113359ced6b05c143d31e03c | <ide><path>utils/uname_darwin.go
<ide> package utils
<ide>
<ide> import (
<ide> "errors"
<del> "syscall"
<ide> )
<ide>
<del>func uname() (*syscall.Utsname, error) {
<add>type Utsname struct {
<add> Release [65]byte
<add>}
<add>
<add>func uname() (*Utsname, error) {
<ide> return nil, errors.New("Kernel version detection is not available on darwin")
<ide> }
<ide><path>utils/uname_linux.go
<ide> import (
<ide> "syscall"
<ide> )
<ide>
<del>// FIXME: Move this to utils package
<del>func uname() (*syscall.Utsname, error) {
<add>type Utsname syscall.Utsname
<add>
<add>func uname() (*Utsname, error) {
<ide> uts := &syscall.Utsname{}
<ide>
<ide> if err := syscall.Uname(uts); err != nil { | 2 |
Mixed | Javascript | check input in defaultmaxlisteners | 221b03ad20453f08cef7ac3fcc788b8466edc3ef | <ide><path>doc/api/events.md
<ide> By default, a maximum of `10` listeners can be registered for any single
<ide> event. This limit can be changed for individual `EventEmitter` instances
<ide> using the [`emitter.setMaxListeners(n)`][] method. To change the default
<ide> for *all* `EventEmitter` instances, the `EventEmitter.defaultMaxListeners`
<del>property can be used.
<add>property can be used. If this value is not a positive number, a `TypeError`
<add>will be thrown.
<ide>
<ide> Take caution when setting the `EventEmitter.defaultMaxListeners` because the
<ide> change effects *all* `EventEmitter` instances, including those created before
<ide><path>lib/events.js
<ide> Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
<ide> // force global console to be compiled.
<ide> // see https://github.com/nodejs/node/issues/4467
<ide> console;
<add> // check whether the input is a positive number (whose value is zero or
<add> // greater and not a NaN).
<add> if (typeof arg !== 'number' || arg < 0 || arg !== arg)
<add> throw new TypeError('"defaultMaxListeners" must be a positive number');
<ide> defaultMaxListeners = arg;
<ide> }
<ide> });
<ide><path>test/parallel/test-event-emitter-max-listeners.js
<ide> e.on('maxListeners', common.mustCall(function() {}));
<ide> // Should not corrupt the 'maxListeners' queue.
<ide> e.setMaxListeners(42);
<ide>
<del>assert.throws(function() {
<del> e.setMaxListeners(NaN);
<del>}, /^TypeError: "n" argument must be a positive number$/);
<add>const throwsObjs = [NaN, -1, 'and even this'];
<ide>
<del>assert.throws(function() {
<del> e.setMaxListeners(-1);
<del>}, /^TypeError: "n" argument must be a positive number$/);
<del>
<del>assert.throws(function() {
<del> e.setMaxListeners('and even this');
<del>}, /^TypeError: "n" argument must be a positive number$/);
<add>for (const obj of throwsObjs) {
<add> assert.throws(() => e.setMaxListeners(obj),
<add> /^TypeError: "n" argument must be a positive number$/);
<add> assert.throws(() => events.defaultMaxListeners = obj,
<add> /^TypeError: "defaultMaxListeners" must be a positive number$/);
<add>}
<ide>
<ide> e.emit('maxListeners'); | 3 |
PHP | PHP | fix validation of ipv6 on ipv4 checks | 1302fba6326f854f3a587da421a0374c64f8dca5 | <ide><path>cake/libs/validation.php
<ide> function extension($check, $extensions = array('gif', 'jpeg', 'png', 'jpg')) {
<ide> }
<ide>
<ide> /**
<del> * Validation of an IPv4 address.
<add> * Validation of an IP address.
<add> *
<add> * Valid IP version strings for type restriction are:
<add> * - both: Check both IPv4 and IPv6, return true if the supplied address matches either version
<add> * - IPv4: Version 4 (Eg: 127.0.0.1, 192.168.10.123, 203.211.24.8)
<add> * - IPv6: Version 6 (Eg: ::1, 2001:0db8::1428:57ab)
<ide> *
<ide> * @param string $check The string to test.
<add> * @param string $type The IP Version to test against
<ide> * @return boolean Success
<ide> * @access public
<ide> */
<del> function ip($check, $type = 'IPv4') {
<del> if (function_exists('filter_var')) {
<del> return (boolean) filter_var($check, FILTER_VALIDATE_IP);
<add> function ip($check, $type = 'both') {
<add> $_this =& Validation::getInstance();
<add> $success = false;
<add> if ($type === 'IPv4' || $type === 'both') {
<add> $success |= $_this->_ipv4($check);
<add> }
<add> if ($type === 'IPv6' || $type === 'both') {
<add> $success |= $_this->_ipv6($check);
<ide> }
<add> return $success;
<add> }
<ide>
<add>/**
<add> * Validation of IPv4 addresses.
<add> *
<add> * @param string $check IP Address to test
<add> * @return boolean Success
<add> * @access protected
<add> */
<add> function _ipv4($check) {
<add> if (function_exists('filter_var')) {
<add> return filter_var($check, FILTER_VALIDATE_IP, array('flags' => FILTER_FLAG_IPV4)) !== false;
<add> }
<ide> $_this =& Validation::getInstance();
<add> $_this->__populateIp();
<ide> $_this->check = $check;
<add> $_this->regex = '/^' . $_this->__pattern['IPv4'] . '$/';
<add> return $_this->_check();
<add> }
<add>
<add>/**
<add> * Validation of IPv6 addresses.
<add> *
<add> * @param string $check IP Address to test
<add> * @return boolean Success
<add> * @access protected
<add> */
<add> function _ipv6($check) {
<add> if (function_exists('filter_var')) {
<add> return filter_var($check, FILTER_VALIDATE_IP, array('flags' => FILTER_FLAG_IPV6)) !== false;
<add> }
<add> $_this =& Validation::getInstance();
<ide> $_this->__populateIp();
<del> $_this->regex = '/^' . $_this->__pattern[$type] . '$/';
<add> $_this->check = $check;
<add> $_this->regex = '/^' . $_this->__pattern['IPv6'] . '$/';
<ide> return $_this->_check();
<ide> }
<ide>
<ide> function _luhn() {
<ide> * Lazily popualate the IP address patterns used for validations
<ide> *
<ide> * @return void
<add> * @access private
<ide> */
<ide> function __populateIp() {
<ide> if (!isset($this->__pattern['IPv6'])) {
<ide><path>cake/tests/cases/libs/validation.test.php
<ide> function testEqualTo() {
<ide> * @access public
<ide> * @return void
<ide> */
<del> function testIp() {
<del> $this->assertTrue(Validation::ip('0.0.0.0'));
<del> $this->assertTrue(Validation::ip('192.168.1.156'));
<del> $this->assertTrue(Validation::ip('255.255.255.255'));
<del> $this->assertFalse(Validation::ip('127.0.0'));
<del> $this->assertFalse(Validation::ip('127.0.0.a'));
<del> $this->assertFalse(Validation::ip('127.0.0.256'));
<add> function testIpv4() {
<add> $this->assertTrue(Validation::ip('0.0.0.0', 'IPv4'));
<add> $this->assertTrue(Validation::ip('192.168.1.156', 'IPv4'));
<add> $this->assertTrue(Validation::ip('255.255.255.255', 'IPv4'));
<add>
<add> $this->assertFalse(Validation::ip('127.0.0', 'IPv4'));
<add> $this->assertFalse(Validation::ip('127.0.0.a', 'IPv4'));
<add> $this->assertFalse(Validation::ip('127.0.0.256', 'IPv4'));
<add>
<add> $this->assertFalse(Validation::ip('2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'IPv4'));
<ide> }
<ide>
<ide> /**
<ide> function testIpv6() {
<ide> $this->assertFalse(Validation::ip('1:2:3::4:5:6:7:8:9', 'IPv6'));
<ide> $this->assertFalse(Validation::ip('::ffff:2.3.4', 'IPv6'));
<ide> $this->assertFalse(Validation::ip('::ffff:257.1.2.3', 'IPv6'));
<add>
<add> $this->assertFalse(Validation::ip('0.0.0.0', 'IPv6'));
<add> }
<add>
<add>/**
<add> * testIpBoth method
<add> *
<add> * @return void
<add> * @access public
<add> */
<add> function testIpBoth() {
<add> $this->assertTrue(Validation::ip('0.0.0.0'));
<add> $this->assertTrue(Validation::ip('192.168.1.156'));
<add> $this->assertTrue(Validation::ip('255.255.255.255'));
<add>
<add> $this->assertFalse(Validation::ip('127.0.0'));
<add> $this->assertFalse(Validation::ip('127.0.0.a'));
<add> $this->assertFalse(Validation::ip('127.0.0.256'));
<add>
<add> $this->assertTrue(Validation::ip('2001:0db8:85a3:0000:0000:8a2e:0370:7334'));
<add> $this->assertTrue(Validation::ip('2001:db8:85a3:0:0:8a2e:370:7334'));
<add> $this->assertTrue(Validation::ip('2001:db8:85a3::8a2e:370:7334'));
<add>
<add> $this->assertFalse(Validation::ip('2001:db8:85a3::8a2e:37023:7334'));
<add> $this->assertFalse(Validation::ip('2001:db8:85a3::8a2e:370k:7334'));
<add> $this->assertFalse(Validation::ip('1:2:3:4:5:6:7:8:9'));
<ide> }
<ide>
<ide> /** | 2 |
Ruby | Ruby | broaden refute_predicate nudge | a0f48619341c2cf6f1980a019bcd4005cf066e21 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def line_problems(line, _lineno)
<ide> problem "Use `assert_predicate <path_to_file>, :exist?` instead of `#{Regexp.last_match(1)}`"
<ide> end
<ide>
<del> if line =~ /assert !File\.exist\?/
<del> problem "Use `refute_predicate <path_to_file>, :exist?` instead of `assert !File.exist?`"
<add> if line =~ /(assert !File\.exist\?|assert !\(.*\)\.exist\?)/
<add> problem "Use `refute_predicate <path_to_file>, :exist?` instead of `#{Regexp.last_match(1)}`"
<ide> end
<ide>
<ide> return unless @strict | 1 |
Java | Java | add test to corner potential bug with @cacheevict | 0053319c6279a55094a723dc5fc0955b901cfd1c | <ide><path>org.springframework.context/src/test/java/org/springframework/cache/annotation/AnnotationCacheOperationSourceTest.java
<ide> public void singleStereotype() {
<ide> @EvictBar
<ide> public void multipleStereotype() {
<ide> }
<add>
<add> @Caching(cacheable = { @Cacheable(value = "test", key = "a"), @Cacheable(value = "test", key = "b") })
<add> public void multipleCaching() {
<add> }
<ide> }
<ide>
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide><path>org.springframework.context/src/test/java/org/springframework/cache/interceptor/ExpressionEvalutatorTest.java
<add>/*
<add> * Copyright 2011 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.cache.interceptor;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.lang.reflect.Method;
<add>import java.util.Collection;
<add>import java.util.Iterator;
<add>
<add>import org.junit.Test;
<add>import org.springframework.cache.Cache;
<add>import org.springframework.cache.annotation.AnnotationCacheOperationSource;
<add>import org.springframework.cache.annotation.Cacheable;
<add>import org.springframework.cache.annotation.Caching;
<add>import org.springframework.cache.concurrent.ConcurrentMapCache;
<add>import org.springframework.expression.EvaluationContext;
<add>import org.springframework.util.ReflectionUtils;
<add>
<add>import edu.emory.mathcs.backport.java.util.Collections;
<add>
<add>public class ExpressionEvalutatorTest {
<add> private ExpressionEvaluator eval = new ExpressionEvaluator();
<add>
<add> private AnnotationCacheOperationSource source = new AnnotationCacheOperationSource();
<add>
<add> private Collection<CacheOperation> getOps(String name) {
<add> Method method = ReflectionUtils.findMethod(AnnotatedClass.class, name, Object.class, Object.class);
<add> return source.getCacheOperations(method, AnnotatedClass.class);
<add> }
<add>
<add> @Test
<add> public void testMultipleCachingSource() throws Exception {
<add> Collection<CacheOperation> ops = getOps("multipleCaching");
<add> assertEquals(2, ops.size());
<add> Iterator<CacheOperation> it = ops.iterator();
<add> CacheOperation next = it.next();
<add> assertTrue(next instanceof CacheableOperation);
<add> assertTrue(next.getCacheNames().contains("test"));
<add> assertEquals("#a", next.getKey());
<add> next = it.next();
<add> assertTrue(next instanceof CacheableOperation);
<add> assertTrue(next.getCacheNames().contains("test"));
<add> assertEquals("#b", next.getKey());
<add> }
<add>
<add> @Test
<add> public void testMultipleCachingEval() throws Exception {
<add> AnnotatedClass target = new AnnotatedClass();
<add> Method method = ReflectionUtils.findMethod(AnnotatedClass.class, "multipleCaching", Object.class,
<add> Object.class);
<add> Object[] args = new Object[] { new Object(), new Object() };
<add> Collection<Cache> map = Collections.singleton(new ConcurrentMapCache("test"));
<add>
<add> EvaluationContext evalCtx = eval.createEvaluationContext(map, method, args, target, target.getClass());
<add> Collection<CacheOperation> ops = getOps("multipleCaching");
<add>
<add> Iterator<CacheOperation> it = ops.iterator();
<add>
<add> Object keyA = eval.key(it.next().getKey(), method, evalCtx);
<add> Object keyB = eval.key(it.next().getKey(), method, evalCtx);
<add>
<add> assertEquals(args[0], keyA);
<add> assertEquals(args[1], keyB);
<add> }
<add>
<add> private static class AnnotatedClass {
<add> @Caching(cacheable = { @Cacheable(value = "test", key = "#a"), @Cacheable(value = "test", key = "#b") })
<add> public void multipleCaching(Object a, Object b) {
<add> }
<add> }
<add>}
<ide>\ No newline at end of file | 2 |
Python | Python | check like= type for __array_function__ | 5a3180cf8513910208e1653e40d9b8722d1c8756 | <ide><path>numpy/core/overrides.py
<ide> def set_array_function_like_doc(public_api):
<ide>
<ide>
<ide> def array_function_dispatch_like(func, *args, **kwargs):
<del> if not hasattr(kwargs['like'], '__array_function__'):
<add> if not hasattr(type(kwargs['like']), '__array_function__'):
<ide> raise TypeError(
<ide> 'The `like` object must implement the `__array_function__` '
<ide> 'protocol.' | 1 |
Mixed | Text | improve changelog entry from [ci skip] | b1c72a3675d57a3a575563acbc120d125d2c667b | <ide><path>actionpack/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<del>* Fix `image_alt` method to work with underscored or hyphenated file names.
<del> Currently, underscored filenames become
<del> `<img alt="A_long_file_name_with_underscores"` in HTML, which is
<del> poor for accessibility; Apple's VoiceOver Utility pronounces
<del> each underscore. "A_long_file_name" thus becomes "A underscore
<del> long underscore file underscore name." This patch makes underscored
<del> or hyphenated file names (both of which are very popular naming
<del> conventions) read more naturally in screen readers by converting
<del> both hyphens and underscores to spaces.
<add>* Change `image_alt` method to replace underscores/hyphens to spaces in filenames.
<ide>
<del> Example:
<del> # current implementation
<del> image_tag('underscored_file_name.png')
<del> #=> <img alt="Underscored_file_name" src="/assets/underscored_file_name.png" />
<add> Previously, underscored filenames became `alt="A_long_file_name_with_underscores"`
<add> in HTML, which is poor for accessibility. For instance, Apple's VoiceOver Utility
<add> pronounces each underscore. `A_long_file_name` thus would be read as `A underscore
<add> long underscore file underscore name.` Now underscored or hyphenated filenames
<add> (both of which are very popular naming conventions) read more naturally in
<add> screen readers by converting both hyphens and underscores to spaces.
<ide>
<del> # this patch
<add> Before:
<add> image_tag('underscored_file_name.png')
<add> # => <img alt="Underscored_file_name" src="/assets/underscored_file_name.png" />
<add>
<add> After:
<ide> image_tag('underscored_file_name.png')
<del> #=> <img alt="Underscored file name" src="/assets/underscored_file_name.png" />
<add> # => <img alt="Underscored file name" src="/assets/underscored_file_name.png" />
<ide>
<ide> *Nick Cox*
<ide>
<ide><path>actionpack/lib/action_view/helpers/asset_tag_helper.rb
<ide> def image_tag(source, options={})
<ide>
<ide> # Returns a string suitable for an html image tag alt attribute.
<ide> # The +src+ argument is meant to be an image file path.
<del> # The method removes the basename of the file path and the digest,
<add> # The method removes the basename of the file path and the digest,
<ide> # if any. It also removes hyphens and underscores from file names and
<ide> # replaces them with spaces, returning a space-separated, titleized
<ide> # string.
<del> #
<add> #
<ide> # ==== Examples
<ide> #
<ide> # image_tag('rails.png')
<ide> # # => <img alt="Rails" src="/assets/rails.png" />
<ide> #
<ide> # image_tag('hyphenated-file-name.png')
<ide> # # => <img alt="Hyphenated file name" src="/assets/hyphenated-file-name.png" />
<del> #
<add> #
<ide> # image_tag('underscored_file_name.png')
<ide> # # => <img alt="Underscored file name" src="/assets/underscored_file_name.png" />
<ide> def image_alt(src) | 2 |
PHP | PHP | fix cookie decryption when using psr7 | c7704bea42ee1db02dea0acebc4ec0285ba7544e | <ide><path>src/Http/ResponseTransformer.php
<ide> protected static function parseCookies(array $cookieHeader)
<ide> }
<ide>
<ide> list($name, $value) = explode('=', array_shift($parts), 2);
<del> $parsed = compact('name', 'value');
<add> $parsed = compact('name') + ['value' => urldecode($value)];
<ide>
<ide> foreach ($parts as $part) {
<ide> if (strpos($part, '=') !== false) {
<ide><path>tests/TestCase/TestSuite/CookieEncryptedUsingControllerTest.php
<ide> public function setUp()
<ide> DispatcherFactory::add('ControllerFactory');
<ide> }
<ide>
<add> /**
<add> * tear down.
<add> *
<add> * @return void
<add> */
<add> public function tearDown()
<add> {
<add> parent::tearDown();
<add> $this->_useHttpServer = false;
<add> }
<add>
<ide> /**
<ide> * Can encrypt/decrypt the cookie value.
<ide> */
<ide> public function testCanAssertCookieEncryptedWithAnotherEncryptionKey()
<ide> $this->get('/cookie_component_test/set_cookie');
<ide> $this->assertCookieEncrypted('abc', 'NameOfCookie', 'aes', $key);
<ide> }
<add>
<add> /**
<add> * Can AssertCookie even if encrypted with the aes when using PSR7 server.
<add> */
<add> public function testCanAssertCookieEncryptedWithAesWhenUsingPsr7()
<add> {
<add> $this->_useHttpServer = true;
<add> $this->get('/cookie_component_test/set_cookie');
<add> $this->assertCookieEncrypted('abc', 'NameOfCookie', 'aes');
<add> }
<ide> }
<ide><path>tests/test_app/TestApp/Controller/CookieComponentTestController.php
<ide> class CookieComponentTestController extends Controller
<ide> 'Cookie',
<ide> ];
<ide>
<add> public $autoRender = false;
<add>
<ide> /**
<ide> * view
<ide> * | 3 |
Javascript | Javascript | fix beautify test | 1fa2ba750cf873bc1d2f8316501dd20b102e256c | <ide><path>bin/webpack.js
<ide> function processOptions(options) {
<ide> if(!options.exitByHelpOrVersion && !validationErrorOcurred) {
<ide> processOptions(options);
<ide> }
<del> | 1 |
Text | Text | revise ci text in collaborator guide | 67bc0ec7ac9054358b57c13e711deae7cb62aed3 | <ide><path>doc/guides/collaborator-guide.md
<ide> the comment anyway to avoid any doubt.
<ide> All fixes must have a test case which demonstrates the defect. The test should
<ide> fail before the change, and pass after the change.
<ide>
<del>Do not land any pull requests without a passing (green or yellow) CI run.
<del>A green GitHub Actions CI result is required. A passing
<del>[Jenkins CI](https://ci.nodejs.org/) is also required if PR contains changes
<del>that will affect the `node` binary. This is critical as GitHub Actions CI does
<del>not cover all the environments supported by Node.js.
<add>Do not land any pull requests without the necessary passing CI runs.
<add>A passing (green) GitHub Actions CI result is required. A passing (green or
<add>yellow) [Jenkins CI](https://ci.nodejs.org/) is also required if the pull
<add>request contains changes that will affect the `node` binary. This is because
<add>GitHub Actions CI does not cover all the environments supported by Node.js.
<ide>
<ide> <details>
<ide> <summary>Changes that affect the `node` binary</summary>
<ide> in the form:
<ide> To specify the branch this way, `refs/heads/BRANCH` is used
<ide> (e.g. for `master` -> `refs/heads/master`).
<ide> For pull requests, it will look like `refs/pull/PR_NUMBER/head`
<del>(e.g. for PR#42 -> `refs/pull/42/head`).
<add>(e.g. for pull request #42 -> `refs/pull/42/head`).
<ide> * `REBASE_ONTO`: Change that to `origin/master` so the pull request gets rebased
<ide> onto master. This can especially be important for pull requests that have been
<ide> open a while. | 1 |
Javascript | Javascript | add e2e testing of command | ecec4319c4fda9bebc90216d5340442b2a5725df | <ide><path>local-cli/__mocks__/fs.js
<ide> fs.readdir.mockImplementation((filepath, callback) => {
<ide> return callback(null, Object.keys(node));
<ide> });
<ide>
<del>fs.readFile.mockImplementation(function(filepath, encoding, callback) {
<del> filepath = path.normalize(filepath);
<del> callback = asyncCallback(callback);
<del> if (arguments.length === 2) {
<del> callback = encoding;
<del> encoding = null;
<del> }
<del>
<del> let node;
<del> try {
<del> node = getToNode(filepath);
<del> if (isDirNode(node)) {
<del> callback(new Error('Error readFile a dir: ' + filepath));
<del> }
<del> if (node == null) {
<del> return callback(Error('No such file: ' + filepath));
<del> } else {
<del> return callback(null, node);
<del> }
<del> } catch (e) {
<del> return callback(e);
<del> }
<del>});
<add>fs.readFile.mockImplementation(asyncify(fs.readFileSync));
<ide>
<ide> fs.readFileSync.mockImplementation(function(filepath, encoding) {
<ide> filepath = path.normalize(filepath);
<ide> fs.mkdirSync.mockImplementation((dirPath, mode) => {
<ide> if (!isDirNode(node)) {
<ide> throw fsError('ENOTDIR', 'not a directory: ' + parentPath);
<ide> }
<del> node[path.basename(dirPath)] = {};
<add> if (node[path.basename(dirPath)] == null) {
<add> node[path.basename(dirPath)] = {};
<add> }
<ide> });
<ide>
<ide> function fsError(code, message) {
<ide><path>local-cli/__tests__/fs-mock-test.js
<ide> describe('fs mock', () => {
<ide> * comment and run Flow. */
<ide> expect(content).toEqual('foobar');
<ide> });
<add>
<add> it('does not erase directories', () => {
<add> fs.mkdirSync('/dir', 0o777);
<add> fs.writeFileSync('/dir/test', 'foobar', 'utf8');
<add> fs.mkdirSync('/dir', 0o777);
<add> const content = fs.readFileSync('/dir/test', 'utf8');
<add> /* $FlowFixMe(>=0.56.0 site=react_native_oss) This comment suppresses an
<add> * error found when Flow v0.56 was deployed. To see the error delete this
<add> * comment and run Flow. */
<add> expect(content).toEqual('foobar');
<add> });
<ide> });
<ide>
<ide> describe('createWriteStream()', () => { | 2 |
Python | Python | fix endianness in unstuctured_to_structured test | ae6ac2e085635e383a38cc43e85edec39aa6e8d3 | <ide><path>numpy/lib/tests/test_recfunctions.py
<ide> def test_structured_to_unstructured(self):
<ide> ( 5, ( 6., 7), [ 8., 9.]),
<ide> (10, (11., 12), [13., 14.]),
<ide> (15, (16., 17), [18., 19.])],
<del> dtype=[('a', '<i4'),
<del> ('b', [('f0', '<f4'), ('f1', '<u2')]),
<del> ('c', '<f4', (2,))])
<add> dtype=[('a', 'i4'),
<add> ('b', [('f0', 'f4'), ('f1', 'u2')]),
<add> ('c', 'f4', (2,))])
<ide> assert_equal(out, want)
<ide>
<ide> d = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], | 1 |
Javascript | Javascript | unify import syntax for turbomoduleregistry | 0e72137c99b6493e6f015d7a0a6976a73e07faca | <ide><path>Libraries/TurboModule/samples/NativeSampleTurboModule.js
<ide> 'use strict';
<ide>
<ide> import type {TurboModule} from 'RCTExport';
<del>import {getEnforcing} from 'TurboModuleRegistry';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<ide>
<ide> export interface Spec extends TurboModule {
<ide> // Exported methods.
<ide> export interface Spec extends TurboModule {
<ide> +getValueWithPromise: (error: boolean) => Promise<string>;
<ide> }
<ide>
<del>export default getEnforcing<Spec>('SampleTurboModule');
<add>export default TurboModuleRegistry.getEnforcing<Spec>('SampleTurboModule'); | 1 |
Javascript | Javascript | improve assertion fail messages | 0ce54a7ec96431a088a15a5e24614428184497f0 | <ide><path>test/parallel/test-stream-inheritance.js
<ide> assert.ok(!(undefined instanceof Writable));
<ide>
<ide> // Simple inheritance check for `Writable` works fine in a subclass constructor.
<ide> function CustomWritable() {
<del> assert.ok(this instanceof Writable, 'inherits from Writable');
<del> assert.ok(this instanceof CustomWritable, 'inherits from CustomWritable');
<add> assert.ok(
<add> this instanceof CustomWritable,
<add> `${this} does not inherit from CustomWritable`
<add> );
<add> assert.ok(
<add> this instanceof Writable,
<add> `${this} does not inherit from Writable`
<add> );
<ide> }
<ide>
<ide> Object.setPrototypeOf(CustomWritable, Writable);
<ide> Object.setPrototypeOf(CustomWritable.prototype, Writable.prototype);
<ide>
<ide> new CustomWritable();
<ide>
<del>assert.throws(CustomWritable,
<del> common.expectsError({
<del> code: 'ERR_ASSERTION',
<del> message: /^inherits from Writable$/
<del> }));
<add>common.expectsError(
<add> CustomWritable,
<add> {
<add> code: 'ERR_ASSERTION',
<add> type: assert.AssertionError,
<add> message: 'undefined does not inherit from CustomWritable'
<add> }
<add>); | 1 |
PHP | PHP | fix cs error | c302b9fd4b356bb0b2936174327ce083c657cc62 | <ide><path>src/Mailer/Email.php
<ide> public function createFromArray($config)
<ide> /**
<ide> * Serializes the Email object.
<ide> *
<del> * @return void.
<add> * @return string
<ide> */
<ide> public function serialize()
<ide> {
<ide><path>src/View/ViewBuilder.php
<ide> public function createFromArray($config)
<ide> /**
<ide> * Serializes the view builder object.
<ide> *
<del> * @return void
<add> * @return string
<ide> */
<ide> public function serialize()
<ide> { | 2 |
Ruby | Ruby | show the new short-form in an example | f9a4cf15627ba0c905bf0ab3de2b49b515ac197d | <ide><path>railties/lib/rails/generators/rails/app/templates/config/routes.rb
<ide> # first created -> highest priority.
<ide>
<ide> # Sample of regular route:
<del> # match 'products/:id', :to => 'catalog#view'
<add> # match 'products/:id' => 'catalog#view'
<ide> # Keep in mind you can assign values other than :controller and :action
<ide>
<ide> # Sample of named route: | 1 |
Ruby | Ruby | use consistent order of the arguments | fe21c8589fc44d3e08fb45baa4da8321a7c8f00c | <ide><path>railties/lib/rails/generators/app_base.rb
<ide> def comment_if(value)
<ide> options[value] ? '# ' : ''
<ide> end
<ide>
<del> class GemfileEntry < Struct.new(:name, :comment, :version, :options, :commented_out)
<del> def initialize(name, comment, version, options = {}, commented_out = false)
<add> class GemfileEntry < Struct.new(:name, :version, :comment, :options, :commented_out)
<add> def initialize(name, version, comment, options = {}, commented_out = false)
<ide> super
<ide> end
<ide>
<ide> def self.github(name, github, comment = nil)
<del> new(name, comment, nil, github: github)
<add> new(name, nil, comment, github: github)
<ide> end
<ide>
<ide> def self.version(name, version, comment = nil)
<del> new(name, comment, version)
<add> new(name, version, comment)
<ide> end
<ide>
<ide> def self.path(name, path, comment = nil)
<del> new(name, comment, nil, path: path)
<add> new(name, nil, comment, path: path)
<ide> end
<ide>
<ide> def padding(max_width)
<ide> def jbuilder_gemfile_entry
<ide>
<ide> def webconsole_gemfile_entry
<ide> comment = 'Run `rails console` in the browser. Read more: https://github.com/rails/web-console'
<del> GemfileEntry.new('web-console', comment, nil, group: :development)
<add> GemfileEntry.new('web-console', nil, comment, group: :development)
<ide> end
<ide>
<ide> def sdoc_gemfile_entry
<ide> comment = 'bundle exec rake doc:rails generates the API under doc/api.'
<del> GemfileEntry.new('sdoc', comment, nil, { :group => :doc, :require => false })
<add> GemfileEntry.new('sdoc', nil, comment, { group: :doc, require: false })
<ide> end
<ide>
<ide> def coffee_gemfile_entry
<ide> def javascript_gemfile_entry
<ide> def javascript_runtime_gemfile_entry
<ide> comment = 'See https://github.com/sstephenson/execjs#readme for more supported runtimes'
<ide> if defined?(JRUBY_VERSION)
<del> GemfileEntry.version 'therubyrhino', comment, nil
<add> GemfileEntry.version 'therubyrhino', nil,comment
<ide> else
<del> GemfileEntry.new 'therubyracer', comment, nil, { :platforms => :ruby }, true
<add> GemfileEntry.new 'therubyracer', nil, comment, { platforms: :ruby }, true
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | move wip fibers to childinprogress | af7dd8e0a13600870a18b244608cfa37da5ae21c | <ide><path>src/renderers/noop/ReactNoop.js
<ide> var ReactNoop = {
<ide>
<ide> function logFiber(fiber : Fiber, depth) {
<ide> console.log(
<del> ' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'),
<add> ' '.repeat(depth) + '- ' + (fiber.type ? fiber.type.name || fiber.type : '[root]'),
<ide> '[' + fiber.pendingWorkPriority + (fiber.pendingProps ? '*' : '') + ']'
<ide> );
<add> const childInProgress = fiber.childInProgress;
<add> if (childInProgress) {
<add> if (childInProgress === fiber.child) {
<add> console.log(' '.repeat(depth + 1) + 'ERROR: IN PROGRESS == CURRENT');
<add> } else {
<add> console.log(' '.repeat(depth + 1) + 'IN PROGRESS');
<add> logFiber(childInProgress, depth + 1);
<add> if (fiber.child) {
<add> console.log(' '.repeat(depth + 1) + 'CURRENT');
<add> }
<add> }
<add> }
<ide> if (fiber.child) {
<ide> logFiber(fiber.child, depth + 1);
<ide> }
<ide><path>src/renderers/shared/fiber/ReactChildFiber.js
<ide> const {
<ide>
<ide> const isArray = Array.isArray;
<ide>
<del>function createSubsequentChild(
<del> returnFiber : Fiber,
<del> existingChild : ?Fiber,
<del> previousSibling : Fiber,
<del> newChildren,
<del> priority : PriorityLevel
<del>) : Fiber {
<del> if (typeof newChildren !== 'object' || newChildren === null) {
<del> return previousSibling;
<del> }
<add>function ChildReconciler(shouldClone) {
<add>
<add> function createSubsequentChild(
<add> returnFiber : Fiber,
<add> existingChild : ?Fiber,
<add> previousSibling : Fiber,
<add> newChildren,
<add> priority : PriorityLevel
<add> ) : Fiber {
<add> if (typeof newChildren !== 'object' || newChildren === null) {
<add> return previousSibling;
<add> }
<ide>
<del> switch (newChildren.$$typeof) {
<del> case REACT_ELEMENT_TYPE: {
<del> const element = (newChildren : ReactElement<any>);
<del> if (existingChild &&
<del> element.type === existingChild.type &&
<del> element.key === existingChild.key) {
<del> // TODO: This is not sufficient since previous siblings could be new.
<del> // Will fix reconciliation properly later.
<del> const clone = cloneFiber(existingChild, priority);
<del> clone.pendingProps = element.props;
<del> clone.child = existingChild.child;
<del> clone.sibling = null;
<del> clone.return = returnFiber;
<del> previousSibling.sibling = clone;
<del> return clone;
<add> switch (newChildren.$$typeof) {
<add> case REACT_ELEMENT_TYPE: {
<add> const element = (newChildren : ReactElement<any>);
<add> if (existingChild &&
<add> element.type === existingChild.type &&
<add> element.key === existingChild.key) {
<add> // TODO: This is not sufficient since previous siblings could be new.
<add> // Will fix reconciliation properly later.
<add> const clone = shouldClone ? cloneFiber(existingChild, priority) : existingChild;
<add> if (!shouldClone) {
<add> clone.pendingWorkPriority = priority;
<add> }
<add> clone.pendingProps = element.props;
<add> clone.child = existingChild.child;
<add> clone.sibling = null;
<add> clone.return = returnFiber;
<add> previousSibling.sibling = clone;
<add> return clone;
<add> }
<add> const child = createFiberFromElement(element, priority);
<add> previousSibling.sibling = child;
<add> child.return = returnFiber;
<add> return child;
<ide> }
<del> const child = createFiberFromElement(element, priority);
<del> previousSibling.sibling = child;
<del> child.return = returnFiber;
<del> return child;
<del> }
<ide>
<del> case REACT_COROUTINE_TYPE: {
<del> const coroutine = (newChildren : ReactCoroutine);
<del> const child = createFiberFromCoroutine(coroutine, priority);
<del> previousSibling.sibling = child;
<del> child.return = returnFiber;
<del> return child;
<del> }
<add> case REACT_COROUTINE_TYPE: {
<add> const coroutine = (newChildren : ReactCoroutine);
<add> const child = createFiberFromCoroutine(coroutine, priority);
<add> previousSibling.sibling = child;
<add> child.return = returnFiber;
<add> return child;
<add> }
<ide>
<del> case REACT_YIELD_TYPE: {
<del> const yieldNode = (newChildren : ReactYield);
<del> const reifiedYield = createReifiedYield(yieldNode);
<del> const child = createFiberFromYield(yieldNode, priority);
<del> child.output = reifiedYield;
<del> previousSibling.sibling = child;
<del> child.return = returnFiber;
<del> return child;
<add> case REACT_YIELD_TYPE: {
<add> const yieldNode = (newChildren : ReactYield);
<add> const reifiedYield = createReifiedYield(yieldNode);
<add> const child = createFiberFromYield(yieldNode, priority);
<add> child.output = reifiedYield;
<add> previousSibling.sibling = child;
<add> child.return = returnFiber;
<add> return child;
<add> }
<ide> }
<del> }
<ide>
<del> if (isArray(newChildren)) {
<del> let prev : Fiber = previousSibling;
<del> let existing : ?Fiber = existingChild;
<del> for (var i = 0; i < newChildren.length; i++) {
<del> prev = createSubsequentChild(returnFiber, existing, prev, newChildren[i], priority);
<del> if (prev && existing) {
<del> // TODO: This is not correct because there could've been more
<del> // than one sibling consumed but I don't want to return a tuple.
<del> existing = existing.sibling;
<add> if (isArray(newChildren)) {
<add> let prev : Fiber = previousSibling;
<add> let existing : ?Fiber = existingChild;
<add> for (var i = 0; i < newChildren.length; i++) {
<add> var nextExisting = existing && existing.sibling;
<add> prev = createSubsequentChild(returnFiber, existing, prev, newChildren[i], priority);
<add> if (prev && existing) {
<add> // TODO: This is not correct because there could've been more
<add> // than one sibling consumed but I don't want to return a tuple.
<add> existing = nextExisting;
<add> }
<ide> }
<add> return prev;
<add> } else {
<add> // TODO: Throw for unknown children.
<add> return previousSibling;
<ide> }
<del> return prev;
<del> } else {
<del> // TODO: Throw for unknown children.
<del> return previousSibling;
<ide> }
<del>}
<ide>
<del>function createFirstChild(returnFiber, existingChild, newChildren, priority) {
<del> if (typeof newChildren !== 'object' || newChildren === null) {
<del> return null;
<del> }
<add> function createFirstChild(returnFiber, existingChild, newChildren, priority) {
<add> if (typeof newChildren !== 'object' || newChildren === null) {
<add> return null;
<add> }
<ide>
<del> switch (newChildren.$$typeof) {
<del> case REACT_ELEMENT_TYPE: {
<del> const element = (newChildren : ReactElement<any>);
<del> if (existingChild &&
<del> element.type === existingChild.type &&
<del> element.key === existingChild.key) {
<del> // Get the clone of the existing fiber.
<del> const clone = cloneFiber(existingChild, priority);
<del> clone.pendingProps = element.props;
<del> clone.child = existingChild.child;
<del> clone.sibling = null;
<del> clone.return = returnFiber;
<del> return clone;
<add> switch (newChildren.$$typeof) {
<add> case REACT_ELEMENT_TYPE: {
<add> const element = (newChildren : ReactElement<any>);
<add> if (existingChild &&
<add> element.type === existingChild.type &&
<add> element.key === existingChild.key) {
<add> // Get the clone of the existing fiber.
<add> const clone = shouldClone ? cloneFiber(existingChild, priority) : existingChild;
<add> if (!shouldClone) {
<add> clone.pendingWorkPriority = priority;
<add> }
<add> clone.pendingProps = element.props;
<add> clone.child = existingChild.child;
<add> clone.sibling = null;
<add> clone.return = returnFiber;
<add> return clone;
<add> }
<add> const child = createFiberFromElement(element, priority);
<add> child.return = returnFiber;
<add> return child;
<ide> }
<del> const child = createFiberFromElement(element, priority);
<del> child.return = returnFiber;
<del> return child;
<del> }
<ide>
<del> case REACT_COROUTINE_TYPE: {
<del> const coroutine = (newChildren : ReactCoroutine);
<del> const child = createFiberFromCoroutine(coroutine, priority);
<del> child.return = returnFiber;
<del> return child;
<del> }
<add> case REACT_COROUTINE_TYPE: {
<add> const coroutine = (newChildren : ReactCoroutine);
<add> const child = createFiberFromCoroutine(coroutine, priority);
<add> child.return = returnFiber;
<add> return child;
<add> }
<ide>
<del> case REACT_YIELD_TYPE: {
<del> // A yield results in a fragment fiber whose output is the continuation.
<del> // TODO: When there is only a single child, we can optimize this to avoid
<del> // the fragment.
<del> const yieldNode = (newChildren : ReactYield);
<del> const reifiedYield = createReifiedYield(yieldNode);
<del> const child = createFiberFromYield(yieldNode, priority);
<del> child.output = reifiedYield;
<del> child.return = returnFiber;
<del> return child;
<add> case REACT_YIELD_TYPE: {
<add> // A yield results in a fragment fiber whose output is the continuation.
<add> // TODO: When there is only a single child, we can optimize this to avoid
<add> // the fragment.
<add> const yieldNode = (newChildren : ReactYield);
<add> const reifiedYield = createReifiedYield(yieldNode);
<add> const child = createFiberFromYield(yieldNode, priority);
<add> child.output = reifiedYield;
<add> child.return = returnFiber;
<add> return child;
<add> }
<ide> }
<del> }
<ide>
<del> if (isArray(newChildren)) {
<del> var first : ?Fiber = null;
<del> var prev : ?Fiber = null;
<del> var existing : ?Fiber = existingChild;
<del> for (var i = 0; i < newChildren.length; i++) {
<del> if (prev == null) {
<del> prev = createFirstChild(returnFiber, existing, newChildren[i], priority);
<del> first = prev;
<del> } else {
<del> prev = createSubsequentChild(returnFiber, existing, prev, newChildren[i], priority);
<del> }
<del> if (prev && existing) {
<del> // TODO: This is not correct because there could've been more
<del> // than one sibling consumed but I don't want to return a tuple.
<del> existing = existing.sibling;
<add> if (isArray(newChildren)) {
<add> var first : ?Fiber = null;
<add> var prev : ?Fiber = null;
<add> var existing : ?Fiber = existingChild;
<add> for (var i = 0; i < newChildren.length; i++) {
<add> var nextExisting = existing && existing.sibling;
<add> if (prev == null) {
<add> prev = createFirstChild(returnFiber, existing, newChildren[i], priority);
<add> first = prev;
<add> } else {
<add> prev = createSubsequentChild(returnFiber, existing, prev, newChildren[i], priority);
<add> }
<add> if (prev && existing) {
<add> // TODO: This is not correct because there could've been more
<add> // than one sibling consumed but I don't want to return a tuple.
<add> existing = nextExisting;
<add> }
<ide> }
<add> return first;
<add> } else {
<add> // TODO: Throw for unknown children.
<add> return null;
<ide> }
<del> return first;
<del> } else {
<del> // TODO: Throw for unknown children.
<del> return null;
<ide> }
<add>
<add> // TODO: This API won't work because we'll need to transfer the side-effects of
<add> // unmounting children to the returnFiber.
<add> function reconcileChildFibers(
<add> returnFiber : Fiber,
<add> currentFirstChild : ?Fiber,
<add> newChildren : ReactNodeList,
<add> priority : PriorityLevel
<add> ) : ?Fiber {
<add> return createFirstChild(returnFiber, currentFirstChild, newChildren, priority);
<add> }
<add>
<add> return reconcileChildFibers;
<ide> }
<ide>
<del>// TODO: This API won't work because we'll need to transfer the side-effects of
<del>// unmounting children to the returnFiber.
<del>exports.reconcileChildFibers = function(
<del> returnFiber : Fiber,
<del> currentFirstChild : ?Fiber,
<del> newChildren : ReactNodeList,
<del> priority : PriorityLevel
<del>) : ?Fiber {
<del> return createFirstChild(returnFiber, currentFirstChild, newChildren, priority);
<del>};
<add>exports.reconcileChildFibers = ChildReconciler(true);
<add>
<add>exports.reconcileChildFibersInPlace = ChildReconciler(false);
<ide><path>src/renderers/shared/fiber/ReactFiber.js
<ide> export type Fiber = Instance & {
<ide> // memory if we need to.
<ide> alternate: ?Fiber,
<ide>
<del> // Keeps track if we've completed this node or if we're currently in the
<del> // middle of processing it. We really should know this based on pendingProps
<del> // or something else. We could also reuse the tag for this purpose. However,
<del> // I'm not really sure so I'll use a flag for now.
<del> // TODO: Find another way to infer this flag.
<del> hasWorkInProgress: bool,
<del> // Keeps track if we've deprioritized the children of this node so we know to
<del> // reuse the existing children.
<del> // TODO: Find another way to infer this flag or separate children updates from
<del> // property updates so that we simply don't try to update children here.
<del> wasDeprioritized: bool,
<add> // Keeps track of the children that are currently being processed but have not
<add> // yet completed.
<add> childInProgress: ?Fiber,
<ide>
<ide> // Conceptual aliases
<ide> // workInProgress : Fiber -> alternate The alternate used for reuse happens
<ide> var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber {
<ide>
<ide> pendingWorkPriority: NoWork,
<ide>
<del> hasWorkInProgress: false,
<del> wasDeprioritized: false,
<add> childInProgress: null,
<ide>
<ide> alternate: null,
<ide>
<ide> exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi
<ide> if (alt) {
<ide> alt.stateNode = fiber.stateNode;
<ide> alt.child = fiber.child;
<add> alt.childInProgress = fiber.childInProgress;
<ide> alt.sibling = fiber.sibling;
<ide> alt.ref = alt.ref;
<ide> alt.pendingProps = fiber.pendingProps;
<ide> exports.cloneFiber = function(fiber : Fiber, priorityLevel : PriorityLevel) : Fi
<ide> alt.type = fiber.type;
<ide> alt.stateNode = fiber.stateNode;
<ide> alt.child = fiber.child;
<add> alt.childInProgress = fiber.childInProgress;
<ide> alt.sibling = fiber.sibling;
<ide> alt.ref = alt.ref;
<ide> // pendingProps is here for symmetry but is unnecessary in practice for now.
<ide> function createFiberFromElementType(type : mixed, key : null | string) {
<ide> throw new Error('Unknown component type: ' + typeof type);
<ide> }
<ide> return fiber;
<del>};
<add>}
<ide>
<ide> exports.createFiberFromElementType = createFiberFromElementType;
<ide>
<ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js
<ide> import type { ReactCoroutine } from 'ReactCoroutine';
<ide> import type { Fiber } from 'ReactFiber';
<ide> import type { HostConfig } from 'ReactFiberReconciler';
<ide>
<del>var { reconcileChildFibers } = require('ReactChildFiber');
<add>var {
<add> reconcileChildFibers,
<add> reconcileChildFibersInPlace,
<add>} = require('ReactChildFiber');
<ide> var ReactTypeOfWork = require('ReactTypeOfWork');
<ide> var {
<ide> IndeterminateComponent,
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide>
<ide> function reconcileChildren(current, workInProgress, nextChildren) {
<ide> const priority = workInProgress.pendingWorkPriority;
<del> workInProgress.child = reconcileChildFibers(
<del> workInProgress,
<del> current ? current.child : null,
<del> nextChildren,
<del> priority
<del> );
<add> reconcileChildrenAtPriority(current, workInProgress, nextChildren, priority);
<add> }
<add>
<add> function reconcileChildrenAtPriority(current, workInProgress, nextChildren, priorityLevel) {
<add> if (current && current.childInProgress) {
<add> workInProgress.childInProgress = reconcileChildFibersInPlace(
<add> workInProgress,
<add> current.childInProgress,
<add> nextChildren,
<add> priorityLevel
<add> );
<add> // This is now invalid because we reused nodes.
<add> current.childInProgress = null;
<add> } else if (workInProgress.childInProgress) {
<add> workInProgress.childInProgress = reconcileChildFibersInPlace(
<add> workInProgress,
<add> workInProgress.childInProgress,
<add> nextChildren,
<add> priorityLevel
<add> );
<add> } else {
<add> workInProgress.childInProgress = reconcileChildFibers(
<add> workInProgress,
<add> current ? current.child : null,
<add> nextChildren,
<add> priorityLevel
<add> );
<add> }
<ide> }
<ide>
<ide> function updateFunctionalComponent(current, workInProgress) {
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> return bailoutOnCurrent(current, workInProgress);
<ide> }
<ide> }
<del> if (!workInProgress.hasWorkInProgress && workInProgress.memoizedProps) {
<add> if (!workInProgress.childInProgress && workInProgress.memoizedProps) {
<ide> // Reset the props, in case this is a ping-pong case rather than a
<ide> // completed update case. For the completed update case, the instance
<ide> // props will already be the memoizedProps.
<ide> instance.props = workInProgress.memoizedProps;
<ide> if (!instance.shouldComponentUpdate(props)) {
<del> return bailoutOnAlreadyFinishedWork(workInProgress);
<add> return bailoutOnAlreadyFinishedWork(current, workInProgress);
<ide> }
<ide> }
<ide> }
<ide> instance.props = props;
<ide> var nextChildren = instance.render();
<ide> reconcileChildren(current, workInProgress, nextChildren);
<ide> workInProgress.pendingWorkPriority = NoWork;
<del> return workInProgress.child;
<add> return workInProgress.childInProgress;
<ide> }
<ide>
<ide> function updateHostComponent(current, workInProgress) {
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> // If this host component is hidden, we can reconcile its children at
<ide> // the lowest priority and bail out from this particular pass. Unless, we're
<ide> // currently reconciling the lowest priority.
<del> workInProgress.child = reconcileChildFibers(
<del> workInProgress,
<del> current ? current.child : null,
<del> nextChildren,
<del> OffscreenPriority
<del> );
<add> // If we have a child in progress already, we reconcile against that set
<add> // to retain any work within it. We'll recreate any component that was in
<add> // the current set and next set but not in the previous in progress set.
<add> // TODO: This attaches a node that hasn't completed rendering so it
<add> // becomes part of the render tree, even though it never completed. Its
<add> // `output` property is unpredictable because of it.
<add> reconcileChildrenAtPriority(current, workInProgress, nextChildren, OffscreenPriority);
<ide> workInProgress.pendingWorkPriority = OffscreenPriority;
<del> workInProgress.wasDeprioritized = true;
<ide> return null;
<ide> } else {
<del> workInProgress.child = reconcileChildFibers(
<del> workInProgress,
<del> current ? current.child : null,
<del> nextChildren,
<del> priority
<del> );
<add> reconcileChildren(current, workInProgress, nextChildren);
<ide> workInProgress.pendingWorkPriority = NoWork;
<del> workInProgress.wasDeprioritized = false;
<del> return workInProgress.child;
<add> return workInProgress.childInProgress;
<ide> }
<ide> }
<ide>
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> workInProgress.pendingProps = null;
<ide> workInProgress.pendingWorkPriority = NoWork;
<ide> workInProgress.stateNode = current.stateNode;
<add> workInProgress.childInProgress = current.childInProgress;
<ide> if (current.child) {
<ide> // If we bail out but still has work with the current priority in this
<ide> // subtree, we need to go find it right now. If we don't, we won't flush
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> }
<ide> }
<ide>
<del> function bailoutOnAlreadyFinishedWork(workInProgress : Fiber) : ?Fiber {
<add> function bailoutOnAlreadyFinishedWork(current, workInProgress : Fiber) : ?Fiber {
<ide> // If we started this work before, and finished it, or if we're in a
<ide> // ping-pong update scenario, this version could already be what we're
<ide> // looking for. In that case, we should be able to just bail out.
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> workInProgress.nextEffect = null;
<ide> workInProgress.lastEffect = null;
<ide>
<del> if (workInProgress.child && workInProgress.child.alternate) {
<del> // On the way up here, we reset the child node to be the current one.
<del> // Therefore we have to reuse the alternate. This is super weird.
<del> let child = workInProgress.child.alternate;
<add> if (workInProgress.child) {
<add> // On the way up here, we reset the child node to be the current one by
<add> // cloning. However, it is really the original child that represents the
<add> // already completed work. Therefore we have to reuse the alternate.
<add> // But if we don't have a current, this was not cloned. This is super weird.
<add> const child = !current ? workInProgress.child : workInProgress.child.alternate;
<add> if (!child) {
<add> throw new Error('We must have a current child to be able to use this.');
<add> }
<ide> workInProgress.child = child;
<ide> // Ensure that the effects of reused work are preserved.
<ide> reuseChildrenEffects(workInProgress, child);
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> return bailoutOnCurrent(current, workInProgress);
<ide> }
<ide>
<del> if (!workInProgress.hasWorkInProgress &&
<add> if (!workInProgress.childInProgress &&
<ide> workInProgress.pendingProps === workInProgress.memoizedProps) {
<del> return bailoutOnAlreadyFinishedWork(workInProgress);
<add> return bailoutOnAlreadyFinishedWork(current, workInProgress);
<ide> }
<ide>
<del> let nextWork;
<ide> switch (workInProgress.tag) {
<ide> case IndeterminateComponent:
<ide> mountIndeterminateComponent(current, workInProgress);
<del> workInProgress.hasWorkInProgress = true;
<del> return workInProgress.child;
<add> return workInProgress.childInProgress;
<ide> case FunctionalComponent:
<ide> updateFunctionalComponent(current, workInProgress);
<del> workInProgress.hasWorkInProgress = true;
<del> return workInProgress.child;
<add> return workInProgress.childInProgress;
<ide> case ClassComponent:
<del> nextWork = updateClassComponent(current, workInProgress);
<del> workInProgress.hasWorkInProgress = true;
<del> return nextWork;
<add> return updateClassComponent(current, workInProgress);
<ide> case HostContainer:
<ide> reconcileChildren(current, workInProgress, workInProgress.pendingProps);
<ide> // A yield component is just a placeholder, we can just run through the
<ide> // next one immediately.
<del> workInProgress.hasWorkInProgress = true;
<ide> workInProgress.pendingWorkPriority = NoWork;
<del> if (workInProgress.child) {
<add> if (workInProgress.childInProgress) {
<ide> return beginWork(
<del> workInProgress.child.alternate,
<del> workInProgress.child
<add> workInProgress.childInProgress.alternate,
<add> workInProgress.childInProgress
<ide> );
<ide> }
<ide> return null;
<ide> case HostComponent:
<del> nextWork = updateHostComponent(current, workInProgress);
<del> workInProgress.hasWorkInProgress = true;
<del> return nextWork;
<add> return updateHostComponent(current, workInProgress);
<ide> case CoroutineHandlerPhase:
<ide> // This is a restart. Reset the tag to the initial phase.
<ide> workInProgress.tag = CoroutineComponent;
<ide> // Intentionally fall through since this is now the same.
<ide> case CoroutineComponent:
<ide> updateCoroutineComponent(current, workInProgress);
<del> workInProgress.hasWorkInProgress = true;
<ide> // This doesn't take arbitrary time so we could synchronously just begin
<ide> // eagerly do the work of workInProgress.child as an optimization.
<del> if (workInProgress.child) {
<add> if (workInProgress.childInProgress) {
<ide> return beginWork(
<del> workInProgress.child.alternate,
<del> workInProgress.child
<add> workInProgress.childInProgress.alternate,
<add> workInProgress.childInProgress
<ide> );
<ide> }
<del> return workInProgress.child;
<add> return workInProgress.childInProgress;
<ide> case YieldComponent:
<ide> // A yield component is just a placeholder, we can just run through the
<ide> // next one immediately.
<ide><path>src/renderers/shared/fiber/ReactFiberCommitWork.js
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> throw new Error('This should only be done during updates.');
<ide> }
<ide> // Commit the work prepared earlier.
<del> let child;
<del> if (finishedWork.wasDeprioritized) {
<del> // If this was a down priority, we need to preserve the old child in
<del> // the output.
<del> child = finishedWork.alternate ? finishedWork.alternate.child : null;
<del> } else {
<del> child = finishedWork.child;
<del> }
<add> const child = finishedWork.child;
<ide> const children = (child && !child.sibling) ? (child.output : ?Fiber | I) : child;
<ide> const newProps = finishedWork.memoizedProps;
<ide> const current = finishedWork.alternate;
<ide><path>src/renderers/shared/fiber/ReactFiberCompleteWork.js
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> markForPreEffect(workInProgress);
<ide> return null;
<ide> case HostComponent:
<del> let child;
<ide> let newProps = workInProgress.pendingProps;
<del> if (workInProgress.wasDeprioritized) {
<del> // If this was a down priority, we need to preserve the old child in
<del> // the output.
<del> child = current ? current.child : null;
<del> } else {
<del> child = workInProgress.child;
<del> }
<add> const child = workInProgress.child;
<ide> const children = (child && !child.sibling) ? (child.output : ?Fiber | I) : child;
<ide> if (current && workInProgress.stateNode != null) {
<ide> // If we have an alternate, that means this is an update and we need to
<ide><path>src/renderers/shared/fiber/ReactFiberPendingWork.js
<ide> exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev
<ide> // because it is the highest priority for the whole subtree.
<ide> // TODO: Coroutines can have work in their stateNode which is another
<ide> // type of child that needs to be searched for work.
<del> if (current.child) {
<del> // Ensure we have a work in progress copy to backtrack through.
<add> if (current.childInProgress) {
<add> let workInProgress = current.childInProgress;
<add> while (workInProgress) {
<add> workInProgress.return = current.alternate;
<add> workInProgress = workInProgress.sibling;
<add> }
<add> workInProgress = current.childInProgress;
<add> while (workInProgress) {
<add> // Don't bother drilling further down this tree if there is no child.
<add> if (workInProgress.pendingWorkPriority !== NoWork &&
<add> workInProgress.pendingWorkPriority <= priorityLevel &&
<add> workInProgress.pendingProps !== null) {
<add> return workInProgress;
<add> }
<add> workInProgress = workInProgress.sibling;
<add> }
<add> } else if (current.child) {
<ide> let currentChild = current.child;
<add> currentChild.return = current;
<add> // Ensure we have a work in progress copy to backtrack through.
<ide> let workInProgress = current.alternate;
<ide> if (!workInProgress) {
<ide> throw new Error('Should have wip now');
<ide> exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev
<ide> currentChild.pendingWorkPriority
<ide> );
<ide> cloneSiblings(currentChild, workInProgress.child, workInProgress);
<del> current = current.child;
<add> current = currentChild;
<ide> continue;
<ide> }
<ide> // If we match the priority but has no child and no work to do,
<ide> // then we can safely reset the flag.
<ide> current.pendingWorkPriority = NoWork;
<ide> }
<ide> if (current === currentRoot) {
<add> if (current.pendingWorkPriority <= priorityLevel) {
<add> // If this subtree had work left to do, we would have returned it by
<add> // now. This could happen if a child with pending work gets cleaned up
<add> // but we don't clear the flag then. It is safe to reset it now.
<add> current.pendingWorkPriority = NoWork;
<add> }
<ide> return null;
<ide> }
<ide> while (!current.sibling) {
<ide> exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev
<ide> current.pendingWorkPriority = NoWork;
<ide> }
<ide> }
<add> current.sibling.return = current.return;
<ide> current = current.sibling;
<ide> }
<ide> return null;
<ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> }
<ide> nextScheduledRoot = nextScheduledRoot.nextScheduledRoot;
<ide> }
<add> // TODO: This is scanning one root at a time. It should be scanning all
<add> // roots for high priority work before moving on to lower priorities.
<ide> let root = nextScheduledRoot;
<ide> while (root) {
<ide> cloneFiber(root.current, root.current.pendingWorkPriority);
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> // We didn't find anything to do in this root, so let's try the next one.
<ide> root = root.nextScheduledRoot;
<ide> }
<add> root = nextScheduledRoot;
<add> while (root) {
<add> root = root.nextScheduledRoot;
<add> }
<add>
<ide> nextPriorityLevel = NoWork;
<ide> return null;
<ide> }
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> // The work is now done. We don't need this anymore. This flags
<ide> // to the system not to redo any work here.
<ide> workInProgress.pendingProps = null;
<del> if (workInProgress.pendingWorkPriority === NoWork) {
<del> workInProgress.hasWorkInProgress = false;
<del> }
<ide>
<ide> const returnFiber = workInProgress.return;
<ide>
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> } else if (returnFiber) {
<ide> // If there's no more work in this returnFiber. Complete the returnFiber.
<ide> workInProgress = returnFiber;
<add> // If we're stepping up through the child, that means we can now commit
<add> // this work. We should only do this when we're stepping upwards because
<add> // completing a downprioritized item is not the same as completing its
<add> // children.
<add> if (workInProgress.childInProgress) {
<add> workInProgress.child = workInProgress.childInProgress;
<add> workInProgress.childInProgress = null;
<add> }
<add> continue;
<ide> } else {
<ide> // If we're at the root, there's no more work to do. We can flush it.
<ide> const root : FiberRoot = (workInProgress.stateNode : any);
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js
<ide> describe('ReactIncremental', function() {
<ide> });
<ide>
<ide> it('can resume work in a bailed subtree within one pass', function() {
<del>
<ide> var ops = [];
<ide>
<ide> function Bar(props) {
<ide> describe('ReactIncremental', function() {
<ide> return <span>{props.children}</span>;
<ide> }
<ide>
<add> // Should content not just bail out on current, not workInProgress?
<add>
<ide> class Content extends React.Component {
<ide> shouldComponentUpdate() {
<ide> return false;
<ide> describe('ReactIncremental', function() {
<ide> // after them which is not correct.
<ide> ReactNoop.flush();
<ide> expect(ops).toEqual(['Bar', 'Middle', 'Bar']);
<del>
<ide> });
<ide>
<ide> it('can reuse work done after being preempted', function() {
<ide> describe('ReactIncremental', function() {
<ide> </div>
<ide> );
<ide>
<add> var step0 = (
<add> <div>
<add> <Middle>Hi</Middle>
<add> <Bar>{'Foo'}</Bar>
<add> <Middle>There</Middle>
<add> </div>
<add> );
<add>
<ide> function Foo(props) {
<ide> ops.push('Foo');
<ide> return (
<ide> <div>
<del> <Bar>{props.text}</Bar>
<add> <Bar>{props.text2}</Bar>
<ide> <div hidden={true}>
<ide> {
<ide> props.step === 0 ?
<del> <div>
<del> <Middle>Hi</Middle>
<del> <Bar>{props.text}</Bar>
<del> <Middle>There</Middle>
<del> </div>
<add> step0
<ide> : middleContent
<ide> }
<ide> </div>
<ide> describe('ReactIncremental', function() {
<ide> }
<ide>
<ide> // Init
<del> ReactNoop.render(<Foo text="foo" step={0} />);
<add> ReactNoop.render(<Foo text="foo" text2="foo" step={0} />);
<add> ReactNoop.flushLowPri(55);
<add>
<add> // We only finish the higher priority work. So the low pri content
<add> // has not yet finished mounting.
<add> expect(ops).toEqual(['Foo', 'Bar', 'Middle', 'Bar']);
<add>
<add> ops = [];
<add>
<add> // Interupt the rendering with a quick update. This should not touch the
<add> // middle content.
<add> ReactNoop.render(<Foo text="foo" text2="bar" step={0} />);
<ide> ReactNoop.flush();
<ide>
<del> expect(ops).toEqual(['Foo', 'Bar', 'Middle', 'Bar', 'Middle']);
<add> // We've now rendered the entire tree but we didn't have to redo the work
<add> // done by the first Middle and Bar already.
<add> expect(ops).toEqual(['Foo', 'Bar', 'Middle']);
<ide>
<ide> ops = [];
<ide>
<ide> // Make a quick update which will schedule low priority work to
<ide> // update the middle content.
<del> ReactNoop.render(<Foo text="bar" step={1} />);
<add> ReactNoop.render(<Foo text="bar" text2="bar" step={1} />);
<ide> ReactNoop.flushLowPri(30);
<ide>
<ide> expect(ops).toEqual(['Foo', 'Bar']);
<ide> describe('ReactIncremental', function() {
<ide>
<ide> // but we'll interupt it to render some higher priority work.
<ide> // The middle content will bailout so it remains untouched.
<del> ReactNoop.render(<Foo text="foo" step={1} />);
<add> ReactNoop.render(<Foo text="foo" text2="bar" step={1} />);
<ide> ReactNoop.flushLowPri(30);
<ide>
<ide> expect(ops).toEqual(['Foo', 'Bar']); | 9 |
Python | Python | add restore functions to numpy.dual | 6a30aaf84be313b29a4072ec3357ff5e4a6b2d74 | <ide><path>numpy/dual.py
<ide> def restore_func(name):
<ide> if name not in __all__:
<ide> raise ValueError, "%s not a dual function." % name
<ide> try:
<del> sys._getframe(0).f_globals[name] = _restore_dict[name]
<add> val = _restore_dict[name]
<ide> except KeyError:
<del> pass
<del>
<add> return
<add> else:
<add> sys._getframe(0).f_globals[name] = val
<add>
<add>def restore_all():
<add> for name in _restore_dict.keys():
<add> restore_func(name)
<add> | 1 |
PHP | PHP | remove meaningless code | 727a0e409b6ca477994078b7b805e92a38fa3e83 | <ide><path>src/Utility/Hash.php
<ide> protected static function _simpleOp($op, $data, $path, $values = null)
<ide> $count = count($path);
<ide> $last = $count - 1;
<ide> foreach ($path as $i => $key) {
<del> if ((is_numeric($key) && (int)$key > 0 || $key === '0') &&
<del> strpos($key, '0') !== 0
<del> ) {
<del> $key = (int)$key;
<del> }
<ide> if ($op === 'insert') {
<ide> if ($i === $last) {
<ide> $_list[$key] = $values; | 1 |
Text | Text | add changelog for fix [skip ci] | 4e757746a626ead999c4cabf443d3b683ac34ffc | <ide><path>activerecord/CHANGELOG.md
<add>* Dont enroll records in the transaction if they dont have commit callbacks.
<add> That was causing a memory grow problem when creating a lot of records inside a transaction.
<add>
<add> Fixes #15549.
<add>
<add> *Will Bryant*, *Aaron Patterson*
<add>
<ide> * Correctly create through records when created on a has many through
<ide> association when using `where`.
<ide> | 1 |
Go | Go | move inspect into the loop on inspectexecid test | f06620ece3557eb263b221e476cef2955235ba75 | <ide><path>integration-cli/docker_cli_exec_test.go
<ide> func (s *DockerSuite) TestInspectExecID(c *check.C) {
<ide> c.Fatalf("failed to start the exec cmd: %q", err)
<ide> }
<ide>
<del> // Since its still running we should see the exec as part of the container
<del> out, err = inspectField(id, "ExecIDs")
<del> if err != nil {
<del> c.Fatalf("failed to inspect container: %s, %v", out, err)
<del> }
<del>
<ide> // Give the exec 10 chances/seconds to start then give up and stop the test
<ide> tries := 10
<ide> for i := 0; i < tries; i++ {
<add> // Since its still running we should see exec as part of the container
<add> out, err = inspectField(id, "ExecIDs")
<add> if err != nil {
<add> c.Fatalf("failed to inspect container: %s, %v", out, err)
<add> }
<add>
<ide> out = strings.TrimSuffix(out, "\n")
<ide> if out != "[]" && out != "<no value>" {
<ide> break | 1 |
Ruby | Ruby | permit weak imports in go reverse deps | 3c6529851991eed20c75ba4661a1734d8a889468 | <ide><path>Library/Homebrew/build.rb
<ide> def install
<ide>
<ide> ENV.activate_extensions!
<ide>
<add> # Go makes extensive use of weak imports.
<add> if formula_deps.any? { |f| f.name == "go" }
<add> ENV.permit_weak_imports
<add> end
<add>
<ide> if superenv?
<ide> ENV.keg_only_deps = keg_only_deps
<ide> ENV.deps = formula_deps | 1 |
Go | Go | create internal directory | 204ce3e31d4ec7275fc58032740a82f6bd656466 | <ide><path>libnetwork/diagnostic/server.go
<ide> import (
<ide> "sync/atomic"
<ide>
<ide> stackdump "github.com/docker/docker/pkg/signal"
<del> "github.com/docker/libnetwork/common"
<add> "github.com/docker/libnetwork/internal/caller"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> func notImplemented(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> rsp := WrongCommand("not implemented", fmt.Sprintf("URL path: %s no method implemented check /help\n", r.URL.Path))
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("command not implemented done")
<ide>
<ide> HTTPReply(w, rsp, json)
<ide> func help(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("help done")
<ide>
<ide> n, ok := ctx.(*Server)
<ide> func ready(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("ready done")
<ide> HTTPReply(w, CommandSucceed(&StringCmd{Info: "OK"}), json)
<ide> }
<ide> func stackTrace(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("stack trace")
<ide>
<ide> path, err := stackdump.DumpStacks("/tmp/")
<ide><path>libnetwork/drivers/overlay/peerdb.go
<ide> import (
<ide> "sync"
<ide> "syscall"
<ide>
<del> "github.com/docker/libnetwork/common"
<add> "github.com/docker/libnetwork/internal/caller"
<add> "github.com/docker/libnetwork/internal/setmatrix"
<ide> "github.com/docker/libnetwork/osl"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide> func (p *peerEntryDB) UnMarshalDB() peerEntry {
<ide>
<ide> type peerMap struct {
<ide> // set of peerEntry, note they have to be objects and not pointers to maintain the proper equality checks
<del> mp common.SetMatrix
<add> mp setmatrix.SetMatrix
<ide> sync.Mutex
<ide> }
<ide>
<ide> func (d *driver) peerDbAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask
<ide> pMap, ok := d.peerDb.mp[nid]
<ide> if !ok {
<ide> d.peerDb.mp[nid] = &peerMap{
<del> mp: common.NewSetMatrix(),
<add> mp: setmatrix.NewSetMatrix(),
<ide> }
<ide>
<ide> pMap = d.peerDb.mp[nid]
<ide> func (d *driver) peerOpRoutine(ctx context.Context, ch chan *peerOperation) {
<ide> }
<ide>
<ide> func (d *driver) peerInit(nid string) {
<del> callerName := common.CallerName(1)
<add> callerName := caller.Name(1)
<ide> d.peerOpCh <- &peerOperation{
<ide> opType: peerOperationINIT,
<ide> networkID: nid,
<ide> func (d *driver) peerAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
<ide> l2Miss: l2Miss,
<ide> l3Miss: l3Miss,
<ide> localPeer: localPeer,
<del> callerName: common.CallerName(1),
<add> callerName: caller.Name(1),
<ide> }
<ide> }
<ide>
<ide> func (d *driver) peerDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMas
<ide> peerIPMask: peerIPMask,
<ide> peerMac: peerMac,
<ide> vtepIP: vtep,
<del> callerName: common.CallerName(1),
<add> callerName: caller.Name(1),
<ide> localPeer: localPeer,
<ide> }
<ide> }
<ide> func (d *driver) peerFlush(nid string) {
<ide> d.peerOpCh <- &peerOperation{
<ide> opType: peerOperationFLUSH,
<ide> networkID: nid,
<del> callerName: common.CallerName(1),
<add> callerName: caller.Name(1),
<ide> }
<ide> }
<ide>
<add><path>libnetwork/internal/caller/caller.go
<del><path>libnetwork/common/caller.go
<del>package common
<add>package caller
<ide>
<ide> import (
<ide> "runtime"
<ide> func callerInfo(i int) string {
<ide> if ok {
<ide> f := runtime.FuncForPC(ptr)
<ide> if f != nil {
<del> // f.Name() is like: github.com/docker/libnetwork/common.MethodName
<add> // f.Name() is like: github.com/docker/libnetwork/caller.MethodName
<ide> tmp := strings.Split(f.Name(), ".")
<ide> if len(tmp) > 0 {
<ide> fName = tmp[len(tmp)-1]
<ide> func callerInfo(i int) string {
<ide> return fName
<ide> }
<ide>
<del>// CallerName returns the name of the function at the specified level
<add>// Name returns the name of the function at the specified level
<ide> // level == 0 means current method name
<del>func CallerName(level int) string {
<add>func Name(level int) string {
<ide> return callerInfo(2 + level)
<ide> }
<add><path>libnetwork/internal/caller/caller_test.go
<del><path>libnetwork/common/caller_test.go
<del>package common
<add>package caller
<ide>
<del>import "testing"
<add>import (
<add> "testing"
<add>
<add> _ "github.com/docker/libnetwork/testutils"
<add>)
<ide>
<ide> func fun1() string {
<del> return CallerName(0)
<add> return Name(0)
<ide> }
<ide>
<ide> func fun2() string {
<del> return CallerName(1)
<add> return Name(1)
<ide> }
<ide>
<ide> func fun3() string {
<ide> return fun4()
<ide> }
<ide>
<ide> func fun4() string {
<del> return CallerName(0)
<add> return Name(0)
<ide> }
<ide>
<ide> func fun5() string {
<ide> return fun6()
<ide> }
<ide>
<ide> func fun6() string {
<del> return CallerName(1)
<add> return Name(1)
<ide> }
<ide>
<ide> func TestCaller(t *testing.T) {
<add><path>libnetwork/internal/setmatrix/setmatrix.go
<del><path>libnetwork/common/setmatrix.go
<del>package common
<add>package setmatrix
<ide>
<ide> import (
<ide> "sync"
<add><path>libnetwork/internal/setmatrix/setmatrix_test.go
<del><path>libnetwork/common/setmatrix_test.go
<del>package common
<add>package setmatrix
<ide>
<ide> import (
<ide> "context"
<ide><path>libnetwork/libnetwork_internal_test.go
<ide> import (
<ide> "testing"
<ide> "time"
<ide>
<del> "github.com/docker/libnetwork/common"
<ide> "github.com/docker/libnetwork/datastore"
<ide> "github.com/docker/libnetwork/discoverapi"
<ide> "github.com/docker/libnetwork/driverapi"
<add> "github.com/docker/libnetwork/internal/setmatrix"
<ide> "github.com/docker/libnetwork/ipamapi"
<ide> "github.com/docker/libnetwork/netlabel"
<ide> "github.com/docker/libnetwork/netutils"
<ide> func TestSRVServiceQuery(t *testing.T) {
<ide> }
<ide>
<ide> sr := svcInfo{
<del> svcMap: common.NewSetMatrix(),
<del> svcIPv6Map: common.NewSetMatrix(),
<del> ipMap: common.NewSetMatrix(),
<add> svcMap: setmatrix.NewSetMatrix(),
<add> svcIPv6Map: setmatrix.NewSetMatrix(),
<add> ipMap: setmatrix.NewSetMatrix(),
<ide> service: make(map[string][]servicePorts),
<ide> }
<ide> // backing container for the service
<ide><path>libnetwork/network.go
<ide> import (
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/libnetwork/common"
<ide> "github.com/docker/libnetwork/config"
<ide> "github.com/docker/libnetwork/datastore"
<ide> "github.com/docker/libnetwork/driverapi"
<ide> "github.com/docker/libnetwork/etchosts"
<add> "github.com/docker/libnetwork/internal/setmatrix"
<ide> "github.com/docker/libnetwork/ipamapi"
<ide> "github.com/docker/libnetwork/netlabel"
<ide> "github.com/docker/libnetwork/netutils"
<ide> type svcMapEntry struct {
<ide> }
<ide>
<ide> type svcInfo struct {
<del> svcMap common.SetMatrix
<del> svcIPv6Map common.SetMatrix
<del> ipMap common.SetMatrix
<add> svcMap setmatrix.SetMatrix
<add> svcIPv6Map setmatrix.SetMatrix
<add> ipMap setmatrix.SetMatrix
<ide> service map[string][]servicePorts
<ide> }
<ide>
<ide> func (n *network) updateSvcRecord(ep *endpoint, localEps []*endpoint, isAdd bool
<ide> }
<ide> }
<ide>
<del>func addIPToName(ipMap common.SetMatrix, name, serviceID string, ip net.IP) {
<add>func addIPToName(ipMap setmatrix.SetMatrix, name, serviceID string, ip net.IP) {
<ide> reverseIP := netutils.ReverseIP(ip.String())
<ide> ipMap.Insert(reverseIP, ipInfo{
<ide> name: name,
<ide> serviceID: serviceID,
<ide> })
<ide> }
<ide>
<del>func delIPToName(ipMap common.SetMatrix, name, serviceID string, ip net.IP) {
<add>func delIPToName(ipMap setmatrix.SetMatrix, name, serviceID string, ip net.IP) {
<ide> reverseIP := netutils.ReverseIP(ip.String())
<ide> ipMap.Remove(reverseIP, ipInfo{
<ide> name: name,
<ide> serviceID: serviceID,
<ide> })
<ide> }
<ide>
<del>func addNameToIP(svcMap common.SetMatrix, name, serviceID string, epIP net.IP) {
<add>func addNameToIP(svcMap setmatrix.SetMatrix, name, serviceID string, epIP net.IP) {
<ide> svcMap.Insert(name, svcMapEntry{
<ide> ip: epIP.String(),
<ide> serviceID: serviceID,
<ide> })
<ide> }
<ide>
<del>func delNameToIP(svcMap common.SetMatrix, name, serviceID string, epIP net.IP) {
<add>func delNameToIP(svcMap setmatrix.SetMatrix, name, serviceID string, epIP net.IP) {
<ide> svcMap.Remove(name, svcMapEntry{
<ide> ip: epIP.String(),
<ide> serviceID: serviceID,
<ide> func (n *network) addSvcRecords(eID, name, serviceID string, epIP, epIPv6 net.IP
<ide> sr, ok := c.svcRecords[n.ID()]
<ide> if !ok {
<ide> sr = svcInfo{
<del> svcMap: common.NewSetMatrix(),
<del> svcIPv6Map: common.NewSetMatrix(),
<del> ipMap: common.NewSetMatrix(),
<add> svcMap: setmatrix.NewSetMatrix(),
<add> svcIPv6Map: setmatrix.NewSetMatrix(),
<add> ipMap: setmatrix.NewSetMatrix(),
<ide> }
<ide> c.svcRecords[n.ID()] = sr
<ide> }
<ide><path>libnetwork/networkdb/networkdbdiagnostic.go
<ide> import (
<ide> "net/http"
<ide> "strings"
<ide>
<del> "github.com/docker/libnetwork/common"
<ide> "github.com/docker/libnetwork/diagnostic"
<add> "github.com/docker/libnetwork/internal/caller"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("join cluster")
<ide>
<ide> if len(r.Form["members"]) < 1 {
<ide> func dbPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("network peers")
<ide>
<ide> if len(r.Form["nid"]) < 1 {
<ide> func dbClusterPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("cluster peers")
<ide>
<ide> nDB, ok := ctx.(*NetworkDB)
<ide> func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> unsafe, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("create entry")
<ide>
<ide> if len(r.Form["tname"]) < 1 ||
<ide> func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> unsafe, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("update entry")
<ide>
<ide> if len(r.Form["tname"]) < 1 ||
<ide> func dbDeleteEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("delete entry")
<ide>
<ide> if len(r.Form["tname"]) < 1 ||
<ide> func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> unsafe, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("get entry")
<ide>
<ide> if len(r.Form["tname"]) < 1 ||
<ide> func dbJoinNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("join network")
<ide>
<ide> if len(r.Form["nid"]) < 1 {
<ide> func dbLeaveNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("leave network")
<ide>
<ide> if len(r.Form["nid"]) < 1 {
<ide> func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> unsafe, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("get table")
<ide>
<ide> if len(r.Form["tname"]) < 1 ||
<ide> func dbNetworkStats(ctx interface{}, w http.ResponseWriter, r *http.Request) {
<ide> _, json := diagnostic.ParseHTTPFormOptions(r)
<ide>
<ide> // audit logs
<del> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": common.CallerName(0), "url": r.URL.String()})
<add> log := logrus.WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
<ide> log.Info("network stats")
<ide>
<ide> if len(r.Form["nid"]) < 1 {
<ide><path>libnetwork/service.go
<ide> import (
<ide> "net"
<ide> "sync"
<ide>
<del> "github.com/docker/libnetwork/common"
<add> "github.com/docker/libnetwork/internal/setmatrix"
<ide> )
<ide>
<ide> var (
<ide> type service struct {
<ide> // associated with it. At stable state the endpoint ID expected is 1
<ide> // but during transition and service change it is possible to have
<ide> // temporary more than 1
<del> ipToEndpoint common.SetMatrix
<add> ipToEndpoint setmatrix.SetMatrix
<ide>
<ide> deleted bool
<ide>
<ide><path>libnetwork/service_common.go
<ide> package libnetwork
<ide> import (
<ide> "net"
<ide>
<del> "github.com/docker/libnetwork/common"
<add> "github.com/docker/libnetwork/internal/setmatrix"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> func newService(name string, id string, ingressPorts []*PortConfig, serviceAlias
<ide> ingressPorts: ingressPorts,
<ide> loadBalancers: make(map[string]*loadBalancer),
<ide> aliases: serviceAliases,
<del> ipToEndpoint: common.NewSetMatrix(),
<add> ipToEndpoint: setmatrix.NewSetMatrix(),
<ide> }
<ide> }
<ide> | 11 |
Javascript | Javascript | add missing semicolon | 54551f17730eaf164416fc6019211194085bd628 | <ide><path>examples/js/BufferGeometryUtils.js
<ide> THREE.BufferGeometryUtils = {
<ide>
<ide> if ( isIndexed ) {
<ide>
<del> count = geometry.index.count
<add> count = geometry.index.count;
<ide>
<ide> } else if ( geometry.attributes.position !== undefined ) {
<ide> | 1 |
PHP | PHP | remove unused property from validator | 46bf67aeedeeab5bdba33c9578bdebef0014f6ee | <ide><path>laravel/validator.php
<ide> class Validator {
<ide> */
<ide> protected $size_rules = array('size', 'between', 'min', 'max');
<ide>
<del> /**
<del> * The inclusion related validation rules.
<del> *
<del> * @var array
<del> */
<del> protected $inclusion_rules = array('in', 'not_in', 'mimes');
<del>
<ide> /**
<ide> * The numeric related validation rules.
<ide> * | 1 |
Text | Text | remove duplicate template | 14308b0958995b118a77c3169099634736a0b342 | <ide><path>.github/ISSUE_TEMPLATE/bug-report--issues-with-coding-challenge.md
<del>---
<del>name: 'Bug Report: Issues with Coding challenge'
<del>about: Reporting issue with a specific challenge, like broken tests, unclear instructions.
<del>
<del>---
<del>
<del><!--
<del>NOTE: If you're reporting a security issue, don't create a GitHub issue. Instead, email security@freecodecamp.org. We will look into it immediately.
<del>-->
<del>**Describe your problem and how to reproduce it:**
<del>
<del>
<del>**Add a Link to the page with the problem:**
<del>
<del>
<del>**Tell us about your browser and operating system:**
<del>* Browser Name:
<del>* Browser Version:
<del>* Operating System:
<del>
<del>
<del>**If possible, add a screenshot here (you can drag and drop, png, jpg, gif, etc. in this box):** | 1 |
Ruby | Ruby | reduce hash creation in formhelper | cade89e034ae7bc37422f4a0b395559e7fc2ec81 | <ide><path>actionview/lib/action_view/helpers/form_helper.rb
<ide> def emitted_hidden_id? # :nodoc:
<ide>
<ide> private
<ide> def objectify_options(options)
<del> @default_options.merge(options.merge(object: @object))
<add> result = @default_options.merge(options)
<add> result[:object] = @object
<add> result
<ide> end
<ide>
<ide> def submit_default_value | 1 |
Python | Python | update a number of example scripts | 803e2869c76c5c73bfe1fbf6ab4af269b4a0d551 | <ide><path>examples/addition_rnn.py
<ide>
<ide> Five digits inverted:
<ide> + One layer LSTM (128 HN), 550k training examples = 99% train/test accuracy in 30 epochs
<del>
<ide> '''
<ide>
<ide> from __future__ import print_function
<ide> from keras.models import Sequential
<del>from keras.engine.training import slice_X
<ide> from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, recurrent
<ide> import numpy as np
<ide> from six.moves import range
<ide> def encode(self, C, num_rows):
<ide> num_rows: Number of rows in the returned one hot encoding. This is
<ide> used to keep the # of rows for each data the same.
<ide> """
<del> X = np.zeros((num_rows, len(self.chars)))
<add> x = np.zeros((num_rows, len(self.chars)))
<ide> for i, c in enumerate(C):
<del> X[i, self.char_indices[c]] = 1
<del> return X
<add> x[i, self.char_indices[c]] = 1
<add> return x
<ide>
<del> def decode(self, X, calc_argmax=True):
<add> def decode(self, x, calc_argmax=True):
<ide> if calc_argmax:
<del> X = X.argmax(axis=-1)
<del> return ''.join(self.indices_char[x] for x in X)
<add> x = x.argmax(axis=-1)
<add> return ''.join(self.indices_char[x] for x in x)
<ide>
<ide>
<ide> class colors:
<ide> class colors:
<ide>
<ide> # Maximum length of input is 'int + int' (e.g., '345+678'). Maximum length of
<ide> # int is DIGITS.
<del>MAXLEN = DIGITS + 1 + DIGITS
<add>MAxLEN = DIGITS + 1 + DIGITS
<ide>
<ide> # All the numbers, plus sign and space for padding.
<ide> chars = '0123456789+ '
<ide> class colors:
<ide> for i in range(np.random.randint(1, DIGITS + 1))))
<ide> a, b = f(), f()
<ide> # Skip any addition questions we've already seen
<del> # Also skip any such that X+Y == Y+X (hence the sorting).
<add> # Also skip any such that x+Y == Y+x (hence the sorting).
<ide> key = tuple(sorted((a, b)))
<ide> if key in seen:
<ide> continue
<ide> seen.add(key)
<del> # Pad the data with spaces such that it is always MAXLEN.
<add> # Pad the data with spaces such that it is always MAxLEN.
<ide> q = '{}+{}'.format(a, b)
<del> query = q + ' ' * (MAXLEN - len(q))
<add> query = q + ' ' * (MAxLEN - len(q))
<ide> ans = str(a + b)
<ide> # Answers can be of maximum size DIGITS + 1.
<ide> ans += ' ' * (DIGITS + 1 - len(ans))
<ide> class colors:
<ide> print('Total addition questions:', len(questions))
<ide>
<ide> print('Vectorization...')
<del>X = np.zeros((len(questions), MAXLEN, len(chars)), dtype=np.bool)
<add>x = np.zeros((len(questions), MAxLEN, len(chars)), dtype=np.bool)
<ide> y = np.zeros((len(questions), DIGITS + 1, len(chars)), dtype=np.bool)
<ide> for i, sentence in enumerate(questions):
<del> X[i] = ctable.encode(sentence, MAXLEN)
<add> x[i] = ctable.encode(sentence, MAxLEN)
<ide> for i, sentence in enumerate(expected):
<ide> y[i] = ctable.encode(sentence, DIGITS + 1)
<ide>
<del># Shuffle (X, y) in unison as the later parts of X will almost all be larger
<add># Shuffle (x, y) in unison as the later parts of x will almost all be larger
<ide> # digits.
<ide> indices = np.arange(len(y))
<ide> np.random.shuffle(indices)
<del>X = X[indices]
<add>x = x[indices]
<ide> y = y[indices]
<ide>
<ide> # Explicitly set apart 10% for validation data that we never train over.
<del>split_at = len(X) - len(X) // 10
<del>(X_train, X_val) = (slice_X(X, 0, split_at), slice_X(X, split_at))
<del>(y_train, y_val) = (y[:split_at], y[split_at:])
<add>split_at = len(x) - len(x) // 10
<add>(x_train, x_val) = x[:split_at], x[split_at:]
<add>(y_train, y_val) = y[:split_at], y[split_at:]
<ide>
<ide> print('Training Data:')
<del>print(X_train.shape)
<add>print(x_train.shape)
<ide> print(y_train.shape)
<ide>
<ide> print('Validation Data:')
<del>print(X_val.shape)
<add>print(x_val.shape)
<ide> print(y_val.shape)
<ide>
<ide> # Try replacing GRU, or SimpleRNN.
<ide> class colors:
<ide> # "Encode" the input sequence using an RNN, producing an output of HIDDEN_SIZE.
<ide> # Note: In a situation where your input sequences have a variable length,
<ide> # use input_shape=(None, num_feature).
<del>model.add(RNN(HIDDEN_SIZE, input_shape=(MAXLEN, len(chars))))
<add>model.add(RNN(HIDDEN_SIZE, input_shape=(MAxLEN, len(chars))))
<ide> # As the decoder RNN's input, repeatedly provide with the last hidden state of
<ide> # RNN for each time step. Repeat 'DIGITS + 1' times as that's the maximum
<ide> # length of output, e.g., when DIGITS=3, max output is 999+999=1998.
<ide> class colors:
<ide> print()
<ide> print('-' * 50)
<ide> print('Iteration', iteration)
<del> model.fit(X_train, y_train, batch_size=BATCH_SIZE, epochs=1,
<del> validation_data=(X_val, y_val))
<add> model.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=1,
<add> validation_data=(x_val, y_val))
<ide> # Select 10 samples from the validation set at random so we can visualize
<ide> # errors.
<ide> for i in range(10):
<del> ind = np.random.randint(0, len(X_val))
<del> rowX, rowy = X_val[np.array([ind])], y_val[np.array([ind])]
<del> preds = model.predict_classes(rowX, verbose=0)
<del> q = ctable.decode(rowX[0])
<add> ind = np.random.randint(0, len(x_val))
<add> rowx, rowy = x_val[np.array([ind])], y_val[np.array([ind])]
<add> preds = model.predict_classes(rowx, verbose=0)
<add> q = ctable.decode(rowx[0])
<ide> correct = ctable.decode(rowy[0])
<ide> guess = ctable.decode(preds[0], calc_argmax=False)
<ide> print('Q', q[::-1] if INVERT else q)
<ide><path>examples/antirectifier.py
<ide> def compute_output_shape(self, input_shape):
<ide> shape[-1] *= 2
<ide> return tuple(shape)
<ide>
<del> def call(self, x, mask=None):
<del> x -= K.mean(x, axis=1, keepdims=True)
<del> x = K.l2_normalize(x, axis=1)
<del> pos = K.relu(x)
<del> neg = K.relu(-x)
<add> def call(self, inputs):
<add> inputs -= K.mean(inputs, axis=1, keepdims=True)
<add> inputs = K.l2_normalize(inputs, axis=1)
<add> pos = K.relu(inputs)
<add> neg = K.relu(-inputs)
<ide> return K.concatenate([pos, neg], axis=1)
<ide>
<ide> # global parameters
<ide> def call(self, x, mask=None):
<ide> epochs = 40
<ide>
<ide> # the data, shuffled and split between train and test sets
<del>(X_train, y_train), (X_test, y_test) = mnist.load_data()
<add>(x_train, y_train), (x_test, y_test) = mnist.load_data()
<ide>
<del>X_train = X_train.reshape(60000, 784)
<del>X_test = X_test.reshape(10000, 784)
<del>X_train = X_train.astype('float32')
<del>X_test = X_test.astype('float32')
<del>X_train /= 255
<del>X_test /= 255
<del>print(X_train.shape[0], 'train samples')
<del>print(X_test.shape[0], 'test samples')
<add>x_train = x_train.reshape(60000, 784)
<add>x_test = x_test.reshape(10000, 784)
<add>x_train = x_train.astype('float32')
<add>x_test = x_test.astype('float32')
<add>x_train /= 255
<add>x_test /= 255
<add>print(x_train.shape[0], 'train samples')
<add>print(x_test.shape[0], 'test samples')
<ide>
<ide> # convert class vectors to binary class matrices
<ide> Y_train = np_utils.to_categorical(y_train, num_classes)
<ide> def call(self, x, mask=None):
<ide> metrics=['accuracy'])
<ide>
<ide> # train the model
<del>model.fit(X_train, Y_train,
<add>model.fit(x_train, Y_train,
<ide> batch_size=batch_size, epochs=epochs,
<del> verbose=1, validation_data=(X_test, Y_test))
<add> verbose=1, validation_data=(x_test, Y_test))
<ide>
<ide> # next, compare with an equivalent network
<ide> # with2x bigger Dense layers and ReLU
<ide><path>examples/babi_rnn.py
<ide> QA3 - Three Supporting Facts | 20 | 20.5
<ide> QA4 - Two Arg. Relations | 61 | 62.9
<ide> QA5 - Three Arg. Relations | 70 | 61.9
<del>QA6 - Yes/No Questions | 48 | 50.7
<add>QA6 - yes/No Questions | 48 | 50.7
<ide> QA7 - Counting | 49 | 78.9
<ide> QA8 - Lists/Sets | 45 | 77.2
<ide> QA9 - Simple Negation | 64 | 64.0
<ide> import tarfile
<ide>
<ide> import numpy as np
<del>np.random.seed(1337) # for reproducibility
<ide>
<ide> from keras.utils.data_utils import get_file
<ide> from keras.layers.embeddings import Embedding
<del>from keras.layers import Dense, Merge, Dropout, RepeatVector
<add>from keras import layers
<ide> from keras.layers import recurrent
<del>from keras.models import Sequential
<add>from keras.models import Model
<ide> from keras.preprocessing.sequence import pad_sequences
<ide>
<ide>
<ide> def get_stories(f, only_supporting=False, max_length=None):
<ide>
<ide>
<ide> def vectorize_stories(data, word_idx, story_maxlen, query_maxlen):
<del> X = []
<del> Xq = []
<del> Y = []
<add> xs = []
<add> xqs = []
<add> ys = []
<ide> for story, query, answer in data:
<ide> x = [word_idx[w] for w in story]
<ide> xq = [word_idx[w] for w in query]
<ide> y = np.zeros(len(word_idx) + 1) # let's not forget that index 0 is reserved
<ide> y[word_idx[answer]] = 1
<del> X.append(x)
<del> Xq.append(xq)
<del> Y.append(y)
<del> return pad_sequences(X, maxlen=story_maxlen), pad_sequences(Xq, maxlen=query_maxlen), np.array(Y)
<add> xs.append(x)
<add> xqs.append(xq)
<add> ys.append(y)
<add> return pad_sequences(xs, maxlen=story_maxlen), pad_sequences(xqs, maxlen=query_maxlen), np.array(ys)
<ide>
<ide> RNN = recurrent.LSTM
<ide> EMBED_HIDDEN_SIZE = 50
<ide> SENT_HIDDEN_SIZE = 100
<del>QUERY_HIDDEN_SIZE = 100
<add>QUERy_HIDDEN_SIZE = 100
<ide> BATCH_SIZE = 32
<ide> EPOCHS = 40
<del>print('RNN / Embed / Sent / Query = {}, {}, {}, {}'.format(RNN, EMBED_HIDDEN_SIZE, SENT_HIDDEN_SIZE, QUERY_HIDDEN_SIZE))
<add>print('RNN / Embed / Sent / Query = {}, {}, {}, {}'.format(RNN, EMBED_HIDDEN_SIZE, SENT_HIDDEN_SIZE, QUERy_HIDDEN_SIZE))
<ide>
<ide> try:
<ide> path = get_file('babi-tasks-v1-2.tar.gz', origin='https://s3.amazonaws.com/text-datasets/babi_tasks_1-20_v1-2.tar.gz')
<ide> def vectorize_stories(data, word_idx, story_maxlen, query_maxlen):
<ide> story_maxlen = max(map(len, (x for x, _, _ in train + test)))
<ide> query_maxlen = max(map(len, (x for _, x, _ in train + test)))
<ide>
<del>X, Xq, Y = vectorize_stories(train, word_idx, story_maxlen, query_maxlen)
<del>tX, tXq, tY = vectorize_stories(test, word_idx, story_maxlen, query_maxlen)
<add>x, xq, y = vectorize_stories(train, word_idx, story_maxlen, query_maxlen)
<add>tx, txq, ty = vectorize_stories(test, word_idx, story_maxlen, query_maxlen)
<ide>
<ide> print('vocab = {}'.format(vocab))
<del>print('X.shape = {}'.format(X.shape))
<del>print('Xq.shape = {}'.format(Xq.shape))
<del>print('Y.shape = {}'.format(Y.shape))
<add>print('x.shape = {}'.format(x.shape))
<add>print('xq.shape = {}'.format(xq.shape))
<add>print('y.shape = {}'.format(y.shape))
<ide> print('story_maxlen, query_maxlen = {}, {}'.format(story_maxlen, query_maxlen))
<ide>
<ide> print('Build model...')
<ide>
<del>sentrnn = Sequential()
<del>sentrnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE,
<del> input_length=story_maxlen))
<del>sentrnn.add(Dropout(0.3))
<add>sentence = layers.Input(shape=(story_maxlen,), dtype='int32')
<add>encoded_sentence = layers.Embedding(vocab_size, EMBED_HIDDEN_SIZE)(sentence)
<add>encoded_sentence = layers.Dropout(0.3)(encoded_sentence)
<ide>
<del>qrnn = Sequential()
<del>qrnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE,
<del> input_length=query_maxlen))
<del>qrnn.add(Dropout(0.3))
<del>qrnn.add(RNN(EMBED_HIDDEN_SIZE, return_sequences=False))
<del>qrnn.add(RepeatVector(story_maxlen))
<add>question = layers.Input(shape=(query_maxlen,), dtype='int32')
<add>encoded_question = layers.Embedding(vocab_size, EMBED_HIDDEN_SIZE)(question)
<add>encoded_question = layers.Dropout(0.3)(encoded_question)
<add>encoded_question = RNN(EMBED_HIDDEN_SIZE)(encoded_question)
<add>encoded_question = layers.RepeatVector(story_maxlen)(encoded_question)
<ide>
<del>model = Sequential()
<del>model.add(Merge([sentrnn, qrnn], mode='sum'))
<del>model.add(RNN(EMBED_HIDDEN_SIZE, return_sequences=False))
<del>model.add(Dropout(0.3))
<del>model.add(Dense(vocab_size, activation='softmax'))
<add>merged = layers.sum([encoded_sentence, encoded_question])
<add>merged = RNN(EMBED_HIDDEN_SIZE)(merged)
<add>merged = layers.Dropout(0.3)(merged)
<add>preds = layers.Dense(vocab_size, activation='softmax')(merged)
<ide>
<add>model = Model([sentence, question], preds)
<ide> model.compile(optimizer='adam',
<ide> loss='categorical_crossentropy',
<ide> metrics=['accuracy'])
<ide>
<ide> print('Training')
<del>model.fit([X, Xq], Y, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_split=0.05)
<del>loss, acc = model.evaluate([tX, tXq], tY, batch_size=BATCH_SIZE)
<add>model.fit([x, xq], y, batch_size=BATCH_SIZE, epochs=EPOCHS, validation_split=0.05)
<add>loss, acc = model.evaluate([tx, txq], ty, batch_size=BATCH_SIZE)
<ide> print('Test loss / test accuracy = {:.4f} / {:.4f}'.format(loss, acc))
<ide><path>examples/cifar10_cnn.py
<ide> '''Train a simple deep CNN on the CIFAR10 small images dataset.
<ide>
<ide> GPU run command with Theano backend (with TensorFlow, the GPU is automatically used):
<del> THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10_cnn.py
<add> THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatx=float32 python cifar10_cnn.py
<ide>
<ide> It gets down to 0.65 test logloss in 25 epochs, and down to 0.55 after 50 epochs.
<ide> (it's still underfitting at that point, though).
<ide> from keras.preprocessing.image import ImageDataGenerator
<ide> from keras.models import Sequential
<ide> from keras.layers import Dense, Dropout, Activation, Flatten
<del>from keras.layers import Convolution2D, MaxPooling2D
<add>from keras.layers import Conv2D, MaxPooling2D
<ide> from keras.utils import np_utils
<ide>
<ide> batch_size = 32
<ide> img_channels = 3
<ide>
<ide> # The data, shuffled and split between train and test sets:
<del>(X_train, y_train), (X_test, y_test) = cifar10.load_data()
<del>print('X_train shape:', X_train.shape)
<del>print(X_train.shape[0], 'train samples')
<del>print(X_test.shape[0], 'test samples')
<add>(x_train, y_train), (x_test, y_test) = cifar10.load_data()
<add>print('x_train shape:', x_train.shape)
<add>print(x_train.shape[0], 'train samples')
<add>print(x_test.shape[0], 'test samples')
<ide>
<ide> # Convert class vectors to binary class matrices.
<del>Y_train = np_utils.to_categorical(y_train, num_classes)
<del>Y_test = np_utils.to_categorical(y_test, num_classes)
<add>y_train = np_utils.to_categorical(y_train, num_classes)
<add>y_test = np_utils.to_categorical(y_test, num_classes)
<ide>
<ide> model = Sequential()
<ide>
<del>model.add(Convolution2D(32, 3, 3, border_mode='same',
<del> input_shape=X_train.shape[1:]))
<add>model.add(Conv2D(32, (3, 3), padding='same',
<add> input_shape=x_train.shape[1:]))
<ide> model.add(Activation('relu'))
<del>model.add(Convolution2D(32, 3, 3))
<add>model.add(Conv2D(32, (3, 3)))
<ide> model.add(Activation('relu'))
<ide> model.add(MaxPooling2D(pool_size=(2, 2)))
<ide> model.add(Dropout(0.25))
<ide>
<del>model.add(Convolution2D(64, 3, 3, border_mode='same'))
<add>model.add(Conv2D(64, (3, 3), padding='same'))
<ide> model.add(Activation('relu'))
<del>model.add(Convolution2D(64, 3, 3))
<add>model.add(Conv2D(64, (3, 3)))
<ide> model.add(Activation('relu'))
<ide> model.add(MaxPooling2D(pool_size=(2, 2)))
<ide> model.add(Dropout(0.25))
<ide> optimizer='rmsprop',
<ide> metrics=['accuracy'])
<ide>
<del>X_train = X_train.astype('float32')
<del>X_test = X_test.astype('float32')
<del>X_train /= 255
<del>X_test /= 255
<add>x_train = x_train.astype('float32')
<add>x_test = x_test.astype('float32')
<add>x_train /= 255
<add>x_test /= 255
<ide>
<ide> if not data_augmentation:
<ide> print('Not using data augmentation.')
<del> model.fit(X_train, Y_train,
<add> model.fit(x_train, y_train,
<ide> batch_size=batch_size,
<ide> epochs=epochs,
<del> validation_data=(X_test, Y_test),
<add> validation_data=(x_test, y_test),
<ide> shuffle=True)
<ide> else:
<ide> print('Using real-time data augmentation.')
<ide>
<ide> # Compute quantities required for featurewise normalization
<ide> # (std, mean, and principal components if ZCA whitening is applied).
<del> datagen.fit(X_train)
<add> datagen.fit(x_train)
<ide>
<ide> # Fit the model on the batches generated by datagen.flow().
<del> model.fit_generator(datagen.flow(X_train, Y_train,
<add> model.fit_generator(datagen.flow(x_train, y_train,
<ide> batch_size=batch_size),
<del> samples_per_epoch=X_train.shape[0],
<add> samples_per_epoch=x_train.shape[0],
<ide> epochs=epochs,
<del> validation_data=(X_test, Y_test))
<add> validation_data=(x_test, y_test))
<ide><path>examples/conv_lstm.py
<ide> generated movie which contains moving squares.
<ide> """
<ide> from keras.models import Sequential
<del>from keras.layers.convolutional import Convolution3D
<add>from keras.layers.convolutional import Conv3D
<ide> from keras.layers.convolutional_recurrent import ConvLSTM2D
<ide> from keras.layers.normalization import BatchNormalization
<ide> import numpy as np
<ide> # of identical shape.
<ide>
<ide> seq = Sequential()
<del>seq.add(ConvLSTM2D(filters=40, num_row=3, num_col=3,
<add>seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
<ide> input_shape=(None, 40, 40, 1),
<del> border_mode='same', return_sequences=True))
<add> padding='same', return_sequences=True))
<ide> seq.add(BatchNormalization())
<ide>
<del>seq.add(ConvLSTM2D(filters=40, num_row=3, num_col=3,
<del> border_mode='same', return_sequences=True))
<add>seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
<add> padding='same', return_sequences=True))
<ide> seq.add(BatchNormalization())
<ide>
<del>seq.add(ConvLSTM2D(filters=40, num_row=3, num_col=3,
<del> border_mode='same', return_sequences=True))
<add>seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
<add> padding='same', return_sequences=True))
<ide> seq.add(BatchNormalization())
<ide>
<del>seq.add(ConvLSTM2D(filters=40, num_row=3, num_col=3,
<del> border_mode='same', return_sequences=True))
<add>seq.add(ConvLSTM2D(filters=40, kernel_size=(3, 3),
<add> padding='same', return_sequences=True))
<ide> seq.add(BatchNormalization())
<ide>
<del>seq.add(Convolution3D(filters=1, kernel_dim1=1, kernel_dim2=3,
<del> kernel_dim3=3, activation='sigmoid',
<del> border_mode='same', data_format='channels_last'))
<del>
<add>seq.add(Conv3D(filters=1, kernel_size=(3, 3, 3),
<add> activation='sigmoid',
<add> padding='same', data_format='channels_last'))
<ide> seq.compile(loss='binary_crossentropy', optimizer='adadelta')
<ide>
<ide>
<ide><path>examples/imdb_lstm.py
<ide> '''
<ide> from __future__ import print_function
<ide> import numpy as np
<del>np.random.seed(1337) # for reproducibility
<ide>
<ide> from keras.preprocessing import sequence
<ide> from keras.models import Sequential
<ide>
<ide> print('Build model...')
<ide> model = Sequential()
<del>model.add(Embedding(max_features, 128, dropout=0.2))
<del>model.add(LSTM(128, dropout_W=0.2, dropout_U=0.2)) # try using a GRU instead, for fun
<del>model.add(Dense(1))
<del>model.add(Activation('sigmoid'))
<add>model.add(Embedding(max_features, 128))
<add>model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))
<add>model.add(Dense(1, activation='sigmoid'))
<ide>
<ide> # try using different optimizers and different optimizer configs
<ide> model.compile(loss='binary_crossentropy',
<ide><path>keras/preprocessing/sequence.py
<ide> def pad_sequences(sequences, maxlen=None, dtype='int32',
<ide> ValueError: in case of invalid values for `truncating` or `padding`,
<ide> or in case of invalid shape for a `sequences` entry.
<ide> """
<del> lengths = [len(s) for s in sequences]
<add> if not hasattr(sequences, '__len__'):
<add> raise ValueError('`sequences` must be iterable.')
<add> lengths = []
<add> for x in sequences:
<add> if not hasattr(x, '__len__'):
<add> raise ValueError('`sequences` must be a list of iterables. '
<add> 'Found non-iterable: ' + str(x))
<add> lengths.append(len(x))
<ide>
<ide> num_samples = len(sequences)
<ide> if maxlen is None: | 7 |
Go | Go | move network settings into separate file | f00ca72baa6c43de35d622caa728587a752d6e5e | <ide><path>runtime/container.go
<ide> type Container struct {
<ide> activeLinks map[string]*links.Link
<ide> }
<ide>
<del>// FIXME: move deprecated port stuff to nat to clean up the core.
<del>type PortMapping map[string]string // Deprecated
<del>
<del>type NetworkSettings struct {
<del> IPAddress string
<del> IPPrefixLen int
<del> Gateway string
<del> Bridge string
<del> PortMapping map[string]PortMapping // Deprecated
<del> Ports nat.PortMap
<del>}
<del>
<del>func (settings *NetworkSettings) PortMappingAPI() *engine.Table {
<del> var outs = engine.NewTable("", 0)
<del> for port, bindings := range settings.Ports {
<del> p, _ := nat.ParsePort(port.Port())
<del> if len(bindings) == 0 {
<del> out := &engine.Env{}
<del> out.SetInt("PublicPort", p)
<del> out.Set("Type", port.Proto())
<del> outs.Add(out)
<del> continue
<del> }
<del> for _, binding := range bindings {
<del> out := &engine.Env{}
<del> h, _ := nat.ParsePort(binding.HostPort)
<del> out.SetInt("PrivatePort", p)
<del> out.SetInt("PublicPort", h)
<del> out.Set("Type", port.Proto())
<del> out.Set("IP", binding.HostIp)
<del> outs.Add(out)
<del> }
<del> }
<del> return outs
<del>}
<del>
<ide> // Inject the io.Reader at the given path. Note: do not close the reader
<ide> func (container *Container) Inject(file io.Reader, pth string) error {
<ide> if err := container.Mount(); err != nil {
<ide><path>runtime/network_settings.go
<add>package runtime
<add>
<add>import (
<add> "github.com/dotcloud/docker/engine"
<add> "github.com/dotcloud/docker/nat"
<add>)
<add>
<add>// FIXME: move deprecated port stuff to nat to clean up the core.
<add>type PortMapping map[string]string // Deprecated
<add>
<add>type NetworkSettings struct {
<add> IPAddress string
<add> IPPrefixLen int
<add> Gateway string
<add> Bridge string
<add> PortMapping map[string]PortMapping // Deprecated
<add> Ports nat.PortMap
<add>}
<add>
<add>func (settings *NetworkSettings) PortMappingAPI() *engine.Table {
<add> var outs = engine.NewTable("", 0)
<add> for port, bindings := range settings.Ports {
<add> p, _ := nat.ParsePort(port.Port())
<add> if len(bindings) == 0 {
<add> out := &engine.Env{}
<add> out.SetInt("PublicPort", p)
<add> out.Set("Type", port.Proto())
<add> outs.Add(out)
<add> continue
<add> }
<add> for _, binding := range bindings {
<add> out := &engine.Env{}
<add> h, _ := nat.ParsePort(binding.HostPort)
<add> out.SetInt("PrivatePort", p)
<add> out.SetInt("PublicPort", h)
<add> out.Set("Type", port.Proto())
<add> out.Set("IP", binding.HostIp)
<add> outs.Add(out)
<add> }
<add> }
<add> return outs
<add>} | 2 |
PHP | PHP | remove unneeded test | 80cc5fd606afc2afd3d89f6e1636c5fc2e0dd296 | <ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testQuickPaginateCorrectlyCreatesPaginatorInstance()
<ide> }
<ide>
<ide>
<del> public function testGetPaginationCountGetsResultCountWithSelectDistinct()
<del> {
<del> unset($_SERVER['orders']);
<del> $builder = $this->getBuilder();
<del> $builder->getConnection()->shouldReceive('select')->once()->with('select count(distinct "foo", "bar") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1)));
<del> $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function($query, $results)
<del> {
<del> $_SERVER['orders'] = $query->orders;
<del> return $results;
<del> });
<del> $results = $builder->distinct()->select('foo', 'bar')->from('users')->orderBy('foo', 'desc')->getPaginationCount();
<del>
<del> $this->assertNull($_SERVER['orders']);
<del> unset($_SERVER['orders']);
<del>
<del> $this->assertEquals(array('foo', 'bar'), $builder->columns);
<del> $this->assertEquals(array(0 => array('column' => 'foo', 'direction' => 'desc')), $builder->orders);
<del> $this->assertEquals(1, $results);
<del> }
<del>
<del>
<ide> public function testPluckMethodReturnsSingleColumn()
<ide> {
<ide> $builder = $this->getBuilder(); | 1 |
Go | Go | unify the defer syntax | 6a3d1e3e3e076724a92ffd589b66010afbce8c58 | <ide><path>client/container_inspect.go
<ide> func (cli *Client) ContainerInspect(ctx context.Context, containerID string) (ty
<ide> if err != nil {
<ide> return types.ContainerJSON{}, wrapResponseError(err, serverResp, "container", containerID)
<ide> }
<add> defer ensureReaderClosed(serverResp)
<ide>
<ide> var response types.ContainerJSON
<ide> err = json.NewDecoder(serverResp.body).Decode(&response)
<del> ensureReaderClosed(serverResp)
<ide> return response, err
<ide> }
<ide> | 1 |
Python | Python | add support for digitalocean spaces sgp1 region | d649a2be5b3f28d5921f5e8a826d20edd3e6b45e | <ide><path>libcloud/storage/drivers/digitalocean_spaces.py
<ide> ]
<ide>
<ide> DO_SPACES_HOSTS_BY_REGION = {'nyc3': 'nyc3.digitaloceanspaces.com',
<del> 'ams3': 'ams3.digitaloceanspaces.com'}
<add> 'ams3': 'ams3.digitaloceanspaces.com',
<add> 'sgp1': 'sgp1.digitaloceanspaces.com'}
<ide> DO_SPACES_DEFAULT_REGION = 'nyc3'
<ide> DEFAULT_SIGNATURE_VERSION = '2'
<ide> S3_API_VERSION = '2006-03-01' | 1 |
Ruby | Ruby | remove unused blue color | 153e16ac770f865853dd8379f4053d7a21b67d74 | <ide><path>railties/lib/rails/test_unit/reporter.rb
<ide> class TestUnitReporter < Minitest::StatisticsReporter
<ide> COLOR_CODES = {
<ide> red: 31,
<ide> green: 32,
<del> yellow: 33,
<del> blue: 34
<add> yellow: 33
<ide> }
<ide>
<ide> def record(result) | 1 |
PHP | PHP | add a shell commend to list loaded plugins | 9ec101c759bbf3a1a60d0d93c8661b42ddc99426 | <ide><path>src/Shell/PluginShell.php
<ide> namespace Cake\Shell;
<ide>
<ide> use Cake\Console\Shell;
<add>use Cake\Core\Plugin;
<ide>
<ide> /**
<ide> * Shell for tasks related to plugins.
<ide> class PluginShell extends Shell
<ide> 'Unload',
<ide> ];
<ide>
<add> /**
<add> * @return void
<add> */
<add> public function loaded() {
<add> $loaded = Plugin::loaded();
<add> $this->out($loaded);
<add> }
<add>
<ide> /**
<ide> * Gets the option parser instance and configures it.
<ide> *
<ide> public function getOptionParser()
<ide> ->addSubcommand('assets', [
<ide> 'help' => 'Symlink / copy plugin assets to app\'s webroot',
<ide> 'parser' => $this->Assets->getOptionParser()
<del> ])->addSubcommand('load', [
<add> ])
<add> ->addSubcommand('loaded', [
<add> 'help' => 'Lists all loaded plugins',
<add> 'parser' => $parser,
<add> ])
<add> ->addSubcommand('load', [
<ide> 'help' => 'Loads a plugin',
<ide> 'parser' => $this->Load->getOptionParser(),
<ide> ]) | 1 |
Javascript | Javascript | remove some duplicate conditions | 4d12812bb4b8ffd04e6587f075b5c5036b612ac6 | <ide><path>test/e2e/tools/fixture.js
<ide> function generateFixture(test, query) {
<ide> }
<ide> });
<ide>
<del> if (jquery && (!('jquery' in query) || (/^(0|no|false|off|n)$/i).test(query.jquery))) {
<del> $(jquery).remove();
<del> } else if ('jquery' in query) {
<del> if ((/^(0|no|false|off|n)$/i).test(query.jquery)) {
<del> if (jquery) {
<del> $(jquery).remove();
<del> }
<del> } else {
<del> if (!jquery) {
<del> jquery = $.load('<script></script>')('script')[0];
<del> if (firstScript) {
<del> $(firstScript).before(jquery);
<add> if (!('jquery' in query) || (/^(0|no|false|off|n)$/i).test(query.jquery)) {
<add> if (jquery) {
<add> $(jquery).remove();
<add> }
<add> } else {
<add> if (!jquery) {
<add> jquery = $.load('<script></script>')('script')[0];
<add> if (firstScript) {
<add> $(firstScript).before(jquery);
<add> } else {
<add> var head = $$('head');
<add> if (head.length) {
<add> head.prepend(jquery);
<ide> } else {
<del> var head = $$('head');
<del> if (head.length) {
<del> head.prepend(jquery);
<del> } else {
<del> $$.root().first().before(jquery);
<del> }
<add> $$.root().first().before(jquery);
<ide> }
<ide> }
<del> if (!/^\d+\.\d+.*$/.test(query.jquery)) {
<del> $(jquery).attr('src', '/bower_components/jquery/dist/jquery.js');
<del> } else {
<del> $(jquery).attr('src', '//ajax.googleapis.com/ajax/libs/jquery/' + query.jquery + '/jquery.js');
<del> }
<add> }
<add> if (!/^\d+\.\d+.*$/.test(query.jquery)) {
<add> $(jquery).attr('src', '/bower_components/jquery/dist/jquery.js');
<add> } else {
<add> $(jquery).attr('src', '//ajax.googleapis.com/ajax/libs/jquery/' + query.jquery + '/jquery.js');
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | add additional test coverage to shelltask | 2c44702ef2ff62106cc027129fb35f90604550f8 | <ide><path>tests/TestCase/Console/Command/Task/SimpleBakeTaskTest.php
<ide> public function subclassProvider() {
<ide> ['Cake\Console\Command\Task\BehaviorTask'],
<ide> ['Cake\Console\Command\Task\ComponentTask'],
<ide> ['Cake\Console\Command\Task\HelperTask'],
<add> ['Cake\Console\Command\Task\ShellTask'],
<ide> ];
<ide> }
<ide> | 1 |
Java | Java | expose jsresponderhandler api in fabric uimanager | 470ace0932bab425348304928a83a9b92ccb7cf2 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/UIManager.java
<ide> <T extends View> int addRootView(
<ide> */
<ide> void dispatchCommand(int reactTag, String commandId, @Nullable ReadableArray commandArgs);
<ide>
<del> void setJSResponder(int reactTag, boolean blockNativeResponder);
<del>
<del> void clearJSResponder();
<del>
<ide> /**
<ide> * Used by native animated module to bypass the process of updating the values through the shadow
<ide> * view hierarchy. This method will directly update native views, which means that updates for
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
<ide> public void dispatchCommand(
<ide> }
<ide> }
<ide>
<del> @Override
<del> public void setJSResponder(int reactTag, boolean blockNativeResponder) {
<add> /**
<add> * Set the JS responder for the view associated with the tags received as a parameter.
<add> *
<add> * @param reactTag React tag of the first parent of the view that is NOT virtual
<add> * @param initialReactTag React tag of the JS view that initiated the touch operation
<add> * @param blockNativeResponder If native responder should be blocked or not
<add> */
<add> @DoNotStrip
<add> public void setJSResponder(
<add> final int reactTag, final int initialReactTag, final boolean blockNativeResponder) {
<ide> // do nothing for now.
<ide> }
<ide>
<del> @Override
<ide> public void clearJSResponder() {
<ide> // do nothing for now.
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java
<ide> public void viewIsDescendantOf(
<ide> mUIImplementation.viewIsDescendantOf(reactTag, ancestorReactTag, callback);
<ide> }
<ide>
<del> @Override
<ide> @ReactMethod
<ide> public void setJSResponder(int reactTag, boolean blockNativeResponder) {
<ide> mUIImplementation.setJSResponder(reactTag, blockNativeResponder);
<ide> }
<ide>
<del> @Override
<ide> @ReactMethod
<ide> public void clearJSResponder() {
<ide> mUIImplementation.clearJSResponder(); | 3 |
Javascript | Javascript | fix modal actions | a73ba4b3af65ff392a05fe09f656a91b51401c4d | <ide><path>airflow/www/static/js/dag.js
<ide> export function callModal(t, d, extraLinks, tryNumbers, sd) {
<ide> export function callModalDag(dag) {
<ide> $('#dagModal').modal({});
<ide> $('#dagModal').css('margin-top', '0');
<add> executionDate = dag.execution_date;
<ide> updateButtonUrl(buttons.dag_graph_view, {
<del> dag_id: dag && dag.execution_date,
<del> execution_date: dag && dag.dag_id,
<add> dag_id: dag && dag.dag_id,
<add> execution_date: dag && dag.execution_date,
<ide> });
<ide> }
<ide>
<ide> // Task Instance Modal actions
<ide> $('form[data-action]').on('submit', function submit(e) {
<ide> e.preventDefault();
<ide> const form = $(this).get(0);
<del> form.execution_date.value = executionDate;
<del> form.origin.value = window.location;
<del> if (form.task_id) {
<del> form.task_id.value = taskId;
<add> // Somehow submit is fired twice. Only once is the executionDate valid
<add> if (executionDate) {
<add> form.execution_date.value = executionDate;
<add> form.origin.value = window.location;
<add> if (form.task_id) {
<add> form.task_id.value = taskId;
<add> }
<add> form.action = $(this).data('action');
<add> form.submit();
<ide> }
<del> form.action = $(this).data('action');
<del> form.submit();
<ide> });
<ide>
<ide> // DAG Modal actions
<ide> $('form button[data-action]').on('click', function onClick() {
<ide> const form = $(this).closest('form').get(0);
<del> form.execution_date.value = executionDate;
<del> form.origin.value = window.location;
<del> if (form.task_id) {
<del> form.task_id.value = taskId;
<add> // Somehow submit is fired twice. Only once is the executionDate valid
<add> if (executionDate) {
<add> form.execution_date.value = executionDate;
<add> form.origin.value = window.location;
<add> if (form.task_id) {
<add> form.task_id.value = taskId;
<add> }
<add> form.action = $(this).data('action');
<add> form.submit();
<ide> }
<del> form.action = $(this).data('action');
<del> form.submit();
<ide> });
<ide>
<ide> $('#pause_resume').on('change', function onChange() { | 1 |
Python | Python | unflake optimizer test | 3bf913dc35596015c736e56458042be65859e682 | <ide><path>tests/keras/test_optimizers.py
<ide> from __future__ import print_function
<ide> import pytest
<add>import numpy as np
<add>np.random.seed(1337)
<ide>
<ide> from keras.utils.test_utils import get_test_data
<ide> from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam | 1 |
Ruby | Ruby | allow symbols as name | 4d0780e9c796aab7c70dc138fea4374eb73b16cf | <ide><path>actionpack/lib/action_view/helpers/form_tag_helper.rb
<ide> def check_box_tag(name, value = "1", checked = false, options = {})
<ide> # # => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" />
<ide> def radio_button_tag(name, value, checked = false, options = {})
<ide> pretty_tag_value = value.to_s.gsub(/\s/, "_").gsub(/(?!-)\W/, "").downcase
<del> pretty_name = name.gsub(/\[/, "_").gsub(/\]/, "")
<add> pretty_name = name.to_s.gsub(/\[/, "_").gsub(/\]/, "")
<ide> html_options = { "type" => "radio", "name" => name, "id" => "#{pretty_name}_#{pretty_tag_value}", "value" => value }.update(options.stringify_keys)
<ide> html_options["checked"] = "checked" if checked
<ide> tag :input, html_options | 1 |
Python | Python | fix mypy errors at bfs_zero_one_shortest_path | 86baec0bc9d790e2be6f49492e2e4f0f788060af | <ide><path>graphs/bfs_zero_one_shortest_path.py
<ide> from collections import deque
<add>from collections.abc import Iterator
<ide> from dataclasses import dataclass
<del>from typing import Iterator, List
<add>from typing import Optional, Union
<ide>
<ide> """
<ide> Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra.
<ide> class AdjacencyList:
<ide> """Graph adjacency list."""
<ide>
<ide> def __init__(self, size: int):
<del> self._graph: List[List[Edge]] = [[] for _ in range(size)]
<add> self._graph: list[list[Edge]] = [[] for _ in range(size)]
<ide> self._size = size
<ide>
<ide> def __getitem__(self, vertex: int) -> Iterator[Edge]:
<ide> def add_edge(self, from_vertex: int, to_vertex: int, weight: int):
<ide>
<ide> self._graph[from_vertex].append(Edge(to_vertex, weight))
<ide>
<del> def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int:
<add> def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> Optional[int]:
<ide> """
<ide> Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
<ide> 1 1 1
<ide> def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int:
<ide> ValueError: No path from start_vertex to finish_vertex.
<ide> """
<ide> queue = deque([start_vertex])
<del> distances = [None for i in range(self.size)]
<add> distances: list[Union[int, None]] = [None] * self.size
<ide> distances[start_vertex] = 0
<ide>
<ide> while queue:
<ide> current_vertex = queue.popleft()
<ide> current_distance = distances[current_vertex]
<add> if current_distance is None:
<add> continue
<ide>
<ide> for edge in self[current_vertex]:
<ide> new_distance = current_distance + edge.weight
<add> dest_vertex_distance = distances[edge.destination_vertex]
<ide> if (
<del> distances[edge.destination_vertex] is not None
<del> and new_distance >= distances[edge.destination_vertex]
<add> isinstance(dest_vertex_distance, int)
<add> and new_distance >= dest_vertex_distance
<ide> ):
<ide> continue
<ide> distances[edge.destination_vertex] = new_distance | 1 |
Python | Python | update save_model function | d03a41b4262e6aab8ad56cd8395808cacf5921e3 | <ide><path>keras/models.py
<ide> def get_json_type(obj):
<ide> if not proceed:
<ide> return
<ide>
<del> f = h5py.File(filepath, 'w')
<del> f.attrs['keras_version'] = str(keras_version).encode('utf8')
<del> f.attrs['backend'] = K.backend().encode('utf8')
<del> f.attrs['model_config'] = json.dumps({
<del> 'class_name': model.__class__.__name__,
<del> 'config': model.get_config()
<del> }, default=get_json_type).encode('utf8')
<del>
<del> model_weights_group = f.create_group('model_weights')
<del> if legacy_models.needs_legacy_support(model):
<del> model_layers = legacy_models.legacy_sequential_layers(model)
<del> else:
<del> model_layers = model.layers
<del> topology.save_weights_to_hdf5_group(model_weights_group, model_layers)
<del>
<del> if include_optimizer and hasattr(model, 'optimizer'):
<del> if isinstance(model.optimizer, optimizers.TFOptimizer):
<del> warnings.warn(
<del> 'TensorFlow optimizers do not '
<del> 'make it possible to access '
<del> 'optimizer attributes or optimizer state '
<del> 'after instantiation. '
<del> 'As a result, we cannot save the optimizer '
<del> 'as part of the model save file.'
<del> 'You will have to compile your model again after loading it. '
<del> 'Prefer using a Keras optimizer instead '
<del> '(see keras.io/optimizers).')
<add> with h5py.File(filepath, mode='w') as f:
<add> f.attrs['keras_version'] = str(keras_version).encode('utf8')
<add> f.attrs['backend'] = K.backend().encode('utf8')
<add> f.attrs['model_config'] = json.dumps({
<add> 'class_name': model.__class__.__name__,
<add> 'config': model.get_config()
<add> }, default=get_json_type).encode('utf8')
<add>
<add> model_weights_group = f.create_group('model_weights')
<add> if legacy_models.needs_legacy_support(model):
<add> model_layers = legacy_models.legacy_sequential_layers(model)
<ide> else:
<del> f.attrs['training_config'] = json.dumps({
<del> 'optimizer_config': {
<del> 'class_name': model.optimizer.__class__.__name__,
<del> 'config': model.optimizer.get_config()
<del> },
<del> 'loss': model.loss,
<del> 'metrics': model.metrics,
<del> 'sample_weight_mode': model.sample_weight_mode,
<del> 'loss_weights': model.loss_weights,
<del> }, default=get_json_type).encode('utf8')
<del>
<del> # Save optimizer weights.
<del> symbolic_weights = getattr(model.optimizer, 'weights')
<del> if symbolic_weights:
<del> optimizer_weights_group = f.create_group('optimizer_weights')
<del> weight_values = K.batch_get_value(symbolic_weights)
<del> weight_names = []
<del> for i, (w, val) in enumerate(zip(symbolic_weights, weight_values)):
<del> # Default values of symbolic_weights is /variable for theano and cntk
<del> if K.backend() == 'theano' or K.backend() == 'cntk':
<del> if hasattr(w, 'name') and w.name != "/variable":
<del> name = str(w.name)
<add> model_layers = model.layers
<add> topology.save_weights_to_hdf5_group(model_weights_group, model_layers)
<add>
<add> if include_optimizer and hasattr(model, 'optimizer'):
<add> if isinstance(model.optimizer, optimizers.TFOptimizer):
<add> warnings.warn(
<add> 'TensorFlow optimizers do not '
<add> 'make it possible to access '
<add> 'optimizer attributes or optimizer state '
<add> 'after instantiation. '
<add> 'As a result, we cannot save the optimizer '
<add> 'as part of the model save file.'
<add> 'You will have to compile your model again '
<add> 'after loading it. '
<add> 'Prefer using a Keras optimizer instead '
<add> '(see keras.io/optimizers).')
<add> else:
<add> f.attrs['training_config'] = json.dumps({
<add> 'optimizer_config': {
<add> 'class_name': model.optimizer.__class__.__name__,
<add> 'config': model.optimizer.get_config()
<add> },
<add> 'loss': model.loss,
<add> 'metrics': model.metrics,
<add> 'sample_weight_mode': model.sample_weight_mode,
<add> 'loss_weights': model.loss_weights,
<add> }, default=get_json_type).encode('utf8')
<add>
<add> # Save optimizer weights.
<add> symbolic_weights = getattr(model.optimizer, 'weights')
<add> if symbolic_weights:
<add> optimizer_weights_group = f.create_group('optimizer_weights')
<add> weight_values = K.batch_get_value(symbolic_weights)
<add> weight_names = []
<add> for i, (w, val) in enumerate(zip(symbolic_weights,
<add> weight_values)):
<add> # Default values of symbolic_weights is /variable
<add> # for theano and cntk
<add> if K.backend() == 'theano' or K.backend() == 'cntk':
<add> if hasattr(w, 'name') and w.name != "/variable":
<add> name = str(w.name)
<add> else:
<add> name = 'param_' + str(i)
<ide> else:
<del> name = 'param_' + str(i)
<del> else:
<del> if hasattr(w, 'name') and w.name:
<del> name = str(w.name)
<add> if hasattr(w, 'name') and w.name:
<add> name = str(w.name)
<add> else:
<add> name = 'param_' + str(i)
<add> weight_names.append(name.encode('utf8'))
<add> optimizer_weights_group.attrs['weight_names'] = weight_names
<add> for name, val in zip(weight_names, weight_values):
<add> param_dset = optimizer_weights_group.create_dataset(
<add> name,
<add> val.shape,
<add> dtype=val.dtype)
<add> if not val.shape:
<add> # scalar
<add> param_dset[()] = val
<ide> else:
<del> name = 'param_' + str(i)
<del> weight_names.append(name.encode('utf8'))
<del> optimizer_weights_group.attrs['weight_names'] = weight_names
<del> for name, val in zip(weight_names, weight_values):
<del> param_dset = optimizer_weights_group.create_dataset(
<del> name,
<del> val.shape,
<del> dtype=val.dtype)
<del> if not val.shape:
<del> # scalar
<del> param_dset[()] = val
<del> else:
<del> param_dset[:] = val
<del> f.flush()
<del> f.close()
<add> param_dset[:] = val
<add> f.flush()
<ide>
<ide>
<ide> def load_model(filepath, custom_objects=None, compile=True): | 1 |
Python | Python | add tests for "_get_standard_range_str" method | 6b92599eb92d813860f96f7ca43e69b8e577e99d | <ide><path>libcloud/test/storage/test_base.py
<ide> def test_upload_object_via_stream_illegal_seek_errors_are_ignored(self):
<ide> request_path='/',
<ide> stream=iterator)
<ide>
<add> def test_get_standard_range_str(self):
<add> result = self.driver1._get_standard_range_str(0, 5)
<add> self.assertEqual(result, 'bytes=0-5')
<add>
<add> result = self.driver1._get_standard_range_str(0)
<add> self.assertEqual(result, 'bytes=0-')
<add> result = self.driver1._get_standard_range_str(0, 0)
<add>
<add> self.assertEqual(result, 'bytes=0-0')
<add>
<add> result = self.driver1._get_standard_range_str(200)
<add> self.assertEqual(result, 'bytes=200-')
<add>
<add> result = self.driver1._get_standard_range_str(10, 200)
<add> self.assertEqual(result, 'bytes=10-200')
<add>
<add> result = self.driver1._get_standard_range_str(10, 11)
<add> self.assertEqual(result, 'bytes=10-11')
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> sys.exit(unittest.main()) | 1 |
PHP | PHP | replace is_a with instanceof | 88604ac757198dbb2db55bd69e91060904c7b442 | <ide><path>lib/Cake/View/Helper/JsHelper.php
<ide> public function __call($method, $params) {
<ide> $this->buffer($out);
<ide> return null;
<ide> }
<del> if (is_object($out) && is_a($out, 'JsBaseEngineHelper')) {
<add> if (is_object($out) && $out instanceof JsBaseEngineHelper) {
<ide> return $this;
<ide> }
<ide> return $out; | 1 |
Ruby | Ruby | remove argv usage | 25009f94e72ee69e982e832c15e8a8e27893d999 | <ide><path>Library/Homebrew/cmd/list.rb
<ide> def filtered_list(args:)
<ide>
<ide> def list_casks(args:)
<ide> cask_list = Cask::Cmd::List.new args.named
<del> cask_list.one = ARGV.include? "-1"
<add> cask_list.one = args.public_send(:'1?')
<ide> cask_list.versions = args.versions?
<ide> cask_list.full_name = args.full_name?
<ide> cask_list.run | 1 |
Text | Text | fix notable changes for v13.9.0 | 31290824de068eb4b282ab74829450b988ae225b | <ide><path>doc/changelogs/CHANGELOG_V13.md
<ide>
<ide> ### Notable changes
<ide>
<del>* [[`6be51296e4`](https://github.com/nodejs/node/commit/6be51296e4)] - **(SEMVER-MINOR)** **async_hooks**: add executionAsyncResource (Matteo Collina) [#30959](https://github.com/nodejs/node/pull/30959)
<del>* [[`15b24b71ce`](https://github.com/nodejs/node/commit/15b24b71ce)] - **doc**: add ronag to collaborators (Robert Nagy) [#31498](https://github.com/nodejs/node/pull/31498)
<del>* [[`1bcf2f9423`](https://github.com/nodejs/node/commit/1bcf2f9423)] - **report**: add support for Workers (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386)
<del>* [[`676b84a803`](https://github.com/nodejs/node/commit/676b84a803)] - **(SEMVER-MINOR)** **test**: skip keygen tests on arm systems (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<del>* [[`bf46c304dd`](https://github.com/nodejs/node/commit/bf46c304dd)] - **(SEMVER-MINOR)** **crypto**: add crypto.diffieHellman (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<del>* [[`0d3e095941`](https://github.com/nodejs/node/commit/0d3e095941)] - **(SEMVER-MINOR)** **crypto**: add DH support to generateKeyPair (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<del>* [[`15bd2c9f0c`](https://github.com/nodejs/node/commit/15bd2c9f0c)] - **(SEMVER-MINOR)** **crypto**: simplify DH groups (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<del>* [[`572322fddf`](https://github.com/nodejs/node/commit/572322fddf)] - **(SEMVER-MINOR)** **crypto**: add key type 'dh' (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<add>* **async_hooks**
<add> * add executionAsyncResource (Matteo Collina) [#30959](https://github.com/nodejs/node/pull/30959)
<add>* **crypto**
<add> * add crypto.diffieHellman (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<add> * add DH support to generateKeyPair (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<add> * simplify DH groups (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<add> * add key type 'dh' (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<add>* **test**
<add> * skip keygen tests on arm systems (Tobias Nießen) [#31178](https://github.com/nodejs/node/pull/31178)
<add>* **perf_hooks**
<add> * add property flags to GCPerformanceEntry (Kirill Fomichev) [#29547](https://github.com/nodejs/node/pull/29547)
<add>* **process**
<add> * report ArrayBuffer memory in `memoryUsage()` (Anna Henningsen) [#31550](https://github.com/nodejs/node/pull/31550)
<add>* **readline**
<add> * make tab size configurable (Ruben Bridgewater) [#31318](https://github.com/nodejs/node/pull/31318)
<add>* **report**
<add> * add support for Workers (Anna Henningsen) [#31386](https://github.com/nodejs/node/pull/31386)
<add>* **worker**
<add> * add ability to take heap snapshot from parent thread (Anna Henningsen) [#31569](https://github.com/nodejs/node/pull/31569)
<add>* **added new collaborators**
<add> * add ronag to collaborators (Robert Nagy) [#31498](https://github.com/nodejs/node/pull/31498)
<ide>
<ide> ### Commits
<ide> | 1 |
Text | Text | correct config.host_authorization reference | ef291097fce773744f297599304373adabcb13fa | <ide><path>guides/source/configuring.md
<ide> Rails.application.config.hosts << ".product.com"
<ide> ```
<ide>
<ide> You can exclude certain requests from Host Authorization checks by setting
<del>`config.host_configuration.exclude`:
<add>`config.host_authorization.exclude`:
<ide>
<ide> ```ruby
<ide> # Exclude requests for the /healthcheck/ path from host checking
<del>Rails.application.config.host_configuration = {
<add>Rails.application.config.host_authorization = {
<ide> exclude: ->(request) { request.path =~ /healthcheck/ }
<ide> }
<ide> ```
<ide>
<ide> When a request comes to an unauthorized host, a default Rack application
<ide> will run and respond with `403 Forbidden`. This can be customized by setting
<del>`config.host_configuration.response_app`. For example:
<add>`config.host_authorization.response_app`. For example:
<ide>
<ide> ```ruby
<del>Rails.application.config.host_configuration = {
<add>Rails.application.config.host_authorization = {
<ide> response_app: -> env do
<ide> [400, { "Content-Type" => "text/plain" }, ["Bad Request"]]
<ide> end | 1 |
Java | Java | recognize content-type as special header in mhsrb | 8b35c3ff74347f32194149ec91773c4eb2eb21ea | <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public MockHttpServletRequestBuilder param(String name, String... values) {
<ide> * @param values one or more header values
<ide> */
<ide> public MockHttpServletRequestBuilder header(String name, Object... values) {
<add> if ("Content-Type".equalsIgnoreCase(name)) {
<add> List<MediaType> mediaTypes = MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(values));
<add> this.contentType = MediaType.toString(mediaTypes);
<add> }
<ide> addToMultiValueMap(this.headers, name, values);
<ide> return this;
<ide> }
<ide> public MockHttpServletRequestBuilder header(String name, Object... values) {
<ide> * @param httpHeaders the headers and values to add
<ide> */
<ide> public MockHttpServletRequestBuilder headers(HttpHeaders httpHeaders) {
<add> MediaType mediaType = httpHeaders.getContentType();
<add> if (mediaType != null) {
<add> this.contentType = mediaType.toString();
<add> }
<ide> for (String name : httpHeaders.keySet()) {
<ide> Object[] values = ObjectUtils.toObjectArray(httpHeaders.get(name).toArray());
<ide> addToMultiValueMap(this.headers, name, values);
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2014 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> import java.util.Locale;
<ide> import java.util.Map;
<ide>
<add>import javax.print.attribute.standard.Media;
<ide> import javax.servlet.ServletContext;
<ide> import javax.servlet.http.Cookie;
<ide>
<ide> public void contentType() throws Exception {
<ide> assertEquals("text/html", contentTypes.get(0));
<ide> }
<ide>
<add> // SPR-11308
<add>
<add> @Test
<add> public void contentTypeViaHeader() throws Exception {
<add> this.builder.header("Content-Type", MediaType.TEXT_HTML_VALUE);
<add> MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
<add> String contentType = request.getContentType();
<add>
<add> assertEquals("text/html", contentType);
<add> }
<add>
<add> // SPR-11308
<add>
<add> @Test
<add> public void contentTypeViaMultipleHeaderValues() throws Exception {
<add> this.builder.header("Content-Type", MediaType.TEXT_HTML_VALUE, MediaType.ALL_VALUE);
<add> MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
<add> String contentType = request.getContentType();
<add>
<add> assertEquals("text/html, */*", contentType);
<add> }
<add>
<ide> @Test
<ide> public void body() throws Exception {
<ide> byte[] body = "Hello World".getBytes("UTF-8"); | 2 |
Python | Python | make sdist use distutils | fed2509471e77e0357c5252e69fc6159881f6cb2 | <ide><path>setup.py
<ide> os.remove('MANIFEST')
<ide>
<ide> # We need to import setuptools here in order for it to persist in sys.modules.
<del># Its presence/absence is used in subclassing setup in numpy/distutils/core.py,
<del># which may not be the most robust design.
<add># Its presence/absence is used in subclassing setup in numpy/distutils/core.py.
<add># However, we need to run the distutils version of sdist, so import that first
<add># so that it is in sys.modules
<add>import numpy.distutils.command.sdist
<ide> import setuptools
<ide>
<ide> # Initialize cmdclass from versioneer
<ide> def __exit__(self, exception_type, exception_value, traceback):
<ide> f.write(self.bsd_text)
<ide>
<ide>
<del>sdist_class = cmdclass['sdist']
<del>class sdist_checked(sdist_class):
<add># Need to inherit from versioneer version of sdist to get the encoded
<add># version information.
<add>class sdist_checked(cmdclass['sdist']):
<ide> """ check submodules on sdist to prevent incomplete tarballs """
<ide> def run(self):
<ide> check_submodules()
<ide> with concat_license_files():
<del> sdist_class.run(self)
<add> super().run()
<ide>
<ide>
<ide> def get_build_overrides(): | 1 |
Javascript | Javascript | fix port validation | 53cd3d8bab6e79a109565aafe2bed2c9ff4e9dd6 | <ide><path>lib/internal/errors.js
<ide> E('ERR_SOCKET_BAD_PORT', (name, port, allowZero = true) => {
<ide> assert(typeof allowZero === 'boolean',
<ide> "The 'allowZero' argument must be of type boolean.");
<ide> const operator = allowZero ? '>=' : '>';
<del> return `${name} should be ${operator} 0 and < 65536. Received ${port}.`;
<add> return `${name} should be ${operator} 0 and < 65536. Received ${determineSpecificType(port)}.`;
<ide> }, RangeError);
<ide> E('ERR_SOCKET_BAD_TYPE',
<ide> 'Bad socket type specified. Valid types are: udp4, udp6', TypeError);
<ide><path>test/parallel/test-dns.js
<ide> dns.lookup('', {
<ide> const portErr = (port) => {
<ide> const err = {
<ide> code: 'ERR_SOCKET_BAD_PORT',
<del> message:
<del> `Port should be >= 0 and < 65536. Received ${port}.`,
<ide> name: 'RangeError'
<ide> };
<ide>
<ide> const portErr = (port) => {
<ide> dns.lookupService('0.0.0.0', port, common.mustNotCall());
<ide> }, err);
<ide> };
<del>portErr(null);
<del>portErr(undefined);
<del>portErr(65538);
<del>portErr('test');
<add>[null, undefined, 65538, 'test', NaN, Infinity, Symbol(), 0n, true, false, '', () => {}, {}].forEach(portErr);
<ide>
<ide> assert.throws(() => {
<ide> dns.lookupService('0.0.0.0', 80, null); | 2 |
Text | Text | fix text to follow portuguese language syntax | d62a520dd7ed565aa521bc1d18f659e8f2efd48a | <ide><path>curriculum/challenges/portuguese/01-responsive-web-design/css-flexbox/use-display-flex-to-position-two-boxes.portuguese.md
<ide> localeTitle: 'Use display: flex para posicionar duas caixas'
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Esta seção usa estilos de desafio alternados para mostrar como usar o CSS para posicionar elementos de maneira flexível. Primeiro, um desafio explicará a teoria, então um desafio prático usando um simples componente de tweet aplicará o conceito de flexbox. Colocando a <code>display: flex;</code> propriedade CSS <code>display: flex;</code> em um elemento permite que você use outras propriedades flex para criar uma página responsiva. </section>
<add><section id="description"> Esta seção usa estilos de desafio alternados para mostrar como usar o CSS para posicionar elementos de maneira flexível. Primeiro, um desafio explicará a teoria, então um desafio prático usando um simples componente de tweet aplicará o conceito de flexbox.
<add>Colocando a propriedade CSS <code>display: flex;</code> em um elemento permite que você use outras propriedades flex para criar uma página responsiva. </section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> Adicione a <code>display</code> propriedade CSS ao <code>#box-container</code> e defina seu valor como flex. </section>
<add><section id="instructions"> Adicione a propriedade CSS <code>display</code> ao <code>#box-container</code> e defina seu valor como *flex*. </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'> | 1 |
Java | Java | use list.sort instead of collection.sort in tests | 523d2f88be9f2087b058f45f7830f8f2b8d5707e | <ide><path>spring-core/src/test/java/org/springframework/core/annotation/OrderSourceProviderTests.java
<ide> void plainComparator() {
<ide> C c2 = new C(-5);
<ide> items.add(c);
<ide> items.add(c2);
<del> Collections.sort(items, comparator);
<add> items.sort(comparator);
<ide> assertOrder(items, c2, c);
<ide> }
<ide>
<ide> void listNoFactoryMethod() {
<ide> B b = new B();
<ide>
<ide> List<?> items = Arrays.asList(a, c, b);
<del> Collections.sort(items, comparator.withSourceProvider(obj -> null));
<add> items.sort(comparator.withSourceProvider(obj -> null));
<ide> assertOrder(items, c, a, b);
<ide> }
<ide>
<ide> void listFactoryMethod() {
<ide> B b = new B();
<ide>
<ide> List<?> items = Arrays.asList(a, c, b);
<del> Collections.sort(items, comparator.withSourceProvider(obj -> {
<add> items.sort(comparator.withSourceProvider(obj -> {
<ide> if (obj == a) {
<ide> return new C(4);
<ide> }
<ide> void listFactoryMethodOverridesStaticOrder() {
<ide> C c2 = new C(-5);
<ide>
<ide> List<?> items = Arrays.asList(a, c, c2);
<del> Collections.sort(items, comparator.withSourceProvider(obj -> {
<add> items.sort(comparator.withSourceProvider(obj -> {
<ide> if (obj == a) {
<ide> return 4;
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/core/convert/converter/ConvertingComparatorTests.java
<ide> private void testConversion(ConvertingComparator<String, Integer> convertingComp
<ide> void shouldGetMapEntryKeys() throws Exception {
<ide> ArrayList<Entry<String, Integer>> list = createReverseOrderMapEntryList();
<ide> Comparator<Map.Entry<String, Integer>> comparator = ConvertingComparator.mapEntryKeys(new ComparableComparator<String>());
<del> Collections.sort(list, comparator);
<add> list.sort(comparator);
<ide> assertThat(list.get(0).getKey()).isEqualTo("a");
<ide> }
<ide>
<ide> @Test
<ide> void shouldGetMapEntryValues() throws Exception {
<ide> ArrayList<Entry<String, Integer>> list = createReverseOrderMapEntryList();
<ide> Comparator<Map.Entry<String, Integer>> comparator = ConvertingComparator.mapEntryValues(new ComparableComparator<Integer>());
<del> Collections.sort(list, comparator);
<add> list.sort(comparator);
<ide> assertThat(list.get(0).getValue()).isEqualTo(1);
<ide> }
<ide>
<ide><path>spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java
<ide> void patternComparatorSort() {
<ide>
<ide> paths.add(null);
<ide> paths.add("/hotels/new");
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/new");
<ide> assertThat(paths.get(1)).isNull();
<ide> paths.clear();
<ide>
<ide> paths.add("/hotels/new");
<ide> paths.add(null);
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/new");
<ide> assertThat(paths.get(1)).isNull();
<ide> paths.clear();
<ide>
<ide> paths.add("/hotels/*");
<ide> paths.add("/hotels/new");
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/new");
<ide> assertThat(paths.get(1)).isEqualTo("/hotels/*");
<ide> paths.clear();
<ide>
<ide> paths.add("/hotels/new");
<ide> paths.add("/hotels/*");
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/new");
<ide> assertThat(paths.get(1)).isEqualTo("/hotels/*");
<ide> paths.clear();
<ide>
<ide> paths.add("/hotels/**");
<ide> paths.add("/hotels/*");
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/*");
<ide> assertThat(paths.get(1)).isEqualTo("/hotels/**");
<ide> paths.clear();
<ide>
<ide> paths.add("/hotels/*");
<ide> paths.add("/hotels/**");
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/*");
<ide> assertThat(paths.get(1)).isEqualTo("/hotels/**");
<ide> paths.clear();
<ide>
<ide> paths.add("/hotels/{hotel}");
<ide> paths.add("/hotels/new");
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/new");
<ide> assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
<ide> paths.clear();
<ide>
<ide> paths.add("/hotels/new");
<ide> paths.add("/hotels/{hotel}");
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/new");
<ide> assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
<ide> paths.clear();
<ide>
<ide> paths.add("/hotels/*");
<ide> paths.add("/hotels/{hotel}");
<ide> paths.add("/hotels/new");
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/new");
<ide> assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
<ide> assertThat(paths.get(2)).isEqualTo("/hotels/*");
<ide> void patternComparatorSort() {
<ide> paths.add("/hotels/ne*");
<ide> paths.add("/hotels/n*");
<ide> Collections.shuffle(paths);
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/ne*");
<ide> assertThat(paths.get(1)).isEqualTo("/hotels/n*");
<ide> paths.clear();
<ide> void patternComparatorSort() {
<ide> paths.add("/hotels/new.*");
<ide> paths.add("/hotels/{hotel}");
<ide> Collections.shuffle(paths);
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/hotels/new.*");
<ide> assertThat(paths.get(1)).isEqualTo("/hotels/{hotel}");
<ide> paths.clear();
<ide>
<ide> comparator = pathMatcher.getPatternComparator("/web/endUser/action/login.html");
<ide> paths.add("/**/login.*");
<ide> paths.add("/**/endUser/action/login.*");
<del> Collections.sort(paths, comparator);
<add> paths.sort(comparator);
<ide> assertThat(paths.get(0)).isEqualTo("/**/endUser/action/login.*");
<ide> assertThat(paths.get(1)).isEqualTo("/**/login.*");
<ide> paths.clear(); | 3 |
Text | Text | move inactive collaborators to emeriti | e6a55b4391aaaa6ddbf373e2b1fd8e90c2609a9c | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Сковорода Никита Андреевич** <chalkerx@gmail.com> (he/him)
<ide> * [cjihrig](https://github.com/cjihrig) -
<ide> **Colin Ihrig** <cjihrig@gmail.com> (he/him)
<del>* [claudiorodriguez](https://github.com/claudiorodriguez) -
<del>**Claudio Rodriguez** <cjrodr@yahoo.com>
<ide> * [codebytere](https://github.com/codebytere) -
<ide> **Shelley Vohr** <codebytere@gmail.com> (she/her)
<ide> * [danbev](https://github.com/danbev) -
<ide> For information about the governance of the Node.js project, see
<ide> **Yang Guo** <yangguo@chromium.org> (he/him)
<ide> * [hiroppy](https://github.com/hiroppy) -
<ide> **Yuta Hiroto** <hello@hiroppy.me> (he/him)
<del>* [iarna](https://github.com/iarna) -
<del>**Rebecca Turner** <me@re-becca.org>
<ide> * [indutny](https://github.com/indutny) -
<ide> **Fedor Indutny** <fedor.indutny@gmail.com>
<del>* [italoacasas](https://github.com/italoacasas) -
<del>**Italo A. Casas** <me@italoacasas.com> (he/him)
<ide> * [JacksonTian](https://github.com/JacksonTian) -
<ide> **Jackson Tian** <shyvo1987@gmail.com>
<ide> * [jasnell](https://github.com/jasnell) -
<ide> For information about the governance of the Node.js project, see
<ide> **Julien Gilli** <jgilli@nodejs.org>
<ide> * [mmarchini](https://github.com/mmarchini) -
<ide> **Matheus Marchini** <mat@mmarchini.me>
<del>* [MoonBall](https://github.com/MoonBall) -
<del>**Chen Gang** <gangc.cxy@foxmail.com>
<ide> * [mscdex](https://github.com/mscdex) -
<ide> **Brian White** <mscdex@mscdex.net>
<ide> * [MylesBorins](https://github.com/MylesBorins) -
<ide> For information about the governance of the Node.js project, see
<ide> **Tiancheng "Timothy" Gu** <timothygu99@gmail.com> (he/him)
<ide> * [tniessen](https://github.com/tniessen) -
<ide> **Tobias Nießen** <tniessen@tnie.de>
<del>* [trevnorris](https://github.com/trevnorris) -
<del>**Trevor Norris** <trev.norris@gmail.com>
<ide> * [trivikr](https://github.com/trivikr) -
<ide> **Trivikram Kamat** <trivikr.dev@gmail.com>
<ide> * [Trott](https://github.com/Trott) -
<ide> For information about the governance of the Node.js project, see
<ide> **Calvin Metcalf** <calvin.metcalf@gmail.com>
<ide> * [chrisdickinson](https://github.com/chrisdickinson) -
<ide> **Chris Dickinson** <christopher.s.dickinson@gmail.com>
<add>* [claudiorodriguez](https://github.com/claudiorodriguez) -
<add>**Claudio Rodriguez** <cjrodr@yahoo.com>
<ide> * [DavidCai1993](https://github.com/DavidCai1993) -
<ide> **David Cai** <davidcai1993@yahoo.com> (he/him)
<ide> * [eljefedelrodeodeljefe](https://github.com/eljefedelrodeodeljefe) -
<ide> For information about the governance of the Node.js project, see
<ide> **Daniel Wang** <wangyang0123@gmail.com>
<ide> * [glentiki](https://github.com/glentiki) -
<ide> **Glen Keane** <glenkeane.94@gmail.com> (he/him)
<add>* [iarna](https://github.com/iarna) -
<add>**Rebecca Turner** <me@re-becca.org>
<ide> * [imran-iq](https://github.com/imran-iq) -
<ide> **Imran Iqbal** <imran@imraniqbal.org>
<ide> * [imyller](https://github.com/imyller) -
<ide> **Ilkka Myller** <ilkka.myller@nodefield.com>
<ide> * [isaacs](https://github.com/isaacs) -
<ide> **Isaac Z. Schlueter** <i@izs.me>
<add>* [italoacasas](https://github.com/italoacasas) -
<add>**Italo A. Casas** <me@italoacasas.com> (he/him)
<ide> * [jasongin](https://github.com/jasongin) -
<ide> **Jason Ginchereau** <jasongin@microsoft.com>
<ide> * [jbergstroem](https://github.com/jbergstroem) -
<ide> For information about the governance of the Node.js project, see
<ide> **Mikeal Rogers** <mikeal.rogers@gmail.com>
<ide> * [monsanto](https://github.com/monsanto) -
<ide> **Christopher Monsanto** <chris@monsan.to>
<add>* [MoonBall](https://github.com/MoonBall) -
<add>**Chen Gang** <gangc.cxy@foxmail.com>
<ide> * [not-an-aardvark](https://github.com/not-an-aardvark) -
<ide> **Teddy Katz** <teddy.katz@gmail.com> (he/him)
<ide> * [Olegas](https://github.com/Olegas) -
<ide> For information about the governance of the Node.js project, see
<ide> **Christian Tellnes** <christian@tellnes.no>
<ide> * [thlorenz](https://github.com/thlorenz) -
<ide> **Thorsten Lorenz** <thlorenz@gmx.de>
<add>* [trevnorris](https://github.com/trevnorris) -
<add>**Trevor Norris** <trev.norris@gmail.com>
<ide> * [tunniclm](https://github.com/tunniclm) -
<ide> **Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com>
<ide> * [vkurchatkin](https://github.com/vkurchatkin) - | 1 |
PHP | PHP | apply fixes from styleci | 6cece2455c5894f4bd6202747fce244cc6c693f2 | <ide><path>src/Illuminate/Routing/RedirectController.php
<ide> public function __invoke(Request $request, UrlGenerator $url)
<ide> $destination = $parameters->pop();
<ide>
<ide> $route = (new Route('GET', $destination, [
<del> 'as' => 'laravel_route_redirect_destination'
<add> 'as' => 'laravel_route_redirect_destination',
<ide> ]))->bind($request);
<ide>
<ide> $parameters = $parameters->only( | 1 |
Javascript | Javascript | remove unused parameters | 80587bb68dd7a1b5d6bea2f70b0362378bf27a62 | <ide><path>src/core/core.controller.js
<ide> helpers.extend(Chart.prototype, /** @lends Chart */ {
<ide> easing: config.easing || animationOptions.easing,
<ide>
<ide> render: function(chart, animationObject) {
<del> var easingFunction = helpers.easing.effects[animationObject.easing];
<del> var currentStep = animationObject.currentStep;
<del> var stepDecimal = currentStep / animationObject.numSteps;
<add> const easingFunction = helpers.easing.effects[animationObject.easing];
<add> const stepDecimal = animationObject.currentStep / animationObject.numSteps;
<ide>
<del> chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
<add> chart.draw(easingFunction(stepDecimal));
<ide> },
<ide>
<ide> onAnimationProgress: animationOptions.onProgress, | 1 |
Text | Text | add changelog entry | 4d4440c5a86fc1611b0a236b3253aa3339366788 | <ide><path>actionpack/CHANGELOG.md
<ide>
<ide> *Adam Forsyth*
<ide>
<add>* Allow `Bearer` as token-keyword in `Authorization-Header`.
<add>
<add> Aditionally to `Token`, the keyword `Bearer` is acceptable as a keyword
<add> for the auth-token. The `Bearer` keyword is described in the original
<add> OAuth RFC and used in libraries like Angular-JWT.
<add>
<add> See #19094.
<add>
<add> *Peter Schröder*
<add>
<ide> * Drop request class from RouteSet constructor.
<ide>
<ide> If you would like to use a custom request class, please subclass and implement | 1 |
Ruby | Ruby | remove useless `new` implementation | ef2d7a69ece612762c199dc1a7fca0ff49400b45 | <ide><path>actionpack/lib/action_dispatch/testing/test_request.rb
<ide> class TestRequest < Request
<ide> "rack.request.cookie_hash" => {}.with_indifferent_access
<ide> )
<ide>
<del> def self.new(env = {})
<del> super
<del> end
<del>
<ide> def initialize(env = {})
<ide> env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
<ide> super(default_env.merge(env)) | 1 |
Java | Java | add shortcut in testgenerationcontext | c5fc0a5ef3fb85a69fd8d9f92c86a2798344df98 | <ide><path>spring-core-test/src/main/java/org/springframework/aot/test/generate/TestGenerationContext.java
<ide> public TestGenerationContext(ClassNameGenerator classNameGenerator) {
<ide>
<ide> /**
<ide> * Create an instance using the specified {@code target}.
<del> * @param target the default target class to use
<add> * @param target the default target class name to use
<ide> */
<ide> public TestGenerationContext(ClassName target) {
<ide> this(new ClassNameGenerator(target));
<ide> }
<ide>
<add> /**
<add> * Create an instance using the specified {@code target}.
<add> * @param target the default target class to use
<add> */
<add> public TestGenerationContext(Class<?> target) {
<add> this(ClassName.get(target));
<add> }
<add>
<add>
<ide> /**
<ide> * Create an instance using {@link #TEST_TARGET} as the {@code target}.
<ide> */ | 1 |
PHP | PHP | use crlf in mail headers | 931c7528e983b224357b62aa72fe1face9522749 | <ide><path>src/Mailer/Transport/MailTransport.php
<ide> public function send(Message $message): array
<ide> $to = $message->getHeaders(['to'])['To'];
<ide> $to = str_replace("\r\n", '', $to);
<ide>
<del> $eol = $this->getConfig('eol', PHP_EOL);
<add> $eol = $this->getConfig('eol', "\r\n");
<ide> $headers = $message->getHeadersString(
<ide> [
<ide> 'from',
<ide><path>tests/TestCase/Mailer/Transport/MailTransportTest.php
<ide> public function testSendData()
<ide> $encoded = '=?UTF-8?B?Rm/DuCBCw6VyIELDqXogRm/DuCBCw6VyIELDqXogRm/DuCBCw6VyIELDqXog?=';
<ide> $encoded .= ' =?UTF-8?B?Rm/DuCBCw6VyIELDqXo=?=';
<ide>
<del> $data = 'From: CakePHP Test <noreply@cakephp.org>' . PHP_EOL;
<del> $data .= 'Reply-To: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>' . PHP_EOL;
<del> $data .= 'Return-Path: CakePHP Return <pleasereply@cakephp.org>' . PHP_EOL;
<del> $data .= 'Cc: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>' . PHP_EOL;
<del> $data .= 'Bcc: phpnut@cakephp.org' . PHP_EOL;
<del> $data .= 'X-Mailer: CakePHP Email' . PHP_EOL;
<del> $data .= 'Date: ' . $date . PHP_EOL;
<del> $data .= 'X-add: ' . $encoded . PHP_EOL;
<del> $data .= 'Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>' . PHP_EOL;
<del> $data .= 'MIME-Version: 1.0' . PHP_EOL;
<del> $data .= 'Content-Type: text/plain; charset=UTF-8' . PHP_EOL;
<add> $data = "From: CakePHP Test <noreply@cakephp.org>\r\n";
<add> $data .= "Reply-To: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>\r\n";
<add> $data .= "Return-Path: CakePHP Return <pleasereply@cakephp.org>\r\n";
<add> $data .= "Cc: Mark Story <mark@cakephp.org>, Juan Basso <juan@cakephp.org>\r\n";
<add> $data .= "Bcc: phpnut@cakephp.org\r\n";
<add> $data .= "X-Mailer: CakePHP Email\r\n";
<add> $data .= 'Date: ' . $date . "\r\n";
<add> $data .= 'X-add: ' . $encoded . "\r\n";
<add> $data .= "Message-ID: <4d9946cf-0a44-4907-88fe-1d0ccbdd56cb@localhost>\r\n";
<add> $data .= "MIME-Version: 1.0\r\n";
<add> $data .= "Content-Type: text/plain; charset=UTF-8\r\n";
<ide> $data .= 'Content-Transfer-Encoding: 8bit';
<ide>
<ide> $this->MailTransport->expects($this->once())->method('_mail')
<ide> ->with(
<ide> 'CakePHP <cake@cakephp.org>',
<ide> $encoded,
<del> implode(PHP_EOL, ['First Line', 'Second Line', '.Third Line', '', '']),
<add> implode("\r\n", ['First Line', 'Second Line', '.Third Line', '', '']),
<ide> $data,
<ide> '-f'
<ide> ); | 2 |
Javascript | Javascript | improve the extractinfo code to be more robust | ae2d130f40fda83f24c3222e953e448864e190f2 | <ide><path>fonts.js
<ide> var Type1Parser = function() {
<ide> * extracted from and eexec encrypted block of data
<ide> */
<ide> this.extractFontProgram = function t1_extractFontProgram(stream) {
<del> var eexecString = decrypt(stream, kEexecEncryptionKey, 4);
<del> var subrs = [], glyphs = [];
<del> var inGlyphs = false;
<del> var inSubrs = false;
<del> var glyph = "";
<add> var eexec = decrypt(stream, kEexecEncryptionKey, 4);
<add> var eexecString = "";
<add> for (var i = 0; i < eexec.length; i++)
<add> eexecString += String.fromCharCode(eexec[i]);
<add>
<add> var glyphsSection = false, subrsSection = false;
<add> var extracted = {
<add> subrs: [],
<add> charstrings: []
<add> };
<ide>
<add> var glyph = "";
<ide> var token = "";
<del> var index = 0;
<ide> var length = 0;
<ide>
<ide> var c = "";
<ide> var count = eexecString.length;
<ide> for (var i = 0; i < count; i++) {
<ide> var c = eexecString[i];
<ide>
<del> if (inSubrs && c == 0x52) {
<del> length = parseInt(length);
<del> var data = eexecString.slice(i + 3, i + 3 + length);
<del> var encodedSubr = decrypt(data, kCharStringsEncryptionKey, 4);
<del> var str = decodeCharString(encodedSubr);
<del>
<del> subrs.push(str.charstring);
<del> i += 3 + length;
<del> } else if (inGlyphs && c == 0x52) {
<del> length = parseInt(length);
<del> var data = eexecString.slice(i + 3, i + 3 + length);
<del> var encodedCharstring = decrypt(data, kCharStringsEncryptionKey, 4);
<del> var str = decodeCharString(encodedCharstring);
<del>
<del> glyphs.push({
<add> if ((glyphsSection || subrsSection) && c == "R") {
<add> var data = eexec.slice(i + 3, i + 3 + length);
<add> var encoded = decrypt(data, kCharStringsEncryptionKey, 4);
<add> var str = decodeCharString(encoded);
<add>
<add> if (glyphsSection) {
<add> extracted.charstrings.push({
<ide> glyph: glyph,
<ide> data: str.charstring,
<ide> lsb: str.lsb,
<ide> width: str.width
<del> });
<del> i += 3 + length;
<del> } else if (inGlyphs && c == 0x2F) {
<del> token = "";
<del> glyph = "";
<del>
<del> while ((c = eexecString[++i]) != 0x20)
<del> glyph += String.fromCharCode(c);
<del> } else if (!inSubrs && !inGlyphs && c == 0x2F && eexecString[i+1] == 0x53) {
<del> while ((c = eexecString[++i]) != 0x20) {};
<del> inSubrs = true;
<del> } else if (c == 0x20) {
<del> index = length;
<del> length = token;
<add> });
<add> } else {
<add> extracted.subrs.push(str.charstring);
<add> }
<add> i += length + 3;
<add> } else if (c == " ") {
<add> length = parseInt(token);
<ide> token = "";
<del> } else if (c == 0x2F && eexecString[i+1] == 0x43 && eexecString[i+2] == 0x68) {
<del> while ((c = eexecString[++i]) != 0x20) {};
<del> inSubrs = false;
<del> inGlyphs = true;
<ide> } else {
<del> token += String.fromCharCode(c);
<add> token += c;
<add> if (!glyphsSection) {
<add> glyphsSection = token.indexOf("/CharString") != -1;
<add> subrsSection = subrsSection || token.indexOf("Subrs") != -1;
<add> } else if (c == "/") {
<add> token = glyph = "";
<add> while ((c = eexecString[++i]) != " ")
<add> glyph += c;
<add> }
<ide> }
<ide> }
<del> return {
<del> subrs: subrs,
<del> charstrings: glyphs
<del> }
<add>
<add> return extracted;
<ide> }
<ide> };
<ide> | 1 |
Java | Java | add reflection hints for httpentity | 93b340e5633d623e0899dd296bda7ce86ce02b20 | <ide><path>spring-core/src/main/java/org/springframework/aot/hint/support/BindingReflectionHintsRegistrar.java
<ide> import org.springframework.core.KotlinDetector;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.ResolvableType;
<add>import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ClassUtils;
<ide>
<ide> /**
<ide> private void registerMembers(ReflectionHints hints, Class<?> type, Builder build
<ide> }
<ide> }
<ide>
<del> private void collectReferencedTypes(Set<Type> seen, Set<Class<?>> types, Type type) {
<del> if (seen.contains(type)) {
<add> private void collectReferencedTypes(Set<Type> seen, Set<Class<?>> types, @Nullable Type type) {
<add> if (type == null || seen.contains(type)) {
<ide> return;
<ide> }
<ide> seen.add(type);
<ide><path>spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMappingReflectiveProcessor.java
<ide> import java.lang.reflect.AnnotatedElement;
<ide> import java.lang.reflect.Method;
<ide> import java.lang.reflect.Parameter;
<add>import java.lang.reflect.Type;
<ide>
<ide> import org.springframework.aot.hint.ExecutableMode;
<ide> import org.springframework.aot.hint.ReflectionHints;
<ide> import org.springframework.aot.hint.annotation.ReflectiveProcessor;
<ide> import org.springframework.aot.hint.support.BindingReflectionHintsRegistrar;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.annotation.AnnotatedElementUtils;
<add>import org.springframework.http.HttpEntity;
<add>import org.springframework.lang.Nullable;
<ide>
<ide> /**
<ide> * {@link ReflectiveProcessor} implementation for {@link RequestMapping}
<ide> * annotated types. On top of registering reflection hints for invoking
<del> * the annotated method, this implementation handles return types annotated
<del> * with {@link ResponseBody} and parameters annotated with {@link RequestBody}
<del> * which are serialized as well.
<add> * the annotated method, this implementation handles:
<add> * <ul>
<add> * <li>Return types annotated with {@link ResponseBody}.</li>
<add> * <li>Parameters annotated with {@link RequestBody}.</li>
<add> * <li>{@link HttpEntity} return type and parameters.</li>
<add> * </ul>
<ide> *
<ide> * @author Stephane Nicoll
<ide> * @author Sebastien Deleuze
<ide> class RequestMappingReflectiveProcessor implements ReflectiveProcessor {
<ide> @Override
<ide> public void registerReflectionHints(ReflectionHints hints, AnnotatedElement element) {
<ide> if (element instanceof Class<?> type) {
<del> registerTypeHint(hints, type);
<add> registerTypeHints(hints, type);
<ide> }
<ide> else if (element instanceof Method method) {
<del> registerMethodHint(hints, method);
<add> registerMethodHints(hints, method);
<ide> }
<ide> }
<ide>
<del> protected void registerTypeHint(ReflectionHints hints, Class<?> type) {
<add> protected void registerTypeHints(ReflectionHints hints, Class<?> type) {
<ide> hints.registerType(type, hint -> {});
<ide> }
<ide>
<del> protected void registerMethodHint(ReflectionHints hints, Method method) {
<add> protected void registerMethodHints(ReflectionHints hints, Method method) {
<add> hints.registerMethod(method, hint -> hint.setModes(ExecutableMode.INVOKE));
<add> registerParameterHints(hints, method);
<add> registerReturnValueHints(hints, method);
<add> }
<add>
<add> protected void registerParameterHints(ReflectionHints hints, Method method) {
<ide> hints.registerMethod(method, hint -> hint.setModes(ExecutableMode.INVOKE));
<ide> for (Parameter parameter : method.getParameters()) {
<ide> MethodParameter methodParameter = MethodParameter.forParameter(parameter);
<ide> if (methodParameter.hasParameterAnnotation(RequestBody.class)) {
<ide> this.bindingRegistrar.registerReflectionHints(hints, methodParameter.getGenericParameterType());
<ide> }
<add> else if (HttpEntity.class.isAssignableFrom(methodParameter.getParameterType())) {
<add> this.bindingRegistrar.registerReflectionHints(hints, getHttpEntityType(methodParameter));
<add> }
<ide> }
<add> }
<add>
<add> protected void registerReturnValueHints(ReflectionHints hints, Method method) {
<ide> MethodParameter returnType = MethodParameter.forExecutable(method, -1);
<ide> if (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) ||
<ide> returnType.hasMethodAnnotation(ResponseBody.class)) {
<ide> this.bindingRegistrar.registerReflectionHints(hints, returnType.getGenericParameterType());
<ide> }
<add> else if (HttpEntity.class.isAssignableFrom(returnType.getParameterType())) {
<add> this.bindingRegistrar.registerReflectionHints(hints, getHttpEntityType(returnType));
<add> }
<ide> }
<add>
<add> @Nullable
<add> protected Type getHttpEntityType(MethodParameter parameter) {
<add> MethodParameter nestedParameter = parameter.nested();
<add> return (nestedParameter.getNestedParameterType() == nestedParameter.getParameterType() ? null : nestedParameter.getNestedParameterType());
<add> }
<add>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/web/bind/annotation/RequestMappingReflectiveProcessorTests.java
<ide> import org.springframework.aot.hint.MemberCategory;
<ide> import org.springframework.aot.hint.ReflectionHints;
<ide> import org.springframework.aot.hint.TypeReference;
<add>import org.springframework.http.HttpEntity;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<ide> void registerReflectiveHintsForClassWithMapping() {
<ide> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleControllerWithClassMapping.class)));
<ide> }
<ide>
<add> @Test
<add> void registerReflectiveHintsForMethodReturningHttpEntity() throws NoSuchMethodException {
<add> Method method = SampleController.class.getDeclaredMethod("getHttpEntity");
<add> processor.registerReflectionHints(hints, method);
<add> assertThat(hints.typeHints()).satisfiesExactlyInAnyOrder(
<add> typeHint -> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleController.class)),
<add> typeHint -> {
<add> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(Response.class));
<add> assertThat(typeHint.getMemberCategories()).containsExactlyInAnyOrder(
<add> MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
<add> MemberCategory.DECLARED_FIELDS);
<add> assertThat(typeHint.methods()).satisfiesExactlyInAnyOrder(
<add> hint -> assertThat(hint.getName()).isEqualTo("getMessage"),
<add> hint -> assertThat(hint.getName()).isEqualTo("setMessage"));
<add> },
<add> typeHint -> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(String.class)));
<add> }
<add>
<add> @Test
<add> void registerReflectiveHintsForMethodReturningRawHttpEntity() throws NoSuchMethodException {
<add> Method method = SampleController.class.getDeclaredMethod("getRawHttpEntity");
<add> processor.registerReflectionHints(hints, method);
<add> assertThat(hints.typeHints()).singleElement().satisfies(
<add> typeHint -> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleController.class)));
<add> }
<add>
<add> @Test
<add> void registerReflectiveHintsForMethodWithHttpEntityParameter() throws NoSuchMethodException {
<add> Method method = SampleController.class.getDeclaredMethod("postHttpEntity", HttpEntity.class);
<add> processor.registerReflectionHints(hints, method);
<add> assertThat(hints.typeHints()).satisfiesExactlyInAnyOrder(
<add> typeHint -> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleController.class)),
<add> typeHint -> {
<add> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(Request.class));
<add> assertThat(typeHint.getMemberCategories()).containsExactlyInAnyOrder(
<add> MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
<add> MemberCategory.DECLARED_FIELDS);
<add> assertThat(typeHint.methods()).satisfiesExactlyInAnyOrder(
<add> hint -> assertThat(hint.getName()).isEqualTo("getMessage"),
<add> hint -> assertThat(hint.getName()).isEqualTo("setMessage"));
<add> },
<add> typeHint -> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(String.class)));
<add> }
<add>
<add> @Test
<add> void registerReflectiveHintsForMethodWithRawHttpEntityParameter() throws NoSuchMethodException {
<add> Method method = SampleController.class.getDeclaredMethod("postRawHttpEntity", HttpEntity.class);
<add> processor.registerReflectionHints(hints, method);
<add> assertThat(hints.typeHints()).singleElement().satisfies(
<add> typeHint -> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleController.class)));
<add> }
<add>
<ide> static class SampleController {
<ide>
<ide> @GetMapping
<ide> void post(@RequestBody Request request) {
<ide> String message() {
<ide> return "";
<ide> }
<add>
<add> @GetMapping
<add> HttpEntity<Response> getHttpEntity() {
<add> return new HttpEntity(new Response("response"));
<add> }
<add>
<add> @GetMapping
<add> HttpEntity getRawHttpEntity() {
<add> return new HttpEntity(new Response("response"));
<add> }
<add>
<add> @PostMapping
<add> void postHttpEntity(HttpEntity<Request> entity) {
<add> }
<add>
<add> @PostMapping
<add> void postRawHttpEntity(HttpEntity entity) {
<add> }
<add>
<ide> }
<ide>
<ide> @RestController | 3 |
Javascript | Javascript | deprecate the non-block params {{with}} syntax | 99854697b6e88f58bf85e1acc5e5f8a80b3ecd1a | <ide><path>packages/ember-htmlbars/lib/helpers/with.js
<ide> import WithView from "ember-views/views/with_view";
<ide>
<ide> NOTE: The alias should not reuse a name from the bound property path.
<ide> For example: `{{#with foo as |foo.bar|}}` is not supported because it attempts to alias using
<del> the first part of the property path, `foo`. Instead, use `{{#with foo.bar as baz}}`.
<add> the first part of the property path, `foo`. Instead, use `{{#with foo.bar as |baz|}}`.
<ide>
<ide> ### `controller` option
<ide>
<ide> import WithView from "ember-views/views/with_view";
<ide> This is very similar to using an `itemController` option with the `{{each}}` helper.
<ide>
<ide> ```handlebars
<del> {{#with users.posts as posts controller='userBlogPosts'}}
<add> {{#with users.posts controller='userBlogPosts' as |posts|}}
<ide> {{!- `posts` is wrapped in our controller instance }}
<ide> {{/with}}
<ide> ```
<ide><path>packages/ember-htmlbars/tests/compat/handlebars_get_test.js
<ide> QUnit.test('it can lookup a path from the current keywords', function() {
<ide> controller: {
<ide> foo: 'bar'
<ide> },
<del> template: compile('{{#with foo as bar}}{{handlebars-get "bar"}}{{/with}}')
<add> template: compile('{{#with foo as |bar|}}{{handlebars-get "bar"}}{{/with}}')
<ide> });
<ide>
<ide> runAppend(view);
<ide><path>packages/ember-htmlbars/tests/helpers/bind_attr_test.js
<ide> QUnit.test("{{bindAttr}} can be used to bind attributes [DEPRECATED]", function(
<ide> });
<ide>
<ide> QUnit.test("should be able to bind element attributes using {{bind-attr}} inside a block", function() {
<del> var template = compile('{{#with view.content as image}}<img {{bind-attr src=image.url alt=image.title}}>{{/with}}');
<add> var template = compile('{{#with view.content as |image|}}<img {{bind-attr src=image.url alt=image.title}}>{{/with}}');
<ide>
<ide> view = EmberView.create({
<ide> template: template,
<ide><path>packages/ember-htmlbars/tests/helpers/with_test.js
<ide> import { runAppend, runDestroy } from "ember-runtime/tests/utils";
<ide> var view, lookup;
<ide> var originalLookup = Ember.lookup;
<ide>
<del>function testWithAs(moduleName, templateString) {
<add>function testWithAs(moduleName, templateString, deprecated) {
<ide> QUnit.module(moduleName, {
<ide> setup() {
<ide> Ember.lookup = lookup = { Ember: Ember };
<ide>
<add> var template;
<add> if (deprecated) {
<add> expectDeprecation(function() {
<add> template = compile(templateString);
<add> }, "Using {{with}} without block syntax is deprecated. Please use standard block form (`{{#with foo as |bar|}}`) instead.");
<add> } else {
<add> template = compile(templateString);
<add> }
<add>
<add>
<ide> view = EmberView.create({
<del> template: compile(templateString),
<add> template: template,
<ide> context: {
<ide> title: "Señor Engineer",
<ide> person: { name: "Tom Dale" }
<ide> function testWithAs(moduleName, templateString) {
<ide> });
<ide> }
<ide>
<del>testWithAs("ember-htmlbars: {{#with}} helper", "{{#with person as tom}}{{title}}: {{tom.name}}{{/with}}");
<add>testWithAs("ember-htmlbars: {{#with}} helper", "{{#with person as tom}}{{title}}: {{tom.name}}{{/with}}", true);
<ide>
<ide> QUnit.module("Multiple Handlebars {{with foo as bar}} helpers", {
<ide> setup() {
<ide> Ember.lookup = lookup = { Ember: Ember };
<ide>
<ide> view = EmberView.create({
<del> template: compile("Admin: {{#with admin as person}}{{person.name}}{{/with}} User: {{#with user as person}}{{person.name}}{{/with}}"),
<add> template: compile("Admin: {{#with admin as |person|}}{{person.name}}{{/with}} User: {{#with user as |person|}}{{person.name}}{{/with}}"),
<ide> context: {
<ide> admin: { name: "Tom Dale" },
<ide> user: { name: "Yehuda Katz" }
<ide> QUnit.test("re-using the same variable with different #with blocks does not over
<ide>
<ide> QUnit.test("the scoped variable is not available outside the {{with}} block.", function() {
<ide> run(function() {
<del> view.set('template', compile("{{name}}-{{#with other as name}}{{name}}{{/with}}-{{name}}"));
<add> view.set('template', compile("{{name}}-{{#with other as |name|}}{{name}}{{/with}}-{{name}}"));
<ide> view.set('context', {
<ide> name: 'Stef',
<ide> other: 'Yehuda'
<ide> QUnit.test("the scoped variable is not available outside the {{with}} block.", f
<ide>
<ide> QUnit.test("nested {{with}} blocks shadow the outer scoped variable properly.", function() {
<ide> run(function() {
<del> view.set('template', compile("{{#with first as ring}}{{ring}}-{{#with fifth as ring}}{{ring}}-{{#with ninth as ring}}{{ring}}-{{/with}}{{ring}}-{{/with}}{{ring}}{{/with}}"));
<add> view.set('template', compile("{{#with first as |ring|}}{{ring}}-{{#with fifth as |ring|}}{{ring}}-{{#with ninth as |ring|}}{{ring}}-{{/with}}{{ring}}-{{/with}}{{ring}}{{/with}}"));
<ide> view.set('context', {
<ide> first: 'Limbo',
<ide> fifth: 'Wrath',
<ide> QUnit.module("Handlebars {{#with}} globals helper [DEPRECATED]", {
<ide>
<ide> lookup.Foo = { bar: 'baz' };
<ide> view = EmberView.create({
<del> template: compile("{{#with Foo.bar as qux}}{{qux}}{{/with}}")
<add> template: compile("{{#with Foo.bar as |qux|}}{{qux}}{{/with}}")
<ide> });
<ide> },
<ide>
<ide> QUnit.test("it should support #with Foo.bar as qux [DEPRECATED]", function() {
<ide> equal(view.$().text(), "updated", "should update");
<ide> });
<ide>
<del>QUnit.module("Handlebars {{#with keyword as foo}}");
<add>QUnit.module("Handlebars {{#with keyword as |foo|}}");
<ide>
<ide> QUnit.test("it should support #with view as foo", function() {
<ide> var view = EmberView.create({
<del> template: compile("{{#with view as myView}}{{myView.name}}{{/with}}"),
<add> template: compile("{{#with view as |myView|}}{{myView.name}}{{/with}}"),
<ide> name: "Sonics"
<ide> });
<ide>
<ide> QUnit.test("it should support #with view as foo", function() {
<ide>
<ide> QUnit.test("it should support #with name as food, then #with foo as bar", function() {
<ide> var view = EmberView.create({
<del> template: compile("{{#with name as foo}}{{#with foo as bar}}{{bar}}{{/with}}{{/with}}"),
<add> template: compile("{{#with name as |foo|}}{{#with foo as |bar|}}{{bar}}{{/with}}{{/with}}"),
<ide> context: { name: "caterpillar" }
<ide> });
<ide>
<ide> QUnit.test("it should support #with name as food, then #with foo as bar", functi
<ide> runDestroy(view);
<ide> });
<ide>
<del>QUnit.module("Handlebars {{#with this as foo}}");
<add>QUnit.module("Handlebars {{#with this as |foo|}}");
<ide>
<ide> QUnit.test("it should support #with this as qux", function() {
<ide> var view = EmberView.create({
<del> template: compile("{{#with this as person}}{{person.name}}{{/with}}"),
<add> template: compile("{{#with this as |person|}}{{person.name}}{{/with}}"),
<ide> controller: EmberObject.create({ name: "Los Pivots" })
<ide> });
<ide>
<ide> QUnit.test("it should wrap keyword with object controller [DEPRECATED]", functio
<ide>
<ide> view = EmberView.create({
<ide> container: container,
<del> template: compile('{{#with person as steve controller="person"}}{{name}} - {{steve.name}}{{/with}}'),
<add> template: compile('{{#with person controller="person" as |steve|}}{{name}} - {{steve.name}}{{/with}}'),
<ide> controller: parentController
<ide> });
<ide>
<ide> QUnit.test("destroys the controller generated with {{with foo as bar controller=
<ide>
<ide> view = EmberView.create({
<ide> container: container,
<del> template: compile('{{#with person as steve controller="person"}}{{controllerName}}{{/with}}'),
<add> template: compile('{{#with person controller="person" as |steve|}}{{controllerName}}{{/with}}'),
<ide> controller: parentController
<ide> });
<ide>
<ide> QUnit.module("{{#with}} helper binding to view keyword", {
<ide> Ember.lookup = lookup = { Ember: Ember };
<ide>
<ide> view = EmberView.create({
<del> template: compile("We have: {{#with view.thing as fromView}}{{fromView.name}} and {{fromContext.name}}{{/with}}"),
<add> template: compile("We have: {{#with view.thing as |fromView|}}{{fromView.name}} and {{fromContext.name}}{{/with}}"),
<ide> thing: { name: 'this is from the view' },
<ide> context: {
<ide> fromContext: { name: "this is from the context" }
<ide><path>packages/ember-htmlbars/tests/helpers/yield_test.js
<ide> QUnit.test("outer keyword doesn't mask inner component property", function () {
<ide>
<ide> view = EmberView.create({
<ide> controller: { boundText: "outer", component: component },
<del> template: compile('{{#with boundText as item}}{{#view component}}{{item}}{{/view}}{{/with}}')
<add> template: compile('{{#with boundText as |item|}}{{#view component}}{{item}}{{/view}}{{/with}}')
<ide> });
<ide>
<ide> runAppend(view);
<ide> QUnit.test("outer keyword doesn't mask inner component property", function () {
<ide> QUnit.test("inner keyword doesn't mask yield property", function() {
<ide> var component = Component.extend({
<ide> boundText: "inner",
<del> layout: compile("{{#with boundText as item}}<p>{{item}}</p><p>{{yield}}</p>{{/with}}")
<add> layout: compile("{{#with boundText as |item|}}<p>{{item}}</p><p>{{yield}}</p>{{/with}}")
<ide> });
<ide>
<ide> view = EmberView.create({
<ide> QUnit.test("can bind a keyword to a component and use it in yield", function() {
<ide>
<ide> view = EmberView.create({
<ide> controller: { boundText: "outer", component: component },
<del> template: compile('{{#with boundText as item}}{{#view component content=item}}{{item}}{{/view}}{{/with}}')
<add> template: compile('{{#with boundText as |item|}}{{#view component content=item}}{{item}}{{/view}}{{/with}}')
<ide> });
<ide>
<ide> runAppend(view);
<ide><path>packages/ember-htmlbars/tests/integration/with_view_test.js
<ide> QUnit.test('bindings can be `this`, in which case they *are* the current context
<ide>
<ide> QUnit.test('child views can be inserted inside a bind block', function() {
<ide> registry.register('template:nester', compile('<h1 id="hello-world">Hello {{world}}</h1>{{view view.bqView}}'));
<del> registry.register('template:nested', compile('<div id="child-view">Goodbye {{#with content as thing}}{{thing.blah}} {{view view.otherView}}{{/with}} {{world}}</div>'));
<add> registry.register('template:nested', compile('<div id="child-view">Goodbye {{#with content as |thing|}}{{thing.blah}} {{view view.otherView}}{{/with}} {{world}}</div>'));
<ide> registry.register('template:other', compile('cruel'));
<ide>
<ide> var context = {
<ide> QUnit.test('child views can be inserted inside a bind block', function() {
<ide> });
<ide>
<ide> QUnit.test('views render their template in the context of the parent view\'s context', function() {
<del> registry.register('template:parent', compile('<h1>{{#with content as person}}{{#view}}{{person.firstName}} {{person.lastName}}{{/view}}{{/with}}</h1>'));
<add> registry.register('template:parent', compile('<h1>{{#with content as |person|}}{{#view}}{{person.firstName}} {{person.lastName}}{{/view}}{{/with}}</h1>'));
<ide>
<ide> var context = {
<ide> content: {
<ide> QUnit.test('views render their template in the context of the parent view\'s con
<ide> });
<ide>
<ide> QUnit.test('views make a view keyword available that allows template to reference view context', function() {
<del> registry.register('template:parent', compile('<h1>{{#with view.content as person}}{{#view person.subview}}{{view.firstName}} {{person.lastName}}{{/view}}{{/with}}</h1>'));
<add> registry.register('template:parent', compile('<h1>{{#with view.content as |person|}}{{#view person.subview}}{{view.firstName}} {{person.lastName}}{{/view}}{{/with}}</h1>'));
<ide>
<ide> view = EmberView.create({
<ide> container: container,
<ide><path>packages/ember-routing-htmlbars/tests/helpers/action_test.js
<ide> QUnit.test("should work properly in an #each block", function() {
<ide> ok(eventHandlerWasCalled, "The event handler was called");
<ide> });
<ide>
<del>QUnit.test("should work properly in a {{#with foo as bar}} block", function() {
<add>QUnit.test("should work properly in a {{#with foo as |bar|}} block", function() {
<ide> var eventHandlerWasCalled = false;
<ide>
<ide> var controller = EmberController.extend({
<ide> QUnit.test("should work properly in a {{#with foo as bar}} block", function() {
<ide> view = EmberView.create({
<ide> controller: controller,
<ide> something: { ohai: 'there' },
<del> template: compile('{{#with view.something as somethingElse}}<a href="#" {{action "edit"}}>click me</a>{{/with}}')
<add> template: compile('{{#with view.something as |somethingElse|}}<a href="#" {{action "edit"}}>click me</a>{{/with}}')
<ide> });
<ide>
<ide> runAppend(view);
<ide><path>packages/ember-template-compiler/lib/plugins/transform-with-as-to-hash.js
<ide> TransformWithAsToHash.prototype.transform = function TransformWithAsToHash_trans
<ide> throw new Error('You cannot use keyword (`{{with foo as bar}}`) and block params (`{{with foo as |bar|}}`) at the same time.');
<ide> }
<ide>
<add> Ember.deprecate(
<add> "Using {{with}} without block syntax is deprecated. " +
<add> "Please use standard block form (`{{#with foo as |bar|}}`) instead.",
<add> false,
<add> { url: "http://emberjs.com/deprecations/v1.x/#toc_code-as-code-sytnax-for-code-with-code" }
<add> );
<add>
<ide> var removedParams = node.sexpr.params.splice(1, 2);
<ide> var keyword = removedParams[1].original;
<ide> node.program.blockParams = [keyword]; | 8 |
Text | Text | add rafael to the tsc | e4b1be63c10729e3664caa7cf94afd868a3d0ea1 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Matteo Collina** <<matteo.collina@gmail.com>> (he/him)
<ide> * [mhdawson](https://github.com/mhdawson) -
<ide> **Michael Dawson** <<midawson@redhat.com>> (he/him)
<add>* [RafaelGSS](https://github.com/RafaelGSS) -
<add> **Rafael Gonzaga** <<rafael.nunu@hotmail.com>> (he/him)
<ide> * [RaisinTen](https://github.com/RaisinTen) -
<ide> **Darshan Sen** <<raisinten@gmail.com>> (he/him)
<ide> * [richardlau](https://github.com/richardlau) - | 1 |
Text | Text | fix the link to advanced features | ea2d8691437e09c2efc379fae57ca61ca5223709 | <ide><path>docs/recipes/ConfiguringYourStore.md
<ide> The only extra change here is that we have encapsulated our app's rendering into
<ide>
<ide> ## Next Steps
<ide>
<del>Now that you know how to encapsulate your store configuration to make it easier to maintain, you can [learn more about the advanced features Redux provides](../basics/README.md), or take a closer look at some of the [extensions available in the Redux ecosystem](../introduction/ecosystem).
<add>Now that you know how to encapsulate your store configuration to make it easier to maintain, you can [learn more about the advanced features Redux provides](../advanced/README.md), or take a closer look at some of the [extensions available in the Redux ecosystem](../introduction/ecosystem). | 1 |
Text | Text | fix translation problems that difficult reading | e9fae2dc10e20aad799388bf476ec2386469bc51 | <ide><path>curriculum/challenges/portuguese/01-responsive-web-design/applied-accessibility/avoid-colorblindness-issues-by-using-sufficient-contrast.portuguese.md
<ide> videoUrl: ''
<ide> localeTitle: Evitar problemas de daltonismo usando o contraste suficiente
<ide> ---
<ide>
<del>## Description
<del><section id="description"> A cor é uma grande parte do design visual, mas seu uso introduz dois problemas de acessibilidade. Primeiro, a cor sozinha não deve ser usada como a única maneira de transmitir informações importantes porque os usuários de leitores de tela não a verão. Segundo, as cores do primeiro plano e do plano de fundo precisam de contraste suficiente para que os usuários daltônicos possam distingui-las. Desafios anteriores cobertos com alternativas de texto para abordar a primeira questão. O último desafio introduziu ferramentas de verificação de contraste para ajudar no segundo. A taxa de contraste recomendada por WCAG de 4.5: 1 aplica-se ao uso de cores, bem como a combinações em escala de cinza. Usuários daltônicos têm dificuldade em distinguir algumas cores de outros - geralmente em matiz, mas às vezes leveza também. Você pode se lembrar que a taxa de contraste é calculada usando os valores relativos de luminância (ou luminosidade) das cores de primeiro plano e de fundo. Na prática, a proporção de 4,5: 1 pode ser alcançada escurecendo a cor mais escura e iluminando a mais clara com o auxílio de um verificador de contraste de cores. As cores mais escuras na roda de cores são consideradas azuis, violetas, magentas e vermelhas, enquanto as cores mais claras são laranjas, amarelos, verdes e azuis-verdes. </section>
<add>## Descrição
<add><section id="description"> A cor é uma grande parte do design visual, mas seu uso introduz dois problemas de acessibilidade. Primeiro, a cor sozinha não deve ser usada como a única maneira de transmitir informações importantes porque os usuários de leitores de tela não a verão. Segundo, as cores do primeiro plano e do plano de fundo precisam de contraste suficiente para que os usuários daltônicos possam distingui-las. Desafios anteriores mostraram alternativas de texto para abordar o primeiro problema. O último desafio introduziu ferramentas de verificação de contraste para ajudar no segundo. A WCAG recomenda uma relação de taxa de contraste de 4.5: 1 aplicada ao uso das cores, bem como a combinações de escalas de cinza. Usuários daltônicos têm dificuldade em distinguir algumas cores de outras - geralmente em tonalidade, mas às vezes em luminosidade também. Você pode se lembrar que a taxa de contraste é calculada usando os valores relativos de luminância (ou luminosidade) das cores de primeiro plano e de fundo. Na prática, a proporção de 4,5: 1 pode ser alcançada escurecendo a cor mais escura e clareando a mais clara com o auxílio de um verificador de contraste de cores. As cores mais escuras na roda de cores são consideradas azuis, violetas, magentas e vermelhas, enquanto as cores mais claras são laranjas, amarelos, verdes e azuis-esverdeados. </section>
<ide>
<del>## Instructions
<del><section id="instructions"> Cat Camper está experimentando com o uso de cores para seu texto blog e fundo, mas sua combinação atual de um esverdeada <code>background-color</code> com texto marrom <code>color</code> tem um 2.5: 1 razão de contraste. Você pode ajustar facilmente a leveza das cores desde que ele as declarou usando a propriedade CSS <code>hsl()</code> (que significa matiz, saturação, luminosidade) alterando o terceiro argumento. Aumente o valor de luminosidade da <code>background-color</code> de 35% para 55% e diminua o valor de luminosidade de <code>color</code> de 20% para 15%. Isso melhora o contraste para 5.9: 1. </section>
<add>## Instruções
<add><section id="instructions"> Cat Camper está experimentando o uso de cores para o texto de seu blog e fundo, mas sua combinação atual de um <code>background-color</code> esverdeado com text <code>color</code> marrom tem uma relação de contraste de 2.5: 1. Você pode ajustar facilmente a luminosidade das cores desde que ele as declarou usando a propriedade CSS <code>hsl()</code> (que significa matiz, saturação, luminosidade) alterando o terceiro argumento. Aumente o valor de luminosidade da <code>background-color</code> de 35% para 55% e diminua o valor de luminosidade de <code>color</code> de 20% para 15%. Isso melhora o contraste para 5.9: 1. </section>
<ide>
<del>## Tests
<add>## Testes
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<ide>
<ide> </section>
<ide>
<del>## Challenge Seed
<add>## Desafio
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='html-seed'>
<ide> tests:
<ide>
<ide> </section>
<ide>
<del>## Solution
<add>## Solução
<ide> <section id='solution'>
<ide>
<ide> ```js | 1 |
Go | Go | add virtual-ip of an endpoint as a secondary ip | f0292e04b8333c9bd88e3a9c1e3965853b61158b | <ide><path>libnetwork/osl/interface_linux.go
<ide> type nwIface struct {
<ide> mac net.HardwareAddr
<ide> address *net.IPNet
<ide> addressIPv6 *net.IPNet
<add> ipAliases []*net.IPNet
<ide> llAddrs []*net.IPNet
<ide> routes []*net.IPNet
<ide> bridge bool
<ide> func (i *nwIface) LinkLocalAddresses() []*net.IPNet {
<ide> return i.llAddrs
<ide> }
<ide>
<add>func (i *nwIface) IPAliases() []*net.IPNet {
<add> i.Lock()
<add> defer i.Unlock()
<add>
<add> return i.ipAliases
<add>}
<add>
<ide> func (i *nwIface) Routes() []*net.IPNet {
<ide> i.Lock()
<ide> defer i.Unlock()
<ide> func configureInterface(nlh *netlink.Handle, iface netlink.Link, i *nwIface) err
<ide> {setInterfaceIPv6, fmt.Sprintf("error setting interface %q IPv6 to %v", ifaceName, i.AddressIPv6())},
<ide> {setInterfaceMaster, fmt.Sprintf("error setting interface %q master to %q", ifaceName, i.DstMaster())},
<ide> {setInterfaceLinkLocalIPs, fmt.Sprintf("error setting interface %q link local IPs to %v", ifaceName, i.LinkLocalAddresses())},
<add> {setInterfaceIPAliases, fmt.Sprintf("error setting interface %q IP Aliases to %v", ifaceName, i.IPAliases())},
<ide> }
<ide>
<ide> for _, config := range ifaceConfigurators {
<ide> func setInterfaceLinkLocalIPs(nlh *netlink.Handle, iface netlink.Link, i *nwIfac
<ide> return nil
<ide> }
<ide>
<add>func setInterfaceIPAliases(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
<add> for _, si := range i.IPAliases() {
<add> ipAddr := &netlink.Addr{IPNet: si}
<add> if err := nlh.AddrAdd(iface, ipAddr); err != nil {
<add> return err
<add> }
<add> }
<add> return nil
<add>}
<add>
<ide> func setInterfaceName(nlh *netlink.Handle, iface netlink.Link, i *nwIface) error {
<ide> return nlh.LinkSetName(iface, i.DstName())
<ide> }
<ide><path>libnetwork/osl/options_linux.go
<ide> func (n *networkNamespace) LinkLocalAddresses(list []*net.IPNet) IfaceOption {
<ide> }
<ide> }
<ide>
<add>func (n *networkNamespace) IPAliases(list []*net.IPNet) IfaceOption {
<add> return func(i *nwIface) {
<add> i.ipAliases = list
<add> }
<add>}
<add>
<ide> func (n *networkNamespace) Routes(routes []*net.IPNet) IfaceOption {
<ide> return func(i *nwIface) {
<ide> i.routes = routes
<ide><path>libnetwork/osl/sandbox.go
<ide> type IfaceOptionSetter interface {
<ide> // LinkLocalAddresses returns an option setter to set the link-local IP addresses.
<ide> LinkLocalAddresses([]*net.IPNet) IfaceOption
<ide>
<add> // IPAliases returns an option setter to set IP address Aliases
<add> IPAliases([]*net.IPNet) IfaceOption
<add>
<ide> // Master returns an option setter to set the master interface if any for this
<ide> // interface. The master interface name should refer to the srcname of a
<ide> // previously added interface of type bridge.
<ide> type Interface interface {
<ide> // LinkLocalAddresses returns the link-local IP addresses assigned to the interface.
<ide> LinkLocalAddresses() []*net.IPNet
<ide>
<add> // IPAliases returns the IP address aliases assigned to the interface.
<add> IPAliases() []*net.IPNet
<add>
<ide> // IP routes for the interface.
<ide> Routes() []*net.IPNet
<ide>
<ide><path>libnetwork/sandbox.go
<ide> func (sb *sandbox) restoreOslSandbox() error {
<ide> if len(i.llAddrs) != 0 {
<ide> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
<ide> }
<add> if len(ep.virtualIP) != 0 {
<add> vipAlias := &net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)}
<add> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().IPAliases([]*net.IPNet{vipAlias}))
<add> }
<ide> Ifaces[fmt.Sprintf("%s+%s", i.srcName, i.dstPrefix)] = ifaceOptions
<ide> if joinInfo != nil {
<ide> for _, r := range joinInfo.StaticRoutes {
<ide> func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
<ide> if len(i.llAddrs) != 0 {
<ide> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().LinkLocalAddresses(i.llAddrs))
<ide> }
<add> if len(ep.virtualIP) != 0 {
<add> vipAlias := &net.IPNet{IP: ep.virtualIP, Mask: net.CIDRMask(32, 32)}
<add> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().IPAliases([]*net.IPNet{vipAlias}))
<add> }
<ide> if i.mac != nil {
<ide> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().MacAddress(i.mac))
<ide> } | 4 |
Python | Python | relax required version for `python-telegram-bot` | ea7e64fd4bc5245725f9fff2121e21e7b2d7fa17 | <ide><path>setup.py
<ide> def get_sphinx_theme_version() -> str:
<ide> 'tableauserverclient',
<ide> ]
<ide> telegram = [
<del> 'python-telegram-bot==13.0',
<add> 'python-telegram-bot~=13.0',
<ide> ]
<ide> trino = ['trino']
<ide> vertica = [ | 1 |
Ruby | Ruby | fix javascript syntax in code comment [ci skip] | 8a13721b8cad5cabc2d26e509d49616dc187b9b1 | <ide><path>actionpack/lib/action_view/helpers/form_helper.rb
<ide> def label(object_name, method, content_or_options = nil, options = nil, &block)
<ide> # text_field(:post, :title, class: "create_input")
<ide> # # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />
<ide> #
<del> # text_field(:session, :user, onchange: "if $('#session_user').value == 'admin' { alert('Your login can not be admin!'); }")
<del> # # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange = "if $('#session_user').value == 'admin' { alert('Your login can not be admin!'); }"/>
<add> # text_field(:session, :user, onchange: "if ($('#session_user').val() === 'admin') { alert('Your login can not be admin!'); }")
<add> # # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange="if ($('#session_user').val() === 'admin') { alert('Your login can not be admin!'); }"/>
<ide> #
<ide> # text_field(:snippet, :code, size: 20, class: 'code_input')
<ide> # # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" />
<ide> def text_field(object_name, method, options = {})
<ide> # password_field(:account, :secret, class: "form_input", value: @account.secret)
<ide> # # => <input type="password" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
<ide> #
<del> # password_field(:user, :password, onchange: "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }")
<del> # # => <input type="password" id="user_password" name="user[password]" onchange = "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }"/>
<add> # password_field(:user, :password, onchange: "if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }")
<add> # # => <input type="password" id="user_password" name="user[password]" onchange="if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }"/>
<ide> #
<ide> # password_field(:account, :pin, size: 20, class: 'form_input')
<ide> # # => <input type="password" id="account_pin" name="account[pin]" size="20" class="form_input" /> | 1 |
Javascript | Javascript | remove unnecessary else | c00903be7ac91cd9cd29c265409eea96198b32c7 | <ide><path>src/ng/interpolate.js
<ide> function $InterpolateProvider() {
<ide> if (value) {
<ide> startSymbol = value;
<ide> return this;
<del> } else {
<del> return startSymbol;
<ide> }
<add> return startSymbol;
<ide> };
<ide>
<ide> /**
<ide> function $InterpolateProvider() {
<ide> if (value) {
<ide> endSymbol = value;
<ide> return this;
<del> } else {
<del> return endSymbol;
<ide> }
<add> return endSymbol;
<ide> };
<ide>
<ide> | 1 |
Javascript | Javascript | fix dynamic import from eval | 4ec02d5afdad4610b59fbc22ff2279e35120294e | <ide><path>lib/internal/modules/esm/loader.js
<ide> const defaultResolve = require('internal/modules/esm/default_resolve');
<ide> const createDynamicModule = require(
<ide> 'internal/modules/esm/create_dynamic_module');
<ide> const { translators } = require('internal/modules/esm/translators');
<del>const { ModuleWrap } = internalBinding('module_wrap');
<ide> const { getOptionValue } = require('internal/options');
<ide>
<ide> const debug = require('internal/util/debuglog').debuglog('esm');
<ide> class Loader {
<ide> source,
<ide> url = pathToFileURL(`${process.cwd()}/[eval${++this.evalIndex}]`).href
<ide> ) {
<del> const evalInstance = (url) => new ModuleWrap(url, undefined, source, 0, 0);
<add> const evalInstance = (url) => {
<add> const { ModuleWrap, callbackMap } = internalBinding('module_wrap');
<add> const module = new ModuleWrap(url, undefined, source, 0, 0);
<add> callbackMap.set(module, {
<add> importModuleDynamically: (specifier, { url }) => {
<add> return this.import(specifier, url);
<add> }
<add> });
<add>
<add> return module;
<add> };
<ide> const job = new ModuleJob(this, url, evalInstance, false, false);
<ide> this.moduleMap.set(url, job);
<ide> const { module, result } = await job.run();
<ide><path>lib/internal/process/execution.js
<ide> function evalModule(source, print) {
<ide> function evalScript(name, body, breakFirstLine, print) {
<ide> const CJSModule = require('internal/modules/cjs/loader').Module;
<ide> const { kVmBreakFirstLineSymbol } = require('internal/util');
<add> const { pathToFileURL } = require('url');
<ide>
<ide> const cwd = tryGetCwd();
<ide> const origModule = global.module; // Set e.g. when called from the REPL.
<ide>
<ide> const module = new CJSModule(name);
<ide> module.filename = path.join(cwd, name);
<ide> module.paths = CJSModule._nodeModulePaths(cwd);
<add>
<ide> global.kVmBreakFirstLineSymbol = kVmBreakFirstLineSymbol;
<add> global.asyncESM = require('internal/process/esm_loader');
<add>
<add> const baseUrl = pathToFileURL(module.filename).href;
<add>
<ide> const script = `
<ide> global.__filename = ${JSONStringify(name)};
<ide> global.exports = exports;
<ide> global.module = module;
<ide> global.__dirname = __dirname;
<ide> global.require = require;
<del> const { kVmBreakFirstLineSymbol } = global;
<add> const { kVmBreakFirstLineSymbol, asyncESM } = global;
<ide> delete global.kVmBreakFirstLineSymbol;
<add> delete global.asyncESM;
<ide> return require("vm").runInThisContext(
<ide> ${JSONStringify(body)}, {
<ide> filename: ${JSONStringify(name)},
<ide> displayErrors: true,
<del> [kVmBreakFirstLineSymbol]: ${!!breakFirstLine}
<add> [kVmBreakFirstLineSymbol]: ${!!breakFirstLine},
<add> async importModuleDynamically (specifier) {
<add> const loader = await asyncESM.ESMLoader;
<add> return loader.import(specifier, ${JSONStringify(baseUrl)});
<add> }
<ide> });\n`;
<ide> const result = module._compile(script, `${name}-wrapper`);
<ide> if (print) {
<ide><path>test/parallel/test-cli-eval.js
<ide> child.exec(
<ide> assert.ifError(err);
<ide> assert.strictEqual(stdout, '.mjs file\n');
<ide> }));
<add>
<add>
<add>// Assert that packages can be dynamic imported initial cwd-relative with --eval
<add>child.exec(
<add> `${nodejs} ${execOptions} ` +
<add> '--eval "process.chdir(\'..\');' +
<add> 'import(\'./test/fixtures/es-modules/mjs-file.mjs\')"',
<add> common.mustCall((err, stdout) => {
<add> assert.ifError(err);
<add> assert.strictEqual(stdout, '.mjs file\n');
<add> }));
<add>
<add>child.exec(
<add> `${nodejs} ` +
<add> '--eval "process.chdir(\'..\');' +
<add> 'import(\'./test/fixtures/es-modules/mjs-file.mjs\')"',
<add> common.mustCall((err, stdout) => {
<add> assert.ifError(err);
<add> assert.strictEqual(stdout, '.mjs file\n');
<add> })); | 3 |
PHP | PHP | register env command | 83bad25e26edf04891c1bee6de1b596c0ef94628 | <ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> public function register()
<ide> return new EnvironmentCommand;
<ide> });
<ide>
<del> $this->commands('command.changes');
<add> $this->commands('command.changes', 'command.environment');
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | exclude opera from toggle test, too (#863) | 5cfaef9ff9b121850f1e27afae6819023acadbf7 | <ide><path>src/event/eventTest.js
<ide> test("toggle(Function, Function) - add toggle event and fake a few clicks", func
<ide> fn2 = function(e) { count--; },
<ide> preventDefault = function(e) { e.preventDefault() },
<ide> link = $('#mark');
<del> if($.browser.msie)
<del> ok( false, "click() on link gets executed in IE, not intended behaviour!" );
<add> if($.browser.msie || $.browser.opera)
<add> ok( false, "click() on link gets executed in IE/Opera, not intended behaviour!" );
<ide> else
<ide> link.click(preventDefault).click().toggle(fn1, fn2).click().click().click().click().click();
<ide> ok( count == 1, "Check for toggle(fn, fn)" ); | 1 |
Ruby | Ruby | simplify value logic by always typecasting | 23750b4733e1d8e7ef334d70998258d1d2e2c6c8 | <ide><path>activerecord/lib/active_record/validations/uniqueness.rb
<ide> def build_relation(klass, table, attribute, value) #:nodoc:
<ide> end
<ide>
<ide> column = klass.columns_hash[attribute.to_s]
<del>
<del> if !value.nil? && column.text? && column.limit
<del> value = value.to_s[0, column.limit]
<del> else
<del> value = klass.connection.type_cast(value, column)
<del> end
<add> value = klass.connection.type_cast(value, column)
<add> value = value.to_s[0, column.limit] if value && column.limit && column.text?
<ide>
<ide> if !options[:case_sensitive] && value && column.text?
<ide> # will use SQL LOWER function before comparison, unless it detects a case insensitive collation
<del> relation = klass.connection.case_insensitive_comparison(table, attribute, column, value)
<add> klass.connection.case_insensitive_comparison(table, attribute, column, value)
<ide> else
<del> value = klass.connection.case_sensitive_modifier(value) unless value.nil?
<del> relation = table[attribute].eq(value)
<add> value = klass.connection.case_sensitive_modifier(value) unless value.nil?
<add> table[attribute].eq(value)
<ide> end
<del>
<del> relation
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | normalize the hash of transformations | 6be1446fc7f4b159097533562920662b85155113 | <ide><path>activestorage/app/models/active_storage/variation.rb
<ide> def encode(transformations)
<ide> end
<ide>
<ide> def initialize(transformations)
<del> @transformations = transformations
<add> @transformations = transformations.deep_symbolize_keys
<ide> end
<ide>
<ide> # Accepts a File object, performs the +transformations+ against it, and
<ide><path>activestorage/test/models/variant_test.rb
<ide> require "database/setup"
<ide>
<ide> class ActiveStorage::VariantTest < ActiveSupport::TestCase
<add> test "variations have the same key for different types of the same transformation" do
<add> blob = create_file_blob(filename: "racecar.jpg")
<add> variant_a = blob.variant(resize: "100x100")
<add> variant_b = blob.variant("resize" => "100x100")
<add>
<add> assert_equal variant_a.key, variant_b.key
<add> end
<add>
<ide> test "resized variation of JPEG blob" do
<ide> blob = create_file_blob(filename: "racecar.jpg")
<ide> variant = blob.variant(resize: "100x100").processed | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.