content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Ruby | Ruby | fix typo in the hook name | 029cbb35352ed79805da1b3a089e724b05bd2a80 | <ide><path>actionpack/lib/action_controller/test_case.rb
<ide> def build_response(klass)
<ide> include ActionDispatch::Assertions
<ide> class_attribute :_controller_class
<ide> setup :setup_controller_request_and_response
<del> ActiveSupport.run_load_hooks(:action_view_test_case, self)
<add> ActiveSupport.run_load_hooks(:action_controller_test_case, self)
<ide> end
<ide>
<ide> private | 1 |
Ruby | Ruby | change def to attr_reader + alias | 7b2ec381ca5ce88fe62a0a42183b3a5df63ee68b | <ide><path>actionpack/lib/action_dispatch/http/cache.rb
<ide> def fresh?(response)
<ide> end
<ide>
<ide> module Response
<del> attr_reader :cache_control
<add> attr_reader :cache_control, :etag
<add> alias :etag? :etag
<ide>
<ide> def initialize(*)
<ide> status, header, body = super
<ide> def last_modified=(utc_time)
<ide> headers['Last-Modified'] = utc_time.httpdate
<ide> end
<ide>
<del> def etag
<del> @etag
<del> end
<del>
<del> def etag?
<del> @etag
<del> end
<del>
<ide> def etag=(etag)
<ide> key = ActiveSupport::Cache.expand_cache_key(etag)
<ide> @etag = self["ETag"] = %("#{Digest::MD5.hexdigest(key)}")
<ide> def set_conditional_cache_control!
<ide>
<ide> if control.empty?
<ide> headers["Cache-Control"] = DEFAULT_CACHE_CONTROL
<del> elsif @cache_control[:no_cache]
<add> elsif control[:no_cache]
<ide> headers["Cache-Control"] = "no-cache"
<ide> else
<ide> extras = control[:extras] | 1 |
Text | Text | add changelog entry | 7aa4b7dc6bd6ecea1f5009c5549ea69dd59d96d4 | <ide><path>activesupport/CHANGELOG.md
<add>* Fix `to_param` behavior when there are nested empty hashes.
<add>
<add> Before:
<add>
<add> params = {c: 3, d: {}}.to_param # => "&c=3"
<add>
<add> After:
<add>
<add> params = {c: 3, d: {}}.to_param # => "c=3&d="
<add>
<add> Fixes #13892.
<add>
<add> *Hincu Petru*
<add>
<ide> * Deprecate custom `BigDecimal` serialization
<ide>
<ide> Deprecate the custom `BigDecimal` serialization that is included when requiring | 1 |
PHP | PHP | fix types of console\command properties | 306208394bf05f9acebce3663c3cfb7e3b1ac21c | <ide><path>src/Illuminate/Console/Command.php
<ide> class Command extends SymfonyCommand
<ide> /**
<ide> * The console command description.
<ide> *
<del> * @var string|null
<add> * @var string
<ide> */
<ide> protected $description;
<ide>
<ide> /**
<ide> * The console command help text.
<ide> *
<del> * @var string|null
<add> * @var string
<ide> */
<ide> protected $help;
<ide> | 1 |
Javascript | Javascript | convert more tests to use emittereventpromise | 42fb2cc55fc07b99243bb2d22b4e7d1634aeb17e | <ide><path>spec/main-process/atom-application.test.js
<ide> describe('AtomApplication', function () {
<ide>
<ide> const atomApplication = buildAtomApplication()
<ide> const window1 = atomApplication.launch(parseCommandLine([path.join(dirAPath, 'new-file')]))
<add> await emitterEventPromise(window1, 'window:locations-opened')
<ide> await focusWindow(window1)
<ide>
<ide> let activeEditorPath
<ide> describe('AtomApplication', function () {
<ide>
<ide> // Opens new windows when opening directories
<ide> const window2 = atomApplication.launch(parseCommandLine([dirCPath]))
<add> await emitterEventPromise(window2, 'window:locations-opened')
<ide> assert.notEqual(window2, window1)
<ide> await focusWindow(window2)
<ide> assert.deepEqual(await getTreeViewRootDirectories(window2), [dirCPath]) | 1 |
Text | Text | add download links to the latest version | 0579fbb7415836728aff0595cf15ec44ac244f6c | <ide><path>README.md
<ide>
<ide> ## Installation
<ide>
<del>To download a zip, go to the Chart.js on Github
<add>You can download the latest version of [Chart.js on GitHub](https://github.com/chartjs/Chart.js/releases/latest) or just use these [Chart.js CDN](https://cdnjs.com/libraries/Chart.js) links.
<ide>
<ide> To install via npm / bower:
<ide>
<ide> ```bash
<ide> npm install chart.js --save
<ide> bower install Chart.js --save
<ide> ```
<del>CDN: https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js
<ide>
<ide> ## Documentation
<ide>
<ide><path>docs/00-Getting-Started.md
<ide> anchor: getting-started
<ide>
<ide> ### Download Chart.js
<ide>
<del>To download a zip, go to [Chart.js on Github](https://github.com/chartjs/Chart.js) and choose the version that is right for your application.
<del>* [Standard build](https://raw.githubusercontent.com/chartjs/Chart.js/master/dist/Chart.js) (~31kB gzipped)
<del>* [Bundled with Moment.js](https://raw.githubusercontent.com/chartjs/Chart.js/master/dist/Chart.bundle.js) (~45kB gzipped)
<del>* [CDN Versions](https://cdnjs.com/libraries/Chart.js)
<add>You can download the latest version of [Chart.js on GitHub](https://github.com/chartjs/Chart.js/releases/latest) or just use these [Chart.js CDN](https://cdnjs.com/libraries/Chart.js) links.
<add>
<add>### Installation
<ide>
<ide> To install via npm / bower:
<ide> | 2 |
Ruby | Ruby | add equality to all the things (that matter) | 6e638bba594b6164190d2a6fb96ffa07a20b11f3 | <ide><path>lib/arel/nodes/and.rb
<ide> def left
<ide> def right
<ide> children[1]
<ide> end
<add>
<add> def hash
<add> children.hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.children == other.children
<add> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/binary.rb
<ide> def initialize_copy other
<ide> @left = @left.clone if @left
<ide> @right = @right.clone if @right
<ide> end
<add>
<add> def hash
<add> [@left, @right].hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.left == other.left &&
<add> self.right == other.right
<add> end
<add> alias :== :eql?
<ide> end
<ide>
<ide> %w{
<ide><path>lib/arel/nodes/extract.rb
<ide> def as aliaz
<ide> self.alias = SqlLiteral.new(aliaz)
<ide> self
<ide> end
<add>
<add> def hash
<add> super ^ [@field, @alias].hash
<add> end
<add>
<add> def eql? other
<add> super &&
<add> self.field == other.field &&
<add> self.alias == other.alias
<add> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/false.rb
<ide> module Arel
<ide> module Nodes
<ide> class False < Arel::Nodes::Node
<add> def hash
<add> self.class.hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/function.rb
<ide> def as aliaz
<ide> self.alias = SqlLiteral.new(aliaz)
<ide> self
<ide> end
<add>
<add> def hash
<add> [@expressions, @alias, @distinct].hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.expressions == other.expressions &&
<add> self.alias == other.alias &&
<add> self.distinct == other.distinct
<add> end
<ide> end
<ide>
<ide> %w{
<ide><path>lib/arel/nodes/insert_statement.rb
<ide> def initialize_copy other
<ide> @columns = @columns.clone
<ide> @values = @values.clone if @values
<ide> end
<add>
<add> def hash
<add> [@relation, @columns, @values].hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.relation == other.relation &&
<add> self.columns == other.columns &&
<add> self.values == other.values
<add> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/named_function.rb
<ide> def initialize name, expr, aliaz = nil
<ide> super(expr, aliaz)
<ide> @name = name
<ide> end
<add>
<add> def hash
<add> super ^ @name.hash
<add> end
<add>
<add> def eql? other
<add> super && self.name == other.name
<add> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/select_core.rb
<ide> def initialize_copy other
<ide> @having = @having.clone if @having
<ide> @windows = @windows.clone
<ide> end
<add>
<add> def hash
<add> [
<add> @source, @top, @set_quantifier, @projections,
<add> @wheres, @groups, @having, @windows
<add> ].hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.source == other.source &&
<add> self.top == other.top &&
<add> self.set_quantifier == other.set_quantifier &&
<add> self.projections == other.projections &&
<add> self.wheres == other.wheres &&
<add> self.groups == other.groups &&
<add> self.having == other.having &&
<add> self.windows == other.windows
<add> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/select_statement.rb
<ide> class SelectStatement < Arel::Nodes::Node
<ide> attr_accessor :limit, :orders, :lock, :offset, :with
<ide>
<ide> def initialize cores = [SelectCore.new]
<del> #puts caller
<ide> @cores = cores
<ide> @orders = []
<ide> @limit = nil
<ide> def initialize_copy other
<ide> @cores = @cores.map { |x| x.clone }
<ide> @orders = @orders.map { |x| x.clone }
<ide> end
<add>
<add> def hash
<add> [@cores, @orders, @limit, @lock, @offset, @with].hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.cores == other.cores &&
<add> self.orders == other.orders &&
<add> self.limit == other.limit &&
<add> self.lock == other.lock &&
<add> self.offset == other.offset &&
<add> self.with == other.with
<add> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/terminal.rb
<ide> module Arel
<ide> module Nodes
<ide> class Distinct < Arel::Nodes::Node
<add> def hash
<add> self.class.hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/true.rb
<ide> module Arel
<ide> module Nodes
<ide> class True < Arel::Nodes::Node
<add> def hash
<add> self.class.hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/unary.rb
<ide> class Unary < Arel::Nodes::Node
<ide> def initialize expr
<ide> @expr = expr
<ide> end
<add>
<add> def hash
<add> @expr.hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.expr == other.expr
<add> end
<add> alias :== :eql?
<ide> end
<ide>
<ide> %w{
<ide><path>lib/arel/nodes/update_statement.rb
<ide> def initialize_copy other
<ide> @wheres = @wheres.clone
<ide> @values = @values.clone
<ide> end
<add>
<add> def hash
<add> [@relation, @wheres, @values, @orders, @limit, @key].hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.relation == other.relation &&
<add> self.wheres == other.wheres &&
<add> self.values == other.values &&
<add> self.orders == other.orders &&
<add> self.limit == other.limit &&
<add> self.key == other.key
<add> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/window.rb
<ide> def initialize_copy other
<ide> super
<ide> @orders = @orders.map { |x| x.clone }
<ide> end
<add>
<add> def hash
<add> [@orders, @framing].hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.orders == other.orders &&
<add> self.framing == other.framing
<add> end
<add> alias :== :eql?
<ide> end
<ide>
<ide> class NamedWindow < Window
<ide> def initialize_copy other
<ide> super
<ide> @name = other.name.clone
<ide> end
<add>
<add> def hash
<add> super ^ @name.hash
<add> end
<add>
<add> def eql? other
<add> super && self.name == other.name
<add> end
<add> alias :== :eql?
<ide> end
<ide>
<ide> class Rows < Unary
<ide> def initialize(expr = nil)
<ide> end
<ide> end
<ide>
<del> class CurrentRow < Arel::Nodes::Node; end
<add> class CurrentRow < Node
<add> def hash
<add> self.class.hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class
<add> end
<add> end
<ide>
<ide> class Preceding < Unary
<ide> def initialize(expr = nil)
<ide><path>lib/arel/table.rb
<ide> def insert_manager
<ide> InsertManager.new(@engine)
<ide> end
<ide>
<add> def hash
<add> [@name, @engine, @aliases, @table_alias].hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.name == other.name &&
<add> self.engine == other.engine &&
<add> self.aliases == other.aliases &&
<add> self.table_alias == other.table_alias
<add> end
<add> alias :== :eql?
<add>
<ide> private
<ide>
<ide> def attributes_for columns
<ide><path>test/nodes/test_and.rb
<add>require 'helper'
<add>
<add>module Arel
<add> module Nodes
<add> describe 'And' do
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> array = [And.new(['foo', 'bar']), And.new(['foo', 'bar'])]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [And.new(['foo', 'bar']), And.new(['foo', 'baz'])]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<add> end
<add> end
<add>end
<add>
<ide><path>test/nodes/test_as.rb
<ide> module Nodes
<ide> assert_kind_of Arel::Nodes::SqlLiteral, as.right
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> array = [As.new('foo', 'bar'), As.new('foo', 'bar')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [As.new('foo', 'bar'), As.new('foo', 'baz')]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_ascending.rb
<ide> def test_descending?
<ide> ascending = Ascending.new 'zomg'
<ide> assert !ascending.descending?
<ide> end
<add>
<add> def test_equality_with_same_ivars
<add> array = [Ascending.new('zomg'), Ascending.new('zomg')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> def test_inequality_with_different_ivars
<add> array = [Ascending.new('zomg'), Ascending.new('zomg!')]
<add> assert_equal 2, array.uniq.size
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_bin.rb
<ide> def test_mysql_to_sql
<ide> node = Arel::Nodes::Bin.new(Arel.sql('zomg'))
<ide> assert_equal 'BINARY zomg', viz.accept(node)
<ide> end
<add>
<add> def test_equality_with_same_ivars
<add> array = [Bin.new('zomg'), Bin.new('zomg')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> def test_inequality_with_different_ivars
<add> array = [Bin.new('zomg'), Bin.new('zomg!')]
<add> assert_equal 2, array.uniq.size
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_count.rb
<ide> }
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> array = [Arel::Nodes::Count.new('foo'), Arel::Nodes::Count.new('foo')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [Arel::Nodes::Count.new('foo'), Arel::Nodes::Count.new('foo!')]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide><path>test/nodes/test_delete_statement.rb
<ide> dolly.wheres.wont_be_same_as statement.wheres
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> statement1 = Arel::Nodes::DeleteStatement.new
<add> statement1.wheres = %w[a b c]
<add> statement2 = Arel::Nodes::DeleteStatement.new
<add> statement2.wheres = %w[a b c]
<add> array = [statement1, statement2]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> statement1 = Arel::Nodes::DeleteStatement.new
<add> statement1.wheres = %w[a b c]
<add> statement2 = Arel::Nodes::DeleteStatement.new
<add> statement2.wheres = %w[1 2 3]
<add> array = [statement1, statement2]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide><path>test/nodes/test_descending.rb
<ide> def test_descending?
<ide> descending = Descending.new 'zomg'
<ide> assert descending.descending?
<ide> end
<add>
<add> def test_equality_with_same_ivars
<add> array = [Descending.new('zomg'), Descending.new('zomg')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> def test_inequality_with_different_ivars
<add> array = [Descending.new('zomg'), Descending.new('zomg!')]
<add> assert_equal 2, array.uniq.size
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_distinct.rb
<add>require 'helper'
<add>
<add>module Arel
<add> module Nodes
<add> describe 'Distinct' do
<add> describe 'equality' do
<add> it 'is equal to other distinct nodes' do
<add> array = [Distinct.new, Distinct.new]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with other nodes' do
<add> array = [Distinct.new, Node.new]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<add> end
<add> end
<add>end
<add>
<ide><path>test/nodes/test_equality.rb
<ide> def quote_table_name(*args) @quote_count += 1; super; end
<ide> node.right.must_equal right
<ide> end
<ide> end
<add>
<add> it 'is equal with equal ivars' do
<add> array = [Equality.new('foo', 'bar'), Equality.new('foo', 'bar')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [Equality.new('foo', 'bar'), Equality.new('foo', 'baz')]
<add> assert_equal 2, array.uniq.size
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_extract.rb
<ide> }
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> table = Arel::Table.new :users
<add> array = [table[:attr].extract('foo'), table[:attr].extract('foo')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> table = Arel::Table.new :users
<add> array = [table[:attr].extract('foo'), table[:attr].extract('bar')]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide><path>test/nodes/test_false.rb
<add>require 'helper'
<add>
<add>module Arel
<add> module Nodes
<add> describe 'False' do
<add> describe 'equality' do
<add> it 'is equal to other false nodes' do
<add> array = [False.new, False.new]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with other nodes' do
<add> array = [False.new, Node.new]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<add> end
<add> end
<add>end
<add>
<ide><path>test/nodes/test_grouping.rb
<ide> module Nodes
<ide> grouping = Grouping.new('foo')
<ide> grouping.eq('foo').to_sql.must_be_like %q{('foo') = 'foo'}
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> array = [Grouping.new('foo'), Grouping.new('foo')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [Grouping.new('foo'), Grouping.new('bar')]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_infix_operation.rb
<ide> def test_opertaion_ordering
<ide> assert_equal operation, ordering.expr
<ide> assert ordering.descending?
<ide> end
<add>
<add> def test_equality_with_same_ivars
<add> array = [InfixOperation.new(:+, 1, 2), InfixOperation.new(:+, 1, 2)]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> def test_inequality_with_different_ivars
<add> array = [InfixOperation.new(:+, 1, 2), InfixOperation.new(:+, 1, 3)]
<add> assert_equal 2, array.uniq.size
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_insert_statement.rb
<ide> dolly.values.wont_be_same_as statement.values
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> statement1 = Arel::Nodes::InsertStatement.new
<add> statement1.columns = %w[a b c]
<add> statement1.values = %w[x y z]
<add> statement2 = Arel::Nodes::InsertStatement.new
<add> statement2.columns = %w[a b c]
<add> statement2.values = %w[x y z]
<add> array = [statement1, statement2]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> statement1 = Arel::Nodes::InsertStatement.new
<add> statement1.columns = %w[a b c]
<add> statement1.values = %w[x y z]
<add> statement2 = Arel::Nodes::InsertStatement.new
<add> statement2.columns = %w[a b c]
<add> statement2.values = %w[1 2 3]
<add> array = [statement1, statement2]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide><path>test/nodes/test_named_function.rb
<ide> def test_construct_with_alias
<ide> assert_kind_of SqlLiteral, function.alias
<ide> assert_equal 'wth', function.alias
<ide> end
<add>
<add> def test_equality_with_same_ivars
<add> array = [
<add> NamedFunction.new('omg', 'zomg', 'wth'),
<add> NamedFunction.new('omg', 'zomg', 'wth')
<add> ]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> def test_inequality_with_different_ivars
<add> array = [
<add> NamedFunction.new('omg', 'zomg', 'wth'),
<add> NamedFunction.new('zomg', 'zomg', 'wth')
<add> ]
<add> assert_equal 2, array.uniq.size
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_not.rb
<ide> module Nodes
<ide> node.expr.must_equal expr
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> array = [Not.new('foo'), Not.new('foo')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [Not.new('foo'), Not.new('baz')]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_or.rb
<ide> module Nodes
<ide> oror.expr.right.must_equal right
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> array = [Or.new('foo', 'bar'), Or.new('foo', 'bar')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [Or.new('foo', 'bar'), Or.new('foo', 'baz')]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_over.rb
<ide> }
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> array = [
<add> Arel::Nodes::Over.new('foo', 'bar'),
<add> Arel::Nodes::Over.new('foo', 'bar')
<add> ]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [
<add> Arel::Nodes::Over.new('foo', 'bar'),
<add> Arel::Nodes::Over.new('foo', 'baz')
<add> ]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide><path>test/nodes/test_select_core.rb
<ide> def test_set_quantifier
<ide> viz = Arel::Visitors::ToSql.new Table.engine.connection_pool
<ide> assert_match 'DISTINCT', viz.accept(core)
<ide> end
<add>
<add> def test_equality_with_same_ivars
<add> core1 = SelectCore.new
<add> core1.froms = %w[a b c]
<add> core1.projections = %w[d e f]
<add> core1.wheres = %w[g h i]
<add> core1.groups = %w[j k l]
<add> core1.windows = %w[m n o]
<add> core1.having = %w[p q r]
<add> core2 = SelectCore.new
<add> core2.froms = %w[a b c]
<add> core2.projections = %w[d e f]
<add> core2.wheres = %w[g h i]
<add> core2.groups = %w[j k l]
<add> core2.windows = %w[m n o]
<add> core2.having = %w[p q r]
<add> array = [core1, core2]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> def test_inequality_with_different_ivars
<add> core1 = SelectCore.new
<add> core1.froms = %w[a b c]
<add> core1.projections = %w[d e f]
<add> core1.wheres = %w[g h i]
<add> core1.groups = %w[j k l]
<add> core1.windows = %w[m n o]
<add> core1.having = %w[p q r]
<add> core2 = SelectCore.new
<add> core2.froms = %w[a b c]
<add> core2.projections = %w[d e f]
<add> core2.wheres = %w[g h i]
<add> core2.groups = %w[j k l]
<add> core2.windows = %w[m n o]
<add> core2.having = %w[l o l]
<add> array = [core1, core2]
<add> assert_equal 2, array.uniq.size
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_select_statement.rb
<ide> dolly.cores.wont_be_same_as statement.cores
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> statement1 = Arel::Nodes::SelectStatement.new %w[a b c]
<add> statement1.offset = 1
<add> statement1.limit = 2
<add> statement1.lock = false
<add> statement1.orders = %w[x y z]
<add> statement1.with = 'zomg'
<add> statement2 = Arel::Nodes::SelectStatement.new %w[a b c]
<add> statement2.offset = 1
<add> statement2.limit = 2
<add> statement2.lock = false
<add> statement2.orders = %w[x y z]
<add> statement2.with = 'zomg'
<add> array = [statement1, statement2]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> statement1 = Arel::Nodes::SelectStatement.new %w[a b c]
<add> statement1.offset = 1
<add> statement1.limit = 2
<add> statement1.lock = false
<add> statement1.orders = %w[x y z]
<add> statement1.with = 'zomg'
<add> statement2 = Arel::Nodes::SelectStatement.new %w[a b c]
<add> statement2.offset = 1
<add> statement2.limit = 2
<add> statement2.lock = false
<add> statement2.orders = %w[x y z]
<add> statement2.with = 'wth'
<add> array = [statement1, statement2]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide><path>test/nodes/test_sql_literal.rb
<ide> module Nodes
<ide> node = SqlLiteral.new('foo').eq(1)
<ide> @visitor.accept(node).must_be_like %{ foo = 1 }
<ide> end
<add>
<add> it 'is equal with equal contents' do
<add> array = [SqlLiteral.new('foo'), SqlLiteral.new('foo')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different contents' do
<add> array = [SqlLiteral.new('foo'), SqlLiteral.new('bar')]
<add> assert_equal 2, array.uniq.size
<add> end
<ide> end
<ide>
<ide> describe 'grouped "or" equality' do
<ide><path>test/nodes/test_sum.rb
<ide> }
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> array = [Arel::Nodes::Sum.new('foo'), Arel::Nodes::Sum.new('foo')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [Arel::Nodes::Sum.new('foo'), Arel::Nodes::Sum.new('foo!')]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide><path>test/nodes/test_table_alias.rb
<ide> module Arel
<ide> module Nodes
<ide> describe 'table alias' do
<ide> it 'has an #engine which delegates to the relation' do
<del> engine = Object.new
<del> relation = OpenStruct.new(:engine => engine)
<add> engine = 'vroom'
<add> relation = Table.new(:users, engine)
<ide>
<ide> node = TableAlias.new relation, :foo
<ide> node.engine.must_equal engine
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> relation1 = Table.new(:users, 'vroom')
<add> node1 = TableAlias.new relation1, :foo
<add> relation2 = Table.new(:users, 'vroom')
<add> node2 = TableAlias.new relation2, :foo
<add> array = [node1, node2]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> relation1 = Table.new(:users, 'vroom')
<add> node1 = TableAlias.new relation1, :foo
<add> relation2 = Table.new(:users, 'vroom')
<add> node2 = TableAlias.new relation2, :bar
<add> array = [node1, node2]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>test/nodes/test_true.rb
<add>require 'helper'
<add>
<add>module Arel
<add> module Nodes
<add> describe 'True' do
<add> describe 'equality' do
<add> it 'is equal to other true nodes' do
<add> array = [True.new, True.new]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with other nodes' do
<add> array = [True.new, Node.new]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<add> end
<add> end
<add>end
<add>
<add>
<ide><path>test/nodes/test_update_statement.rb
<ide> dolly.values.wont_be_same_as statement.values
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> statement1 = Arel::Nodes::UpdateStatement.new
<add> statement1.relation = 'zomg'
<add> statement1.wheres = 2
<add> statement1.values = false
<add> statement1.orders = %w[x y z]
<add> statement1.limit = 42
<add> statement1.key = 'zomg'
<add> statement2 = Arel::Nodes::UpdateStatement.new
<add> statement2.relation = 'zomg'
<add> statement2.wheres = 2
<add> statement2.values = false
<add> statement2.orders = %w[x y z]
<add> statement2.limit = 42
<add> statement2.key = 'zomg'
<add> array = [statement1, statement2]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> statement1 = Arel::Nodes::UpdateStatement.new
<add> statement1.relation = 'zomg'
<add> statement1.wheres = 2
<add> statement1.values = false
<add> statement1.orders = %w[x y z]
<add> statement1.limit = 42
<add> statement1.key = 'zomg'
<add> statement2 = Arel::Nodes::UpdateStatement.new
<add> statement2.relation = 'zomg'
<add> statement2.wheres = 2
<add> statement2.values = false
<add> statement2.orders = %w[x y z]
<add> statement2.limit = 42
<add> statement2.key = 'wth'
<add> array = [statement1, statement2]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide><path>test/nodes/test_window.rb
<add>require 'helper'
<add>
<add>module Arel
<add> module Nodes
<add> describe 'Window' do
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> window1 = Window.new
<add> window1.orders = [1, 2]
<add> window1.frame 3
<add> window2 = Window.new
<add> window2.orders = [1, 2]
<add> window2.frame 3
<add> array = [window1, window2]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> window1 = Window.new
<add> window1.orders = [1, 2]
<add> window1.frame 3
<add> window2 = Window.new
<add> window2.orders = [1, 2]
<add> window2.frame 4
<add> array = [window1, window2]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<add> end
<add>
<add> describe 'NamedWindow' do
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> window1 = NamedWindow.new 'foo'
<add> window1.orders = [1, 2]
<add> window1.frame 3
<add> window2 = NamedWindow.new 'foo'
<add> window2.orders = [1, 2]
<add> window2.frame 3
<add> array = [window1, window2]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> window1 = NamedWindow.new 'foo'
<add> window1.orders = [1, 2]
<add> window1.frame 3
<add> window2 = NamedWindow.new 'bar'
<add> window2.orders = [1, 2]
<add> window2.frame 3
<add> array = [window1, window2]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<add> end
<add>
<add> describe 'CurrentRow' do
<add> describe 'equality' do
<add> it 'is equal to other current row nodes' do
<add> array = [CurrentRow.new, CurrentRow.new]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with other nodes' do
<add> array = [CurrentRow.new, Node.new]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<add> end
<add> end
<add>end
<add>
<add>
<ide><path>test/test_attributes.rb
<ide> module Arel
<ide> assert_equal [attribute], node.expressions
<ide> end
<ide>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> array = [Attribute.new('foo', 'bar'), Attribute.new('foo', 'bar')]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> array = [Attribute.new('foo', 'bar'), Attribute.new('foo', 'baz')]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<add>
<ide> describe 'for' do
<ide> it 'deals with unknown column types' do
<ide> column = Struct.new(:type).new :crazy
<ide><path>test/test_table.rb
<ide> module Arel
<ide> end
<ide> end
<ide> end
<add>
<add> describe 'equality' do
<add> it 'is equal with equal ivars' do
<add> relation1 = Table.new(:users, 'vroom')
<add> relation1.aliases = %w[a b c]
<add> relation1.table_alias = 'zomg'
<add> relation2 = Table.new(:users, 'vroom')
<add> relation2.aliases = %w[a b c]
<add> relation2.table_alias = 'zomg'
<add> array = [relation1, relation2]
<add> assert_equal 1, array.uniq.size
<add> end
<add>
<add> it 'is not equal with different ivars' do
<add> relation1 = Table.new(:users, 'vroom')
<add> relation1.aliases = %w[a b c]
<add> relation1.table_alias = 'zomg'
<add> relation2 = Table.new(:users, 'vroom')
<add> relation2.aliases = %w[x y z]
<add> relation2.table_alias = 'zomg'
<add> array = [relation1, relation2]
<add> assert_equal 2, array.uniq.size
<add> end
<add> end
<ide> end
<ide> end | 43 |
PHP | PHP | fix error in fixturetask | dd335cb18393e833733730830d0ce03f32982ee1 | <ide><path>lib/Cake/Console/Command/Task/FixtureTask.php
<ide> public function bake($model, $useTable = false, $importOptions = array()) {
<ide> $schema = $this->_generateSchema($tableInfo);
<ide> }
<ide>
<del> if (!isset($importOptions['records']) && !isset($importOptions['fromTable'])) {
<add> if (empty($importOptions['records']) && !isset($importOptions['fromTable'])) {
<ide> $recordCount = 1;
<ide> if (isset($this->params['count'])) {
<ide> $recordCount = $this->params['count'];
<ide> }
<ide> $records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
<ide> }
<del> if (isset($this->params['records']) || isset($importOptions['fromTable'])) {
<add> if (!empty($this->params['records']) || isset($importOptions['fromTable'])) {
<ide> $records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
<ide> }
<ide> $out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import', 'fields')); | 1 |
Python | Python | drop erronous print statements | 8be4496586519f84b839b07efc74148a3559349e | <ide><path>tests/test_fields.py
<ide> def test_source(self):
<ide> class ExampleSerializer(serializers.Serializer):
<ide> example_field = serializers.CharField(source='other')
<ide> serializer = ExampleSerializer(data={'example_field': 'abc'})
<del> print serializer.is_valid()
<del> print serializer.data
<ide> assert serializer.is_valid()
<ide> assert serializer.validated_data == {'other': 'abc'}
<ide> | 1 |
Python | Python | add flag to build v8 with object_print | dd0c5228acaf5695f96809e50771ead3167b0f44 | <ide><path>configure.py
<ide> 'memory footprint, but also implies no just-in-time compilation ' +
<ide> 'support, thus much slower execution)')
<ide>
<add>parser.add_option('--v8-enable-object-print',
<add> action='store_true',
<add> dest='v8_enable_object_print',
<add> default=False,
<add> help='compile V8 with auxiliar functions for native debuggers')
<add>
<ide> parser.add_option('--node-builtin-modules-path',
<ide> action='store',
<ide> dest='node_builtin_modules_path',
<ide> def configure_v8(o):
<ide> o['variables']['v8_no_strict_aliasing'] = 1 # Work around compiler bugs.
<ide> o['variables']['v8_optimized_debug'] = 0 if options.v8_non_optimized_debug else 1
<ide> o['variables']['dcheck_always_on'] = 1 if options.v8_with_dchecks else 0
<add> o['variables']['v8_enable_object_print'] = 1 if options.v8_enable_object_print else 0
<ide> o['variables']['v8_random_seed'] = 0 # Use a random seed for hash tables.
<ide> o['variables']['v8_promise_internal_field_count'] = 1 # Add internal field to promises for async hooks.
<ide> o['variables']['v8_use_siphash'] = 0 if options.without_siphash else 1 | 1 |
PHP | PHP | support flush db on clusters | f4e8d5c1f1b72e24baac33c336233cca24230783 | <ide><path>src/Illuminate/Redis/Connections/PhpRedisConnection.php
<ide>
<ide> use Redis;
<ide> use Closure;
<add>use RedisCluster;
<ide> use Illuminate\Contracts\Redis\Connection as ConnectionContract;
<ide>
<ide> /**
<ide> public function createSubscription($channels, Closure $callback, $method = 'subs
<ide> //
<ide> }
<ide>
<add> /**
<add> * Flush the selected Redis database.
<add> *
<add> * @return void
<add> */
<add> public function flushdb()
<add> {
<add> if (! $this->client instanceof RedisCluster) {
<add> return $this->command('flushdb');
<add> }
<add>
<add> foreach ($this->client->_masters() as [$host, $port]) {
<add> tap(new Redis)->connect($host, $port)->flushDb();
<add> }
<add> }
<add>
<ide> /**
<ide> * Execute a raw command.
<ide> *
<ide><path>src/Illuminate/Redis/Connections/PredisConnection.php
<ide> namespace Illuminate\Redis\Connections;
<ide>
<ide> use Closure;
<add>use Predis\Command\ServerFlushDatabase;
<add>use Predis\Connection\Aggregate\PredisCluster;
<ide> use Illuminate\Contracts\Redis\Connection as ConnectionContract;
<ide>
<ide> /**
<ide> public function createSubscription($channels, Closure $callback, $method = 'subs
<ide>
<ide> unset($loop);
<ide> }
<add>
<add> /**
<add> * Flush the selected Redis database.
<add> *
<add> * @return void
<add> */
<add> public function flushdb()
<add> {
<add> if (! $this->client->getConnection() instanceof PredisCluster) {
<add> return $this->command('flushdb');
<add> }
<add>
<add> foreach ($this->getConnection() as $node) {
<add> $node->executeCommand(new ServerFlushDatabase);
<add> }
<add> }
<ide> } | 2 |
Python | Python | improve train_new_entity_type example | 68ad3669351448fc2f86e38f44406f04335dd72a | <ide><path>examples/training/train_new_entity_type.py
<ide> def main(model=None, new_model_name='animal', output_dir=None, n_iter=20):
<ide> else:
<ide> nlp = spacy.blank('en') # create blank Language class
<ide> print("Created blank 'en' model")
<del>
<ide> # Add entity recognizer to model if it's not in the pipeline
<ide> # nlp.create_pipe works for built-ins that are registered with spaCy
<ide> if 'ner' not in nlp.pipe_names:
<ide> def main(model=None, new_model_name='animal', output_dir=None, n_iter=20):
<ide> ner = nlp.get_pipe('ner')
<ide>
<ide> ner.add_label(LABEL) # add new entity label to entity recognizer
<add> if model is None:
<add> optimizer = nlp.begin_training()
<add> else:
<add> # Note that 'begin_training' initializes the models, so it'll zero out
<add> # existing entity types.
<add> optimizer = nlp.entity.create_optimizer()
<add>
<add>
<ide>
<ide> # get names of other pipes to disable them during training
<ide> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
<ide> with nlp.disable_pipes(*other_pipes): # only train NER
<del> optimizer = nlp.begin_training()
<ide> for itn in range(n_iter):
<ide> random.shuffle(TRAIN_DATA)
<ide> losses = {} | 1 |
Text | Text | fix some translation errors | bc3268de39d4eacf01ba3ee8e98e23ef9087bac1 | <ide><path>guide/russian/bootstrap/grid-system/index.md
<ide> ---
<ide> title: Grid System
<del>localeTitle: Сетевая система
<add>localeTitle: Система сеток
<ide> ---
<del>## Сетевая система
<add>## Сиситема сеток
<add>
<ide>
<ide> В кратце: система сеток Bootstrap помогает создавать гибкие макеты. Она состоит из системы строк и столбцов, которая помогает вам структурировать ваш контент.
<ide>
<add>
<ide> Строки представляют собой горизонтальные группы столбцов с максимум 12 столбцами на строку. Внутри каждой строки содержимое помещается внутри столбцов и может занимать от 1 до 12 столбцов.
<ide>
<ide> Bootstrap имеет пять различных типов ячеек сетки, а именно Extra small, Small, Medium, Large и Extra large, для каждой из этих уровней сетки существует точка останова.
<ide> Bootstrap использует пиксели для определения ко
<ide>
<ide> ###### Колонки
<ide>
<del>Классы столбцов указывают количество столбцов, которые вы хотели бы использовать из возможных 12 в строке. Например, `col-sm-6` будет означать, что ваш столбец будет использовать половину ширины `row` на маленьком экране, а `col-lg-4` будет использовать треть на большом экране.
<add>
<add>Классы столбцов указывают количество столбцов, которые вы хотели бы использовать, из возможных 12 в строке. Например, `col-sm-6` будет означать, что ваш столбец будет использовать половину ширины `row` на маленьком экране, а `col-lg-4` будет использовать треть на большом экране.
<add>
<ide>
<ide> Вот как вы бы определили префикс класса, чтобы использовать ширину одного столбца для различных размеров экрана:
<ide>
<ide> Bootstrap использует пиксели для определения ко
<ide> <div class="col-sm-1"></div>
<ide> ```
<ide>
<del>#### пример
<add>#### Пример
<ide>
<ide> Полноразмерная сетка с четырьмя столбцами, каждая из которых занимает полную строку на xs-экранах, половину строки на экранах sm и md и четверть ширины строки на больших и очень больших экранах.
<ide> ```
<ide> Bootstrap предоставляет готовую 12-ти колонную с
<ide>
<ide> * lg -> 1200px Настольные компьютеры
<ide>
<add>
<ide> Bootstrap использует понятие "mobile first" и является отзывчивым(адаптивным).
<add>
<ide>
<ide> Понятие "mobile first" означает, что макет сетки будет автоматически реагировать на меньшие экраны. Затем HTML определяет макет сетки для больших экранов.
<ide>
<ide> Bootstrap предоставляет готовую 12-ти колонную с
<ide>
<ide> _Это руководство основано на Bootstrap v4 (он будет работать с v3, за исключением того, что дополнительные маленькие экраны определяются как `xs` и нет размера `xl` )_
<ide>
<del>* Экстра большой: **ширина видового экрана> = 1200 пикселей**
<del>* Large: **ширина видового экрана> = 992px**
<del>* Средний: **ширина видового экрана> = 768 пикселей**
<del>* Малый: **ширина видового экрана> = 576 пикселей**
<del>* Экстра маленький: **ширина видового экрана ниже 576 пикселей**
<add>* Экстра большой: **ширина окна просмотра> = 1200 пикселей**
<add>* Large: **ширина окна просмотра> = 992px**
<add>* Средний: **ширина окна просмотра> = 768 пикселей**
<add>* Малый: **ширина окна просмотра> = 576 пикселей**
<add>* Экстра маленький: **ширина окна просмотра ниже 576 пикселей**
<ide>
<ide> #### Дополнительная информация:
<ide> | 1 |
Ruby | Ruby | use respond_to_missing? for orderedoptions | 3ea70f985b1799c27b907724920e5615018e505d | <ide><path>activesupport/lib/active_support/ordered_options.rb
<ide> def method_missing(name, *args)
<ide> end
<ide> end
<ide>
<del> def respond_to?(name)
<add> def respond_to_missing?(name, include_private)
<ide> true
<ide> end
<ide> end
<ide><path>activesupport/test/ordered_options_test.rb
<ide> def test_inheritable_options_inheritable_copy
<ide> assert copy.kind_of?(original.class)
<ide> assert_not_equal copy.object_id, original.object_id
<ide> end
<add>
<add> def test_introspection
<add> a = ActiveSupport::OrderedOptions.new
<add> assert a.respond_to?(:blah)
<add> assert a.respond_to?(:blah=)
<add> assert_equal 42, a.method(:blah=).call(42)
<add> assert_equal 42, a.method(:blah).call
<add> end
<ide> end | 2 |
Python | Python | add created_at attribute to container | 689d59a1eda84ff780872cd34465d8551aafa8be | <ide><path>libcloud/container/base.py
<ide> def __init__(
<ide> ip_addresses, # type: List[str]
<ide> driver, # type: ContainerDriver
<ide> extra=None, # type: dict
<add> created_at=None, # type: str
<ide> ):
<ide> """
<ide> :param id: Container id.
<ide> def __init__(
<ide> self.ip_addresses = ip_addresses
<ide> self.driver = driver
<ide> self.extra = extra or {}
<add> self.created_at = created_at
<ide>
<ide> def start(self):
<ide> # type: () -> Container
<ide><path>libcloud/container/drivers/kubernetes.py
<ide> def _to_container(self, data, container_status, pod_data):
<ide> """
<ide> Convert container in Container instances
<ide> """
<add> state = container_status.get('state')
<add> created_at = None
<add> if state:
<add> started_at = list(state.values())[0].get('startedAt')
<add> if started_at:
<add> created_at = datetime.datetime.strptime(
<add> started_at, '%Y-%m-%dT%H:%M:%SZ')
<ide> return Container(
<ide> id=container_status.get("containerID") or data["name"],
<ide> name=data["name"],
<ide> def _to_container(self, data, container_status, pod_data):
<ide> ContainerState.RUNNING if container_status else ContainerState.UNKNOWN
<ide> ),
<ide> driver=self.connection.driver,
<add> created_at=created_at,
<ide> extra={
<ide> "pod": pod_data["metadata"]["name"],
<ide> "namespace": pod_data["metadata"]["namespace"], | 2 |
Javascript | Javascript | remove fs timeouts | b975342e7b1fb708e1be4e277215772e8b714ddd | <ide><path>packager/src/AssetServer/index.js
<ide> const path = require('path');
<ide>
<ide> import type {AssetData} from '../node-haste/lib/AssetPaths';
<ide>
<del>const createTimeoutPromise = timeout => new Promise((resolve, reject) => {
<del> setTimeout(reject, timeout, 'fs operation timeout');
<del>});
<del>function timeoutableDenodeify(fsFunc, timeout) {
<del> return function raceWrapper(...args) {
<del> return Promise.race([
<del> createTimeoutPromise(timeout),
<del> denodeify(fsFunc).apply(this, args),
<del> ]);
<del> };
<del>}
<del>
<del>const FS_OP_TIMEOUT = parseInt(process.env.REACT_NATIVE_FSOP_TIMEOUT, 10) || 15000;
<del>
<del>const stat = timeoutableDenodeify(fs.stat, FS_OP_TIMEOUT);
<del>const readDir = timeoutableDenodeify(fs.readdir, FS_OP_TIMEOUT);
<del>const readFile = timeoutableDenodeify(fs.readFile, FS_OP_TIMEOUT);
<add>const stat = denodeify(fs.stat);
<add>const readDir = denodeify(fs.readdir);
<add>const readFile = denodeify(fs.readFile);
<ide>
<ide> class AssetServer {
<ide> | 1 |
Python | Python | remove a comment | 1202adbbaebb0b2cbd2d90dd4eb2cd61bed0fc06 | <ide><path>libcloud/dns/drivers/rackspace.py
<ide> class RackspaceDNSResponse(OpenStack_1_1_Response):
<ide> """
<ide>
<ide> def parse_error(self):
<del> # Holy fucking jesus,
<del> # "The request could not be understood by the server due to malformed
<del> # syntax." is returned if record already exists
<ide> status = int(self.status)
<ide> context = self.connection.context
<ide> body = self.parse_body() | 1 |
Javascript | Javascript | add keyboard avoiding view examples | a724c8d95ede7f0bdf5b91901beed701f0fc9c9f | <ide><path>packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js
<ide> const CloseButton = props => {
<ide> {marginHorizontal: props.behavior === 'position' ? 0 : 25},
<ide> ]}>
<ide> <Pressable
<del> onPress={() => props.setModdalOpen(false)}
<add> onPress={() => props.setModalOpen(false)}
<ide> style={styles.closeButton}>
<ide> <Text>Close</Text>
<ide> </Pressable>
<ide> const CloseButton = props => {
<ide> };
<ide>
<ide> const KeyboardAvoidingViewBehaviour = () => {
<del> const [modalOpen, setModdalOpen] = useState(false);
<add> const [modalOpen, setModalOpen] = useState(false);
<ide> const [behavior, setBehavior] = useState('padding');
<ide> return (
<ide> <View style={styles.outerContainer}>
<ide> const KeyboardAvoidingViewBehaviour = () => {
<ide> {backgroundColor: behavior === 'position' ? 'blue' : 'white'},
<ide> ]}>
<ide> <Text style={{color: behavior === 'position' ? 'white' : 'blue'}}>
<del> Padding
<add> Position
<ide> </Text>
<ide> </TouchableOpacity>
<ide> <TouchableOpacity
<ide> const KeyboardAvoidingViewBehaviour = () => {
<ide> </Text>
<ide> </TouchableOpacity>
<ide> </View>
<del> <CloseButton behavior={behavior} setModdalOpen={setModdalOpen} />
<add> <CloseButton behavior={behavior} setModalOpen={setModalOpen} />
<ide> <TextInputForm />
<ide> </KeyboardAvoidingView>
<ide> </Modal>
<ide> <View>
<del> <Pressable onPress={() => setModdalOpen(true)}>
<add> <Pressable onPress={() => setModalOpen(true)}>
<ide> <Text>Open Example</Text>
<ide> </Pressable>
<ide> </View>
<ide> const KeyboardAvoidingViewBehaviour = () => {
<ide> };
<ide>
<ide> const KeyboardAvoidingDisabled = () => {
<del> const [modalOpen, setModdalOpen] = useState(false);
<add> const [modalOpen, setModalOpen] = useState(false);
<ide> return (
<ide> <View style={styles.outerContainer}>
<ide> <Modal animationType="fade" visible={modalOpen}>
<ide> <KeyboardAvoidingView
<ide> enabled={false}
<ide> behavior={'height'}
<ide> style={styles.container}>
<del> <CloseButton behavior={'height'} setModdalOpen={setModdalOpen} />
<add> <CloseButton behavior={'height'} setModalOpen={setModalOpen} />
<ide> <TextInputForm />
<ide> </KeyboardAvoidingView>
<ide> </Modal>
<ide> <View>
<del> <Pressable onPress={() => setModdalOpen(true)}>
<add> <Pressable onPress={() => setModalOpen(true)}>
<ide> <Text>Open Example</Text>
<ide> </Pressable>
<ide> </View>
<ide> const KeyboardAvoidingDisabled = () => {
<ide> };
<ide>
<ide> const KeyboardAvoidingVerticalOffset = () => {
<del> const [modalOpen, setModdalOpen] = useState(false);
<add> const [modalOpen, setModalOpen] = useState(false);
<ide> return (
<ide> <View style={styles.outerContainer}>
<ide> <Modal animationType="fade" visible={modalOpen}>
<ide> <KeyboardAvoidingView
<ide> keyboardVerticalOffset={20}
<ide> behavior={'padding'}
<ide> style={styles.container}>
<del> <CloseButton behavior={'height'} setModdalOpen={setModdalOpen} />
<add> <CloseButton behavior={'height'} setModalOpen={setModalOpen} />
<ide> <TextInputForm />
<ide> </KeyboardAvoidingView>
<ide> </Modal>
<ide> <View>
<del> <Pressable onPress={() => setModdalOpen(true)}>
<add> <Pressable onPress={() => setModalOpen(true)}>
<add> <Text>Open Example</Text>
<add> </Pressable>
<add> </View>
<add> </View>
<add> );
<add>};
<add>
<add>const KeyboardAvoidingContentContainerStyle = () => {
<add> const [modalOpen, setModalOpen] = useState(false);
<add> return (
<add> <View>
<add> <Modal animationType="fade" visible={modalOpen}>
<add> <KeyboardAvoidingView
<add> keyboardVerticalOffset={20}
<add> behavior={'position'}
<add> style={styles.container}
<add> contentContainerStyle={styles.contentContainer}>
<add> <CloseButton behavior={'height'} setModalOpen={setModalOpen} />
<add> <TextInputForm />
<add> </KeyboardAvoidingView>
<add> </Modal>
<add> <View>
<add> <Pressable onPress={() => setModalOpen(true)}>
<ide> <Text>Open Example</Text>
<ide> </Pressable>
<ide> </View>
<ide> const styles = StyleSheet.create({
<ide> paddingHorizontal: 20,
<ide> paddingTop: 20,
<ide> },
<add> contentContainer: {
<add> paddingTop: 20,
<add> backgroundColor: '#abdebf',
<add> },
<ide> textInput: {
<ide> borderRadius: 5,
<ide> borderWidth: 1,
<ide> exports.examples = [
<ide> return <KeyboardAvoidingDisabled />;
<ide> },
<ide> },
<add> {
<add> title: 'Keyboard Avoiding View with contentContainerStyle',
<add> render(): React.Node {
<add> return <KeyboardAvoidingContentContainerStyle />;
<add> },
<add> },
<ide> ]; | 1 |
PHP | PHP | add type hints to files under validation | 521ac1b30a2d4eb0e15bcded01b8fe08fd1351ce | <ide><path>src/Validation/RulesProvider.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Validation/ValidatableInterface.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> interface ValidatableInterface
<ide> * @param \Cake\Validation\Validator $validator The validator to use when validating the entity.
<ide> * @return array
<ide> */
<del> public function validate(Validator $validator);
<add> public function validate(Validator $validator): array;
<ide> }
<ide><path>src/Validation/Validation.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class Validation
<ide> *
<ide> * Returns true if string contains something other than whitespace
<ide> *
<del> * @param string $check Value to check
<add> * @param mixed $check Value to check
<ide> * @return bool Success
<ide> */
<del> public static function notBlank($check)
<add> public static function notBlank($check): bool
<ide> {
<ide> if (empty($check) && !is_bool($check) && !is_numeric($check)) {
<ide> return false;
<ide> public static function notBlank($check)
<ide> *
<ide> * Returns true if string contains only integer or letters
<ide> *
<del> * @param string $check Value to check
<add> * @param mixed $check Value to check
<ide> * @return bool Success
<ide> */
<del> public static function alphaNumeric($check)
<add> public static function alphaNumeric($check): bool
<ide> {
<del> if (empty($check) && $check !== '0') {
<add> if ((empty($check) && $check !== '0') || !is_scalar($check)) {
<ide> return false;
<ide> }
<ide>
<ide> public static function alphaNumeric($check)
<ide> * Spaces are included in the character count.
<ide> * Returns true if string matches value min, max, or between min and max,
<ide> *
<del> * @param string $check Value to check for length
<add> * @param mixed $check Value to check for length
<ide> * @param int $min Minimum value in range (inclusive)
<ide> * @param int $max Maximum value in range (inclusive)
<ide> * @return bool Success
<ide> */
<del> public static function lengthBetween($check, $min, $max)
<add> public static function lengthBetween($check, int $min, int $max): bool
<ide> {
<ide> if (!is_string($check)) {
<ide> return false;
<ide> public static function lengthBetween($check, $min, $max)
<ide> * Validation of credit card numbers.
<ide> * Returns true if $check is in the proper credit card format.
<ide> *
<del> * @param string $check credit card number to validate
<add> * @param mixed $check credit card number to validate
<ide> * @param string|array $type 'all' may be passed as a string, defaults to fast which checks format of most major credit cards
<ide> * if an array is used only the values of the array are checked.
<ide> * Example: ['amex', 'bankcard', 'maestro']
<ide> public static function lengthBetween($check, $min, $max)
<ide> * @return bool Success
<ide> * @see \Cake\Validation\Validation::luhn()
<ide> */
<del> public static function cc($check, $type = 'fast', $deep = false, $regex = null)
<add> public static function cc($check, $type = 'fast', $deep = false, $regex = null): bool
<ide> {
<ide> if (!is_scalar($check)) {
<ide> return false;
<ide> public static function cc($check, $type = 'fast', $deep = false, $regex = null)
<ide> * @param int $expectedCount The expected count value.
<ide> * @return bool Success
<ide> */
<del> public static function numElements($check, $operator, $expectedCount)
<add> public static function numElements($check, string $operator, int $expectedCount): bool
<ide> {
<ide> if (!is_array($check) && !$check instanceof \Countable) {
<ide> return false;
<ide> public static function numElements($check, $operator, $expectedCount)
<ide> /**
<ide> * Used to compare 2 numeric values.
<ide> *
<del> * @param string $check1 The left value to compare.
<add> * @param string|int $check1 The left value to compare.
<ide> * @param string $operator Can be either a word or operand
<ide> * is greater >, is less <, greater or equal >=
<ide> * less or equal <=, is less <, equal to ==, not equal !=
<del> * @param int $check2 The right value to compare.
<add> * @param string|int $check2 The right value to compare.
<ide> * @return bool Success
<ide> */
<del> public static function comparison($check1, $operator, $check2)
<add> public static function comparison($check1, string $operator, $check2): bool
<ide> {
<ide> if ((float)$check1 != $check1) {
<ide> return false;
<ide> public static function comparison($check1, $operator, $check2)
<ide> * @param array $context The validation context.
<ide> * @return bool
<ide> */
<del> public static function compareWith($check, $field, $context)
<add> public static function compareWith($check, string $field, array $context): bool
<ide> {
<ide> return self::compareFields($check, $field, static::COMPARE_SAME, $context);
<ide> }
<ide> public static function compareWith($check, $field, $context)
<ide> * @return bool
<ide> * @since 3.6.0
<ide> */
<del> public static function compareFields($check, $field, $operator, $context)
<add> public static function compareFields($check, string $field, string $operator, array $context): bool
<ide> {
<ide> if (!isset($context['data'][$field])) {
<ide> return false;
<ide> public static function compareFields($check, $field, $operator, $context)
<ide> *
<ide> * Returns true if string contains at least the specified number of non-alphanumeric characters
<ide> *
<del> * @param string $check Value to check
<add> * @param mixed $check Value to check
<ide> * @param int $count Number of non-alphanumerics to check for
<ide> * @return bool Success
<ide> */
<del> public static function containsNonAlphaNumeric($check, $count = 1)
<add> public static function containsNonAlphaNumeric($check, int $count = 1): bool
<ide> {
<ide> if (!is_scalar($check)) {
<ide> return false;
<ide> public static function containsNonAlphaNumeric($check, $count = 1)
<ide> * @param string|null $regex If $check is passed as a string, $regex must also be set to valid regular expression
<ide> * @return bool Success
<ide> */
<del> public static function custom($check, $regex = null)
<add> public static function custom(string $check, ?string $regex = null): bool
<ide> {
<ide> if ($regex === null) {
<ide> static::$errors[] = 'You must define a regular expression for Validation::custom()';
<ide> public static function custom($check, $regex = null)
<ide> * @param string|null $regex If a custom regular expression is used this is the only validation that will occur.
<ide> * @return bool Success
<ide> */
<del> public static function date($check, $format = 'ymd', $regex = null)
<add> public static function date($check, $format = 'ymd', ?string $regex = null): bool
<ide> {
<ide> if ($check instanceof DateTimeInterface) {
<ide> return true;
<ide> public static function date($check, $format = 'ymd', $regex = null)
<ide> * @see \Cake\Validation\Validation::date()
<ide> * @see \Cake\Validation\Validation::time()
<ide> */
<del> public static function datetime($check, $dateFormat = 'ymd', $regex = null)
<add> public static function datetime($check, $dateFormat = 'ymd', ?string $regex = null): bool
<ide> {
<ide> if ($check instanceof DateTimeInterface) {
<ide> return true;
<ide> public static function datetime($check, $dateFormat = 'ymd', $regex = null)
<ide> * @param string|\DateTimeInterface $check a valid time string/object
<ide> * @return bool Success
<ide> */
<del> public static function time($check)
<add> public static function time($check): bool
<ide> {
<ide> if ($check instanceof DateTimeInterface) {
<ide> return true;
<ide> public static function time($check)
<ide> $check = static::_getDateString($check);
<ide> }
<ide>
<add> if (!is_scalar($check)) {
<add> return false;
<add> }
<add>
<ide> return static::_check($check, '%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%');
<ide> }
<ide>
<ide> public static function time($check)
<ide> * @throws \InvalidArgumentException when unsupported $type given
<ide> * @see \Cake\I18n\Time::parseDate(), \Cake\I18n\Time::parseTime(), \Cake\I18n\Time::parseDateTime()
<ide> */
<del> public static function localizedTime($check, $type = 'datetime', $format = null)
<add> public static function localizedTime($check, string $type = 'datetime', $format = null): bool
<ide> {
<ide> if ($check instanceof DateTimeInterface) {
<ide> return true;
<ide> public static function localizedTime($check, $type = 'datetime', $format = null)
<ide> * @param array $booleanValues List of valid boolean values, defaults to `[true, false, 0, 1, '0', '1']`.
<ide> * @return bool Success.
<ide> */
<del> public static function boolean($check, array $booleanValues = [])
<add> public static function boolean($check, array $booleanValues = []): bool
<ide> {
<ide> if (!$booleanValues) {
<ide> $booleanValues = [true, false, 0, 1, '0', '1'];
<ide> public static function boolean($check, array $booleanValues = [])
<ide> * @param array $truthyValues List of valid truthy values, defaults to `[true, 1, '1']`.
<ide> * @return bool Success.
<ide> */
<del> public static function truthy($check, array $truthyValues = [])
<add> public static function truthy($check, array $truthyValues = []): bool
<ide> {
<ide> if (!$truthyValues) {
<ide> $truthyValues = [true, 1, '1'];
<ide> public static function truthy($check, array $truthyValues = [])
<ide> * @param array $falseyValues List of valid falsey values, defaults to `[false, 0, '0']`.
<ide> * @return bool Success.
<ide> */
<del> public static function falsey($check, array $falseyValues = [])
<add> public static function falsey($check, array $falseyValues = []): bool
<ide> {
<ide> if (!$falseyValues) {
<ide> $falseyValues = [false, 0, '0'];
<ide> public static function falsey($check, array $falseyValues = [])
<ide> * @param string|null $regex If a custom regular expression is used, this is the only validation that will occur.
<ide> * @return bool Success
<ide> */
<del> public static function decimal($check, $places = null, $regex = null)
<add> public static function decimal($check, $places = null, ?string $regex = null): bool
<ide> {
<ide> if ($regex === null) {
<ide> $lnum = '[0-9]+';
<ide> public static function decimal($check, $places = null, $regex = null)
<ide> $places = '[0-9]{' . $places . '}';
<ide> $dnum = "(?:[0-9]*[\.]{$places}|{$lnum}[\.]{$places})";
<ide> $regex = "/^{$sign}{$dnum}{$exp}$/";
<add> } else {
<add> return false;
<ide> }
<ide> }
<ide>
<ide> public static function decimal($check, $places = null, $regex = null)
<ide> * Only uses getmxrr() checking for deep validation, or
<ide> * any PHP version on a non-windows distribution
<ide> *
<del> * @param string $check Value to check
<add> * @param mixed $check Value to check
<ide> * @param bool $deep Perform a deeper validation (if true), by also checking availability of host
<ide> * @param string|null $regex Regex to use (if none it will use built in regex)
<ide> * @return bool Success
<ide> */
<del> public static function email($check, $deep = false, $regex = null)
<add> public static function email($check, ?bool $deep = false, ?string $regex = null): bool
<ide> {
<ide> if (!is_string($check)) {
<ide> return false;
<ide> public static function email($check, $deep = false, $regex = null)
<ide> * @param mixed $comparedTo Value to compare
<ide> * @return bool Success
<ide> */
<del> public static function equalTo($check, $comparedTo)
<add> public static function equalTo($check, $comparedTo): bool
<ide> {
<ide> return $check === $comparedTo;
<ide> }
<ide> public static function equalTo($check, $comparedTo)
<ide> * @param array $extensions file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg'
<ide> * @return bool Success
<ide> */
<del> public static function extension($check, $extensions = ['gif', 'jpeg', 'png', 'jpg'])
<add> public static function extension($check, array $extensions = ['gif', 'jpeg', 'png', 'jpg']): bool
<ide> {
<ide> if (is_array($check)) {
<ide> $check = $check['name'] ?? array_shift($check);
<ide> public static function extension($check, $extensions = ['gif', 'jpeg', 'png', 'j
<ide> * @param string $type The IP Protocol version to validate against
<ide> * @return bool Success
<ide> */
<del> public static function ip($check, $type = 'both')
<add> public static function ip(string $check, string $type = 'both'): bool
<ide> {
<ide> $type = strtolower($type);
<ide> $flags = 0;
<ide> public static function ip($check, $type = 'both')
<ide> * @param int $min The minimal string length
<ide> * @return bool Success
<ide> */
<del> public static function minLength($check, $min)
<add> public static function minLength(string $check, int $min): bool
<ide> {
<ide> return mb_strlen($check) >= $min;
<ide> }
<ide> public static function minLength($check, $min)
<ide> * @param int $max The maximal string length
<ide> * @return bool Success
<ide> */
<del> public static function maxLength($check, $max)
<add> public static function maxLength(string $check, int $max): bool
<ide> {
<ide> return mb_strlen($check) <= $max;
<ide> }
<ide> public static function maxLength($check, $max)
<ide> * @param int $min The minimal string length (in bytes)
<ide> * @return bool Success
<ide> */
<del> public static function minLengthBytes($check, $min)
<add> public static function minLengthBytes(string $check, int $min): bool
<ide> {
<ide> return strlen($check) >= $min;
<ide> }
<ide> public static function minLengthBytes($check, $min)
<ide> * @param int $max The maximal string length
<ide> * @return bool Success
<ide> */
<del> public static function maxLengthBytes($check, $max)
<add> public static function maxLengthBytes(string $check, int $max): bool
<ide> {
<ide> return strlen($check) <= $max;
<ide> }
<ide> public static function maxLengthBytes($check, $max)
<ide> * @param string $symbolPosition Where symbol is located (left/right)
<ide> * @return bool Success
<ide> */
<del> public static function money($check, $symbolPosition = 'left')
<add> public static function money(string $check, string $symbolPosition = 'left'): bool
<ide> {
<ide> $money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{1,2})?';
<ide> if ($symbolPosition === 'right') {
<ide> public static function money($check, $symbolPosition = 'left')
<ide> * - max => maximum number of non-zero choices that can be made
<ide> * - min => minimum number of non-zero choices that can be made
<ide> *
<del> * @param array $check Value to check
<add> * @param mixed $check Value to check
<ide> * @param array $options Options for the check.
<ide> * @param bool $caseInsensitive Set to true for case insensitive comparison.
<ide> * @return bool Success
<ide> */
<del> public static function multiple($check, array $options = [], $caseInsensitive = false)
<add> public static function multiple($check, array $options = [], bool $caseInsensitive = false): bool
<ide> {
<ide> $defaults = ['in' => null, 'max' => null, 'min' => null];
<ide> $options += $defaults;
<ide> public static function multiple($check, array $options = [], $caseInsensitive =
<ide> /**
<ide> * Checks if a value is numeric.
<ide> *
<del> * @param string $check Value to check
<add> * @param mixed $check Value to check
<ide> * @return bool Success
<ide> */
<del> public static function numeric($check)
<add> public static function numeric($check): bool
<ide> {
<ide> return is_numeric($check);
<ide> }
<ide>
<ide> /**
<ide> * Checks if a value is a natural number.
<ide> *
<del> * @param string $check Value to check
<add> * @param mixed $check Value to check
<ide> * @param bool $allowZero Set true to allow zero, defaults to false
<ide> * @return bool Success
<ide> * @see https://en.wikipedia.org/wiki/Natural_number
<ide> */
<del> public static function naturalNumber($check, $allowZero = false)
<add> public static function naturalNumber($check, bool $allowZero = false): bool
<ide> {
<ide> $regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
<ide>
<ide> public static function naturalNumber($check, $allowZero = false)
<ide> * If they are not set, will return true if $check is a
<ide> * legal finite on this platform.
<ide> *
<del> * @param string $check Value to check
<add> * @param mixed $check Value to check
<ide> * @param int|float|null $lower Lower limit
<ide> * @param int|float|null $upper Upper limit
<ide> * @return bool Success
<ide> */
<del> public static function range($check, $lower = null, $upper = null)
<add> public static function range($check, ?float $lower = null, ?float $upper = null): bool
<ide> {
<ide> if (!is_numeric($check)) {
<ide> return false;
<ide> public static function range($check, $lower = null, $upper = null)
<ide> return $check >= $lower && $check <= $upper;
<ide> }
<ide>
<del> return is_finite($check);
<add> return is_finite((float)$check);
<ide> }
<ide>
<ide> /**
<ide> public static function range($check, $lower = null, $upper = null)
<ide> * @return bool Success
<ide> * @link https://tools.ietf.org/html/rfc3986
<ide> */
<del> public static function url($check, $strict = false)
<add> public static function url(string $check, bool $strict = false): bool
<ide> {
<ide> static::_populateIp();
<ide>
<ide> public static function url($check, $strict = false)
<ide> * @param bool $caseInsensitive Set to true for case insensitive comparison.
<ide> * @return bool Success.
<ide> */
<del> public static function inList($check, array $list, $caseInsensitive = false)
<add> public static function inList($check, array $list, bool $caseInsensitive = false): bool
<ide> {
<ide> if ($caseInsensitive) {
<ide> $list = array_map('mb_strtolower', $list);
<ide> public static function inList($check, array $list, $caseInsensitive = false)
<ide> * @param string $check Value to check
<ide> * @return bool Success
<ide> */
<del> public static function uuid($check)
<add> public static function uuid(string $check): bool
<ide> {
<ide> $regex = '/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[0-5][a-fA-F0-9]{3}-[089aAbB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/';
<ide>
<ide> public static function uuid($check)
<ide> /**
<ide> * Runs a regular expression match.
<ide> *
<del> * @param string $check Value to check against the $regex expression
<add> * @param mixed $check Value to check against the $regex expression
<ide> * @param string $regex Regular expression
<ide> * @return bool Success of match
<ide> */
<del> protected static function _check($check, $regex)
<add> protected static function _check($check, string $regex): bool
<ide> {
<del> return is_string($regex) && is_scalar($check) && preg_match($regex, $check);
<add> return is_string($regex) && is_scalar($check) && preg_match($regex, (string)$check);
<ide> }
<ide>
<ide> /**
<ide> protected static function _check($check, $regex)
<ide> * @return bool Success
<ide> * @see https://en.wikipedia.org/wiki/Luhn_algorithm
<ide> */
<del> public static function luhn($check)
<add> public static function luhn($check): bool
<ide> {
<ide> if (!is_scalar($check) || (int)$check === 0) {
<ide> return false;
<ide> public static function luhn($check)
<ide> * @throws \RuntimeException when mime type can not be determined.
<ide> * @throws \LogicException when ext/fileinfo is missing
<ide> */
<del> public static function mimeType($check, $mimeTypes = [])
<add> public static function mimeType($check, $mimeTypes = []): bool
<ide> {
<ide> $file = static::getFilename($check);
<ide> if ($file === false) {
<ide> protected static function getFilename($check)
<ide> * @param int|string|null $size Size in bytes or human readable string like '5MB'.
<ide> * @return bool Success
<ide> */
<del> public static function fileSize($check, $operator = null, $size = null)
<add> public static function fileSize($check, ?string $operator = null, $size = null): bool
<ide> {
<ide> $file = static::getFilename($check);
<ide> if ($file === false) {
<ide> public static function fileSize($check, $operator = null, $size = null)
<ide> * @return bool
<ide> * @see https://secure.php.net/manual/en/features.file-upload.errors.php
<ide> */
<del> public static function uploadError($check, $allowNoFile = false)
<add> public static function uploadError($check, bool $allowNoFile = false): bool
<ide> {
<ide> if ($check instanceof UploadedFileInterface) {
<ide> $code = $check->getError();
<ide> public static function uploadError($check, $allowNoFile = false)
<ide> * - `optional` - Whether or not this file is optional. Defaults to false.
<ide> * If true a missing file will pass the validator regardless of other constraints.
<ide> *
<del> * @param array $file The uploaded file data from PHP.
<add> * @param mixed $file The uploaded file data from PHP.
<ide> * @param array $options An array of options for the validation.
<ide> * @return bool
<ide> */
<del> public static function uploadedFile($file, array $options = [])
<add> public static function uploadedFile($file, array $options = []): bool
<ide> {
<ide> $options += [
<ide> 'minSize' => null,
<ide> public static function uploadedFile($file, array $options = [])
<ide> * @param array $options Options to validate width and height.
<ide> * @return bool
<ide> */
<del> public static function imageSize($file, $options)
<add> public static function imageSize(array $file, array $options): bool
<ide> {
<ide> if (!isset($options['height']) && !isset($options['width'])) {
<ide> throw new InvalidArgumentException('Invalid image size validation parameters! Missing `width` and / or `height`.');
<ide> public static function imageSize($file, $options)
<ide> * @param int $width Min or max width.
<ide> * @return bool
<ide> */
<del> public static function imageWidth($file, $operator, $width)
<add> public static function imageWidth(array $file, string $operator, int $width): bool
<ide> {
<ide> return self::imageSize($file, [
<ide> 'width' => [
<ide> public static function imageWidth($file, $operator, $width)
<ide> * @param int $height Min or max width.
<ide> * @return bool
<ide> */
<del> public static function imageHeight($file, $operator, $height)
<add> public static function imageHeight(array $file, string $operator, int $height): bool
<ide> {
<ide> return self::imageSize($file, [
<ide> 'height' => [
<ide> public static function imageHeight($file, $operator, $height)
<ide> * @param array $options Options for the validation logic.
<ide> * @return bool
<ide> */
<del> public static function geoCoordinate($value, array $options = [])
<add> public static function geoCoordinate(string $value, array $options = []): bool
<ide> {
<ide> $options += [
<ide> 'format' => 'both',
<ide> public static function geoCoordinate($value, array $options = [])
<ide> * @link https://en.wikipedia.org/wiki/Latitude
<ide> * @see \Cake\Validation\Validation::geoCoordinate()
<ide> */
<del> public static function latitude($value, array $options = [])
<add> public static function latitude(string $value, array $options = []): bool
<ide> {
<ide> $options['format'] = 'lat';
<ide>
<ide> public static function latitude($value, array $options = [])
<ide> * @link https://en.wikipedia.org/wiki/Longitude
<ide> * @see \Cake\Validation\Validation::geoCoordinate()
<ide> */
<del> public static function longitude($value, array $options = [])
<add> public static function longitude(string $value, array $options = []): bool
<ide> {
<ide> $options['format'] = 'long';
<ide>
<ide> public static function longitude($value, array $options = [])
<ide> *
<ide> * This method will reject all non-string values.
<ide> *
<del> * @param string $value The value to check
<add> * @param mixed $value The value to check
<ide> * @return bool
<ide> */
<del> public static function ascii($value)
<add> public static function ascii($value): bool
<ide> {
<ide> if (!is_string($value)) {
<ide> return false;
<ide> public static function ascii($value)
<ide> * MySQL's older utf8 encoding type does not allow characters above
<ide> * the basic multilingual plane. Defaults to false.
<ide> *
<del> * @param string $value The value to check
<add> * @param mixed $value The value to check
<ide> * @param array $options An array of options. See above for the supported options.
<ide> * @return bool
<ide> */
<del> public static function utf8($value, array $options = [])
<add> public static function utf8($value, array $options = []): bool
<ide> {
<ide> if (!is_string($value)) {
<ide> return false;
<ide> public static function utf8($value, array $options = [])
<ide> * This method will accept strings that contain only integer data
<ide> * as well.
<ide> *
<del> * @param string $value The value to check
<add> * @param mixed $value The value to check
<ide> * @return bool
<ide> */
<del> public static function isInteger($value)
<add> public static function isInteger($value): bool
<ide> {
<ide> if (!is_scalar($value) || is_float($value)) {
<ide> return false;
<ide> public static function isInteger($value)
<ide> /**
<ide> * Check that the input value is an array.
<ide> *
<del> * @param array $value The value to check
<add> * @param mixed $value The value to check
<ide> * @return bool
<ide> */
<del> public static function isArray($value)
<add> public static function isArray($value): bool
<ide> {
<ide> return is_array($value);
<ide> }
<ide> public static function isArray($value)
<ide> * @param mixed $value The value to check
<ide> * @return bool
<ide> */
<del> public static function isScalar($value)
<add> public static function isScalar($value): bool
<ide> {
<ide> return is_scalar($value);
<ide> }
<ide> public static function isScalar($value)
<ide> * @param string|array $check The value to check
<ide> * @return bool Success
<ide> */
<del> public static function hexColor($check)
<add> public static function hexColor($check): bool
<ide> {
<ide> return static::_check($check, '/^#[0-9a-f]{6}$/iD');
<ide> }
<ide> public static function hexColor($check)
<ide> *
<ide> * @return bool Success
<ide> */
<del> public static function iban($check)
<add> public static function iban(string $check): bool
<ide> {
<ide> if (!preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/', $check)) {
<ide> return false;
<ide> public static function iban($check)
<ide> * @param array $value The array representing a date or datetime.
<ide> * @return string
<ide> */
<del> protected static function _getDateString($value)
<add> protected static function _getDateString(array $value): string
<ide> {
<ide> $formatted = '';
<ide> if (isset($value['year'], $value['month'], $value['day']) &&
<ide> protected static function _getDateString($value)
<ide> *
<ide> * @return void
<ide> */
<del> protected static function _populateIp()
<add> protected static function _populateIp(): void
<ide> {
<ide> if (!isset(static::$_pattern['IPv6'])) {
<ide> $pattern = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}';
<ide> protected static function _populateIp()
<ide> *
<ide> * @return void
<ide> */
<del> protected static function _reset()
<add> protected static function _reset(): void
<ide> {
<ide> static::$errors = [];
<ide> }
<ide><path>src/Validation/ValidationRule.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * ValidationRule.
<ide> *
<ide> public function __construct(array $validator = [])
<ide> *
<ide> * @return bool
<ide> */
<del> public function isLast()
<add> public function isLast(): bool
<ide> {
<ide> return (bool)$this->_last;
<ide> }
<ide> public function process($value, array $providers, array $context = [])
<ide> * be passed as the last argument for the validation method
<ide> * @return bool True if the ValidationRule should be skipped
<ide> */
<del> protected function _skip($context)
<add> protected function _skip(array $context): bool
<ide> {
<ide> if (!is_string($this->_on) && is_callable($this->_on)) {
<ide> $function = $this->_on;
<ide> protected function _skip($context)
<ide> * @param array $validator [optional]
<ide> * @return void
<ide> */
<del> protected function _addValidatorProps($validator = [])
<add> protected function _addValidatorProps(array $validator = []): void
<ide> {
<ide> foreach ($validator as $key => $value) {
<ide> if (!isset($value) || empty($value)) {
<ide> protected function _addValidatorProps($validator = [])
<ide> * @param string $property The name of the property to retrieve.
<ide> * @return mixed
<ide> */
<del> public function get($property)
<add> public function get(string $property)
<ide> {
<ide> $property = '_' . $property;
<ide> if (isset($this->{$property})) {
<ide><path>src/Validation/ValidationSet.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function allowEmpty($allowEmpty)
<ide> * @param string $name The name under which the rule is set.
<ide> * @return \Cake\Validation\ValidationRule|null
<ide> */
<del> public function rule($name)
<add> public function rule(string $name): ?ValidationRule
<ide> {
<ide> if (!empty($this->_rules[$name])) {
<ide> return $this->_rules[$name];
<ide> }
<add>
<add> return null;
<ide> }
<ide>
<ide> /**
<ide> * Returns all rules for this validation set
<ide> *
<ide> * @return \Cake\Validation\ValidationRule[]
<ide> */
<del> public function rules()
<add> public function rules(): array
<ide> {
<ide> return $this->_rules;
<ide> }
<ide> public function rules()
<ide> * @param \Cake\Validation\ValidationRule|array $rule The validation rule to be set
<ide> * @return $this
<ide> */
<del> public function add($name, $rule)
<add> public function add(string $name, $rule)
<ide> {
<ide> if (!($rule instanceof ValidationRule)) {
<ide> $rule = new ValidationRule($rule);
<ide> public function add($name, $rule)
<ide> * @param string $name The name under which the rule should be unset
<ide> * @return $this
<ide> */
<del> public function remove($name)
<add> public function remove(string $name)
<ide> {
<ide> unset($this->_rules[$name]);
<ide>
<ide> public function offsetUnset($index)
<ide> *
<ide> * @return \ArrayIterator
<ide> */
<del> public function getIterator()
<add> public function getIterator(): ArrayIterator
<ide> {
<ide> return new ArrayIterator($this->_rules);
<ide> }
<ide> public function getIterator()
<ide> *
<ide> * @return int
<ide> */
<del> public function count()
<add> public function count(): int
<ide> {
<ide> return count($this->_rules);
<ide> }
<ide><path>src/Validation/Validator.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct()
<ide> * @param bool $newRecord whether the data to be validated is new or to be updated.
<ide> * @return array Array of invalid fields
<ide> */
<del> public function errors(array $data, $newRecord = true)
<add> public function errors(array $data, bool $newRecord = true): array
<ide> {
<ide> $errors = [];
<ide>
<ide> public function errors(array $data, $newRecord = true)
<ide> * @param \Cake\Validation\ValidationSet|null $set The set of rules for field
<ide> * @return \Cake\Validation\ValidationSet
<ide> */
<del> public function field($name, ?ValidationSet $set = null)
<add> public function field(string $name, ?ValidationSet $set = null): ValidationSet
<ide> {
<ide> if (empty($this->_fields[$name])) {
<ide> $set = $set ?: new ValidationSet();
<ide> public function field($name, ?ValidationSet $set = null)
<ide> * @param string $name The field name to check.
<ide> * @return bool
<ide> */
<del> public function hasField($name)
<add> public function hasField(string $name): bool
<ide> {
<ide> return isset($this->_fields[$name]);
<ide> }
<ide> public function hasField($name)
<ide> * @param object|string $object Provider object or class name.
<ide> * @return $this
<ide> */
<del> public function setProvider($name, $object)
<add> public function setProvider(string $name, $object)
<ide> {
<ide> $this->_providers[$name] = $object;
<ide>
<ide> public function setProvider($name, $object)
<ide> * @return object|string|null
<ide> * @throws \ReflectionException
<ide> */
<del> public function getProvider($name)
<add> public function getProvider(string $name)
<ide> {
<ide> if (isset($this->_providers[$name])) {
<ide> return $this->_providers[$name];
<ide> public function getProvider($name)
<ide> * @param string $name The name under which the provider should be retrieved.
<ide> * @return object|string|null
<ide> */
<del> public static function getDefaultProvider($name)
<add> public static function getDefaultProvider(string $name)
<ide> {
<ide> if (!isset(self::$_defaultProviders[$name])) {
<ide> return null;
<ide> public static function getDefaultProvider($name)
<ide> * @param object|string $object Provider object or class name.
<ide> * @return void
<ide> */
<del> public static function addDefaultProvider($name, $object)
<add> public static function addDefaultProvider(string $name, $object): void
<ide> {
<ide> self::$_defaultProviders[$name] = $object;
<ide> }
<ide> public static function addDefaultProvider($name, $object)
<ide> *
<ide> * @return array
<ide> */
<del> public static function getDefaultProviders()
<add> public static function getDefaultProviders(): array
<ide> {
<ide> return array_keys(self::$_defaultProviders);
<ide> }
<ide> public static function getDefaultProviders()
<ide> *
<ide> * @return array
<ide> */
<del> public function providers()
<add> public function providers(): array
<ide> {
<ide> return array_keys($this->_providers);
<ide> }
<ide> public function offsetUnset($field)
<ide> *
<ide> * @return \ArrayIterator
<ide> */
<del> public function getIterator()
<add> public function getIterator(): ArrayIterator
<ide> {
<ide> return new ArrayIterator($this->_fields);
<ide> }
<ide> public function getIterator()
<ide> *
<ide> * @return int
<ide> */
<del> public function count()
<add> public function count(): int
<ide> {
<ide> return count($this->_fields);
<ide> }
<ide> public function count()
<ide> * @param array|\Cake\Validation\ValidationRule $rule the rule to add
<ide> * @return $this
<ide> */
<del> public function add($field, $name, $rule = [])
<add> public function add(string $field, $name, $rule = [])
<ide> {
<ide> $field = $this->field($field);
<ide>
<ide> public function add($field, $name, $rule = [])
<ide> * true when the validation rule should be applied.
<ide> * @return $this
<ide> */
<del> public function addNested($field, Validator $validator, $message = null, $when = null)
<add> public function addNested(string $field, Validator $validator, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['message' => $message, 'on' => $when]);
<ide>
<ide> public function addNested($field, Validator $validator, $message = null, $when =
<ide> * true when the validation rule should be applied.
<ide> * @return $this
<ide> */
<del> public function addNestedMany($field, Validator $validator, $message = null, $when = null)
<add> public function addNestedMany(string $field, Validator $validator, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['message' => $message, 'on' => $when]);
<ide>
<ide> public function addNestedMany($field, Validator $validator, $message = null, $wh
<ide> * @param string|null $rule the name of the rule to be removed
<ide> * @return $this
<ide> */
<del> public function remove($field, $rule = null)
<add> public function remove(string $field, ?string $rule = null)
<ide> {
<ide> if ($rule === null) {
<ide> unset($this->_fields[$field]);
<ide> public function remove($field, $rule = null)
<ide> * @param string|null $message The message to show if the field presence validation fails.
<ide> * @return $this
<ide> */
<del> public function requirePresence($field, $mode = true, $message = null)
<add> public function requirePresence($field, $mode = true, ?string $message = null)
<ide> {
<ide> $defaults = [
<ide> 'mode' => $mode,
<ide> public function allowEmpty($field, $when = true, $message = null)
<ide> * @param string|array $settings settings from data
<ide> * @return array
<ide> */
<del> protected function _convertValidatorToArray($fieldName, $defaults = [], $settings = [])
<add> protected function _convertValidatorToArray($fieldName, $defaults = [], $settings = []): array
<ide> {
<ide> if (is_string($settings)) {
<ide> $fieldName = $settings;
<ide> public function notEmpty($field, $message = null, $when = false)
<ide> * @see \Cake\Validation\Validation::notBlank()
<ide> * @return $this
<ide> */
<del> public function notBlank($field, $message = null, $when = null)
<add> public function notBlank(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function notBlank($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::alphaNumeric()
<ide> * @return $this
<ide> */
<del> public function alphaNumeric($field, $message = null, $when = null)
<add> public function alphaNumeric(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function alphaNumeric($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::alphaNumeric()
<ide> * @return $this
<ide> */
<del> public function lengthBetween($field, array $range, $message = null, $when = null)
<add> public function lengthBetween(string $field, array $range, ?string $message = null, $when = null)
<ide> {
<ide> if (count($range) !== 2) {
<ide> throw new InvalidArgumentException('The $range argument requires 2 numbers');
<ide> public function lengthBetween($field, array $range, $message = null, $when = nul
<ide> * @see \Cake\Validation\Validation::cc()
<ide> * @return $this
<ide> */
<del> public function creditCard($field, $type = 'all', $message = null, $when = null)
<add> public function creditCard(string $field, string $type = 'all', ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function creditCard($field, $type = 'all', $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::comparison()
<ide> * @return $this
<ide> */
<del> public function greaterThan($field, $value, $message = null, $when = null)
<add> public function greaterThan(string $field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function greaterThan($field, $value, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::comparison()
<ide> * @return $this
<ide> */
<del> public function greaterThanOrEqual($field, $value, $message = null, $when = null)
<add> public function greaterThanOrEqual(string $field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function greaterThanOrEqual($field, $value, $message = null, $when = null
<ide> * @see \Cake\Validation\Validation::comparison()
<ide> * @return $this
<ide> */
<del> public function lessThan($field, $value, $message = null, $when = null)
<add> public function lessThan(string $field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function lessThan($field, $value, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::comparison()
<ide> * @return $this
<ide> */
<del> public function lessThanOrEqual($field, $value, $message = null, $when = null)
<add> public function lessThanOrEqual(string $field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function lessThanOrEqual($field, $value, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::comparison()
<ide> * @return $this
<ide> */
<del> public function equals($field, $value, $message = null, $when = null)
<add> public function equals(string $field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function equals($field, $value, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::comparison()
<ide> * @return $this
<ide> */
<del> public function notEquals($field, $value, $message = null, $when = null)
<add> public function notEquals(string $field, $value, $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function notEquals($field, $value, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::compareFields()
<ide> * @return $this
<ide> */
<del> public function sameAs($field, $secondField, $message = null, $when = null)
<add> public function sameAs(string $field, string $secondField, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function sameAs($field, $secondField, $message = null, $when = null)
<ide> * @return $this
<ide> * @since 3.6.0
<ide> */
<del> public function notSameAs($field, $secondField, $message = null, $when = null)
<add> public function notSameAs(string $field, string $secondField, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function notSameAs($field, $secondField, $message = null, $when = null)
<ide> * @return $this
<ide> * @since 3.6.0
<ide> */
<del> public function equalToField($field, $secondField, $message = null, $when = null)
<add> public function equalToField(string $field, string $secondField, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function equalToField($field, $secondField, $message = null, $when = null
<ide> * @return $this
<ide> * @since 3.6.0
<ide> */
<del> public function notEqualToField($field, $secondField, $message = null, $when = null)
<add> public function notEqualToField(string $field, string $secondField, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function notEqualToField($field, $secondField, $message = null, $when = n
<ide> * @return $this
<ide> * @since 3.6.0
<ide> */
<del> public function greaterThanField($field, $secondField, $message = null, $when = null)
<add> public function greaterThanField(string $field, string $secondField, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function greaterThanField($field, $secondField, $message = null, $when =
<ide> * @return $this
<ide> * @since 3.6.0
<ide> */
<del> public function greaterThanOrEqualToField($field, $secondField, $message = null, $when = null)
<add> public function greaterThanOrEqualToField(string $field, string $secondField, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function greaterThanOrEqualToField($field, $secondField, $message = null,
<ide> * @return $this
<ide> * @since 3.6.0
<ide> */
<del> public function lessThanField($field, $secondField, $message = null, $when = null)
<add> public function lessThanField(string $field, string $secondField, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function lessThanField($field, $secondField, $message = null, $when = nul
<ide> * @return $this
<ide> * @since 3.6.0
<ide> */
<del> public function lessThanOrEqualToField($field, $secondField, $message = null, $when = null)
<add> public function lessThanOrEqualToField(string $field, string $secondField, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function lessThanOrEqualToField($field, $secondField, $message = null, $w
<ide> * @see \Cake\Validation\Validation::containsNonAlphaNumeric()
<ide> * @return $this
<ide> */
<del> public function containsNonAlphaNumeric($field, $limit = 1, $message = null, $when = null)
<add> public function containsNonAlphaNumeric(string $field, int $limit = 1, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function containsNonAlphaNumeric($field, $limit = 1, $message = null, $wh
<ide> * @see \Cake\Validation\Validation::date()
<ide> * @return $this
<ide> */
<del> public function date($field, $formats = ['ymd'], $message = null, $when = null)
<add> public function date(string $field, array $formats = ['ymd'], ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function date($field, $formats = ['ymd'], $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::datetime()
<ide> * @return $this
<ide> */
<del> public function dateTime($field, $formats = ['ymd'], $message = null, $when = null)
<add> public function dateTime(string $field, array $formats = ['ymd'], ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function dateTime($field, $formats = ['ymd'], $message = null, $when = nu
<ide> * @see \Cake\Validation\Validation::time()
<ide> * @return $this
<ide> */
<del> public function time($field, $message = null, $when = null)
<add> public function time(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function time($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::localizedTime()
<ide> * @return $this
<ide> */
<del> public function localizedTime($field, $type = 'datetime', $message = null, $when = null)
<add> public function localizedTime(string $field, string $type = 'datetime', ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function localizedTime($field, $type = 'datetime', $message = null, $when
<ide> * @see \Cake\Validation\Validation::boolean()
<ide> * @return $this
<ide> */
<del> public function boolean($field, $message = null, $when = null)
<add> public function boolean(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function boolean($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::decimal()
<ide> * @return $this
<ide> */
<del> public function decimal($field, $places = null, $message = null, $when = null)
<add> public function decimal(string $field, ?int $places = null, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function decimal($field, $places = null, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::email()
<ide> * @return $this
<ide> */
<del> public function email($field, $checkMX = false, $message = null, $when = null)
<add> public function email(string $field, bool $checkMX = false, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function email($field, $checkMX = false, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::ip()
<ide> * @return $this
<ide> */
<del> public function ip($field, $message = null, $when = null)
<add> public function ip(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function ip($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::ip()
<ide> * @return $this
<ide> */
<del> public function ipv4($field, $message = null, $when = null)
<add> public function ipv4(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function ipv4($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::ip()
<ide> * @return $this
<ide> */
<del> public function ipv6($field, $message = null, $when = null)
<add> public function ipv6(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function ipv6($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::minLength()
<ide> * @return $this
<ide> */
<del> public function minLength($field, $min, $message = null, $when = null)
<add> public function minLength(string $field, int $min, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function minLength($field, $min, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::minLengthBytes()
<ide> * @return $this
<ide> */
<del> public function minLengthBytes($field, $min, $message = null, $when = null)
<add> public function minLengthBytes(string $field, int $min, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function minLengthBytes($field, $min, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::maxLength()
<ide> * @return $this
<ide> */
<del> public function maxLength($field, $max, $message = null, $when = null)
<add> public function maxLength(string $field, int $max, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function maxLength($field, $max, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::maxLengthBytes()
<ide> * @return $this
<ide> */
<del> public function maxLengthBytes($field, $max, $message = null, $when = null)
<add> public function maxLengthBytes(string $field, int $max, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function maxLengthBytes($field, $max, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::numeric()
<ide> * @return $this
<ide> */
<del> public function numeric($field, $message = null, $when = null)
<add> public function numeric(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function numeric($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::naturalNumber()
<ide> * @return $this
<ide> */
<del> public function naturalNumber($field, $message = null, $when = null)
<add> public function naturalNumber(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function naturalNumber($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::naturalNumber()
<ide> * @return $this
<ide> */
<del> public function nonNegativeInteger($field, $message = null, $when = null)
<add> public function nonNegativeInteger(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function nonNegativeInteger($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::range()
<ide> * @return $this
<ide> */
<del> public function range($field, array $range, $message = null, $when = null)
<add> public function range(string $field, array $range, ?string $message = null, $when = null)
<ide> {
<ide> if (count($range) !== 2) {
<ide> throw new InvalidArgumentException('The $range argument requires 2 numbers');
<ide> public function range($field, array $range, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::url()
<ide> * @return $this
<ide> */
<del> public function url($field, $message = null, $when = null)
<add> public function url(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function url($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::url()
<ide> * @return $this
<ide> */
<del> public function urlWithProtocol($field, $message = null, $when = null)
<add> public function urlWithProtocol(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function urlWithProtocol($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::inList()
<ide> * @return $this
<ide> */
<del> public function inList($field, array $list, $message = null, $when = null)
<add> public function inList(string $field, array $list, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function inList($field, array $list, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::uuid()
<ide> * @return $this
<ide> */
<del> public function uuid($field, $message = null, $when = null)
<add> public function uuid(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function uuid($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::uploadedFile()
<ide> * @return $this
<ide> */
<del> public function uploadedFile($field, array $options, $message = null, $when = null)
<add> public function uploadedFile(string $field, array $options, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function uploadedFile($field, array $options, $message = null, $when = nu
<ide> * @see \Cake\Validation\Validation::uuid()
<ide> * @return $this
<ide> */
<del> public function latLong($field, $message = null, $when = null)
<add> public function latLong(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function latLong($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::latitude()
<ide> * @return $this
<ide> */
<del> public function latitude($field, $message = null, $when = null)
<add> public function latitude(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function latitude($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::longitude()
<ide> * @return $this
<ide> */
<del> public function longitude($field, $message = null, $when = null)
<add> public function longitude(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function longitude($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::ascii()
<ide> * @return $this
<ide> */
<del> public function ascii($field, $message = null, $when = null)
<add> public function ascii(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function ascii($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::utf8()
<ide> * @return $this
<ide> */
<del> public function utf8($field, $message = null, $when = null)
<add> public function utf8(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function utf8($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::utf8()
<ide> * @return $this
<ide> */
<del> public function utf8Extended($field, $message = null, $when = null)
<add> public function utf8Extended(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function utf8Extended($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::isInteger()
<ide> * @return $this
<ide> */
<del> public function integer($field, $message = null, $when = null)
<add> public function integer(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function integer($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::isArray()
<ide> * @return $this
<ide> */
<del> public function isArray($field, $message = null, $when = null)
<add> public function isArray(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function isArray($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::isScalar()
<ide> * @return $this
<ide> */
<del> public function scalar($field, $message = null, $when = null)
<add> public function scalar(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function scalar($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::hexColor()
<ide> * @return $this
<ide> */
<del> public function hexColor($field, $message = null, $when = null)
<add> public function hexColor(string $field, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function hexColor($field, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::multiple()
<ide> * @return $this
<ide> */
<del> public function multipleOptions($field, array $options = [], $message = null, $when = null)
<add> public function multipleOptions(string $field, array $options = [], ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide> $caseInsensitive = $options['caseInsensitive'] ?? false;
<ide> public function multipleOptions($field, array $options = [], $message = null, $w
<ide> * @see \Cake\Validation\Validation::numElements()
<ide> * @return $this
<ide> */
<del> public function hasAtLeast($field, $count, $message = null, $when = null)
<add> public function hasAtLeast(string $field, int $count, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function hasAtLeast($field, $count, $message = null, $when = null)
<ide> * @see \Cake\Validation\Validation::numElements()
<ide> * @return $this
<ide> */
<del> public function hasAtMost($field, $count, $message = null, $when = null)
<add> public function hasAtMost(string $field, int $count, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function hasAtMost($field, $count, $message = null, $when = null)
<ide> * @param bool $newRecord whether the data to be validated is new or to be updated.
<ide> * @return bool
<ide> */
<del> public function isEmptyAllowed($field, $newRecord)
<add> public function isEmptyAllowed(string $field, bool $newRecord): bool
<ide> {
<ide> $providers = $this->_providers;
<ide> $data = [];
<ide> public function isEmptyAllowed($field, $newRecord)
<ide> * @param bool $newRecord Whether the data to be validated is new or to be updated.
<ide> * @return bool
<ide> */
<del> public function isPresenceRequired($field, $newRecord)
<add> public function isPresenceRequired(string $field, bool $newRecord): bool
<ide> {
<ide> $providers = $this->_providers;
<ide> $data = [];
<ide> public function isPresenceRequired($field, $newRecord)
<ide> * true when the validation rule should be applied.
<ide> * @return $this
<ide> */
<del> public function regex($field, $regex, $message = null, $when = null)
<add> public function regex(string $field, string $regex, ?string $message = null, $when = null)
<ide> {
<ide> $extra = array_filter(['on' => $when, 'message' => $message]);
<ide>
<ide> public function regex($field, $regex, $message = null, $when = null)
<ide> * @param string $field Field name
<ide> * @return string|null
<ide> */
<del> public function getRequiredMessage($field)
<add> public function getRequiredMessage(string $field): ?string
<ide> {
<ide> if (!isset($this->_fields[$field])) {
<ide> return null;
<ide> public function getRequiredMessage($field)
<ide> * @param string $field Field name
<ide> * @return string|null
<ide> */
<del> public function getNotEmptyMessage($field)
<add> public function getNotEmptyMessage(string $field): ?string
<ide> {
<ide> if (!isset($this->_fields[$field])) {
<ide> return null;
<ide> public function getNotEmptyMessage($field)
<ide> * @param array $context A key value list of data containing the validation context.
<ide> * @return bool
<ide> */
<del> protected function _checkPresence($field, $context)
<add> protected function _checkPresence(\Cake\Validation\ValidationSet $field, array $context): bool
<ide> {
<ide> $required = $field->isPresenceRequired();
<ide>
<ide> protected function _checkPresence($field, $context)
<ide> * @param array $context a key value list of data containing the validation context.
<ide> * @return bool
<ide> */
<del> protected function _canBeEmpty($field, $context)
<add> protected function _canBeEmpty(\Cake\Validation\ValidationSet $field, array $context): bool
<ide> {
<ide> $allowed = $field->isEmptyAllowed();
<ide>
<ide> protected function _canBeEmpty($field, $context)
<ide> * @param mixed $data value to check against
<ide> * @return bool
<ide> */
<del> protected function _fieldIsEmpty($data)
<add> protected function _fieldIsEmpty($data): bool
<ide> {
<ide> if (empty($data) && !is_bool($data) && !is_numeric($data)) {
<ide> return true;
<ide> protected function _fieldIsEmpty($data)
<ide> * @param bool $newRecord whether is it a new record or an existing one
<ide> * @return array
<ide> */
<del> protected function _processRules($field, ValidationSet $rules, $data, $newRecord)
<add> protected function _processRules(string $field, ValidationSet $rules, array $data, bool $newRecord): array
<ide> {
<ide> $errors = [];
<ide> // Loading default provider in case there is none
<ide> protected function _processRules($field, ValidationSet $rules, $data, $newRecord
<ide> *
<ide> * @return array
<ide> */
<del> public function __debugInfo()
<add> public function __debugInfo(): array
<ide> {
<ide> $fields = [];
<ide> foreach ($this->_fields as $name => $fieldSet) {
<ide><path>src/Validation/ValidatorAwareInterface.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> interface ValidatorAwareInterface
<ide> * @param string|null $name The name of the validation set to return.
<ide> * @return \Cake\Validation\Validator
<ide> */
<del> public function getValidator($name = null);
<add> public function getValidator(?string $name = null): Validator;
<ide>
<ide> /**
<ide> * This method stores a custom validator under the given name.
<ide> public function getValidator($name = null);
<ide> * @param \Cake\Validation\Validator $validator Validator object to be set.
<ide> * @return $this
<ide> */
<del> public function setValidator($name, Validator $validator);
<add> public function setValidator(string $name, Validator $validator);
<ide>
<ide> /**
<ide> * Checks whether or not a validator has been set.
<ide> *
<ide> * @param string $name The name of a validator.
<ide> * @return bool
<ide> */
<del> public function hasValidator($name);
<add> public function hasValidator(string $name): bool;
<ide> }
<ide><path>src/Validation/ValidatorAwareTrait.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> trait ValidatorAwareTrait
<ide> * @param string|null $name The name of the validation set to return.
<ide> * @return \Cake\Validation\Validator
<ide> */
<del> public function getValidator($name = null)
<add> public function getValidator(?string $name = null): Validator
<ide> {
<ide> $name = $name ?: self::DEFAULT_VALIDATOR;
<ide> if (!isset($this->_validators[$name])) {
<ide> public function getValidator($name = null)
<ide> * @return \Cake\Validation\Validator
<ide> * @throws \RuntimeException
<ide> */
<del> protected function createValidator($name)
<add> protected function createValidator(string $name): Validator
<ide> {
<ide> $method = 'validation' . ucfirst($name);
<ide> if (!$this->validationMethodExists($method)) {
<ide> protected function createValidator($name)
<ide> * @param \Cake\Validation\Validator $validator Validator object to be set.
<ide> * @return $this
<ide> */
<del> public function setValidator($name, Validator $validator)
<add> public function setValidator(string $name, Validator $validator)
<ide> {
<ide> $validator->setProvider(self::VALIDATOR_PROVIDER_NAME, $this);
<ide> $this->_validators[$name] = $validator;
<ide> public function setValidator($name, Validator $validator)
<ide> * @param string $name The name of a validator.
<ide> * @return bool
<ide> */
<del> public function hasValidator($name)
<add> public function hasValidator(string $name): bool
<ide> {
<ide> $method = 'validation' . ucfirst($name);
<ide> if ($this->validationMethodExists($method)) {
<ide> public function hasValidator($name)
<ide> * @param string $name Validation method name.
<ide> * @return bool
<ide> */
<del> protected function validationMethodExists($name)
<add> protected function validationMethodExists(string $name): bool
<ide> {
<ide> return method_exists($this, $name);
<ide> }
<ide> protected function validationMethodExists($name)
<ide> * add some rules to it.
<ide> * @return \Cake\Validation\Validator
<ide> */
<del> public function validationDefault(Validator $validator)
<add> public function validationDefault(Validator $validator): Validator
<ide> {
<ide> return $validator;
<ide> }
<ide><path>tests/TestCase/Validation/RulesProviderTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide>
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Validation\RulesProvider;
<add>use Cake\Validation\ValidationSet;
<ide>
<ide> /**
<ide> * Tests RulesProvider class
<ide> public function testCustomObject()
<ide> $mock->expects($this->once())
<ide> ->method('field')
<ide> ->with('first', null)
<del> ->will($this->returnValue(true));
<add> ->will($this->returnValue(new ValidationSet()));
<ide>
<ide> $provider = new RulesProvider($mock);
<ide> $provider->field('first', compact('provider'));
<ide><path>tests/TestCase/Validation/ValidationRuleTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) Tests <https://book.cakephp.org/view/1196/Testing>
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Validation/ValidationSetTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * ValidationSetTest file
<ide> *
<ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function testAllCcDeep()
<ide> */
<ide> public function testComparison()
<ide> {
<del> $this->assertFalse(Validation::comparison(7, null, 6));
<ide> $this->assertTrue(Validation::comparison(7, Validation::COMPARE_GREATER, 6));
<ide> $this->assertTrue(Validation::comparison(6, Validation::COMPARE_LESS, 7));
<ide> $this->assertTrue(Validation::comparison(7, Validation::COMPARE_GREATER_OR_EQUAL, 7));
<ide><path>tests/TestCase/Validation/ValidatorTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function testGetDefaultProvider()
<ide> $this->assertEquals(Validator::getDefaultProvider('test-provider'), 'MyNameSpace\Validation\MyProvider', 'Default provider `test-provider` is missing');
<ide>
<ide> $this->assertNull(Validator::getDefaultProvider('invalid-provider'), 'Default provider (`invalid-provider`) should be missing');
<del> $this->assertNull(Validator::getDefaultProvider(null), 'Default provider (null) should be missing');
<ide>
<ide> Validator::addDefaultProvider('test-provider2', 'MyNameSpace\Validation\MySecondProvider');
<ide> $this->assertEquals(Validator::getDefaultProviders(), ['test-provider', 'test-provider2'], 'Default providers incorrect');
<ide><path>tests/TestCase/Validation/stubs.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) | 14 |
PHP | PHP | fix cs error | a42d24c5d0fcad2e199b3fe7ed53be51f219bd33 | <ide><path>src/Mailer/Mailer.php
<ide> abstract class Mailer implements EventListenerInterface
<ide> *
<ide> * @var string
<ide> */
<del> static public $name;
<add> public static $name;
<ide>
<ide> /**
<ide> * Email instance.
<ide><path>tests/TestCase/Cache/Engine/ApcuEngineTest.php
<ide> class ApcuEngineTest extends TestCase
<ide> *
<ide> * @var bool
<ide> */
<del> static protected $useRequestTime = null;
<add> protected static $useRequestTime = null;
<ide>
<ide> /**
<ide> * Ensure use_request_time is turned off | 2 |
Ruby | Ruby | add deprecation_date and disable_date methods | 2eb34b0b27160ed26f46594ff21bd2a629176398 | <ide><path>Library/Homebrew/formula.rb
<ide> def link_overwrite?(path)
<ide> # @return [Boolean]
<ide> delegate deprecated?: :"self.class"
<ide>
<add> # The date that this {Formula} was or becomes deprecated.
<add> # Returns `nil` if no date is specified.
<add> # @!method deprecation_date
<add> # @return Date
<add> delegate deprecation_date: :"self.class"
<add>
<ide> # The reason this {Formula} is deprecated.
<ide> # Returns `nil` if no reason is specified or the formula is not deprecated.
<ide> # @!method deprecation_reason
<ide> def link_overwrite?(path)
<ide> # @return [Boolean]
<ide> delegate disabled?: :"self.class"
<ide>
<add> # The date that this {Formula} was or becomes disabled.
<add> # Returns `nil` if no date is specified.
<add> # @!method disable_date
<add> # @return Date
<add> delegate disable_date: :"self.class"
<add>
<ide> # The reason this {Formula} is disabled.
<ide> # Returns `nil` if no reason is specified or the formula is not disabled.
<ide> # @!method disable_reason
<ide> def deprecate!(date: nil, because: nil)
<ide> odeprecated "`deprecate!` without a reason", "`deprecate! because: \"reason\"`" if because.blank?
<ide> odeprecated "`deprecate!` without a date", "`deprecate! date: \"#{Date.today}\"`" if date.blank?
<ide>
<add> @deprecation_date = Date.parse(date) if date.present?
<add>
<ide> return if date.present? && Date.parse(date) > Date.today
<ide>
<ide> @deprecation_reason = because if because.present?
<ide> def deprecated?
<ide> @deprecated == true
<ide> end
<ide>
<add> # The date that this {Formula} was or becomes deprecated.
<add> # Returns `nil` if no date is specified.
<add> # @return Date
<add> attr_reader :deprecation_date
<add>
<ide> # The reason for deprecation of a {Formula}.
<ide> # @return [nil] if no reason was provided or the formula is not deprecated.
<ide> # @return [String, Symbol]
<ide> def disable!(date: nil, because: nil)
<ide> odeprecated "`disable!` without a reason", "`disable! because: \"reason\"`" if because.blank?
<ide> odeprecated "`disable!` without a date", "`disable! date: \"#{Date.today}\"`" if date.blank?
<ide>
<del> if date.present? && Date.parse(date) > Date.today
<add> @disable_date = Date.parse(date) if date.present?
<add>
<add> if @disable_date && @disable_date > Date.today
<ide> @deprecation_reason = because if because.present?
<ide> @deprecated = true
<ide> return
<ide> def disabled?
<ide> @disabled == true
<ide> end
<ide>
<add> # The date that this {Formula} was or becomes disabled.
<add> # Returns `nil` if no date is specified.
<add> # @return Date
<add> attr_reader :disable_date
<add>
<ide> # The reason this {Formula} is disabled.
<ide> # Returns `nil` if no reason was provided or the formula is not disabled.
<ide> # @return [String, Symbol] | 1 |
PHP | PHP | fix bug in route handles method | 9bcbe6a357a0f33aabdd7d529c447fe86ae6b04a | <ide><path>laravel/routing/route.php
<ide> public function is($name)
<ide> */
<ide> public function handles($uri)
<ide> {
<del> $pattern = '#'.str_replace('*', '(.*)', $uri).'#';
<add> $pattern = ($uri !== '/') ? str_replace('*', '(.*)', $uri) : '^/$';
<ide>
<ide> return ! is_null(array_first($this->uris, function($key, $uri) use ($pattern)
<ide> {
<del> return preg_match($pattern, $uri);
<add> return preg_match('#'.$pattern.'#', $uri);
<ide> }));
<ide> }
<ide>
<ide><path>tests/cases/laravel/route.test.php
<ide> public function testHandlesIndicatesIfTheRouteHandlesAGivenURI()
<ide> {
<ide> $route = new Laravel\Routing\Route('GET /', array('handles' => array('GET /foo/bar')));
<ide>
<del> $this->assertFalse($route->handles('/'));
<del> $this->assertFalse($route->handles('baz'));
<ide> $this->assertTrue($route->handles('foo/*'));
<ide> $this->assertTrue($route->handles('foo/bar'));
<add> $this->assertFalse($route->handles('/'));
<add> $this->assertFalse($route->handles('baz'));
<add> $this->assertFalse($route->handles('/foo'));
<ide>
<ide> $route = new Laravel\Routing\Route('GET /', array('handles' => array('GET /', 'GET /home')));
<ide> | 2 |
Python | Python | fix mini scheduler expansion of mapped task | ed92e5d521f958642615b038ec13068b527db1c4 | <ide><path>airflow/jobs/local_task_job.py
<ide> from __future__ import annotations
<ide>
<ide> import signal
<del>from typing import TYPE_CHECKING
<ide>
<ide> import psutil
<del>from sqlalchemy.exc import OperationalError
<ide>
<ide> from airflow.configuration import conf
<ide> from airflow.exceptions import AirflowException
<ide> from airflow.jobs.base_job import BaseJob
<ide> from airflow.listeners.events import register_task_instance_state_events
<ide> from airflow.listeners.listener import get_listener_manager
<del>from airflow.models.dagrun import DagRun
<ide> from airflow.models.taskinstance import TaskInstance
<del>from airflow.sentry import Sentry
<ide> from airflow.stats import Stats
<ide> from airflow.task.task_runner import get_task_runner
<ide> from airflow.utils import timezone
<ide> from airflow.utils.net import get_hostname
<ide> from airflow.utils.session import provide_session
<del>from airflow.utils.sqlalchemy import with_row_locks
<ide> from airflow.utils.state import State
<ide>
<ide>
<ide> def handle_task_exit(self, return_code: int) -> None:
<ide>
<ide> if not self.task_instance.test_mode:
<ide> if conf.getboolean('scheduler', 'schedule_after_task_execution', fallback=True):
<del> self._run_mini_scheduler_on_child_tasks()
<add> self.task_instance.schedule_downstream_tasks()
<ide>
<ide> def on_kill(self):
<ide> self.task_runner.terminate()
<ide> def heartbeat_callback(self, session=None):
<ide> self.terminating = True
<ide> self._state_change_checks += 1
<ide>
<del> @provide_session
<del> @Sentry.enrich_errors
<del> def _run_mini_scheduler_on_child_tasks(self, session=None) -> None:
<del> try:
<del> # Re-select the row with a lock
<del> dag_run = with_row_locks(
<del> session.query(DagRun).filter_by(
<del> dag_id=self.dag_id,
<del> run_id=self.task_instance.run_id,
<del> ),
<del> session=session,
<del> ).one()
<del>
<del> task = self.task_instance.task
<del> if TYPE_CHECKING:
<del> assert task.dag
<del>
<del> # Get a partial DAG with just the specific tasks we want to examine.
<del> # In order for dep checks to work correctly, we include ourself (so
<del> # TriggerRuleDep can check the state of the task we just executed).
<del> partial_dag = task.dag.partial_subset(
<del> task.downstream_task_ids,
<del> include_downstream=True,
<del> include_upstream=False,
<del> include_direct_upstream=True,
<del> )
<del>
<del> dag_run.dag = partial_dag
<del> info = dag_run.task_instance_scheduling_decisions(session)
<del>
<del> skippable_task_ids = {
<del> task_id for task_id in partial_dag.task_ids if task_id not in task.downstream_task_ids
<del> }
<del>
<del> schedulable_tis = [ti for ti in info.schedulable_tis if ti.task_id not in skippable_task_ids]
<del> for schedulable_ti in schedulable_tis:
<del> if not hasattr(schedulable_ti, "task"):
<del> schedulable_ti.task = task.dag.get_task(schedulable_ti.task_id)
<del>
<del> num = dag_run.schedule_tis(schedulable_tis)
<del> self.log.info("%d downstream tasks scheduled from follow-on schedule check", num)
<del>
<del> session.commit()
<del> except OperationalError as e:
<del> # Any kind of DB error here is _non fatal_ as this block is just an optimisation.
<del> self.log.info(
<del> "Skipping mini scheduling run due to exception: %s",
<del> e.statement,
<del> exc_info=True,
<del> )
<del> session.rollback()
<del>
<ide> @staticmethod
<ide> def _enable_task_listeners():
<ide> """
<ide><path>airflow/models/mappedoperator.py
<ide> def expand_mapped_task(self, run_id: str, *, session: Session) -> tuple[Sequence
<ide> try:
<ide> total_length = self._get_specified_expand_input().get_total_map_length(run_id, session=session)
<ide> except NotFullyPopulated as e:
<del> self.log.info(
<del> "Cannot expand %r for run %s; missing upstream values: %s",
<del> self,
<del> run_id,
<del> sorted(e.missing),
<del> )
<ide> total_length = None
<add> # partial dags comes from the mini scheduler. It's
<add> # possible that the upstream tasks are not yet done,
<add> # but we don't have upstream of upstreams in partial dags,
<add> # so we ignore this exception.
<add> if not self.dag or not self.dag.partial:
<add> self.log.error(
<add> "Cannot expand %r for run %s; missing upstream values: %s",
<add> self,
<add> run_id,
<add> sorted(e.missing),
<add> )
<ide>
<ide> state: TaskInstanceState | None = None
<ide> unmapped_ti: TaskInstance | None = (
<ide> def expand_mapped_task(self, run_id: str, *, session: Session) -> tuple[Sequence
<ide> # The unmapped task instance still exists and is unfinished, i.e. we
<ide> # haven't tried to run it before.
<ide> if total_length is None:
<del> # If the map length cannot be calculated (due to unavailable
<del> # upstream sources), fail the unmapped task.
<del> unmapped_ti.state = TaskInstanceState.UPSTREAM_FAILED
<del> indexes_to_map: Iterable[int] = ()
<add> if self.dag and self.dag.partial:
<add> # If the DAG is partial, it's likely that the upstream tasks
<add> # are not done yet, so we do nothing
<add> indexes_to_map: Iterable[int] = ()
<add> else:
<add> # If the map length cannot be calculated (due to unavailable
<add> # upstream sources), fail the unmapped task.
<add> unmapped_ti.state = TaskInstanceState.UPSTREAM_FAILED
<add> indexes_to_map = ()
<ide> elif total_length < 1:
<ide> # If the upstream maps this to a zero-length value, simply mark
<ide> # the unmapped task instance as SKIPPED (if needed).
<ide><path>airflow/models/taskinstance.py
<ide> def ti_selector_condition(cls, vals: Collection[str | tuple[str, int]]) -> Colum
<ide> return filters[0]
<ide> return or_(*filters)
<ide>
<add> @Sentry.enrich_errors
<add> @provide_session
<add> def schedule_downstream_tasks(self, session=None):
<add> """
<add> The mini-scheduler for scheduling downstream tasks of this task instance
<add> :meta: private
<add> """
<add> from sqlalchemy.exc import OperationalError
<add>
<add> from airflow.models import DagRun
<add>
<add> try:
<add> # Re-select the row with a lock
<add> dag_run = with_row_locks(
<add> session.query(DagRun).filter_by(
<add> dag_id=self.dag_id,
<add> run_id=self.run_id,
<add> ),
<add> session=session,
<add> ).one()
<add>
<add> task = self.task
<add> if TYPE_CHECKING:
<add> assert task.dag
<add>
<add> # Get a partial DAG with just the specific tasks we want to examine.
<add> # In order for dep checks to work correctly, we include ourself (so
<add> # TriggerRuleDep can check the state of the task we just executed).
<add> partial_dag = task.dag.partial_subset(
<add> task.downstream_task_ids,
<add> include_downstream=True,
<add> include_upstream=False,
<add> include_direct_upstream=True,
<add> )
<add>
<add> dag_run.dag = partial_dag
<add> info = dag_run.task_instance_scheduling_decisions(session)
<add>
<add> skippable_task_ids = {
<add> task_id for task_id in partial_dag.task_ids if task_id not in task.downstream_task_ids
<add> }
<add>
<add> schedulable_tis = [ti for ti in info.schedulable_tis if ti.task_id not in skippable_task_ids]
<add> for schedulable_ti in schedulable_tis:
<add> if not hasattr(schedulable_ti, "task"):
<add> schedulable_ti.task = task.dag.get_task(schedulable_ti.task_id)
<add>
<add> num = dag_run.schedule_tis(schedulable_tis, session=session)
<add> self.log.info("%d downstream tasks scheduled from follow-on schedule check", num)
<add>
<add> session.flush()
<add>
<add> except OperationalError as e:
<add> # Any kind of DB error here is _non fatal_ as this block is just an optimisation.
<add> self.log.info(
<add> "Skipping mini scheduling run due to exception: %s",
<add> e.statement,
<add> exc_info=True,
<add> )
<add> session.rollback()
<add>
<ide>
<ide> # State of the task instance.
<ide> # Stores string version of the task state.
<ide><path>tests/jobs/test_local_task_job.py
<ide> def test_mini_scheduler_works_with_wait_for_upstream(self, caplog, get_test_dag)
<ide> ti2_l.refresh_from_db()
<ide> assert ti2_k.state == State.SUCCESS
<ide> assert ti2_l.state == State.NONE
<del> assert "0 downstream tasks scheduled from follow-on schedule" in caplog.text
<ide>
<ide> failed_deps = list(ti2_l.get_failed_dep_statuses())
<ide> assert len(failed_deps) == 1
<ide><path>tests/models/test_taskinstance.py
<ide> def get_extra_env():
<ide>
<ide> echo_task = dag.get_task("echo")
<ide> assert "get_extra_env" in echo_task.upstream_task_ids
<add>
<add>
<add>def test_mapped_task_does_not_error_in_mini_scheduler_if_upstreams_are_not_done(dag_maker, caplog, session):
<add> """
<add> This tests that when scheduling child tasks of a task and there's a mapped downstream task,
<add> if the mapped downstream task has upstreams that are not yet done, the mapped downstream task is
<add> not marked as `upstream_failed'
<add> """
<add> with dag_maker() as dag:
<add>
<add> @dag.task
<add> def second_task():
<add> return [0, 1, 2]
<add>
<add> @dag.task
<add> def first_task():
<add> print(2)
<add>
<add> @dag.task
<add> def middle_task(id):
<add> return id
<add>
<add> middle = middle_task.expand(id=second_task())
<add>
<add> @dag.task
<add> def last_task():
<add> print(3)
<add>
<add> [first_task(), middle] >> last_task()
<add>
<add> dag_run = dag_maker.create_dagrun()
<add> first_ti = dag_run.get_task_instance(task_id="first_task")
<add> second_ti = dag_run.get_task_instance(task_id="second_task")
<add> first_ti.state = State.SUCCESS
<add> second_ti.state = State.RUNNING
<add> session.merge(first_ti)
<add> session.merge(second_ti)
<add> session.commit()
<add> first_ti.schedule_downstream_tasks(session=session)
<add> middle_ti = dag_run.get_task_instance(task_id="middle_task")
<add> assert middle_ti.state != State.UPSTREAM_FAILED
<add> assert "0 downstream tasks scheduled from follow-on schedule" in caplog.text
<add>
<add>
<add>def test_mapped_task_expands_in_mini_scheduler_if_upstreams_are_done(dag_maker, caplog, session):
<add> """Test that mini scheduler expands mapped task"""
<add> with dag_maker() as dag:
<add>
<add> @dag.task
<add> def second_task():
<add> return [0, 1, 2]
<add>
<add> @dag.task
<add> def first_task():
<add> print(2)
<add>
<add> @dag.task
<add> def middle_task(id):
<add> return id
<add>
<add> middle = middle_task.expand(id=second_task())
<add>
<add> @dag.task
<add> def last_task():
<add> print(3)
<add>
<add> [first_task(), middle] >> last_task()
<add>
<add> dr = dag_maker.create_dagrun()
<add>
<add> first_ti = dr.get_task_instance(task_id="first_task")
<add> first_ti.state = State.SUCCESS
<add> session.merge(first_ti)
<add> session.commit()
<add> second_task = dag.get_task("second_task")
<add> second_ti = dr.get_task_instance(task_id="second_task")
<add> second_ti.refresh_from_task(second_task)
<add> second_ti.run()
<add> second_ti.schedule_downstream_tasks(session=session)
<add> for i in range(3):
<add> middle_ti = dr.get_task_instance(task_id="middle_task", map_index=i)
<add> assert middle_ti.state == State.SCHEDULED
<add> assert "3 downstream tasks scheduled from follow-on schedule" in caplog.text | 5 |
Javascript | Javascript | fix regression when compiled with fips | 0a23538e49e27b95ee35b051b6507eca74e2bb20 | <ide><path>test/parallel/test-process-versions.js
<ide> assert(/^\d+\.\d+\.\d+(?:\.\d+)?-node\.\d+(?: \(candidate\))?$/
<ide> assert(/^\d+$/.test(process.versions.modules));
<ide>
<ide> if (common.hasCrypto) {
<del> assert(/^\d+\.\d+\.\d+[a-z]?$/.test(process.versions.openssl));
<add> assert(/^\d+\.\d+\.\d+[a-z]?(-fips)?$/.test(process.versions.openssl));
<ide> }
<ide>
<ide> for (let i = 0; i < expected_keys.length; i++) { | 1 |
Javascript | Javascript | add test for bypassing queuemicrotask | e2453e2007083a67bf93f59c8ef2f39df2aaf636 | <ide><path>packages/react-reconciler/src/__tests__/ReactIsomorphicAct-test.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @jest-environment node
<add> */
<add>
<add>// sanity tests for act()
<add>
<add>let React;
<add>let ReactNoop;
<add>let act;
<add>let DiscreteEventPriority;
<add>
<add>describe('isomorphic act()', () => {
<add> beforeEach(() => {
<add> React = require('react');
<add> ReactNoop = require('react-noop-renderer');
<add> DiscreteEventPriority = require('react-reconciler/constants')
<add> .DiscreteEventPriority;
<add> act = React.unstable_act;
<add> });
<add>
<add> // @gate __DEV__
<add> test('bypasses queueMicrotask', async () => {
<add> const root = ReactNoop.createRoot();
<add>
<add> // First test what happens without wrapping in act. This update would
<add> // normally be queued in a microtask.
<add> ReactNoop.unstable_runWithPriority(DiscreteEventPriority, () => {
<add> root.render('A');
<add> });
<add> // Nothing has rendered yet
<add> expect(root).toMatchRenderedOutput(null);
<add> // Flush the microtasks by awaiting
<add> await null;
<add> expect(root).toMatchRenderedOutput('A');
<add>
<add> // Now do the same thing but wrap the update with `act`. No
<add> // `await` necessary.
<add> act(() => {
<add> ReactNoop.unstable_runWithPriority(DiscreteEventPriority, () => {
<add> root.render('B');
<add> });
<add> });
<add> expect(root).toMatchRenderedOutput('B');
<add> });
<add>}); | 1 |
PHP | PHP | fix casing and conflicts | 9e80174f4a055a34fa9c40da51b7ac73deedf0fb | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function groupBy($groupBy)
<ide>
<ide> foreach ($this->items as $key => $value)
<ide> {
<del> $results[$this->getGroupbyKey($groupBy, $key, $value)][] = $value;
<add> $results[$this->getGroupByKey($groupBy, $key, $value)][] = $value;
<ide> }
<ide>
<ide> return new static($results);
<ide> public function groupBy($groupBy)
<ide> * @param mixed $value
<ide> * @return string
<ide> */
<del> protected function getGroupbyKey($groupBy, $key, $value)
<add> protected function getGroupByKey($groupBy, $key, $value)
<ide> {
<ide> if ( ! is_string($groupBy) && is_callable($groupBy))
<ide> { | 1 |
PHP | PHP | fix auth stub | 8fe1ff6804330d92bae2c376eb8e18e9205c4ca3 | <ide><path>src/Illuminate/Auth/Console/MakeAuthCommand.php
<ide> public function fire()
<ide> $this->info('Updated Routes File.');
<ide>
<ide> file_put_contents(
<del> app_path('Http/routes.php'),
<add> base_path('routes/web.php'),
<ide> file_get_contents(__DIR__.'/stubs/make/routes.stub'),
<ide> FILE_APPEND
<ide> ); | 1 |
Python | Python | add a test case for | 0710d23de52a1c2c4841937e4c7c17b81950b9ae | <ide><path>libcloud/test/storage/test_base.py
<ide> # limitations under the License.
<ide>
<ide> import sys
<add>import hashlib
<ide>
<ide> from libcloud.utils.py3 import httplib
<ide> from io import BytesIO
<ide>
<add>import mock
<ide> from mock import Mock
<ide>
<ide> from libcloud.utils.py3 import StringIO
<ide>
<ide> from libcloud.test import unittest
<ide> from libcloud.test import MockHttp
<add>from libcloud.test import BodyStream
<ide>
<ide>
<ide> class BaseMockRawResponse(MockHttp):
<ide> def test_upload_no_content_type_supplied_or_detected(self):
<ide> request_path='/',
<ide> stream=iterator)
<ide>
<add> @mock.patch('libcloud.utils.files.exhaust_iterator')
<add> @mock.patch('libcloud.utils.files.read_in_chunks')
<add> def test_upload_object_hash_calculation_is_efficient(self, mock_read_in_chunks,
<add> mock_exhaust_iterator):
<add> # Verify that we don't buffer whole file in memory when calculating
<add> # object has when iterator has __next__ method, but instead read and calculate hash in chunks
<add> size = 100
<add>
<add> mock_read_in_chunks.return_value = 'a' * size
<add>
<add> iterator = BodyStream('a' * size)
<add>
<add> upload_func = Mock()
<add> upload_func.return_value = True, '', size
<add>
<add> # strict_mode is disabled, default content type should be used
<add> self.driver1.connection = Mock()
<add>
<add> self.assertEqual(mock_read_in_chunks.call_count, 0)
<add> self.assertEqual(mock_exhaust_iterator.call_count, 0)
<add>
<add> result = self.driver1._upload_object(object_name='test',
<add> content_type=None,
<add> upload_func=upload_func,
<add> upload_func_kwargs={},
<add> request_path='/',
<add> stream=iterator)
<add>
<add> hasher = hashlib.md5()
<add> hasher.update('a' * size)
<add> expected_hash = hasher.hexdigest()
<add>
<add> self.assertEqual(result['data_hash'], expected_hash)
<add> self.assertEqual(result['bytes_transferred'], size)
<add>
<add> headers = self.driver1.connection.request.call_args[-1]['headers']
<add> self.assertEqual(headers['Content-Type'], DEFAULT_CONTENT_TYPE)
<add>
<add> self.assertEqual(mock_read_in_chunks.call_count, 1)
<add> self.assertEqual(mock_exhaust_iterator.call_count, 0)
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> sys.exit(unittest.main()) | 1 |
Text | Text | fix typo in change log | 80448c3341e6c072b06e69e2f265c849e64a4c27 | <ide><path>laravel/documentation/changes.md
<ide> - Fixed replacement of optional parameters in `URL::transpose` method.
<ide> - Improved `update` handling on `Has_Many` and `Has_One` relationships.
<ide> - Improved View performance by only loading contents from file once.
<del>- Fix handling of URLs beginning with has in `URL::to`.
<add>- Fix handling of URLs beginning with hashes in `URL::to`.
<ide> - Fix the resolution of unset Eloquent attributes.
<ide> - Allows pivot table timestamps to be disabled.
<ide> - Made the `get_timestamp` Eloquent method static. | 1 |
Python | Python | use builtin next method | a5cbc93168e08f7a083a7df174a44314c1af9bd4 | <ide><path>numpy/core/shape_base.py
<ide> def format_index(index):
<ide> idxs_ndims = (_block_check_depths_match(arr, parent_index + [i])
<ide> for i, arr in enumerate(arrays))
<ide>
<del> first_index, max_arr_ndim = idxs_ndims.__next__()
<add> first_index, max_arr_ndim = next(idxs_ndims)
<ide> for i, (index, ndim) in enumerate(idxs_ndims, 1):
<ide> if ndim > max_arr_ndim:
<ide> max_arr_ndim = ndim | 1 |
PHP | PHP | apply fixes from styleci | 0cb88d66e87b8843307c98f604216ae73e76453b | <ide><path>src/Illuminate/Support/helpers.php
<ide> function retry($times, callable $callback, $sleep = 0, $when = null)
<ide> {
<ide> $attempts = 0;
<ide>
<del> beginning:
<add> beginning :
<ide> $attempts++;
<ide> $times--;
<ide> | 1 |
Ruby | Ruby | add gitless and telegram-cli to prerelease list | ad4fd55b78772d456b3c8ed84436a6c86212a8f7 | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def get_repo_data(regex)
<ide> "libepoxy" => "1.5",
<ide> }.freeze
<ide>
<del> GITHUB_PRERELEASE_ALLOWLIST = %w[].freeze
<add> GITHUB_PRERELEASE_ALLOWLIST = {
<add> "gitless" => "0.8.8",
<add> "telegram-cli" => "1.3.1",
<add> }.freeze
<ide>
<ide> # version_prefix = stable_version_string.sub(/\d+$/, "")
<ide> # version_prefix = stable_version_string.split(".")[0..1].join(".") | 1 |
Javascript | Javascript | remove unused _valuedidchange function | f67eb2be75bf8f7130d3213f7123a88b1b3479f4 | <ide><path>packages/sproutcore-handlebars/lib/controls/text_field.js
<ide> SC.TextField = SC.View.extend(
<ide> set(this, 'value', this.$().val());
<ide> },
<ide>
<del> _valueDidChange: function() {
<del> SC.run.once(this, this._updateElementValue);
<del> },
<del>
<ide> _updateElementValue: function() {
<ide> this.$().val(get(this, 'value'));
<ide> } | 1 |
Python | Python | fix lint issues | 25f13fa9a7fdea5d03ff7c1179f0fda586666e54 | <ide><path>official/recommendation/ncf_keras_main.py
<ide> def __init__(self, params):
<ide> super(MetricLayer, self).__init__()
<ide> self.params = params
<ide> self.metric = tf.keras.metrics.Mean(name=rconst.HR_METRIC_NAME)
<del>
<add>
<ide> def call(self, inputs):
<ide> logits, dup_mask = inputs
<ide> in_top_k, metric_weights = metric_fn(logits, dup_mask, self.params)
<ide> def _get_keras_model(params):
<ide> batch_size=params["batches_per_step"],
<ide> name=movielens.ITEM_COLUMN,
<ide> dtype=tf.int32)
<del>
<add>
<ide> valid_pt_mask_input = tf.keras.layers.Input(
<ide> shape=(batch_size,),
<ide> batch_size=params["batches_per_step"],
<ide> def step_fn(inputs):
<ide> features, _ = inputs
<ide> softmax_logits = keras_model(features)
<ide> in_top_k, metric_weights = metric_fn(
<del> softmax_logits, features[rconst.DUPLICATE_MASK], params)
<add> softmax_logits, features[rconst.DUPLICATE_MASK], params)
<ide> hr_sum = tf.reduce_sum(in_top_k*metric_weights)
<ide> hr_count = tf.reduce_sum(metric_weights)
<ide> return hr_sum, hr_count | 1 |
Javascript | Javascript | remove infrastructure-log for big-assets test case | 61f9f933d82d7be7842fc79b2127105b0f2dc43f | <ide><path>test/cases/large/big-assets/infrastructure-log.js
<del>module.exports = [
<del> /^Pack got invalid because of write to: ResolverCachePlugin|normal|dependencyType=|esm|path=|.+|request=|\.\/large\/big-assets\/$/
<del>]; | 1 |
Javascript | Javascript | update todo message | a5c6f3e8a1868f39283afc123c2c222af9a91d52 | <ide><path>lib/fs.js
<ide> function watch(filename, options, listener) {
<ide>
<ide> let watcher;
<ide>
<del> // TODO(anonrig): Remove this when/if libuv supports it.
<add> // TODO(anonrig): Remove non-native watcher when/if libuv supports recursive.
<ide> // As of November 2022, libuv does not support recursive file watch on all platforms,
<ide> // e.g. Linux due to the limitations of inotify.
<ide> if (options.recursive && !isOSX && !isWindows) {
<ide><path>lib/internal/fs/promises.js
<ide> async function* _watch(filename, options = kEmptyObject) {
<ide> if (options.recursive != null) {
<ide> validateBoolean(options.recursive, 'options.recursive');
<ide>
<del> // TODO(anonrig): Remove this when/if libuv supports it.
<add> // TODO(anonrig): Remove non-native watcher when/if libuv supports recursive.
<ide> // As of November 2022, libuv does not support recursive file watch on all platforms,
<ide> // e.g. Linux due to the limitations of inotify.
<ide> if (options.recursive && !isOSX && !isWindows) {
<ide><path>lib/internal/fs/recursive_watch.js
<ide> const { getValidatedPath } = require('internal/fs/utils');
<ide> const { kFSWatchStart, StatWatcher } = require('internal/fs/watchers');
<ide> const { kEmptyObject } = require('internal/util');
<ide> const { validateBoolean, validateAbortSignal } = require('internal/validators');
<del>const path = require('path');
<add>const {
<add> basename: pathBasename,
<add> join: pathJoin,
<add> relative: pathRelative,
<add> resolve: pathResolve,
<add>} = require('path');
<ide>
<ide> let internalSync;
<ide> let internalPromises;
<ide> async function traverse(dir, files = new SafeMap(), symbolicLinks = new SafeSet(
<ide> const subdirectories = [];
<ide>
<ide> for await (const file of filenames) {
<del> const f = path.join(dir, file.name);
<add> const f = pathJoin(dir, file.name);
<ide>
<ide> files.set(f, file);
<ide>
<ide> class FSWatcher extends EventEmitter {
<ide> #closed = false;
<ide> #files = new SafeMap();
<ide> #symbolicFiles = new SafeSet();
<del> #rootPath = path.resolve();
<add> #rootPath = pathResolve();
<ide> #watchingFile = false;
<ide>
<ide> constructor(options = kEmptyObject) {
<ide> class FSWatcher extends EventEmitter {
<ide> break;
<ide> }
<ide>
<del> const f = path.join(folder, file.name);
<add> const f = pathJoin(folder, file.name);
<ide>
<ide> if (!this.#files.has(f)) {
<del> this.emit('change', 'rename', path.relative(this.#rootPath, f));
<add> this.emit('change', 'rename', pathRelative(this.#rootPath, f));
<ide>
<ide> if (file.isSymbolicLink()) {
<ide> this.#symbolicFiles.add(f);
<ide> class FSWatcher extends EventEmitter {
<ide> if (currentStats.birthtimeMs === 0 && previousStats.birthtimeMs !== 0) {
<ide> // The file is now deleted
<ide> this.#files.delete(file);
<del> this.emit('change', 'rename', path.relative(this.#rootPath, file));
<add> this.emit('change', 'rename', pathRelative(this.#rootPath, file));
<ide> this.#unwatchFiles(file);
<ide> } else if (file === this.#rootPath && this.#watchingFile) {
<ide> // This case will only be triggered when watching a file with fs.watch
<del> this.emit('change', 'change', path.basename(file));
<add> this.emit('change', 'change', pathBasename(file));
<ide> } else if (this.#symbolicFiles.has(file)) {
<ide> // Stats from watchFile does not return correct value for currentStats.isSymbolicLink()
<ide> // Since it is only valid when using fs.lstat(). Therefore, check the existing symbolic files.
<del> this.emit('change', 'rename', path.relative(this.#rootPath, file));
<add> this.emit('change', 'rename', pathRelative(this.#rootPath, file));
<ide> } else if (currentStats.isDirectory()) {
<ide> this.#watchFolder(file);
<ide> }
<ide> });
<ide> }
<ide>
<ide> [kFSWatchStart](filename) {
<del> filename = path.resolve(getValidatedPath(filename));
<add> filename = pathResolve(getValidatedPath(filename));
<ide>
<ide> try {
<ide> const file = lazyLoadFsSync().statSync(filename); | 3 |
PHP | PHP | allow trailing slashes | 7670d5c9462d5a34295cc5967b0d420cb7a5e6a0 | <ide><path>src/Illuminate/Routing/Router.php
<ide> protected function findRoute(Request $request)
<ide> // that's used by the Illuminate foundation framework for responses.
<ide> try
<ide> {
<del> $path = '/'.ltrim($request->getPathInfo(), '/');
<add> $path = $this->formatRequestPath($request);
<ide>
<ide> $parameters = $this->getUrlMatcher($request)->match($path);
<ide> }
<ide> protected function findRoute(Request $request)
<ide> return $route;
<ide> }
<ide>
<add> /**
<add> * Format the request path info for routing.
<add> *
<add> * @param Illuminate\Http\Request $request
<add> * @return string
<add> */
<add> protected function formatRequestPath($request)
<add> {
<add> $path = $request->getPathInfo();
<add>
<add> if (strlen($path) > 1 and ends_with($path, '/'))
<add> {
<add> return '/'.ltrim(substr($path, 0, -1), '/');
<add> }
<add>
<add> return '/'.ltrim($path, '/');
<add> }
<add>
<ide> /**
<ide> * Register a "before" routing filter.
<ide> *
<ide><path>tests/Routing/RoutingTest.php
<ide> public function testBasic()
<ide> $router = new Router;
<ide> $router->get('/', function() { return 'root'; });
<ide> $router->get('/foo', function() { return 'bar'; });
<del> $router->get('/foo//', function() { return 'foo'; });
<ide> $request = Request::create('/foo', 'GET');
<ide> $this->assertEquals('bar', $router->dispatch($request)->getContent());
<ide>
<del> $request = Request::create('/foo//', 'GET');
<del> $this->assertEquals('foo', $router->dispatch($request)->getContent());
<add> $request = Request::create('/foo/', 'GET');
<add> $this->assertEquals('bar', $router->dispatch($request)->getContent());
<ide>
<ide> $request = Request::create('http://foo.com', 'GET');
<ide> $this->assertEquals('root', $router->dispatch($request)->getContent());
<ide>
<del> $request = Request::create('http://foo.com///', 'GET');
<del> $this->assertEquals('root', $router->dispatch($request)->getContent());
<del>
<ide> $router = new Router;
<ide> $router->get('/foo/{name}/{age}', function($name, $age) { return $name.$age; });
<ide> $request = Request::create('/foo/taylor/25', 'GET'); | 2 |
Mixed | Ruby | add database_exists? method to connection adapters | fe30211574648fa21bff958a3cf952fd0c20c3b1 | <ide><path>activerecord/CHANGELOG.md
<add>* Add database_exists? method to connection adapters to check if a database exists.
<add>
<add> *Guilherme Mansur*
<add>
<ide> * PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute.
<ide>
<ide> Fixes #36022.
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def adapter_name
<ide> self.class::ADAPTER_NAME
<ide> end
<ide>
<add> # Does the database for this adapter exist?
<add> def self.database_exists?(config)
<add> raise NotImplementedError
<add> end
<add>
<ide> # Does this adapter support DDL rollbacks in transactions? That is, would
<ide> # CREATE TABLE or ALTER TABLE get rolled back by a transaction?
<ide> def supports_ddl_transactions?
<ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
<ide> def initialize(connection, logger, connection_options, config)
<ide> configure_connection
<ide> end
<ide>
<add> def self.database_exists?(config)
<add> !!ActiveRecord::Base.mysql2_connection(config)
<add> rescue ActiveRecord::NoDatabaseError
<add> false
<add> end
<add>
<ide> def supports_json?
<ide> !mariadb? && database_version >= "5.7.8"
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def initialize(connection, logger, connection_parameters, config)
<ide> @use_insert_returning = @config.key?(:insert_returning) ? self.class.type_cast_config_to_boolean(@config[:insert_returning]) : true
<ide> end
<ide>
<add> def self.database_exists?(config)
<add> !!ActiveRecord::Base.postgresql_connection(config)
<add> rescue ActiveRecord::NoDatabaseError
<add> false
<add> end
<add>
<ide> # Is this connection alive and ready for queries?
<ide> def active?
<ide> @lock.synchronize do
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> def initialize(connection, logger, connection_options, config)
<ide> configure_connection
<ide> end
<ide>
<add> def self.database_exists?(config)
<add> config = config.symbolize_keys
<add> if config[:database] == ":memory:"
<add> return true
<add> else
<add> database_file = defined?(Rails.root) ? File.expand_path(config[:database], Rails.root) : config[:database]
<add> File.exist?(database_file)
<add> end
<add> end
<add>
<ide> def supports_ddl_transactions?
<ide> true
<ide> end
<ide><path>activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb
<ide> def test_exec_query_nothing_raises_with_no_result_queries
<ide> end
<ide> end
<ide>
<add> def test_database_exists_returns_false_if_database_does_not_exist
<add> config = ActiveRecord::Base.configurations["arunit"].merge(database: "inexistent_activerecord_unittest")
<add> assert_not ActiveRecord::ConnectionAdapters::Mysql2Adapter.database_exists?(config),
<add> "expected database to not exist"
<add> end
<add>
<add> def test_database_exists_returns_true_when_the_database_exists
<add> config = ActiveRecord::Base.configurations["arunit"]
<add> assert ActiveRecord::ConnectionAdapters::Mysql2Adapter.database_exists?(config),
<add> "expected database #{config[:database]} to exist"
<add> end
<add>
<ide> def test_columns_for_distinct_zero_orders
<ide> assert_equal "posts.id",
<ide> @conn.columns_for_distinct("posts.id", [])
<ide><path>activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
<ide> def test_bad_connection
<ide> end
<ide> end
<ide>
<add> def test_database_exists_returns_false_when_the_database_does_not_exist
<add> config = { database: "non_extant_database", adapter: "postgresql" }
<add> assert_not ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.database_exists?(config),
<add> "expected database #{config[:database]} to not exist"
<add> end
<add>
<add> def test_database_exists_returns_true_when_the_database_exists
<add> config = ActiveRecord::Base.configurations["arunit"]
<add> assert ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.database_exists?(config),
<add> "expected database #{config[:database]} to exist"
<add> end
<add>
<ide> def test_primary_key
<ide> with_example_table do
<ide> assert_equal "id", @connection.primary_key("ex")
<ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
<ide> def test_bad_connection
<ide> end
<ide> end
<ide>
<add> def test_database_exists_returns_false_when_the_database_does_not_exist
<add> assert_not SQLite3Adapter.database_exists?(adapter: "sqlite3", database: "non_extant_db"),
<add> "expected non_extant_db to not exist"
<add> end
<add>
<add> def test_database_exists_returns_true_when_databae_exists
<add> config = ActiveRecord::Base.configurations["arunit"]
<add> assert SQLite3Adapter.database_exists?(config),
<add> "expected #{config[:database]} to exist"
<add> end
<add>
<ide> unless in_memory_db?
<ide> def test_connect_with_url
<ide> original_connection = ActiveRecord::Base.remove_connection
<ide> def test_connect_memory_with_url
<ide> end
<ide> end
<ide>
<add> def test_database_exists_returns_true_for_an_in_memory_db
<add> assert SQLite3Adapter.database_exists?(database: ":memory:"),
<add> "Expected in memory database to exist"
<add> end
<add>
<ide> def test_column_types
<ide> owner = Owner.create!(name: "hello".encode("ascii-8bit"))
<ide> owner.reload | 8 |
PHP | PHP | add ability to support existing urls | 66b9130107c4f696b054f6409d758fc4e1e83280 | <ide><path>lib/Cake/Routing/Router.php
<ide> public static function setExtensions($extensions, $merge = true) {
<ide> return static::$_validExtensions = array_merge(static::$_validExtensions, $extensions);
<ide> }
<ide>
<add>/**
<add> * Provides legacy support for named parameters on incoming URLs.
<add> *
<add> * Checks the passed parameters for elements containing `$options['separator']`
<add> * Those parameters are split and parsed as if they were old style named parameters.
<add> *
<add> * The parsed parameters will be moved from params['pass'] to params['named'].
<add> *
<add> * ### Options
<add> *
<add> * - `separator` The string to use as a separator. Defaults to `:`.
<add> *
<add> * @param Request $request The request object to modify.
<add> * @param array $options The array of options.
<add> * @return The modified request
<add> */
<add> public static function parseNamedParams(Request $request, $options = array()) {
<add> $options += array('separator' => ':');
<add> if (empty($request->params['pass'])) {
<add> $request->params['named'] = array();
<add> return $request;
<add> }
<add> $named = array();
<add> foreach ($request->params['pass'] as $key => $value) {
<add> if (strpos($value, $options['separator']) === false) {
<add> continue;
<add> }
<add> unset($request->params['pass'][$key]);
<add> list($key, $value) = explode($options['separator'], $value, 2);
<add>
<add> if (preg_match_all('/\[([A-Za-z0-9_-]+)?\]/', $key, $matches, PREG_SET_ORDER)) {
<add> $matches = array_reverse($matches);
<add> $parts = explode('[', $key);
<add> $key = array_shift($parts);
<add> $arr = $value;
<add> foreach ($matches as $match) {
<add> if (empty($match[1])) {
<add> $arr = array($arr);
<add> } else {
<add> $arr = array(
<add> $match[1] => $arr
<add> );
<add> }
<add> }
<add> $value = $arr;
<add> }
<add> $named = array_merge_recursive($named, array($key => $value));
<add> }
<add> $request->params['named'] = $named;
<add> return $request;
<add> }
<add>
<ide> }
<ide>
<ide> //Save the initial state
<ide><path>lib/Cake/Test/TestCase/Routing/RouterTest.php
<ide> public function testSettingNonExistentDefaultRouteException() {
<ide> }
<ide>
<ide> /**
<del> * Tests generating well-formed querystrings
<add> * Test that the compatibility method for incoming urls works.
<ide> *
<ide> * @return void
<ide> */
<del> public function testQueryString() {
<del> $result = Router::queryString(array('var' => 'foo bar'));
<del> $expected = '?var=foo+bar';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = Router::queryString(false, array('some' => 'param', 'foo' => 'bar'));
<del> $expected = '?some=param&foo=bar';
<del> $this->assertEquals($expected, $result);
<del>
<del> $existing = array('apple' => 'red', 'pear' => 'green');
<del> $result = Router::queryString($existing, array('some' => 'param', 'foo' => 'bar'));
<del> $expected = '?apple=red&pear=green&some=param&foo=bar';
<del> $this->assertEquals($expected, $result);
<del>
<del> $existing = 'apple=red&pear=green';
<del> $result = Router::queryString($existing, array('some' => 'param', 'foo' => 'bar'));
<del> $expected = '?apple=red&pear=green&some=param&foo=bar';
<del> $this->assertEquals($expected, $result);
<del>
<del> $existing = '?apple=red&pear=green';
<del> $result = Router::queryString($existing, array('some' => 'param', 'foo' => 'bar'));
<del> $expected = '?apple=red&pear=green&some=param&foo=bar';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = Router::queryString('apple=red&pear=green');
<del> $expected = '?apple=red&pear=green';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = Router::queryString('foo=bar', array('php' => 'nut', 'jose' => 'zap'), true);
<del> $expected = '?foo=bar&php=nut&jose=zap';
<del> $this->assertEquals($expected, $result);
<del>
<del> $result = Router::queryString('foo=bar&', array('php' => 'nut', 'jose' => 'zap'), true);
<del> $expected = '?foo=bar&php=nut&jose=zap';
<del> $this->assertEquals($expected, $result);
<add> public function testParseNamedParameters() {
<add> $request = new Request();
<add> $request->addParams(array(
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> ));
<add> $result = Router::parseNamedParams($request);
<add> $this->assertEquals(array(), $result->params['named']);
<ide>
<del> $result = Router::queryString('foo=bar&', array('php' => 'nut', 'jose' => 'zap'));
<del> $expected = '?foo=bar&php=nut&jose=zap';
<del> $this->assertEquals($expected, $result);
<add> $request = new Request();
<add> $request->addParams(array(
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> 'pass' => array('home', 'one:two', 'three:four', 'five[nested][0]:six', 'five[nested][1]:seven')
<add> ));
<add> Router::parseNamedParams($request);
<add> $expected = array(
<add> 'plugin' => null,
<add> 'controller' => 'posts',
<add> 'action' => 'index',
<add> 'pass' => array('home'),
<add> 'named' => array(
<add> 'one' => 'two',
<add> 'three' => 'four',
<add> 'five' => array(
<add> 'nested' => array('six', 'seven')
<add> )
<add> )
<add> );
<add> $this->assertEquals($expected, $request->params);
<ide> }
<add>
<ide> } | 2 |
Python | Python | fix broken `none` value for `timefield` | ad336cc636d98022ea7eda516a04a7937eb32238 | <ide><path>rest_framework/fields.py
<ide> def from_native(self, value):
<ide> def to_native(self, value):
<ide> if value is None:
<ide> return None
<add>
<ide> if isinstance(value, datetime.datetime):
<ide> value = value.date()
<add>
<ide> if self.format.lower() == ISO_8601:
<ide> return value.isoformat()
<ide> return value.strftime(self.format)
<ide> def from_native(self, value):
<ide> def to_native(self, value):
<ide> if value is None:
<ide> return None
<add>
<ide> if self.format.lower() == ISO_8601:
<ide> return value.isoformat()
<ide> return value.strftime(self.format)
<ide> def from_native(self, value):
<ide> raise ValidationError(msg)
<ide>
<ide> def to_native(self, value):
<add> if value is None:
<add> return None
<add>
<ide> if isinstance(value, datetime.datetime):
<ide> value = value.time()
<add>
<ide> if self.format.lower() == ISO_8601:
<ide> return value.isoformat()
<ide> return value.strftime(self.format) | 1 |
PHP | PHP | remove ties to old dispatcher code | af19c0e0decc6c82650cc0f0c85a2cc4362b0bf3 | <ide><path>src/Http/ActionDispatcher.php
<ide> class ActionDispatcher
<ide> *
<ide> * @param \Cake\Http\ControllerFactory|null $factory A controller factory instance.
<ide> * @param \Cake\Event\EventManager|null $eventManager An event manager if you want to inject one.
<del> * @param \Cake\Event\EventListenerInterface[] $filters The list of filters to include.
<ide> */
<del> public function __construct($factory = null, $eventManager = null, array $filters = [])
<add> public function __construct($factory = null, $eventManager = null)
<ide> {
<ide> if ($eventManager) {
<ide> $this->setEventManager($eventManager);
<ide> }
<del> foreach ($filters as $filter) {
<del> $this->addFilter($filter);
<del> }
<ide> $this->factory = $factory ?: new ControllerFactory();
<ide> }
<ide>
<ide> protected function _invoke(Controller $controller)
<ide> return $response;
<ide> }
<ide>
<del> /**
<del> * Add a filter to this dispatcher.
<del> *
<del> * The added filter will be attached to the event manager used
<del> * by this dispatcher.
<del> *
<del> * @param \Cake\Event\EventListenerInterface $filter The filter to connect. Can be
<del> * any EventListenerInterface. Typically an instance of \Cake\Routing\DispatcherFilter.
<del> * @return void
<del> * @deprecated This is only available for backwards compatibility with DispatchFilters
<del> */
<del> public function addFilter(EventListenerInterface $filter)
<del> {
<del> deprecationWarning(
<del> 'ActionDispatcher::addFilter() is deprecated. ' .
<del> 'This is only available for backwards compatibility with DispatchFilters'
<del> );
<del>
<del> $this->filters[] = $filter;
<del> $this->getEventManager()->on($filter);
<del> }
<del>
<ide> /**
<ide> * Get the connected filters.
<ide> *
<ide><path>src/Http/BaseApplication.php
<ide> use Cake\Event\EventDispatcherTrait;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Event\EventManagerInterface;
<del>use Cake\Routing\DispatcherFactory;
<ide> use Cake\Routing\Router;
<ide> use InvalidArgumentException;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> public function __invoke(ServerRequestInterface $request, ResponseInterface $res
<ide> */
<ide> protected function getDispatcher()
<ide> {
<del> return new ActionDispatcher(null, $this->getEventManager(), DispatcherFactory::filters());
<add> return new ActionDispatcher(null, $this->getEventManager());
<ide> }
<ide> }
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function setUp()
<ide> parent::setUp();
<ide> $this->server = $_SERVER;
<ide> static::setAppNamespace();
<del> DispatcherFactory::add('Routing');
<del> DispatcherFactory::add('ControllerFactory');
<ide> $this->_init();
<ide> }
<ide>
<ide> protected function _init()
<ide> public function tearDown()
<ide> {
<ide> parent::tearDown();
<del> DispatcherFactory::clear();
<ide> Router::reload();
<del> Router::$initialized = false;
<ide> $_SERVER = $this->server;
<ide> unset($this->RequestHandler, $this->Controller);
<ide> }
<ide><path>tests/TestCase/Http/ActionDispatcherTest.php
<ide> public function setUp()
<ide> $this->dispatcher = new ActionDispatcher();
<ide> }
<ide>
<del> /**
<del> * Teardown
<del> *
<del> * @return void
<del> */
<del> public function tearDown()
<del> {
<del> parent::tearDown();
<del> DispatcherFactory::clear();
<del> }
<del>
<ide> /**
<ide> * Ensure the constructor args end up on the right protected properties.
<ide> *
<ide> public function testConstructorArgs()
<ide> $this->assertAttributeSame($factory, 'factory', $dispatcher);
<ide> }
<ide>
<del> /**
<del> * Ensure that filters connected to the DispatcherFactory are
<del> * also applied
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testDispatcherFactoryCompat()
<del> {
<del> $this->deprecated(function () {
<del> $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter')
<del> ->setMethods(['beforeDispatch', 'afterDispatch'])
<del> ->getMock();
<del> DispatcherFactory::add($filter);
<del> $dispatcher = new ActionDispatcher(null, null, DispatcherFactory::filters());
<del> $this->assertCount(1, $dispatcher->getFilters());
<del> $this->assertSame($filter, $dispatcher->getFilters()[0]);
<del> });
<del> }
<del>
<del> /**
<del> * Test adding routing filters
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testAddFilter()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertCount(0, $this->dispatcher->getFilters());
<del> $events = $this->dispatcher->getEventManager();
<del> $this->assertCount(0, $events->listeners('Dispatcher.beforeDispatch'));
<del> $this->assertCount(0, $events->listeners('Dispatcher.afterDispatch'));
<del>
<del> $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter')
<del> ->setMethods(['beforeDispatch', 'afterDispatch'])
<del> ->getMock();
<del> $this->dispatcher->addFilter($filter);
<del>
<del> $this->assertCount(1, $this->dispatcher->getFilters());
<del> $this->assertCount(1, $events->listeners('Dispatcher.beforeDispatch'));
<del> $this->assertCount(1, $events->listeners('Dispatcher.afterDispatch'));
<del> });
<del> }
<del>
<ide> /**
<ide> * Ensure that aborting in the beforeDispatch doesn't invoke the controller
<ide> * | 4 |
Java | Java | fix failing test and warings | f33578ef0f20af90a41c2daddedcb7ba1b96c278 | <ide><path>spring-jms/src/test/java/org/springframework/jms/config/MethodJmsListenerEndpointTests.java
<ide> import org.springframework.messaging.handler.annotation.Payload;
<ide> import org.springframework.messaging.handler.annotation.SendTo;
<ide> import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
<del>import org.springframework.messaging.handler.annotation.support.MethodArgumentTypeMismatchException;
<ide> import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.validation.Errors;
<ide> import org.springframework.validation.Validator;
<ide> import org.springframework.validation.annotation.Validated;
<ide>
<del>import static org.junit.Assert.*;
<del>import static org.mockito.BDDMockito.*;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertNotNull;
<add>import static org.junit.Assert.assertSame;
<add>import static org.junit.Assert.assertTrue;
<add>import static org.mockito.BDDMockito.given;
<add>import static org.mockito.BDDMockito.mock;
<add>import static org.mockito.BDDMockito.verify;
<ide>
<ide> /**
<ide> * @author Stephane Nicoll
<ide> public void invalidMessagePayloadType() throws JMSException {
<ide> Session session = mock(Session.class);
<ide>
<ide> thrown.expect(ListenerExecutionFailedException.class);
<del> thrown.expectCause(Matchers.isA(MethodArgumentTypeMismatchException.class));
<add> thrown.expectCause(Matchers.isA(MessageConversionException.class));
<ide> listener.onMessage(createSimpleJmsTextMessage("test"), session); // Message<String> as Message<Integer>
<ide> }
<ide>
<ide> private Method getTestMethod() {
<ide> }
<ide>
<ide>
<del> @SendTo("defaultReply")
<add> @SendTo("defaultReply") @SuppressWarnings("unused")
<ide> static class JmsEndpointSampleBean {
<ide>
<del> private final Map<String, Boolean> invocations = new HashMap<String, Boolean>();
<add> private final Map<String, Boolean> invocations = new HashMap<>();
<ide>
<ide> public void resolveMessageAndSession(javax.jms.Message message, Session session) {
<ide> invocations.put("resolveMessageAndSession", true); | 1 |
Text | Text | fix return type of `crypto.getfips()` | d4fd03e67371ef8db8c47d2981bbee9601700034 | <ide><path>doc/api/crypto.md
<ide> console.log(aliceSecret === bobSecret);
<ide> added: v10.0.0
<ide> -->
<ide>
<del>* Returns: {boolean} `true` if and only if a FIPS compliant crypto provider is
<del> currently in use.
<add>* Returns: {number} `1` if and only if a FIPS compliant crypto provider is
<add> currently in use, `0` otherwise.
<ide>
<ide> ### `crypto.getHashes()`
<ide> <!-- YAML | 1 |
Python | Python | ensure bulk_create returns what it is supposed to | f2bc919ec00457fd53f093af53ab71c7f1bcfbcd | <ide><path>django/db/models/query.py
<ide> def bulk_create(self, objs):
<ide> self.model._base_manager._insert(objs_with_pk, fields=fields, using=self.db)
<ide> if objs_without_pk:
<ide> self.model._base_manager._insert(objs_without_pk, fields=[f for f in fields if not isinstance(f, AutoField)], using=self.db)
<add> return objs
<ide>
<ide> def get_or_create(self, **kwargs):
<ide> """
<ide><path>tests/regressiontests/bulk_create/tests.py
<ide> def setUp(self):
<ide> ]
<ide>
<ide> def test_simple(self):
<del> Country.objects.bulk_create(self.data)
<add> created = Country.objects.bulk_create(self.data)
<add> self.assertEqual(len(created), 4)
<ide> self.assertQuerysetEqual(Country.objects.order_by("-name"), [
<ide> "United States of America", "The Netherlands", "Germany", "Czech Republic"
<ide> ], attrgetter("name")) | 2 |
Javascript | Javascript | add mode setting and strict to make.js | 0e948f138db0691dcbd1d06511bf4dbfd80abfab | <ide><path>make.js
<add>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
<add>/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
<add>
<add>'use strict';
<add>
<ide> require('./external/shelljs/make');
<ide> var builder = require('./external/builder/builder.js');
<ide> var crlfchecker = require('./external/crlfchecker/crlfchecker.js'); | 1 |
Mixed | Text | update https urls [ci skip] | b24190807db460d0fa342b401c5166844aab14dc | <ide><path>RELEASING_RAILS.md
<ide> sure the code samples in his book
<ide> all work. These are valuable system tests
<ide> for Rails. You can check the status of these tests here:
<ide>
<del>[http://intertwingly.net/projects/dashboard.html](http://intertwingly.net/projects/dashboard.html)
<add>[https://intertwingly.net/projects/dashboard.html](https://intertwingly.net/projects/dashboard.html)
<ide>
<ide> Do not release with Red AWDwR tests.
<ide>
<ide><path>actionpack/lib/action_dispatch/middleware/remote_ip.rb
<ide> module ActionDispatch
<ide> # contain the address, and then picking the last-set address that is not
<ide> # on the list of trusted IPs. This follows the precedent set by e.g.
<ide> # {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453],
<del> # with {reasoning explained at length}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection]
<add> # with {reasoning explained at length}[https://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection]
<ide> # by @gingerlime. A more detailed explanation of the algorithm is given
<ide> # at GetIp#calculate_ip.
<ide> #
<ide> # Some Rack servers concatenate repeated headers, like {HTTP RFC 2616}[https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2]
<ide> # requires. Some Rack servers simply drop preceding headers, and only report
<del> # the value that was {given in the last header}[http://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers].
<add> # the value that was {given in the last header}[https://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers].
<ide> # If you are behind multiple proxy servers (like NGINX to HAProxy to Unicorn)
<ide> # then you should test your Rack server to make sure your data is good.
<ide> #
<ide> def initialize(req, check_ip, proxies)
<ide> # proxies, that header may contain a list of IPs. Other proxy services
<ide> # set the Client-Ip header instead, so we check that too.
<ide> #
<del> # As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
<add> # As discussed in {this post about Rails IP Spoofing}[https://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
<ide> # while the first IP in the list is likely to be the "originating" IP,
<ide> # it could also have been set by the client maliciously.
<ide> #
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> module CustomUrls
<ide> # of routing helpers, e.g:
<ide> #
<ide> # direct :homepage do
<del> # "http://www.rubyonrails.org"
<add> # "https://rubyonrails.org"
<ide> # end
<ide> #
<ide> # direct :commentable do |model|
<ide><path>actionview/test/ujs/public/test/call-remote.js
<ide> asyncTest('allow empty form "action"', 1, function() {
<ide>
<ide> // Actual location (strip out settings.data that jQuery serializes and appends)
<ide> // HACK: can no longer use settings.data below to see what was appended to URL, as of
<del> // jQuery 1.6.3 (see http://bugs.jquery.com/ticket/10202 and https://github.com/jquery/jquery/pull/544)
<add> // jQuery 1.6.3 (see https://bugs.jquery.com/ticket/10202 and https://github.com/jquery/jquery/pull/544)
<ide> ajaxLocation = settings.url.replace('user_name=john', '').replace(/&$/, '').replace(/\?$/, '')
<ide> equal(ajaxLocation.match(/^(.*)/)[1], currentLocation, 'URL should be current page by default')
<ide>
<ide><path>activesupport/lib/active_support/duration.rb
<ide> def to_s
<ide> # 1.year.to_i # => 31556952
<ide> #
<ide> # In such cases, Ruby's core
<del> # Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
<del> # Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
<add> # Date[https://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
<add> # Time[https://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
<ide> # date and time arithmetic.
<ide> def to_i
<ide> @value.to_i
<ide><path>activesupport/lib/active_support/ordered_hash.rb
<ide> module ActiveSupport
<ide> # oh.keys # => [:a, :b], this order is guaranteed
<ide> #
<ide> # Also, maps the +omap+ feature for YAML files
<del> # (See http://yaml.org/type/omap.html) to support ordered items
<add> # (See https://yaml.org/type/omap.html) to support ordered items
<ide> # when loading from yaml.
<ide> #
<ide> # <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts
<ide><path>guides/source/generators.md
<ide> class InitializerGenerator < Rails::Generators::Base
<ide> end
<ide> ```
<ide>
<del>NOTE: `create_file` is a method provided by `Thor::Actions`. Documentation for `create_file` and other Thor methods can be found in [Thor's documentation](http://rdoc.info/github/erikhuda/thor/master/Thor/Actions.html)
<add>NOTE: `create_file` is a method provided by `Thor::Actions`. Documentation for `create_file` and other Thor methods can be found in [Thor's documentation](https://rdoc.info/github/erikhuda/thor/master/Thor/Actions.html)
<ide>
<ide> Our new generator is quite simple: it inherits from `Rails::Generators::Base` and has one method definition. When a generator is invoked, each public method in the generator is executed sequentially in the order that it is defined. Finally, we invoke the `create_file` method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you'll feel right at home with the new generators API.
<ide>
<ide> Whilst the final section of this guide doesn't cover how to generate the most aw
<ide>
<ide> Adding Command Line Arguments
<ide> -----------------------------
<del>Rails generators can be easily modified to accept custom command line arguments. This functionality comes from [Thor](http://www.rubydoc.info/github/erikhuda/thor/master/Thor/Base/ClassMethods#class_option-instance_method):
<add>Rails generators can be easily modified to accept custom command line arguments. This functionality comes from [Thor](https://www.rubydoc.info/github/erikhuda/thor/master/Thor/Base/ClassMethods#class_option-instance_method):
<ide>
<ide> ```
<ide> class_option :scope, type: :string, default: 'read_products'
<ide> Generator methods
<ide>
<ide> The following are methods available for both generators and templates for Rails.
<ide>
<del>NOTE: Methods provided by Thor are not covered this guide and can be found in [Thor's documentation](http://rdoc.info/github/erikhuda/thor/master/Thor/Actions.html)
<add>NOTE: Methods provided by Thor are not covered this guide and can be found in [Thor's documentation](https://rdoc.info/github/erikhuda/thor/master/Thor/Actions.html)
<ide>
<ide> ### `gem`
<ide>
<ide><path>guides/source/maintenance_policy.md
<ide> follows, all versions in `X.Y.Z` format.
<ide>
<ide> --------------------------------------------------------------------------------
<ide>
<del>Rails follows a shifted version of [semver](http://semver.org/):
<add>Rails follows a shifted version of [semver](https://semver.org/):
<ide>
<ide> **Patch `Z`**
<ide>
<ide><path>guides/source/plugins.md
<ide> $ bundle exec rake rdoc
<ide> ### References
<ide>
<ide> * [Developing a RubyGem using Bundler](https://github.com/radar/guides/blob/master/gem-development.md)
<del>* [Using .gemspecs as Intended](http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/)
<add>* [Using .gemspecs as Intended](https://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/)
<ide> * [Gemspec Reference](https://guides.rubygems.org/specification-reference/)
<ide><path>guides/source/security.md
<ide> However, the attacker may also take over the account by changing the e-mail addr
<ide>
<ide> #### Other
<ide>
<del>Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in [Google Mail](http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/). In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in an HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to their e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, _review your application logic and eliminate all XSS and CSRF vulnerabilities_.
<add>Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in [Google Mail](https://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/). In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in an HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to their e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, _review your application logic and eliminate all XSS and CSRF vulnerabilities_.
<ide>
<ide> ### CAPTCHAs
<ide>
<ide> Here are some ideas how to hide honeypot fields by JavaScript and/or CSS:
<ide>
<ide> The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on.
<ide>
<del>You can find more sophisticated negative CAPTCHAs in Ned Batchelder's [blog post](http://nedbatchelder.com/text/stopbots.html):
<add>You can find more sophisticated negative CAPTCHAs in Ned Batchelder's [blog post](https://nedbatchelder.com/text/stopbots.html):
<ide>
<ide> * Include a field with the current UTC time-stamp in it and check it on the server. If it is too far in the past, or if it is in the future, the form is invalid.
<ide> * Randomize the field names
<ide> With web page defacement an attacker can do a lot of things, for example, presen
<ide> <iframe name="StatPage" src="http://58.xx.xxx.xxx" width=5 height=5 style="display:none"></iframe>
<ide> ```
<ide>
<del>This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This iframe is taken from an actual attack on legitimate Italian sites using the [Mpack attack framework](http://isc.sans.org/diary.html?storyid=3015). Mpack tries to install malicious software through security holes in the web browser - very successfully, 50% of the attacks succeed.
<add>This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This iframe is taken from an actual attack on legitimate Italian sites using the [Mpack attack framework](https://isc.sans.edu/diary/MPack+Analysis/3015). Mpack tries to install malicious software through security holes in the web browser - very successfully, 50% of the attacks succeed.
<ide>
<ide> A more specialized attack could overlap the entire web site or display a login form, which looks the same as the site's original, but transmits the user name and password to the attacker's site. Or it could use CSS and/or JavaScript to hide a legitimate link in the web application, and display another one at its place which redirects to a fake web site.
<ide>
<ide> The worms exploit a hole in Yahoo's HTML/JavaScript filter, which usually filter
<ide>
<ide> Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on [Rosario Valotta's paper](http://www.xssed.com/news/37/Nduja_Connection_A_cross_webmail_worm_XWW/). Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with.
<ide>
<del>In December 2006, 34,000 actual user names and passwords were stolen in a [MySpace phishing attack](http://news.netcraft.com/archives/2006/10/27/myspace_accounts_compromised_by_phishers.html). The idea of the attack was to create a profile page named "login_home_index_html", so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form.
<add>In December 2006, 34,000 actual user names and passwords were stolen in a [MySpace phishing attack](https://news.netcraft.com/archives/2006/10/27/myspace_accounts_compromised_by_phishers.html). The idea of the attack was to create a profile page named "login_home_index_html", so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form.
<ide>
<ide> ### CSS Injection
<ide>
<ide> Another problem for the worm's author was the [CSRF security tokens](#cross-site
<ide>
<ide> In the end, he got a 4 KB worm, which he injected into his profile page.
<ide>
<del>The [moz-binding](http://www.securiteam.com/securitynews/5LP051FHPE.html) CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example).
<add>The [moz-binding](https://www.securiteam.com/securitynews/5LP051FHPE.html) CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example).
<ide>
<ide> #### Countermeasures
<ide> | 10 |
Text | Text | add initial documentation for java-based packages | e92d67d15c9d00bce05504dedc52491c8be71925 | <ide><path>docs/Homebrew-and-Java.md
<add># Homebrew and Java
<add>
<add>This page describes how Java is handled in Homebrew for users. Prospective formula authors may refer to existing Java-based formulae for examples of how to install packages written in Java via Homebrew, or visit the [Homebrew discussion forum](https://github.com/Homebrew/discussions/discussions) to seek guidance for their specific situation.
<add>
<add>Most Java-based packages in Homebrew use the default Homebrew-provided `openjdk` package for their JDK dependency, although some packages with specific version requirements may use a versioned package such as `openjdk@8`.
<add>
<add>## Executing commands using a different JDK
<add>
<add>In situations where the user wants to override the use of the Homebrew-provided JDK, setting the `JAVA_HOME` environment variable will cause the specified location to be used as the Java home directory instead of the version of `openjdk` specified as a dependency. | 1 |
Javascript | Javascript | fix parsing of coordindex when not ending with -1 | 76d1e9d1b95633b52228d595b878052f41e8fed8 | <ide><path>examples/js/loaders/VRMLLoader.js
<ide> THREE.VRMLLoader = ( function () {
<ide>
<ide> // an index of -1 indicates that the current face has ended and the next one begins
<ide>
<del> if ( index[ i + 3 ] === - 1 ) {
<add> if ( index[ i + 3 ] === - 1 || i + 3 >= l ) {
<ide>
<ide> i += 3;
<ide> start = i + 1;
<ide> THREE.VRMLLoader = ( function () {
<ide>
<ide> // an index of -1 indicates that the current face has ended and the next one begins
<ide>
<del> if ( index[ i + 3 ] === - 1 ) {
<add> if ( index[ i + 3 ] === - 1 || i + 3 >= l ) {
<ide>
<ide> i += 3;
<ide> start ++;
<ide> THREE.VRMLLoader = ( function () {
<ide>
<ide> // an index of -1 indicates that the current line has ended and the next one begins
<ide>
<del> if ( index[ i + 2 ] === - 1 ) {
<add> if ( index[ i + 2 ] === - 1 || i + 2 >= l ) {
<ide>
<ide> i += 2;
<ide>
<ide> THREE.VRMLLoader = ( function () {
<ide>
<ide> // an index of -1 indicates that the current line has ended and the next one begins
<ide>
<del> if ( index[ i + 2 ] === - 1 ) {
<add> if ( index[ i + 2 ] === - 1 || i + 2 >= l ) {
<ide>
<ide> i += 2;
<ide> start ++; | 1 |
PHP | PHP | use inner join instead of a left join | 3bdcf7b440febde90c3eb5d0260716cba70847df | <ide><path>lib/Cake/Model/AclNode.php
<ide> public function node($ref = null) {
<ide> 'joins' => array(array(
<ide> 'table' => $table,
<ide> 'alias' => "{$type}0",
<del> 'type' => 'LEFT',
<add> 'type' => 'INNER',
<ide> 'conditions' => array(
<ide> $db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"),
<ide> $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght") | 1 |
Javascript | Javascript | avoid re-exports from ember-metal/platform | a5d91490cd1ef0e99da06ee61fbb7e1c423b14b8 | <ide><path>packages/ember-application/lib/system/application.js
<ide> import { runLoadHooks } from "ember-runtime/system/lazy_load";
<ide> import Namespace from "ember-runtime/system/namespace";
<ide> import DeferredMixin from "ember-runtime/mixins/deferred";
<ide> import DefaultResolver from "ember-application/system/resolver";
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide> import run from "ember-metal/run_loop";
<ide> import { canInvoke } from "ember-metal/utils";
<ide> import Controller from "ember-runtime/controllers/controller";
<ide><path>packages/ember-htmlbars/lib/helpers.js
<ide> @submodule ember-htmlbars
<ide> */
<ide>
<del>import { create as o_create } from "ember-metal/platform";
<add>import o_create from "ember-metal/platform/create";
<ide>
<ide> /**
<ide> @private
<ide><path>packages/ember-htmlbars/tests/integration/escape_integration_test.js
<ide> import EmberView from 'ember-views/views/view';
<ide> import compile from 'ember-template-compiler/system/compile';
<ide>
<ide> import { set } from 'ember-metal/property_set';
<del>import { create as o_create } from 'ember-metal/platform';
<add>import o_create from 'ember-metal/platform/create';
<ide> import { runAppend, runDestroy } from "ember-runtime/tests/utils";
<ide>
<ide> var view;
<ide><path>packages/ember-metal-views/tests/test_helpers.js
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import { Renderer } from "ember-metal-views";
<ide>
<ide> var renderer;
<ide><path>packages/ember-metal/lib/alias.js
<ide> import {
<ide> defineProperty
<ide> } from "ember-metal/properties";
<ide> import { ComputedProperty } from "ember-metal/computed";
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide> import {
<ide> meta,
<ide> inspect
<ide><path>packages/ember-metal/lib/dependent_keys.js
<ide> //
<ide> // REMOVE_USE_STRICT: true
<ide>
<del>import {
<del> create as o_create
<del>} from "ember-metal/platform";
<add>import o_create from "ember-metal/platform/create";
<ide> import {
<ide> watch,
<ide> unwatch
<ide><path>packages/ember-metal/lib/deprecate_property.js
<ide> */
<ide>
<ide> import Ember from "ember-metal/core";
<del>import { hasPropertyAccessors } from "ember-metal/platform";
<add>import { hasPropertyAccessors } from "ember-metal/platform/define_property";
<ide> import { defineProperty } from "ember-metal/properties";
<ide> import { get } from "ember-metal/property_get";
<ide> import { set } from "ember-metal/property_set";
<ide><path>packages/ember-metal/lib/dictionary.js
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide>
<ide> // the delete is meant to hint at runtimes that this object should remain in
<ide> // dictionary mode. This is clearly a runtime specific hack, but currently it
<ide><path>packages/ember-metal/lib/error.js
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide>
<ide> var errorProps = [
<ide> 'description',
<ide><path>packages/ember-metal/lib/events.js
<ide> import {
<ide> apply,
<ide> applyStr
<ide> } from "ember-metal/utils";
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide>
<ide> var a_slice = [].slice;
<ide>
<ide><path>packages/ember-metal/lib/injected_property.js
<ide> import Ember from "ember-metal/core"; // Ember.assert
<ide> import { ComputedProperty } from "ember-metal/computed";
<ide> import { AliasedProperty } from "ember-metal/alias";
<ide> import { Descriptor } from "ember-metal/properties";
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide> import { meta } from "ember-metal/utils";
<ide>
<ide> /**
<ide><path>packages/ember-metal/lib/keys.js
<del>import { canDefineNonEnumerableProperties } from 'ember-metal/platform';
<add>import { canDefineNonEnumerableProperties } from 'ember-metal/platform/define_property';
<ide>
<ide> /**
<ide> Returns all of the keys defined on an object or hash. This is useful
<ide><path>packages/ember-metal/lib/main.js
<ide> import EmberError from "ember-metal/error";
<ide> import EnumerableUtils from "ember-metal/enumerable_utils";
<ide> import Cache from "ember-metal/cache";
<ide> import {
<del> create,
<ide> hasPropertyAccessors
<del>} from "ember-metal/platform";
<add>} from 'ember-metal/platform/define_property';
<add>import create from 'ember-metal/platform/create';
<ide> import {
<ide> filter,
<ide> forEach,
<ide><path>packages/ember-metal/lib/map.js
<ide>
<ide> import { guidFor } from "ember-metal/utils";
<ide> import { indexOf } from "ember-metal/array";
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide> import { deprecateProperty } from "ember-metal/deprecate_property";
<ide>
<ide> function missingFunction(fn) {
<ide><path>packages/ember-metal/lib/mixin.js
<ide> import {
<ide> indexOf as a_indexOf,
<ide> forEach as a_forEach
<ide> } from "ember-metal/array";
<del>import {
<del> create as o_create
<del>} from "ember-metal/platform";
<add>import o_create from "ember-metal/platform/create";
<ide> import { get } from "ember-metal/property_get";
<ide> import { set, trySet } from "ember-metal/property_set";
<ide> import {
<ide><path>packages/ember-metal/lib/platform.js
<del>import {
<del> hasES5CompliantDefineProperty,
<del> defineProperty
<del>} from 'ember-metal/platform/define_property';
<del>import defineProperties from 'ember-metal/platform/define_properties';
<del>import create from 'ember-metal/platform/create';
<del>
<del>/**
<del>@module ember-metal
<del>*/
<del>
<del>var hasPropertyAccessors = hasES5CompliantDefineProperty;
<del>var canDefineNonEnumerableProperties = hasES5CompliantDefineProperty;
<del>
<del>/**
<del> Platform specific methods and feature detectors needed by the framework.
<del>
<del> @class platform
<del> @namespace Ember
<del> @static
<del>*/
<del>
<del>export {
<del> create,
<del> defineProperty,
<del> defineProperties,
<del> hasPropertyAccessors,
<del> canDefineNonEnumerableProperties
<del>};
<del>
<ide><path>packages/ember-metal/lib/platform/define_property.js
<ide> if (hasES5CompliantDefineProperty && typeof document !== 'undefined') {
<ide> }
<ide>
<ide> if (!hasES5CompliantDefineProperty) {
<del> defineProperty = function defineProperty(obj, keyName, desc) {
<add> defineProperty = function definePropertyPolyfill(obj, keyName, desc) {
<ide> if (!desc.get) { obj[keyName] = desc.value; }
<ide> };
<ide> }
<ide>
<add>var hasPropertyAccessors = hasES5CompliantDefineProperty;
<add>var canDefineNonEnumerableProperties = hasES5CompliantDefineProperty;
<add>
<ide> export {
<ide> hasES5CompliantDefineProperty,
<del> defineProperty
<add> defineProperty,
<add> hasPropertyAccessors,
<add> canDefineNonEnumerableProperties
<ide> };
<ide><path>packages/ember-metal/lib/properties.js
<ide> import { meta as metaFor } from "ember-metal/utils";
<ide> import {
<ide> defineProperty as objectDefineProperty,
<ide> hasPropertyAccessors
<del>} from "ember-metal/platform";
<add>} from 'ember-metal/platform/define_property';
<ide> import { overrideChains } from "ember-metal/property_events";
<ide> // ..........................................................
<ide> // DESCRIPTOR
<ide><path>packages/ember-metal/lib/property_get.js
<ide> import {
<ide> isPath,
<ide> hasThis as pathHasThis
<ide> } from "ember-metal/path_cache";
<del>import { hasPropertyAccessors } from "ember-metal/platform";
<add>import { hasPropertyAccessors } from "ember-metal/platform/define_property";
<ide>
<ide> var FIRST_KEY = /^([^\.]+)/;
<ide>
<ide><path>packages/ember-metal/lib/property_set.js
<ide> import EmberError from "ember-metal/error";
<ide> import {
<ide> isPath
<ide> } from "ember-metal/path_cache";
<del>import { hasPropertyAccessors } from "ember-metal/platform";
<add>import { hasPropertyAccessors } from "ember-metal/platform/define_property";
<ide>
<ide> var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/;
<ide>
<ide><path>packages/ember-metal/lib/streams/conditional.js
<ide> import {
<ide> unsubscribe,
<ide> isStream
<ide> } from "ember-metal/streams/utils";
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide>
<ide> export default function conditional(test, consequent, alternate) {
<ide> if (isStream(test)) {
<ide><path>packages/ember-metal/lib/streams/simple.js
<ide> import merge from "ember-metal/merge";
<ide> import Stream from "ember-metal/streams/stream";
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide> import { read, isStream } from "ember-metal/streams/utils";
<ide>
<ide> function SimpleStream(source) {
<ide><path>packages/ember-metal/lib/streams/stream.js
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide> import {
<ide> getFirstKey,
<ide> getTailPath
<ide><path>packages/ember-metal/lib/streams/stream_binding.js
<del>import { create } from "ember-metal/platform";
<add>import create from "ember-metal/platform/create";
<ide> import merge from "ember-metal/merge";
<ide> import run from "ember-metal/run_loop";
<ide> import Stream from "ember-metal/streams/stream";
<ide><path>packages/ember-metal/lib/utils.js
<ide> // REMOVE_USE_STRICT: true
<ide>
<ide> import Ember from "ember-metal/core";
<add>import o_create from 'ember-metal/platform/create';
<ide> import {
<del> defineProperty as o_defineProperty,
<del> canDefineNonEnumerableProperties,
<ide> hasPropertyAccessors,
<del> create as o_create
<del>} from "ember-metal/platform";
<add> defineProperty as o_defineProperty,
<add> canDefineNonEnumerableProperties
<add>} from 'ember-metal/platform/define_property';
<ide>
<ide> import {
<ide> forEach
<ide><path>packages/ember-metal/lib/watch_key.js
<ide> import {
<ide> import {
<ide> defineProperty as o_defineProperty,
<ide> hasPropertyAccessors
<del>} from "ember-metal/platform";
<add>} from "ember-metal/platform/define_property";
<ide> import {
<ide> MANDATORY_SETTER_FUNCTION,
<ide> DEFAULT_GETTER_FUNCTION
<ide><path>packages/ember-metal/tests/accessors/get_path_test.js
<ide> import { get } from 'ember-metal/property_get';
<ide>
<ide> function expectGlobalContextDeprecation(assertion) {
<del> expectDeprecation(function() {
<del> assertion();
<del> }, "Ember.get fetched 'localPathGlobal' from the global context. This behavior will change in the future (issue #3852)");
<add> expectDeprecation(
<add> assertion,
<add> "Ember.get fetched 'localPathGlobal' from the global context. This behavior will change in the future (issue #3852)"
<add> );
<ide> }
<ide>
<ide> var obj;
<ide><path>packages/ember-metal/tests/accessors/get_test.js
<ide> import {
<ide> observer
<ide> } from 'ember-metal/mixin';
<ide> import { addObserver } from "ember-metal/observer";
<del>import { create } from 'ember-metal/platform';
<add>import create from 'ember-metal/platform/create';
<ide>
<ide> QUnit.module('Ember.get');
<ide>
<ide><path>packages/ember-metal/tests/accessors/mandatory_setters_test.js
<ide> import { set } from "ember-metal/property_set";
<ide> import { watch } from "ember-metal/watching";
<ide> import {
<ide> hasPropertyAccessors,
<del> defineProperty,
<del> create
<del>} from "ember-metal/platform";
<add> defineProperty
<add>} from "ember-metal/platform/define_property";
<add>import create from 'ember-metal/platform/create';
<ide> import { meta as metaFor } from "ember-metal/utils";
<ide>
<ide> QUnit.module('mandatory-setters');
<ide><path>packages/ember-metal/tests/chains_test.js
<ide> import { addObserver } from "ember-metal/observer";
<ide> import { finishChains } from "ember-metal/chains";
<del>import { create } from 'ember-metal/platform';
<add>import create from 'ember-metal/platform/create';
<ide>
<ide> QUnit.module("Chains");
<ide>
<ide><path>packages/ember-metal/tests/computed_test.js
<ide> import Ember from 'ember-metal/core';
<ide> import { testBoth } from 'ember-metal/tests/props_helper';
<del>import { create } from 'ember-metal/platform';
<add>import create from 'ember-metal/platform/create';
<ide> import {
<ide> ComputedProperty,
<ide> computed,
<ide><path>packages/ember-metal/tests/core/inspect_test.js
<ide> import { inspect } from "ember-metal/utils";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide>
<ide> QUnit.module("Ember.inspect");
<ide>
<ide><path>packages/ember-metal/tests/events_test.js
<ide> import { Mixin } from 'ember-metal/mixin';
<del>import { create } from 'ember-metal/platform';
<add>import create from 'ember-metal/platform/create';
<ide> import { meta } from 'ember-metal/utils';
<ide>
<ide> import {
<ide><path>packages/ember-metal/tests/map_test.js
<ide> import {
<ide>
<ide> import {
<ide> hasPropertyAccessors
<del>} from "ember-metal/platform";
<add>} from "ember-metal/platform/define_property";
<ide>
<ide> var object, number, string, map, variety;
<ide> var varieties = [['Map', Map], ['MapWithDefault', MapWithDefault]];
<ide><path>packages/ember-metal/tests/mixin/method_test.js
<del>import { create } from 'ember-metal/platform';
<add>import create from 'ember-metal/platform/create';
<ide> import {
<ide> mixin,
<ide> Mixin
<ide><path>packages/ember-metal/tests/observer_test.js
<ide> import {
<ide> propertyWillChange,
<ide> propertyDidChange
<ide> } from 'ember-metal/property_events';
<del>import { create } from 'ember-metal/platform';
<add>import create from 'ember-metal/platform/create';
<ide> import { defineProperty } from 'ember-metal/properties';
<ide> import {
<ide> computed,
<ide><path>packages/ember-metal/tests/platform/create_test.js
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide>
<ide> QUnit.module("Ember.create()");
<ide>
<ide><path>packages/ember-metal/tests/platform/define_property_test.js
<del>import { defineProperty, hasPropertyAccessors, canDefineNonEnumerableProperties } from 'ember-metal/platform';
<add>import {
<add> defineProperty,
<add> hasPropertyAccessors,
<add> canDefineNonEnumerableProperties
<add>} from 'ember-metal/platform/define_property';
<ide> import EnumerableUtils from 'ember-metal/enumerable_utils';
<ide>
<ide> function isEnumerable(obj, keyName) {
<ide><path>packages/ember-metal/tests/properties_test.js
<del>import { hasPropertyAccessors } from "ember-metal/platform";
<add>import { hasPropertyAccessors } from "ember-metal/platform/define_property";
<ide> import { computed } from 'ember-metal/computed';
<ide> import { defineProperty } from "ember-metal/properties";
<ide> import { deprecateProperty } from "ember-metal/deprecate_property";
<ide><path>packages/ember-metal/tests/utils/meta_test.js
<ide> /*global jQuery*/
<ide> import Ember from 'ember-metal/core';
<ide> import {
<del> create,
<ide> canDefineNonEnumerableProperties
<del>} from 'ember-metal/platform';
<add>} from 'ember-metal/platform/define_property';
<add>import create from 'ember-metal/platform/create';
<ide> import {
<ide> getMeta,
<ide> setMeta,
<ide><path>packages/ember-routing-htmlbars/tests/helpers/render_test.js
<ide> import Ember from 'ember-metal/core'; // TEMPLATES
<ide> import { set } from "ember-metal/property_set";
<ide> import run from "ember-metal/run_loop";
<del>import { canDefineNonEnumerableProperties } from 'ember-metal/platform';
<add>import { canDefineNonEnumerableProperties } from 'ember-metal/platform/define_property';
<ide> import { observer } from 'ember-metal/mixin';
<ide>
<ide> import Namespace from "ember-runtime/system/namespace";
<ide><path>packages/ember-routing/lib/system/router.js
<ide> import {
<ide> getActiveTargetName,
<ide> stashParamNames
<ide> } from "ember-routing/utils";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide>
<ide> import RouterState from "./router_state";
<ide>
<ide><path>packages/ember-runtime/lib/computed/array_computed.js
<ide> import {
<ide> ReduceComputedProperty
<ide> } from 'ember-runtime/computed/reduce_computed';
<ide> import { forEach } from 'ember-metal/enumerable_utils';
<del>import { create as o_create } from 'ember-metal/platform';
<add>import o_create from 'ember-metal/platform/create';
<ide> import { addObserver } from 'ember-metal/observer';
<ide> import EmberError from 'ember-metal/error';
<ide>
<ide><path>packages/ember-runtime/lib/computed/reduce_computed.js
<ide> import {
<ide> ComputedProperty,
<ide> cacheFor
<ide> } from 'ember-metal/computed';
<del>import { create as o_create } from 'ember-metal/platform';
<add>import o_create from 'ember-metal/platform/create';
<ide> import { forEach } from 'ember-metal/enumerable_utils';
<ide> import TrackedArray from 'ember-runtime/system/tracked_array';
<ide> import EmberArray from 'ember-runtime/mixins/array';
<ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> import {
<ide> guidFor,
<ide> apply
<ide> } from "ember-metal/utils";
<del>import { create as o_create } from "ember-metal/platform";
<add>import o_create from 'ember-metal/platform/create';
<ide> import {
<ide> generateGuid,
<ide> GUID_KEY_PROPERTY,
<ide> import {
<ide> } from "ember-metal/mixin";
<ide> import { indexOf } from "ember-metal/enumerable_utils";
<ide> import EmberError from "ember-metal/error";
<del>import { defineProperty as o_defineProperty } from "ember-metal/platform";
<add>import { defineProperty as o_defineProperty } from "ember-metal/platform/define_property";
<ide> import keys from "ember-metal/keys";
<ide> import ActionHandler from "ember-runtime/mixins/action_handler";
<ide> import { defineProperty } from "ember-metal/properties";
<ide> import { destroy } from "ember-metal/watching";
<ide> import {
<ide> K
<ide> } from 'ember-metal/core';
<del>import { hasPropertyAccessors } from "ember-metal/platform";
<add>import { hasPropertyAccessors } from "ember-metal/platform/define_property";
<ide> import { validatePropertyInjections } from "ember-runtime/inject";
<ide>
<ide> var schedule = run.schedule;
<ide><path>packages/ember-runtime/tests/core/copy_test.js
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import copy from "ember-runtime/copy";
<ide>
<ide> QUnit.module("Ember Copy Method");
<ide><path>packages/ember-runtime/tests/ext/mixin_test.js
<ide> import {set} from "ember-metal/property_set";
<ide> import {get} from "ember-metal/property_get";
<ide> import {Mixin} from "ember-metal/mixin";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import { Binding } from "ember-metal/binding";
<ide> import run from "ember-metal/run_loop";
<ide>
<ide><path>packages/ember-runtime/tests/mixins/promise_proxy_test.js
<del>import {create} from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import {get} from "ember-metal/property_get";
<ide> import run from "ember-metal/run_loop";
<ide> import ObjectProxy from "ember-runtime/system/object_proxy";
<ide><path>packages/ember-runtime/tests/system/object/destroy_test.js
<ide> import run from "ember-metal/run_loop";
<del>import { hasPropertyAccessors } from "ember-metal/platform";
<add>import { hasPropertyAccessors } from "ember-metal/platform/define_property";
<ide> import { observer } from "ember-metal/mixin";
<ide> import { set } from "ember-metal/property_set";
<ide> import { bind } from "ember-metal/binding";
<ide><path>packages/ember-testing/lib/test.js
<ide> import Ember from "ember-metal/core";
<ide> import emberRun from "ember-metal/run_loop";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import RSVP from "ember-runtime/ext/rsvp";
<ide> import setupForTesting from "ember-testing/setup_for_testing";
<ide> import EmberApplication from "ember-application/system/application";
<ide><path>packages/ember-views/lib/streams/context_stream.js
<ide> import Ember from 'ember-metal/core';
<ide>
<ide> import merge from "ember-metal/merge";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import { isGlobal } from "ember-metal/path_cache";
<ide> import Stream from "ember-metal/streams/stream";
<ide> import SimpleStream from "ember-metal/streams/simple";
<ide><path>packages/ember-views/lib/streams/key_stream.js
<ide> import Ember from 'ember-metal/core';
<ide>
<ide> import merge from "ember-metal/merge";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import { get } from "ember-metal/property_get";
<ide> import { set } from "ember-metal/property_set";
<ide> import {
<ide><path>packages/ember-views/lib/streams/should_display.js
<ide> import {
<ide> unsubscribe,
<ide> isStream
<ide> } from "ember-metal/streams/utils";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import { get } from "ember-metal/property_get";
<ide> import { isArray } from "ember-metal/utils";
<ide>
<ide><path>packages/ember-views/lib/system/render_buffer.js
<ide>
<ide> import jQuery from "ember-views/system/jquery";
<ide> import Ember from "ember-metal/core";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import environment from "ember-metal/environment";
<ide> import { normalizeProperty } from "morph/dom-helper/prop";
<ide>
<ide><path>packages/ember-views/lib/system/renderer.js
<ide> import Ember from "ember-metal/core";
<ide> import Renderer from 'ember-metal-views/renderer';
<del>import { create } from 'ember-metal/platform';
<add>import create from 'ember-metal/platform/create';
<ide> import RenderBuffer from "ember-views/system/render_buffer";
<ide> import run from "ember-metal/run_loop";
<ide> import { set } from "ember-metal/property_set";
<ide><path>packages/ember-views/lib/views/states.js
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import merge from "ember-metal/merge";
<ide> import _default from "ember-views/views/states/default";
<ide> import preRender from "ember-views/views/states/pre_render";
<ide><path>packages/ember-views/lib/views/states/destroying.js
<ide> import merge from "ember-metal/merge";
<del>import {create} from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import {fmt} from "ember-runtime/system/string";
<ide> import _default from "ember-views/views/states/default";
<ide> import EmberError from "ember-metal/error";
<ide><path>packages/ember-views/lib/views/states/has_element.js
<ide> import _default from "ember-views/views/states/default";
<ide> import run from "ember-metal/run_loop";
<ide> import merge from "ember-metal/merge";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import jQuery from "ember-views/system/jquery";
<ide> import EmberError from "ember-metal/error";
<ide>
<ide><path>packages/ember-views/lib/views/states/in_buffer.js
<ide> import _default from "ember-views/views/states/default";
<ide> import EmberError from "ember-metal/error";
<ide>
<ide> import jQuery from "ember-views/system/jquery";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import merge from "ember-metal/merge";
<ide>
<ide> /**
<ide><path>packages/ember-views/lib/views/states/in_dom.js
<ide> import Ember from "ember-metal/core"; // Ember.assert
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide> import merge from "ember-metal/merge";
<ide> import EmberError from "ember-metal/error";
<ide> import { addBeforeObserver } from 'ember-metal/observer';
<ide><path>packages/ember-views/lib/views/states/pre_render.js
<ide> import _default from "ember-views/views/states/default";
<del>import { create } from "ember-metal/platform";
<add>import create from 'ember-metal/platform/create';
<ide>
<ide> /**
<ide> @module ember
<ide><path>packages/ember-views/lib/views/view.js
<ide> // Ember.ContainerView circular dependency
<ide> // Ember.ENV
<ide> import Ember from 'ember-metal/core';
<del>import { create } from 'ember-metal/platform';
<add>import create from 'ember-metal/platform/create';
<ide>
<ide> import Evented from "ember-runtime/mixins/evented";
<ide> import EmberObject from "ember-runtime/system/object";
<ide><path>packages/ember-views/tests/views/view/state_deprecation_test.js
<del>import { hasPropertyAccessors } from "ember-metal/platform";
<add>import { hasPropertyAccessors } from "ember-metal/platform/define_property";
<ide> import run from "ember-metal/run_loop";
<ide> import EmberView from "ember-views/views/view";
<ide>
<ide><path>packages/ember/tests/routing/query_params_test.js
<ide> import "ember";
<ide> import { computed } from "ember-metal/computed";
<del>import { canDefineNonEnumerableProperties } from 'ember-metal/platform';
<add>import { canDefineNonEnumerableProperties } from 'ember-metal/platform/define_property';
<ide> import { capitalize } from "ember-runtime/system/string";
<ide>
<ide> import EmberHandlebars from "ember-htmlbars/compat"; | 64 |
Ruby | Ruby | fix rubocop issue | 42469c50610d574d83f329f4a93b3ce4b97fed27 | <ide><path>actionview/lib/action_view/template.rb
<ide> def encode!
<ide> end
<ide> end
<ide>
<del>
<add>
<ide> # Exceptions are marshalled when using the parallel test runner with DRb, so we need
<ide> # to ensure that references to the template object can be marshalled as well. This means forgoing
<ide> # the marshalling of the compiler mutex and instantiating that again on unmarshalling. | 1 |
Ruby | Ruby | fix typos and grammar mistake [ci skip] | 517caa85c97b0addba0d27fffa03aec40f70ff1f | <ide><path>activerecord/lib/active_record/attribute_methods.rb
<ide> def column_for_attribute(name)
<ide> end
<ide>
<ide> # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
<del> # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). It raises
<add> # "2004-12-12" in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises
<ide> # <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
<ide> #
<ide> # Alias for the <tt>read_attribute</tt> method.
<ide><path>activesupport/lib/active_support/core_ext/thread.rb
<ide> def thread_variable_set(key, value)
<ide> _locals[key.to_sym] = value
<ide> end
<ide>
<del> # Returns an an array of the names of the thread-local variables (as Symbols).
<add> # Returns an array of the names of the thread-local variables (as Symbols).
<ide> #
<ide> # thr = Thread.new do
<ide> # Thread.current.thread_variable_set(:cat, 'meow') | 2 |
PHP | PHP | remove 5.5 bug workaround | 38d5d28b1afe33f22fde12c4c463b703f8461285 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function fill(array $attributes)
<ide> */
<ide> public function forceFill(array $attributes)
<ide> {
<del> // Since some versions of PHP have a bug that prevents it from properly
<del> // binding the late static context in a closure, we will first store
<del> // the model in a variable, which we will then use in the closure.
<del> $model = $this;
<del>
<del> return static::unguarded(function () use ($model, $attributes) {
<del> return $model->fill($attributes);
<add> return static::unguarded(function () use ($attributes) {
<add> return $this->fill($attributes);
<ide> });
<ide> }
<ide>
<ide> public static function create(array $attributes = [])
<ide> */
<ide> public static function forceCreate(array $attributes)
<ide> {
<del> // Since some versions of PHP have a bug that prevents it from properly
<del> // binding the late static context in a closure, we will first store
<del> // the model in a variable, which we will then use in the closure.
<del> $model = new static;
<del>
<del> return static::unguarded(function () use ($model, $attributes) {
<del> return $model->create($attributes);
<add> return static::unguarded(function () use ($attributes) {
<add> return (new static)->create($attributes);
<ide> });
<ide> }
<ide> | 1 |
Ruby | Ruby | add support for rar archives | 0b56c62bf50c1291f0259aa2ea9ff86afe826c0b | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def stage
<ide> # TODO check if it's really a tar archive
<ide> safe_system '/usr/bin/tar', 'xf', @tarball_path
<ide> chdir
<add> when 'Rar!'
<add> quiet_safe_system 'unrar', 'x', {:quiet_flag => '-inul'}, @tarball_path
<ide> else
<ide> # we are assuming it is not an archive, use original filename
<ide> # this behaviour is due to ScriptFileFormula expectations | 1 |
Java | Java | remove inconsistent spaces | fb898e17272c13ef01f68125c3bba35f55f3fb7a | <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/adapter/MethodBeforeAdviceInterceptor.java
<ide> public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
<ide>
<ide> @Override
<ide> public Object invoke(MethodInvocation mi) throws Throwable {
<del> this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
<add> this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
<ide> return mi.proceed();
<ide> }
<ide>
<ide><path>spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java
<ide> public void tearDown() {
<ide> @Test
<ide> public void testBasicFunctionality() {
<ide> SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable");
<del> assertEquals(INITIAL_COUNT, proxied.getCount() );
<add> assertEquals(INITIAL_COUNT, proxied.getCount());
<ide> proxied.doWork();
<del> assertEquals(INITIAL_COUNT + 1, proxied.getCount() );
<add> assertEquals(INITIAL_COUNT + 1, proxied.getCount());
<ide>
<ide> proxied = (SideEffectBean) beanFactory.getBean("swappable");
<ide> proxied.doWork();
<del> assertEquals(INITIAL_COUNT + 2, proxied.getCount() );
<add> assertEquals(INITIAL_COUNT + 2, proxied.getCount());
<ide> }
<ide>
<ide> @Test
<ide> public void testValidSwaps() {
<ide> SideEffectBean target2 = (SideEffectBean) beanFactory.getBean("target2");
<ide>
<ide> SideEffectBean proxied = (SideEffectBean) beanFactory.getBean("swappable");
<del> assertEquals(target1.getCount(), proxied.getCount() );
<add> assertEquals(target1.getCount(), proxied.getCount());
<ide> proxied.doWork();
<del> assertEquals(INITIAL_COUNT + 1, proxied.getCount() );
<add> assertEquals(INITIAL_COUNT + 1, proxied.getCount());
<ide>
<ide> HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper");
<ide> Object old = swapper.swap(target2);
<ide><path>spring-aop/src/test/java/org/springframework/aop/target/PrototypeTargetSourceTests.java
<ide> public void setUp() throws Exception {
<ide> @Test
<ide> public void testPrototypeAndSingletonBehaveDifferently() {
<ide> SideEffectBean singleton = (SideEffectBean) beanFactory.getBean("singleton");
<del> assertEquals(INITIAL_COUNT, singleton.getCount() );
<add> assertEquals(INITIAL_COUNT, singleton.getCount());
<ide> singleton.doWork();
<del> assertEquals(INITIAL_COUNT + 1, singleton.getCount() );
<add> assertEquals(INITIAL_COUNT + 1, singleton.getCount());
<ide>
<ide> SideEffectBean prototype = (SideEffectBean) beanFactory.getBean("prototype");
<del> assertEquals(INITIAL_COUNT, prototype.getCount() );
<add> assertEquals(INITIAL_COUNT, prototype.getCount());
<ide> prototype.doWork();
<del> assertEquals(INITIAL_COUNT, prototype.getCount() );
<add> assertEquals(INITIAL_COUNT, prototype.getCount());
<ide> }
<ide>
<ide>
<ide><path>spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java
<ide> protected void tearDown() {
<ide> @Test
<ide> public void testUseDifferentManagedInstancesInSameThread() {
<ide> SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
<del> assertEquals(INITIAL_COUNT, apartment.getCount() );
<add> assertEquals(INITIAL_COUNT, apartment.getCount());
<ide> apartment.doWork();
<del> assertEquals(INITIAL_COUNT + 1, apartment.getCount() );
<add> assertEquals(INITIAL_COUNT + 1, apartment.getCount());
<ide>
<ide> ITestBean test = (ITestBean) beanFactory.getBean("threadLocal2");
<ide> assertEquals("Rod", test.getName());
<ide> public void testUseDifferentManagedInstancesInSameThread() {
<ide> @Test
<ide> public void testReuseInSameThread() {
<ide> SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
<del> assertEquals(INITIAL_COUNT, apartment.getCount() );
<add> assertEquals(INITIAL_COUNT, apartment.getCount());
<ide> apartment.doWork();
<del> assertEquals(INITIAL_COUNT + 1, apartment.getCount() );
<add> assertEquals(INITIAL_COUNT + 1, apartment.getCount());
<ide>
<ide> apartment = (SideEffectBean) beanFactory.getBean("apartment");
<del> assertEquals(INITIAL_COUNT + 1, apartment.getCount() );
<add> assertEquals(INITIAL_COUNT + 1, apartment.getCount());
<ide> }
<ide>
<ide> /**
<ide> public void testCanGetStatsViaMixin() {
<ide> @Test
<ide> public void testNewThreadHasOwnInstance() throws InterruptedException {
<ide> SideEffectBean apartment = (SideEffectBean) beanFactory.getBean("apartment");
<del> assertEquals(INITIAL_COUNT, apartment.getCount() );
<add> assertEquals(INITIAL_COUNT, apartment.getCount());
<ide> apartment.doWork();
<ide> apartment.doWork();
<ide> apartment.doWork();
<del> assertEquals(INITIAL_COUNT + 3, apartment.getCount() );
<add> assertEquals(INITIAL_COUNT + 3, apartment.getCount());
<ide>
<ide> class Runner implements Runnable {
<ide> public SideEffectBean mine;
<ide> @Override
<ide> public void run() {
<ide> this.mine = (SideEffectBean) beanFactory.getBean("apartment");
<del> assertEquals(INITIAL_COUNT, mine.getCount() );
<add> assertEquals(INITIAL_COUNT, mine.getCount());
<ide> mine.doWork();
<del> assertEquals(INITIAL_COUNT + 1, mine.getCount() );
<add> assertEquals(INITIAL_COUNT + 1, mine.getCount());
<ide> }
<ide> }
<ide> Runner r = new Runner();
<ide> public void run() {
<ide> assertNotNull(r);
<ide>
<ide> // Check it didn't affect the other thread's copy
<del> assertEquals(INITIAL_COUNT + 3, apartment.getCount() );
<add> assertEquals(INITIAL_COUNT + 3, apartment.getCount());
<ide>
<ide> // When we use other thread's copy in this thread
<ide> // it should behave like ours
<del> assertEquals(INITIAL_COUNT + 3, r.mine.getCount() );
<add> assertEquals(INITIAL_COUNT + 3, r.mine.getCount());
<ide>
<ide> // Bound to two threads
<ide> assertEquals(2, ((ThreadLocalTargetSourceStats) apartment).getObjectCount());
<ide><path>spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java
<ide> private Object testPrototypeInstancesAreIndependent(String beanName) {
<ide>
<ide> // Check it works without AOP
<ide> SideEffectBean raw = (SideEffectBean) bf.getBean("prototypeTarget");
<del> assertEquals(INITIAL_COUNT, raw.getCount() );
<add> assertEquals(INITIAL_COUNT, raw.getCount());
<ide> raw.doWork();
<del> assertEquals(INITIAL_COUNT+1, raw.getCount() );
<add> assertEquals(INITIAL_COUNT+1, raw.getCount());
<ide> raw = (SideEffectBean) bf.getBean("prototypeTarget");
<del> assertEquals(INITIAL_COUNT, raw.getCount() );
<add> assertEquals(INITIAL_COUNT, raw.getCount());
<ide>
<ide> // Now try with advised instances
<ide> SideEffectBean prototype2FirstInstance = (SideEffectBean) bf.getBean(beanName);
<del> assertEquals(INITIAL_COUNT, prototype2FirstInstance.getCount() );
<add> assertEquals(INITIAL_COUNT, prototype2FirstInstance.getCount());
<ide> prototype2FirstInstance.doWork();
<del> assertEquals(INITIAL_COUNT + 1, prototype2FirstInstance.getCount() );
<add> assertEquals(INITIAL_COUNT + 1, prototype2FirstInstance.getCount());
<ide>
<ide> SideEffectBean prototype2SecondInstance = (SideEffectBean) bf.getBean(beanName);
<ide> assertFalse("Prototypes are not ==", prototype2FirstInstance == prototype2SecondInstance);
<del> assertEquals(INITIAL_COUNT, prototype2SecondInstance.getCount() );
<del> assertEquals(INITIAL_COUNT + 1, prototype2FirstInstance.getCount() );
<add> assertEquals(INITIAL_COUNT, prototype2SecondInstance.getCount());
<add> assertEquals(INITIAL_COUNT + 1, prototype2FirstInstance.getCount());
<ide>
<ide> return prototype2FirstInstance;
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java
<ide> private void testFunctionality(String name) {
<ide> // Just check that it works--we can't make assumptions
<ide> // about the count
<ide> pooled.doWork();
<del> //assertEquals(INITIAL_COUNT + 1, apartment.getCount() );
<add> //assertEquals(INITIAL_COUNT + 1, apartment.getCount());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-context/src/test/java/org/springframework/cache/AbstractCacheTests.java
<ide> private void doTestCacheGetCallable(Object returnValue) {
<ide> String key = createRandomKey();
<ide>
<ide> assertNull(cache.get(key));
<del> Object value = cache.get(key, () -> returnValue );
<add> Object value = cache.get(key, () -> returnValue);
<ide> assertEquals(returnValue, value);
<ide> assertEquals(value, cache.get(key).get());
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java
<ide> public void testInvokesMethodOnEjbInstance() throws Exception {
<ide>
<ide> LocalSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
<ide>
<del> ProxyFactory pf = new ProxyFactory(new Class<?>[] { BusinessMethods.class } );
<add> ProxyFactory pf = new ProxyFactory(new Class<?>[] { BusinessMethods.class });
<ide> pf.addAdvice(si);
<ide> BusinessMethods target = (BusinessMethods) pf.getProxy();
<ide>
<ide> public void testInvokesMethodOnEjbInstanceWithSeparateBusinessMethods() throws E
<ide>
<ide> LocalSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
<ide>
<del> ProxyFactory pf = new ProxyFactory(new Class<?>[] { BusinessMethods.class } );
<add> ProxyFactory pf = new ProxyFactory(new Class<?>[] { BusinessMethods.class });
<ide> pf.addAdvice(si);
<ide> BusinessMethods target = (BusinessMethods) pf.getProxy();
<ide>
<ide> private void testException(Exception expected) throws Exception {
<ide>
<ide> LocalSlsbInvokerInterceptor si = configuredInterceptor(mockContext, jndiName);
<ide>
<del> ProxyFactory pf = new ProxyFactory(new Class<?>[] { LocalInterfaceWithBusinessMethods.class } );
<add> ProxyFactory pf = new ProxyFactory(new Class<?>[] { LocalInterfaceWithBusinessMethods.class });
<ide> pf.addAdvice(si);
<ide> LocalInterfaceWithBusinessMethods target = (LocalInterfaceWithBusinessMethods) pf.getProxy();
<ide>
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java
<ide> public void test5() throws Exception {
<ide> lob.setTypeValue(preparedStatement, 1, Types.CLOB, "test");
<ide> verify(creator).setClobAsAsciiStream(eq(preparedStatement), eq(1), inputStreamCaptor.capture(), eq(3));
<ide> byte[] bytes = new byte[3];
<del> inputStreamCaptor.getValue().read(bytes );
<add> inputStreamCaptor.getValue().read(bytes);
<ide> assertThat(bytes, equalTo(testContent));
<ide> }
<ide>
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolver.java
<ide> protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> m
<ide> logger.warn("Message headers contain two values for the same header '" + name + "', " +
<ide> "one in the top level header map and a second in the nested map with native headers. " +
<ide> "Using the value from top level map. " +
<del> "Use 'nativeHeader.myHeader' to resolve to the value from the nested native header map." );
<add> "Use 'nativeHeader.myHeader' to resolve to the value from the nested native header map.");
<ide> }
<ide> }
<ide>
<ide><path>spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java
<ide> public boolean rollbackOn(Throwable t) {
<ide> }
<ide> catch (Throwable t) {
<ide> if (rollbackException) {
<del> assertEquals("Caught wrong exception", tex, t );
<add> assertEquals("Caught wrong exception", tex, t);
<ide> }
<ide> else {
<ide> assertEquals("Caught wrong exception", ex, t);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJackson2JsonView.java
<ide> protected void writePrefix(JsonGenerator generator, Object object) throws IOExce
<ide> }
<ide> if (jsonpFunction != null) {
<ide> generator.writeRaw("/**/");
<del> generator.writeRaw(jsonpFunction + "(" );
<add> generator.writeRaw(jsonpFunction + "(");
<ide> }
<ide> }
<ide>
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java
<ide> public void handleMatchMatrixVariablesDecoding() {
<ide> urlPathHelper.setUrlDecode(false);
<ide> urlPathHelper.setRemoveSemicolonContent(false);
<ide>
<del> this.handlerMapping.setUrlPathHelper(urlPathHelper );
<add> this.handlerMapping.setUrlPathHelper(urlPathHelper);
<ide>
<ide> request = new MockHttpServletRequest();
<ide> handleMatch(request, "/path{filter}", "/path;mvar=a%2fb");
<ide> protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handler
<ide> }
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add>}
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java
<ide> public abstract class AbstractSockJsService implements SockJsService, CorsConfig
<ide>
<ide> private long heartbeatTime = TimeUnit.SECONDS.toMillis(25);
<ide>
<del> private long disconnectDelay = TimeUnit.SECONDS.toMillis(5 );
<add> private long disconnectDelay = TimeUnit.SECONDS.toMillis(5);
<ide>
<ide> private int httpMessageCacheSize = 100;
<ide> | 14 |
Python | Python | prepare 1.1.1 release | c6d2ccd453bc71144ba891abc6876772144985c4 | <ide><path>keras/__init__.py
<ide> from . import optimizers
<ide> from . import regularizers
<ide>
<del>__version__ = '1.1.0'
<add>__version__ = '1.1.1'
<ide><path>setup.py
<ide>
<ide>
<ide> setup(name='Keras',
<del> version='1.1.0',
<add> version='1.1.1',
<ide> description='Deep Learning for Python',
<ide> author='Francois Chollet',
<ide> author_email='francois.chollet@gmail.com',
<ide> url='https://github.com/fchollet/keras',
<del> download_url='https://github.com/fchollet/keras/tarball/1.1.0',
<add> download_url='https://github.com/fchollet/keras/tarball/1.1.1',
<ide> license='MIT',
<ide> install_requires=['theano', 'pyyaml', 'six'],
<ide> extras_require={ | 2 |
Text | Text | add model card for singbert. | b6512d235792f7be4effcb480f701944b051274b | <ide><path>model_cards/zanelim/singbert/README.md
<add>---
<add>language: en
<add>tags:
<add>- singapore
<add>- sg
<add>- singlish
<add>- malaysia
<add>- ms
<add>- manglish
<add>- bert-base-uncased
<add>license: mit
<add>datasets:
<add>- reddit singapore, malaysia
<add>- hardwarezone
<add>widget:
<add>- text: "die [MASK] must try"
<add>- text: "kopi c siew [MASK]"
<add>---
<add>
<add># Model name
<add>
<add>SingBert - Bert for Singlish (SG) and Manglish (MY).
<add>
<add>## Model description
<add>
<add>[BERT base uncased](https://github.com/google-research/bert#pre-trained-models), with pre-training finetuned on
<add>[singlish](https://en.wikipedia.org/wiki/Singlish) and [manglish](https://en.wikipedia.org/wiki/Manglish) data.
<add>
<add>## Intended uses & limitations
<add>
<add>#### How to use
<add>
<add>```python
<add>>>> from transformers import pipeline
<add>>>> nlp = pipeline('fill-mask', model='zanelim/singbert')
<add>>>> nlp("kopi c siew [MASK]")
<add>
<add>[{'sequence': '[CLS] kopi c siew dai [SEP]',
<add> 'score': 0.5092713236808777,
<add> 'token': 18765,
<add> 'token_str': 'dai'},
<add> {'sequence': '[CLS] kopi c siew mai [SEP]',
<add> 'score': 0.3515934646129608,
<add> 'token': 14736,
<add> 'token_str': 'mai'},
<add> {'sequence': '[CLS] kopi c siew bao [SEP]',
<add> 'score': 0.05576375499367714,
<add> 'token': 25945,
<add> 'token_str': 'bao'},
<add> {'sequence': '[CLS] kopi c siew. [SEP]',
<add> 'score': 0.006019321270287037,
<add> 'token': 1012,
<add> 'token_str': '.'},
<add> {'sequence': '[CLS] kopi c siew sai [SEP]',
<add> 'score': 0.0038361591286957264,
<add> 'token': 18952,
<add> 'token_str': 'sai'}]
<add>
<add>>>> nlp("one teh c siew dai, and one kopi [MASK].")
<add>
<add>[{'sequence': '[CLS] one teh c siew dai, and one kopi c [SEP]',
<add> 'score': 0.6176503300666809,
<add> 'token': 1039,
<add> 'token_str': 'c'},
<add> {'sequence': '[CLS] one teh c siew dai, and one kopi o [SEP]',
<add> 'score': 0.21094971895217896,
<add> 'token': 1051,
<add> 'token_str': 'o'},
<add> {'sequence': '[CLS] one teh c siew dai, and one kopi. [SEP]',
<add> 'score': 0.13027705252170563,
<add> 'token': 1012,
<add> 'token_str': '.'},
<add> {'sequence': '[CLS] one teh c siew dai, and one kopi! [SEP]',
<add> 'score': 0.004680239595472813,
<add> 'token': 999,
<add> 'token_str': '!'},
<add> {'sequence': '[CLS] one teh c siew dai, and one kopi w [SEP]',
<add> 'score': 0.002034128177911043,
<add> 'token': 1059,
<add> 'token_str': 'w'}]
<add>
<add>>>> nlp("dont play [MASK] leh")
<add>
<add>[{'sequence': '[CLS] dont play play leh [SEP]',
<add> 'score': 0.9281464219093323,
<add> 'token': 2377,
<add> 'token_str': 'play'},
<add> {'sequence': '[CLS] dont play politics leh [SEP]',
<add> 'score': 0.010990909300744534,
<add> 'token': 4331,
<add> 'token_str': 'politics'},
<add> {'sequence': '[CLS] dont play punk leh [SEP]',
<add> 'score': 0.005583590362221003,
<add> 'token': 7196,
<add> 'token_str': 'punk'},
<add> {'sequence': '[CLS] dont play dirty leh [SEP]',
<add> 'score': 0.0025784350000321865,
<add> 'token': 6530,
<add> 'token_str': 'dirty'},
<add> {'sequence': '[CLS] dont play cheat leh [SEP]',
<add> 'score': 0.0025066907983273268,
<add> 'token': 21910,
<add> 'token_str': 'cheat'}]
<add>
<add>>>> nlp("catch no [MASK]")
<add>
<add>[{'sequence': '[CLS] catch no ball [SEP]',
<add> 'score': 0.7922210693359375,
<add> 'token': 3608,
<add> 'token_str': 'ball'},
<add> {'sequence': '[CLS] catch no balls [SEP]',
<add> 'score': 0.20503675937652588,
<add> 'token': 7395,
<add> 'token_str': 'balls'},
<add> {'sequence': '[CLS] catch no tail [SEP]',
<add> 'score': 0.0006608376861549914,
<add> 'token': 5725,
<add> 'token_str': 'tail'},
<add> {'sequence': '[CLS] catch no talent [SEP]',
<add> 'score': 0.0002158183924620971,
<add> 'token': 5848,
<add> 'token_str': 'talent'},
<add> {'sequence': '[CLS] catch no prisoners [SEP]',
<add> 'score': 5.3481446229852736e-05,
<add> 'token': 5895,
<add> 'token_str': 'prisoners'}]
<add>
<add>>>> nlp("confirm plus [MASK]")
<add>
<add>[{'sequence': '[CLS] confirm plus chop [SEP]',
<add> 'score': 0.992355227470398,
<add> 'token': 24494,
<add> 'token_str': 'chop'},
<add> {'sequence': '[CLS] confirm plus one [SEP]',
<add> 'score': 0.0037301010452210903,
<add> 'token': 2028,
<add> 'token_str': 'one'},
<add> {'sequence': '[CLS] confirm plus minus [SEP]',
<add> 'score': 0.0014284878270700574,
<add> 'token': 15718,
<add> 'token_str': 'minus'},
<add> {'sequence': '[CLS] confirm plus 1 [SEP]',
<add> 'score': 0.0011354683665558696,
<add> 'token': 1015,
<add> 'token_str': '1'},
<add> {'sequence': '[CLS] confirm plus chopped [SEP]',
<add> 'score': 0.0003804611915256828,
<add> 'token': 24881,
<add> 'token_str': 'chopped'}]
<add>
<add>>>> nlp("die [MASK] must try")
<add>
<add>[{'sequence': '[CLS] die die must try [SEP]',
<add> 'score': 0.9552758932113647,
<add> 'token': 3280,
<add> 'token_str': 'die'},
<add> {'sequence': '[CLS] die also must try [SEP]',
<add> 'score': 0.03644804656505585,
<add> 'token': 2036,
<add> 'token_str': 'also'},
<add> {'sequence': '[CLS] die liao must try [SEP]',
<add> 'score': 0.003282855963334441,
<add> 'token': 727,
<add> 'token_str': 'liao'},
<add> {'sequence': '[CLS] die already must try [SEP]',
<add> 'score': 0.0004937972989864647,
<add> 'token': 2525,
<add> 'token_str': 'already'},
<add> {'sequence': '[CLS] die hard must try [SEP]',
<add> 'score': 0.0003659659414552152,
<add> 'token': 2524,
<add> 'token_str': 'hard'}]
<add>
<add>```
<add>
<add>Here is how to use this model to get the features of a given text in PyTorch:
<add>```python
<add>from transformers import BertTokenizer, BertModel
<add>tokenizer = BertTokenizer.from_pretrained('zanelim/singbert')
<add>model = BertModel.from_pretrained("zanelim/singbert")
<add>text = "Replace me by any text you'd like."
<add>encoded_input = tokenizer(text, return_tensors='pt')
<add>output = model(**encoded_input)
<add>```
<add>
<add>and in TensorFlow:
<add>```python
<add>from transformers import BertTokenizer, TFBertModel
<add>tokenizer = BertTokenizer.from_pretrained("zanelim/singbert")
<add>model = TFBertModel.from_pretrained("zanelim/singbert")
<add>text = "Replace me by any text you'd like."
<add>encoded_input = tokenizer(text, return_tensors='tf')
<add>output = model(encoded_input)
<add>```
<add>
<add>#### Limitations and bias
<add>This model was finetuned on colloquial Singlish and Manglish corpus, hence it is best applied on downstream tasks involving the main
<add>constituent languages- english, mandarin, malay. Also, as the training data is mainly from forums, beware of existing inherent bias.
<add>
<add>## Training data
<add>Colloquial singlish and manglish (both are a mixture of English, Mandarin, Tamil, Malay, and other local dialects like Hokkien, Cantonese or Teochew)
<add>corpus. The corpus is collected from subreddits- `r/singapore` and `r/malaysia`, and forums such as `hardwarezone`.
<add>
<add>## Training procedure
<add>
<add>Initialized with [bert base uncased](https://github.com/google-research/bert#pre-trained-models) vocab and checkpoints (pre-trained weights).
<add>Top 1000 custom vocab tokens (non-overlapped with original bert vocab) were further extracted from training data and filled into unused tokens in original bert vocab.
<add>
<add>Pre-training was further finetuned on training data with the following hyperparameters
<add>* train_batch_size: 512
<add>* max_seq_length: 128
<add>* num_train_steps: 300000
<add>* num_warmup_steps: 5000
<add>* learning_rate: 2e-5
<add>* hardware: TPU v3-8 | 1 |
Python | Python | set version to v2.2.4 | 26a90f011b8c21dfc06940579479aaff8006ff74 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "2.2.4.dev0"
<add>__version__ = "2.2.4"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Python | Python | add python 3.6 support to suppress_warnings | 6b49167c3134e695efb1a122f73c3524a9049db5 | <ide><path>numpy/testing/utils.py
<ide> def __init__(self, forwarding_rule="always"):
<ide> self._forwarding_rule = forwarding_rule
<ide>
<ide> def _clear_registries(self):
<add> if hasattr(warnings, "_filters_mutated"):
<add> # clearing the registry should not be necessary on new pythons,
<add> # instead the filters should be mutated.
<add> warnings._filters_mutated()
<add> return
<ide> # Simply clear the registry, this should normally be harmless,
<ide> # note that on new pythons it would be invalidated anyway.
<ide> for module in self._tmp_modules:
<ide> def __enter__(self):
<ide> raise RuntimeError("cannot enter suppress_warnings twice.")
<ide>
<ide> self._orig_show = warnings.showwarning
<add> if hasattr(warnings, "_showwarnmsg"):
<add> self._orig_showmsg = warnings._showwarnmsg
<ide> self._filters = warnings.filters
<ide> warnings.filters = self._filters[:]
<ide>
<ide> def __enter__(self):
<ide> module=module_regex)
<ide> self._tmp_modules.add(mod)
<ide> warnings.showwarning = self._showwarning
<add> if hasattr(warnings, "_showwarnmsg"):
<add> warnings._showwarnmsg = self._showwarnmsg
<ide> self._clear_registries()
<ide>
<ide> return self
<ide>
<ide> def __exit__(self, *exc_info):
<ide> warnings.showwarning = self._orig_show
<add> if hasattr(warnings, "_showwarnmsg"):
<add> warnings._showwarnmsg = self._orig_showmsg
<ide> warnings.filters = self._filters
<ide> self._clear_registries()
<ide> self._entered = False
<ide> del self._orig_show
<ide> del self._filters
<ide>
<add> def _showwarnmsg(self, msg):
<add> self._showwarning(msg.message, msg.category, msg.filename, msg.lineno,
<add> msg.file, msg.line, use_warnmsg=msg)
<add>
<ide> def _showwarning(self, message, category, filename, lineno,
<ide> *args, **kwargs):
<add> use_warnmsg = kwargs.pop("use_warnmsg", None)
<ide> for cat, _, pattern, mod, rec in (
<ide> self._suppressions + self._tmp_suppressions)[::-1]:
<ide> if (issubclass(category, cat) and
<ide> def _showwarning(self, message, category, filename, lineno,
<ide> # There is no filter in place, so pass to the outside handler
<ide> # unless we should only pass it once
<ide> if self._forwarding_rule == "always":
<del> self._orig_show(message, category, filename, lineno,
<del> *args, **kwargs)
<add> if use_warnmsg is None:
<add> self._orig_show(message, category, filename, lineno,
<add> *args, **kwargs)
<add> else:
<add> self._orig_showmsg(use_warnmsg)
<ide> return
<ide>
<ide> if self._forwarding_rule == "once":
<ide> def _showwarning(self, message, category, filename, lineno,
<ide> if signature in self._forwarded:
<ide> return
<ide> self._forwarded.add(signature)
<del> self._orig_show(message, category, filename, lineno, *args, **kwargs)
<add> if use_warnmsg is None:
<add> self._orig_show(message, category, filename, lineno, *args,
<add> **kwargs)
<add> else:
<add> self._orig_showmsg(use_warnmsg)
<ide>
<ide> def __call__(self, func):
<ide> """ | 1 |
Go | Go | ignore lchown error on docker cp | 9e51b7abaea3fb30dc994a1d004cd79f2e100c1a | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdCp(args ...string) error {
<ide> }
<ide>
<ide> if statusCode == 200 {
<del> if err := archive.Untar(stream, copyData.Get("HostPath"), nil); err != nil {
<add> if err := archive.Untar(stream, copyData.Get("HostPath"), &archive.TarOptions{NoLchown: true}); err != nil {
<ide> return err
<ide> }
<ide> }
<ide><path>archive/archive.go
<ide> type (
<ide> TarOptions struct {
<ide> Includes []string
<ide> Compression Compression
<add> NoLchown bool
<ide> }
<ide> )
<ide>
<ide> func addTarFile(path, name string, tw *tar.Writer) error {
<ide> return nil
<ide> }
<ide>
<del>func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader) error {
<add>func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool) error {
<ide> // hdr.Mode is in linux format, which we can use for sycalls,
<ide> // but for os.Foo() calls we need the mode converted to os.FileMode,
<ide> // so use hdrInfo.Mode() (they differ for e.g. setuid bits)
<ide> func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader) e
<ide> return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag)
<ide> }
<ide>
<del> if err := os.Lchown(path, hdr.Uid, hdr.Gid); err != nil {
<add> if err := os.Lchown(path, hdr.Uid, hdr.Gid); err != nil && Lchown {
<ide> return err
<ide> }
<ide>
<ide> func Untar(archive io.Reader, dest string, options *TarOptions) error {
<ide> }
<ide> }
<ide> }
<del>
<del> if err := createTarFile(path, dest, hdr, tr); err != nil {
<add> if err := createTarFile(path, dest, hdr, tr, options == nil || !options.NoLchown); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>archive/archive_test.go
<ide> package archive
<ide> import (
<ide> "bytes"
<ide> "fmt"
<del> "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> "io"
<ide> "io/ioutil"
<ide> "os"
<ide> "os/exec"
<ide> "path"
<ide> "testing"
<ide> "time"
<add>
<add> "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> )
<ide>
<ide> func TestCmdStreamLargeStderr(t *testing.T) {
<ide> func TestTarUntar(t *testing.T) {
<ide> // Failing prevents the archives from being uncompressed during ADD
<ide> func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) {
<ide> hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader}
<del> err := createTarFile("pax_global_header", "some_dir", &hdr, nil)
<add> err := createTarFile("pax_global_header", "some_dir", &hdr, nil, true)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide><path>archive/diff.go
<ide> package archive
<ide>
<ide> import (
<ide> "fmt"
<del> "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> "io"
<ide> "io/ioutil"
<ide> "os"
<ide> "path/filepath"
<ide> "strings"
<ide> "syscall"
<add>
<add> "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> )
<ide>
<ide> // Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes.
<ide> func ApplyLayer(dest string, layer ArchiveReader) error {
<ide> }
<ide> defer os.RemoveAll(aufsTempdir)
<ide> }
<del> if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr); err != nil {
<add> if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func ApplyLayer(dest string, layer ArchiveReader) error {
<ide> srcData = tmpFile
<ide> }
<ide>
<del> if err := createTarFile(path, dest, srcHdr, srcData); err != nil {
<add> if err := createTarFile(path, dest, srcHdr, srcData, true); err != nil {
<ide> return err
<ide> }
<ide> | 4 |
Javascript | Javascript | use native for loop instead of foreach for arrays | 36625de0d3ebc1fc091af474d942c6ce16b0a1c0 | <ide><path>src/Angular.js
<ide> function forEach(obj, iterator, context) {
<ide> iterator.call(context, obj[key], key);
<ide> }
<ide> }
<del> } else if (obj.forEach && obj.forEach !== forEach) {
<del> obj.forEach(iterator, context);
<del> } else if (isArrayLike(obj)) {
<add> } else if (isArray(obj) || isArrayLike(obj)) {
<ide> for (key = 0, length = obj.length; key < length; key++) {
<ide> iterator.call(context, obj[key], key);
<ide> }
<add> } else if (obj.forEach && obj.forEach !== forEach) {
<add> obj.forEach(iterator, context);
<ide> } else {
<ide> for (key in obj) {
<ide> if (obj.hasOwnProperty(key)) { | 1 |
Javascript | Javascript | avoid json.stringify for better performance | 0fd50ddd849a262a39316e9ba24effe118c44290 | <ide><path>lib/cache/ResolverCachePlugin.js
<ide> const asyncLib = require("neo-async");
<ide>
<ide> const INVALID = {};
<ide>
<add>const requestToString = request => {
<add> let str = "";
<add> for (const key in request) {
<add> const value = request[key];
<add> if (typeof value === "object" && value !== null) {
<add> str += `/${key}={${requestToString(value)}}`;
<add> } else {
<add> str += `/${key}=${value}`;
<add> }
<add> }
<add> return str;
<add>};
<add>
<ide> class ResolverCachePlugin {
<ide> /**
<ide> * @param {Compiler} compiler Webpack compiler
<ide> class ResolverCachePlugin {
<ide> if (request._ResolverCachePluginCacheMiss || !fileSystemInfo) {
<ide> return callback();
<ide> }
<del> const identifier = `/resolve/${type}/${JSON.stringify(
<add> const identifier = `/resolve/${type}${requestToString(
<ide> request
<ide> )}`;
<ide> cache.get(identifier, null, (err, cacheEntry) => { | 1 |
Ruby | Ruby | use directory? to check rack existence | 1ae44d44299803ec0da62731ac7b808d1d32f5aa | <ide><path>Library/Homebrew/cmd/install.rb
<ide> def install
<ide> msg = "#{f.full_name}-#{f.installed_version} already installed"
<ide> msg << ", it's just not linked" unless f.linked_keg.symlink? || f.keg_only?
<ide> opoo msg
<del> elsif f.oldname && (dir = HOMEBREW_CELLAR/f.oldname).exist? && !dir.subdirs.empty? \
<add> elsif f.oldname && (dir = HOMEBREW_CELLAR/f.oldname).directory? && !dir.subdirs.empty? \
<ide> && f.tap == Tab.for_keg(dir.subdirs.first).tap && !ARGV.force?
<ide> # Check if the formula we try to install is the same as installed
<ide> # but not migrated one. If --force passed then install anyway.
<ide><path>Library/Homebrew/cmd/outdated.rb
<ide> def outdated_brews(formulae)
<ide> all_versions = []
<ide> older_or_same_tap_versions = []
<ide>
<del> if f.oldname && !f.rack.exist? && (dir = HOMEBREW_CELLAR/f.oldname).exist?
<del> if f.tap == Tab.for_keg(dir.subdirs.first).tap
<del> raise Migrator::MigrationNeededError.new(f)
<del> end
<add> if f.oldname && !f.rack.exist? && (dir = HOMEBREW_CELLAR/f.oldname).directory? &&
<add> !dir.subdirs.empty? && f.tap == Tab.for_keg(dir.subdirs.first).tap
<add> raise Migrator::MigrationNeededError.new(f)
<ide> end
<ide>
<ide> f.rack.subdirs.each do |keg_dir| | 2 |
Python | Python | fix cloudstack tests | d8da3fe6838582e3c639a23b0785a59a6a3f35e9 | <ide><path>libcloud/test/compute/test_cloudstack.py
<ide> def test_list_images_no_images_available(self):
<ide> self.assertEqual(0, len(images))
<ide>
<ide> def test_list_images(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'listTemplates_default.json')
<ide> templates = fixture['listtemplatesresponse']['template']
<ide>
<ide> def test_ex_list_disk_offerings(self):
<ide> self.assertEqual(10, diskOffering.size)
<ide>
<ide> def test_ex_list_networks(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'listNetworks_default.json')
<ide> fixture_networks = fixture['listnetworksresponse']['network']
<ide>
<ide> def test_ex_list_networks(self):
<ide> self.assertEqual(network.zoneid, fixture_networks[i]['zoneid'])
<ide>
<ide> def test_ex_list_network_offerings(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'listNetworkOfferings_default.json')
<ide> fixture_networkoffers = \
<ide> fixture['listnetworkofferingsresponse']['networkoffering']
<ide> def test_ex_list_network_offerings(self):
<ide> fixture_networkoffers[i]['serviceofferingid'])
<ide>
<ide> def test_ex_create_network(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'createNetwork_default.json')
<ide>
<ide> fixture_network = fixture['createnetworkresponse']['network']
<ide> def test_ex_delete_network(self):
<ide> self.assertTrue(result)
<ide>
<ide> def test_ex_list_nics(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'listNics_default.json')
<ide>
<ide> fixture_nic = fixture['listnicsresponse']['nic']
<ide> def test_ex_remove_nic_from_node(self):
<ide> self.assertTrue(result)
<ide>
<ide> def test_ex_list_vpc_offerings(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'listVPCOfferings_default.json')
<ide> fixture_vpcoffers = \
<ide> fixture['listvpcofferingsresponse']['vpcoffering']
<ide> def test_ex_list_vpc_offerings(self):
<ide> fixture_vpcoffers[i]['displaytext'])
<ide>
<ide> def test_ex_list_vpcs(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'listVPCs_default.json')
<ide> fixture_vpcs = fixture['listvpcsresponse']['vpc']
<ide>
<ide> def test_ex_list_vpcs(self):
<ide> self.assertEqual(vpc.zone_id, fixture_vpcs[i]['zoneid'])
<ide>
<ide> def test_ex_list_routers(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'listRouters_default.json')
<ide> fixture_routers = fixture['listroutersresponse']['router']
<ide>
<ide> def test_ex_list_routers(self):
<ide> self.assertEqual(router.vpc_id, fixture_routers[i]['vpcid'])
<ide>
<ide> def test_ex_create_vpc(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'createVPC_default.json')
<ide>
<ide> fixture_vpc = fixture['createvpcresponse']
<ide> def test_ex_delete_vpc(self):
<ide> self.assertTrue(result)
<ide>
<ide> def test_ex_create_network_acllist(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'createNetworkACLList_default.json')
<ide>
<ide> fixture_network_acllist = fixture['createnetworkacllistresponse']
<ide> def test_ex_create_network_acllist(self):
<ide> self.assertEqual(network_acllist.id, fixture_network_acllist['id'])
<ide>
<ide> def test_ex_list_network_acllist(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'listNetworkACLLists_default.json')
<ide> fixture_acllist = \
<ide> fixture['listnetworkacllistsresponse']['networkacllist']
<ide> def test_ex_list_network_acllist(self):
<ide> fixture_acllist[i]['description'])
<ide>
<ide> def test_ex_create_network_acl(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'createNetworkACL_default.json')
<ide>
<ide> fixture_network_acllist = fixture['createnetworkaclresponse']
<ide> def test_ex_create_network_acl(self):
<ide> self.assertEqual(network_acl.id, fixture_network_acllist['id'])
<ide>
<ide> def test_ex_list_projects(self):
<del> _, fixture = CloudStackMockHttp()._load_fixture(
<add> _, fixture = self.driver.connection.connection._load_fixture(
<ide> 'listProjects_default.json')
<ide> fixture_projects = fixture['listprojectsresponse']['project']
<ide>
<ide> def list_nodes_mock(self, **kwargs):
<ide> self.assertEqual('1', kwargs.get('zoneid'))
<ide>
<ide> body, obj = self._load_fixture('listVirtualMachines_default.json')
<del> return (httplib.OK, body, obj, httplib.responses[httplib.OK])
<add> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<ide> CloudStackMockHttp._cmd_listVirtualMachines = list_nodes_mock
<ide> try: | 1 |
Text | Text | clarify note in spanish | 6953662931cad5287ef59d3e57b420d1d8bf6bdc | <ide><path>guide/spanish/java/arrays/index.md
<ide> dataType[] arrayName = {value_0, value_1, ..., value_k};
<ide> ```java
<ide> double[] list = {1, 2, 3, 4};
<ide>
<del> The code above is equivalent to:
<add> El fragmento de código arriba es equivalente a:
<ide> double[] list = new double[4];
<del> *IMPORTANT NOTE: Please note the difference between the types of brackets
<del> that are used to represent arrays in two different ways.
<add> *NOTA IMPORTANTE: Por favor notar la diferencia entre los
<add> tipos de paréntesis que son usandos para representar arrays
<add> de dos diferentes maneras.
<ide> ```
<ide>
<ide> ## Accediendo a Arrays:
<ide> Salida:
<ide>
<ide> #### Más información:
<ide>
<del>* Fuente: [Java Arrays](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
<ide>\ No newline at end of file
<add>* Fuente: [Java Arrays](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) | 1 |
Ruby | Ruby | add test case for `preventing_writes?` | 3d5db4920a3d5fb0bdd4a912fd5e29eec12ef02e | <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def preventing_writes?
<ide> replica? || prevent_writes
<ide> end
<ide>
<del> # Prevent writing to the database regardless of role.
<add> # Prevent writing to the database regardless of role.
<ide> #
<ide> # In some cases you may want to prevent writes to the database
<ide> # even if you are on a database that can write. `while_preventing_writes`
<ide><path>activerecord/test/cases/adapter_test.rb
<ide> class << @connection
<ide> end
<ide> end
<ide>
<add> def test_preventing_writes_predicate
<add> assert_not_predicate @connection, :preventing_writes?
<add>
<add> @connection.while_preventing_writes do
<add> assert_predicate @connection, :preventing_writes?
<add> end
<add>
<add> assert_not_predicate @connection, :preventing_writes?
<add> end
<add>
<ide> def test_errors_when_an_insert_query_is_called_while_preventing_writes
<ide> assert_no_queries do
<ide> assert_raises(ActiveRecord::ReadOnlyError) do | 2 |
Ruby | Ruby | stop the recursive insanity | 0fbf829b1e147c6c0f6c9d5e447bad0e9216b7b1 | <ide><path>activerecord/lib/active_record/relation.rb
<ide> def update_all(updates, conditions = nil, options = {})
<ide> if conditions || options.present?
<ide> where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
<ide> else
<add> limit = nil
<add> order = []
<ide> # Apply limit and order only if they're both present
<ide> if @limit_value.present? == @order_values.present?
<del> stmt = arel.compile_update(Arel::SqlLiteral.new(@klass.send(:sanitize_sql_for_assignment, updates)))
<del> stmt.key = @klass.arel_table[@klass.primary_key]
<del> @klass.connection.update stmt.to_sql
<del> else
<del> except(:limit, :order).update_all(updates)
<add> limit = arel.limit
<add> order = arel.orders
<ide> end
<add>
<add> stmt = arel.compile_update(Arel::SqlLiteral.new(@klass.send(:sanitize_sql_for_assignment, updates)))
<add> stmt.take limit
<add> stmt.order(*order)
<add> stmt.key = @klass.arel_table[@klass.primary_key]
<add> @klass.connection.update stmt.to_sql
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | add host argument for packager | d4f6e447d2019ba784a83149a22bc6f392accee5 | <ide><path>local-cli/server/runServer.js
<ide> function runServer(args, config, readyCallback) {
<ide>
<ide> const serverInstance = http.createServer(app).listen(
<ide> args.port,
<del> '::',
<add> args.host,
<ide> function() {
<ide> attachHMRServer({
<ide> httpServer: serverInstance,
<ide><path>local-cli/server/server.js
<ide> function _server(argv, config, resolve, reject) {
<ide> command: 'port',
<ide> default: 8081,
<ide> type: 'string',
<add> }, {
<add> command: 'host',
<add> default: '',
<add> type: 'string',
<ide> }, {
<ide> command: 'root',
<ide> type: 'string', | 2 |
Python | Python | adjust trimmed_pod_id and replace '.' with '-' | 563315857d1f54f0c56059ff38dc6aa9af4f08b7 | <ide><path>airflow/kubernetes/pod_generator.py
<ide> def make_unique_pod_id(pod_id: str) -> str:
<ide> return None
<ide>
<ide> safe_uuid = uuid.uuid4().hex # safe uuid will always be less than 63 chars
<del> # Strip trailing '-' and '.' as they can't be followed by '.'
<del> trimmed_pod_id = pod_id[:MAX_LABEL_LEN].rstrip('-.')
<ide>
<del> safe_pod_id = f"{trimmed_pod_id}.{safe_uuid}"
<del> return safe_pod_id
<add> # Get prefix length after subtracting the uuid length. Clean up '.' and '-' from
<add> # end of podID ('.' can't be followed by '-').
<add> label_prefix_length = MAX_LABEL_LEN - len(safe_uuid) - 1 # -1 for separator
<add> trimmed_pod_id = pod_id[:label_prefix_length].rstrip('-.')
<add>
<add> # previously used a '.' as the separator, but this could create errors in some situations
<add> return f"{trimmed_pod_id}-{safe_uuid}"
<ide>
<ide>
<ide> def merge_objects(base_obj, client_obj):
<ide><path>tests/kubernetes/models/test_secret.py
<ide> def test_attach_to_pod(self, mock_uuid):
<ide> 'kind': 'Pod',
<ide> 'metadata': {
<ide> 'labels': {'app': 'myapp'},
<del> 'name': 'myapp-pod.cf4a56d281014217b0272af6216feb48',
<add> 'name': 'myapp-pod-cf4a56d281014217b0272af6216feb48',
<ide> 'namespace': 'default',
<ide> },
<ide> 'spec': {
<ide><path>tests/kubernetes/test_pod_generator.py
<ide> def setup_method(self):
<ide> kind="Pod",
<ide> metadata=k8s.V1ObjectMeta(
<ide> namespace="default",
<del> name='myapp-pod.' + self.static_uuid.hex,
<add> name='myapp-pod-' + self.static_uuid.hex,
<ide> labels={'app': 'myapp'},
<ide> ),
<ide> spec=k8s.V1PodSpec(
<ide> def test_construct_pod(self, mock_uuid, config_image, expected_image):
<ide> expected.metadata.labels = self.labels
<ide> expected.metadata.labels['app'] = 'myapp'
<ide> expected.metadata.annotations = self.annotations
<del> expected.metadata.name = 'pod_id.' + self.static_uuid.hex
<add> expected.metadata.name = 'pod_id-' + self.static_uuid.hex
<ide> expected.metadata.namespace = 'test_namespace'
<ide> expected.spec.containers[0].args = ['command']
<ide> expected.spec.containers[0].image = expected_image
<ide> def test_construct_pod_empty_executor_config(self, mock_uuid):
<ide> worker_config.metadata.annotations = self.annotations
<ide> worker_config.metadata.labels = self.labels
<ide> worker_config.metadata.labels['app'] = 'myapp'
<del> worker_config.metadata.name = 'pod_id.' + self.static_uuid.hex
<add> worker_config.metadata.name = 'pod_id-' + self.static_uuid.hex
<ide> worker_config.metadata.namespace = 'namespace'
<ide> worker_config.spec.containers[0].env.append(
<ide> k8s.V1EnvVar(name="AIRFLOW_IS_K8S_EXECUTOR_POD", value='True')
<ide> def test_ensure_max_label_length(self, mock_uuid):
<ide> base_worker_pod=worker_config,
<ide> )
<ide>
<del> assert result.metadata.name == 'a' * 63 + '.' + self.static_uuid.hex
<add> assert result.metadata.name == 'a' * 30 + '-' + self.static_uuid.hex
<ide> for _, v in result.metadata.labels.items():
<ide> assert len(v) <= 63
<ide>
<ide> def test_deserialize_model_file(self):
<ide> def test_pod_name_confirm_to_max_length(self, _, pod_id):
<ide> name = PodGenerator.make_unique_pod_id(pod_id)
<ide> assert len(name) <= 253
<del> parts = name.split(".")
<del> if len(pod_id) <= 63:
<del> assert len(parts[0]) == len(pod_id)
<del> else:
<del> assert len(parts[0]) <= 63
<del> assert len(parts[1]) <= 63
<add> parts = name.split("-")
<add>
<add> # 63 is the MAX_LABEL_LEN in pod_generator.py
<add> # 33 is the length of uuid4 + 1 for the separating '-' (32 + 1)
<add> # 30 is the max length of the prefix
<add> # so 30 = 63 - (32 + 1)
<add> assert len(parts[0]) <= 30
<add> assert len(parts[1]) == 32
<ide>
<ide> @parameterized.expand(
<ide> (
<ide> def test_pod_name_is_valid(self, pod_id, expected_starts_with):
<ide> len(name) <= 253 and all(ch.lower() == ch for ch in name) and re.match(regex, name)
<ide> ), "pod_id is invalid - fails allowed regex check"
<ide>
<del> assert name.rsplit(".")[0] == expected_starts_with
<add> assert name.rsplit("-", 1)[0] == expected_starts_with
<ide>
<ide> def test_deserialize_model_string(self):
<ide> fixture = """ | 3 |
Javascript | Javascript | emit $includecontenterror when http request fails | e4419daf705d6d2d116ced573f72c24b5c53be1f | <ide><path>src/ng/directive/ngInclude.js
<ide> * @description
<ide> * Emitted every time the ngInclude content is reloaded.
<ide> */
<add>
<add>
<add>/**
<add> * @ngdoc event
<add> * @name ng.directive:ngInclude#$includeContentError
<add> * @eventOf ng.directive:ngInclude
<add> * @eventType emit on the scope ngInclude was declared in
<add> * @description
<add> * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299)
<add> */
<ide> var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
<ide> function($http, $templateCache, $anchorScroll, $animate, $sce) {
<ide> return {
<ide> var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate'
<ide> currentScope.$emit('$includeContentLoaded');
<ide> scope.$eval(onloadExp);
<ide> }).error(function() {
<del> if (thisChangeId === changeCounter) cleanupLastIncludeContent();
<add> if (thisChangeId === changeCounter) {
<add> cleanupLastIncludeContent();
<add> scope.$emit('$includeContentError');
<add> }
<ide> });
<ide> scope.$emit('$includeContentRequested');
<ide> } else {
<ide><path>test/ng/directive/ngIncludeSpec.js
<ide> describe('ngInclude', function() {
<ide> }));
<ide>
<ide>
<add> it('should fire $includeContentError event when content request fails', inject(
<add> function($rootScope, $compile, $httpBackend, $templateCache) {
<add> var contentLoadedSpy = jasmine.createSpy('content loaded'),
<add> contentErrorSpy = jasmine.createSpy('content error');
<add>
<add> $rootScope.$on('$includeContentLoaded', contentLoadedSpy);
<add> $rootScope.$on('$includeContentError', contentErrorSpy);
<add>
<add> $httpBackend.expect('GET', 'tpl.html').respond(400, 'nope');
<add>
<add> element = $compile('<div><div ng-include="template"></div></div>')($rootScope);
<add>
<add> $rootScope.$apply(function() {
<add> $rootScope.template = 'tpl.html';
<add> });
<add> $httpBackend.flush();
<add>
<add> expect(contentLoadedSpy).not.toHaveBeenCalled();
<add> expect(contentErrorSpy).toHaveBeenCalledOnce();
<add> expect(element.children('div').contents().length).toBe(0);
<add> }));
<add>
<add>
<ide> it('should evaluate onload expression when a partial is loaded', inject(
<ide> putIntoCache('myUrl', 'my partial'),
<ide> function($rootScope, $compile) { | 2 |
Go | Go | remove unused functions, variables, fields | 744f1c261c57ed68e3bc8d05f4ab58223be24009 | <ide><path>distribution/pull_v2_test.go
<ide> func TestValidateManifest(t *testing.T) {
<ide> t.Fatal("error unmarshaling manifest:", err)
<ide> }
<ide>
<del> verifiedManifest, err = verifySchema1Manifest(&badSignedManifest, expectedDigest)
<add> _, err = verifySchema1Manifest(&badSignedManifest, expectedDigest)
<ide> if err == nil || !strings.HasPrefix(err.Error(), "image verification failed for digest") {
<ide> t.Fatal("expected validateManifest to fail with digest error")
<ide> }
<ide><path>layer/layer_test.go
<ide> func getCachedLayer(l Layer) *roLayer {
<ide> return l.(*roLayer)
<ide> }
<ide>
<del>func getMountLayer(l RWLayer) *mountedLayer {
<del> return l.(*referencedRWLayer).mountedLayer
<del>}
<del>
<ide> func createMetadata(layers ...Layer) []Metadata {
<ide> metadata := make([]Metadata, len(layers))
<ide> for i := range layers {
<ide><path>layer/mounted_layer.go
<ide> type mountedLayer struct {
<ide> mountID string
<ide> initID string
<ide> parent *roLayer
<del> path string
<ide> layerStore *layerStore
<ide>
<ide> sync.Mutex
<ide><path>opts/env_test.go
<ide> func TestValidateEnv(t *testing.T) {
<ide> }{
<ide> value: "PaTh",
<ide> expected: fmt.Sprintf("PaTh=%v", os.Getenv("PATH")),
<add> err: nil,
<ide> }
<ide> testcase = append(testcase, tmp)
<del>
<ide> }
<ide>
<ide> for _, r := range testcase {
<ide><path>pkg/mount/mount_unix_test.go
<ide> func TestMountReadonly(t *testing.T) {
<ide> }
<ide> }()
<ide>
<del> f, err = os.OpenFile(targetPath, os.O_RDWR, 0777)
<add> _, err = os.OpenFile(targetPath, os.O_RDWR, 0777)
<ide> if err == nil {
<ide> t.Fatal("Should not be able to open a ro file as rw")
<ide> }
<ide><path>pkg/tailfile/tailfile.go
<ide> type scanner struct {
<ide> delim []byte
<ide> err error
<ide> idx int
<del> done bool
<ide> }
<ide>
<ide> func (s *scanner) Start(ctx context.Context) int64 {
<ide><path>reference/store_test.go
<ide> func TestAddDeleteGet(t *testing.T) {
<ide> t.Fatalf("error creating temp file: %v", err)
<ide> }
<ide> _, err = jsonFile.Write([]byte(`{}`))
<del> jsonFile.Close()
<del> defer os.RemoveAll(jsonFile.Name())
<add> assert.NilError(t, err)
<add> _ = jsonFile.Close()
<add> defer func() { _ = os.RemoveAll(jsonFile.Name()) }()
<ide>
<ide> store, err := NewReferenceStore(jsonFile.Name())
<ide> if err != nil {
<ide><path>volume/service/service_test.go
<ide> func TestServiceGet(t *testing.T) {
<ide> assert.NilError(t, err)
<ide> assert.Assert(t, is.Len(v.Status, 1), v.Status)
<ide>
<del> v, err = service.Get(ctx, "test", opts.WithGetDriver("notarealdriver"))
<add> _, err = service.Get(ctx, "test", opts.WithGetDriver("notarealdriver"))
<ide> assert.Assert(t, errdefs.IsConflict(err), err)
<ide> v, err = service.Get(ctx, "test", opts.WithGetDriver("d1"))
<ide> assert.Assert(t, err == nil)
<ide> assert.Assert(t, is.DeepEqual(created, v))
<ide>
<ide> assert.Assert(t, ds.Register(testutils.NewFakeDriver("d2"), "d2"))
<del> v, err = service.Get(ctx, "test", opts.WithGetDriver("d2"))
<add> _, err = service.Get(ctx, "test", opts.WithGetDriver("d2"))
<ide> assert.Assert(t, errdefs.IsConflict(err), err)
<ide> }
<ide> | 8 |
Go | Go | ignore sigurg on linux | b7ebf32ba3f0342343558431df976d4ccb8039ba | <ide><path>pkg/signal/signal.go
<ide> import (
<ide> )
<ide>
<ide> // CatchAll catches all signals and relays them to the specified channel.
<add>// On Linux, SIGURG is not handled, as it's used by the Go runtime to support
<add>// preemptable system calls.
<ide> func CatchAll(sigc chan os.Signal) {
<ide> var handledSigs []os.Signal
<ide> for _, s := range SignalMap {
<add> if isRuntimeSig(s) {
<add> // Do not handle SIGURG on Linux, as in go1.14+, the go runtime issues
<add> // SIGURG as an interrupt to support preemptable system calls on Linux.
<add> continue
<add> }
<ide> handledSigs = append(handledSigs, s)
<ide> }
<ide> signal.Notify(sigc, handledSigs...)
<ide><path>pkg/signal/signal_darwin.go
<ide> package signal // import "github.com/docker/docker/pkg/signal"
<ide>
<ide> import (
<add> "os"
<ide> "syscall"
<ide> )
<ide>
<ide> var SignalMap = map[string]syscall.Signal{
<ide> "XCPU": syscall.SIGXCPU,
<ide> "XFSZ": syscall.SIGXFSZ,
<ide> }
<add>
<add>func isRuntimeSig(_ os.Signal) bool {
<add> return false
<add>}
<ide><path>pkg/signal/signal_freebsd.go
<ide> package signal // import "github.com/docker/docker/pkg/signal"
<ide>
<ide> import (
<add> "os"
<ide> "syscall"
<ide> )
<ide>
<ide> var SignalMap = map[string]syscall.Signal{
<ide> "XCPU": syscall.SIGXCPU,
<ide> "XFSZ": syscall.SIGXFSZ,
<ide> }
<add>
<add>func isRuntimeSig(_ os.Signal) bool {
<add> return false
<add>}
<ide><path>pkg/signal/signal_linux.go
<ide> package signal // import "github.com/docker/docker/pkg/signal"
<ide>
<ide> import (
<add> "os"
<ide> "syscall"
<ide>
<ide> "golang.org/x/sys/unix"
<ide> var SignalMap = map[string]syscall.Signal{
<ide> "RTMAX-1": sigrtmax - 1,
<ide> "RTMAX": sigrtmax,
<ide> }
<add>
<add>func isRuntimeSig(s os.Signal) bool {
<add> return s == unix.SIGURG
<add>}
<ide><path>pkg/signal/signal_linux_mipsx.go
<ide> package signal // import "github.com/docker/docker/pkg/signal"
<ide>
<ide> import (
<add> "os"
<ide> "syscall"
<ide>
<ide> "golang.org/x/sys/unix"
<ide> var SignalMap = map[string]syscall.Signal{
<ide> "RTMAX-1": sigrtmax - 1,
<ide> "RTMAX": sigrtmax,
<ide> }
<add>
<add>func isRuntimeSig(s os.Signal) bool {
<add> return s == unix.SIGURG
<add>}
<ide><path>pkg/signal/signal_linux_test.go
<ide> import (
<ide> "os"
<ide> "syscall"
<ide> "testing"
<add> "time"
<ide>
<ide> "gotest.tools/v3/assert"
<ide> is "gotest.tools/v3/assert/cmp"
<ide> func TestCatchAll(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func TestCatchAllIgnoreSigUrg(t *testing.T) {
<add> sigs := make(chan os.Signal, 1)
<add> CatchAll(sigs)
<add> defer StopCatch(sigs)
<add>
<add> err := syscall.Kill(syscall.Getpid(), syscall.SIGURG)
<add> assert.NilError(t, err)
<add> timer := time.NewTimer(1 * time.Second)
<add> defer timer.Stop()
<add> select {
<add> case <-timer.C:
<add> case s := <-sigs:
<add> t.Fatalf("expected no signals to be handled, but received %q", s.String())
<add> }
<add>}
<add>
<ide> func TestStopCatch(t *testing.T) {
<ide> signal := SignalMap["HUP"]
<ide> channel := make(chan os.Signal, 1)
<ide><path>pkg/signal/signal_windows.go
<ide> package signal // import "github.com/docker/docker/pkg/signal"
<ide>
<ide> import (
<add> "os"
<ide> "syscall"
<ide> )
<ide>
<ide> var SignalMap = map[string]syscall.Signal{
<ide> "KILL": syscall.SIGKILL,
<ide> "TERM": syscall.SIGTERM,
<ide> }
<add>
<add>func isRuntimeSig(_ os.Signal) bool {
<add> return false
<add>} | 7 |
Mixed | Ruby | add date and time `#yesterday?` and `#tomorrow?` | 5df9b4584cd6fb653d169ec9a1671532799bdf95 | <ide><path>activesupport/CHANGELOG.md
<add>* Add Date and Time `#yesterday?` and `#tomorrow?` alongside `#today?`.
<add>
<add> Aliased to `#prev_day?` and `#next_day?` to match the existing `#prev/next_day` methods.
<add>
<add> *Jatin Dhankhar*
<add>
<ide> * Add `Enumerable#pick` to complement `ActiveRecord::Relation#pick`.
<ide>
<ide> *Eugene Kenny*
<ide><path>activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
<ide> def today?
<ide> to_date == ::Date.current
<ide> end
<ide>
<add> # Returns true if the date/time is tomorrow.
<add> def tomorrow?
<add> to_date == ::Date.current.tomorrow
<add> end
<add> alias :next_day? :tomorrow?
<add>
<add> # Returns true if the date/time is yesterday.
<add> def yesterday?
<add> to_date == ::Date.current.yesterday
<add> end
<add> alias :prev_day? :yesterday?
<add>
<ide> # Returns true if the date/time is in the past.
<ide> def past?
<ide> self < self.class.current
<ide><path>activesupport/lib/active_support/time_with_zone.rb
<ide> def today?
<ide> time.today?
<ide> end
<ide>
<add> # Returns true if the current object's time falls within
<add> # the next day (tomorrow).
<add> def tomorrow?
<add> time.tomorrow?
<add> end
<add> alias :next_day? :tomorrow?
<add>
<add> # Returns true if the current object's time falls within
<add> # the previous day (yesterday).
<add> def yesterday?
<add> time.yesterday?
<add> end
<add> alias :prev_day? :yesterday?
<add>
<ide> # Returns true if the current object's time is in the future.
<ide> def future?
<ide> utc.future?
<ide><path>activesupport/test/core_ext/date_time_ext_test.rb
<ide> def test_today_without_offset
<ide> end
<ide> end
<ide>
<add> def test_yesterday_with_offset
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, DateTime.civil(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)).yesterday?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-18000, 86400)).yesterday?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 23, 59, 59, Rational(-18000, 86400)).yesterday?
<add> assert_equal true, DateTime.civil(1999, 12, 31, 0, 0, 0, Rational(-18000, 86400)).yesterday?
<add> end
<add> end
<add>
<add> def test_yesterday_without_offset
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, DateTime.civil(1999, 12, 31, 23, 59, 59).yesterday?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 0).yesterday?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 23, 59, 59).yesterday?
<add> assert_equal false, DateTime.civil(2000, 1, 2, 0).yesterday?
<add> end
<add> end
<add>
<add> def test_prev_day_with_offset
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, DateTime.civil(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)).prev_day?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-18000, 86400)).prev_day?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 23, 59, 59, Rational(-18000, 86400)).prev_day?
<add> assert_equal true, DateTime.civil(1999, 12, 31, 0, 0, 0, Rational(-18000, 86400)).prev_day?
<add> end
<add> end
<add>
<add> def test_prev_day_without_offset
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, DateTime.civil(1999, 12, 31, 23, 59, 59).prev_day?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 0).prev_day?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 23, 59, 59).prev_day?
<add> assert_equal false, DateTime.civil(2000, 1, 2, 0).prev_day?
<add> end
<add> end
<add>
<add> def test_tomorrow_with_offset
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, DateTime.civil(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)).tomorrow?
<add> assert_equal true, DateTime.civil(2000, 1, 2, 0, 0, 0, Rational(-18000, 86400)).tomorrow?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 23, 59, 59, Rational(-18000, 86400)).tomorrow?
<add> assert_equal true, DateTime.civil(2000, 1, 2, 23, 59, 59, Rational(-18000, 86400)).tomorrow?
<add> end
<add> end
<add>
<add> def test_tomorrow_without_offset
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, DateTime.civil(1999, 12, 31, 23, 59, 59).tomorrow?
<add> assert_equal true, DateTime.civil(2000, 1, 2, 0).tomorrow?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 23, 59, 59).tomorrow?
<add> assert_equal false, DateTime.civil(2000, 1, 3, 0).tomorrow?
<add> end
<add> end
<add>
<add> def test_next_day_with_offset
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, DateTime.civil(1999, 12, 31, 23, 59, 59, Rational(-18000, 86400)).next_day?
<add> assert_equal true, DateTime.civil(2000, 1, 2, 0, 0, 0, Rational(-18000, 86400)).next_day?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 23, 59, 59, Rational(-18000, 86400)).next_day?
<add> assert_equal true, DateTime.civil(2000, 1, 2, 23, 59, 59, Rational(-18000, 86400)).next_day?
<add> end
<add> end
<add>
<add> def test_next_day_without_offset
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, DateTime.civil(1999, 12, 31, 23, 59, 59).next_day?
<add> assert_equal true, DateTime.civil(2000, 1, 2, 0).next_day?
<add> assert_equal false, DateTime.civil(2000, 1, 1, 23, 59, 59).next_day?
<add> assert_equal false, DateTime.civil(2000, 1, 3, 0).next_day?
<add> end
<add> end
<add>
<ide> def test_past_with_offset
<ide> DateTime.stub(:current, DateTime.civil(2005, 2, 10, 15, 30, 45, Rational(-18000, 86400))) do
<del> assert_equal true, DateTime.civil(2005, 2, 10, 15, 30, 44, Rational(-18000, 86400)).past?
<add> assert_equal true, DateTime.civil(2005, 2, 10, 15, 30, 44, Rational(-18000, 86400)).past?
<ide> assert_equal false, DateTime.civil(2005, 2, 10, 15, 30, 45, Rational(-18000, 86400)).past?
<ide> assert_equal false, DateTime.civil(2005, 2, 10, 15, 30, 46, Rational(-18000, 86400)).past?
<ide> end
<ide><path>activesupport/test/core_ext/time_ext_test.rb
<ide> def test_today_with_time_utc
<ide> end
<ide> end
<ide>
<add> def test_yesterday_with_time_local
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, Time.local(1999, 12, 31, 23, 59, 59).yesterday?
<add> assert_equal false, Time.local(2000, 1, 1, 0).yesterday?
<add> assert_equal true, Time.local(1999, 12, 31).yesterday?
<add> assert_equal false, Time.local(2000, 1, 2, 0).yesterday?
<add> end
<add> end
<add>
<add> def test_yesterday_with_time_utc
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, Time.utc(1999, 12, 31, 23, 59, 59).yesterday?
<add> assert_equal false, Time.utc(2000, 1, 1, 0).yesterday?
<add> assert_equal true, Time.utc(1999, 12, 31).yesterday?
<add> assert_equal false, Time.utc(2000, 1, 2, 0).yesterday?
<add> end
<add> end
<add>
<add> def test_prev_day_with_time_local
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, Time.local(1999, 12, 31, 23, 59, 59).prev_day?
<add> assert_equal false, Time.local(2000, 1, 1, 0).prev_day?
<add> assert_equal true, Time.local(1999, 12, 31).prev_day?
<add> assert_equal false, Time.local(2000, 1, 2, 0).prev_day?
<add> end
<add> end
<add>
<add> def test_prev_day_with_time_utc
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, Time.utc(1999, 12, 31, 23, 59, 59).prev_day?
<add> assert_equal false, Time.utc(2000, 1, 1, 0).prev_day?
<add> assert_equal true, Time.utc(1999, 12, 31).prev_day?
<add> assert_equal false, Time.utc(2000, 1, 2, 0).prev_day?
<add> end
<add> end
<add>
<add> def test_tomorrow_with_time_local
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, Time.local(1999, 12, 31, 23, 59, 59).tomorrow?
<add> assert_equal true, Time.local(2000, 1, 2, 0).tomorrow?
<add> assert_equal true, Time.local(2000, 1, 2, 23, 59, 59).tomorrow?
<add> assert_equal false, Time.local(2000, 1, 1, 0).tomorrow?
<add> end
<add> end
<add>
<add> def test_tomorrow_with_time_utc
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, Time.utc(1999, 12, 31, 23, 59, 59).tomorrow?
<add> assert_equal true, Time.utc(2000, 1, 2, 0).tomorrow?
<add> assert_equal true, Time.utc(2000, 1, 2, 23, 59, 59).tomorrow?
<add> assert_equal false, Time.utc(2000, 1, 1, 0).tomorrow?
<add> end
<add> end
<add>
<add> def test_next_day_with_time_local
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, Time.local(1999, 12, 31, 23, 59, 59).next_day?
<add> assert_equal true, Time.local(2000, 1, 2, 0).next_day?
<add> assert_equal true, Time.local(2000, 1, 2, 23, 59, 59).next_day?
<add> assert_equal false, Time.local(2000, 1, 1, 0).next_day?
<add> end
<add> end
<add>
<add> def test_next_day_with_time_utc
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, Time.utc(1999, 12, 31, 23, 59, 59).next_day?
<add> assert_equal true, Time.utc(2000, 1, 2, 0).next_day?
<add> assert_equal true, Time.utc(2000, 1, 2, 23, 59, 59).next_day?
<add> assert_equal false, Time.utc(2000, 1, 1, 0).next_day?
<add> end
<add> end
<add>
<ide> def test_past_with_time_current_as_time_local
<ide> with_env_tz "US/Eastern" do
<ide> Time.stub(:current, Time.local(2005, 2, 10, 15, 30, 45)) do
<ide><path>activesupport/test/core_ext/time_with_zone_test.rb
<ide> def test_today
<ide> end
<ide> end
<ide>
<add> def test_yesterday?
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 23, 59, 59)).yesterday?
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 1, 0)).yesterday?
<add> assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31)).yesterday?
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 2, 0)).yesterday?
<add> end
<add> end
<add>
<add> def test_prev_day?
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 23, 59, 59)).prev_day?
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 1, 0)).prev_day?
<add> assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31)).prev_day?
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 2, 0)).prev_day?
<add> end
<add> end
<add>
<add> def test_tomorrow?
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 23, 59, 59)).tomorrow?
<add> assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 2, 0)).tomorrow?
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 1, 23, 59, 59)).tomorrow?
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 0)).tomorrow?
<add> end
<add> end
<add>
<add> def test_next_day?
<add> Date.stub(:current, Date.new(2000, 1, 1)) do
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 23, 59, 59)).next_day?
<add> assert_equal true, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 2, 0)).next_day?
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(2000, 1, 1, 23, 59, 59)).next_day?
<add> assert_equal false, ActiveSupport::TimeWithZone.new(nil, @time_zone, Time.utc(1999, 12, 31, 0)).next_day?
<add> end
<add> end
<add>
<ide> def test_past_with_time_current_as_time_local
<ide> with_env_tz "US/Eastern" do
<ide> Time.stub(:current, Time.local(2005, 2, 10, 15, 30, 45)) do
<ide><path>guides/source/active_support_core_extensions.md
<ide> INFO: The following calculation methods have edge cases in October 1582, since d
<ide>
<ide> #### `Date.current`
<ide>
<del>Active Support defines `Date.current` to be today in the current time zone. That's like `Date.today`, except that it honors the user time zone, if defined. It also defines `Date.yesterday` and `Date.tomorrow`, and the instance predicates `past?`, `today?`, `future?`, `on_weekday?` and `on_weekend?`, all of them relative to `Date.current`.
<add>Active Support defines `Date.current` to be today in the current time zone. That's like `Date.today`, except that it honors the user time zone, if defined. It also defines `Date.yesterday` and `Date.tomorrow`, and the instance predicates `past?`, `today?`, `tomorrow?`, `next_day?`, `yesterday?`, `prev_day?`, `future?`, `on_weekday?` and `on_weekend?`, all of them relative to `Date.current`.
<ide>
<ide> When making Date comparisons using methods which honor the user time zone, make sure to use `Date.current` and not `Date.today`. There are cases where the user time zone might be in the future compared to the system time zone, which `Date.today` uses by default. This means `Date.today` may equal `Date.yesterday`.
<ide>
<ide> t.advance(seconds: 1)
<ide>
<ide> #### `Time.current`
<ide>
<del>Active Support defines `Time.current` to be today in the current time zone. That's like `Time.now`, except that it honors the user time zone, if defined. It also defines the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Time.current`.
<add>Active Support defines `Time.current` to be today in the current time zone. That's like `Time.now`, except that it honors the user time zone, if defined. It also defines the instance predicates `past?`, `today?`, `tomorrow?`, `next_day?`, `yesterday?`, `prev_day?` and `future?`, all of them relative to `Time.current`.
<ide>
<ide> When making Time comparisons using methods which honor the user time zone, make sure to use `Time.current` instead of `Time.now`. There are cases where the user time zone might be in the future compared to the system time zone, which `Time.now` uses by default. This means `Time.now.to_date` may equal `Date.yesterday`.
<ide> | 7 |
PHP | PHP | fix seed method on test case | 0124a458f4cd2306fef0f4989f781781d6e271bd | <ide><path>src/Illuminate/Foundation/Testing/TestCase.php
<ide> public function be(UserInterface $user, $driver = null)
<ide> /**
<ide> * Seed a given database connection.
<ide> *
<del> * @param string $connection
<add> * @param string $class
<ide> * @return void
<ide> */
<del> public function seed($connection = null)
<add> public function seed($class = 'DatabaseSeeder')
<ide> {
<del> $connection = $this->app['db']->connection($connection);
<del>
<del> $this->app['seeder']->seed($connection, $this->app['path'].'/database/seeds');
<add> $this->app[$class]->run();
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | use the correct transclusion scope | 4f32e3eef152bcaab7f7ab151fc824e71a591473 | <ide><path>src/ng/directive/ngSwitch.js
<ide> var ngSwitchDirective = ['$animate', function($animate) {
<ide> if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
<ide> scope.$eval(attr.change);
<ide> forEach(selectedTranscludes, function(selectedTransclude) {
<del> var selectedScope = scope.$new();
<del> selectedScopes.push(selectedScope);
<del> selectedTransclude.transclude(selectedScope, function(caseElement) {
<add> selectedTransclude.transclude(function(caseElement, selectedScope) {
<add> selectedScopes.push(selectedScope);
<ide> var anchor = selectedTransclude.element;
<ide>
<ide> selectedElements.push(caseElement);
<ide> var ngSwitchDirective = ['$animate', function($animate) {
<ide>
<ide> var ngSwitchWhenDirective = ngDirective({
<ide> transclude: 'element',
<del> priority: 800,
<add> priority: 1200,
<ide> require: '^ngSwitch',
<ide> multiElement: true,
<ide> link: function(scope, element, attrs, ctrl, $transclude) {
<ide> var ngSwitchWhenDirective = ngDirective({
<ide>
<ide> var ngSwitchDefaultDirective = ngDirective({
<ide> transclude: 'element',
<del> priority: 800,
<add> priority: 1200,
<ide> require: '^ngSwitch',
<ide> multiElement: true,
<ide> link: function(scope, element, attr, ctrl, $transclude) {
<ide><path>test/ng/directive/ngSwitchSpec.js
<ide> describe('ngSwitch', function() {
<ide> $rootScope.url = 'x';
<ide> $rootScope.$apply();
<ide> expect(getChildScope()).toBeUndefined();
<del> expect(child1.$destroy).toHaveBeenCalledOnce();
<add> expect(child1.$destroy).toHaveBeenCalled();
<ide>
<ide> $rootScope.url = 'a';
<ide> $rootScope.$apply();
<ide> describe('ngSwitch', function() {
<ide> }));
<ide>
<ide>
<add> it("should use the correct transclusion scope if there is a transclude directive on the ng-swith-when/ng-switch-default element", inject(function($rootScope, $compile) {
<add> element = $compile(
<add> '<div ng-switch="foo">' +
<add> '<pre ng-switch-when="item1" ng-repeat="bar in bars">' +
<add> 'foo = {{foo}}' +
<add> 'bar = {{bar}}' +
<add> '$index = {{$index}}' +
<add> '</pre>' +
<add> '</div>'
<add> )($rootScope);
<add> $rootScope.$apply('foo="item1";bars=["one", "two"]');
<add> expect(element.text()).toEqual(
<add> 'foo = item1' +
<add> 'bar = one' +
<add> '$index = 0' +
<add> 'foo = item1' +
<add> 'bar = two' +
<add> '$index = 1'
<add> );
<add> }));
<add>
<add>
<ide> it('should not leak jq data when compiled but not attached to parent when parent is destroyed',
<ide> inject(function($rootScope, $compile) {
<ide> element = $compile( | 2 |
Java | Java | fix race condition in writeresultpublisher | c0c3c01afd3cb756e56039720fdf30a39f3751c4 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/WriteResultPublisher.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2020 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> void publishComplete(WriteResultPublisher publisher) {
<ide> @Override
<ide> void publishError(WriteResultPublisher publisher, Throwable ex) {
<ide> publisher.errorBeforeSubscribed = ex;
<add> if(State.SUBSCRIBED.equals(publisher.state.get())) {
<add> publisher.state.get().publishError(publisher, ex);
<add> }
<ide> }
<ide> },
<ide>
<ide> void publishComplete(WriteResultPublisher publisher) {
<ide> @Override
<ide> void publishError(WriteResultPublisher publisher, Throwable ex) {
<ide> publisher.errorBeforeSubscribed = ex;
<add> if(State.SUBSCRIBED.equals(publisher.state.get())) {
<add> publisher.state.get().publishError(publisher, ex);
<add> }
<ide> }
<ide> },
<ide> | 1 |
Ruby | Ruby | remove nulls first/last. closes | 404b73bce1f9347ca05b1496db8fc64438d66bd2 | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def distinct(columns, orders) #:nodoc:
<ide>
<ide> # Construct a clean list of column names from the ORDER BY clause, removing
<ide> # any ASC/DESC modifiers
<del> order_columns = orders.collect { |s| s.gsub(/\s+(ASC|DESC)\s*/i, '') }
<add> order_columns = orders.collect { |s| s.gsub(/\s+(ASC|DESC)\s*(NULLS\s+(FIRST|LAST)\s*)?/i, '') }
<ide> order_columns.delete_if { |c| c.blank? }
<ide> order_columns = order_columns.zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" }
<ide>
<ide><path>activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
<ide> def test_partial_index
<ide> assert_equal "(number > 100)", index.where
<ide> end
<ide>
<add> def test_distinct_with_nulls
<add> assert_equal "DISTINCT posts.title, posts.updater_id AS alias_0", @connection.distinct("posts.title", ["posts.updater_id desc nulls first"])
<add> assert_equal "DISTINCT posts.title, posts.updater_id AS alias_0", @connection.distinct("posts.title", ["posts.updater_id desc nulls last"])
<add> end
<add>
<ide> private
<ide> def insert(ctx, data)
<ide> binds = data.map { |name, value| | 2 |
Ruby | Ruby | add from_path helper method | ac10b2ab50e987858b9fa5514785b12b7600787f | <ide><path>Library/Homebrew/tap.rb
<ide> def self.fetch(*args)
<ide> CACHE.fetch(cache_key) { |key| CACHE[key] = Tap.new(user, repo) }
<ide> end
<ide>
<add> def self.from_path(path)
<add> path.to_s =~ HOMEBREW_TAP_PATH_REGEX
<add> raise "Invalid tap path '#{path}'" unless $1
<add> fetch($1, $2)
<add> rescue
<add> # No need to error as a nil tap is sufficient to show failure.
<add> nil
<add> end
<add>
<ide> extend Enumerable
<ide>
<ide> # The user name of this {Tap}. Usually, it's the Github username of | 1 |
Javascript | Javascript | remove setimmediate from timeout test | ab73265b9c3e59d168aab485b0f936aedd47032b | <ide><path>test/sequential/test-http2-session-timeout.js
<ide> server.listen(0, common.mustCall(() => {
<ide> const diff = process.hrtime(startTime);
<ide> const milliseconds = (diff[0] * 1e3 + diff[1] / 1e6);
<ide> if (milliseconds < serverTimeout * 2) {
<del> setImmediate(makeReq);
<add> makeReq();
<ide> } else {
<ide> server.removeListener('timeout', mustNotCall);
<ide> server.close(); | 1 |
Javascript | Javascript | restrict pbkdf2 args to signed int | 8bf77545389563b864d0352b8c58f292aa1691f2 | <ide><path>lib/internal/crypto/pbkdf2.js
<ide> const {
<ide>
<ide> const {
<ide> validateFunction,
<add> validateInt32,
<ide> validateInteger,
<ide> validateString,
<ide> validateUint32,
<ide> function check(password, salt, iterations, keylen, digest) {
<ide>
<ide> password = getArrayBufferOrView(password, 'password');
<ide> salt = getArrayBufferOrView(salt, 'salt');
<del> validateUint32(iterations, 'iterations', true);
<del> validateUint32(keylen, 'keylen');
<add> // OpenSSL uses a signed int to represent these values, so we are restricted
<add> // to the 31-bit range here (which is plenty).
<add> validateInt32(iterations, 'iterations', 1);
<add> validateInt32(keylen, 'keylen', 0);
<ide>
<ide> return { password, salt, iterations, keylen, digest };
<ide> }
<ide><path>test/parallel/test-crypto-pbkdf2.js
<ide> assert.throws(
<ide> }
<ide> );
<ide>
<del>for (const iterations of [-1, 0]) {
<add>for (const iterations of [-1, 0, 2147483648]) {
<ide> assert.throws(
<ide> () => crypto.pbkdf2Sync('password', 'salt', iterations, 20, 'sha1'),
<ide> {
<ide> for (const iterations of [-1, 0]) {
<ide> });
<ide> });
<ide>
<del>[-1, 4294967297].forEach((input) => {
<add>[-1, 2147483648, 4294967296].forEach((input) => {
<ide> assert.throws(
<ide> () => {
<ide> crypto.pbkdf2('password', 'salt', 1, input, 'sha256', | 2 |
Text | Text | add missing links in deprecated.md doc | 7bc9e0aebbddb934f14ce287f0c3b419663cb480 | <ide><path>docs/deprecated.md
<ide> weight=80
<ide> The following list of features are deprecated in Engine.
<ide>
<ide> ### `-e` and `--email` flags on `docker login`
<del>**Deprecated In Release: v1.11**
<add>**Deprecated In Release: [v1.11.0](https://github.com/docker/docker/releases/tag/v1.11.0)**
<ide>
<ide> **Target For Removal In Release: v1.13**
<ide>
<ide> The docker login command is removing the ability to automatically register for an account with the target registry if the given username doesn't exist. Due to this change, the email flag is no longer required, and will be deprecated.
<ide>
<ide> ### Separator (`:`) of `--security-opt` flag on `docker run`
<del>**Deprecated In Release: v1.11**
<add>**Deprecated In Release: [v1.11.0](https://github.com/docker/docker/releases/tag/v1.11.0)**
<ide>
<ide> **Target For Removal In Release: v1.13**
<ide>
<ide> The flag `--security-opt` doesn't use the colon separator(`:`) anymore to divide keys and values, it uses the equal symbol(`=`) for consinstency with other similar flags, like `--storage-opt`.
<ide>
<ide> ### Ambiguous event fields in API
<del>**Deprecated In Release: v1.10**
<add>**Deprecated In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
<ide>
<ide> The fields `ID`, `Status` and `From` in the events API have been deprecated in favor of a more rich structure.
<ide> See the events API documentation for the new format.
<ide>
<ide> ### `-f` flag on `docker tag`
<ide> **Deprecated In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
<ide>
<del>**Removed In Release: v1.12.0**
<add>**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
<ide>
<ide> To make tagging consistent across the various `docker` commands, the `-f` flag on the `docker tag` command is deprecated. It is not longer necessary to specify `-f` to move a tag from one image to another. Nor will `docker` generate an error if the `-f` flag is missing and the specified tag is already in use.
<ide>
<ide> ### HostConfig at API container start
<del>**Deprecated In Release: v1.10**
<add>**Deprecated In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
<ide>
<del>**Target For Removal In Release: v1.12**
<add>**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
<ide>
<ide> Passing an `HostConfig` to `POST /containers/{name}/start` is deprecated in favor of
<ide> defining it at container creation (`POST /containers/create`).
<ide> defining it at container creation (`POST /containers/create`).
<ide>
<ide> **Deprecated In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
<ide>
<del>**Removed In Release: v1.12**
<add>**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
<ide>
<ide> The `docker ps --before` and `docker ps --since` options are deprecated.
<ide> Use `docker ps --filter=before=...` and `docker ps --filter=since=...` instead.
<ide> Use `docker ps --filter=before=...` and `docker ps --filter=since=...` instead.
<ide>
<ide> **Deprecated in Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
<ide>
<del>**Removed In Release: v1.14**
<add>**Target For Removal In Release: v1.14**
<ide>
<ide> The `docker search --automated` and `docker search --stars` options are deprecated.
<ide> Use `docker search --filter=is-automated=...` and `docker search --filter=stars=...` instead.
<ide>
<ide> ### Driver Specific Log Tags
<del>**Deprecated In Release: v1.9**
<add>**Deprecated In Release: [v1.9.0](https://github.com/docker/docker/releases/tag/v1.9.0)**
<ide>
<del>**Removed In Release: v1.12**
<add>**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
<ide>
<ide> Log tags are now generated in a standard way across different logging drivers.
<ide> Because of which, the driver specific log tag options `syslog-tag`, `gelf-tag` and
<ide> Because of which, the driver specific log tag options `syslog-tag`, `gelf-tag` a
<ide> docker --log-driver=syslog --log-opt tag="{{.ImageName}}/{{.Name}}/{{.ID}}"
<ide>
<ide> ### LXC built-in exec driver
<del>**Deprecated In Release: v1.8**
<add>**Deprecated In Release: [v1.8.0](https://github.com/docker/docker/releases/tag/v1.8.0)**
<ide>
<del>**Removed In Release: v1.10**
<add>**Removed In Release: [v1.10.0](https://github.com/docker/docker/releases/tag/v1.10.0)**
<ide>
<ide> The built-in LXC execution driver, the lxc-conf flag, and API fields have been removed.
<ide>
<ide> The following double-dash options are deprecated and have no replacement:
<ide> Version 1.9 adds a flag (`--disable-legacy-registry=false`) which prevents the docker daemon from `pull`, `push`, and `login` operations against v1 registries. Though disabled by default, this signals the intent to deprecate the v1 protocol.
<ide>
<ide> ### Docker Content Trust ENV passphrase variables name change
<del>**Deprecated In Release: v1.9**
<add>**Deprecated In Release: [v1.9.0](https://github.com/docker/docker/releases/tag/v1.9.0)**
<ide>
<del>**Removed In Release: v1.12**
<add>**Removed In Release: [v1.12.0](https://github.com/docker/docker/releases/tag/v1.12.0)**
<ide>
<ide> Since 1.9, Docker Content Trust Offline key has been renamed to Root key and the Tagging key has been renamed to Repository key. Due to this renaming, we're also changing the corresponding environment variables
<ide> | 1 |
Ruby | Ruby | add comprehensive locking around db transactions | e4c197c7698e204d0c74a2ece20adf831c2f9a8d | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
<ide> def initialize(connection)
<ide> end
<ide>
<ide> def begin_transaction(options = {})
<del> run_commit_callbacks = !current_transaction.joinable?
<del> transaction =
<del> if @stack.empty?
<del> RealTransaction.new(@connection, options, run_commit_callbacks: run_commit_callbacks)
<del> else
<del> SavepointTransaction.new(@connection, "active_record_#{@stack.size}", options,
<del> run_commit_callbacks: run_commit_callbacks)
<del> end
<add> @connection.lock.synchronize do
<add> run_commit_callbacks = !current_transaction.joinable?
<add> transaction =
<add> if @stack.empty?
<add> RealTransaction.new(@connection, options, run_commit_callbacks: run_commit_callbacks)
<add> else
<add> SavepointTransaction.new(@connection, "active_record_#{@stack.size}", options,
<add> run_commit_callbacks: run_commit_callbacks)
<add> end
<ide>
<del> @stack.push(transaction)
<del> transaction
<add> @stack.push(transaction)
<add> transaction
<add> end
<ide> end
<ide>
<ide> def commit_transaction
<del> transaction = @stack.last
<add> @connection.lock.synchronize do
<add> transaction = @stack.last
<ide>
<del> begin
<del> transaction.before_commit_records
<del> ensure
<del> @stack.pop
<del> end
<add> begin
<add> transaction.before_commit_records
<add> ensure
<add> @stack.pop
<add> end
<ide>
<del> transaction.commit
<del> transaction.commit_records
<add> transaction.commit
<add> transaction.commit_records
<add> end
<ide> end
<ide>
<ide> def rollback_transaction(transaction = nil)
<del> transaction ||= @stack.pop
<del> transaction.rollback
<del> transaction.rollback_records
<add> @connection.lock.synchronize do
<add> transaction ||= @stack.pop
<add> transaction.rollback
<add> transaction.rollback_records
<add> end
<ide> end
<ide>
<ide> def within_new_transaction(options = {})
<del> transaction = begin_transaction options
<del> yield
<del> rescue Exception => error
<del> if transaction
<del> rollback_transaction
<del> after_failure_actions(transaction, error)
<del> end
<del> raise
<del> ensure
<del> unless error
<del> if Thread.current.status == "aborting"
<del> rollback_transaction if transaction
<del> else
<del> begin
<del> commit_transaction
<del> rescue Exception
<del> rollback_transaction(transaction) unless transaction.state.completed?
<del> raise
<add> @connection.lock.synchronize do
<add> begin
<add> transaction = begin_transaction options
<add> yield
<add> rescue Exception => error
<add> if transaction
<add> rollback_transaction
<add> after_failure_actions(transaction, error)
<add> end
<add> raise
<add> ensure
<add> unless error
<add> if Thread.current.status == "aborting"
<add> rollback_transaction if transaction
<add> else
<add> begin
<add> commit_transaction
<add> rescue Exception
<add> rollback_transaction(transaction) unless transaction.state.completed?
<add> raise
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> class AbstractAdapter
<ide> SIMPLE_INT = /\A\d+\z/
<ide>
<ide> attr_accessor :visitor, :pool
<del> attr_reader :schema_cache, :owner, :logger, :prepared_statements
<add> attr_reader :schema_cache, :owner, :logger, :prepared_statements, :lock
<ide> alias :in_use? :owner
<ide>
<ide> def self.type_cast_config_to_integer(config)
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def truncate(table_name, name = nil)
<ide>
<ide> # Is this connection alive and ready for queries?
<ide> def active?
<del> @connection.query "SELECT 1"
<add> @lock.synchronize do
<add> @connection.query "SELECT 1"
<add> end
<ide> true
<ide> rescue PG::Error
<ide> false
<ide> end
<ide>
<ide> # Close then reopen the connection.
<ide> def reconnect!
<del> super
<del> @connection.reset
<del> configure_connection
<add> @lock.synchronize do
<add> super
<add> @connection.reset
<add> configure_connection
<add> end
<ide> end
<ide>
<ide> def reset!
<del> clear_cache!
<del> reset_transaction
<del> unless @connection.transaction_status == ::PG::PQTRANS_IDLE
<del> @connection.query "ROLLBACK"
<add> @lock.synchronize do
<add> clear_cache!
<add> reset_transaction
<add> unless @connection.transaction_status == ::PG::PQTRANS_IDLE
<add> @connection.query "ROLLBACK"
<add> end
<add> @connection.query "DISCARD ALL"
<add> configure_connection
<ide> end
<del> @connection.query "DISCARD ALL"
<del> configure_connection
<ide> end
<ide>
<ide> # Disconnects from the database if already connected. Otherwise, this
<ide> # method does nothing.
<ide> def disconnect!
<del> super
<del> @connection.close rescue nil
<add> @lock.synchronize do
<add> super
<add> @connection.close rescue nil
<add> end
<ide> end
<ide>
<ide> def native_database_types #:nodoc: | 3 |
Python | Python | add missed deprecations for cncf | 4a73d8f3d1f0c2cb52707901f9e9a34198573d5e | <ide><path>airflow/providers/cncf/kubernetes/backcompat/pod.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<del>"""Classes for interacting with Kubernetes API"""
<add>"""
<add>Classes for interacting with Kubernetes API.
<add>
<add>This module is deprecated. Please use :mod:`kubernetes.client.models.V1ResourceRequirements`
<add>and :mod:`kubernetes.client.models.V1ContainerPort`.
<add>"""
<add>
<add>import warnings
<ide>
<ide> from kubernetes.client import models as k8s
<ide>
<add>warnings.warn(
<add> (
<add> "This module is deprecated. Please use `kubernetes.client.models.V1ResourceRequirements`"
<add> " and `kubernetes.client.models.V1ContainerPort`."
<add> ),
<add> DeprecationWarning,
<add> stacklevel=2,
<add>)
<add>
<ide>
<ide> class Resources:
<del> """backwards compat for Resources"""
<add> """backwards compat for Resources."""
<ide>
<ide> __slots__ = (
<ide> 'request_memory',
<ide><path>airflow/providers/cncf/kubernetes/backcompat/pod_runtime_info_env.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<del>"""Classes for interacting with Kubernetes API"""
<add>"""
<add>Classes for interacting with Kubernetes API.
<add>
<add>This module is deprecated. Please use :mod:`kubernetes.client.models.V1EnvVar`.
<add>"""
<add>
<add>import warnings
<ide>
<ide> import kubernetes.client.models as k8s
<ide>
<add>warnings.warn(
<add> "This module is deprecated. Please use `kubernetes.client.models.V1EnvVar`.",
<add> DeprecationWarning,
<add> stacklevel=2,
<add>)
<add>
<ide>
<ide> class PodRuntimeInfoEnv:
<del> """Defines Pod runtime information as environment variable"""
<add> """Defines Pod runtime information as environment variable."""
<ide>
<ide> def __init__(self, name, field_path):
<ide> """
<ide><path>airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py
<ide> convert_volume,
<ide> convert_volume_mount,
<ide> )
<del>from airflow.providers.cncf.kubernetes.backcompat.pod_runtime_info_env import PodRuntimeInfoEnv
<ide> from airflow.providers.cncf.kubernetes.utils import xcom_sidecar
<ide> from airflow.providers.cncf.kubernetes.utils.pod_manager import PodLaunchFailedException, PodManager, PodPhase
<ide> from airflow.settings import pod_mutation_hook
<ide> def __init__(
<ide> do_xcom_push: bool = False,
<ide> pod_template_file: Optional[str] = None,
<ide> priority_class_name: Optional[str] = None,
<del> pod_runtime_info_envs: Optional[List[PodRuntimeInfoEnv]] = None,
<add> pod_runtime_info_envs: Optional[List[k8s.V1EnvVar]] = None,
<ide> termination_grace_period: Optional[int] = None,
<ide> configmaps: Optional[List[str]] = None,
<ide> **kwargs,
<ide><path>dev/provider_packages/prepare_provider_packages.py
<ide> def summarise_total_vs_bad_and_warnings(total: int, bad: int, warns: List[warnin
<ide> "This module is deprecated. Please use `airflow.providers.tableau.hooks.tableau`.",
<ide> "This module is deprecated. Please use `kubernetes.client.models.V1Volume`.",
<ide> "This module is deprecated. Please use `kubernetes.client.models.V1VolumeMount`.",
<add> (
<add> "This module is deprecated. Please use `kubernetes.client.models.V1ResourceRequirements`"
<add> " and `kubernetes.client.models.V1ContainerPort`."
<add> ),
<add> "This module is deprecated. Please use `kubernetes.client.models.V1EnvVar`.",
<ide> 'numpy.ufunc size changed, may indicate binary incompatibility. Expected 192 from C header,'
<ide> ' got 216 from PyObject',
<ide> "This module is deprecated. Please use `airflow.providers.amazon.aws.sensors.step_function`.", | 4 |
Javascript | Javascript | simplify the unsubscribe routes and handlers | bf564a5023f154f12505f062323c0e0ae3beefcc | <ide><path>server/boot/randomAPIs.js
<ide> module.exports = function(app) {
<ide> noLangRouter.get('/api/github', githubCalls);
<ide> noLangRouter.get('/chat', chat);
<ide> noLangRouter.get('/twitch', twitch);
<del> noLangRouter.get('/unsubscribe/:email', unsubscribeMonthly);
<del> noLangRouter.get(
<del> '/unsubscribe-notifications/:email',
<del> unsubscribeNotifications
<del> );
<del> noLangRouter.get('/unsubscribe-quincy/:email', unsubscribeQuincy);
<add> noLangRouter.get('/unsubscribe/:email', unsubscribeAll);
<add> noLangRouter.get('/unsubscribe-notifications/:email', unsubscribeAll);
<add> noLangRouter.get('/unsubscribe-quincy/:email', unsubscribeAll);
<ide> noLangRouter.get('/submit-cat-photo', submitCatPhoto);
<ide> noLangRouter.get(
<ide> '/the-fastest-web-page-on-the-internet',
<ide> module.exports = function(app) {
<ide> res.redirect('https://twitch.tv/freecodecamp');
<ide> }
<ide>
<del> function unsubscribeMonthly(req, res, next) {
<del> req.checkParams('email', 'Must send a valid email').isEmail();
<del> return User.findOne({ where: { email: req.params.email } }, (err, user) => {
<del> if (err) { return next(err); }
<del> if (!user) {
<del> req.flash('info', {
<del> msg: 'Email address not found. ' +
<del> 'Please update your Email preferences from your profile.'
<del> });
<del> return res.redirect('/map');
<del> }
<del> return user.updateAttributes({
<del> sendMonthlyEmail: false,
<del> sendQuincyEmail: false,
<del> sendNotificationEmail: false
<del> }, (err) => {
<del> if (err) { return next(err); }
<del> req.flash('info', {
<del> msg: 'We\'ve successfully updated your Email preferences.'
<del> });
<del> return res.redirect('/unsubscribed');
<del> });
<del> });
<del> }
<del>
<del> function unsubscribeNotifications(req, res, next) {
<del> req.checkParams('email', 'Must send a valid email').isEmail();
<del> return User.findOne({ where: { email: req.params.email } }, (err, user) => {
<del> if (err) { return next(err); }
<del> if (!user) {
<del> req.flash('info', {
<del> msg: 'Email address not found. ' +
<del> 'Please update your Email preferences from your profile.'
<del> });
<del> return res.redirect('/map');
<del> }
<del> return user.updateAttribute('sendNotificationEmail', false, (err) => {
<del> if (err) { return next(err); }
<del> req.flash('info', {
<del> msg: 'We\'ve successfully updated your Email preferences.'
<del> });
<del> return res.redirect('/unsubscribed');
<del> });
<del> });
<del> }
<del>
<del> function unsubscribeQuincy(req, res, next) {
<add> function unsubscribeAll(req, res, next) {
<ide> req.checkParams('email', 'Must send a valid email').isEmail();
<ide> return User.findOne({ where: { email: req.params.email } }, (err, user) => {
<ide> if (err) { return next(err); } | 1 |
Text | Text | fix whitespace in link | f6db83d6f26cb8623acfb669b59b7804fd526716 | <ide><path>README.md
<ide> For this certification, you'll work on **two projects from scratch** and then **
<ide>
<ide> ---
<ide>
<del>This code is running live at [freeCodeCamp.org](https://www.freecodecamp.org). We also have [Gitter chat rooms](https://gitter.im/FreeCodeCamp/FreeCodeCamp), a [Medium publication](https://medium.freecodecamp.org), an [interactive forum](https://forum.freecodecamp.org), a [wiki knowledgebase](https://forum.freecodecamp.org/c/wiki), local [FaceBook groups] (https://study-group-directory.freecodecamp.org/), and even a [YouTube channel](https://youtube.com/freecodecamp).
<add>This code is running live at [freeCodeCamp.org](https://www.freecodecamp.org). We also have [Gitter chat rooms](https://gitter.im/FreeCodeCamp/FreeCodeCamp), a [Medium publication](https://medium.freecodecamp.org), an [interactive forum](https://forum.freecodecamp.org), a [wiki knowledgebase](https://forum.freecodecamp.org/c/wiki), local [FaceBook groups](https://study-group-directory.freecodecamp.org/), and even a [YouTube channel](https://youtube.com/freecodecamp).
<ide>
<ide> ### [Join our community here](https://www.freecodecamp.org/signin).
<ide> | 1 |
Text | Text | fix the column name [ci skip] | 967a6dc8985ee5d9956b23ba23f0f9d39a0c07d9 | <ide><path>activerecord/CHANGELOG.md
<ide> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
<ide>
<ide> User.active
<del> # => SELECT "users".* FROM "users" WHERE "users"."status" = 'active'
<add> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'active'
<ide>
<ide> User.where(state: 'inactive')
<del> # => SELECT "users".* FROM "users" WHERE "users"."status" = 'inactive'
<add> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
<ide>
<ide> After:
<ide>
<ide> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
<ide>
<ide> User.active
<del> # => SELECT "users".* FROM "users" WHERE "users"."status" = 'pending' AND "users"."status" = 'active'
<add> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'active'
<ide>
<ide> User.where(state: 'inactive')
<del> # => SELECT "users".* FROM "users" WHERE "users"."status" = 'pending' AND "users"."status" = 'inactive'
<add> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'inactive'
<ide>
<ide> To get the previous behavior it is needed to explicitly remove the
<ide> `default_scope` condition using `unscoped`, `unscope`, `rewhere` or
<ide> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
<ide>
<ide> User.active
<del> # => SELECT "users".* FROM "users" WHERE "users"."status" = 'active'
<add> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'active'
<ide>
<ide> User.inactive
<del> # => SELECT "users".* FROM "users" WHERE "users"."status" = 'inactive'
<add> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
<ide>
<ide> * Perform necessary deeper encoding when hstore is inside an array.
<ide>
<ide><path>guides/source/active_record_querying.md
<ide> User.all
<ide> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
<ide>
<ide> User.active
<del># => SELECT "users".* FROM "users" WHERE "users"."status" = 'pending' AND "users"."status" = 'active'
<add># => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'active'
<ide>
<ide> User.where(state: 'inactive')
<del># => SELECT "users".* FROM "users" WHERE "users"."status" = 'pending' AND "users"."status" = 'inactive'
<add># => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'inactive'
<ide> ```
<ide>
<ide> As you can see above the `default_scope` is being merged in both
<ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> User.all
<ide> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
<ide>
<ide> User.active
<del># => SELECT "users".* FROM "users" WHERE "users"."status" = 'active'
<add># => SELECT "users".* FROM "users" WHERE "users"."state" = 'active'
<ide>
<ide> User.where(state: 'inactive')
<del># => SELECT "users".* FROM "users" WHERE "users"."status" = 'inactive'
<add># => SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
<ide> ```
<ide>
<ide> After:
<ide> User.all
<ide> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
<ide>
<ide> User.active
<del># => SELECT "users".* FROM "users" WHERE "users"."status" = 'pending' AND "users"."status" = 'active'
<add># => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'active'
<ide>
<ide> User.where(state: 'inactive')
<del># => SELECT "users".* FROM "users" WHERE "users"."status" = 'pending' AND "users"."status" = 'inactive'
<add># => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending' AND "users"."state" = 'inactive'
<ide> ```
<ide>
<ide> To get the previous behavior it is needed to explicitly remove the
<ide> User.all
<ide> # => SELECT "users".* FROM "users" WHERE "users"."state" = 'pending'
<ide>
<ide> User.active
<del># => SELECT "users".* FROM "users" WHERE "users"."status" = 'active'
<add># => SELECT "users".* FROM "users" WHERE "users"."state" = 'active'
<ide>
<ide> User.inactive
<del># => SELECT "users".* FROM "users" WHERE "users"."status" = 'inactive'
<add># => SELECT "users".* FROM "users" WHERE "users"."state" = 'inactive'
<ide> ```
<ide>
<ide> Upgrading from Rails 3.2 to Rails 4.0 | 3 |
Go | Go | add ian murdock to the names generator | e11ebfcb0984225690dccc1e644712a80bae2dec | <ide><path>pkg/namesgenerator/names-generator.go
<ide> var (
<ide> // Samuel Morse - contributed to the invention of a single-wire telegraph system based on European telegraphs and was a co-developer of the Morse code - https://en.wikipedia.org/wiki/Samuel_Morse
<ide> "morse",
<ide>
<add> // Ian Murdock - founder of the Debian project - https://en.wikipedia.org/wiki/Ian_Murdock
<add> "murdock",
<add>
<ide> // Isaac Newton invented classic mechanics and modern optics. https://en.wikipedia.org/wiki/Isaac_Newton
<ide> "newton",
<ide> | 1 |
Java | Java | create yogaprops interface | e27ca7f24e116bbf8a154ec9fcb85f69ee20af56 | <ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaNode.java
<ide>
<ide> import javax.annotation.Nullable;
<ide>
<del>public abstract class YogaNode {
<add>public abstract class YogaNode implements YogaProps {
<ide>
<ide> /** The interface the {@link #getData()} object can optionally implement. */
<ide> public interface Inputs {
<ide><path>ReactAndroid/src/main/java/com/facebook/yoga/YogaProps.java
<add>/*
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>package com.facebook.yoga;
<add>
<add>public interface YogaProps {
<add>
<add> /* Width properties */
<add>
<add> void setWidth(float width);
<add>
<add> void setWidthPercent(float percent);
<add>
<add> void setMinWidth(float minWidth);
<add>
<add> void setMinWidthPercent(float percent);
<add>
<add> void setMaxWidth(float maxWidth);
<add>
<add> void setMaxWidthPercent(float percent);
<add>
<add> void setWidthAuto();
<add>
<add> /* Height properties */
<add>
<add> void setHeight(float height);
<add>
<add> void setHeightPercent(float percent);
<add>
<add> void setMinHeight(float minHeight);
<add>
<add> void setMinHeightPercent(float percent);
<add>
<add> void setMaxHeight(float maxHeight);
<add>
<add> void setMaxHeightPercent(float percent);
<add>
<add> void setHeightAuto();
<add>
<add> /* Margin properties */
<add>
<add> void setMargin(YogaEdge edge, float margin);
<add>
<add> void setMarginPercent(YogaEdge edge, float percent);
<add>
<add> void setMarginAuto(YogaEdge edge);
<add>
<add> /* Padding properties */
<add>
<add> void setPadding(YogaEdge edge, float padding);
<add>
<add> void setPaddingPercent(YogaEdge edge, float percent);
<add>
<add> /* Position properties */
<add>
<add> void setPositionType(YogaPositionType positionType);
<add>
<add> void setPosition(YogaEdge edge, float position);
<add>
<add> void setPositionPercent(YogaEdge edge, float percent);
<add>
<add> /* Alignment properties */
<add>
<add> void setAlignContent(YogaAlign alignContent);
<add>
<add> void setAlignItems(YogaAlign alignItems);
<add>
<add> void setAlignSelf(YogaAlign alignSelf);
<add>
<add> /* Flex properties */
<add>
<add> void setFlex(float flex);
<add>
<add> void setFlexBasisAuto();
<add>
<add> void setFlexBasisPercent(float percent);
<add>
<add> void setFlexBasis(float flexBasis);
<add>
<add> void setFlexDirection(YogaFlexDirection direction);
<add>
<add> void setFlexGrow(float flexGrow);
<add>
<add> void setFlexShrink(float flexShrink);
<add>
<add> /* Other properties */
<add>
<add> void setJustifyContent(YogaJustify justifyContent);
<add>
<add> void setDirection(YogaDirection direction);
<add>
<add> void setBorder(YogaEdge edge, float value);
<add>
<add> void setWrap(YogaWrap wrap);
<add>
<add> void setAspectRatio(float aspectRatio);
<add>
<add> void setIsReferenceBaseline(boolean isReferenceBaseline);
<add>
<add> void setMeasureFunction(YogaMeasureFunction measureFunction);
<add>
<add> void setBaselineFunction(YogaBaselineFunction yogaBaselineFunction);
<add>
<add> /* Getters */
<add>
<add> YogaValue getWidth();
<add>
<add> YogaValue getMinWidth();
<add>
<add> YogaValue getMaxWidth();
<add>
<add> YogaValue getHeight();
<add>
<add> YogaValue getMinHeight();
<add>
<add> YogaValue getMaxHeight();
<add>
<add> YogaDirection getStyleDirection();
<add>
<add> YogaFlexDirection getFlexDirection();
<add>
<add> YogaJustify getJustifyContent();
<add>
<add> YogaAlign getAlignItems();
<add>
<add> YogaAlign getAlignSelf();
<add>
<add> YogaAlign getAlignContent();
<add>
<add> YogaPositionType getPositionType();
<add>
<add> float getFlexGrow();
<add>
<add> float getFlexShrink();
<add>
<add> YogaValue getFlexBasis();
<add>
<add> float getAspectRatio();
<add>
<add> YogaValue getMargin(YogaEdge edge);
<add>
<add> YogaValue getPadding(YogaEdge edge);
<add>
<add> YogaValue getPosition(YogaEdge edge);
<add>
<add> float getBorder(YogaEdge edge);
<add>} | 2 |
PHP | PHP | remove pointless condition | 0750069126b1941060926a63300e6f61f6fec6a0 | <ide><path>lib/Cake/Model/Model.php
<ide> public function deconstruct($field, $data) {
<ide> foreach ($timeFields as $key => $val) {
<ide> if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') {
<ide> $data[$val] = '00';
<del> } elseif ($data[$val] === '') {
<del> $data[$val] = '';
<del> } else {
<add> } elseif ($data[$val] !== '') {
<ide> $data[$val] = sprintf('%02d', $data[$val]);
<ide> }
<ide> if (!empty($data[$val])) { | 1 |
Python | Python | remove trailing whitespace from numpy/ma/core.py | b3dfa8de56c4a892db58284aebe7554e25829c64 | <ide><path>numpy/ma/core.py
<ide> def resize(x, new_shape):
<ide> return result
<ide>
<ide>
<del>def rank(obj):
<add>def rank(obj):
<ide> """
<ide> maskedarray version of the numpy function.
<ide>
<ide> def rank(obj):
<ide> rank.__doc__ = np.rank.__doc__
<ide>
<ide>
<del>def ndim(obj):
<add>def ndim(obj):
<ide> """
<ide> maskedarray version of the numpy function.
<ide> | 1 |
Go | Go | fix gcplogs memory/connection leak | ef553e14a4e27fc479b9c8e94d76654ec67694fe | <ide><path>daemon/logger/gcplogs/gcplogging.go
<ide> func init() {
<ide> }
<ide>
<ide> type gcplogs struct {
<add> client *logging.Client
<ide> logger *logging.Logger
<ide> instance *instanceInfo
<ide> container *containerInfo
<ide> func New(info logger.Info) (logger.Logger, error) {
<ide> }
<ide>
<ide> l := &gcplogs{
<add> client: c,
<ide> logger: lg,
<ide> container: &containerInfo{
<ide> Name: info.ContainerName,
<ide> func (l *gcplogs) Log(m *logger.Message) error {
<ide>
<ide> func (l *gcplogs) Close() error {
<ide> l.logger.Flush()
<del> return nil
<add> return l.client.Close()
<ide> }
<ide>
<ide> func (l *gcplogs) Name() string { | 1 |
Ruby | Ruby | pass the outer joins to join_constraints | 796c0fc1b065bc4248a410110e728e5b2c6db19e | <ide><path>activerecord/lib/active_record/associations/join_dependency.rb
<ide> def apply_tables!(node)
<ide> node.children.each { |child| construct_tables! node, child }
<ide> end
<ide>
<del> def join_constraints
<add> def join_constraints(outer_joins)
<add> outer_joins.each { |oj| merge_outer_joins! oj }
<ide> make_joins join_root
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def build_joins(manager, joins)
<ide> join_list
<ide> )
<ide>
<del> stashed_association_joins.each do |dep|
<del> join_dependency.merge_outer_joins! dep
<del> end
<del>
<del> joins = join_dependency.join_constraints
<add> joins = join_dependency.join_constraints stashed_association_joins
<ide>
<ide> joins.each { |join| manager.from(join) }
<ide> | 2 |
Ruby | Ruby | add pre el capitan keg_only | 48ba192a3bac609c1bdd7355d4749d624b973c46 | <ide><path>Library/Homebrew/formula_support.rb
<ide> def valid?
<ide> MacOS.version < :mountain_lion
<ide> when :provided_pre_mavericks
<ide> MacOS.version < :mavericks
<add> when :provided_pre_el_capitan
<add> MacOS.version < :el_capitan
<ide> when :provided_until_xcode43
<ide> MacOS::Xcode.version < "4.3"
<ide> when :provided_until_xcode5
<ide> def to_s
<ide> when :shadowed_by_osx then <<-EOS
<ide> OS X provides similar software and installing this software in
<ide> parallel can cause all kinds of trouble.
<add>EOS
<add> when :provided_pre_mountain_lion then <<-EOS
<add>OS X already provides this software in versions before Mountain Lion.
<ide> EOS
<ide> when :provided_pre_mavericks then <<-EOS
<ide> OS X already provides this software in versions before Mavericks.
<ide> EOS
<del> when :provided_pre_mountain_lion then <<-EOS
<del>OS X already provides this software in versions before Mountain Lion.
<add> when :provided_pre_el_capitan then <<-EOS
<add>OS X already provides this software in versions before El Capitan.
<ide> EOS
<ide> when :provided_until_xcode43
<ide> "Xcode provides this software prior to version 4.3." | 1 |
Text | Text | update exercise portion of onboarding doc | 4c7688138366bc350ed0260583d457733f835828 | <ide><path>doc/onboarding.md
<ide> Landing a PR
<ide> * Close the pull request with a "Landed in `<commit hash>`" comment.
<ide>
<ide>
<del>## exercise: make PRs adding yourselves to the README
<add>## Exercise: Make a PR adding yourself to the README
<ide>
<ide> * Example: https://github.com/nodejs/node/commit/7b09aade8468e1c930f36b9c81e6ac2ed5bc8732
<del> * to see full URL: `git log 7b09aade8468e1c930f36b9c81e6ac2ed5bc8732 -1`
<del> * Collaborators in alphabetical order by username
<del> * Label your pull request with the `doc` subsystem label
<del> * If you would like to run CI on your PR, feel free to
<del> * Make sure to added the `PR-URL: <full-pr-url>`!
<add> * For raw commit message: `git log 7b09aade8468e1c930f36b9c81e6ac2ed5bc8732 -1`
<add> * Collaborators are in alphabetical order by GitHub username.
<add> * Label your pull request with the `doc` subsystem label.
<add> * Run CI on your PR.
<add> * After a `LGTM` or two, land the PR.
<add> * Be sure to add the `PR-URL: <full-pr-url>` and appropriate `Reviewed-By:` metadata!
<ide>
<ide>
<ide> ## final notes | 1 |
Python | Python | add chinese punctuation | 1f1f35dcd07d419a2aca449c0ef738e098e37b68 | <ide><path>spacy/language_data/punctuation.py
<ide>
<ide> _QUOTES = r"""
<ide> ' '' " ” “ `` ` ‘ ´ ‚ , „ » «
<add>「 」 『 』 ( ) 〔 〕 【 】 《 》 〈 〉
<ide> """
<ide>
<ide>
<ide> _PUNCT = r"""
<ide> … , : ; \! \? ¿ ¡ \( \) \[ \] \{ \} < > _ # \* &
<add>。? ! , 、 ; : ~
<ide> """
<ide>
<ide> | 1 |
Javascript | Javascript | fix lint failure | 648d78dab5b3fbb18ae2d84aceda11ca3803151b | <ide><path>lib/util/identifier.js
<ide> const _makePathsRelative = (context, identifier) => {
<ide> .map(str => looksLikeAbsolutePath(str) ?
<ide> normalizePathSeparator(path.relative(context, str)) : str)
<ide> .join("");
<del>}
<add>};
<ide>
<ide> exports.makePathsRelative = (context, identifier, cache) => {
<ide> if(!cache) return _makePathsRelative(context, identifier); | 1 |
PHP | PHP | ignore phpcs and long lines in html template | 6d7a9550d9a128e29f1948d0e566a0222c930896 | <ide><path>src/Error/Renderer/HtmlRenderer.php
<ide> private function renderToggle(string $text, string $id, string $suffix): string
<ide> {
<ide> $selector = $id . '-' . $suffix;
<ide>
<add> // phpcs:disable
<ide> return <<<HTML
<del><a
<del> href="javascript:void(0);"
<del> onclick="document.getElementById('{$selector}').style.display = (document.getElementById('{$selector}').style.display == 'none' ? '' : 'none'"
<add><a href="javascript:void(0);"
<add> onclick="document.getElementById('{$selector}').style.display = (document.getElementById('{$selector}').style.display == 'none' ? '' : 'none'"
<ide> >
<ide> {$text}
<ide> </a>
<ide> HTML;
<add> // phpcs:enable
<ide> }
<ide> } | 1 |
Text | Text | add npm install instructions to readme | 17c9dffed47d105e0872b7944cd6720571129d22 | <ide><path>README.md
<ide> If you'd like to use [bower](http://bower.io), it's as easy as:
<ide> bower install --save react
<ide> ```
<ide>
<add>And it's just as easy with [npm](http://npmjs.com):
<add>
<add>```sh
<add>npm i --save react
<add>```
<add>
<ide> ## Contribute
<ide>
<ide> The main purpose of this repository is to continue to evolve React core, making it faster and easier to use. If you're interested in helping with that, then keep reading. If you're not interested in helping right now that's ok too. :) Any feedback you have about using React would be greatly appreciated. | 1 |
PHP | PHP | add a slash after port number | 9279cb5dad9f9eb5714133dd19813b8a7b602668 | <ide><path>src/Illuminate/Foundation/Console/ServeCommand.php
<ide> public function fire()
<ide>
<ide> $base = $this->laravel->basePath();
<ide>
<del> $this->info("Laravel development server started on http://{$host}:{$port}");
<add> $this->info("Laravel development server started on http://{$host}:{$port}/");
<ide>
<ide> passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} \"{$base}\"/server.php");
<ide> } | 1 |
Python | Python | add meaniou metric | de27619e9dc602833a5578e59f034bc49a8d9cd4 | <ide><path>keras/backend/__init__.py
<ide> from .load_backend import manual_variable_initialization
<ide> from .load_backend import get_session
<ide> from .load_backend import set_session
<add> from .load_backend import top_k
<add> from .load_backend import MeanIoU
<ide> elif backend() == 'cntk':
<ide> from .load_backend import clear_session
<ide><path>keras/backend/tensorflow_backend.py
<ide> py_sum = sum
<ide> py_slice = slice
<ide>
<add>MeanIoU = tf.keras.metrics.MeanIoU
<add>
<ide> # INTERNAL UTILS
<ide>
<ide> # This list holds the available devices.
<ide> def in_top_k(predictions, targets, k):
<ide> k=k)
<ide>
<ide>
<add>def top_k(input, k=1, sorted=True, name=None):
<add> """Finds values and indices of the k largest entries for the last dimension.
<add>
<add> # Arguments
<add> input: 1-D or higher Tensor with last dimension at least k.
<add> k: 0-D int32 Tensor. Number of top elements to look for along the last
<add> dimension (along each row for matrices).
<add> sorted: If true the resulting k elements will be sorted by the values
<add> in descending order.
<add> name: Optional name for the operation.
<add>
<add> # Returns
<add> values: The k largest elements along each last dimensional slice.
<add> indices: The indices of values within the last dimension of input.
<add> """
<add> return tf.math.top_k(input, k=k, sorted=sorted, name=name)
<add>
<add>
<ide> # CONVOLUTIONS
<ide>
<ide>
<ide><path>keras/metrics.py
<ide> def __init__(self,
<ide> dtype=None):
<ide> super(Precision, self).__init__(name=name, dtype=dtype)
<ide> self.init_thresholds = thresholds
<add> if top_k is not None and K.backend() != 'tensorflow':
<add> raise RuntimeError(
<add> '`top_k` argument for `Precision` metric is currently supported only '
<add> 'with TensorFlow backend.')
<add>
<ide> self.top_k = top_k
<ide> self.class_id = class_id
<ide>
<ide> def __init__(self,
<ide> dtype=None):
<ide> super(Recall, self).__init__(name=name, dtype=dtype)
<ide> self.init_thresholds = thresholds
<add> if top_k is not None and K.backend() != 'tensorflow':
<add> raise RuntimeError(
<add> '`top_k` argument for `Recall` metric is currently supported only '
<add> 'with TensorFlow backend.')
<add>
<ide> self.top_k = top_k
<ide> self.class_id = class_id
<ide>
<ide> def get_config(self):
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide>
<del>class MeanIoU(Metric):
<del> """Computes the mean Intersection-Over-Union metric.
<del>
<del> Mean Intersection-Over-Union is a common evaluation metric for semantic image
<del> segmentation, which first computes the IOU for each semantic class and then
<del> computes the average over classes. IOU is defined as follows:
<del> IOU = true_positive / (true_positive + false_positive + false_negative).
<del>
<del> The predictions are accumulated in a confusion matrix, weighted by
<del> `sample_weight` and the metric is then calculated from it.
<del>
<del> If `sample_weight` is `None`, weights default to 1.
<del> Use `sample_weight` of 0 to mask values.
<del>
<del> Usage with the compile API:
<del> ```python
<del> model = keras.Model(inputs, outputs)
<del> model.compile(
<del> 'sgd',
<del> loss='mse',
<del> metrics=[eras.metrics.MeanIoU(num_classes=2)])
<del> ```
<del>
<del> # Arguments
<del> num_classes: The possible number of labels the prediction task can have.
<del> This value must be provided, since a confusion matrix of dimension =
<del> [num_classes, num_classes] will be allocated.
<del> name: (Optional) string name of the metric instance.
<del> dtype: (Optional) data type of the metric result.
<del> """
<del>
<del> def __init__(self, num_classes, name=None, dtype=None):
<del> super(MeanIoU, self).__init__(name=name, dtype=dtype)
<del> self.num_classes = num_classes
<del>
<del> # Variable to accumulate the predictions in the confusion matrix. Setting
<del> # the type to be `float64` as required by confusion_matrix_ops.
<del> self.total_cm = self.add_weight(
<del> 'total_confusion_matrix',
<del> shape=(num_classes, num_classes),
<del> initializer='zeros',
<del> dtype='float64')
<del>
<del> def update_state(self, y_true, y_pred, sample_weight=None):
<del> y_true = K.cast(y_true, self._dtype)
<del> y_pred = K.cast(y_pred, self._dtype)
<del>
<del> # Flatten the input if its rank > 1.
<del> if y_pred.shape.ndims > 1:
<del> y_pred = K.reshape(y_pred, [-1])
<del>
<del> if y_true.shape.ndims > 1:
<del> y_true = K.reshape(y_true, [-1])
<del>
<del> if sample_weight is not None and sample_weight.shape.ndims > 1:
<del> sample_weight = K.reshape(sample_weight, [-1])
<del>
<del> # Accumulate the prediction to current confusion matrix.
<del> current_cm = confusion_matrix.confusion_matrix(
<del> y_true,
<del> y_pred,
<del> self.num_classes,
<del> weights=sample_weight,
<del> dtype=dtypes.float64)
<del>
<del> return self.total_cm.assign_add(current_cm)
<del>
<del> def result(self):
<del> """Compute the mean intersection-over-union via the confusion matrix."""
<del> sum_over_row = K.cast(
<del> K.sum(self.total_cm, axis=0), dtype=self._dtype)
<del> sum_over_col = K.cast(
<del> K.sum(self.total_cm, axis=1), dtype=self._dtype)
<del> true_positives = K.cast(
<del> array_ops.diag_part(self.total_cm), dtype=self._dtype)
<del>
<del> # sum_over_row + sum_over_col =
<del> # 2 * true_positives + false_positives + false_negatives.
<del> denominator = sum_over_row + sum_over_col - true_positives
<del>
<del> # The mean is only computed over classes that appear in the
<del> # label or prediction tensor. If the denominator is 0, we need to
<del> # ignore the class.
<del> num_valid_entries = K.sum(
<del> K.cast(K.not_equal(denominator, 0), dtype=self._dtype))
<del>
<del> denominator = K.maximum(denominator, 0)
<del> iou = K.switch(
<del> K.greater(denominator, 0),
<del> true_positives / denominator,
<del> K.zeros_like(true_positives))
<del> return K.switch(
<del> K.greater(num_valid_entries, 0),
<del> K.sum(iou) / num_valid_entries,
<del> K.zeros_like(K.sum(iou)))
<del>
<del> def reset_states(self):
<del> K.set_value(self.total_cm, np.zeros((self.num_classes, self.num_classes)))
<del>
<del> def get_config(self):
<del> config = {'num_classes': self.num_classes}
<del> base_config = super(MeanIoU, self).get_config()
<del> return dict(list(base_config.items()) + list(config.items()))
<del>
<del>
<ide> def accuracy(y_true, y_pred):
<ide> if not K.is_tensor(y_pred):
<ide> y_pred = K.constant(y_pred)
<ide> def clone_metrics(metrics):
<ide> mape = MAPE = mean_absolute_percentage_error
<ide> msle = MSLE = mean_squared_logarithmic_error
<ide> cosine = cosine_similarity = cosine_proximity
<add>MeanIoU = K.MeanIoU
<ide>
<ide>
<ide> def serialize(metric):
<ide><path>keras/utils/metrics_utils.py
<ide> def filter_top_k(x, k):
<ide> """Filters top-k values in the last dim of x and set the rest to NEG_INF.
<ide> Used for computing top-k prediction values in dense labels (which has the same
<ide> shape as predictions) for recall and precision top-k metrics.
<add>
<ide> # Arguments
<ide> x: tensor with any dimensions.
<ide> k: the number of values to keep.
<add>
<ide> # Returns
<ide> tensor with same shape and dtype as x.
<ide> """
<del> _, top_k_idx = nn_ops.top_k(x, k, sorted=False)
<add> _, top_k_idx = K.top_k(x, k, sorted=False)
<ide> top_k_mask = K.sum(
<del> K.one_hot(top_k_idx, x.shape[-1], axis=-1), axis=-2)
<add> K.one_hot(top_k_idx, x.shape[-1]), axis=-2)
<ide> return x * top_k_mask + NEG_INF * (1 - top_k_mask)
<ide>
<ide>
<ide> def weighted_assign_add(label, pred, weights, var):
<ide> def update_confusion_matrix_variables(variables_to_update,
<ide> y_true,
<ide> y_pred,
<del> thresholds,
<add> thresholds=0.5,
<ide> top_k=None,
<ide> class_id=None,
<ide> sample_weight=None):
<ide> def update_confusion_matrix_variables(variables_to_update,
<ide>
<ide> # Compare predictions and threshold.
<ide> pred_is_pos = K.greater(preds_tiled, thresh_tiled)
<del> pred_is_neg = K.greater(thresh_tiled, preds_tiled)
<ide>
<ide> # Tile labels by number of thresholds
<ide> label_is_pos = K.tile(labels_2d, [num_thresholds, 1])
<ide> def update_confusion_matrix_variables(variables_to_update,
<ide> update_fn = ConfusionMatrix.FALSE_NEGATIVES in variables_to_update
<ide>
<ide> if update_fn or update_tn:
<add> pred_is_neg = K.equal(
<add> pred_is_pos, K.zeros_like(pred_is_pos, dtype=pred_is_pos.dtype))
<ide> loop_vars[ConfusionMatrix.FALSE_NEGATIVES] = (label_is_pos, pred_is_neg)
<ide>
<ide> if update_fp or update_tn:
<ide><path>tests/keras/metrics_confusion_matrix_test.py
<ide> def test_weighted_with_threshold(self):
<ide> expected_precision = weighted_tp / weighted_positives
<ide> assert np.allclose([expected_precision, 0], K.eval(result), 1e-3)
<ide>
<del> # def test_unweighted_top_k(self):
<del> # p_obj = metrics.Precision(top_k=3)
<del> # y_pred = K.constant([0.2, 0.1, 0.5, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = p_obj(y_true, y_pred)
<del> # assert np.isclose(1. / 3, K.eval(result))
<del>
<del> # def test_weighted_top_k(self):
<del> # p_obj = metrics.Precision(top_k=3)
<del> # y_pred1 = K.constant([0.2, 0.1, 0.4, 0, 0.2], shape=(1, 5))
<del> # y_true1 = K.constant([0, 1, 1, 0, 1], shape=(1, 5))
<del> # K.eval(
<del> # p_obj(
<del> # y_true1,
<del> # y_pred1,
<del> # sample_weight=K.constant([[1, 4, 2, 3, 5]])))
<del>
<del> # y_pred2 = K.constant([0.2, 0.6, 0.4, 0.2, 0.2], shape=(1, 5))
<del> # y_true2 = K.constant([1, 0, 1, 1, 1], shape=(1, 5))
<del> # result = p_obj(y_true2, y_pred2, sample_weight=K.constant(3))
<del>
<del> # tp = (2 + 5) + (3 + 3)
<del> # predicted_positives = (1 + 2 + 5) + (3 + 3 + 3)
<del> # expected_precision = tp / predicted_positives
<del> # assert np.isclose(expected_precision, K.eval(result))
<del>
<del> # def test_unweighted_class_id(self):
<del> # p_obj = metrics.Precision(class_id=2)
<del>
<del> # y_pred = K.constant([0.2, 0.1, 0.6, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = p_obj(y_true, y_pred)
<del> # assert np.isclose(1, K.eval(result))
<del> # assert np.isclose(1, K.eval(p_obj.true_positives))
<del> # assert np.isclose(0, K.eval(p_obj.false_positives))
<del>
<del> # y_pred = K.constant([0.2, 0.1, 0, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = p_obj(y_true, y_pred)
<del> # assert np.isclose(1, K.eval(result))
<del> # assert np.isclose(1, K.eval(p_obj.true_positives))
<del> # assert np.isclose(0, K.eval(p_obj.false_positives))
<del>
<del> # y_pred = K.constant([0.2, 0.1, 0.6, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 0, 0, 0], shape=(1, 5))
<del> # result = p_obj(y_true, y_pred)
<del> # assert np.isclose(0.5, K.eval(result))
<del> # assert np.isclose(1, K.eval(p_obj.true_positives))
<del> # assert np.isclose(1, K.eval(p_obj.false_positives))
<del>
<del> # def test_unweighted_top_k_and_class_id(self):
<del> # p_obj = metrics.Precision(class_id=2, top_k=2)
<del>
<del> # y_pred = K.constant([0.2, 0.6, 0.3, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = p_obj(y_true, y_pred)
<del> # assert np.isclose(1, K.eval(result))
<del> # assert np.isclose(1, K.eval(p_obj.true_positives))
<del> # assert np.isclose(0, K.eval(p_obj.false_positives))
<del>
<del> # y_pred = K.constant([1, 1, 0.9, 1, 1], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = p_obj(y_true, y_pred)
<del> # assert np.isclose(1, K.eval(result))
<del> # assert np.isclose(1, K.eval(p_obj.true_positives))
<del> # assert np.isclose(0, K.eval(p_obj.false_positives))
<del>
<del> # def test_unweighted_top_k_and_threshold(self):
<del> # p_obj = metrics.Precision(thresholds=.7, top_k=2)
<del>
<del> # y_pred = K.constant([0.2, 0.8, 0.6, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 1], shape=(1, 5))
<del> # result = p_obj(y_true, y_pred)
<del> # assert np.isclose(1, K.eval(result))
<del> # assert np.isclose(1, K.eval(p_obj.true_positives))
<del> # assert np.isclose(0, K.eval(p_obj.false_positives))
<add> @pytest.mark.skipif(K.backend() != 'tensorflow', reason="requires tensorflow")
<add> def test_unweighted_top_k(self):
<add> p_obj = metrics.Precision(top_k=3)
<add> y_pred = K.constant([0.2, 0.1, 0.5, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = p_obj(y_true, y_pred)
<add> assert np.isclose(1. / 3, K.eval(result))
<add>
<add> @pytest.mark.skipif(K.backend() != 'tensorflow', reason="requires tensorflow")
<add> def test_weighted_top_k(self):
<add> p_obj = metrics.Precision(top_k=3)
<add> y_pred1 = K.constant([0.2, 0.1, 0.4, 0, 0.2], shape=(1, 5))
<add> y_true1 = K.constant([0, 1, 1, 0, 1], shape=(1, 5))
<add> K.eval(
<add> p_obj(
<add> y_true1,
<add> y_pred1,
<add> sample_weight=K.constant([[1, 4, 2, 3, 5]])))
<add>
<add> y_pred2 = K.constant([0.2, 0.6, 0.4, 0.2, 0.2], shape=(1, 5))
<add> y_true2 = K.constant([1, 0, 1, 1, 1], shape=(1, 5))
<add> result = p_obj(y_true2, y_pred2, sample_weight=K.constant(3))
<add>
<add> tp = (2 + 5) + (3 + 3)
<add> predicted_positives = (1 + 2 + 5) + (3 + 3 + 3)
<add> expected_precision = tp / predicted_positives
<add> assert np.isclose(expected_precision, K.eval(result))
<add>
<add> def test_unweighted_class_id(self):
<add> p_obj = metrics.Precision(class_id=2)
<add>
<add> y_pred = K.constant([0.2, 0.1, 0.6, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = p_obj(y_true, y_pred)
<add> assert np.isclose(1, K.eval(result))
<add> assert np.isclose(1, K.eval(p_obj.true_positives))
<add> assert np.isclose(0, K.eval(p_obj.false_positives))
<add>
<add> y_pred = K.constant([0.2, 0.1, 0, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = p_obj(y_true, y_pred)
<add> assert np.isclose(1, K.eval(result))
<add> assert np.isclose(1, K.eval(p_obj.true_positives))
<add> assert np.isclose(0, K.eval(p_obj.false_positives))
<add>
<add> y_pred = K.constant([0.2, 0.1, 0.6, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 0, 0, 0], shape=(1, 5))
<add> result = p_obj(y_true, y_pred)
<add> assert np.isclose(0.5, K.eval(result))
<add> assert np.isclose(1, K.eval(p_obj.true_positives))
<add> assert np.isclose(1, K.eval(p_obj.false_positives))
<add>
<add> @pytest.mark.skipif(K.backend() != 'tensorflow', reason="requires tensorflow")
<add> def test_unweighted_top_k_and_class_id(self):
<add> p_obj = metrics.Precision(class_id=2, top_k=2)
<add>
<add> y_pred = K.constant([0.2, 0.6, 0.3, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = p_obj(y_true, y_pred)
<add> assert np.isclose(1, K.eval(result))
<add> assert np.isclose(1, K.eval(p_obj.true_positives))
<add> assert np.isclose(0, K.eval(p_obj.false_positives))
<add>
<add> y_pred = K.constant([1, 1, 0.9, 1, 1], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = p_obj(y_true, y_pred)
<add> assert np.isclose(1, K.eval(result))
<add> assert np.isclose(1, K.eval(p_obj.true_positives))
<add> assert np.isclose(0, K.eval(p_obj.false_positives))
<add>
<add> @pytest.mark.skipif(K.backend() != 'tensorflow', reason="requires tensorflow")
<add> def test_unweighted_top_k_and_threshold(self):
<add> p_obj = metrics.Precision(thresholds=.7, top_k=2)
<add>
<add> y_pred = K.constant([0.2, 0.8, 0.6, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 1], shape=(1, 5))
<add> result = p_obj(y_true, y_pred)
<add> assert np.isclose(1, K.eval(result))
<add> assert np.isclose(1, K.eval(p_obj.true_positives))
<add> assert np.isclose(0, K.eval(p_obj.false_positives))
<ide>
<ide>
<ide> class TestRecall(object):
<ide> def test_weighted_with_threshold(self):
<ide> expected_recall = weighted_tp / weighted_positives
<ide> assert np.allclose([expected_recall, 0], K.eval(result), 1e-3)
<ide>
<del> # def test_unweighted_top_k(self):
<del> # r_obj = metrics.Recall(top_k=3)
<del> # y_pred = K.constant([0.2, 0.1, 0.5, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = r_obj(y_true, y_pred)
<del> # assert np.isclose(0.5, K.eval(result))
<del>
<del> # def test_weighted_top_k(self):
<del> # r_obj = metrics.Recall(top_k=3)
<del> # y_pred1 = K.constant([0.2, 0.1, 0.4, 0, 0.2], shape=(1, 5))
<del> # y_true1 = K.constant([0, 1, 1, 0, 1], shape=(1, 5))
<del> # K.eval(
<del> # r_obj(
<del> # y_true1,
<del> # y_pred1,
<del> # sample_weight=K.constant([[1, 4, 2, 3, 5]])))
<del>
<del> # y_pred2 = K.constant([0.2, 0.6, 0.4, 0.2, 0.2], shape=(1, 5))
<del> # y_true2 = K.constant([1, 0, 1, 1, 1], shape=(1, 5))
<del> # result = r_obj(y_true2, y_pred2, sample_weight=K.constant(3))
<del>
<del> # tp = (2 + 5) + (3 + 3)
<del> # positives = (4 + 2 + 5) + (3 + 3 + 3 + 3)
<del> # expected_recall = tp / positives
<del> # assert np.isclose(expected_recall, K.eval(result))
<del>
<del> # def test_unweighted_class_id(self):
<del> # r_obj = metrics.Recall(class_id=2)
<del>
<del> # y_pred = K.constant([0.2, 0.1, 0.6, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = r_obj(y_true, y_pred)
<del> # assert np.isclose(1, K.eval(result))
<del> # assert np.isclose(1, K.eval(r_obj.true_positives))
<del> # assert np.isclose(0, K.eval(r_obj.false_negatives))
<del>
<del> # y_pred = K.constant([0.2, 0.1, 0, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = r_obj(y_true, y_pred)
<del> # assert np.isclose(0.5, K.eval(result))
<del> # assert np.isclose(1, K.eval(r_obj.true_positives))
<del> # assert np.isclose(1, K.eval(r_obj.false_negatives))
<del>
<del> # y_pred = K.constant([0.2, 0.1, 0.6, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 0, 0, 0], shape=(1, 5))
<del> # result = r_obj(y_true, y_pred)
<del> # assert np.isclose(0.5, K.eval(result))
<del> # assert np.isclose(1, K.eval(r_obj.true_positives))
<del> # assert np.isclose(1, K.eval(r_obj.false_negatives))
<del>
<del> # def test_unweighted_top_k_and_class_id(self):
<del> # r_obj = metrics.Recall(class_id=2, top_k=2)
<del>
<del> # y_pred = K.constant([0.2, 0.6, 0.3, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = r_obj(y_true, y_pred)
<del> # assert np.isclose(1, K.eval(result))
<del> # assert np.isclose(1, K.eval(r_obj.true_positives))
<del> # assert np.isclose(0, K.eval(r_obj.false_negatives))
<del>
<del> # y_pred = K.constant([1, 1, 0.9, 1, 1], shape=(1, 5))
<del> # y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<del> # result = r_obj(y_true, y_pred)
<del> # assert np.isclose(0.5, K.eval(result))
<del> # assert np.isclose(1, K.eval(r_obj.true_positives))
<del> # assert np.isclose(1, K.eval(r_obj.false_negatives))
<del>
<del> # def test_unweighted_top_k_and_threshold(self):
<del> # r_obj = metrics.Recall(thresholds=.7, top_k=2)
<del>
<del> # y_pred = K.constant([0.2, 0.8, 0.6, 0, 0.2], shape=(1, 5))
<del> # y_true = K.constant([1, 1, 1, 0, 1], shape=(1, 5))
<del> # result = r_obj(y_true, y_pred)
<del> # assert np.isclose(0.25, K.eval(result))
<del> # assert np.isclose(1, K.eval(r_obj.true_positives))
<del> # assert np.isclose(3, K.eval(r_obj.false_negatives))
<add> @pytest.mark.skipif(K.backend() != 'tensorflow', reason="requires tensorflow")
<add> def test_unweighted_top_k(self):
<add> r_obj = metrics.Recall(top_k=3)
<add> y_pred = K.constant([0.2, 0.1, 0.5, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = r_obj(y_true, y_pred)
<add> assert np.isclose(0.5, K.eval(result))
<add>
<add> @pytest.mark.skipif(K.backend() != 'tensorflow', reason="requires tensorflow")
<add> def test_weighted_top_k(self):
<add> r_obj = metrics.Recall(top_k=3)
<add> y_pred1 = K.constant([0.2, 0.1, 0.4, 0, 0.2], shape=(1, 5))
<add> y_true1 = K.constant([0, 1, 1, 0, 1], shape=(1, 5))
<add> K.eval(
<add> r_obj(
<add> y_true1,
<add> y_pred1,
<add> sample_weight=K.constant([[1, 4, 2, 3, 5]])))
<add>
<add> y_pred2 = K.constant([0.2, 0.6, 0.4, 0.2, 0.2], shape=(1, 5))
<add> y_true2 = K.constant([1, 0, 1, 1, 1], shape=(1, 5))
<add> result = r_obj(y_true2, y_pred2, sample_weight=K.constant(3))
<add>
<add> tp = (2 + 5) + (3 + 3)
<add> positives = (4 + 2 + 5) + (3 + 3 + 3 + 3)
<add> expected_recall = tp / positives
<add> assert np.isclose(expected_recall, K.eval(result))
<add>
<add> def test_unweighted_class_id(self):
<add> r_obj = metrics.Recall(class_id=2)
<add>
<add> y_pred = K.constant([0.2, 0.1, 0.6, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = r_obj(y_true, y_pred)
<add> assert np.isclose(1, K.eval(result))
<add> assert np.isclose(1, K.eval(r_obj.true_positives))
<add> assert np.isclose(0, K.eval(r_obj.false_negatives))
<add>
<add> y_pred = K.constant([0.2, 0.1, 0, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = r_obj(y_true, y_pred)
<add> assert np.isclose(0.5, K.eval(result))
<add> assert np.isclose(1, K.eval(r_obj.true_positives))
<add> assert np.isclose(1, K.eval(r_obj.false_negatives))
<add>
<add> y_pred = K.constant([0.2, 0.1, 0.6, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 0, 0, 0], shape=(1, 5))
<add> result = r_obj(y_true, y_pred)
<add> assert np.isclose(0.5, K.eval(result))
<add> assert np.isclose(1, K.eval(r_obj.true_positives))
<add> assert np.isclose(1, K.eval(r_obj.false_negatives))
<add>
<add> @pytest.mark.skipif(K.backend() != 'tensorflow', reason="requires tensorflow")
<add> def test_unweighted_top_k_and_class_id(self):
<add> r_obj = metrics.Recall(class_id=2, top_k=2)
<add>
<add> y_pred = K.constant([0.2, 0.6, 0.3, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = r_obj(y_true, y_pred)
<add> assert np.isclose(1, K.eval(result))
<add> assert np.isclose(1, K.eval(r_obj.true_positives))
<add> assert np.isclose(0, K.eval(r_obj.false_negatives))
<add>
<add> y_pred = K.constant([1, 1, 0.9, 1, 1], shape=(1, 5))
<add> y_true = K.constant([0, 1, 1, 0, 0], shape=(1, 5))
<add> result = r_obj(y_true, y_pred)
<add> assert np.isclose(0.5, K.eval(result))
<add> assert np.isclose(1, K.eval(r_obj.true_positives))
<add> assert np.isclose(1, K.eval(r_obj.false_negatives))
<add>
<add> @pytest.mark.skipif(K.backend() != 'tensorflow', reason="requires tensorflow")
<add> def test_unweighted_top_k_and_threshold(self):
<add> r_obj = metrics.Recall(thresholds=.7, top_k=2)
<add>
<add> y_pred = K.constant([0.2, 0.8, 0.6, 0, 0.2], shape=(1, 5))
<add> y_true = K.constant([1, 1, 1, 0, 1], shape=(1, 5))
<add> result = r_obj(y_true, y_pred)
<add> assert np.isclose(0.25, K.eval(result))
<add> assert np.isclose(1, K.eval(r_obj.true_positives))
<add> assert np.isclose(3, K.eval(r_obj.false_negatives))
<add>
<add>
<add>@pytest.mark.skipif(K.backend() != 'tensorflow', reason="requires tensorflow")
<add>class TestMeanIoU(object):
<add>
<add> def test_config(self):
<add> m_obj = metrics.MeanIoU(num_classes=2, name='mean_iou')
<add> assert m_obj.name == 'mean_iou'
<add> assert m_obj.num_classes == 2
<add>
<add> m_obj2 = metrics.MeanIoU.from_config(m_obj.get_config())
<add> assert m_obj2.name == 'mean_iou'
<add> assert m_obj2.num_classes == 2
<add>
<add> def test_unweighted(self):
<add> y_pred = K.constant([0, 1, 0, 1], shape=(1, 4))
<add> y_true = K.constant([0, 0, 1, 1], shape=(1, 4))
<add>
<add> m_obj = metrics.MeanIoU(num_classes=2)
<add> result = m_obj(y_true, y_pred)
<add>
<add> # cm = [[1, 1],
<add> # [1, 1]]
<add> # sum_row = [2, 2], sum_col = [2, 2], true_positives = [1, 1]
<add> # iou = true_positives / (sum_row + sum_col - true_positives))
<add> expected_result = (1 / (2 + 2 - 1) + 1 / (2 + 2 - 1)) / 2
<add> assert np.allclose(K.eval(result), expected_result, atol=1e-3)
<add>
<add> def test_weighted(self):
<add> y_pred = K.constant([0, 1, 0, 1], dtype='float32')
<add> y_true = K.constant([0, 0, 1, 1])
<add> sample_weight = K.constant([0.2, 0.3, 0.4, 0.1])
<add>
<add> m_obj = metrics.MeanIoU(num_classes=2)
<add> result = m_obj(y_true, y_pred, sample_weight=sample_weight)
<add>
<add> # cm = [[0.2, 0.3],
<add> # [0.4, 0.1]]
<add> # sum_row = [0.6, 0.4], sum_col = [0.5, 0.5], true_positives = [0.2, 0.1]
<add> # iou = true_positives / (sum_row + sum_col - true_positives))
<add> expected_result = (0.2 / (0.6 + 0.5 - 0.2) + 0.1 / (0.4 + 0.5 - 0.1)) / 2
<add> assert np.allclose(K.eval(result), expected_result, atol=1e-3)
<add>
<add> def test_multi_dim_input(self):
<add> y_pred = K.constant([[0, 1], [0, 1]], dtype='float32')
<add> y_true = K.constant([[0, 0], [1, 1]])
<add> sample_weight = K.constant([[0.2, 0.3], [0.4, 0.1]])
<add>
<add> m_obj = metrics.MeanIoU(num_classes=2)
<add> result = m_obj(y_true, y_pred, sample_weight=sample_weight)
<add>
<add> # cm = [[0.2, 0.3],
<add> # [0.4, 0.1]]
<add> # sum_row = [0.6, 0.4], sum_col = [0.5, 0.5], true_positives = [0.2, 0.1]
<add> # iou = true_positives / (sum_row + sum_col - true_positives))
<add> expected_result = (0.2 / (0.6 + 0.5 - 0.2) + 0.1 / (0.4 + 0.5 - 0.1)) / 2
<add> assert np.allclose(K.eval(result), expected_result, atol=1e-3)
<add>
<add> def test_zero_valid_entries(self):
<add> m_obj = metrics.MeanIoU(num_classes=2)
<add> assert np.allclose(K.eval(m_obj.result()), 0, atol=1e-3)
<add>
<add> def test_zero_and_non_zero_entries(self):
<add> y_pred = K.constant([1], dtype='float32')
<add> y_true = K.constant([1])
<add>
<add> m_obj = metrics.MeanIoU(num_classes=2)
<add> result = m_obj(y_true, y_pred)
<add>
<add> # cm = [[0, 0],
<add> # [0, 1]]
<add> # sum_row = [0, 1], sum_col = [0, 1], true_positives = [0, 1]
<add> # iou = true_positives / (sum_row + sum_col - true_positives))
<add> expected_result = (0 + 1 / (1 + 1 - 1)) / 1
<add> assert np.allclose(K.eval(result), expected_result, atol=1e-3) | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.