content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Ruby | Ruby | add inflight checks and server shutdown | b22c4e2a1cc0d8d094e19b5901908ace54cd812e | <ide><path>activesupport/lib/active_support/testing/parallel_server.rb
<del># frozen_string_literal: true
<del>
<del>require "drb"
<del>require "drb/unix" unless Gem.win_platform?
<del>
<del>module ActiveSupport
<del> module Testing
<del> class Parallelization # :nodoc:
<del> class Server
<del> include DRb::DRbUndumped
<del>
<del> def initialize
<del> @queue = Queue.new
<del> end
<del>
<del> def record(reporter, result)
<del> raise DRb::DRbConnError if result.is_a?(DRb::DRbUnknown)
<del>
<del> reporter.synchronize do
<del> reporter.record(result)
<del> end
<del> end
<del>
<del> def <<(o)
<del> o[2] = DRbObject.new(o[2]) if o
<del> @queue << o
<del> end
<del>
<del> def length
<del> @queue.length
<del> end
<del>
<del> def pop; @queue.pop; end
<del> end
<del> end
<del> end
<del>end
<ide><path>activesupport/lib/active_support/testing/parallelization.rb
<ide> require "drb"
<ide> require "drb/unix" unless Gem.win_platform?
<ide> require "active_support/core_ext/module/attribute_accessors"
<del>require "active_support/testing/parallel_server"
<del>require "active_support/testing/parallel_worker"
<add>require "active_support/testing/parallelization/server"
<add>require "active_support/testing/parallelization/worker"
<ide>
<ide> module ActiveSupport
<ide> module Testing
<ide> class Parallelization # :nodoc:
<add> @@after_fork_hooks = []
<add>
<add> def self.after_fork_hook(&blk)
<add> @@after_fork_hooks << blk
<add> end
<add>
<add> cattr_reader :after_fork_hooks
<add>
<add> @@run_cleanup_hooks = []
<add>
<add> def self.run_cleanup_hook(&blk)
<add> @@run_cleanup_hooks << blk
<add> end
<add>
<add> cattr_reader :run_cleanup_hooks
<add>
<ide> def initialize(worker_count)
<ide> @worker_count = worker_count
<del> @queue = Server.new
<del> @pool = []
<del>
<del> @url = DRb.start_service("drbunix:", @queue).uri
<add> @queue_server = Server.new
<add> @worker_pool = []
<add> @url = DRb.start_service("drbunix:", @queue_server).uri
<ide> end
<ide>
<ide> def start
<del> @pool = @worker_count.times.map do |worker|
<add> @worker_pool = @worker_count.times.map do |worker|
<ide> Worker.new(worker, @url).start
<ide> end
<ide> end
<ide>
<ide> def <<(work)
<del> @queue << work
<add> @queue_server << work
<ide> end
<ide>
<ide> def shutdown
<del> @worker_count.times { @queue << nil }
<del> @pool.each { |pid| Process.waitpid pid }
<del>
<del> if @queue.length > 0
<del> raise "Queue not empty, but all workers have finished. This probably means that a worker crashed and #{@queue.length} tests were missed."
<del> end
<add> @queue_server.shutdown
<add> @worker_pool.each { |pid| Process.waitpid pid }
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/testing/parallelization/server.rb
<add># frozen_string_literal: true
<add>
<add>require "drb"
<add>require "drb/unix" unless Gem.win_platform?
<add>
<add>module ActiveSupport
<add> module Testing
<add> class Parallelization # :nodoc:
<add> class Server
<add> include DRb::DRbUndumped
<add>
<add> def initialize
<add> @queue = Queue.new
<add> @active_workers = Concurrent::Map.new
<add> @in_flight = Concurrent::Map.new
<add> end
<add>
<add> def record(reporter, result)
<add> raise DRb::DRbConnError if result.is_a?(DRb::DRbUnknown)
<add>
<add> @in_flight.delete([result.klass, result.name])
<add>
<add> reporter.synchronize do
<add> reporter.record(result)
<add> end
<add> end
<add>
<add> def <<(o)
<add> o[2] = DRbObject.new(o[2]) if o
<add> @queue << o
<add> end
<add>
<add> def pop
<add> if test = @queue.pop
<add> @in_flight[[test[0].to_s, test[1]]] = test
<add> test
<add> end
<add> end
<add>
<add> def start_worker(worker_id)
<add> @active_workers[worker_id] = true
<add> end
<add>
<add> def stop_worker(worker_id)
<add> @active_workers.delete(worker_id)
<add> end
<add>
<add> def active_workers?
<add> @active_workers.size > 0
<add> end
<add>
<add> def shutdown
<add> # Wait for initial queue to drain
<add> while @queue.length != 0
<add> sleep 0.1
<add> end
<add>
<add> @queue.close
<add>
<add> # Wait until all workers have finished
<add> while active_workers?
<add> sleep 0.1
<add> end
<add>
<add> @in_flight.values.each do |(klass, name, reporter)|
<add> result = Minitest::Result.from(klass.new(name))
<add> error = RuntimeError.new("result not reported")
<add> error.set_backtrace([""])
<add> result.failures << Minitest::UnexpectedError.new(error)
<add> reporter.synchronize do
<add> reporter.record(result)
<add> end
<add> end
<add> end
<add> end
<add> end
<add> end
<add>end
<add><path>activesupport/lib/active_support/testing/parallelization/worker.rb
<del><path>activesupport/lib/active_support/testing/parallel_worker.rb
<add># frozen_string_literal: true
<add>
<ide> module ActiveSupport
<ide> module Testing
<ide> class Parallelization # :nodoc:
<ide> class Worker
<del> def initialize(id, url)
<del> @id = id
<add> def initialize(number, url)
<add> @id = SecureRandom.uuid
<add> @number = number
<ide> @url = url
<ide> @title = "Rails test worker #{@id}"
<ide> @setup_exception = nil
<ide> def start
<ide>
<ide> DRb.stop_service
<ide>
<add> @queue = DRbObject.new_with_uri(@url)
<add> @queue.start_worker(@id)
<add>
<ide> begin
<ide> after_fork
<ide> rescue => @setup_exception; end
<ide>
<del> @queue = DRbObject.new_with_uri(@url)
<del>
<ide> work_from_queue
<ide> ensure
<ide> Process.setproctitle("#{@title} - (stopping)")
<ide>
<ide> run_cleanup
<add> @queue.stop_worker(@id)
<ide> end
<ide> end
<ide>
<ide> def safe_record(reporter, result)
<ide> Process.setproctitle("#{@title} - (idle)")
<ide> end
<ide>
<del> @@after_fork_hooks = []
<del>
<del> def self.after_fork_hook(&blk)
<del> @@after_fork_hooks << blk
<del> end
<del>
<del> cattr_reader :after_fork_hooks
<del>
<del> @@run_cleanup_hooks = []
<del>
<del> def self.run_cleanup_hook(&blk)
<del> @@run_cleanup_hooks << blk
<del> end
<del>
<del> cattr_reader :run_cleanup_hooks
<del>
<ide> def after_fork
<del> self.class.after_fork_hooks.each do |cb|
<add> Parallelization.after_fork_hooks.each do |cb|
<ide> cb.call(@id)
<ide> end
<ide> end
<ide>
<ide> def run_cleanup
<del> self.class.run_cleanup_hooks.each do |cb|
<add> Parallelization.run_cleanup_hooks.each do |cb|
<ide> cb.call(@id)
<ide> end
<ide> end
<ide><path>railties/test/application/test_runner_test.rb
<ide> def test_crash
<ide>
<ide> output = run_test_command(file_name)
<ide>
<del> assert_match %r{Queue not empty, but all workers have finished. This probably means that a worker crashed and 1 tests were missed.}, output
<add> assert_match %r{RuntimeError: result not reported}, output
<ide> end
<ide>
<ide> def test_run_in_parallel_with_threads | 5 |
Text | Text | clarify docker attach | da1dbd2093ec040f05f4daf9fc8ca28dc8262ec8 | <ide><path>docs/reference/commandline/attach.md
<ide> using `CTRL-p CTRL-q` key sequence.
<ide> It is forbidden to redirect the standard input of a `docker attach` command
<ide> while attaching to a tty-enabled container (i.e.: launched with `-t`).
<ide>
<add>While a client is connected to container's stdio using `docker attach`, Docker
<add>uses a ~1MB memory buffer to maximize the throughput of the application. If
<add>this buffer is filled, the speed of the API connection will start to have an
<add>effect on the process output writing speed. This is similar to other
<add>applications like SSH. Because of this, it is not recommended to run
<add>performance critical applications that generate a lot of output in the
<add>foreground over a slow client connection. Instead, users should use the
<add>`docker logs` command to get access to the logs.
<add>
<ide>
<ide> ## Override the detach sequence
<ide> | 1 |
Ruby | Ruby | fix unused variable | 9d1573c0405ead882a38d2bb70cfd66f76c06ccf | <ide><path>Library/Homebrew/compat/hbc/cli.rb
<ide> class CLI
<ide> EOS
<ide> end)
<ide>
<del> option "--caskroom=PATH", (lambda do |value|
<add> option "--caskroom=PATH", (lambda do |*|
<ide> odisabled "`brew cask` with the `--caskroom` flag"
<ide> end)
<ide> end | 1 |
PHP | PHP | add postgres table escaping and regression test | f55331d0f47415e4da6d6bf0fc0f1f4f950acd60 | <ide><path>src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php
<ide> public function compileDropIfExists(Blueprint $blueprint, Fluent $command)
<ide> */
<ide> public function compileDropAllTables($tables)
<ide> {
<del> return 'drop table '.implode(',', $tables).' cascade';
<add> return 'drop table "'.implode('","', $tables).'" cascade';
<ide> }
<ide>
<ide> /**
<ide><path>tests/Database/DatabasePostgresSchemaGrammarTest.php
<ide> public function testAddingMacAddress()
<ide> $this->assertEquals('alter table "users" add column "foo" macaddr not null', $statements[0]);
<ide> }
<ide>
<add> public function testDropAllTablesEscapesTableNames()
<add> {
<add> $statement = $this->getGrammar()->compileDropAllTables(['alpha', 'beta', 'gamma']);
<add>
<add> $this->assertEquals('drop table "alpha","beta","gamma" cascade', $statement);
<add> }
<add>
<ide> protected function getConnection()
<ide> {
<ide> return m::mock('Illuminate\Database\Connection'); | 2 |
Javascript | Javascript | remove unused modules | fdeb862f2bc41d6d26e2fae8c588c4fc698e0cae | <ide><path>lib/_http_client.js
<ide> const util = require('util');
<ide> const net = require('net');
<ide> const url = require('url');
<del>const EventEmitter = require('events');
<ide> const HTTPParser = process.binding('http_parser').HTTPParser;
<ide> const assert = require('assert').ok;
<ide> const common = require('_http_common');
<ide><path>lib/os.js
<ide> 'use strict';
<ide>
<ide> const binding = process.binding('os');
<del>const util = require('util');
<ide> const internalUtil = require('internal/util');
<ide> const isWindows = process.platform === 'win32';
<ide>
<ide><path>lib/tty.js
<ide> 'use strict';
<ide>
<ide> const util = require('util');
<del>const internalUtil = require('internal/util');
<ide> const net = require('net');
<ide> const TTY = process.binding('tty_wrap').TTY;
<ide> const isTTY = process.binding('tty_wrap').isTTY; | 3 |
Python | Python | fix bug in blackman docstring | 1cf7e661bced0b4ea3ea2e4fa1a4d08dc271e83c | <ide><path>numpy/lib/function_base.py
<ide> def bartlett(M):
<ide> >>> response = 20*log10(mag)
<ide> >>> response = clip(response,-100,100)
<ide> >>> plt.plot(freq, response)
<del> >>> plt.title("Frequency response of Bartlett window")
<add> >>> plt.title("Frequency response of Blackman window")
<ide> >>> plt.ylabel("Magnitude [dB]")
<ide> >>> plt.xlabel("Normalized frequency [cycles per sample]")
<ide> >>> plt.axis('tight') | 1 |
Text | Text | impose moratorium on remote registry access | 24f7d0afc9b62da1684e5bf9998ad927aec37cb0 | <ide><path>ROADMAP.md
<ide> lacking for many, we cannot make it a priority yet for the above reasons.
<ide>
<ide> Again, this is not about saying that the Dockerfile syntax is done, it's about making choices about
<ide> what we want to do first!
<add>
<add>## 2.3 Remote Registry Operations
<add>
<add>A large amount of work is ongoing in the area of image distribution and
<add>provenance. This includes moving to the V2 Registry API and heavily
<add>refactoring the code that powers these features. The desired result is more
<add>secure, reliable and easier to use image distribution.
<add>
<add>Part of the problem with this part of the code base is the lack of a stable
<add>and flexible interface. If new features are added that access the registry
<add>without solidifying these interfaces, achieving feature parity will continue
<add>to be elusive. While we get a handle on this situation, we are imposing a
<add>moratorium on new code that accesses the Registry API in commands that don't
<add>already make remote calls.
<add>
<add>Currently, only the following commands cause interaction with a remote
<add>registry:
<add>
<add>- push
<add>- pull
<add>- run
<add>- build
<add>- search
<add>- login
<add>
<add>In the interest of stabilizing the registry access model during this ongoing
<add>work, we are not accepting additions to other commands that will cause remote
<add>interaction with the Registry API. This moratorium will lift when the goals of
<add>the distribution project have been met. | 1 |
Javascript | Javascript | remove applyastemplate function | 5050eed9bfb31b326b65ccec6040ae3bf7fdc0ca | <ide><path>lib/dependencies/ModuleDependencyTemplateAsRequireId.js
<ide> class ModuleDependencyTemplateAsRequireId {
<ide> content = require("./WebpackMissingModule").module(dep.request);
<ide> source.replace(dep.range[0], dep.range[1] - 1, content);
<ide> }
<del>
<del> applyAsTemplateArgument(name, dep, source) {
<del> if(!dep.range) return;
<del> source.replace(dep.range[0], dep.range[1] - 1, "(__webpack_require__(" + name + "))");
<del> }
<ide> }
<ide> module.exports = ModuleDependencyTemplateAsRequireId; | 1 |
Ruby | Ruby | restore test deliveries for actionmailer | 64edb6cb19863ab78ecea88cf15ed5fd19046ab6 | <ide><path>actionpack/test/controller/assert_select_test.rb
<ide> def xml()
<ide>
<ide> def setup
<ide> super
<add> @old_delivery_method = ActionMailer::Base.delivery_method
<add> @old_perform_deliveries = ActionMailer::Base.perform_deliveries
<ide> ActionMailer::Base.delivery_method = :test
<ide> ActionMailer::Base.perform_deliveries = true
<del> ActionMailer::Base.deliveries = []
<ide> end
<ide>
<ide> def teardown
<ide> super
<add> ActionMailer::Base.delivery_method = @old_delivery_method
<add> ActionMailer::Base.perform_deliveries = @old_perform_deliveries
<ide> ActionMailer::Base.deliveries.clear
<ide> end
<ide> | 1 |
Javascript | Javascript | remove fellback in width/height csshook | d66c3b6d84c2af1132727c5be335bc2860dcbda9 | <ide><path>src/css.js
<ide> jQuery.curCSS = jQuery.css;
<ide> jQuery.each(["height", "width"], function( i, name ) {
<ide> jQuery.cssHooks[ name ] = {
<ide> get: function( elem, computed, extra ) {
<del> var val, fellback = false;
<add> var val;
<ide>
<ide> if ( computed ) {
<ide> if ( elem.offsetWidth !== 0 ) { | 1 |
Javascript | Javascript | remove compiled coffee file from src dir | dd1e617a41720e50ca8e9747a1e2526f927812c8 | <ide><path>spec/app/range-spec.js
<del>(function() {
<del> var Point, Range;
<del>
<del> Range = require('range');
<del>
<del> Point = require('point');
<del>
<del> describe("Range", function() {
<del> describe("constructor", function() {
<del> return it("ensures that @start <= @end", function() {
<del> var range1, range2;
<del> range1 = new Range(new Point(0, 1), new Point(0, 4));
<del> expect(range1.start).toEqual({
<del> row: 0,
<del> column: 1
<del> });
<del> range2 = new Range(new Point(1, 4), new Point(0, 1));
<del> return expect(range2.start).toEqual({
<del> row: 0,
<del> column: 1
<del> });
<del> });
<del> });
<del> describe(".isEmpty()", function() {
<del> return it("returns true if @start equals @end", function() {
<del> expect(new Range(new Point(1, 1), new Point(1, 1)).isEmpty()).toBeTruthy();
<del> return expect(new Range(new Point(1, 1), new Point(1, 2)).isEmpty()).toBeFalsy();
<del> });
<del> });
<del> return describe(".intersectsWith(otherRange)", function() {
<del> return fit("returns the intersection of the two ranges", function() {
<del> var range1, range2;
<del> range1 = new Range([1, 1], [2, 10]);
<del> range2 = new Range([2, 1], [3, 10]);
<del> expect(range1.intersectsWith(range2)).toBeTruth;
<del> range2 = range1 = new Range([2, 1], [3, 10]);
<del> return expect(range1.intersectsWith(range2)).toBeTruth;
<del> });
<del> });
<del> });
<del>
<del>}).call(this); | 1 |
Javascript | Javascript | add desktop.ini to ignored names | 5301c556698c68432f74511dd00f2b98f350efe8 | <ide><path>src/config-schema.js
<ide> const configSchema = {
<ide> properties: {
<ide> ignoredNames: {
<ide> type: 'array',
<del> default: ['.git', '.hg', '.svn', '.DS_Store', '._*', 'Thumbs.db'],
<add> default: ['.git', '.hg', '.svn', '.DS_Store', '._*', 'Thumbs.db', 'desktop.ini'],
<ide> items: {
<ide> type: 'string'
<ide> }, | 1 |
Text | Text | translate 2 docs into japanese | 574b906f9b43a78fbd4759a25e95b2fd036c749c | <ide><path>docs/docs/getting-started.jp.md
<add>---
<add>id: getting-started-ja
<add>title: 始めてみましょう
<add>next: tutorial-ja.html
<add>redirect_from: "docs/index-ja.html"
<add>---
<add>
<add>## JSFiddle
<add>
<add>React でのハッキングを始めるにあたり、一番簡単なものとして次の JSFiddle で動いている Hello World の例を取り上げます。
<add>
<add> * **[React JSFiddle](http://jsfiddle.net/reactjs/69z2wepo/)**
<add> * [React JSFiddle without JSX](http://jsfiddle.net/reactjs/5vjqabv3/)
<add>
<add>## スターターキット
<add>
<add>始めるためにスターターキットをダウンロードしましょう。
<add>
<add><div class="buttons-unit downloads">
<add> <a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
<add> Download Starter Kit {{site.react_version}}
<add> </a>
<add></div>
<add>
<add>スターターキットのルートディレクトリに `helloworld.html` を作り、次のように書いてみましょう。
<add>```html
<add><!DOCTYPE html>
<add><html>
<add> <head>
<add> <script src="build/react.js"></script>
<add> <script src="build/JSXTransformer.js"></script>
<add> </head>
<add> <body>
<add> <div id="example"></div>
<add> <script type="text/jsx">
<add> React.render(
<add> <h1>Hello, world!</h1>,
<add> document.getElementById('example')
<add> );
<add> </script>
<add> </body>
<add></html>
<add>```
<add>
<add>JavaScript の中に書かれた XML シンタックスは JSX と呼ばれるものです(JSX の詳しいことについては [JSX syntax](/react/docs/jsx-in-depth.html) を読んでください)。ここでは JSX から vanilla JavaScript への変換をブラウザ内で行わせるため、先程のコードには `<script type="text/jsx">` と書いており、加えて `JSXTransformer.js` を読み込ませています。
<add>
<add>### ファイルの分割
<add>
<add>React の JSX コードは別ファイルに分離することができます。 次のような `src/helloworld.js` を作ってみましょう。
<add>
<add>```javascript
<add>React.render(
<add> <h1>Hello, world!</h1>,
<add> document.getElementById('example')
<add>);
<add>```
<add>
<add>それが終わったら、`helloworld.js` への参照を `helloworld.html` に書き込みましょう。
<add>
<add>```html{10}
<add><script type="text/jsx" src="src/helloworld.js"></script>
<add>```
<add>
<add>### オフラインでの変換
<add>
<add>まずはコマンドラインツールをインストールしましょう([npm](http://npmjs.org/) が必要です)。
<add>
<add>```
<add>npm install -g react-tools
<add>```
<add>
<add>インストールが終わったら、先程書いた `src/helloworld.js` ファイルを生の JavaScript に変換してみましょう。
<add>
<add>```
<add>jsx --watch src/ build/
<add>
<add>```
<add>
<add>すると、`src/helloword.js` に変更を加えるごとに `build/helloworld.js` が自動で生成されるようになります。
<add>
<add>```javascript{2}
<add>React.render(
<add> React.createElement('h1', null, 'Hello, world!'),
<add> document.getElementById('example')
<add>);
<add>```
<add>
<add>
<add>最後に HTML ファイルを以下のように書き換えましょう。
<add>
<add>```html{6,10}
<add><!DOCTYPE html>
<add><html>
<add> <head>
<add> <title>Hello React!</title>
<add> <script src="build/react.js"></script>
<add> <!-- JSXTransformer は必要ありません! -->
<add> </head>
<add> <body>
<add> <div id="example"></div>
<add> <script src="build/helloworld.js"></script>
<add> </body>
<add></html>
<add>```
<add>
<add>## CommonJS を使うには
<add>
<add>React を [browserify](http://browserify.org/) や [webpack](http://webpack.github.io/)、または CommonJS 準拠の他のモジュールシステムと一緒に使いたい場合、 [`react` npm package](https://www.npmjs.org/package/react) を使ってみてください。また、`jsx` ビルドツールをパッケージングシステム(CommonJS に限らず)に導入することも非常に簡単です。
<add>
<add>## 次にすること
<add>
<add>[チュートリアル](/react/docs/tutorial.html) や、スターターキットの `examples` ディレクトリに入っている他の例を読んでみてください。
<add>
<add>また、[ワークフロー、UIコンポーネント、ルーティング、データマネジメントなど](https://github.com/facebook/react/wiki/Complementary-Tools)の方面で貢献しているコミュニティの wiki もあります。
<add>
<add>幸運を祈ります!React へようこそ!
<ide><path>docs/docs/tutorial.jp.md
<add>---
<add>id: tutorial
<add>title: チュートリアル
<add>prev: getting-started-ja.html
<add>next: thinking-in-react-ja.html
<add>---
<add>
<add>これから、シンプルながらも現実的なコメントボックスを作ってみましょう。ブログにも設置できるようなもので、Disqus や LiveFyre、Facebook comments が採用しているリアルタイムコメントの基本機能を備えたものを想定しています。
<add>
<add>その機能とは次のようなものです。
<add>
<add>* コメント全件の表示欄
<add>* コメントの送信フォーム
<add>* 自作のバックエンドとの連携機能
<add>
<add>ついでに小洒落た機能もいくつか加えましょう。
<add>
<add>* **コメントの先読み:** 送信したコメントをサーバに保存される前に表示させることで、アプリ動作の体感速度をアップさせます。
<add>* **自動更新:** 他のユーザのコメントをリアルタイムで表示させます。
<add>* **Markdown 記法:** ユーザが Markdown 記法でコメントを書けるようにします。
<add>
<add>### 全部飛ばしてソースを見たいんだけど?
<add>
<add>[全部 GitHub にあります。](https://github.com/reactjs/react-tutorial)
<add>
<add>### サーバを動かす
<add>
<add>このチュートリアルを始めるにあたっては必要ないですが、後半ではサーバに POST を投げる機能を追加します。サーバのことは良く知っていて自分でサーバを建てたいのであれば、それでも構いません。そうではないけれども、サーバサイドは考えずに React のことだけに焦点を絞って学びたい方のため、シンプルなサーバのソースコードを書いておきました。言語は JavaScript (Node.js)または Python、Ruby、Go、ないし PHP で用意してあり、すべて GitHub にあります。[ソースを見る](https://github.com/reactjs/react-tutorial/) ことも出来ますし、 [zip ファイルでダウンロード](https://github.com/reactjs/react-tutorial/archive/master.zip)することも出来ます。
<add>
<add>それでは最初のチュートリアルとして、`public/index.html` の編集から始めましょう。
<add>
<add>### 始めてみましょう
<add>
<add>このチュートリアルでは、あらかじめビルドされた JavaScript ファイルを CDN から読み込むことになります。自分の好きなエディタを立ち上げて、次のように新規の HTML ドキュメントを作りましょう。
<add>
<add>```html
<add><!-- index.html -->
<add><html>
<add> <head>
<add> <title>Hello React</title>
<add> <script src="https://fb.me/react-{{site.react_version}}.js"></script>
<add> <script src="https://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
<add> <script src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
<add> </head>
<add> <body>
<add> <div id="content"></div>
<add> <script type="text/jsx">
<add> // ここにコードが入ります
<add> </script>
<add> </body>
<add></html>
<add>```
<add>
<add>このチュートリアルに関しては、JavaScript コードを script タグの中へ書いていくことにします。
<add>
<add>> 確認:
<add>>
<add>> 上のコードで jQuery を読み込んでいますが、これはチュートリアル後半で ajax のコードを簡潔に書きたいだけなので、React を動かすのに必要なものでは**ありません**。
<add>
<add>### 最初のコンポーネント
<add>
<add>React はすべて、モジュール単位で組み立てられる(composable)コンポーネントからなっています。今回取り上げるコメントボックスの例では、以下のようなコンポーネント構造をとります。
<add>
<add>```
<add>- CommentBox
<add> - CommentList
<add> - Comment
<add> - CommentForm
<add>```
<add>
<add>それではまず `CommentBox` コンポーネントから作っていきましょう。とは言っても単なる `<div>` です。
<add>
<add>```javascript
<add>// tutorial1.js
<add>var CommentBox = React.createClass({
<add> render: function() {
<add> return (
<add> <div className="commentBox">
<add> Hello, world! I am a CommentBox.
<add> </div>
<add> );
<add> }
<add>});
<add>React.render(
<add> <CommentBox />,
<add> document.getElementById('content')
<add>);
<add>```
<add>
<add>#### JSX シンタックス
<add>
<add>先程書いた JavaScript の中に、XMLに似たシンタックスがあることに気付いたでしょうか。このシンタックスシュガーは、シンプルなプリコンパイラによって次のような生の JavaScript に変換されます。
<add>
<add>```javascript
<add>// tutorial1-raw.js
<add>var CommentBox = React.createClass({displayName: 'CommentBox',
<add> render: function() {
<add> return (
<add> React.createElement('div', {className: "commentBox"},
<add> "Hello, world! I am a CommentBox."
<add> )
<add> );
<add> }
<add>});
<add>React.render(
<add> React.createElement(CommentBox, null),
<add> document.getElementById('content')
<add>);
<add>```
<add>
<add>どちらを採るかは自由ですが、生の JavaScript よりも JSX シンタックスのほうが扱いやすいと考えています。詳しくは [JSX シンタックスの記事](/react/docs/jsx-in-depth.html) を読んでみてください。
<add>
<add>#### 何をしているのか
<add>
<add>先程のコードでは、とあるメソッドを持った JavaScript オブジェクトを `React.createClass()` に渡しています。これは新しい React コンポーネントを作るためです。このメソッドは `render` と呼ばれており、最終的に HTML へレンダリングされる React コンポーネントのツリーを返す点が肝になります。
<add>
<add>コードに書いた `<div>` タグは実際の DOM ノードではありません。これは React の `div` コンポーネントのインスタンスです。 これらは React が理解できるマーカーやデータの一部だと見なせます。React は **安全** です。デフォルトで XSS 対策を行っているので、HTML 文字列を生成することはありません。
<add>
<add>実際の HTML を返す必要はありません。 自分が(もしくは他の誰かが)組み立てたコンポーネントツリーを返せばいいのです。 これこそ React が **composable**な(組み立てられる)ものである理由であり、この大事なルールを守ればフロントエンドはメンテナンスしやすいものとなります。
<add>
<add>`React.render()` はまずルートコンポーネントのインスタンスを作り、フレームワークを立ち上げます。そして、第2引数で与えられた実際の DOM 要素にマークアップを挿入します。
<add>
<add>## コンポーネントの組み立て
<add>
<add>それでは `CommentList` と `CommentForm` の骨組みを作りましょう。繰り返しになりますが、これらはただの `<div>` です。
<add>
<add>```javascript
<add>// tutorial2.js
<add>var CommentList = React.createClass({
<add> render: function() {
<add> return (
<add> <div className="commentList">
<add> Hello, world! I am a CommentList.
<add> </div>
<add> );
<add> }
<add>});
<add>
<add>var CommentForm = React.createClass({
<add> render: function() {
<add> return (
<add> <div className="commentForm">
<add> Hello, world! I am a CommentForm.
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>さて、この新しいコンポーネントを使えるように `CommentBox` コンポーネントを書き直しましょう。
<add>
<add>```javascript{6-8}
<add>// tutorial3.js
<add>var CommentBox = React.createClass({
<add> render: function() {
<add> return (
<add> <div className="commentBox">
<add> <h1>Comments</h1>
<add> <CommentList />
<add> <CommentForm />
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>ここで、HTML タグと組み立てているコンポーネントが、どのようにミックスされているかを確認しましょう。 HTML コンポーネントは既定の React コンポーネントですが、自分で定義したもの同士はそれぞれ別物になります。JSX コンパイラは HTML タグを自動的に `React.createElement(tagName)` の式に書き換え、それぞれを別々のものに変換します。これはグローバルの名前空間が汚染させるのを防ぐためです。
<add>
<add>### Props を使う
<add>
<add>次のステップは `Comment` コンポーネントの作成です。このコンポーネントは、自分の親にあたるコンポーネントから渡されたデータを扱います。親から渡されたデータは、子のコンポーネントで「プロパティ」として利用できます。この「プロパティ」には `this.props` を通してアクセスします。props(プロパティ)を使うと `CommentList` から `Comment` に渡されたデータの読み込み、マークアップのレンダリングが可能になります。
<add>
<add>```javascript
<add>// tutorial4.js
<add>var Comment = React.createClass({
<add> render: function() {
<add> return (
<add> <div className="comment">
<add> <h2 className="commentAuthor">
<add> {this.props.author}
<add> </h2>
<add> {this.props.children}
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>JSX の内側で(属性値または子要素として)JavaScript の式を波括弧で囲むと、テキストや React コンポーネントをツリーに加えることが出来ます。コンポーネントに渡された属性値には名前が付けられており、`this.props` をキーとしてアクセスできます。また、ネストされた子要素の値は `this.props.children` でアクセスが可能です。
<add>
<add>### コンポーネントのプロパティ
<add>
<add>さて、これまでに `Comment` コンポーネントを定義しました。これからこのコンポーネントに、コメントの著者名と内容を渡せるようにします。これを実装することで、それぞれ別のコメントに対して同じコードを使い回せるようになります。それでは早速 `CommentList` の中にコメントを追加していきましょう。
<add>
<add>```javascript{6-7}
<add>// tutorial5.js
<add>var CommentList = React.createClass({
<add> render: function() {
<add> return (
<add> <div className="commentList">
<add> <Comment author="Pete Hunt">This is one comment</Comment>
<add> <Comment author="Jordan Walke">This is *another* comment</Comment>
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>ここで確認してもらいたいのは、親の `CommentList` コンポーネントから、子の `Comment` コンポーネントにデータが渡されている点です。この例ではまず、*Pete Hunt*(属性値を通して)と *This is one comment*(XML のような子ノードを通して)といったデータを `Comment` コンポーネントに渡しています。少し前に確認した通り、`Comment` コンポーネントからこれらの「プロパティ」にアクセスするには、`this.props.author` と `this.props.children` を使います。
<add>
<add>### Markdown の追加
<add>
<add>Markdown はインラインでテキストをフォーマットする簡単な記法です。例えば、テキストをアスタリスクで挟むと強調されて表示されます。
<add>
<add>まず最初に、サードパーティ製の **Showdown** ライブラリをアプリケーションに追加します。 Showdown は Markdown テキストを生の HTML に変換する JavaScript ライブラリです。 既にある head タグの内側に script タグを書き込み、以下のように Showdown を読み込ませます。
<add>
<add>```html{7}
<add><!-- index.html -->
<add><head>
<add> <title>Hello React</title>
<add> <script src="https://fb.me/react-{{site.react_version}}.js"></script>
<add> <script src="https://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
<add> <script src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
<add> <script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/0.3.1/showdown.min.js"></script>
<add></head>
<add>```
<add>
<add>次に、Markdown で書かれたコメントを変換して出力してみましょう。
<add>
<add>```javascript{2,10}
<add>// tutorial6.js
<add>var converter = new Showdown.converter();
<add>var Comment = React.createClass({
<add> render: function() {
<add> return (
<add> <div className="comment">
<add> <h2 className="commentAuthor">
<add> {this.props.author}
<add> </h2>
<add> {converter.makeHtml(this.props.children.toString())}
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>このコードでは Showdown のライブラリを呼び出すことしかしていません。`this.props.children` は React によってラップされたテキストですが、これを Showdown が理解できる生の文字列に変換する必要があります。そのため、上のコードでは明示的に `toString()` を呼び出しているのです。
<add>
<add>しかし問題があります!ブラウザがレンダリングしたコメントは次のように表示されているはずです -- "`<p>`This is `<em>`another`</em>` comment`</p>`" このようなタグは実際に HTML としてレンダリングさせたいですね。
<add>
<add>このような現象が起きるのは React が XSS 攻撃に対する防御を行っているからです。これを回避する方法はありますが、それを使うときにはフレームワークが警告をします。
<add>
<add>```javascript{5,11}
<add>// tutorial7.js
<add>var converter = new Showdown.converter();
<add>var Comment = React.createClass({
<add> render: function() {
<add> var rawMarkup = converter.makeHtml(this.props.children.toString());
<add> return (
<add> <div className="comment">
<add> <h2 className="commentAuthor">
<add> {this.props.author}
<add> </h2>
<add> <span dangerouslySetInnerHTML={{"{{"}}__html: rawMarkup}} />
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>これは特別な API であり、生の HTML が挿入されにくくなるよう意図的に作ったものです。しかし、ここでは Showdown のためにこのバックドアを利用しています。
<add>
<add>**注意:** この機能を使うことで、Showdown は安全なものと信頼することになります。
<add>
<add>### データモデルとの連携
<add>
<add>これまではソースコードにコメントを直に書き込んでいました。その代わりに、これからは JSON の blob データをコメントリストにレンダリングしてみましょう。サーバからデータを取得するのが最後の目標ですが、とりあえず今はソースコードの中にデータを書いておくことにします。
<add>
<add>```javascript
<add>// tutorial8.js
<add>var data = [
<add> {author: "Pete Hunt", text: "This is one comment"},
<add> {author: "Jordan Walke", text: "This is *another* comment"}
<add>];
<add>```
<add>
<add>このデータはモジュールを使って `CommentList` に取り込む必要があります。`CommentBox` の `React.render()` の部分を手直しして、props を通してデータが `CommentList` へ渡るようにしましょう。
<add>
<add>```javascript{7,15}
<add>// tutorial9.js
<add>var CommentBox = React.createClass({
<add> render: function() {
<add> return (
<add> <div className="commentBox">
<add> <h1>Comments</h1>
<add> <CommentList data={this.props.data} />
<add> <CommentForm />
<add> </div>
<add> );
<add> }
<add>});
<add>
<add>React.render(
<add> <CommentBox data={data} />,
<add> document.getElementById('content')
<add>);
<add>```
<add>
<add>こうして `CommentList` がデータを扱えるようになりました。それでは、コメントを動的にレンダリングしてみましょう。
<add>
<add>```javascript{4-10,13}
<add>// tutorial10.js
<add>var CommentList = React.createClass({
<add> render: function() {
<add> var commentNodes = this.props.data.map(function (comment) {
<add> return (
<add> <Comment author={comment.author}>
<add> {comment.text}
<add> </Comment>
<add> );
<add> });
<add> return (
<add> <div className="commentList">
<add> {commentNodes}
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>これだけ!
<add>
<add>### サーバからのデータの取得
<add>
<add>続いて、ハードコーディングしていたデータを、サーバからの動的なデータに置き換えてみましょう。
<add>
<add>```javascript{3}
<add>// tutorial11.js
<add>React.render(
<add> <CommentBox url="comments.json" />,
<add> document.getElementById('content')
<add>);
<add>```
<add>
<add>このコンポーネントは自身を再びレンダリングすることになるので、これまでのコンポーネントとは異なります。レスポンスがサーバから返ってくると、送られてきた新しいコメントをコンポーネントがレンダリングすることになります。ですが、その時点までコンポーネントには何もデータがないはずです。
<add>
<add>### Reactive state
<add>
<add>これまで、それぞれのコンポーネントは自身の props の値を用いて、一度だけレンダリングしていました。`props` はイミュータブルです。つまり、props は親から渡されますが、同時に props は親の「所有物」なのです。データが相互にやり取りされるのを実現するため、ここでミュータブルな **state**(状態)をコンポーネントに取り入れましょう。コンポーネントは `this.state` というプライベートな値を持ち、`this.setState()` を呼び出すことで state を更新することが出来ます。コンポーネントの state が更新されれば、そのコンポーネントは自身を再びレンダリングし直します。
<add>
<add>`render()` メソッドは `this.props` や `this.state` と同じく宣言的に書かれています。このフレームワークによって、UI と入力が常に一致するようになります。
<add>
<add>サーバがデータを集めてくれば、今あるコメントのデータを更新することになるかもしれません。state を表すコメントのデータの配列を `CommentBox` コンポーネントに加えましょう。
<add>
<add>```javascript{3-5,10}
<add>// tutorial12.js
<add>var CommentBox = React.createClass({
<add> getInitialState: function() {
<add> return {data: []};
<add> },
<add> render: function() {
<add> return (
<add> <div className="commentBox">
<add> <h1>Comments</h1>
<add> <CommentList data={this.state.data} />
<add> <CommentForm />
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>`getInitialState()` メソッドはコンポーネントのライフサイクル内で一回だけ実行され、コンポーネントの state における初期値を設定します。
<add>
<add>#### State の更新
<add>コンポーネントの作成と同時に、サーバから JSON データを GET で取得し、state を更新して最新のデータを反映させてみましょう。実際のアプリケーションでは動的なエンドポイントになるでしょうが、今回の例では話を簡単にするため、以下の静的な JSON ファイルを使います。
<add>
<add>```javascript
<add>// tutorial13.json
<add>[
<add> {"author": "Pete Hunt", "text": "This is one comment"},
<add> {"author": "Jordan Walke", "text": "This is *another* comment"}
<add>]
<add>```
<add>
<add>サーバへの非同期リクエストを作るため、ここでは jQuery を使います。
<add>
<add>注意: ここからは AJAX アプリケーションを作っていくので、自分のファイルシステム上ではなく Web サーバを使ってアプリを作る必要があります。残りのチュートリアルに必要な機能は [冒頭で紹介した](#running-a-server) サーバに含まれています。ソースコードは [GitHub に](https://github.com/reactjs/react-tutorial/)用意してあります。
<add>
<add>```javascript{6-17}
<add>// tutorial13.js
<add>var CommentBox = React.createClass({
<add> getInitialState: function() {
<add> return {data: []};
<add> },
<add> componentDidMount: function() {
<add> $.ajax({
<add> url: this.props.url,
<add> dataType: 'json',
<add> success: function(data) {
<add> this.setState({data: data});
<add> }.bind(this),
<add> error: function(xhr, status, err) {
<add> console.error(this.props.url, status, err.toString());
<add> }.bind(this)
<add> });
<add> },
<add> render: function() {
<add> return (
<add> <div className="commentBox">
<add> <h1>Comments</h1>
<add> <CommentList data={this.state.data} />
<add> <CommentForm />
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>さて、`componentDidMount` はコンポーネントがレンダリングされたときに React が自動的に呼び出すメソッドです。動的な更新の鍵となるのは `this.setState()` の呼び出し方です。ここでは、古いコメントの配列をサーバから取ってきた新しい配列に置き換え、UI を自動的に更新させてみましょう。このような reactivity(反応性・柔軟性)のおかげで、リアルタイム更新を最小限にすることが出来ます。次のコードではシンプルなポーリングをしていますが、WebSockets や他の方法でも簡単に実現できます。
<add>
<add>```javascript{3,14,19-20,34}
<add>// tutorial14.js
<add>var CommentBox = React.createClass({
<add> loadCommentsFromServer: function() {
<add> $.ajax({
<add> url: this.props.url,
<add> dataType: 'json',
<add> success: function(data) {
<add> this.setState({data: data});
<add> }.bind(this),
<add> error: function(xhr, status, err) {
<add> console.error(this.props.url, status, err.toString());
<add> }.bind(this)
<add> });
<add> },
<add> getInitialState: function() {
<add> return {data: []};
<add> },
<add> componentDidMount: function() {
<add> this.loadCommentsFromServer();
<add> setInterval(this.loadCommentsFromServer, this.props.pollInterval);
<add> },
<add> render: function() {
<add> return (
<add> <div className="commentBox">
<add> <h1>Comments</h1>
<add> <CommentList data={this.state.data} />
<add> <CommentForm />
<add> </div>
<add> );
<add> }
<add>});
<add>
<add>React.render(
<add> <CommentBox url="comments.json" pollInterval={2000} />,
<add> document.getElementById('content')
<add>);
<add>
<add>```
<add>
<add>ここまでに、AJAX を呼び出す部分を別のメソッド内に移動させました。加えて、コンポーネントが最初に読み込まれてから2秒ごとに AJAX のメソッドが呼び出されるようにしました。ぜひ自分のブラウザで実行させて、`comments.json` ファイルに変更を加えてみてください。2秒以内に表示が更新されるはずです!
<add>
<add>### 新しいコメントの追加
<add>
<add>いよいよフォームを作る段階に来ました。ここで `CommentForm` コンポーネントは、ユーザに自分の名前とコメントの内容を入力させ、コメントを保存させるためにサーバへリクエストを送る役割を果たすことになります。
<add>
<add>```javascript{5-9}
<add>// tutorial15.js
<add>var CommentForm = React.createClass({
<add> render: function() {
<add> return (
<add> <form className="commentForm">
<add> <input type="text" placeholder="Your name" />
<add> <input type="text" placeholder="Say something..." />
<add> <input type="submit" value="Post" />
<add> </form>
<add> );
<add> }
<add>});
<add>```
<add>
<add>それでは、フォームを使ってデータをやり取りできるようにしましょう。ユーザがフォームから送信したら、フォームをクリアしてサーバにリクエストを送り、コメントリストをリフレッシュすることになります。まず手始めに、フォームからの送信イベントを受け取ってフォームをクリアできるようにしましょう。
<add>
<add>```javascript{3-13,16-19}
<add>// tutorial16.js
<add>var CommentForm = React.createClass({
<add> handleSubmit: function(e) {
<add> e.preventDefault();
<add> var author = React.findDOMNode(this.refs.author).value.trim();
<add> var text = React.findDOMNode(this.refs.text).value.trim();
<add> if (!text || !author) {
<add> return;
<add> }
<add> // TODO: サーバにリクエストを送信
<add> React.findDOMNode(this.refs.author).value = '';
<add> React.findDOMNode(this.refs.text).value = '';
<add> return;
<add> },
<add> render: function() {
<add> return (
<add> <form className="commentForm" onSubmit={this.handleSubmit}>
<add> <input type="text" placeholder="Your name" ref="author" />
<add> <input type="text" placeholder="Say something..." ref="text" />
<add> <input type="submit" value="Post" />
<add> </form>
<add> );
<add> }
<add>});
<add>```
<add>
<add>##### イベント
<add>
<add>React がコンポーネントにイベントハンドラを登録する際は camelCase の命名規則に従います。上のコードではフォームに `onSubmit` ハンドラを登録し、フォームから妥当な入力が送信されたらフォームをクリアするようになっています。
<add>
<add>また `preventDefault()` を呼び出しているので、フォームからの送信に対してブラウザのデフォルト処理が反応することはありません。
<add>
<add>##### Refs
<add>
<add>先程のコードでは `ref` 属性値を使って子のコンポーネントに名前を付けており、`this.ref` でそのコンポーネントを参照しています。`React.findDOMNode(component)` にコンポーネントを指定して呼び出すことで、ブラウザの持つ実際の DOM 要素を取得することが出来ます。
<add>
<add>##### Props としてのコールバック
<add>
<add>ユーザがコメントを送信したら、コメントリストをリフレッシュして新しいリストを読み込むことになります。コメントリストを表す state を保持しているのは `CommentBox` なので、必要なロジックは `CommentBox` の中に書くのが筋でしょう。
<add>
<add>ここでは子のコンポーネントから親に向かって、いつもとは逆方向にデータを返す必要があります。まず、親のコンポーネントに新しいコールバック関数(`handleCommentSubmit`)を定義します。続いて `render` メソッド内にある子のコンポーネントにコールバックを渡すことで、`onCommentSubmit` イベントとコールバックを結び付けています。こうすることで、イベントが発生するたびにコールバックが呼び出されます。
<add>
<add>```javascript{15-17,30}
<add>// tutorial17.js
<add>var CommentBox = React.createClass({
<add> loadCommentsFromServer: function() {
<add> $.ajax({
<add> url: this.props.url,
<add> dataType: 'json',
<add> success: function(data) {
<add> this.setState({data: data});
<add> }.bind(this),
<add> error: function(xhr, status, err) {
<add> console.error(this.props.url, status, err.toString());
<add> }.bind(this)
<add> });
<add> },
<add> handleCommentSubmit: function(comment) {
<add> // TODO: サーバに送信、リストをリフレッシュ
<add> },
<add> getInitialState: function() {
<add> return {data: []};
<add> },
<add> componentDidMount: function() {
<add> this.loadCommentsFromServer();
<add> setInterval(this.loadCommentsFromServer, this.props.pollInterval);
<add> },
<add> render: function() {
<add> return (
<add> <div className="commentBox">
<add> <h1>Comments</h1>
<add> <CommentList data={this.state.data} />
<add> <CommentForm onCommentSubmit={this.handleCommentSubmit} />
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>それでは、ユーザがフォームから送信したら `CommentForm` がコールバックを呼び出せるようにしましょう。
<add>
<add>```javascript{10}
<add>// tutorial18.js
<add>var CommentForm = React.createClass({
<add> handleSubmit: function(e) {
<add> e.preventDefault();
<add> var author = React.findDOMNode(this.refs.author).value.trim();
<add> var text = React.findDOMNode(this.refs.text).value.trim();
<add> if (!text || !author) {
<add> return;
<add> }
<add> this.props.onCommentSubmit({author: author, text: text});
<add> React.findDOMNode(this.refs.author).value = '';
<add> React.findDOMNode(this.refs.text).value = '';
<add> return;
<add> },
<add> render: function() {
<add> return (
<add> <form className="commentForm" onSubmit={this.handleSubmit}>
<add> <input type="text" placeholder="Your name" ref="author" />
<add> <input type="text" placeholder="Say something..." ref="text" />
<add> <input type="submit" value="Post" />
<add> </form>
<add> );
<add> }
<add>});
<add>```
<add>
<add>こうしてコールバックが出来たので、あとはサーバにコメントを送信してリストをリフレッシュすれば完璧です。
<add>
<add>```javascript{16-27}
<add>// tutorial19.js
<add>var CommentBox = React.createClass({
<add> loadCommentsFromServer: function() {
<add> $.ajax({
<add> url: this.props.url,
<add> dataType: 'json',
<add> success: function(data) {
<add> this.setState({data: data});
<add> }.bind(this),
<add> error: function(xhr, status, err) {
<add> console.error(this.props.url, status, err.toString());
<add> }.bind(this)
<add> });
<add> },
<add> handleCommentSubmit: function(comment) {
<add> $.ajax({
<add> url: this.props.url,
<add> dataType: 'json',
<add> type: 'POST',
<add> data: comment,
<add> success: function(data) {
<add> this.setState({data: data});
<add> }.bind(this),
<add> error: function(xhr, status, err) {
<add> console.error(this.props.url, status, err.toString());
<add> }.bind(this)
<add> });
<add> },
<add> getInitialState: function() {
<add> return {data: []};
<add> },
<add> componentDidMount: function() {
<add> this.loadCommentsFromServer();
<add> setInterval(this.loadCommentsFromServer, this.props.pollInterval);
<add> },
<add> render: function() {
<add> return (
<add> <div className="commentBox">
<add> <h1>Comments</h1>
<add> <CommentList data={this.state.data} />
<add> <CommentForm onCommentSubmit={this.handleCommentSubmit} />
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>### 最適化: 先読み更新
<add>
<add>アプリケーションに必要な機能は一通り実装できました。しかし、フォームからコメントを送信しても、サーバからのレスポンスが来るまで自分のコメントはリストに載らないため、アプリの動作は遅く感じます。ここでは、送信したコメントをリストに先読みさせて、アプリの体感速度をアップさせましょう。
<add>
<add>```javascript{16-18}
<add>// tutorial20.js
<add>var CommentBox = React.createClass({
<add> loadCommentsFromServer: function() {
<add> $.ajax({
<add> url: this.props.url,
<add> dataType: 'json',
<add> success: function(data) {
<add> this.setState({data: data});
<add> }.bind(this),
<add> error: function(xhr, status, err) {
<add> console.error(this.props.url, status, err.toString());
<add> }.bind(this)
<add> });
<add> },
<add> handleCommentSubmit: function(comment) {
<add> var comments = this.state.data;
<add> var newComments = comments.concat([comment]);
<add> this.setState({data: newComments});
<add> $.ajax({
<add> url: this.props.url,
<add> dataType: 'json',
<add> type: 'POST',
<add> data: comment,
<add> success: function(data) {
<add> this.setState({data: data});
<add> }.bind(this),
<add> error: function(xhr, status, err) {
<add> console.error(this.props.url, status, err.toString());
<add> }.bind(this)
<add> });
<add> },
<add> getInitialState: function() {
<add> return {data: []};
<add> },
<add> componentDidMount: function() {
<add> this.loadCommentsFromServer();
<add> setInterval(this.loadCommentsFromServer, this.props.pollInterval);
<add> },
<add> render: function() {
<add> return (
<add> <div className="commentBox">
<add> <h1>Comments</h1>
<add> <CommentList data={this.state.data} />
<add> <CommentForm onCommentSubmit={this.handleCommentSubmit} />
<add> </div>
<add> );
<add> }
<add>});
<add>```
<add>
<add>### おめでとう!
<add>
<add>シンプルな手順を追ううちにコメントボックスを作ることが出来ました。さらに詳しいことは[なぜ React を使うのか](/react/docs/why-react.html)を読んだり、[API リファレンス](/react/docs/top-level-api.html)を開いたりしてハッキングを始めましょう!幸運を祈ります! | 2 |
Python | Python | fix various typos | 3d85402ca548957030685c451c96b05342454906 | <ide><path>keras/layers/core.py
<ide> class AutoEncoder(Layer):
<ide> encoder = containers.Sequential([Dense(16, input_dim=32), Dense(8)])
<ide> decoder = containers.Sequential([Dense(16, input_dim=8), Dense(32)])
<ide>
<del> autoencoder = Sequential()
<del> autoencoder.add(AutoEncoder(encoder=encoder, decoder=decoder,
<del> output_reconstruction=True))
<add> autoencoder = AutoEncoder(encoder=encoder, decoder=decoder, output_reconstruction=True)
<add> model = Sequential()
<add> model.add(autoencoder)
<ide>
<ide> # training the autoencoder:
<del> autoencoder.compile(optimizer='sgd', loss='mse')
<del> autoencoder.fit(X_train, X_train, nb_epoch=10)
<add> model.compile(optimizer='sgd', loss='mse')
<add> model.fit(X_train, X_train, nb_epoch=10)
<ide>
<ide> # predicting compressed representations of inputs:
<del> autoencoder.output_reconstruction = False # the autoencoder has to be recompiled after modifying this property
<del> autoencoder.compile(optimizer='sgd', loss='mse')
<del> representations = autoencoder.predict(X_test)
<add> autoencoder.output_reconstruction = False # the model has to be recompiled after modifying this property
<add> model.compile(optimizer='sgd', loss='mse')
<add> representations = model.predict(X_test)
<ide>
<ide> # the model is still trainable, although it now expects compressed representations as targets:
<del> autoencoder.fit(X_test, representations, nb_epoch=1) # in this case the loss will be 0, so it's useless
<add> model.fit(X_test, representations, nb_epoch=1) # in this case the loss will be 0, so it's useless
<ide>
<ide> # to keep training against the original inputs, just switch back output_reconstruction to True:
<ide> autoencoder.output_reconstruction = True
<del> autoencoder.compile(optimizer='sgd', loss='mse')
<del> autoencoder.fit(X_train, X_train, nb_epoch=10)
<add> model.compile(optimizer='sgd', loss='mse')
<add> model.fit(X_train, X_train, nb_epoch=10)
<ide> ```
<ide> '''
<ide> def __init__(self, encoder, decoder, output_reconstruction=True,
<ide><path>tests/keras/layers/test_core.py
<ide> def test_autoencoder_advanced():
<ide> X_train = np.random.random((100, 10))
<ide> X_test = np.random.random((100, 10))
<ide>
<del> autoencoder = Sequential()
<del> autoencoder.add(core.Dense(output_dim=10, input_dim=10))
<del> autoencoder.add(core.AutoEncoder(encoder=encoder, decoder=decoder,
<del> output_reconstruction=True))
<add> model = Sequential()
<add> model.add(core.Dense(output_dim=10, input_dim=10))
<add> autoencoder = core.AutoEncoder(encoder=encoder, decoder=decoder,
<add> output_reconstruction=True)
<add> model.add(autoencoder)
<ide>
<ide> # training the autoencoder:
<del> autoencoder.compile(optimizer='sgd', loss='mse')
<del> autoencoder.fit(X_train, X_train, nb_epoch=1, batch_size=32)
<add> model.compile(optimizer='sgd', loss='mse')
<add> assert autoencoder.output_reconstruction
<add>
<add> model.fit(X_train, X_train, nb_epoch=1, batch_size=32)
<ide>
<ide> # predicting compressed representations of inputs:
<ide> autoencoder.output_reconstruction = False # the autoencoder has to be recompiled after modifying this property
<del> autoencoder.compile(optimizer='sgd', loss='mse')
<del> representations = autoencoder.predict(X_test)
<add> assert not autoencoder.output_reconstruction
<add> model.compile(optimizer='sgd', loss='mse')
<add> representations = model.predict(X_test)
<add> assert representations.shape == (100, 5)
<ide>
<ide> # the model is still trainable, although it now expects compressed representations as targets:
<del> autoencoder.fit(X_test, representations, nb_epoch=1, batch_size=32)
<add> model.fit(X_test, representations, nb_epoch=1, batch_size=32)
<ide>
<ide> # to keep training against the original inputs, just switch back output_reconstruction to True:
<ide> autoencoder.output_reconstruction = True
<del> autoencoder.compile(optimizer='sgd', loss='mse')
<del> autoencoder.fit(X_train, X_train, nb_epoch=1)
<add> model.compile(optimizer='sgd', loss='mse')
<add> model.fit(X_train, X_train, nb_epoch=1)
<add>
<add> reconstructions = model.predict(X_test)
<add> assert reconstructions.shape == (100, 10)
<ide>
<ide>
<ide> def test_maxout_dense(): | 2 |
Go | Go | use dockercmdindir in build tests | 372f9bb58b820b85ed1975ea713958b684c17e94 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestBuildCacheADD(t *testing.T) {
<del> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildCacheADD", "1")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testcacheadd1", ".")
<del> buildCmd.Dir = buildDirectory
<del> exitCode, err := runCommand(buildCmd)
<del> errorOut(err, t, fmt.Sprintf("build failed to complete: %v", err))
<add> var (
<add> exitCode int
<add> out string
<add> err error
<add> )
<add> {
<add> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildCacheADD", "1")
<add> out, exitCode, err = dockerCmdInDir(t, buildDirectory, "build", "-t", "testcacheadd1", ".")
<add> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<del> if err != nil || exitCode != 0 {
<del> t.Fatal("failed to build the image")
<add> if err != nil || exitCode != 0 {
<add> t.Fatal("failed to build the image")
<add> }
<ide> }
<add> {
<add> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildCacheADD", "2")
<add> out, exitCode, err = dockerCmdInDir(t, buildDirectory, "build", "-t", "testcacheadd2", ".")
<add> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<del> buildDirectory = filepath.Join(workingDirectory, "build_tests", "TestBuildCacheADD", "2")
<del> buildCmd = exec.Command(dockerBinary, "build", "-t", "testcacheadd2", ".")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<del> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<del>
<del> if err != nil || exitCode != 0 {
<del> t.Fatal("failed to build the image")
<add> if err != nil || exitCode != 0 {
<add> t.Fatal("failed to build the image")
<add> }
<ide> }
<ide>
<ide> if strings.Contains(out, "Using cache") {
<ide> func TestBuildCacheADD(t *testing.T) {
<ide>
<ide> func TestBuildSixtySteps(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildSixtySteps")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "foobuildsixtysteps", ".")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "foobuildsixtysteps", ".")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestAddSingleFileToRoot(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> f.Close()
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testaddimg", ".")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testaddimg", ".")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestAddSingleFileToWorkdir(t *testing.T) {
<ide>
<ide> func TestAddSingleFileToExistDir(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testaddimg", "SingleFileToExistDir")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testaddimg", "SingleFileToExistDir")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestAddSingleFileToExistDir(t *testing.T) {
<ide>
<ide> func TestAddSingleFileToNonExistDir(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testaddimg", "SingleFileToNonExistDir")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testaddimg", "SingleFileToNonExistDir")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestAddSingleFileToNonExistDir(t *testing.T) {
<ide>
<ide> func TestAddDirContentToRoot(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testaddimg", "DirContentToRoot")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testaddimg", "DirContentToRoot")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestAddDirContentToRoot(t *testing.T) {
<ide>
<ide> func TestAddDirContentToExistDir(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testaddimg", "DirContentToExistDir")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testaddimg", "DirContentToExistDir")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestAddWholeDirToRoot(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> f.Close()
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testaddimg", ".")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testaddimg", ".")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestAddWholeDirToRoot(t *testing.T) {
<ide>
<ide> func TestAddEtcToRoot(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestAdd")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testaddimg", "EtcToRoot")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testaddimg", "EtcToRoot")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestCopySingleFileToRoot(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> f.Close()
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testcopyimg", ".")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testcopyimg", ".")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestCopySingleFileToWorkdir(t *testing.T) {
<ide>
<ide> func TestCopySingleFileToExistDir(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testcopyimg", "SingleFileToExistDir")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testcopyimg", "SingleFileToExistDir")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestCopySingleFileToExistDir(t *testing.T) {
<ide>
<ide> func TestCopySingleFileToNonExistDir(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testcopyimg", "SingleFileToNonExistDir")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testcopyimg", "SingleFileToNonExistDir")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestCopySingleFileToNonExistDir(t *testing.T) {
<ide>
<ide> func TestCopyDirContentToRoot(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testcopyimg", "DirContentToRoot")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testcopyimg", "DirContentToRoot")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestCopyDirContentToRoot(t *testing.T) {
<ide>
<ide> func TestCopyDirContentToExistDir(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testcopyimg", "DirContentToExistDir")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testcopyimg", "DirContentToExistDir")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestCopyWholeDirToRoot(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide> f.Close()
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testcopyimg", ".")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testcopyimg", ".")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestCopyWholeDirToRoot(t *testing.T) {
<ide>
<ide> func TestCopyEtcToRoot(t *testing.T) {
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestCopy")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testcopyimg", "EtcToRoot")
<del> buildCmd.Dir = buildDirectory
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testcopyimg", "EtcToRoot")
<ide> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out, err))
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> func TestBuildWithInaccessibleFilesInContext(t *testing.T) {
<ide> // This test doesn't require that we run commands as an unprivileged user
<ide> pathToDirectoryWhichContainsLinks := filepath.Join(buildDirectory, "linksdirectory")
<ide>
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testlinksok", ".")
<del> buildCmd.Dir = pathToDirectoryWhichContainsLinks
<del> out, exitCode, err := runCommandWithOutput(buildCmd)
<add> out, exitCode, err := dockerCmdInDir(t, pathToDirectoryWhichContainsLinks, "build", "-t", "testlinksok", ".")
<ide> if err != nil || exitCode != 0 {
<ide> t.Fatalf("build should have worked: %s %s", err, out)
<ide> }
<ide> func TestBuildRm(t *testing.T) {
<ide> }
<ide>
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildRm")
<del> buildCmd := exec.Command(dockerBinary, "build", "--rm", "-t", "testbuildrm", ".")
<del> buildCmd.Dir = buildDirectory
<del> _, exitCode, err := runCommandWithOutput(buildCmd)
<add> _, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "--rm", "-t", "testbuildrm", ".")
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> t.Fatal("failed to build the image")
<ide> func TestBuildRm(t *testing.T) {
<ide> }
<ide>
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildRm")
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", "testbuildrm", ".")
<del> buildCmd.Dir = buildDirectory
<del> _, exitCode, err := runCommandWithOutput(buildCmd)
<add> _, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "-t", "testbuildrm", ".")
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> t.Fatal("failed to build the image")
<ide> func TestBuildRm(t *testing.T) {
<ide> }
<ide>
<ide> buildDirectory := filepath.Join(workingDirectory, "build_tests", "TestBuildRm")
<del> buildCmd := exec.Command(dockerBinary, "build", "--rm=false", "-t", "testbuildrm", ".")
<del> buildCmd.Dir = buildDirectory
<del> _, exitCode, err := runCommandWithOutput(buildCmd)
<add> _, exitCode, err := dockerCmdInDir(t, buildDirectory, "build", "--rm=false", "-t", "testbuildrm", ".")
<ide>
<ide> if err != nil || exitCode != 0 {
<ide> t.Fatal("failed to build the image")
<ide> func TestBuildEntrypoint(t *testing.T) {
<ide>
<ide> // #6445 ensure ONBUILD triggers aren't committed to grandchildren
<ide> func TestBuildOnBuildLimitedInheritence(t *testing.T) {
<del> name1 := "testonbuildtrigger1"
<del> dockerfile1 := `
<add> var (
<add> out2, out3 string
<add> )
<add> {
<add> name1 := "testonbuildtrigger1"
<add> dockerfile1 := `
<ide> FROM busybox
<ide> RUN echo "GRANDPARENT"
<ide> ONBUILD RUN echo "ONBUILD PARENT"
<del> `
<del> ctx1, err := fakeContext(dockerfile1, nil)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> buildCmd := exec.Command(dockerBinary, "build", "-t", name1, ".")
<del> buildCmd.Dir = ctx1.Dir
<del> out1, _, err := runCommandWithOutput(buildCmd)
<del> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out1, err))
<del> defer deleteImages(name1)
<add> `
<add> ctx, err := fakeContext(dockerfile1, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide>
<del> name2 := "testonbuildtrigger2"
<del> dockerfile2 := `
<del> FROM testonbuildtrigger1
<del> `
<del> ctx2, err := fakeContext(dockerfile2, nil)
<del> if err != nil {
<del> t.Fatal(err)
<add> out1, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", name1, ".")
<add> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out1, err))
<add> defer deleteImages(name1)
<ide> }
<add> {
<add> name2 := "testonbuildtrigger2"
<add> dockerfile2 := `
<add> FROM testonbuildtrigger1
<add> `
<add> ctx, err := fakeContext(dockerfile2, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide>
<del> buildCmd = exec.Command(dockerBinary, "build", "-t", name2, ".")
<del> buildCmd.Dir = ctx2.Dir
<del> out2, _, err := runCommandWithOutput(buildCmd)
<del> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out2, err))
<del> defer deleteImages(name2)
<del>
<del> name3 := "testonbuildtrigger3"
<del> dockerfile3 := `
<del> FROM testonbuildtrigger2
<del> `
<del> ctx3, err := fakeContext(dockerfile3, nil)
<del> if err != nil {
<del> t.Fatal(err)
<add> out2, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name2, ".")
<add> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out2, err))
<add> defer deleteImages(name2)
<ide> }
<add> {
<add> name3 := "testonbuildtrigger3"
<add> dockerfile3 := `
<add> FROM testonbuildtrigger2
<add> `
<add> ctx, err := fakeContext(dockerfile3, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide>
<del> buildCmd = exec.Command(dockerBinary, "build", "-t", name3, ".")
<del> buildCmd.Dir = ctx3.Dir
<del> out3, _, err := runCommandWithOutput(buildCmd)
<del> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out3, err))
<del> defer deleteImages(name3)
<add> out3, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name3, ".")
<add> errorOut(err, t, fmt.Sprintf("build failed to complete: %v %v", out3, err))
<add> defer deleteImages(name3)
<add> }
<ide>
<ide> // ONBUILD should be run in second build.
<ide> if !strings.Contains(out2, "ONBUILD PARENT") { | 1 |
Text | Text | add 1.13.0 - 1.13.8 + 2.0.0 to changelog.md | d34aaed42c7471744254eafdedeb5c8e3e077d2b | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.0.0 (August 13, 2015)
<add>
<add>- [#12036](https://github.com/emberjs/ember.js/pull/12036) Cleanup CP Set and Volatile
<add>- [#11993](https://github.com/emberjs/ember.js/pull/11993) [CLEANUP] Remove `Ember.TrackedArray` and `Ember.SubArray`.
<add>- [#11550](https://github.com/emberjs/ember.js/pull/11550) [BUGFIX] Ensure that specifying an observer in a child class only observes changes to the childs dependent keys.
<add>- [#10259](https://github.com/emberjs/ember.js/pull/10259) [BUGFIX] Make `Ember.computed.or` return the last falsey value (similar to `||`).
<add>- [#11957](https://github.com/emberjs/ember.js/pull/11957) [BUGFIX] Enable `Ember.DefaultResolver` to properly normalize hyphens (`-`).
<add>- [#11969](https://github.com/emberjs/ember.js/pull/11969) / [#11959](https://github.com/emberjs/ember.js/pull/11959) [DEPRECATE] Deprecate usage of `Ember.String.fmt`.
<add>- [#11990](https://github.com/emberjs/ember.js/pull/11990) [PERF] `@each` should remain a stable node for chains.
<add>- [#11964](https://github.com/emberjs/ember.js/pull/11964) [BUGFIX] Update htmlbars to v0.14.2.
<add>- [#11965](https://github.com/emberjs/ember.js/pull/11965) [CLEANUP] Remove `Ember.HTMLBars.makeViewHelper`.
<add>- [#11965](https://github.com/emberjs/ember.js/pull/11965) [CLEANUP] Remove `Ember.HTMLBars._registerHelper`.
<add>- [#11965](https://github.com/emberjs/ember.js/pull/11965) [CLEANUP] Remove `Ember.Handlebars.registerHelper`.
<add>- [#11965](https://github.com/emberjs/ember.js/pull/11965) [CLEANUP] Remove `Ember.Handlebars.makeBoundHelper`.
<add>- [#11965](https://github.com/emberjs/ember.js/pull/11965) [CLEANUP] Remove `Ember.Handlebars.makeViewHelper`.
<add>- [#11965](https://github.com/emberjs/ember.js/pull/11965) [CLEANUP] Remove `Ember.Handlebars.helper`.
<add>- [#11965](https://github.com/emberjs/ember.js/pull/11965) [CLEANUP] Remove `Ember.Handlebars.registerBoundHelper`.
<add>- [#12024](https://github.com/emberjs/ember.js/pull/12024) [CLEANUP] Remove `ComponentTemplateDeprecation` mixin.
<add>- [#12001](https://github.com/emberjs/ember.js/pull/12001) [CLEANUP] Remove {{with}} keyword's controller option.
<add>- [#12027](https://github.com/emberjs/ember.js/pull/12027) [CLEANUP] Remove deprecated `template` access in Ember.Component.
<add>- [#12019](https://github.com/emberjs/ember.js/pull/12019) [DOC] Add helpful assertion when using @each as a leaf in DK.
<add>- [#12020](https://github.com/emberjs/ember.js/pull/12020) [CLEANUP] Remove specifying `.render` method to views and components.
<add>- [#12027](https://github.com/emberjs/ember.js/pull/12027) [CLEANUP] Remove `positionalParams` specified to `Ember.Component` at extend time.
<add>- [#12027](https://github.com/emberjs/ember.js/pull/12027) [CLEANUP] Remove support for specifying `template` in a component.
<add>- [#12027](https://github.com/emberjs/ember.js/pull/12027) [CLEANUP] Remove deprecated `template` access in Ember.Component.
<add>- [#12028](https://github.com/emberjs/ember.js/pull/12028) [CLEANUP] Store actions in `actions` not `_actions`.
<add>- [#11854](https://github.com/emberjs/ember.js/pull/11854) [CLEANUP] Remove `length` from `OrderedSet` and `Map`.
<add>- [#11854](https://github.com/emberjs/ember.js/pull/11854) [CLEANUP] Remove `OrderedSet.prototype.length`.
<add>- [#11854](https://github.com/emberjs/ember.js/pull/11854) [CLEANUP] Remove `Ember.libraries.each`.
<add>- [#11854](https://github.com/emberjs/ember.js/pull/11854) [CLEANUP] Remove deprecated special `{{each}}` keys.
<add>- [#11854](https://github.com/emberjs/ember.js/pull/11854) [CLEANUP] Remove Ember.Location.registerImplementation.
<add>- [#11854](https://github.com/emberjs/ember.js/pull/11854) [CLEANUP] Remove `{{template}}` support.
<add>- [#11854](https://github.com/emberjs/ember.js/pull/11854) [CLEANUP] Remove Ember.Route#setupControllers deprecation.
<add>- [#11854](https://github.com/emberjs/ember.js/pull/11854) [CLEANUP] Remove Ember.Route#renderTemplates deprecation.
<add>- [#11845](https://github.com/emberjs/ember.js/pull/11845) [CLEANUP] Remove Ember.Application#initialize.
<add>- [#11845](https://github.com/emberjs/ember.js/pull/11845) [CLEANUP] Remove support for `Ember.Application.resolver`.
<add>- [#11845](https://github.com/emberjs/ember.js/pull/11845) [CLEANUP] Remove support for resolver without `normalize`.
<add>- [#11845](https://github.com/emberjs/ember.js/pull/11845) [CLEANUP] Remove IE6 & IE7 deprecation.
<add>- [#11845](https://github.com/emberjs/ember.js/pull/11845) [CLEANUP] Remove returning string of attrs from helper support.
<add>- [#11845](https://github.com/emberjs/ember.js/pull/11845) [CLEANUP] Remove support for returning string of attrs from helper.
<add>- [#11845](https://github.com/emberjs/ember.js/pull/11845) [CLEANUP] Remove support for `view` and `viewClass` with `{{outlet}}`.
<add>- [#11771](https://github.com/emberjs/ember.js/pull/11771) [CLEANUP] Remove deprecated `Controller#controllerFor`.
<add>- [#11750](https://github.com/emberjs/ember.js/pull/11750) [CLEANUP] Remove `metaPath`, `getMeta` and `setMeta`.
<add>- [#11854](https://github.com/emberjs/ember.js/pull/11854) [CLEANUP] Lots of deprecation removals.
<add>- [#11820](https://github.com/emberjs/ember.js/pull/11820) [CLEANUP] Remove sendEvent hook.
<add>- [#11815](https://github.com/emberjs/ember.js/pull/11815) [CLEANUP] Remove `{chainWatchers: null}` from `Meta.prototype`.
<add>- [#11819](https://github.com/emberjs/ember.js/pull/11819) [CLEANUP] Abstract chainWatchers into an object.
<add>- [#11824](https://github.com/emberjs/ember.js/pull/11824) Revert "[CLEANUP] Remove support for reversed args in `Ember.observer`.
<add>- [#11822](https://github.com/emberjs/ember.js/pull/11822) [BUGFIX] Deprecate `currentWhen` with `{{link-to}}`.
<add>- [#11838](https://github.com/emberjs/ember.js/pull/11838) [CLEANUP] Only register `Ember.ContainerView` when legacy view support enabled.
<add>- [#11852](https://github.com/emberjs/ember.js/pull/11852) [CLEANUP] Remove `Ember.RenderBuffer`.
<add>- [#11853](https://github.com/emberjs/ember.js/pull/11853) [CLEANUP] Remove deprecated `Registry` and `Container` behavior.
<add>- [#11850](https://github.com/emberjs/ember.js/pull/11850) [CLEANUP] Remove context switching `{{each}}` helper variant.
<add>- [#11878](https://github.com/emberjs/ember.js/pull/11878) [BUGFIX] Fix issue with QP routes named after `Object.prototype` properties.
<add>- [#11903](https://github.com/emberjs/ember.js/pull/11903) [BUGFIX] Upgrade RSVP + Backburner. Fixes a number of scenarios around testing rejected promise scenarios.
<add>- [#11914](https://github.com/emberjs/ember.js/pull/11914) [CLEANUP] Remove `Ember.oneWay`.
<add>- [#11895](https://github.com/emberjs/ember.js/pull/11895) [BUGFIX] Properly detect if the environment is Node.
<add>- [#11897](https://github.com/emberjs/ember.js/pull/11897) [CLEANUP] Remove globals lookup from templates.
<add>- [#11777](https://github.com/emberjs/ember.js/pull/11777) [CLEANUP] Remove context switching form of `{{#each model}}{{/each}}`, use `{{#each model as |item|}}{{/each}}` instead.
<add>- [#11484](https://github.com/emberjs/ember.js/pull/11484) [CLEANUP] Remove `Ember.ArrayController` support, use `ember-legacy-controllers` addon for support until 2.4.
<add>- [#11782](https://github.com/emberjs/ember.js/pull/11782) [CLEANUP] Remove support for reversed args in `Ember.observer`.
<add>- [#11722](https://github.com/emberjs/ember.js/pull/11722) [BUGFIX] Provide a better error when `InjectedProperty` is misused.
<add>- [#11691](https://github.com/emberjs/ember.js/pull/11691) [BUGFIX] `{{get}}` helper subscribes to values and can be updated.
<add>- [#11792](https://github.com/emberjs/ember.js/pull/11792) [CLEANUP] Remove `Application#then` support.
<add>- [#11737](https://github.com/emberjs/ember.js/pull/11737) [BUGFIX] Ensure `this` context inside former reduced computed macros is correct.
<add>- [#11790](https://github.com/emberjs/ember.js/pull/11790) [CLEANUP] Remove context switching `{{with foo}}` support.
<add>- [#11754](https://github.com/emberjs/ember.js/pull/11754) [CLEANUP] Remove `emptyView="Global.foo"` for Ember.View instances.
<add>- [#11746](https://github.com/emberjs/ember.js/pull/11746) [CLEANUP] Cleanup `Ember.get`:
<add> - Remove support for globals: `Ember.get('App.foo')` and `Ember.get(null, 'App.foo')`.
<add> - Remove support for `this`: `Ember.get(object, 'this.foo')`.
<add> - Enforce strict usage with two arguments: `Ember.get(object, path)`.
<add> - Assert object is a non-null object & path is a string.
<add>- [#11761](https://github.com/emberjs/ember.js/pull/11761) [CLEANUP] Cleanup `Ember.set`:
<add> - Removes support for set with global paths.
<add> - Removes support for set with 'this' paths.
<add> - Removes support for set with null as first parameter.
<add> - Path must be a string.
<add> - Requires set to be passed in three or four arguments.
<add>- [#11797](https://github.com/emberjs/ember.js/pull/11797) [CLEANUP] Move support of `itemController`, `itemViewClass`, `itemView`, etc into `ember-legacy-views` addon.
<add>- [#11776](https://github.com/emberjs/ember.js/pull/11776) [CLEANUP] Remove deprecated support for `{{each foo as bar}}`.
<add>- [#11770](https://github.com/emberjs/ember.js/pull/11770) [CLEANUP] Remove deprecated `Controller#needs`, use `Ember.inject.controller()` instead.
<add>- [#11800](https://github.com/emberjs/ember.js/pull/11800) [CLEANUP] Move support of `{{view}}` helper into `ember-legacy-views` addon.
<add>- [#11804](https://github.com/emberjs/ember.js/pull/11804) [CLEANUP] Remove `EmberObject.createWithMixins`.
<add>- [#11786](https://github.com/emberjs/ember.js/pull/11786) [CLEANUP] Remove `{{with foo as bar}}` support.
<add>- [#11805](https://github.com/emberjs/ember.js/pull/11805) [CLEANUP] Remove deprecated `anyBy`, `everyProperty`, and `some`.
<add>- [#11788](https://github.com/emberjs/ember.js/pull/11788) [CLEANUP] Remove slash for a namespace in the `{{render}}` helper
<add>- [#11791](https://github.com/emberjs/ember.js/pull/11791) [CLEANUP] Remove support for actions in `events` key.
<add>- [#11794](https://github.com/emberjs/ember.js/pull/11794) [CLEANUP] Move `Ember.View` and `Ember.CoreView` into `ember-legacy-views` addon.
<add>- [#11796](https://github.com/emberjs/ember.js/pull/11796) [CLEANUP] Remove `Ember.beforeObserver`, `Ember.addBeforeObserver`, `Ember.removeBeforeObserver`, `Ember.beforeObserversFor`, `Ember._suspendBeforeObserver`, `Ember._suspendBeforeObservers`, and `Function.prototype.observesBefore`.
<add>- [#11806](https://github.com/emberjs/ember.js/pull/11806) [CLEANUP] Remove deprecated `Controller#transitionTo` and `Controller#replaceWith`.
<add>- [#11807](https://github.com/emberjs/ember.js/pull/11807) [CLEANUP] Remove deprecated `Ember.Handlebars.get`.
<add>- [#11808](https://github.com/emberjs/ember.js/pull/11808) [CLEANUP] Remove deprecated `Binding#oneWay`.
<add>- [#11809](https://github.com/emberjs/ember.js/pull/11809) [CLEANUP] Remove deprecated `Map#remove`.
<add>- [#11213](https://github.com/emberjs/ember.js/pull/11213) [CLEANUP] Remove chaining in Observable.set
<add>- [#11438](https://github.com/emberjs/ember.js/pull/11438) [CLEANUP] Remove CP semantics
<add>- [#11447](https://github.com/emberjs/ember.js/pull/11447) [CLEANUP] Remove `Ember.Set` (**not** `Ember.set`).
<add>- [#11443](https://github.com/emberjs/ember.js/pull/11443) [CLEANUP] Remove `Ember.LinkView`.
<add>- [#11439](https://github.com/emberjs/ember.js/pull/11439) [CLEANUP] Remove computed macros.
<add>- [#11648](https://github.com/emberjs/ember.js/pull/11648) [CLEANUP] Remove `Ember.computed.mapProperty`.
<add>- [#11460](https://github.com/emberjs/ember.js/pull/11460) [CLEANUP] Remove `Object.create` polyfill.
<add>- [#11448](https://github.com/emberjs/ember.js/pull/11448) [CLEANUP] Remove `Ember.DeferredMixin`.
<add>- [#11458](https://github.com/emberjs/ember.js/pull/11458) [CLEANUP] Remove `Ember.ArrayPolyfils`.
<add>- [#11449](https://github.com/emberjs/ember.js/pull/11449) [CLEANUP] Remove `Ember.RSVP.prototype.fail`.
<add>- [#11459](https://github.com/emberjs/ember.js/pull/11459) [CLEANUP] Remove `Ember.keys`.
<add>- [#11456](https://github.com/emberjs/ember.js/pull/11456) [CLEANUP] Remove `Ember.View.prototype.state & `Ember.View.prototype._states`.
<add>- [#11455](https://github.com/emberjs/ember.js/pull/11455) [CLEANUP] Remove `Ember.EnumerableUtils`.
<add>- [#11462](https://github.com/emberjs/ember.js/pull/11462) [CLEANUP] Remove `Object.defineProperty` polyfill.
<add>- [#11517](https://github.com/emberjs/ember.js/pull/11517) [DEPRECATION] Deprecate `this.resource` in `Router.map`.
<add>- [#11479](https://github.com/emberjs/ember.js/pull/11479) [CLEANUP] Remove `Ember.ObjectController`.
<add>- [#11513](https://github.com/emberjs/ember.js/pull/11513) [BUGFIX] Replace array computed macros with plain array versions.
<add>- [#11513](https://github.com/emberjs/ember.js/pull/11513) [CLEANUP] Remove `Ember.arrayComputed`, `Ember.reduceComputed`, `Ember.ArrayComputed`, and `Ember.ReduceComputed`.
<add>- [#11547](https://github.com/emberjs/ember.js/pull/11547) [CLEANUP] Remove work around for Safari's double finally on error bug.
<add>- [#11528](https://github.com/emberjs/ember.js/pull/11528) [BUGFIX] Add helpful assertion when using `Ember.computed.map` without a function callback.
<add>- [#11528](https://github.com/emberjs/ember.js/pull/11528) [BUGFIX] Add helpful assertion when using `Ember.computed.mapBy` without a string property name.
<add>- [#11587](https://github.com/emberjs/ember.js/pull/11587) [CLEANUP] Remove `{{bind-attr}}`.
<add>- [#11611](https://github.com/emberjs/ember.js/pull/11611) [CLEANUP] Remove `Ember.computed.filterProperty`.
<add>- [#11608](https://github.com/emberjs/ember.js/pull/11608) [CLEANUP] Remove `{{linkTo}}` helper (**not** `{{link-to}}`).
<add>- [#11706](https://github.com/emberjs/ember.js/pull/11706) [CLEANUP] Remove `Enumerable.rejectProperty`.
<add>- [#11708](https://github.com/emberjs/ember.js/pull/11708) [BUGFIX] Update `fillIn` test helper to trigger the `input` event.
<add>- [#11710](https://github.com/emberjs/ember.js/pull/11710) Add repository field to package.json
<add>- [#11700](https://github.com/emberjs/ember.js/pull/11700) [CLEANUP] Removes `Enumerable.findProperty`.
<add>- [#11707](https://github.com/emberjs/ember.js/pull/11707) [CLEANUP] Remove `Enumerable.everyBy`.
<add>- [#10701](https://github.com/emberjs/ember.js/pull/10701) Refactor `lazyGet`.
<add>- [#11262](https://github.com/emberjs/ember.js/pull/11262) Fix basic Fastboot usage.
<add>- [#11375](https://github.com/emberjs/ember.js/pull/11375) Transition feature flag infrastructure to modules.
<add>- [#11383](https://github.com/emberjs/ember.js/pull/11383) Update {{each-in}} to use ember-metal/should-display.
<add>- [#11396](https://github.com/emberjs/ember.js/pull/11396) Make Ember.Checkbox extend from Ember.Component.
<add>
<add>### 1.13.8 (August 13, 2015)
<add>
<add>- [#12056](https://github.com/emberjs/ember.js/pull/12056) [BUGFIX] Ensure initializers can augment `customEvents`.
<add>- [#12037](https://github.com/emberjs/ember.js/pull/12037) [BUGFIX] Fix error in some query params scenarios.
<add>- [#12058](https://github.com/emberjs/ember.js/pull/12058) [BUGFIX] Fix link-to with only qps linking to outdated route.
<add>- [#12061](https://github.com/emberjs/ember.js/pull/12061) [PERF] Improve performance of guidFor when reading an existing Ember.Object.
<add>- [#12067](https://github.com/emberjs/ember.js/pull/12067) [BUGFIX] Prevent `helper:@content-helper` lookup errors when using a paramless helper.
<add>- [#12071](https://github.com/emberjs/ember.js/pull/12071) [BUGFIX] Fix issue with accessing component attributes before initial render.
<add>- [#12073](https://github.com/emberjs/ember.js/pull/12073) [BUGFIX] Fix issue with events when invoking a component and specifying `classNames=`.
<add>
<add>
<add>### 1.13.7 (August 9, 2015)
<add>
<add>- [#12000](https://github.com/emberjs/ember.js/pull/12000) [DEPRECATION] Deprecate using `controller` for {{with}}
<add>- [#11946](https://github.com/emberjs/ember.js/pull/11946) [PERF] Speed up `AttrProxy` implementation.
<add>- [#11956](https://github.com/emberjs/ember.js/pull/11956) [BUGFIX] Ensure that `Ember.View.views` is present on deprecated `Ember.View`.
<add>- [#11960](https://github.com/emberjs/ember.js/pull/11960) [BUGFIX] Fix issue preventing proper rerendering when specifying bound properties to `{{link-to}}`.
<add>- [#12018](https://github.com/emberjs/ember.js/pull/12018) [DEPRECATION] Deprecate `{{#unbound}}{{/unbound}}`.
<add>- [#12018](https://github.com/emberjs/ember.js/pull/12018) [DEPRECATION] Deprecate `{{unbound}}` with multiple params.
<add>- [#11964](https://github.com/emberjs/ember.js/pull/11964) [BUGFIX] Update htmlbars to v0.13.35.
<add>- [#12017](https://github.com/emberjs/ember.js/pull/12017) [DEPRECATION] Deprecate specifying `render` function to `Ember.View` or `Ember.Component` at extend time.
<add>- [#11993](https://github.com/emberjs/ember.js/pull/11993) [DEPRECATION] Deprecate `Ember.TrackedArray` and `Ember.SubArray`.
<add>- [#11994](https://github.com/emberjs/ember.js/pull/11994) [DEPRECATION] Deprecate using `@each` as a leaf node in a dependent key. Refactor from `Ember.computed('foo.@each', function() {});` to `Ember.computed('foo.[]', function() { });`.
<add>- [#12026](https://github.com/emberjs/ember.js/pull/12026) [BUGFIX] Remove wasted dependent keys for `template` and `layout` properties of `Ember.View`/`Ember.Component`.
<add>
<add>
<add>### 1.13.6 (July 31, 2015)
<add>
<add>- [#11900](https://github.com/emberjs/ember.js/pull/11900) [DEPRECATION] Deprecate `Ember.Handlebars.makeViewHelper`.
<add>- [#11900](https://github.com/emberjs/ember.js/pull/11900) [DEPRECATION] Deprecate `Ember.HTMLBars.makeViewHelper`.
<add>- [#11900](https://github.com/emberjs/ember.js/pull/11900) [DEPRECATION] Deprecate `Ember.HTMLBars._registerHelper` (manual registration is no longer needed).
<add>- [#11900](https://github.com/emberjs/ember.js/pull/11900) [DEPRECATION] Deprecate `Ember.HTMLBars.makeBoundHelper` in favor of `Ember.Helper.helper`.
<add>- [#11900](https://github.com/emberjs/ember.js/pull/11900) [DEPRECATION] Deprecate `Ember.Handlebars.makeBoundHelper` in favor of `Ember.Helper.helper`.
<add>- [#11900](https://github.com/emberjs/ember.js/pull/11900) [DEPRECATION] Deprecate `Ember.Handlebars.registerBoundHelper` in favor of `Ember.Helper.helper`.
<add>- [#11900](https://github.com/emberjs/ember.js/pull/11900) [DEPRECATION] Deprecate `Ember.Handlebars.helper` in favor of `Ember.Helper.helper` and automatic helper resolution.
<add>- [#11900](https://github.com/emberjs/ember.js/pull/11900) [DEPRECATION] Deprecate `Ember.Handlebars.registerHelper` in favor of `Ember.Helper.helper` and automatic helper resolution.
<add>- [#11832](https://github.com/emberjs/ember.js/pull/11832) [BUGFIX] Fix memory leaks with application creation and acceptance test helpers.
<add>- [#11826](https://github.com/emberjs/ember.js/pull/11826) [DEPRECATION] Deprecate Ember.ContainerView
<add>- [#11864](https://github.com/emberjs/ember.js/pull/11864) [BUGFIX] Ensure acceptance test helpers are removed during teardown.
<add>- [#11861](https://github.com/emberjs/ember.js/pull/11861) [BUGFIX] Update HTMLBars to allow duplicate {{each}} keys.
<add>- [#11889](https://github.com/emberjs/ember.js/pull/11889) [BUGFIX] Fix `attributeBindings` for `id` attribute.
<add>- [#11866](https://github.com/emberjs/ember.js/pull/11866) [BUGFIX] Fix DeprecatedView (and friends) reopen function to delegate to original.
<add>- [#11891](https://github.com/emberjs/ember.js/pull/11891) [DEPRECATION] Deprecate Ember.CollectionView
<add>- [#11910](https://github.com/emberjs/ember.js/pull/11910) [BUGFIX] Ensure `Ember.CollectionView.CONTAINER_MAP` is present on deprecated `CollectionView`.
<add>- [#11917](https://github.com/emberjs/ember.js/pull/11917) [BUGFIX] Ensure `"use strict";` is properly added for modules.
<add>- [#11934](https://github.com/emberjs/ember.js/pull/11934) [DEPRECATION] Deprecate specifying `positionalParams` at extend time in favor of using static factory properties.
<add>- [#11935](https://github.com/emberjs/ember.js/pull/11935) [BUGFIX] Avoid unnecessary change events during initial render.
<add>
<add>### 1.13.5 (July 19, 2015)
<add>
<add>- [#11767](https://github.com/emberjs/ember.js/pull/11767) [DEPRECATION] Deprecate Controller#needs
<add>- [#11468](https://github.com/emberjs/ember.js/pull/11468) [DEPRECATION] Deprecate `Ember.Freezable` and `frozenCopy`.
<add>- [#11762](https://github.com/emberjs/ember.js/pull/11762) / [#11744](https://github.com/emberjs/ember.js/pull/11744) [BUGFIX] Ensure deprecated `Ember.beforeObserver` is available in production.
<add>- [#11765](https://github.com/emberjs/ember.js/pull/11765) [DEPRECATION] Mark `Ember.oneWay` as deprecated
<add>- [#11774](https://github.com/emberjs/ember.js/pull/11774) [BUGFIX] Add deprecation warnings to deprecated Enumerable methods.
<add>- [#11778](https://github.com/emberjs/ember.js/pull/11778) [DEPRECATION] Deprecate reverse argument ordering in `Ember.observer`.
<add>- [#11787](https://github.com/emberjs/ember.js/pull/11787) [DEPRECATION] Deprecate slash for a namespace in the `{{render}}` helper.
<add>- [#11798](https://github.com/emberjs/ember.js/pull/11798) [DEPRECATION] Deprecate `Function#observesBefore`.
<add>- [#11812](https://github.com/emberjs/ember.js/pull/11812) [DEPRECATION] Add deprecation messages when using `Ember.get` / `Ember.set` in a certain ways.
<add>
<add>### 1.13.4 (July 13, 2015)
<add>
<add>- [#11651](https://github.com/emberjs/ember.js/pull/11651) [BUGFIX] Ensure child views of non-dirty components get the correct parentView when rerendered.
<add>- [#11662](https://github.com/emberjs/ember.js/pull/11662) [BUGFIX] Prevent ArrayController deprecation on generated controllers.
<add>- [#11655](https://github.com/emberjs/ember.js/pull/11655) [BUGFIX] Fix issue with blockless link-to with only query params.
<add>- [#11664](https://github.com/emberjs/ember.js/pull/11664) [BUGFIX] Ensure Route actions can be unit tested.
<add>- [#11667](https://github.com/emberjs/ember.js/pull/11667) [BUGFIX] Fix memory leak in rendering engine.
<add>
<add>### 1.13.3 (July 5, 2015)
<add>
<add>- [#11510](https://github.com/emberjs/ember.js/pull/11510) [DEPRECATION] Deprecate `Ember.Object.createWithMixins`.
<add>- [#11512](https://github.com/emberjs/ember.js/pull/11512) [DEPRECATION] Deprecate `Ember.oneWay` in favor of `Ember.computed.oneWay`.
<add>- [#11525](https://github.com/emberjs/ember.js/pull/11525) [BUGFIX] Add helpful error when using `{{each}}` with duplicate keys. This replaces a difficult to understand error deep in the HTMLBars internals, with an error that explains the duplicate key issue a bit better.
<add>- [#11511](https://github.com/emberjs/ember.js/pull/11511) [DEPRECATION] Deprecate `Ember.keys` in favor of `Object.keys`.
<add>- [#11511](https://github.com/emberjs/ember.js/pull/11511) [DEPRECATION] Deprecate `Ember.create` in favor of `Object.create`.
<add>- [#11543](https://github.com/emberjs/ember.js/pull/11543) / [#11594](https://github.com/emberjs/ember.js/pull/11594) / [#11603](https://github.com/emberjs/ember.js/pull/11603) - [BUGFIX] Fix extending or reopening `Ember.LinkView`.
<add>- [#11561](https://github.com/emberjs/ember.js/pull/11561) [BUGFIX] Fix issue with `{{link-to}}` not properly updating the link for certain routing state changes.
<add>- [#11572](https://github.com/emberjs/ember.js/pull/11572) [BUGFIX] Ensure local component state can shadow attributes provided during invocation.
<add>- [#11570](https://github.com/emberjs/ember.js/pull/11570) [BUGFIX] Prevent infinite loop when a yielded block param is changed.
<add>- [#11577](https://github.com/emberjs/ember.js/pull/11577) [BUGFIX] Ensure route backed views are properly destroyed.
<add>- [#11636](https://github.com/emberjs/ember.js/pull/11636) [BUGFIX] Fix sticky query params for nested and for dynamic routes.
<add>- [#11639](https://github.com/emberjs/ember.js/pull/11639) [BUGFIX] Fix testing of components containing `{{link-to}}`'s.
<add>- [#11650](https://github.com/emberjs/ember.js/pull/11650) [BUGFIX] Update HTMLBars to 0.13.32. Fixes a number of issues with the property first strategy used:
<add> * for exceptions `input.form`, `input.list`, `button.type` always use `elem.setAttribute`
<add> * for `form.action` always escape
<add> * always assign handlers to props, even if the case appears strange
<add>
<add>### 1.13.2 (June 17, 2015)
<add>
<add>- [#11461](https://github.com/emberjs/ember.js/pull/11461) Remove `{{each}}` without `key=` warning. Deprecates `@guid` and `@item` in favor of the new default `@identity`.
<add>- [#11495](https://github.com/emberjs/ember.js/pull/11495) [PERFORMANCE] Remove debug statements from production builds.
<add>
<add>### 1.13.1 (June 16, 2015)
<add>
<add>- [#11445](https://github.com/emberjs/ember.js/pull/11445) [BUGFIX] Allow recomputation for `Ember.Helper` with arguments.
<add>- [#11317](https://github.com/emberjs/ember.js/pull/11317) [BUGFIX] Ensure handleURL called after setURL in visit helper.
<add>- [#11464](https://github.com/emberjs/ember.js/pull/11464) [DEPRECATION] Deprecate `Ember.immediateObserver`.
<add>- [#11476](https://github.com/emberjs/ember.js/pull/11476) [DEPRECATION] Deprecate `Ember.ArrayController`.
<add>- [#11478](https://github.com/emberjs/ember.js/pull/11478) [DEPRECATION] Deprecate `Ember.RenderBuffer`.
<add>
<ide> ### 1.13.0 (June 12, 2015)
<ide>
<ide> - [#11270](https://github.com/emberjs/ember.js/pull/11270) [BUGFIX] Ensure view registry is propagated to components. | 1 |
Text | Text | add v3.14.0-beta.3 to changelog | 1db41748d5563538add872084d8ebedd2eb420e2 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.14.0-beta.3 (October 1, 2019)
<add>
<add>- [#18429](https://github.com/emberjs/ember.js/pull/18429) [BUGFIX] Fix incorrect error message for octane features.
<add>
<ide> ### v3.14.0-beta.2 (September 24, 2019)
<ide>
<ide> - [#18273](https://github.com/emberjs/ember.js/pull/18273) [BUGFIX] Fix issues with SSR rehydration of <title>. | 1 |
Python | Python | improve input validation in graph.compile | f3fd56db501f75b72db253a4e1d06792b81c2a60 | <ide><path>keras/models.py
<ide> def compile(self, optimizer, loss, sample_weight_modes={}):
<ide> you will need to set the sample weight mode for this output
<ide> to "temporal".
<ide> '''
<add> assert type(loss) is dict, 'The "loss" argument should be a dictionary.'
<add> assert type(sample_weight_modes) is dict, 'The "sample_weight_modes" argument should be a dictionary.'
<add>
<ide> self.sample_weight_modes = sample_weight_modes
<ide> ys = []
<ide> ys_train = [] | 1 |
Text | Text | add prompt of $ | 638546d1206dd229c5e00df0725de6966725b2e0 | <ide><path>docs/installation/linux/SUSE.md
<ide> The `docker` package creates a new group named `docker`. Users, other than
<ide> `root` user, must be part of this group to interact with the
<ide> Docker daemon. You can add users with this command syntax:
<ide>
<del> sudo /usr/sbin/usermod -a -G docker <username>
<add> $ sudo /usr/sbin/usermod -a -G docker <username>
<ide>
<ide> Once you add a user, make sure they relog to pick up these new permissions.
<ide> | 1 |
Python | Python | raise validation error on invalid timezone parsing | bf7fcc495b36a692570f6fe9210c96e746f75bf8 | <ide><path>rest_framework/fields.py
<ide> def to_internal_value(self, value):
<ide> if input_format.lower() == ISO_8601:
<ide> try:
<ide> parsed = parse_datetime(value)
<del> except (ValueError, TypeError):
<del> pass
<del> else:
<ide> if parsed is not None:
<ide> return self.enforce_timezone(parsed)
<add> except (ValueError, TypeError):
<add> pass
<ide> else:
<ide> try:
<ide> parsed = self.datetime_parser(value, input_format)
<add> return self.enforce_timezone(parsed)
<ide> except (ValueError, TypeError):
<ide> pass
<del> else:
<del> return self.enforce_timezone(parsed)
<ide>
<ide> humanized_format = humanize_datetime.datetime_formats(input_formats)
<ide> self.fail('invalid', format=humanized_format)
<ide><path>tests/test_fields.py
<ide> class TestDateTimeField(FieldValues):
<ide> invalid_inputs = {
<ide> 'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
<ide> '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
<add> '2018-08-16 22:00-24:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].'],
<ide> datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'],
<ide> }
<ide> outputs = { | 2 |
Java | Java | delete dead code in annotationattributes | 53dd88437e81f8ef3c95ed36671048c2a7d4738e | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java
<ide> package org.springframework.core.annotation;
<ide>
<ide> import java.lang.annotation.Annotation;
<del>import java.lang.reflect.AnnotatedElement;
<ide> import java.lang.reflect.Array;
<ide> import java.util.Iterator;
<ide> import java.util.LinkedHashMap;
<del>import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> private <T> T getRequiredAttribute(String attributeName, Class<T> expectedType)
<ide> return (T) value;
<ide> }
<ide>
<del> /**
<del> * Get the value stored under the specified {@code attributeName} as an
<del> * object of the {@code expectedType}, taking into account alias semantics
<del> * defined via {@link AliasFor @AliasFor}.
<del> * <p>If there is no value stored under the specified {@code attributeName}
<del> * but the attribute has an alias declared via {@code @AliasFor}, the
<del> * value of the alias will be returned.
<del> * @param attributeName the name of the attribute to get; never
<del> * {@code null} or empty
<del> * @param annotationType the type of annotation represented by this
<del> * {@code AnnotationAttributes} instance; never {@code null}
<del> * @param annotationSource the source of the annotation represented by
<del> * this {@code AnnotationAttributes} (e.g., the {@link AnnotatedElement});
<del> * or {@code null} if unknown
<del> * @param expectedType the expected type; never {@code null}
<del> * @return the value
<del> * @throws IllegalArgumentException if the attribute and its alias do
<del> * not exist or are not of the {@code expectedType}
<del> * @throws AnnotationConfigurationException if the attribute and its
<del> * alias are both present with different non-empty values
<del> * @since 4.2
<del> * @see ObjectUtils#isEmpty(Object)
<del> */
<del> private <T> T getRequiredAttributeWithAlias(String attributeName, Class<? extends Annotation> annotationType,
<del> Object annotationSource, Class<T> expectedType) {
<del>
<del> Assert.hasText(attributeName, "'attributeName' must not be null or empty");
<del> Assert.notNull(annotationType, "'annotationType' must not be null");
<del> Assert.notNull(expectedType, "'expectedType' must not be null");
<del>
<del> T attributeValue = getAttribute(attributeName, expectedType);
<del>
<del> List<String> aliasNames = AnnotationUtils.getAttributeAliasMap(annotationType).get(attributeName);
<del> if (aliasNames != null) {
<del> for (String aliasName : aliasNames) {
<del> T aliasValue = getAttribute(aliasName, expectedType);
<del> boolean attributeEmpty = ObjectUtils.isEmpty(attributeValue);
<del> boolean aliasEmpty = ObjectUtils.isEmpty(aliasValue);
<del>
<del> if (!attributeEmpty && !aliasEmpty && !ObjectUtils.nullSafeEquals(attributeValue, aliasValue)) {
<del> String elementName = (annotationSource == null ? "unknown element" : annotationSource.toString());
<del> String msg = String.format("In annotation [%s] declared on [%s], attribute [%s] and its " +
<del> "alias [%s] are present with values of [%s] and [%s], but only one is permitted.",
<del> annotationType.getName(), elementName, attributeName, aliasName,
<del> ObjectUtils.nullSafeToString(attributeValue), ObjectUtils.nullSafeToString(aliasValue));
<del> throw new AnnotationConfigurationException(msg);
<del> }
<del>
<del> // If we expect an array and the current tracked value is null but the
<del> // current alias value is non-null, then replace the current null value
<del> // with the non-null value (which may be an empty array).
<del> if (expectedType.isArray() && attributeValue == null && aliasValue != null) {
<del> attributeValue = aliasValue;
<del> }
<del> // Else: if we're not expecting an array, we can rely on the behavior of
<del> // ObjectUtils.isEmpty().
<del> else if (attributeEmpty && !aliasEmpty) {
<del> attributeValue = aliasValue;
<del> }
<del> }
<del> assertAttributePresence(attributeName, aliasNames, attributeValue);
<del> }
<del>
<del> return attributeValue;
<del> }
<del>
<del> /**
<del> * Get the value stored under the specified {@code attributeName},
<del> * ensuring that the value is of the {@code expectedType}.
<del> * @param attributeName the name of the attribute to get; never
<del> * {@code null} or empty
<del> * @param expectedType the expected type; never {@code null}
<del> * @return the value
<del> * @throws IllegalArgumentException if the attribute is not of the
<del> * expected type
<del> * @see #getRequiredAttribute(String, Class)
<del> */
<del> @SuppressWarnings("unchecked")
<del> private <T> T getAttribute(String attributeName, Class<T> expectedType) {
<del> Object value = get(attributeName);
<del> if (value != null) {
<del> assertNotException(attributeName, value);
<del> assertAttributeType(attributeName, value, expectedType);
<del> }
<del> return (T) value;
<del> }
<del>
<ide> private void assertAttributePresence(String attributeName, Object attributeValue) {
<ide> Assert.notNull(attributeValue, () -> String.format("Attribute '%s' not found in attributes for annotation [%s]",
<ide> attributeName, this.displayName));
<ide> }
<ide>
<del> private void assertAttributePresence(String attributeName, List<String> aliases, Object attributeValue) {
<del> Assert.notNull(attributeValue, () -> String.format(
<del> "Neither attribute '%s' nor one of its aliases %s was found in attributes for annotation [%s]",
<del> attributeName, aliases, this.displayName));
<del> }
<del>
<ide> private void assertNotException(String attributeName, Object attributeValue) {
<ide> if (attributeValue instanceof Exception) {
<ide> throw new IllegalArgumentException(String.format( | 1 |
PHP | PHP | add driver parameter for new doctrine connection | 0cf3027150a1d7d519f00ce0282ac29b8cd4c64e | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function getDoctrineSchemaManager()
<ide> public function getDoctrineConnection()
<ide> {
<ide> if (is_null($this->doctrineConnection)) {
<del> $data = ['pdo' => $this->getPdo(), 'dbname' => $this->getConfig('database')];
<add> $driver = $this->getDoctrineDriver();
<add> $data = [
<add> 'pdo' => $this->getPdo(),
<add> 'dbname' => $this->getConfig('database'),
<add> 'driver' => $driver->getName(),
<add> ];
<ide>
<ide> $this->doctrineConnection = new DoctrineConnection(
<del> $data, $this->getDoctrineDriver()
<add> $data, $driver
<ide> );
<ide> }
<ide> | 1 |
Go | Go | allow compilation (again) | fa22255b2dcfa46572d25cb4647e424232daaba6 | <ide><path>libnetwork/sandbox/namespace_unsupported.go
<add>// +build !linux
<add>
<add>package sandbox
<add>
<add>// GC triggers garbage collection of namespace path right away
<add>// and waits for it.
<add>func GC() {
<add>} | 1 |
Text | Text | fix some small formatting issues [ci-skip] | 680ce0189654db6d1b8a1dfb3f9a0d51cb8db171 | <ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> The new configuration allows you to conditionally implement the new behavior:
<ide> def changed_method
<ide> if ActiveJob.existing_behavior
<ide> # Existing behavior
<del> else
<add> else
<ide> # New behavior
<ide> end
<ide> end
<ide> As a last step add the new configuration to configuration guide in
<ide> | --------------------- | -------------------- |
<ide> | (original) | `true` |
<ide> | 7.1 | `false` |
<del>
<add>```
<ide>
<ide> ### Ignoring Files Created by Your Editor / IDE
<ide> | 1 |
Javascript | Javascript | log timer identifiers in systrace | a1f31d12fde29db43f5af5d23c0d403c0bd22003 | <ide><path>Libraries/JavaScriptAppEngine/System/JSTimers/JSTimers.js
<ide> // in dependencies. NativeModules > BatchedBridge > MessageQueue > JSTimersExecution
<ide> const RCTTiming = require('NativeModules').Timing;
<ide> const JSTimersExecution = require('JSTimersExecution');
<add>const parseErrorStack = require('parseErrorStack');
<ide>
<ide> // Returns a free index if one is available, and the next consecutive index otherwise.
<ide> function _getFreeIndex(): number {
<ide> function _allocateCallback(func: Function, type: $Keys<typeof JSTimersExecution.
<ide> JSTimersExecution.timerIDs[freeIndex] = id;
<ide> JSTimersExecution.callbacks[freeIndex] = func;
<ide> JSTimersExecution.types[freeIndex] = type;
<add> if (__DEV__) {
<add> const e = (new Error() : any);
<add> e.framesToPop = 1;
<add> const stack = parseErrorStack(e);
<add> if (stack) {
<add> JSTimersExecution.identifiers[freeIndex] = stack.shift();
<add> }
<add> }
<ide> return id;
<ide> }
<ide>
<ide><path>Libraries/JavaScriptAppEngine/System/JSTimers/JSTimersExecution.js
<ide> const JSTimersExecution = {
<ide> timerIDs: [],
<ide> immediates: [],
<ide> requestIdleCallbacks: [],
<add> identifiers: ([] : [{methodName: string}]),
<ide>
<ide> errors: (null : ?[Error]),
<ide>
<ide> const JSTimersExecution = {
<ide> return;
<ide> }
<ide>
<add> if (__DEV__) {
<add> const identifier = JSTimersExecution.identifiers[timerIndex] || {};
<add> Systrace.beginEvent('Systrace.callTimer: ' + identifier.methodName);
<add> }
<add>
<ide> // Clear the metadata
<ide> if (type === JSTimersExecution.Type.setTimeout ||
<ide> type === JSTimersExecution.Type.setImmediate ||
<ide> const JSTimersExecution = {
<ide> JSTimersExecution.errors.push(e);
<ide> }
<ide> }
<add>
<add> if (__DEV__) {
<add> Systrace.endEvent();
<add> }
<ide> },
<ide>
<ide> /**
<ide> const JSTimersExecution = {
<ide> JSTimersExecution.timerIDs[i] = null;
<ide> JSTimersExecution.callbacks[i] = null;
<ide> JSTimersExecution.types[i] = null;
<add> JSTimersExecution.identifiers[i] = null;
<ide> },
<ide> };
<ide> | 2 |
Ruby | Ruby | fix analytics string to test for ci | 30c4663066b2b95b54fb0bbece8cb13fd8545735 | <ide><path>Library/Homebrew/test/utils/analytics_spec.rb
<ide> described_class.clear_os_arch_prefix_ci
<ide> end
<ide>
<add> ci = ", CI" if ENV["CI"]
<add>
<ide> it "returns OS_VERSION and prefix when HOMEBREW_PREFIX is a custom prefix on intel" do
<ide> allow(Hardware::CPU).to receive(:type).and_return(:intel)
<ide> allow(Hardware::CPU).to receive(:in_rosetta2?).and_return(false)
<ide> allow(Homebrew).to receive(:default_prefix?).and_return(false)
<del> expected = "#{OS_VERSION}, #{described_class.custom_prefix_label}"
<add> expected = "#{OS_VERSION}, #{described_class.custom_prefix_label}#{ci}"
<ide> expect(described_class.os_arch_prefix_ci).to eq expected
<ide> end
<ide>
<ide> it 'returns OS_VERSION, "ARM" and prefix when HOMEBREW_PREFIX is a custom prefix on arm' do
<ide> allow(Hardware::CPU).to receive(:type).and_return(:arm)
<ide> allow(Hardware::CPU).to receive(:in_rosetta2?).and_return(false)
<ide> allow(Homebrew).to receive(:default_prefix?).and_return(false)
<del> expected = "#{OS_VERSION}, ARM, #{described_class.custom_prefix_label}"
<add> expected = "#{OS_VERSION}, ARM, #{described_class.custom_prefix_label}#{ci}"
<ide> expect(described_class.os_arch_prefix_ci).to eq expected
<ide> end
<ide>
<ide> it 'returns OS_VERSION, "Rosetta" and prefix when HOMEBREW_PREFIX is a custom prefix using Rosetta' do
<ide> allow(Hardware::CPU).to receive(:type).and_return(:intel)
<ide> allow(Hardware::CPU).to receive(:in_rosetta2?).and_return(true)
<ide> allow(Homebrew).to receive(:default_prefix?).and_return(false)
<del> expected = "#{OS_VERSION}, Rosetta, #{described_class.custom_prefix_label}"
<add> expected = "#{OS_VERSION}, Rosetta, #{described_class.custom_prefix_label}#{ci}"
<ide> expect(described_class.os_arch_prefix_ci).to eq expected
<ide> end
<ide> | 1 |
Python | Python | improve error message | 2b3beeff21ffca1c97fc8807838d0a4b1d7518da | <ide><path>libcloud/compute/ssh.py
<ide> def _get_pkey_object(self, key):
<ide> else:
<ide> return key
<ide>
<del> msg = 'Invalid or unsupported key type'
<add> msg = ('Invalid or unsupported key type (only RSA, DSS and ECDSA keys'
<add> ' are supported)')
<ide> raise paramiko.ssh_exception.SSHException(msg)
<ide>
<ide> | 1 |
Text | Text | update changelog for 16.4.0 | fa7fa812c70084e139d13437fb204fcdf9152299 | <ide><path>CHANGELOG.md
<del>## [Unreleased]
<del><details>
<del> <summary>
<del> Changes that have landed in master but are not yet released.
<del> Click to see more.
<del> </summary>
<add>## 16.4.0 (May 23, 2018)
<ide>
<ide> ### React
<ide>
<ide>
<ide> * The [new host config shape](https://github.com/facebook/react/blob/c601f7a64640290af85c9f0e33c78480656b46bc/packages/react-noop-renderer/src/createReactNoop.js#L82-L285) is flat and doesn't use nested objects. ([@gaearon](https://github.com/gaearon) in [#12792](https://github.com/facebook/react/pull/12792))
<ide>
<del></details>
<del>
<ide> ## 16.3.2 (April 16, 2018)
<ide>
<ide> ### React | 1 |
Python | Python | add tests for zeros, ones, empty and filled | 5991bbeb417719663178ecf4ac283d8f538f48fd | <ide><path>numpy/core/tests/test_numeric.py
<ide> def test_basic(self):
<ide> assert_almost_equal(std(A)**2,real_var)
<ide>
<ide>
<add>class TestCreationFuncs(TestCase):
<add>
<add> def setUp(self):
<add> self.dtypes = ('b', 'i', 'u', 'f', 'c', 'S', 'a', 'U', 'V')
<add> self.orders = {'C': 'c_contiguous', 'F': 'f_contiguous'}
<add> self.ndims = 10
<add>
<add> def check_function(self, func, fill_value=None):
<add> fill_kwarg = {}
<add> if fill_value is not None:
<add> fill_kwarg = {'val': fill_value}
<add> for size in (0, 1, 2):
<add> for ndims in range(self.ndims):
<add> shape = ndims * [size]
<add> for order in self.orders:
<add> for type in self.dtypes:
<add> for bytes in 2**np.arange(9):
<add> try:
<add> dtype = np.dtype('%s%d' % (type, bytes))
<add> except TypeError:
<add> continue
<add> else:
<add> if fill_value is not None and type == 'V':
<add> continue
<add> arr = func(shape, order=order, dtype=dtype,
<add> **fill_kwarg)
<add> assert arr.dtype == dtype
<add> assert getattr(arr.flags, self.orders[order])
<add> if fill_value is not None:
<add> assert_equal(arr, dtype.type(fill_value))
<add>
<add> def test_zeros(self):
<add> self.check_function(np.zeros)
<add>
<add> def test_ones(self):
<add> self.check_function(np.zeros)
<add>
<add> def test_empty(self):
<add> self.check_function(np.empty)
<add>
<add> def test_filled(self):
<add> self.check_function(np.filled, 0)
<add> self.check_function(np.filled, 1)
<add>
<add>
<ide> class TestLikeFuncs(TestCase):
<ide> '''Test ones_like, zeros_like, empty_like and filled_like'''
<ide> | 1 |
Ruby | Ruby | add path name to brew edit error message | c8a8b797306237404e6670dfd3cabe1edcf0639d | <ide><path>Library/Homebrew/dev-cmd/edit.rb
<ide> def edit
<ide> next path if path.exist?
<ide>
<ide> raise UsageError, "#{path} doesn't exist on disk. " \
<del> "Run #{Formatter.identifier("brew create $URL")} to create a new Formula!"
<add> "Run #{Formatter.identifier("brew create --set-name #{path.basename} $URL")} " \
<add> "to create a new Formula!"
<ide> end.presence
<ide>
<ide> # If no brews are listed, open the project root in an editor. | 1 |
Javascript | Javascript | improve formatting of inline code | cb192293f42f0be4d17598bba39ac1f95982e39b | <ide><path>src/ngAnimate/animate.js
<ide> * # Usage
<ide> *
<ide> * To see animations in action, all that is required is to define the appropriate CSS classes
<del> * or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are:
<add> * or to register a JavaScript animation via the `myModule.animation()` function. The directives that support animation automatically are:
<ide> * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation
<ide> * by using the `$animate` service.
<ide> *
<ide> * ### Structural transition animations
<ide> *
<ide> * Structural transitions (such as enter, leave and move) will always apply a `0s none` transition
<del> * value to force the browser into rendering the styles defined in the setup (.ng-enter, .ng-leave
<del> * or .ng-move) class. This means that any active transition animations operating on the element
<add> * value to force the browser into rendering the styles defined in the setup (`.ng-enter`, `.ng-leave`
<add> * or `.ng-move`) class. This means that any active transition animations operating on the element
<ide> * will be cut off to make way for the enter, leave or move animation.
<ide> *
<ide> * ### Class-based transition animations
<ide> angular.module('ngAnimate', ['ng'])
<ide> *
<ide> * Below is a breakdown of each step that occurs during the `animate` animation:
<ide> *
<del> * | Animation Step | What the element class attribute looks like |
<del> * |-------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|
<del> * | 1. $animate.animate(...) is called | class="my-animation" |
<del> * | 2. $animate waits for the next digest to start the animation | class="my-animation ng-animate" |
<del> * | 3. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
<del> * | 4. the className class value is added to the element | class="my-animation ng-animate className" |
<del> * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate className" |
<del> * | 6. $animate blocks all CSS transitions on the element to ensure the .className class styling is applied right away| class="my-animation ng-animate className" |
<del> * | 7. $animate applies the provided collection of `from` CSS styles to the element | class="my-animation ng-animate className" |
<del> * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate className" |
<del> * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate className" |
<del> * | 10. the className-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate className className-active" |
<del> * | 11. $animate applies the collection of `to` CSS styles to the element which are then handled by the transition | class="my-animation ng-animate className className-active" |
<del> * | 12. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate className className-active" |
<del> * | 13. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
<del> * | 14. The returned promise is resolved. | class="my-animation" |
<add> * | Animation Step | What the element class attribute looks like |
<add> * |-----------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------|
<add> * | 1. `$animate.animate(...)` is called | `class="my-animation"` |
<add> * | 2. `$animate` waits for the next digest to start the animation | `class="my-animation ng-animate"` |
<add> * | 3. `$animate` runs the JavaScript-defined animations detected on the element | `class="my-animation ng-animate"` |
<add> * | 4. the `className` class value is added to the element | `class="my-animation ng-animate className"` |
<add> * | 5. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class="my-animation ng-animate className"` |
<add> * | 6. `$animate` blocks all CSS transitions on the element to ensure the `.className` class styling is applied right away| `class="my-animation ng-animate className"` |
<add> * | 7. `$animate` applies the provided collection of `from` CSS styles to the element | `class="my-animation ng-animate className"` |
<add> * | 8. `$animate` waits for a single animation frame (this performs a reflow) | `class="my-animation ng-animate className"` |
<add> * | 9. `$animate` removes the CSS transition block placed on the element | `class="my-animation ng-animate className"` |
<add> * | 10. the `className-active` class is added (this triggers the CSS transition/animation) | `class="my-animation ng-animate className className-active"` |
<add> * | 11. `$animate` applies the collection of `to` CSS styles to the element which are then handled by the transition | `class="my-animation ng-animate className className-active"` |
<add> * | 12. `$animate` waits for the animation to complete (via events and timeout) | `class="my-animation ng-animate className className-active"` |
<add> * | 13. The animation ends and all generated CSS classes are removed from the element | `class="my-animation"` |
<add> * | 14. The returned promise is resolved. | `class="my-animation"` |
<ide> *
<ide> * @param {DOMElement} element the element that will be the focus of the enter animation
<ide> * @param {object} from a collection of CSS styles that will be applied to the element at the start of the animation
<ide> angular.module('ngAnimate', ['ng'])
<ide> *
<ide> * Below is a breakdown of each step that occurs during enter animation:
<ide> *
<del> * | Animation Step | What the element class attribute looks like |
<del> * |-------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|
<del> * | 1. $animate.enter(...) is called | class="my-animation" |
<del> * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" |
<del> * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" |
<del> * | 4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
<del> * | 5. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" |
<del> * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" |
<del> * | 7. $animate blocks all CSS transitions on the element to ensure the .ng-enter class styling is applied right away | class="my-animation ng-animate ng-enter" |
<del> * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-enter" |
<del> * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-enter" |
<del> * | 10. the .ng-enter-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-enter ng-enter-active" |
<del> * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-enter ng-enter-active" |
<del> * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
<del> * | 13. The returned promise is resolved. | class="my-animation" |
<add> * | Animation Step | What the element class attribute looks like |
<add> * |-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|
<add> * | 1. `$animate.enter(...)` is called | `class="my-animation"` |
<add> * | 2. element is inserted into the `parentElement` element or beside the `afterElement` element | `class="my-animation"` |
<add> * | 3. `$animate` waits for the next digest to start the animation | `class="my-animation ng-animate"` |
<add> * | 4. `$animate` runs the JavaScript-defined animations detected on the element | `class="my-animation ng-animate"` |
<add> * | 5. the `.ng-enter` class is added to the element | `class="my-animation ng-animate ng-enter"` |
<add> * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class="my-animation ng-animate ng-enter"` |
<add> * | 7. `$animate` blocks all CSS transitions on the element to ensure the `.ng-enter` class styling is applied right away | `class="my-animation ng-animate ng-enter"` |
<add> * | 8. `$animate` waits for a single animation frame (this performs a reflow) | `class="my-animation ng-animate ng-enter"` |
<add> * | 9. `$animate` removes the CSS transition block placed on the element | `class="my-animation ng-animate ng-enter"` |
<add> * | 10. the `.ng-enter-active` class is added (this triggers the CSS transition/animation) | `class="my-animation ng-animate ng-enter ng-enter-active"` |
<add> * | 11. `$animate` waits for the animation to complete (via events and timeout) | `class="my-animation ng-animate ng-enter ng-enter-active"` |
<add> * | 12. The animation ends and all generated CSS classes are removed from the element | `class="my-animation"` |
<add> * | 13. The returned promise is resolved. | `class="my-animation"` |
<ide> *
<ide> * @param {DOMElement} element the element that will be the focus of the enter animation
<ide> * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation
<ide> angular.module('ngAnimate', ['ng'])
<ide> *
<ide> * Below is a breakdown of each step that occurs during leave animation:
<ide> *
<del> * | Animation Step | What the element class attribute looks like |
<del> * |-------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|
<del> * | 1. $animate.leave(...) is called | class="my-animation" |
<del> * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
<del> * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" |
<del> * | 4. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" |
<del> * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" |
<del> * | 6. $animate blocks all CSS transitions on the element to ensure the .ng-leave class styling is applied right away | class="my-animation ng-animate ng-leave" |
<del> * | 7. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-leave" |
<del> * | 8. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-leave" |
<del> * | 9. the .ng-leave-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-leave ng-leave-active" |
<del> * | 10. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-leave ng-leave-active" |
<del> * | 11. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
<del> * | 12. The element is removed from the DOM | ... |
<del> * | 13. The returned promise is resolved. | ... |
<add> * | Animation Step | What the element class attribute looks like |
<add> * |-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|
<add> * | 1. `$animate.leave(...)` is called | `class="my-animation"` |
<add> * | 2. `$animate` runs the JavaScript-defined animations detected on the element | `class="my-animation ng-animate"` |
<add> * | 3. `$animate` waits for the next digest to start the animation | `class="my-animation ng-animate"` |
<add> * | 4. the `.ng-leave` class is added to the element | `class="my-animation ng-animate ng-leave"` |
<add> * | 5. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class="my-animation ng-animate ng-leave"` |
<add> * | 6. `$animate` blocks all CSS transitions on the element to ensure the `.ng-leave` class styling is applied right away | `class="my-animation ng-animate ng-leave"` |
<add> * | 7. `$animate` waits for a single animation frame (this performs a reflow) | `class="my-animation ng-animate ng-leave"` |
<add> * | 8. `$animate` removes the CSS transition block placed on the element | `class="my-animation ng-animate ng-leave"` |
<add> * | 9. the `.ng-leave-active` class is added (this triggers the CSS transition/animation) | `class="my-animation ng-animate ng-leave ng-leave-active"` |
<add> * | 10. `$animate` waits for the animation to complete (via events and timeout) | `class="my-animation ng-animate ng-leave ng-leave-active"` |
<add> * | 11. The animation ends and all generated CSS classes are removed from the element | `class="my-animation"` |
<add> * | 12. The element is removed from the DOM | ... |
<add> * | 13. The returned promise is resolved. | ... |
<ide> *
<ide> * @param {DOMElement} element the element that will be the focus of the leave animation
<ide> * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation
<ide> angular.module('ngAnimate', ['ng'])
<ide> *
<ide> * Below is a breakdown of each step that occurs during move animation:
<ide> *
<del> * | Animation Step | What the element class attribute looks like |
<del> * |------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------|
<del> * | 1. $animate.move(...) is called | class="my-animation" |
<del> * | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" |
<del> * | 3. $animate waits for the next digest to start the animation | class="my-animation ng-animate" |
<del> * | 4. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
<del> * | 5. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" |
<del> * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" |
<del> * | 7. $animate blocks all CSS transitions on the element to ensure the .ng-move class styling is applied right away | class="my-animation ng-animate ng-move" |
<del> * | 8. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate ng-move" |
<del> * | 9. $animate removes the CSS transition block placed on the element | class="my-animation ng-animate ng-move" |
<del> * | 10. the .ng-move-active class is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-move ng-move-active" |
<del> * | 11. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate ng-move ng-move-active" |
<del> * | 12. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
<del> * | 13. The returned promise is resolved. | class="my-animation" |
<add> * | Animation Step | What the element class attribute looks like |
<add> * |----------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|
<add> * | 1. `$animate.move(...)` is called | `class="my-animation"` |
<add> * | 2. element is moved into the parentElement element or beside the afterElement element | `class="my-animation"` |
<add> * | 3. `$animate` waits for the next digest to start the animation | `class="my-animation ng-animate"` |
<add> * | 4. `$animate` runs the JavaScript-defined animations detected on the element | `class="my-animation ng-animate"` |
<add> * | 5. the `.ng-move` class is added to the element | `class="my-animation ng-animate ng-move"` |
<add> * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class="my-animation ng-animate ng-move"` |
<add> * | 7. `$animate` blocks all CSS transitions on the element to ensure the `.ng-move` class styling is applied right away | `class="my-animation ng-animate ng-move"` |
<add> * | 8. `$animate` waits for a single animation frame (this performs a reflow) | `class="my-animation ng-animate ng-move"` |
<add> * | 9. `$animate` removes the CSS transition block placed on the element | `class="my-animation ng-animate ng-move"` |
<add> * | 10. the `.ng-move-active` class is added (this triggers the CSS transition/animation) | `class="my-animation ng-animate ng-move ng-move-active"` |
<add> * | 11. `$animate` waits for the animation to complete (via events and timeout) | `class="my-animation ng-animate ng-move ng-move-active"` |
<add> * | 12. The animation ends and all generated CSS classes are removed from the element | `class="my-animation"` |
<add> * | 13. The returned promise is resolved. | `class="my-animation"` |
<ide> *
<ide> * @param {DOMElement} element the element that will be the focus of the move animation
<ide> * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation
<ide> angular.module('ngAnimate', ['ng'])
<ide> *
<ide> * Below is a breakdown of each step that occurs during addClass animation:
<ide> *
<del> * | Animation Step | What the element class attribute looks like |
<del> * |----------------------------------------------------------------------------------------------------|------------------------------------------------------------------|
<del> * | 1. $animate.addClass(element, 'super') is called | class="my-animation" |
<del> * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate" |
<del> * | 3. the .super-add class is added to the element | class="my-animation ng-animate super-add" |
<del> * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate super-add" |
<del> * | 5. the .super and .super-add-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate super super-add super-add-active" |
<del> * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super super-add super-add-active" |
<del> * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate super super-add super-add-active" |
<del> * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" |
<del> * | 9. The super class is kept on the element | class="my-animation super" |
<del> * | 10. The returned promise is resolved. | class="my-animation super" |
<add> * | Animation Step | What the element class attribute looks like |
<add> * |--------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|
<add> * | 1. `$animate.addClass(element, 'super')` is called | `class="my-animation"` |
<add> * | 2. `$animate` runs the JavaScript-defined animations detected on the element | `class="my-animation ng-animate"` |
<add> * | 3. the `.super-add` class is added to the element | `class="my-animation ng-animate super-add"` |
<add> * | 4. `$animate` waits for a single animation frame (this performs a reflow) | `class="my-animation ng-animate super-add"` |
<add> * | 5. the `.super` and `.super-add-active` classes are added (this triggers the CSS transition/animation) | `class="my-animation ng-animate super super-add super-add-active"` |
<add> * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class="my-animation ng-animate super super-add super-add-active"` |
<add> * | 7. `$animate` waits for the animation to complete (via events and timeout) | `class="my-animation ng-animate super super-add super-add-active"` |
<add> * | 8. The animation ends and all generated CSS classes are removed from the element | `class="my-animation super"` |
<add> * | 9. The super class is kept on the element | `class="my-animation super"` |
<add> * | 10. The returned promise is resolved. | `class="my-animation super"` |
<ide> *
<ide> * @param {DOMElement} element the element that will be animated
<ide> * @param {string} className the CSS class that will be added to the element and then animated
<ide> angular.module('ngAnimate', ['ng'])
<ide> *
<ide> * Below is a breakdown of each step that occurs during removeClass animation:
<ide> *
<del> * | Animation Step | What the element class attribute looks like |
<del> * |------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------|
<del> * | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" |
<del> * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation super ng-animate" |
<del> * | 3. the .super-remove class is added to the element | class="my-animation super ng-animate super-remove" |
<del> * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation super ng-animate super-remove" |
<del> * | 5. the .super-remove-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate super-remove super-remove-active" |
<del> * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-remove super-remove-active" |
<del> * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate super-remove super-remove-active" |
<del> * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
<del> * | 9. The returned promise is resolved. | class="my-animation" |
<add> * | Animation Step | What the element class attribute looks like |
<add> * |----------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|
<add> * | 1. `$animate.removeClass(element, 'super')` is called | `class="my-animation super"` |
<add> * | 2. `$animate` runs the JavaScript-defined animations detected on the element | `class="my-animation super ng-animate"` |
<add> * | 3. the `.super-remove` class is added to the element | `class="my-animation super ng-animate super-remove"` |
<add> * | 4. `$animate` waits for a single animation frame (this performs a reflow) | `class="my-animation super ng-animate super-remove"` |
<add> * | 5. the `.super-remove-active` classes are added and `.super` is removed (this triggers the CSS transition/animation) | `class="my-animation ng-animate super-remove super-remove-active"` |
<add> * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class="my-animation ng-animate super-remove super-remove-active"` |
<add> * | 7. `$animate` waits for the animation to complete (via events and timeout) | `class="my-animation ng-animate super-remove super-remove-active"` |
<add> * | 8. The animation ends and all generated CSS classes are removed from the element | `class="my-animation"` |
<add> * | 9. The returned promise is resolved. | `class="my-animation"` |
<ide> *
<ide> *
<ide> * @param {DOMElement} element the element that will be animated
<ide> angular.module('ngAnimate', ['ng'])
<ide> * @name $animate#setClass
<ide> *
<ide> * @description Adds and/or removes the given CSS classes to and from the element.
<del> * Once complete, the done() callback will be fired (if provided).
<add> * Once complete, the `done()` callback will be fired (if provided).
<ide> *
<del> * | Animation Step | What the element class attribute looks like |
<del> * |--------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
<del> * | 1. $animate.setClass(element, 'on', 'off') is called | class="my-animation off" |
<del> * | 2. $animate runs the JavaScript-defined animations detected on the element | class="my-animation ng-animate off" |
<del> * | 3. the .on-add and .off-remove classes are added to the element | class="my-animation ng-animate on-add off-remove off" |
<del> * | 4. $animate waits for a single animation frame (this performs a reflow) | class="my-animation ng-animate on-add off-remove off" |
<del> * | 5. the .on, .on-add-active and .off-remove-active classes are added and .off is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" |
<del> * | 6. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" |
<del> * | 7. $animate waits for the animation to complete (via events and timeout) | class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active" |
<del> * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation on" |
<del> * | 9. The returned promise is resolved. | class="my-animation on" |
<add> * | Animation Step | What the element class attribute looks like |
<add> * |----------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|
<add> * | 1. `$animate.setClass(element, 'on', 'off')` is called | `class="my-animation off"` |
<add> * | 2. `$animate` runs the JavaScript-defined animations detected on the element | `class="my-animation ng-animate off"` |
<add> * | 3. the `.on-add` and `.off-remove` classes are added to the element | `class="my-animation ng-animate on-add off-remove off"` |
<add> * | 4. `$animate` waits for a single animation frame (this performs a reflow) | `class="my-animation ng-animate on-add off-remove off"` |
<add> * | 5. the `.on`, `.on-add-active` and `.off-remove-active` classes are added and `.off` is removed (this triggers the CSS transition/animation) | `class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active"` |
<add> * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay | `class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active"` |
<add> * | 7. `$animate` waits for the animation to complete (via events and timeout) | `class="my-animation ng-animate on on-add on-add-active off-remove off-remove-active"` |
<add> * | 8. The animation ends and all generated CSS classes are removed from the element | `class="my-animation on"` |
<add> * | 9. The returned promise is resolved. | `class="my-animation on"` |
<ide> *
<ide> * @param {DOMElement} element the element which will have its CSS classes changed
<ide> * removed from it
<ide> angular.module('ngAnimate', ['ng'])
<ide> all animations call this shared animation triggering function internally.
<ide> The animationEvent variable refers to the JavaScript animation event that will be triggered
<ide> and the className value is the name of the animation that will be applied within the
<del> CSS code. Element, parentElement and afterElement are provided DOM elements for the animation
<add> CSS code. Element, `parentElement` and `afterElement` are provided DOM elements for the animation
<ide> and the onComplete callback will be fired once the animation is fully complete.
<ide> */
<ide> function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, options, doneCallback) { | 1 |
Text | Text | simplify wording to make more sense | e5b4ae17a0cbb48693a8b75738c54fe1d73799da | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.md
<ide> for (var i = 10; i > 0; i -= 2) {
<ide> }
<ide> ```
<ide>
<del>`ourArray` will now contain `[10,8,6,4,2]`. Let's change our initialization and final expression so we can count backward by twos by odd numbers.
<add>`ourArray` will now contain `[10,8,6,4,2]`. Let's change our initialization and final expression so we can count backwards by twos to create an array of descending odd numbers.
<ide>
<ide> # --instructions--
<ide> | 1 |
Ruby | Ruby | modify tests for zsh completions | 0e97793f9196279ef44d327571cf31617da2195e | <ide><path>Library/Homebrew/test/completions_spec.rb
<ide> def delete_completions_setting(setting: "linkcompletions")
<ide> '--hide[Act as if none of the specified hidden are installed. hidden should be a comma-separated list of formulae]' \\
<ide> '--quiet[Make some output more quiet]' \\
<ide> '--verbose[Make some output more verbose]' \\
<del> '::formula:__brew_formulae'
<add> - formula \\
<add> '*::formula:__brew_formulae'
<ide> }
<ide> COMPLETION
<ide> end
<ide> def delete_completions_setting(setting: "linkcompletions")
<ide> end
<ide>
<ide> it "returns appropriate completion for a command with multiple named arg types" do
<del> completion = described_class.generate_zsh_subcommand_completion("upgrade")
<add> completion = described_class.generate_zsh_subcommand_completion("livecheck")
<ide> expect(completion).to match(
<del> /'::outdated_formula:__brew_outdated_formulae' \\\n '::outdated_cask:__brew_outdated_casks'\n}$/,
<add> /'*::formula:__brew_formulae'/,
<add> )
<add> expect(completion).to match(
<add> /'*::cask:__brew_casks'\n}$/,
<ide> )
<ide> end
<ide> end | 1 |
Javascript | Javascript | remove broken endpoints | 604e29c4bcda71330a13cc30163370d0b42d7636 | <ide><path>api-server/src/server/boot/randomAPIs.js
<ide> module.exports = function (app) {
<ide> router.get('/u/:email', unsubscribeDeprecated);
<ide> router.get('/unsubscribe/:email', unsubscribeDeprecated);
<ide> router.get('/ue/:unsubscribeId', unsubscribeById);
<del> router.get(
<del> '/the-fastest-web-page-on-the-internet',
<del> theFastestWebPageOnTheInternet
<del> );
<del> router.get('/unsubscribed/:unsubscribeId', unsubscribedWithId);
<del> router.get('/unsubscribed', unsubscribed);
<ide> router.get('/resubscribe/:unsubscribeId', resubscribe);
<del> router.get('/nonprofits', nonprofits);
<del> router.get('/coding-bootcamp-cost-calculator', bootcampCalculator);
<ide>
<ide> app.use(router);
<ide>
<del> function theFastestWebPageOnTheInternet(req, res) {
<del> res.render('resources/the-fastest-web-page-on-the-internet', {
<del> title: 'This is the fastest web page on the internet'
<del> });
<del> }
<del>
<del> function bootcampCalculator(req, res) {
<del> res.render('resources/calculator', {
<del> title: 'Coding Bootcamp Cost Calculator'
<del> });
<del> }
<del>
<del> function nonprofits(req, res) {
<del> res.render('resources/nonprofits', {
<del> title: 'Your Nonprofit Can Get Pro Bono Code'
<del> });
<del> }
<del>
<ide> function unsubscribeDeprecated(req, res) {
<ide> req.flash(
<ide> 'info',
<ide> module.exports = function (app) {
<ide> });
<ide> }
<ide>
<del> function unsubscribed(req, res) {
<del> res.render('resources/unsubscribed', {
<del> title: 'You have been unsubscribed'
<del> });
<del> }
<del>
<del> function unsubscribedWithId(req, res) {
<del> const { unsubscribeId } = req.params;
<del> return res.render('resources/unsubscribed', {
<del> title: 'You have been unsubscribed',
<del> unsubscribeId
<del> });
<del> }
<del>
<ide> function resubscribe(req, res, next) {
<ide> const { unsubscribeId } = req.params;
<ide> const { origin } = getRedirectParams(req); | 1 |
PHP | PHP | fix duplicate method call | 7e857d30e9759dd0eb6c43c4e54a475aab67fefa | <ide><path>src/Datasource/Paginator.php
<ide> public function paginate($object, array $params = [], array $settings = [])
<ide>
<ide> $pagingParams = $this->buildParams($data);
<ide> $alias = $object->getAlias();
<del> $this->_pagingParams = [$alias => $this->buildParams($data)];
<add> $this->_pagingParams = [$alias => $pagingParams];
<ide> if ($pagingParams['requestedPage'] > $pagingParams['page']) {
<ide> throw new PageOutOfBoundsException([
<ide> 'requestedPage' => $pagingParams['requestedPage'], | 1 |
PHP | PHP | apply fixes from styleci | eb50ed3a69950f337459ff9b45e3916d96801d84 | <ide><path>src/Illuminate/Log/Writer.php
<ide> use Monolog\Formatter\LineFormatter;
<ide> use Monolog\Handler\ErrorLogHandler;
<ide> use Monolog\Logger as MonologLogger;
<del>use Monolog\Handler\RotatingFileHandler;
<ide> use Illuminate\Log\Events\MessageLogged;
<add>use Monolog\Handler\RotatingFileHandler;
<ide> use Illuminate\Contracts\Support\Jsonable;
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Support\Arrayable; | 1 |
Mixed | Ruby | change the behavior of route defaults | f1d8f2af72e21d41efd02488f1c2dcf829e17783 | <ide><path>actionpack/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Change the behavior of route defaults so that explicit defaults are no longer
<add> required where the key is not part of the path. For example:
<add>
<add> resources :posts, bucket_type: 'posts'
<add>
<add> will be required whenever constructing the url from a hash such as a functional
<add> test or using url_for directly. However using the explicit form alters the
<add> behavior so it's not required:
<add>
<add> resources :projects, defaults: { bucket_type: 'projects' }
<add>
<add> This changes existing behavior slightly in that any routes which only differ
<add> in their defaults will match the first route rather than the closest match.
<add>
<add> *Andrew White*
<add>
<ide> * Add support for routing constraints other than Regexp and String.
<ide> For example this now allows the use of arrays like this:
<ide>
<ide><path>actionpack/lib/action_dispatch/journey/route.rb
<ide> def segments
<ide> end
<ide>
<ide> def required_keys
<del> path.required_names.map { |x| x.to_sym } + required_defaults.keys
<add> required_parts + required_defaults.keys
<ide> end
<ide>
<ide> def score(constraints)
<ide> def required_parts
<ide> @required_parts ||= path.required_names.map { |n| n.to_sym }
<ide> end
<ide>
<add> def required_default?(key)
<add> (constraints[:required_defaults] || []).include?(key)
<add> end
<add>
<ide> def required_defaults
<del> @required_defaults ||= begin
<del> matches = parts
<del> @defaults.dup.delete_if { |k,_| matches.include?(k) }
<add> @required_defaults ||= @defaults.dup.delete_if do |k,_|
<add> parts.include?(k) || !required_default?(k)
<ide> end
<ide> end
<ide>
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def initialize(set, scope, path, options)
<ide> normalize_path!
<ide> normalize_options!
<ide> normalize_requirements!
<del> normalize_defaults!
<ide> normalize_conditions!
<add> normalize_defaults!
<ide> end
<ide>
<ide> def to_route
<ide> def normalize_conditions!
<ide> @conditions[key] = condition
<ide> end
<ide>
<add> @conditions[:required_defaults] = []
<add> options.each do |key, required_default|
<add> next if segment_keys.include?(key) || IGNORE_OPTIONS.include?(key)
<add> next if Regexp === required_default
<add> @conditions[:required_defaults] << key
<add> end
<add>
<ide> via_all = options.delete(:via) if options[:via] == :all
<ide>
<ide> if !via_all && options[:via].blank?
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def build_conditions(current_conditions, path_values)
<ide> end
<ide>
<ide> conditions.keep_if do |k, _|
<del> k == :action || k == :controller ||
<add> k == :action || k == :controller || k == :required_defaults ||
<ide> @request_class.public_method_defined?(k) || path_values.include?(k)
<ide> end
<ide> end
<ide><path>actionpack/test/controller/test_case_test.rb
<ide> def test_controller_name
<ide> assert_equal 'anonymous', @response.body
<ide> end
<ide> end
<add>
<add>class RoutingDefaultsTest < ActionController::TestCase
<add> def setup
<add> @controller = Class.new(ActionController::Base) do
<add> def post
<add> render :text => request.fullpath
<add> end
<add>
<add> def project
<add> render :text => request.fullpath
<add> end
<add> end.new
<add>
<add> @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
<add> r.draw do
<add> get '/posts/:id', :to => 'anonymous#post', :bucket_type => 'post'
<add> get '/projects/:id', :to => 'anonymous#project', :defaults => { :bucket_type => 'project' }
<add> end
<add> end
<add> end
<add>
<add> def test_route_option_can_be_passed_via_process
<add> get :post, :id => 1, :bucket_type => 'post'
<add> assert_equal '/posts/1', @response.body
<add> end
<add>
<add> def test_route_default_is_not_required_for_building_request_uri
<add> get :project, :id => 2
<add> assert_equal '/projects/2', @response.body
<add> end
<add>end
<ide><path>actionpack/test/dispatch/routing_test.rb
<ide> def test_regexp_port_constraints
<ide> assert_response :success
<ide> end
<ide> end
<add>
<add>class TestRouteDefaults < ActionDispatch::IntegrationTest
<add> stub_controllers do |routes|
<add> Routes = routes
<add> Routes.draw do
<add> resources :posts, bucket_type: 'post'
<add> resources :projects, defaults: { bucket_type: 'project' }
<add> end
<add> end
<add>
<add> def app
<add> Routes
<add> end
<add>
<add> include Routes.url_helpers
<add>
<add> def test_route_options_are_required_for_url_for
<add> assert_raises(ActionController::UrlGenerationError) do
<add> assert_equal '/posts/1', url_for(controller: 'posts', action: 'show', id: 1, only_path: true)
<add> end
<add>
<add> assert_equal '/posts/1', url_for(controller: 'posts', action: 'show', id: 1, bucket_type: 'post', only_path: true)
<add> end
<add>
<add> def test_route_defaults_are_not_required_for_url_for
<add> assert_equal '/projects/1', url_for(controller: 'projects', action: 'show', id: 1, only_path: true)
<add> end
<add>end
<ide><path>actionpack/test/journey/route_test.rb
<ide> class TestRoute < ActiveSupport::TestCase
<ide> def test_initialize
<ide> app = Object.new
<ide> path = Path::Pattern.new '/:controller(/:action(/:id(.:format)))'
<del> defaults = Object.new
<add> defaults = {}
<ide> route = Route.new("name", app, path, {}, defaults)
<ide>
<ide> assert_equal app, route.app
<ide> assert_equal path, route.path
<del> assert_equal defaults, route.defaults
<add> assert_same defaults, route.defaults
<ide> end
<ide>
<ide> def test_route_adds_itself_as_memo
<ide> app = Object.new
<ide> path = Path::Pattern.new '/:controller(/:action(/:id(.:format)))'
<del> defaults = Object.new
<add> defaults = {}
<ide> route = Route.new("name", app, path, {}, defaults)
<ide>
<ide> route.ast.grep(Nodes::Terminal).each do |node|
<ide> def test_extras_are_not_included_if_optional_parameter_is_nil
<ide> end
<ide>
<ide> def test_score
<add> constraints = {:required_defaults => [:controller, :action]}
<add> defaults = {:controller=>"pages", :action=>"show"}
<add>
<ide> path = Path::Pattern.new "/page/:id(/:action)(.:format)"
<del> specific = Route.new "name", nil, path, {}, {:controller=>"pages", :action=>"show"}
<add> specific = Route.new "name", nil, path, constraints, defaults
<ide>
<ide> path = Path::Pattern.new "/:controller(/:action(/:id))(.:format)"
<del> generic = Route.new "name", nil, path, {}
<add> generic = Route.new "name", nil, path, constraints
<ide>
<ide> knowledge = {:id=>20, :controller=>"pages", :action=>"show"}
<ide> | 7 |
Python | Python | fix post-mortem in v0.11 | eba7aae107cb3b482e13b0e88908436fe69a3109 | <ide><path>deps/v8/tools/gen-postmortem-metadata.py
<ide> { 'name': 'SmiShiftSize', 'value': 'kSmiShiftSize' },
<ide> { 'name': 'PointerSizeLog2', 'value': 'kPointerSizeLog2' },
<ide>
<add> { 'name': 'OddballFalse', 'value': 'Oddball::kFalse' },
<add> { 'name': 'OddballTrue', 'value': 'Oddball::kTrue' },
<add> { 'name': 'OddballTheHole', 'value': 'Oddball::kTheHole' },
<add> { 'name': 'OddballNull', 'value': 'Oddball::kNull' },
<add> { 'name': 'OddballArgumentMarker', 'value': 'Oddball::kArgumentMarker' },
<add> { 'name': 'OddballUndefined', 'value': 'Oddball::kUndefined' },
<add> { 'name': 'OddballOther', 'value': 'Oddball::kOther' },
<add>
<ide> { 'name': 'prop_desc_key',
<ide> 'value': 'DescriptorArray::kDescriptorKey' },
<ide> { 'name': 'prop_desc_details',
<ide> { 'name': 'prop_type_mask',
<ide> 'value': 'PropertyDetails::TypeField::kMask' },
<ide>
<add> { 'name': 'bit_field2_elements_kind_mask',
<add> 'value': 'Map::kElementsKindMask' },
<add> { 'name': 'bit_field2_elements_kind_shift',
<add> 'value': 'Map::kElementsKindShift' },
<add> { 'name': 'bit_field3_dictionary_map_shift',
<add> 'value': 'Map::DictionaryMap::kShift' },
<add>
<add> { 'name': 'elements_fast_holey_elements',
<add> 'value': 'FAST_HOLEY_ELEMENTS' },
<add> { 'name': 'elements_fast_elements',
<add> 'value': 'FAST_ELEMENTS' },
<add> { 'name': 'elements_dictionary_elements',
<add> 'value': 'DICTIONARY_ELEMENTS' },
<add>
<ide> { 'name': 'off_fp_context',
<ide> 'value': 'StandardFrameConstants::kContextOffset' },
<ide> { 'name': 'off_fp_marker',
<ide> 'Map, transitions, uintptr_t, kTransitionsOrBackPointerOffset',
<ide> 'Map, inobject_properties, int, kInObjectPropertiesOffset',
<ide> 'Map, instance_size, int, kInstanceSizeOffset',
<add> 'Map, bit_field, char, kBitFieldOffset',
<add> 'Map, bit_field2, char, kBitField2Offset',
<add> 'Map, prototype, Object, kPrototypeOffset',
<add> 'StringDictionaryShape, prefix_size, int, kPrefixSize',
<add> 'StringDictionaryShape, entry_size, int, kEntrySize',
<add> 'SeededNumberDictionaryShape, prefix_size, int, kPrefixSize',
<add> 'UnseededNumberDictionaryShape, prefix_size, int, kPrefixSize',
<add> 'NumberDictionaryShape, entry_size, int, kEntrySize',
<add> 'Oddball, kind_offset, int, kKindOffset',
<ide> 'HeapNumber, value, double, kValueOffset',
<ide> 'ConsString, first, String, kFirstOffset',
<ide> 'ConsString, second, String, kSecondOffset',
<ide> def parse_field(call):
<ide> 'value': '%s::%s' % (klass, offset)
<ide> });
<ide>
<del> assert(kind == 'SMI_ACCESSORS');
<add> assert(kind == 'SMI_ACCESSORS' or kind == 'ACCESSORS_TO_SMI');
<ide> klass = args[0];
<ide> field = args[1];
<ide> offset = args[2];
<ide> def load_fields():
<ide> # may span multiple lines and may contain nested parentheses. We also
<ide> # call parse_field() to pick apart the invocation.
<ide> #
<del> prefixes = [ 'ACCESSORS', 'ACCESSORS_GCSAFE', 'SMI_ACCESSORS' ];
<add> prefixes = [ 'ACCESSORS', 'ACCESSORS_GCSAFE',
<add> 'SMI_ACCESSORS', 'ACCESSORS_TO_SMI' ];
<ide> current = '';
<ide> opens = 0;
<ide> | 1 |
Ruby | Ruby | uniformize the desc problems | 18bda1c9b18f53879263a7893f5359ba96b75bff | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_desc
<ide> end
<ide>
<ide> if desc =~ /^([Aa]n?)\s/
<del> problem "Please remove the indefinite article \"#{$1}\" from the beginning of the description"
<add> problem "Description shouldn't start with an indefinite article (#{$1})"
<ide> end
<ide>
<ide> if desc =~ /^#{formula.name} is\s/i | 1 |
Javascript | Javascript | add test for issue #460 | 49ef31403da93b08f88ee47f1eff3f1cd5017d5f | <ide><path>packages/ember-metal/tests/binding/sync_test.js
<ide> testBoth("bindings should do the right thing when binding is in prototype", func
<ide> equal(get(obj, 'selection'), 'a');
<ide> });
<ide>
<add>testBoth("binding with transform should only fire one change when set", function (get, set) {
<add> var a, b, changed, transform;
<add>
<add> Ember.run(function() {
<add> a = {array: null};
<add> b = {a: a};
<add> changed = 0;
<add>
<add> Ember.addObserver(a, 'array', function() {
<add> changed++;
<add> });
<add>
<add> transform = {
<add> to: function(array) {
<add> if (array) {
<add> return array.join(',');
<add> } else {
<add> return array;
<add> }
<add> },
<add> from: function(string) {
<add> if (string) {
<add> return string.split(',');
<add> } else {
<add> return string;
<add> }
<add> }
<add> };
<add> Ember.Binding.from('a.array').to('string').transform(transform).connect(b);
<add> });
<add>
<add> Ember.run(function() {
<add> set(a, 'array', ['a', 'b', 'c']);
<add> });
<add>
<add> equal(changed, 1);
<add> equal(get(b, 'string'), 'a,b,c');
<add>
<add> Ember.run(function() {
<add> set(b, 'string', '1,2,3');
<add> });
<add>
<add> equal(changed, 2);
<add> deepEqual(get(a, 'array'), ['1','2','3']);
<add>});
<add>
<ide> testBoth("bindings should not try to sync destroyed objects", function(get, set) {
<ide> var a, b;
<ide> | 1 |
PHP | PHP | replace \r\n with a proper php_eol | 93b56001c5045a8327a154b6a6534d5faf860bbd | <ide><path>src/Illuminate/Routing/Console/ControllerMakeCommand.php
<ide> protected function buildFormRequestReplacements(array $replace, $modelClass)
<ide>
<ide> $namespacedRequests = $namespace.'\\'.$storeRequestClass.';';
<ide> if ($storeRequestClass != $updateRequestClass) {
<del> $namespacedRequests .= "\r\nuse ".$namespace.'\\'.$updateRequestClass.';';
<add> $namespacedRequests .= PHP_EOL."use ".$namespace.'\\'.$updateRequestClass.';';
<ide> }
<ide>
<ide> return array_merge($replace, [ | 1 |
Javascript | Javascript | add test case | 684d3755418763cc2f671635f5d1de8d41c9afd0 | <ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/0/delayed.js
<add>})]
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/0/foo/0.js
<add>module.exports = '0';
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/0/foo/a.js
<add>module.exports = "This ";
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/0/foo/b.js
<add>module.exports = "is only ";
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/0/foo/c.js
<add>module.exports = "a test";
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/0/index.js
<add>it("should watch for changes", function () {
<add> if (+WATCH_STEP !== 3) expect(require("./delayed")).toBe(WATCH_STEP);
<add> else expect(require("./delayed")).toBe("This is only a test." + WATCH_STEP);
<add> if (+WATCH_STEP > 0) {
<add> for (var m of STATS_JSON.modules.filter(m =>
<add> /(a|b|c)\.js$/.test(m.identifier)
<add> ))
<add> expect(m.issuer).toBe(null);
<add> }
<add>});
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/1/foo/1.js
<add>module.exports = '1';
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/2/foo/2.js
<add>module.exports = '2';
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/3/foo/3.js
<add>var a = require("./a");
<add>var b = require("./b");
<add>var c = require("./c");
<add>
<add>module.exports = a + b + c + '.3';
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/delayed.js
<add>module.exports = function (source) {
<add> expect(source).toMatch(/^\}\)\]/);
<add> this.cacheable(false);
<add> return new Promise(resolve => {
<add> setTimeout(() => {
<add> resolve("module.exports = require('./foo/' + WATCH_STEP);");
<add> }, 500);
<add> });
<add>};
<ide><path>test/watchCases/plugins/automatic-prefetch-plugin-9485/webpack.config.js
<add>const path = require("path");
<add>const webpack = require("../../../../");
<add>
<add>/** @type {import("../../../../").Configuration} */
<add>module.exports = {
<add> module: {
<add> rules: [
<add> {
<add> test: /delayed/,
<add> use: path.resolve(__dirname, "./delayed")
<add> }
<add> ]
<add> },
<add> plugins: [new webpack.AutomaticPrefetchPlugin()]
<add>}; | 11 |
Python | Python | fix model loading for leakyrelu layer | c73ba916f6295586324a298316b5774a53505d8a | <ide><path>keras/layers/advanced_activations.py
<ide> def call(self, inputs):
<ide> return K.relu(inputs, alpha=self.alpha)
<ide>
<ide> def get_config(self):
<del> config = {'alpha': self.alpha}
<add> config = {'alpha': float(self.alpha)}
<ide> base_config = super(LeakyReLU, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide> | 1 |
Python | Python | add option to predict on test set | 5ff9cd158a08f6bcfa5c635c0a2eb6d79e4ef9c2 | <ide><path>examples/run_ner.py
<ide> def train(args, train_dataset, model, tokenizer, labels, pad_token_label_id):
<ide> if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0:
<ide> # Log metrics
<ide> if args.local_rank == -1 and args.evaluate_during_training: # Only evaluate when single GPU otherwise metrics may not average well
<del> results = evaluate(args, model, tokenizer, labels, pad_token_label_id)
<add> results, _ = evaluate(args, model, tokenizer, labels, pad_token_label_id)
<ide> for key, value in results.items():
<ide> tb_writer.add_scalar("eval_{}".format(key), value, global_step)
<ide> tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step)
<ide> def train(args, train_dataset, model, tokenizer, labels, pad_token_label_id):
<ide> return global_step, tr_loss / global_step
<ide>
<ide>
<del>def evaluate(args, model, tokenizer, labels, pad_token_label_id, prefix=""):
<del> eval_dataset = load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, evaluate=True)
<add>def evaluate(args, model, tokenizer, labels, pad_token_label_id, mode, prefix=""):
<add> eval_dataset = load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, mode=mode)
<ide>
<ide> args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
<ide> # Note that DistributedSampler samples randomly
<ide> def evaluate(args, model, tokenizer, labels, pad_token_label_id, prefix=""):
<ide> for key in sorted(results.keys()):
<ide> logger.info(" %s = %s", key, str(results[key]))
<ide>
<del> return results
<add> return results, preds_list
<ide>
<ide>
<del>def load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, evaluate=False):
<add>def load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, mode):
<ide> if args.local_rank not in [-1, 0] and not evaluate:
<ide> torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache
<ide>
<ide> # Load data features from cache or dataset file
<del> cached_features_file = os.path.join(args.data_dir, "cached_{}_{}_{}".format("dev" if evaluate else "train",
<add> cached_features_file = os.path.join(args.data_dir, "cached_{}_{}_{}".format(mode,
<ide> list(filter(None, args.model_name_or_path.split("/"))).pop(),
<ide> str(args.max_seq_length)))
<ide> if os.path.exists(cached_features_file):
<ide> logger.info("Loading features from cached file %s", cached_features_file)
<ide> features = torch.load(cached_features_file)
<ide> else:
<ide> logger.info("Creating features from dataset file at %s", args.data_dir)
<del> examples = read_examples_from_file(args.data_dir, evaluate=evaluate)
<add> examples = read_examples_from_file(args.data_dir, mode)
<ide> features = convert_examples_to_features(examples, labels, args.max_seq_length, tokenizer,
<ide> cls_token_at_end=bool(args.model_type in ["xlnet"]),
<ide> # xlnet has a cls token at the end
<ide> def main():
<ide> help="Whether to run training.")
<ide> parser.add_argument("--do_eval", action="store_true",
<ide> help="Whether to run eval on the dev set.")
<add> parser.add_argument("--do_predict", action="store_true",
<add> help="Whether to run predictions on the test set.")
<ide> parser.add_argument("--evaluate_during_training", action="store_true",
<ide> help="Whether to run evaluation during training at each logging step.")
<ide> parser.add_argument("--do_lower_case", action="store_true",
<ide> def main():
<ide>
<ide> # Training
<ide> if args.do_train:
<del> train_dataset = load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, evaluate=False)
<add> train_dataset = load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, mode="train")
<ide> global_step, tr_loss = train(args, train_dataset, model, tokenizer, labels, pad_token_label_id)
<ide> logger.info(" global_step = %s, average loss = %s", global_step, tr_loss)
<ide>
<ide> def main():
<ide> global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else ""
<ide> model = model_class.from_pretrained(checkpoint)
<ide> model.to(args.device)
<del> result = evaluate(args, model, tokenizer, labels, pad_token_label_id, prefix=global_step)
<add> result, _ = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode="dev", prefix=global_step)
<ide> if global_step:
<ide> result = {"{}_{}".format(global_step, k): v for k, v in result.items()}
<ide> results.update(result)
<ide> def main():
<ide> for key in sorted(results.keys()):
<ide> writer.write("{} = {}\n".format(key, str(results[key])))
<ide>
<add> if args.do_predict and args.local_rank in [-1, 0]:
<add> tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
<add> model = model_class.from_pretrained(args.output_dir)
<add> model.to(args.device)
<add> result, predictions = evaluate(args, model, tokenizer, labels, pad_token_label_id, mode="test")
<add> # Save results
<add> output_test_results_file = os.path.join(args.output_dir, "test_results.txt")
<add> with open(output_test_results_file, "w") as writer:
<add> for key in sorted(result.keys()):
<add> writer.write("{} = {}\n".format(key, str(result[key])))
<add> # Save predictions
<add> output_test_predictions_file = os.path.join(args.output_dir, "test_predictions.txt")
<add> with open(output_test_predictions_file, "w") as writer:
<add> with open(os.path.join(args.data_dir, "test.txt"), "r") as f:
<add> example_id = 0
<add> for line in f:
<add> if line.startswith("-DOCSTART-") or line == "" or line == "\n":
<add> writer.write(line)
<add> if not predictions[example_id]:
<add> example_id += 1
<add> elif predictions[example_id]:
<add> output_line = line.split()[0] + " " + predictions[example_id].pop(0) + "\n"
<add> writer.write(output_line)
<add> else:
<add> logger.warning("Maximum sequence length exceeded: No prediction for '%s'.", line.split()[0])
<add>
<ide> return results
<ide>
<ide>
<ide><path>examples/utils_ner.py
<ide> def __init__(self, input_ids, input_mask, segment_ids, label_ids):
<ide> self.label_ids = label_ids
<ide>
<ide>
<del>def read_examples_from_file(data_dir, evaluate=False):
<del> if evaluate:
<del> file_path = os.path.join(data_dir, "dev.txt")
<del> guid_prefix = "dev"
<del> else:
<del> file_path = os.path.join(data_dir, "train.txt")
<del> guid_prefix = "train"
<add>def read_examples_from_file(data_dir, mode):
<add> file_path = os.path.join(data_dir, "{}.txt".format(mode))
<ide> guid_index = 1
<ide> examples = []
<ide> with open(file_path, encoding="utf-8") as f:
<ide> def read_examples_from_file(data_dir, evaluate=False):
<ide> for line in f:
<ide> if line.startswith("-DOCSTART-") or line == "" or line == "\n":
<ide> if words:
<del> examples.append(InputExample(guid="{}-{}".format(guid_prefix, guid_index),
<add> examples.append(InputExample(guid="{}-{}".format(mode, guid_index),
<ide> words=words,
<ide> labels=labels))
<ide> guid_index += 1
<ide> def read_examples_from_file(data_dir, evaluate=False):
<ide> else:
<ide> splits = line.split(" ")
<ide> words.append(splits[0])
<del> labels.append(splits[-1].replace("\n", ""))
<add> if len(splits) > 1:
<add> labels.append(splits[-1].replace("\n", ""))
<add> else:
<add> # Examples could have no label for mode = "test"
<add> labels.append("O")
<ide> if words:
<del> examples.append(InputExample(guid="%s-%d".format(guid_prefix, guid_index),
<add> examples.append(InputExample(guid="%s-%d".format(mode, guid_index),
<ide> words=words,
<ide> labels=labels))
<ide> return examples | 2 |
Python | Python | remove unnecessary import of mock | 24244939700a061f206db148786a4611040d57b8 | <ide><path>spacy/tests/parser/test_neural_parser.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide> from thinc.neural import Model
<del>from mock import Mock
<ide> import pytest
<ide> import numpy
<ide> | 1 |
PHP | PHP | fix code and test | 9d14fbb21290b0948a46b449e7aa92361eb1df2c | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function where($column, $operator = null, $value = null, $boolean = 'and'
<ide> {
<ide> if ($column instanceof Closure)
<ide> {
<del> $query = $this->model->newQuery();
<add> // Get a new query builder instance but avoid including any soft
<add> // delete constraints that could mess up the nested query.
<add> $query = $this->model->newQuery(false);
<ide>
<ide> call_user_func($column, $query);
<ide>
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php
<ide> public function testNestedWhere()
<ide> $nestedRawQuery = $this->getMockQueryBuilder();
<ide> $nestedQuery->shouldReceive('getQuery')->once()->andReturn($nestedRawQuery);
<ide> $model = $this->getMockModel()->makePartial();
<del> $model->shouldReceive('newQuery')->once()->andReturn($nestedQuery);
<add> $model->shouldReceive('newQuery')->with(false)->once()->andReturn($nestedQuery);
<ide> $builder = $this->getBuilder();
<ide> $builder->getQuery()->shouldReceive('from');
<ide> $builder->setModel($model); | 2 |
Text | Text | change the title of the tip block to note | a6eaaf771f60575927d368bf9b6d48a87c14f902 | <ide><path>docs/charts/area.md
<ide>
<ide> Both [line](./line.mdx) and [radar](./radar.mdx) charts support a `fill` option on the dataset object which can be used to create space between two datasets or a dataset and a boundary, i.e. the scale `origin`, `start,` or `end` (see [filling modes](#filling-modes)).
<ide>
<del>:::tip
<add>:::tip Note
<ide> This feature is implemented by the [`filler` plugin](https://github.com/chartjs/Chart.js/blob/master/src/plugins/plugin.filler.js).
<ide> :::
<ide>
<ide><path>docs/charts/bar.md
<ide> This setting is used to avoid drawing the bar stroke at the base of the fill, or
<ide> In general, this does not need to be changed except when creating chart types
<ide> that derive from a bar chart.
<ide>
<del>:::tip
<add>:::tip Note
<ide> For negative bars in a vertical chart, `top` and `bottom` are flipped. Same goes for `left` and `right` in a horizontal chart.
<ide> :::
<ide>
<ide><path>docs/configuration/animations.md
<ide> Namespace: `options.animations[animation]`
<ide> | `colors` | `properties` | `['color', 'borderColor', 'backgroundColor']`
<ide> | `colors` | `type` | `'color'`
<ide>
<del>:::tip
<add>:::tip Note
<ide> These default animations are overridden by most of the dataset controllers.
<ide> :::
<ide>
<ide><path>docs/general/options.md
<ide> A plugin can provide `additionalOptionScopes` array of paths to additionally loo
<ide> Scriptable options also accept a function which is called for each of the underlying data values and that takes the unique argument `context` representing contextual information (see [option context](options.md#option-context)).
<ide> A resolver is passed as second parameter, that can be used to access other options in the same context.
<ide>
<del>:::tip
<add>:::tip Note
<ide>
<ide> The `context` argument should be validated in the scriptable function, because the function can be invoked in different contexts. The `type` field is a good candidate for this validation.
<ide> | 4 |
Javascript | Javascript | fix an issue with bar charts that are not stacked | 37cfbdb8028b24715589620e9e1ed191486f410a | <ide><path>src/Chart.Bar.js
<ide>
<ide> var offset = 0;
<ide>
<del> for (j = datasetIndex; j < datasets.length; j++) {
<add> for (var j = datasetIndex; j < self.data.datasets.length; j++) {
<ide> if (j === datasetIndex && value) {
<ide> offset += value;
<ide> } else { | 1 |
PHP | PHP | remove the serve command | 84c42305e562c5710fd45e9082ea1ed5c57705b0 | <ide><path>src/Illuminate/Foundation/Console/ServeCommand.php
<del><?php namespace Illuminate\Foundation\Console;
<del>
<del>use Illuminate\Console\Command;
<del>use Symfony\Component\Console\Input\InputOption;
<del>
<del>class ServeCommand extends Command {
<del>
<del> /**
<del> * The console command name.
<del> *
<del> * @var string
<del> */
<del> protected $name = 'serve';
<del>
<del> /**
<del> * The console command description.
<del> *
<del> * @var string
<del> */
<del> protected $description = "Serve the application on the PHP development server";
<del>
<del> /**
<del> * Execute the console command.
<del> *
<del> * @return void
<del> */
<del> public function fire()
<del> {
<del> $this->checkPhpVersion();
<del>
<del> chdir($this->laravel['path.base']);
<del>
<del> $host = $this->input->getOption('host');
<del>
<del> $port = $this->input->getOption('port');
<del>
<del> $public = $this->laravel['path.public'];
<del>
<del> $this->info("Laravel development server started on http://{$host}:{$port}");
<del>
<del> passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} -t \"{$public}\" server.php");
<del> }
<del>
<del> /**
<del> * Check the current PHP version is >= 5.4.
<del> *
<del> * @return void
<del> *
<del> * @throws \Exception
<del> */
<del> protected function checkPhpVersion()
<del> {
<del> if (version_compare(PHP_VERSION, '5.4.0', '<'))
<del> {
<del> throw new \Exception('This PHP binary is not version 5.4 or greater.');
<del> }
<del> }
<del>
<del> /**
<del> * Get the console command options.
<del> *
<del> * @return array
<del> */
<del> protected function getOptions()
<del> {
<del> return array(
<del> array('host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost'),
<del>
<del> array('port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000),
<del> );
<del> }
<del>
<del>}
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> use Illuminate\Support\ServiceProvider;
<ide> use Illuminate\Foundation\Console\UpCommand;
<ide> use Illuminate\Foundation\Console\DownCommand;
<del>use Illuminate\Foundation\Console\ServeCommand;
<ide> use Illuminate\Foundation\Console\TinkerCommand;
<ide> use Illuminate\Foundation\Console\AppNameCommand;
<ide> use Illuminate\Foundation\Console\ChangesCommand;
<ide> class ArtisanServiceProvider extends ServiceProvider {
<ide> 'RouteClear' => 'command.route.clear',
<ide> 'RouteList' => 'command.route.list',
<ide> 'RouteScan' => 'command.route.scan',
<del> 'Serve' => 'command.serve',
<ide> 'Tinker' => 'command.tinker',
<ide> 'Up' => 'command.up',
<ide> ];
<ide> protected function registerRouteScanCommand()
<ide> });
<ide> }
<ide>
<del> /**
<del> * Register the command.
<del> *
<del> * @return void
<del> */
<del> protected function registerServeCommand()
<del> {
<del> $this->app->singleton('command.serve', function()
<del> {
<del> return new ServeCommand;
<del> });
<del> }
<del>
<ide> /**
<ide> * Register the command.
<ide> * | 2 |
Go | Go | remove debug messages | 8d6df3a7e2080d4fad9743beb159f12caa0ff6f7 | <ide><path>engine/job.go
<ide> func (job *Job) DecodeEnv(src io.Reader) error {
<ide> // encoding/json decodes integers to float64, but cannot encode them back.
<ide> // (See http://golang.org/src/pkg/encoding/json/decode.go#L46)
<ide> if fval, ok := v.(float64); ok {
<del> job.Logf("Converted to float: %v->%v", v, fval)
<ide> job.SetenvInt(k, int64(fval))
<ide> } else if sval, ok := v.(string); ok {
<del> job.Logf("Converted to string: %v->%v", v, sval)
<ide> job.Setenv(k, sval)
<ide> } else if val, err := json.Marshal(v); err == nil {
<ide> job.Setenv(k, string(val))
<ide> } else {
<ide> job.Setenv(k, fmt.Sprintf("%v", v))
<ide> }
<del> job.Logf("Decoded %s=%#v to %s=%#v", k, v, k, job.Getenv(k))
<ide> }
<ide> return nil
<ide> }
<ide> func (job *Job) EncodeEnv(dst io.Writer) error {
<ide> } else {
<ide> m[k] = v
<ide> }
<del> job.Logf("Encoded %s=%#v to %s=%#v", k, v, k, m[k])
<ide> }
<ide> if err := json.NewEncoder(dst).Encode(&m); err != nil {
<ide> return err
<ide> func (job *Job) EncodeEnv(dst io.Writer) error {
<ide> }
<ide>
<ide> func (job *Job) ExportEnv(dst interface{}) (err error) {
<del> fmt.Fprintf(os.Stderr, "ExportEnv()\n")
<ide> defer func() {
<ide> if err != nil {
<ide> err = fmt.Errorf("ExportEnv %s", err)
<ide> }
<ide> }()
<ide> var buf bytes.Buffer
<del> job.Logf("ExportEnv: step 1: encode/marshal the env to an intermediary json representation")
<del> fmt.Fprintf(os.Stderr, "Printed ExportEnv step 1\n")
<add> // step 1: encode/marshal the env to an intermediary json representation
<ide> if err := job.EncodeEnv(&buf); err != nil {
<ide> return err
<ide> }
<del> job.Logf("ExportEnv: step 1 complete: json=|%s|", buf)
<del> job.Logf("ExportEnv: step 2: decode/unmarshal the intermediary json into the destination object")
<add> // step 2: decode/unmarshal the intermediary json into the destination object
<ide> if err := json.NewDecoder(&buf).Decode(dst); err != nil {
<ide> return err
<ide> }
<del> job.Logf("ExportEnv: step 2 complete")
<ide> return nil
<ide> }
<ide>
<ide> func (job *Job) ImportEnv(src interface{}) (err error) {
<ide> if err := json.NewEncoder(&buf).Encode(src); err != nil {
<ide> return err
<ide> }
<del> job.Logf("ImportEnv: json=|%s|", buf)
<ide> if err := job.DecodeEnv(&buf); err != nil {
<ide> return err
<ide> }
<ide><path>server.go
<ide> func (srv *Server) RegisterLinks(name string, hostConfig *HostConfig) error {
<ide> }
<ide>
<ide> func (srv *Server) ContainerStart(job *engine.Job) string {
<del> job.Logf("srv engine = %s", srv.Eng.Root())
<del> job.Logf("job engine = %s", job.Eng.Root())
<ide> if len(job.Args) < 1 {
<ide> return fmt.Sprintf("Usage: %s container_id", job.Name)
<ide> }
<ide> name := job.Args[0]
<ide> runtime := srv.runtime
<del> job.Logf("loading containers from %s", runtime.repository)
<ide> container := runtime.Get(name)
<ide> if container == nil {
<ide> return fmt.Sprintf("No such container: %s", name) | 2 |
Java | Java | add support for show layout bounds | 7df627f9be5fdcf05bb2d5244e1fe44102b299eb | <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/AbstractDrawCommand.java
<ide> package com.facebook.react.flat;
<ide>
<ide> import android.graphics.Canvas;
<add>import android.graphics.Color;
<ide>
<ide> /**
<ide> * Base class for all DrawCommands. Becomes immutable once it has its bounds set. Until then, a
<ide> public final void draw(FlatViewGroup parent, Canvas canvas) {
<ide> }
<ide> }
<ide>
<add> protected static int getDebugBorderColor() {
<add> return Color.CYAN;
<add> }
<add>
<add> protected String getDebugName() {
<add> return getClass().getSimpleName().substring(4);
<add> }
<add>
<add> @Override
<add> public void debugDraw(FlatViewGroup parent, Canvas canvas) {
<add> parent.debugDrawNamedRect(
<add> canvas,
<add> getDebugBorderColor(),
<add> getDebugName(),
<add> mLeft,
<add> mTop,
<add> mRight,
<add> mBottom);
<add> }
<add>
<ide> protected void onPreDraw(FlatViewGroup parent, Canvas canvas) {
<ide> }
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawCommand.java
<ide> public interface DrawCommand {
<ide> /**
<ide> * Performs drawing into the given canvas.
<ide> *
<add> * @param parent The parent to get child information from, if needed
<ide> * @param canvas The canvas to draw into
<ide> */
<ide> public void draw(FlatViewGroup parent, Canvas canvas);
<add>
<add> /**
<add> * Performs debug bounds drawing into the given canvas.
<add> *
<add> * @param parent The parent to get child information from, if needed
<add> * @param canvas The canvas to draw into
<add> */
<add> public void debugDraw(FlatViewGroup parent, Canvas canvas);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/DrawView.java
<ide> public void draw(FlatViewGroup parent, Canvas canvas) {
<ide> parent.drawNextChild(canvas);
<ide> }
<ide> }
<add>
<add> @Override
<add> public void debugDraw(FlatViewGroup parent, Canvas canvas) {
<add> parent.debugDrawNextChild(canvas);
<add> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatViewGroup.java
<ide> import android.annotation.SuppressLint;
<ide> import android.content.Context;
<ide> import android.graphics.Canvas;
<add>import android.graphics.Color;
<add>import android.graphics.Paint;
<ide> import android.graphics.Rect;
<ide> import android.graphics.drawable.Drawable;
<ide> import android.view.MotionEvent;
<ide> public void dispatchImageLoadEvent(int reactTag, int imageLoadEvent) {
<ide> }
<ide> }
<ide>
<add> private static final boolean DEBUG_DRAW = false;
<add> private static final boolean DEBUG_DRAW_TEXT = false;
<add> private boolean mAndroidDebugDraw;
<add> private static Paint sDebugTextPaint;
<add> private static Paint sDebugTextBackgroundPaint;
<add> private static Paint sDebugRectPaint;
<add> private static Paint sDebugCornerPaint;
<add> private static Rect sDebugRect;
<add>
<ide> private static final ArrayList<FlatViewGroup> LAYOUT_REQUESTS = new ArrayList<>();
<ide> private static final Rect VIEW_BOUNDS = new Rect();
<ide> private static final Rect EMPTY_RECT = new Rect();
<ide> public boolean interceptsTouchEvent(float touchX, float touchY) {
<ide> return nodeRegion != null && nodeRegion.mIsVirtual;
<ide> }
<ide>
<add> // This is hidden in the Android ViewGroup, but still gets called in super.dispatchDraw.
<add> protected void onDebugDraw(Canvas canvas) {
<add> // Android is drawing layout bounds, so we should as well.
<add> mAndroidDebugDraw = true;
<add> }
<add>
<ide> @Override
<ide> public void dispatchDraw(Canvas canvas) {
<add> mAndroidDebugDraw = false;
<ide> super.dispatchDraw(canvas);
<ide>
<ide> if (mRemoveClippedSubviews) {
<ide> public void dispatchDraw(Canvas canvas) {
<ide> }
<ide> mDrawChildIndex = 0;
<ide>
<add> if (DEBUG_DRAW || mAndroidDebugDraw) {
<add> initDebugDrawResources();
<add> debugDraw(canvas);
<add> }
<add>
<ide> if (mHotspot != null) {
<ide> mHotspot.draw(canvas);
<ide> }
<ide> }
<ide>
<add> private void debugDraw(Canvas canvas) {
<add> for (DrawCommand drawCommand : mDrawCommands) {
<add> if (drawCommand instanceof DrawView) {
<add> if (!((DrawView) drawCommand).isViewGroupClipped) {
<add> drawCommand.debugDraw(this, canvas);
<add> }
<add> // else, don't draw, and don't increment index
<add> } else {
<add> drawCommand.debugDraw(this, canvas);
<add> }
<add> }
<add> mDrawChildIndex = 0;
<add> }
<add>
<ide> @Override
<ide> protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
<ide> // suppress
<ide> // no drawing -> no invalidate -> return false
<ide> return false;
<ide> }
<ide>
<add> /* package */ void debugDrawNextChild(Canvas canvas) {
<add> View child = getChildAt(mDrawChildIndex);
<add> // Draw FlatViewGroups a different color than regular child views.
<add> int color = child instanceof FlatViewGroup ? Color.DKGRAY : Color.RED;
<add> debugDrawRect(
<add> canvas,
<add> color,
<add> child.getLeft(),
<add> child.getTop(),
<add> child.getRight(),
<add> child.getBottom());
<add> ++mDrawChildIndex;
<add> }
<add>
<add> // Used in debug drawing.
<add> private int dipsToPixels(int dips) {
<add> float scale = getResources().getDisplayMetrics().density;
<add> return (int) (dips * scale + 0.5f);
<add> }
<add>
<add> // Used in debug drawing.
<add> private static void fillRect(Canvas canvas, Paint paint, float x1, float y1, float x2, float y2) {
<add> if (x1 != x2 && y1 != y2) {
<add> if (x1 > x2) {
<add> float tmp = x1; x1 = x2; x2 = tmp;
<add> }
<add> if (y1 > y2) {
<add> float tmp = y1; y1 = y2; y2 = tmp;
<add> }
<add> canvas.drawRect(x1, y1, x2, y2, paint);
<add> }
<add> }
<add>
<add> // Used in debug drawing.
<add> private static int sign(float x) {
<add> return (x >= 0) ? 1 : -1;
<add> }
<add>
<add> // Used in debug drawing.
<add> private static void drawCorner(
<add> Canvas c,
<add> Paint paint,
<add> float x1,
<add> float y1,
<add> float dx,
<add> float dy,
<add> float lw) {
<add> fillRect(c, paint, x1, y1, x1 + dx, y1 + lw * sign(dy));
<add> fillRect(c, paint, x1, y1, x1 + lw * sign(dx), y1 + dy);
<add> }
<add>
<add> // Used in debug drawing.
<add> private static void drawRectCorners(
<add> Canvas canvas,
<add> float x1,
<add> float y1,
<add> float x2,
<add> float y2,
<add> Paint paint,
<add> int lineLength,
<add> int lineWidth) {
<add> drawCorner(canvas, paint, x1, y1, lineLength, lineLength, lineWidth);
<add> drawCorner(canvas, paint, x1, y2, lineLength, -lineLength, lineWidth);
<add> drawCorner(canvas, paint, x2, y1, -lineLength, lineLength, lineWidth);
<add> drawCorner(canvas, paint, x2, y2, -lineLength, -lineLength, lineWidth);
<add> }
<add>
<add> private void initDebugDrawResources() {
<add> if (sDebugTextPaint == null) {
<add> sDebugTextPaint = new Paint();
<add> sDebugTextPaint.setTextAlign(Paint.Align.RIGHT);
<add> sDebugTextPaint.setTextSize(dipsToPixels(9));
<add> sDebugTextPaint.setColor(Color.RED);
<add> }
<add> if (sDebugTextBackgroundPaint == null) {
<add> sDebugTextBackgroundPaint = new Paint();
<add> sDebugTextBackgroundPaint.setColor(Color.WHITE);
<add> sDebugTextBackgroundPaint.setAlpha(200);
<add> sDebugTextBackgroundPaint.setStyle(Paint.Style.FILL);
<add> }
<add> if (sDebugRectPaint == null) {
<add> sDebugRectPaint = new Paint();
<add> sDebugRectPaint.setAlpha(100);
<add> sDebugRectPaint.setStyle(Paint.Style.STROKE);
<add> }
<add> if (sDebugCornerPaint == null) {
<add> sDebugCornerPaint = new Paint();
<add> sDebugCornerPaint.setAlpha(200);
<add> sDebugCornerPaint.setColor(Color.rgb(63, 127, 255));
<add> sDebugCornerPaint.setStyle(Paint.Style.FILL);
<add> }
<add> if (sDebugRect == null) {
<add> sDebugRect = new Rect();
<add> }
<add> }
<add>
<add> private void debugDrawRect(
<add> Canvas canvas,
<add> int color,
<add> float left,
<add> float top,
<add> float right,
<add> float bottom) {
<add> debugDrawNamedRect(canvas, color, "", left, top, right, bottom);
<add> }
<add>
<add> /* package */ void debugDrawNamedRect(
<add> Canvas canvas,
<add> int color,
<add> String name,
<add> float left,
<add> float top,
<add> float right,
<add> float bottom) {
<add> if (DEBUG_DRAW_TEXT && !name.isEmpty()) {
<add> sDebugTextPaint.getTextBounds(name, 0, name.length(), sDebugRect);
<add> int inset = dipsToPixels(2);
<add> float textRight = right - inset - 1;
<add> float textBottom = bottom - inset - 1;
<add> canvas.drawRect(
<add> textRight - sDebugRect.right - inset,
<add> textBottom + sDebugRect.top - inset,
<add> textRight + inset,
<add> textBottom + inset,
<add> sDebugTextBackgroundPaint);
<add> canvas.drawText(name, textRight, textBottom, sDebugTextPaint);
<add> }
<add> // Retain the alpha component.
<add> sDebugRectPaint.setColor((sDebugRectPaint.getColor() & 0xFF000000) | (color & 0x00FFFFFF));
<add> sDebugRectPaint.setAlpha(100);
<add> canvas.drawRect(
<add> left,
<add> top,
<add> right - 1,
<add> bottom - 1,
<add> sDebugRectPaint);
<add> drawRectCorners(
<add> canvas,
<add> left,
<add> top,
<add> right,
<add> bottom,
<add> sDebugCornerPaint,
<add> dipsToPixels(8),
<add> dipsToPixels(1));
<add> }
<add>
<ide> @Override
<ide> protected void onLayout(boolean changed, int l, int t, int r, int b) {
<ide> // nothing to do here | 4 |
Python | Python | add test for __array_interface__ | 47161378d8e4eb892846f7b0156fa2344fd11ee2 | <ide><path>numpy/core/tests/test_multiarray.py
<ide> def __array_interface__(self):
<ide> f.iface['shape'] = (2,)
<ide> assert_raises(ValueError, np.array, f)
<ide>
<add> # test scalar with no shape
<add> class ArrayLike(object):
<add> array = np.array(1)
<add> __array_interface__ = array.__array_interface__
<add> assert_equal(np.array(ArrayLike()), 1)
<add>
<add>
<ide> def test_flat_element_deletion():
<ide> it = np.ones(3).flat
<ide> try: | 1 |
Python | Python | fix defaults for ud-train | 3eb9f3e2b84361de37e8c7d08df75b2ead01aea0 | <ide><path>spacy/cli/ud_train.py
<ide> def initialize_pipeline(nlp, docs, golds, config, device):
<ide> ########################
<ide>
<ide> class Config(object):
<del> def __init__(self, vectors=None, max_doc_length=10, multitask_tag=True,
<del> multitask_sent=True, multitask_dep=True, multitask_vectors=False,
<del> nr_epoch=30, min_batch_size=1, max_batch_size=16, batch_by_words=False,
<del> dropout=0.2, conv_depth=4, subword_features=True):
<add> def __init__(self, vectors=None, max_doc_length=10, multitask_tag=False,
<add> multitask_sent=False, multitask_dep=False, multitask_vectors=None,
<add> nr_epoch=30, min_batch_size=100, max_batch_size=1000,
<add> batch_by_words=True, dropout=0.2, conv_depth=4, subword_features=True,
<add> vectors_dir=None):
<add> if vectors_dir is not None:
<add> if vectors is None:
<add> vectors = True
<add> if multitask_vectors is None:
<add> multitask_vectors = True
<ide> for key, value in locals().items():
<ide> setattr(self, key, value)
<ide>
<ide> @classmethod
<del> def load(cls, loc):
<add> def load(cls, loc, vectors_dir=None):
<ide> with Path(loc).open('r', encoding='utf8') as file_:
<ide> cfg = json.load(file_)
<add> if vectors_dir is not None:
<add> cfg['vectors_dir'] = vectors_dir
<ide> return cls(**cfg)
<ide>
<ide>
<ide> def __init__(self, ud_path, treebank, **cfg):
<ide> vectors_dir=("Path to directory with pre-trained vectors, named e.g. en/",
<ide> "option", "v", Path),
<ide> )
<del>def main(ud_dir, parses_dir, config=None, corpus, limit=0, use_gpu=-1, vectors_dir=None,
<add>def main(ud_dir, parses_dir, corpus, config=None, limit=0, use_gpu=-1, vectors_dir=None,
<ide> use_oracle_segments=False):
<ide> spacy.util.fix_random_seed()
<ide> lang.zh.Chinese.Defaults.use_jieba = False
<ide> lang.ja.Japanese.Defaults.use_janome = False
<ide>
<ide> if config is not None:
<del> config = Config.load(config)
<add> config = Config.load(config, vectors_dir=vectors_dir)
<ide> else:
<del> config = Config()
<add> config = Config(vectors_dir=vectors_dir)
<ide> paths = TreebankPaths(ud_dir, corpus)
<ide> if not (parses_dir / corpus).exists():
<ide> (parses_dir / corpus).mkdir() | 1 |
Go | Go | fix typos in daemon_unix.go | 25c9bd81f6d293996856daeb19108ebb2522416b | <ide><path>daemon/daemon_unix.go
<ide> func configureMaxThreads(config *Config) error {
<ide> return nil
<ide> }
<ide>
<del>// configureKernelSecuritySupport configures and validate security support for the kernel
<add>// configureKernelSecuritySupport configures and validates security support for the kernel
<ide> func configureKernelSecuritySupport(config *Config, driverName string) error {
<ide> if config.EnableSelinuxSupport {
<ide> if selinuxEnabled() {
<ide> func parseRemappedRoot(usergrp string) (string, string, error) {
<ide>
<ide> if len(idparts) == 2 {
<ide> // groupname or gid is separately specified and must be resolved
<del> // to a unsigned 32-bit gid
<add> // to an unsigned 32-bit gid
<ide> if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
<ide> // must be a gid, take it as valid
<ide> groupID = int(gid)
<ide> func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error
<ide> if config.RemappedRoot != "" {
<ide> config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootUID, rootGID))
<ide> logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
<del> // Create the root directory if it doesn't exists
<add> // Create the root directory if it doesn't exist
<ide> if err := idtools.MkdirAllAs(config.Root, 0700, rootUID, rootGID); err != nil {
<ide> return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
<ide> }
<ide> func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
<ide> return s, nil
<ide> }
<ide>
<del>// setDefaultIsolation determine the default isolation mode for the
<add>// setDefaultIsolation determines the default isolation mode for the
<ide> // daemon to run in. This is only applicable on Windows
<ide> func (daemon *Daemon) setDefaultIsolation() error {
<ide> return nil | 1 |
Go | Go | fix flaky test testtransfer | 2f4aa9658408ac72a598363c6e22eadf93dbb8a7 | <ide><path>distribution/xfer/transfer_test.go
<ide> func TestTransfer(t *testing.T) {
<ide> if p.Current != 0 {
<ide> t.Fatalf("got unexpected progress value: %d (expected 0)", p.Current)
<ide> }
<del> } else if p.Current != val+1 {
<add> } else if p.Current <= val {
<ide> t.Fatalf("got unexpected progress value: %d (expected %d)", p.Current, val+1)
<ide> }
<ide> receivedProgress[p.ID] = p.Current | 1 |
Text | Text | add lint disabling comment for collaborator list | 25d48a63c045a8c52f560e050710176a5a4ee304 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide>
<ide> ### TSC (Technical Steering Committee)
<ide>
<add><!--lint disable prohibited-strings-->
<ide> * [addaleax](https://github.com/addaleax) -
<ide> **Anna Henningsen** <[email protected]> (she/her)
<ide> * [apapirovski](https://github.com/apapirovski) -
<ide> For information about the governance of the Node.js project, see
<ide> **Vse Mozhet Byt** <[email protected]> (he/him)
<ide> * [whitlockjc](https://github.com/whitlockjc) -
<ide> **Jeremy Whitlock** <[email protected]>
<add><!--lint enable prohibited-strings-->
<ide>
<ide> Collaborators follow the [Collaborator Guide](./doc/guides/collaborator-guide.md) in
<ide> maintaining the Node.js project. | 1 |
Python | Python | reduce np.testing to is_pypy | e52472411e6596808963e1a34d7b9ef0a1f6ef41 | <ide><path>numpy/f2py/tests/test_abstract_interface.py
<ide> from . import util
<ide> from numpy.f2py import crackfortran
<ide>
<del>from numpy.testing import assert_
<del>
<ide>
<ide> class TestAbstractInterface(util.F2PyTest):
<ide> sources = [util.getpath("tests", "src", "abstract_interface", "foo.f90")]
<ide>
<ide> skip = ["add1", "add2"]
<ide>
<ide> def test_abstract_interface(self):
<del> assert_(self.module.ops_module.foo(3, 5) == (8, 13))
<add> assert self.module.ops_module.foo(3, 5) == (8, 13)
<ide>
<ide> def test_parse_abstract_interface(self):
<ide> # Test gh18403
<ide><path>numpy/f2py/tests/test_array_from_pyobj.py
<ide>
<ide> import numpy as np
<ide>
<del>from numpy.testing import assert_, assert_equal
<ide> from numpy.core.multiarray import typeinfo
<ide> from . import util
<ide>
<ide> def _init(self, name):
<ide> self.NAME = name.upper()
<ide> info = typeinfo[self.NAME]
<ide> self.type_num = getattr(wrap, "NPY_" + self.NAME)
<del> assert_equal(self.type_num, info.num)
<add> assert self.type_num == info.num
<ide> self.dtype = np.dtype(info.type)
<ide> self.type = info.type
<ide> self.elsize = info.bits / 8
<ide> def __init__(self, typ, dims, intent, obj):
<ide> # arr.dtypechar may be different from typ.dtypechar
<ide> self.arr = wrap.call(typ.type_num, dims, intent.flags, obj)
<ide>
<del> assert_(isinstance(self.arr, np.ndarray), repr(type(self.arr)))
<add> assert isinstance(self.arr, np.ndarray)
<ide>
<ide> self.arr_attr = wrap.array_attrs(self.arr)
<ide>
<ide> if len(dims) > 1:
<ide> if self.intent.is_intent("c"):
<del> assert_(intent.flags & wrap.F2PY_INTENT_C)
<del> assert_(
<del> not self.arr.flags["FORTRAN"],
<del> repr((self.arr.flags, getattr(obj, "flags", None))),
<del> )
<del> assert_(self.arr.flags["CONTIGUOUS"])
<del> assert_(not self.arr_attr[6] & wrap.FORTRAN)
<add> assert (intent.flags & wrap.F2PY_INTENT_C)
<add> assert not self.arr.flags["FORTRAN"]
<add> assert self.arr.flags["CONTIGUOUS"]
<add> assert (not self.arr_attr[6] & wrap.FORTRAN)
<ide> else:
<del> assert_(not intent.flags & wrap.F2PY_INTENT_C)
<del> assert_(self.arr.flags["FORTRAN"])
<del> assert_(not self.arr.flags["CONTIGUOUS"])
<del> assert_(self.arr_attr[6] & wrap.FORTRAN)
<add> assert (not intent.flags & wrap.F2PY_INTENT_C)
<add> assert self.arr.flags["FORTRAN"]
<add> assert not self.arr.flags["CONTIGUOUS"]
<add> assert (self.arr_attr[6] & wrap.FORTRAN)
<ide>
<ide> if obj is None:
<ide> self.pyarr = None
<ide> self.pyarr_attr = None
<ide> return
<ide>
<ide> if intent.is_intent("cache"):
<del> assert_(isinstance(obj, np.ndarray), repr(type(obj)))
<add> assert isinstance(obj, np.ndarray), repr(type(obj))
<ide> self.pyarr = np.array(obj).reshape(*dims).copy()
<ide> else:
<ide> self.pyarr = np.array(
<ide> np.array(obj, dtype=typ.dtypechar).reshape(*dims),
<ide> order=self.intent.is_intent("c") and "C" or "F",
<ide> )
<del> assert_(self.pyarr.dtype == typ, repr((self.pyarr.dtype, typ)))
<add> assert self.pyarr.dtype == typ
<ide> self.pyarr.setflags(write=self.arr.flags["WRITEABLE"])
<del> assert_(self.pyarr.flags["OWNDATA"], (obj, intent))
<add> assert self.pyarr.flags["OWNDATA"], (obj, intent)
<ide> self.pyarr_attr = wrap.array_attrs(self.pyarr)
<ide>
<ide> if len(dims) > 1:
<ide> if self.intent.is_intent("c"):
<del> assert_(not self.pyarr.flags["FORTRAN"])
<del> assert_(self.pyarr.flags["CONTIGUOUS"])
<del> assert_(not self.pyarr_attr[6] & wrap.FORTRAN)
<add> assert not self.pyarr.flags["FORTRAN"]
<add> assert self.pyarr.flags["CONTIGUOUS"]
<add> assert (not self.pyarr_attr[6] & wrap.FORTRAN)
<ide> else:
<del> assert_(self.pyarr.flags["FORTRAN"])
<del> assert_(not self.pyarr.flags["CONTIGUOUS"])
<del> assert_(self.pyarr_attr[6] & wrap.FORTRAN)
<add> assert self.pyarr.flags["FORTRAN"]
<add> assert not self.pyarr.flags["CONTIGUOUS"]
<add> assert (self.pyarr_attr[6] & wrap.FORTRAN)
<ide>
<del> assert_(self.arr_attr[1] == self.pyarr_attr[1]) # nd
<del> assert_(self.arr_attr[2] == self.pyarr_attr[2]) # dimensions
<add> assert self.arr_attr[1] == self.pyarr_attr[1] # nd
<add> assert self.arr_attr[2] == self.pyarr_attr[2] # dimensions
<ide> if self.arr_attr[1] <= 1:
<del> assert_(
<del> self.arr_attr[3] == self.pyarr_attr[3],
<del> repr((
<del> self.arr_attr[3],
<del> self.pyarr_attr[3],
<del> self.arr.tobytes(),
<del> self.pyarr.tobytes(),
<del> )),
<del> ) # strides
<del> assert_(
<del> self.arr_attr[5][-2:] == self.pyarr_attr[5][-2:],
<del> repr((self.arr_attr[5], self.pyarr_attr[5])),
<del> ) # descr
<del> assert_(
<del> self.arr_attr[6] == self.pyarr_attr[6],
<del> repr((
<del> self.arr_attr[6],
<del> self.pyarr_attr[6],
<del> flags2names(0 * self.arr_attr[6] - self.pyarr_attr[6]),
<del> flags2names(self.arr_attr[6]),
<del> intent,
<del> )),
<del> ) # flags
<add> assert self.arr_attr[3] == self.pyarr_attr[3], repr((
<add> self.arr_attr[3],
<add> self.pyarr_attr[3],
<add> self.arr.tobytes(),
<add> self.pyarr.tobytes(),
<add> )) # strides
<add> assert self.arr_attr[5][-2:] == self.pyarr_attr[5][-2:] # descr
<add> assert self.arr_attr[6] == self.pyarr_attr[6], repr((
<add> self.arr_attr[6],
<add> self.pyarr_attr[6],
<add> flags2names(0 * self.arr_attr[6] - self.pyarr_attr[6]),
<add> flags2names(self.arr_attr[6]),
<add> intent,
<add> )) # flags
<ide>
<ide> if intent.is_intent("cache"):
<del> assert_(
<del> self.arr_attr[5][3] >= self.type.elsize,
<del> repr((self.arr_attr[5][3], self.type.elsize)),
<del> )
<add> assert self.arr_attr[5][3] >= self.type.elsize
<ide> else:
<del> assert_(
<del> self.arr_attr[5][3] == self.type.elsize,
<del> repr((self.arr_attr[5][3], self.type.elsize)),
<del> )
<del> assert_(self.arr_equal(self.pyarr, self.arr))
<add> assert self.arr_attr[5][3] == self.type.elsize
<add> assert (self.arr_equal(self.pyarr, self.arr))
<ide>
<ide> if isinstance(self.obj, np.ndarray):
<ide> if typ.elsize == Type(obj.dtype).elsize:
<ide> if not intent.is_intent("copy") and self.arr_attr[1] <= 1:
<del> assert_(self.has_shared_memory())
<add> assert self.has_shared_memory()
<ide>
<ide> def arr_equal(self, arr1, arr2):
<ide> if arr1.shape != arr2.shape:
<ide> def has_shared_memory(self):
<ide>
<ide> class TestIntent:
<ide> def test_in_out(self):
<del> assert_equal(str(intent.in_.out), "intent(in,out)")
<del> assert_(intent.in_.c.is_intent("c"))
<del> assert_(not intent.in_.c.is_intent_exact("c"))
<del> assert_(intent.in_.c.is_intent_exact("c", "in"))
<del> assert_(intent.in_.c.is_intent_exact("in", "c"))
<del> assert_(not intent.in_.is_intent("c"))
<add> assert str(intent.in_.out) == "intent(in,out)"
<add> assert intent.in_.c.is_intent("c")
<add> assert not intent.in_.c.is_intent_exact("c")
<add> assert intent.in_.c.is_intent_exact("c", "in")
<add> assert intent.in_.c.is_intent_exact("in", "c")
<add> assert not intent.in_.is_intent("c")
<ide>
<ide>
<ide> class TestSharedMemory:
<ide> def setup_type(self, request):
<ide>
<ide> def test_in_from_2seq(self):
<ide> a = self.array([2], intent.in_, self.num2seq)
<del> assert_(not a.has_shared_memory())
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_in_from_2casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = np.array(self.num2seq, dtype=t.dtype)
<ide> a = self.array([len(self.num2seq)], intent.in_, obj)
<ide> if t.elsize == self.type.elsize:
<del> assert_(a.has_shared_memory(), repr(
<del> (self.type.dtype, t.dtype)))
<add> assert a.has_shared_memory(), repr((self.type.dtype, t.dtype))
<ide> else:
<del> assert_(not a.has_shared_memory(), repr(t.dtype))
<add> assert not a.has_shared_memory()
<ide>
<ide> @pytest.mark.parametrize("write", ["w", "ro"])
<ide> @pytest.mark.parametrize("order", ["C", "F"])
<ide> def test_in_nocopy(self, write, order, inp):
<ide> def test_inout_2seq(self):
<ide> obj = np.array(self.num2seq, dtype=self.type.dtype)
<ide> a = self.array([len(self.num2seq)], intent.inout, obj)
<del> assert_(a.has_shared_memory())
<add> assert a.has_shared_memory()
<ide>
<ide> try:
<ide> a = self.array([2], intent.in_.inout, self.num2seq)
<ide> def test_f_inout_23seq(self):
<ide> obj = np.array(self.num23seq, dtype=self.type.dtype, order="F")
<ide> shape = (len(self.num23seq), len(self.num23seq[0]))
<ide> a = self.array(shape, intent.in_.inout, obj)
<del> assert_(a.has_shared_memory())
<add> assert a.has_shared_memory()
<ide>
<ide> obj = np.array(self.num23seq, dtype=self.type.dtype, order="C")
<ide> shape = (len(self.num23seq), len(self.num23seq[0]))
<ide> def test_c_inout_23seq(self):
<ide> obj = np.array(self.num23seq, dtype=self.type.dtype)
<ide> shape = (len(self.num23seq), len(self.num23seq[0]))
<ide> a = self.array(shape, intent.in_.c.inout, obj)
<del> assert_(a.has_shared_memory())
<add> assert a.has_shared_memory()
<ide>
<ide> def test_in_copy_from_2casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = np.array(self.num2seq, dtype=t.dtype)
<ide> a = self.array([len(self.num2seq)], intent.in_.copy, obj)
<del> assert_(not a.has_shared_memory(), repr(t.dtype))
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_c_in_from_23seq(self):
<ide> a = self.array(
<ide> [len(self.num23seq), len(self.num23seq[0])], intent.in_,
<ide> self.num23seq)
<del> assert_(not a.has_shared_memory())
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_in_from_23casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = np.array(self.num23seq, dtype=t.dtype)
<ide> a = self.array(
<ide> [len(self.num23seq), len(self.num23seq[0])], intent.in_, obj)
<del> assert_(not a.has_shared_memory(), repr(t.dtype))
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_f_in_from_23casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = np.array(self.num23seq, dtype=t.dtype, order="F")
<ide> a = self.array(
<ide> [len(self.num23seq), len(self.num23seq[0])], intent.in_, obj)
<ide> if t.elsize == self.type.elsize:
<del> assert_(a.has_shared_memory(), repr(t.dtype))
<add> assert a.has_shared_memory()
<ide> else:
<del> assert_(not a.has_shared_memory(), repr(t.dtype))
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_c_in_from_23casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = np.array(self.num23seq, dtype=t.dtype)
<ide> a = self.array(
<ide> [len(self.num23seq), len(self.num23seq[0])], intent.in_.c, obj)
<ide> if t.elsize == self.type.elsize:
<del> assert_(a.has_shared_memory(), repr(t.dtype))
<add> assert a.has_shared_memory()
<ide> else:
<del> assert_(not a.has_shared_memory(), repr(t.dtype))
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_f_copy_in_from_23casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = np.array(self.num23seq, dtype=t.dtype, order="F")
<ide> a = self.array(
<ide> [len(self.num23seq), len(self.num23seq[0])], intent.in_.copy,
<ide> obj)
<del> assert_(not a.has_shared_memory(), repr(t.dtype))
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_c_copy_in_from_23casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = np.array(self.num23seq, dtype=t.dtype)
<ide> a = self.array(
<ide> [len(self.num23seq), len(self.num23seq[0])], intent.in_.c.copy,
<ide> obj)
<del> assert_(not a.has_shared_memory(), repr(t.dtype))
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_in_cache_from_2casttype(self):
<ide> for t in self.type.all_types():
<ide> def test_in_cache_from_2casttype(self):
<ide> obj = np.array(self.num2seq, dtype=t.dtype)
<ide> shape = (len(self.num2seq), )
<ide> a = self.array(shape, intent.in_.c.cache, obj)
<del> assert_(a.has_shared_memory(), repr(t.dtype))
<add> assert a.has_shared_memory()
<ide>
<ide> a = self.array(shape, intent.in_.cache, obj)
<del> assert_(a.has_shared_memory(), repr(t.dtype))
<add> assert a.has_shared_memory()
<ide>
<ide> obj = np.array(self.num2seq, dtype=t.dtype, order="F")
<ide> a = self.array(shape, intent.in_.c.cache, obj)
<del> assert_(a.has_shared_memory(), repr(t.dtype))
<add> assert a.has_shared_memory()
<ide>
<ide> a = self.array(shape, intent.in_.cache, obj)
<del> assert_(a.has_shared_memory(), repr(t.dtype))
<add> assert a.has_shared_memory(), repr(t.dtype)
<ide>
<ide> try:
<ide> a = self.array(shape, intent.in_.cache, obj[::-1])
<ide> def test_in_cache_from_2casttype_failure(self):
<ide> def test_cache_hidden(self):
<ide> shape = (2, )
<ide> a = self.array(shape, intent.cache.hide, None)
<del> assert_(a.arr.shape == shape)
<add> assert a.arr.shape == shape
<ide>
<ide> shape = (2, 3)
<ide> a = self.array(shape, intent.cache.hide, None)
<del> assert_(a.arr.shape == shape)
<add> assert a.arr.shape == shape
<ide>
<ide> shape = (-1, 3)
<ide> try:
<ide> def test_cache_hidden(self):
<ide> def test_hidden(self):
<ide> shape = (2, )
<ide> a = self.array(shape, intent.hide, None)
<del> assert_(a.arr.shape == shape)
<del> assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
<add> assert a.arr.shape == shape
<add> assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
<ide>
<ide> shape = (2, 3)
<ide> a = self.array(shape, intent.hide, None)
<del> assert_(a.arr.shape == shape)
<del> assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
<del> assert_(a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"])
<add> assert a.arr.shape == shape
<add> assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
<add> assert a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"]
<ide>
<ide> shape = (2, 3)
<ide> a = self.array(shape, intent.c.hide, None)
<del> assert_(a.arr.shape == shape)
<del> assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
<del> assert_(not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"])
<add> assert a.arr.shape == shape
<add> assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
<add> assert not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"]
<ide>
<ide> shape = (-1, 3)
<ide> try:
<ide> def test_hidden(self):
<ide> def test_optional_none(self):
<ide> shape = (2, )
<ide> a = self.array(shape, intent.optional, None)
<del> assert_(a.arr.shape == shape)
<del> assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
<add> assert a.arr.shape == shape
<add> assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
<ide>
<ide> shape = (2, 3)
<ide> a = self.array(shape, intent.optional, None)
<del> assert_(a.arr.shape == shape)
<del> assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
<del> assert_(a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"])
<add> assert a.arr.shape == shape
<add> assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
<add> assert a.arr.flags["FORTRAN"] and not a.arr.flags["CONTIGUOUS"]
<ide>
<ide> shape = (2, 3)
<ide> a = self.array(shape, intent.c.optional, None)
<del> assert_(a.arr.shape == shape)
<del> assert_(a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype)))
<del> assert_(not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"])
<add> assert a.arr.shape == shape
<add> assert a.arr_equal(a.arr, np.zeros(shape, dtype=self.type.dtype))
<add> assert not a.arr.flags["FORTRAN"] and a.arr.flags["CONTIGUOUS"]
<ide>
<ide> def test_optional_from_2seq(self):
<ide> obj = self.num2seq
<ide> shape = (len(obj), )
<ide> a = self.array(shape, intent.optional, obj)
<del> assert_(a.arr.shape == shape)
<del> assert_(not a.has_shared_memory())
<add> assert a.arr.shape == shape
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_optional_from_23seq(self):
<ide> obj = self.num23seq
<ide> shape = (len(obj), len(obj[0]))
<ide> a = self.array(shape, intent.optional, obj)
<del> assert_(a.arr.shape == shape)
<del> assert_(not a.has_shared_memory())
<add> assert a.arr.shape == shape
<add> assert not a.has_shared_memory()
<ide>
<ide> a = self.array(shape, intent.optional.c, obj)
<del> assert_(a.arr.shape == shape)
<del> assert_(not a.has_shared_memory())
<add> assert a.arr.shape == shape
<add> assert not a.has_shared_memory()
<ide>
<ide> def test_inplace(self):
<ide> obj = np.array(self.num23seq, dtype=self.type.dtype)
<del> assert_(not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"])
<add> assert not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"]
<ide> shape = obj.shape
<ide> a = self.array(shape, intent.inplace, obj)
<del> assert_(obj[1][2] == a.arr[1][2], repr((obj, a.arr)))
<add> assert obj[1][2] == a.arr[1][2], repr((obj, a.arr))
<ide> a.arr[1][2] = 54
<del> assert_(
<del> obj[1][2] == a.arr[1][2] == np.array(54, dtype=self.type.dtype),
<del> repr((obj, a.arr)),
<del> )
<del> assert_(a.arr is obj)
<del> assert_(obj.flags["FORTRAN"]) # obj attributes are changed inplace!
<del> assert_(not obj.flags["CONTIGUOUS"])
<add> assert obj[1][2] == a.arr[1][2] == np.array(54, dtype=self.type.dtype)
<add> assert a.arr is obj
<add> assert obj.flags["FORTRAN"] # obj attributes are changed inplace!
<add> assert not obj.flags["CONTIGUOUS"]
<ide>
<ide> def test_inplace_from_casttype(self):
<ide> for t in self.type.cast_types():
<ide> if t is self.type:
<ide> continue
<ide> obj = np.array(self.num23seq, dtype=t.dtype)
<del> assert_(obj.dtype.type == t.type)
<del> assert_(obj.dtype.type is not self.type.type)
<del> assert_(not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"])
<add> assert obj.dtype.type == t.type
<add> assert obj.dtype.type is not self.type.type
<add> assert not obj.flags["FORTRAN"] and obj.flags["CONTIGUOUS"]
<ide> shape = obj.shape
<ide> a = self.array(shape, intent.inplace, obj)
<del> assert_(obj[1][2] == a.arr[1][2], repr((obj, a.arr)))
<add> assert obj[1][2] == a.arr[1][2], repr((obj, a.arr))
<ide> a.arr[1][2] = 54
<del> assert_(
<del> obj[1][2] == a.arr[1][2] == np.array(54,
<del> dtype=self.type.dtype),
<del> repr((obj, a.arr)),
<del> )
<del> assert_(a.arr is obj)
<del> assert_(obj.flags["FORTRAN"]) # obj attributes changed inplace!
<del> assert_(not obj.flags["CONTIGUOUS"])
<del> assert_(obj.dtype.type is self.type.type) # obj changed inplace!
<add> assert obj[1][2] == a.arr[1][2] == np.array(54,
<add> dtype=self.type.dtype)
<add> assert a.arr is obj
<add> assert obj.flags["FORTRAN"] # obj attributes changed inplace!
<add> assert not obj.flags["CONTIGUOUS"]
<add> assert obj.dtype.type is self.type.type # obj changed inplace!
<ide><path>numpy/f2py/tests/test_assumed_shape.py
<ide> import pytest
<ide> import tempfile
<ide>
<del>from numpy.testing import assert_
<ide> from . import util
<ide>
<ide>
<ide> class TestAssumedShapeSumExample(util.F2PyTest):
<ide> @pytest.mark.slow
<ide> def test_all(self):
<ide> r = self.module.fsum([1, 2])
<del> assert_(r == 3, repr(r))
<add> assert r == 3
<ide> r = self.module.sum([1, 2])
<del> assert_(r == 3, repr(r))
<add> assert r == 3
<ide> r = self.module.sum_with_use([1, 2])
<del> assert_(r == 3, repr(r))
<add> assert r == 3
<ide>
<ide> r = self.module.mod.sum([1, 2])
<del> assert_(r == 3, repr(r))
<add> assert r == 3
<ide> r = self.module.mod.fsum([1, 2])
<del> assert_(r == 3, repr(r))
<add> assert r == 3
<ide>
<ide>
<ide> class TestF2cmapOption(TestAssumedShapeSumExample):
<ide><path>numpy/f2py/tests/test_block_docstring.py
<ide> import pytest
<ide> from . import util
<ide>
<del>from numpy.testing import assert_equal, IS_PYPY
<add>from numpy.testing import IS_PYPY
<ide>
<ide>
<ide> class TestBlockDocString(util.F2PyTest):
<ide> class TestBlockDocString(util.F2PyTest):
<ide> reason="PyPy cannot modify tp_doc after PyType_Ready")
<ide> def test_block_docstring(self):
<ide> expected = "bar : 'i'-array(2,3)\n"
<del> assert_equal(self.module.block.__doc__, expected)
<add> assert self.module.block.__doc__ == expected
<ide><path>numpy/f2py/tests/test_callback.py
<ide> import time
<ide>
<ide> import numpy as np
<del>from numpy.testing import assert_, assert_equal, IS_PYPY
<add>from numpy.testing import IS_PYPY
<ide> from . import util
<ide>
<ide>
<ide> def fun(): return a
<ide> Return objects:
<ide> a : int
<ide> """)
<del> assert_equal(self.module.t.__doc__, expected)
<add> assert self.module.t.__doc__ == expected
<ide>
<ide> def check_function(self, name):
<ide> t = getattr(self.module, name)
<ide> r = t(lambda: 4)
<del> assert_(r == 4, repr(r))
<add> assert r == 4
<ide> r = t(lambda a: 5, fun_extra_args=(6, ))
<del> assert_(r == 5, repr(r))
<add> assert r == 5
<ide> r = t(lambda a: a, fun_extra_args=(6, ))
<del> assert_(r == 6, repr(r))
<add> assert r == 6
<ide> r = t(lambda a: 5 + a, fun_extra_args=(7, ))
<del> assert_(r == 12, repr(r))
<add> assert r == 12
<ide> r = t(lambda a: math.degrees(a), fun_extra_args=(math.pi, ))
<del> assert_(r == 180, repr(r))
<add> assert r == 180
<ide> r = t(math.degrees, fun_extra_args=(math.pi, ))
<del> assert_(r == 180, repr(r))
<add> assert r == 180
<ide>
<ide> r = t(self.module.func, fun_extra_args=(6, ))
<del> assert_(r == 17, repr(r))
<add> assert r == 17
<ide> r = t(self.module.func0)
<del> assert_(r == 11, repr(r))
<add> assert r == 11
<ide> r = t(self.module.func0._cpointer)
<del> assert_(r == 11, repr(r))
<add> assert r == 11
<ide>
<ide> class A:
<ide> def __call__(self):
<ide> def mth(self):
<ide>
<ide> a = A()
<ide> r = t(a)
<del> assert_(r == 7, repr(r))
<add> assert r == 7
<ide> r = t(a.mth)
<del> assert_(r == 9, repr(r))
<add> assert r == 9
<ide>
<ide> @pytest.mark.skipif(sys.platform == "win32",
<ide> reason="Fails with MinGW64 Gfortran (Issue #9673)")
<ide> def callback(code):
<ide>
<ide> f = getattr(self.module, "string_callback")
<ide> r = f(callback)
<del> assert_(r == 0, repr(r))
<add> assert r == 0
<ide>
<ide> @pytest.mark.skipif(sys.platform == "win32",
<ide> reason="Fails with MinGW64 Gfortran (Issue #9673)")
<ide> def callback(cu, lencu):
<ide>
<ide> f = getattr(self.module, "string_callback_array")
<ide> res = f(callback, cu, len(cu))
<del> assert_(res == 0, repr(res))
<add> assert res == 0
<ide>
<ide> def test_threadsafety(self):
<ide> # Segfaults if the callback handling is not threadsafe
<ide> def cb():
<ide>
<ide> # Check reentrancy
<ide> r = self.module.t(lambda: 123)
<del> assert_(r == 123)
<add> assert r == 123
<ide>
<ide> return 42
<ide>
<ide> def runner(name):
<ide> try:
<ide> for j in range(50):
<ide> r = self.module.t(cb)
<del> assert_(r == 42)
<add> assert r == 42
<ide> self.check_function(name)
<ide> except Exception:
<ide> errors.append(traceback.format_exc())
<ide> def test_hidden_callback(self):
<ide> try:
<ide> self.module.hidden_callback(2)
<ide> except Exception as msg:
<del> assert_(str(msg).startswith("Callback global_f not defined"))
<add> assert str(msg).startswith("Callback global_f not defined")
<ide>
<ide> try:
<ide> self.module.hidden_callback2(2)
<ide> except Exception as msg:
<del> assert_(str(msg).startswith("cb: Callback global_f not defined"))
<add> assert str(msg).startswith("cb: Callback global_f not defined")
<ide>
<ide> self.module.global_f = lambda x: x + 1
<ide> r = self.module.hidden_callback(2)
<del> assert_(r == 3)
<add> assert r == 3
<ide>
<ide> self.module.global_f = lambda x: x + 2
<ide> r = self.module.hidden_callback(2)
<del> assert_(r == 4)
<add> assert r == 4
<ide>
<ide> del self.module.global_f
<ide> try:
<ide> self.module.hidden_callback(2)
<ide> except Exception as msg:
<del> assert_(str(msg).startswith("Callback global_f not defined"))
<add> assert str(msg).startswith("Callback global_f not defined")
<ide>
<ide> self.module.global_f = lambda x=0: x + 3
<ide> r = self.module.hidden_callback(2)
<del> assert_(r == 5)
<add> assert r == 5
<ide>
<ide> # reproducer of gh18341
<ide> r = self.module.hidden_callback2(2)
<del> assert_(r == 3)
<add> assert r == 3
<ide>
<ide>
<ide> class TestF77CallbackPythonTLS(TestF77Callback):
<ide><path>numpy/f2py/tests/test_common.py
<ide> import numpy as np
<ide> from . import util
<ide>
<del>from numpy.testing import assert_array_equal
<del>
<ide>
<ide> class TestCommonBlock(util.F2PyTest):
<ide> sources = [util.getpath("tests", "src", "common", "block.f")]
<ide> class TestCommonBlock(util.F2PyTest):
<ide> reason="Fails with MinGW64 Gfortran (Issue #9673)")
<ide> def test_common_block(self):
<ide> self.module.initcb()
<del> assert_array_equal(self.module.block.long_bn,
<del> np.array(1.0, dtype=np.float64))
<del> assert_array_equal(self.module.block.string_bn,
<del> np.array("2", dtype="|S1"))
<del> assert_array_equal(self.module.block.ok, np.array(3, dtype=np.int32))
<add> assert self.module.block.long_bn == np.array(1.0, dtype=np.float64)
<add> assert self.module.block.string_bn == np.array("2", dtype="|S1")
<add> assert self.module.block.ok == np.array(3, dtype=np.int32)
<ide><path>numpy/f2py/tests/test_compile_function.py
<ide>
<ide> import numpy.f2py
<ide>
<del>from numpy.testing import assert_equal
<ide> from . import util
<ide>
<ide>
<ide> def test_f2py_init_compile(extra_args):
<ide> source_fn=source_fn)
<ide>
<ide> # check for compile success return value
<del> assert_equal(ret_val, 0)
<add> assert ret_val == 0
<ide>
<ide> # we are not currently able to import the Python-Fortran
<ide> # interface module on Windows / Appveyor, even though we do get
<ide> def test_f2py_init_compile(extra_args):
<ide> # result of the sum operation
<ide> return_check = import_module(modname)
<ide> calc_result = return_check.foo()
<del> assert_equal(calc_result, 15)
<add> assert calc_result == 15
<ide> # Removal from sys.modules, is not as such necessary. Even with
<ide> # removal, the module (dict) stays alive.
<ide> del sys.modules[modname]
<ide> def test_f2py_init_compile_failure():
<ide> # verify an appropriate integer status value returned by
<ide> # f2py.compile() when invalid Fortran is provided
<ide> ret_val = numpy.f2py.compile(b"invalid")
<del> assert_equal(ret_val, 1)
<add> assert ret_val == 1
<ide>
<ide>
<ide> def test_f2py_init_compile_bad_cmd():
<ide> def test_f2py_init_compile_bad_cmd():
<ide>
<ide> # the OSError should take precedence over invalid Fortran
<ide> ret_val = numpy.f2py.compile(b"invalid")
<del> assert_equal(ret_val, 127)
<add> assert ret_val == 127
<ide> finally:
<ide> sys.executable = temp
<ide>
<ide> def test_compile_from_strings(tmpdir, fsource):
<ide> ret_val = numpy.f2py.compile(fsource,
<ide> modulename="test_compile_from_strings",
<ide> extension=".f90")
<del> assert_equal(ret_val, 0)
<add> assert ret_val == 0
<ide><path>numpy/f2py/tests/test_crackfortran.py
<ide> import pytest
<ide> import numpy as np
<del>from numpy.testing import assert_array_equal, assert_equal
<ide> from numpy.f2py.crackfortran import markinnerspaces
<ide> from . import util
<ide> from numpy.f2py import crackfortran
<ide> def test_module(self):
<ide> k = np.array([1, 2, 3], dtype=np.float64)
<ide> w = np.array([1, 2, 3], dtype=np.float64)
<ide> self.module.subb(k)
<del> assert_array_equal(k, w + 1)
<add> assert np.allclose(k, w + 1)
<ide> self.module.subc([w, k])
<del> assert_array_equal(k, w + 1)
<add> assert np.allclose(k, w + 1)
<ide> assert self.module.t0(23) == b"2"
<ide>
<ide>
<ide> class TestMarkinnerspaces:
<ide> def test_do_not_touch_normal_spaces(self):
<ide> test_list = ["a ", " a", "a b c", "'abcdefghij'"]
<ide> for i in test_list:
<del> assert_equal(markinnerspaces(i), i)
<add> assert markinnerspaces(i) == i
<ide>
<ide> def test_one_relevant_space(self):
<del> assert_equal(markinnerspaces("a 'b c' \\' \\'"), "a 'b@_@c' \\' \\'")
<del> assert_equal(markinnerspaces(r'a "b c" \" \"'), r'a "b@_@c" \" \"')
<add> assert markinnerspaces("a 'b c' \\' \\'") == "a 'b@_@c' \\' \\'"
<add> assert markinnerspaces(r'a "b c" \" \"') == r'a "b@_@c" \" \"'
<ide>
<ide> def test_ignore_inner_quotes(self):
<del> assert_equal(markinnerspaces("a 'b c\" \" d' e"),
<del> "a 'b@_@c\"@_@\"@_@d' e")
<del> assert_equal(markinnerspaces("a \"b c' ' d\" e"),
<del> "a \"b@_@c'@_@'@_@d\" e")
<add> assert markinnerspaces("a 'b c\" \" d' e") == "a 'b@_@c\"@_@\"@_@d' e"
<add> assert markinnerspaces("a \"b c' ' d\" e") == "a \"b@_@c'@_@'@_@d\" e"
<ide>
<ide> def test_multiple_relevant_spaces(self):
<del> assert_equal(markinnerspaces("a 'b c' 'd e'"), "a 'b@_@c' 'd@_@e'")
<del> assert_equal(markinnerspaces(r'a "b c" "d e"'), r'a "b@_@c" "d@_@e"')
<add> assert markinnerspaces("a 'b c' 'd e'") == "a 'b@_@c' 'd@_@e'"
<add> assert markinnerspaces(r'a "b c" "d e"') == r'a "b@_@c" "d@_@e"'
<ide>
<ide>
<ide> class TestDimSpec(util.F2PyTest):
<ide><path>numpy/f2py/tests/test_kind.py
<ide> import os
<ide> import pytest
<ide>
<del>from numpy.testing import assert_
<ide> from numpy.f2py.crackfortran import (
<ide> _selected_int_kind_func as selected_int_kind,
<ide> _selected_real_kind_func as selected_real_kind,
<ide> class TestKind(util.F2PyTest):
<ide> sources = [util.getpath("tests", "src", "kind", "foo.f90")]
<ide>
<del> @pytest.mark.slow
<ide> def test_all(self):
<ide> selectedrealkind = self.module.selectedrealkind
<ide> selectedintkind = self.module.selectedintkind
<ide>
<ide> for i in range(40):
<del> assert_(
<del> selectedintkind(i) in [selected_int_kind(i), -1],
<del> "selectedintkind(%s): expected %r but got %r" %
<del> (i, selected_int_kind(i), selectedintkind(i)),
<del> )
<add> assert selectedintkind(i) == selected_int_kind(
<add> i
<add> ), f"selectedintkind({i}): expected {selected_int_kind(i)!r} but got {selectedintkind(i)!r}"
<ide>
<ide> for i in range(20):
<del> assert_(
<del> selectedrealkind(i) in [selected_real_kind(i), -1],
<del> "selectedrealkind(%s): expected %r but got %r" %
<del> (i, selected_real_kind(i), selectedrealkind(i)),
<del> )
<add> assert selectedrealkind(i) == selected_real_kind(
<add> i
<add> ), f"selectedrealkind({i}): expected {selected_real_kind(i)!r} but got {selectedrealkind(i)!r}"
<ide><path>numpy/f2py/tests/test_mixed.py
<ide> import textwrap
<ide> import pytest
<ide>
<del>from numpy.testing import assert_, assert_equal, IS_PYPY
<add>from numpy.testing import IS_PYPY
<ide> from . import util
<ide>
<ide>
<ide> class TestMixed(util.F2PyTest):
<ide> ]
<ide>
<ide> def test_all(self):
<del> assert_(self.module.bar11() == 11)
<del> assert_(self.module.foo_fixed.bar12() == 12)
<del> assert_(self.module.foo_free.bar13() == 13)
<add> assert self.module.bar11() == 11
<add> assert self.module.foo_fixed.bar12() == 12
<add> assert self.module.foo_free.bar13() == 13
<ide>
<ide> @pytest.mark.xfail(IS_PYPY,
<ide> reason="PyPy cannot modify tp_doc after PyType_Ready")
<ide> def test_docstring(self):
<ide> -------
<ide> a : int
<ide> """)
<del> assert_equal(self.module.bar11.__doc__, expected)
<add> assert self.module.bar11.__doc__ == expected
<ide><path>numpy/f2py/tests/test_module_doc.py
<ide> import textwrap
<ide>
<ide> from . import util
<del>from numpy.testing import assert_equal, IS_PYPY
<add>from numpy.testing import IS_PYPY
<ide>
<ide>
<ide> class TestModuleDocString(util.F2PyTest):
<ide> class TestModuleDocString(util.F2PyTest):
<ide> @pytest.mark.xfail(IS_PYPY,
<ide> reason="PyPy cannot modify tp_doc after PyType_Ready")
<ide> def test_module_docstring(self):
<del> assert_equal(
<del> self.module.mod.__doc__,
<del> textwrap.dedent("""\
<add> assert self.module.mod.__doc__ == textwrap.dedent("""\
<ide> i : 'i'-scalar
<ide> x : 'i'-array(4)
<ide> a : 'f'-array(2,3)
<ide> b : 'f'-array(-1,-1), not allocated\x00
<ide> foo()\n
<del> Wrapper for ``foo``.\n\n"""),
<del> )
<add> Wrapper for ``foo``.\n\n""")
<ide><path>numpy/f2py/tests/test_parameter.py
<ide> import pytest
<ide>
<ide> import numpy as np
<del>from numpy.testing import assert_raises, assert_equal
<ide>
<ide> from . import util
<ide>
<ide> class TestParameters(util.F2PyTest):
<ide> def test_constant_real_single(self):
<ide> # non-contiguous should raise error
<ide> x = np.arange(6, dtype=np.float32)[::2]
<del> assert_raises(ValueError, self.module.foo_single, x)
<add> pytest.raises(ValueError, self.module.foo_single, x)
<ide>
<ide> # check values with contiguous array
<ide> x = np.arange(3, dtype=np.float32)
<ide> self.module.foo_single(x)
<del> assert_equal(x, [0 + 1 + 2 * 3, 1, 2])
<add> assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])
<ide>
<ide> @pytest.mark.slow
<ide> def test_constant_real_double(self):
<ide> # non-contiguous should raise error
<ide> x = np.arange(6, dtype=np.float64)[::2]
<del> assert_raises(ValueError, self.module.foo_double, x)
<add> pytest.raises(ValueError, self.module.foo_double, x)
<ide>
<ide> # check values with contiguous array
<ide> x = np.arange(3, dtype=np.float64)
<ide> self.module.foo_double(x)
<del> assert_equal(x, [0 + 1 + 2 * 3, 1, 2])
<add> assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])
<ide>
<ide> @pytest.mark.slow
<ide> def test_constant_compound_int(self):
<ide> # non-contiguous should raise error
<ide> x = np.arange(6, dtype=np.int32)[::2]
<del> assert_raises(ValueError, self.module.foo_compound_int, x)
<add> pytest.raises(ValueError, self.module.foo_compound_int, x)
<ide>
<ide> # check values with contiguous array
<ide> x = np.arange(3, dtype=np.int32)
<ide> self.module.foo_compound_int(x)
<del> assert_equal(x, [0 + 1 + 2 * 6, 1, 2])
<add> assert np.allclose(x, [0 + 1 + 2 * 6, 1, 2])
<ide>
<ide> @pytest.mark.slow
<ide> def test_constant_non_compound_int(self):
<ide> # check values
<ide> x = np.arange(4, dtype=np.int32)
<ide> self.module.foo_non_compound_int(x)
<del> assert_equal(x, [0 + 1 + 2 + 3 * 4, 1, 2, 3])
<add> assert np.allclose(x, [0 + 1 + 2 + 3 * 4, 1, 2, 3])
<ide>
<ide> @pytest.mark.slow
<ide> def test_constant_integer_int(self):
<ide> # non-contiguous should raise error
<ide> x = np.arange(6, dtype=np.int32)[::2]
<del> assert_raises(ValueError, self.module.foo_int, x)
<add> pytest.raises(ValueError, self.module.foo_int, x)
<ide>
<ide> # check values with contiguous array
<ide> x = np.arange(3, dtype=np.int32)
<ide> self.module.foo_int(x)
<del> assert_equal(x, [0 + 1 + 2 * 3, 1, 2])
<add> assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])
<ide>
<ide> @pytest.mark.slow
<ide> def test_constant_integer_long(self):
<ide> # non-contiguous should raise error
<ide> x = np.arange(6, dtype=np.int64)[::2]
<del> assert_raises(ValueError, self.module.foo_long, x)
<add> pytest.raises(ValueError, self.module.foo_long, x)
<ide>
<ide> # check values with contiguous array
<ide> x = np.arange(3, dtype=np.int64)
<ide> self.module.foo_long(x)
<del> assert_equal(x, [0 + 1 + 2 * 3, 1, 2])
<add> assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])
<ide>
<ide> @pytest.mark.slow
<ide> def test_constant_both(self):
<ide> # non-contiguous should raise error
<ide> x = np.arange(6, dtype=np.float64)[::2]
<del> assert_raises(ValueError, self.module.foo, x)
<add> pytest.raises(ValueError, self.module.foo, x)
<ide>
<ide> # check values with contiguous array
<ide> x = np.arange(3, dtype=np.float64)
<ide> self.module.foo(x)
<del> assert_equal(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
<add> assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
<ide>
<ide> @pytest.mark.slow
<ide> def test_constant_no(self):
<ide> # non-contiguous should raise error
<ide> x = np.arange(6, dtype=np.float64)[::2]
<del> assert_raises(ValueError, self.module.foo_no, x)
<add> pytest.raises(ValueError, self.module.foo_no, x)
<ide>
<ide> # check values with contiguous array
<ide> x = np.arange(3, dtype=np.float64)
<ide> self.module.foo_no(x)
<del> assert_equal(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
<add> assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
<ide>
<ide> @pytest.mark.slow
<ide> def test_constant_sum(self):
<ide> # non-contiguous should raise error
<ide> x = np.arange(6, dtype=np.float64)[::2]
<del> assert_raises(ValueError, self.module.foo_sum, x)
<add> pytest.raises(ValueError, self.module.foo_sum, x)
<ide>
<ide> # check values with contiguous array
<ide> x = np.arange(3, dtype=np.float64)
<ide> self.module.foo_sum(x)
<del> assert_equal(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
<add> assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
<ide><path>numpy/f2py/tests/test_quoted_character.py
<ide> import sys
<ide> import pytest
<ide>
<del>from numpy.testing import assert_equal
<ide> from . import util
<ide>
<ide>
<ide> class TestQuotedCharacter(util.F2PyTest):
<ide> @pytest.mark.skipif(sys.platform == "win32",
<ide> reason="Fails with MinGW64 Gfortran (Issue #9673)")
<ide> def test_quoted_character(self):
<del> assert_equal(self.module.foo(), (b"'", b'"', b";", b"!", b"(", b")"))
<add> assert self.module.foo() == (b"'", b'"', b";", b"!", b"(", b")")
<ide><path>numpy/f2py/tests/test_regression.py
<ide> import pytest
<ide>
<ide> import numpy as np
<del>from numpy.testing import assert_, assert_raises, assert_equal, assert_string_equal
<ide>
<ide> from . import util
<ide>
<ide> class TestIntentInOut(util.F2PyTest):
<ide> def test_inout(self):
<ide> # non-contiguous should raise error
<ide> x = np.arange(6, dtype=np.float32)[::2]
<del> assert_raises(ValueError, self.module.foo, x)
<add> pytest.raises(ValueError, self.module.foo, x)
<ide>
<ide> # check values with contiguous array
<ide> x = np.arange(3, dtype=np.float32)
<ide> self.module.foo(x)
<del> assert_equal(x, [3, 1, 2])
<add> assert np.allclose(x, [3, 1, 2])
<ide>
<ide>
<ide> class TestNumpyVersionAttribute(util.F2PyTest):
<ide> class TestNumpyVersionAttribute(util.F2PyTest):
<ide> def test_numpy_version_attribute(self):
<ide>
<ide> # Check that self.module has an attribute named "__f2py_numpy_version__"
<del> assert_(
<del> hasattr(self.module, "__f2py_numpy_version__"),
<del> msg="Fortran module does not have __f2py_numpy_version__",
<del> )
<add> assert hasattr(self.module, "__f2py_numpy_version__")
<ide>
<ide> # Check that the attribute __f2py_numpy_version__ is a string
<del> assert_(
<del> isinstance(self.module.__f2py_numpy_version__, str),
<del> msg="__f2py_numpy_version__ is not a string",
<del> )
<add> assert isinstance(self.module.__f2py_numpy_version__, str)
<ide>
<ide> # Check that __f2py_numpy_version__ has the value numpy.__version__
<del> assert_string_equal(np.__version__, self.module.__f2py_numpy_version__)
<add> assert np.__version__ == self.module.__f2py_numpy_version__
<ide>
<ide>
<ide> def test_include_path():
<ide><path>numpy/f2py/tests/test_return_character.py
<ide> import pytest
<ide>
<ide> from numpy import array
<del>from numpy.testing import assert_
<ide> from . import util
<ide> import platform
<ide>
<ide> class TestReturnCharacter(util.F2PyTest):
<ide> def check_function(self, t, tname):
<ide> if tname in ["t0", "t1", "s0", "s1"]:
<del> assert_(t(23) == b"2")
<add> assert t(23) == b"2"
<ide> r = t("ab")
<del> assert_(r == b"a", repr(r))
<add> assert r == b"a"
<ide> r = t(array("ab"))
<del> assert_(r == b"a", repr(r))
<add> assert r == b"a"
<ide> r = t(array(77, "u1"))
<del> assert_(r == b"M", repr(r))
<del> # assert_(_raises(ValueError, t, array([77,87])))
<del> # assert_(_raises(ValueError, t, array(77)))
<add> assert r == b"M"
<ide> elif tname in ["ts", "ss"]:
<del> assert_(t(23) == b"23", repr(t(23)))
<del> assert_(t("123456789abcdef") == b"123456789a")
<add> assert t(23) == b"23"
<add> assert t("123456789abcdef") == b"123456789a"
<ide> elif tname in ["t5", "s5"]:
<del> assert_(t(23) == b"23", repr(t(23)))
<del> assert_(t("ab") == b"ab", repr(t("ab")))
<del> assert_(t("123456789abcdef") == b"12345")
<add> assert t(23) == b"23"
<add> assert t("ab") == b"ab"
<add> assert t("123456789abcdef") == b"12345"
<ide> else:
<ide> raise NotImplementedError
<ide>
<ide><path>numpy/f2py/tests/test_return_complex.py
<ide> import pytest
<ide>
<ide> from numpy import array
<del>from numpy.testing import assert_, assert_raises
<ide> from . import util
<ide>
<ide>
<ide> def check_function(self, t, tname):
<ide> err = 1e-5
<ide> else:
<ide> err = 0.0
<del> assert_(abs(t(234j) - 234.0j) <= err)
<del> assert_(abs(t(234.6) - 234.6) <= err)
<del> assert_(abs(t(234) - 234.0) <= err)
<del> assert_(abs(t(234.6 + 3j) - (234.6 + 3j)) <= err)
<del> # assert_( abs(t('234')-234.)<=err)
<del> # assert_( abs(t('234.6')-234.6)<=err)
<del> assert_(abs(t(-234) + 234.0) <= err)
<del> assert_(abs(t([234]) - 234.0) <= err)
<del> assert_(abs(t((234, )) - 234.0) <= err)
<del> assert_(abs(t(array(234)) - 234.0) <= err)
<del> assert_(abs(t(array(23 + 4j, "F")) - (23 + 4j)) <= err)
<del> assert_(abs(t(array([234])) - 234.0) <= err)
<del> assert_(abs(t(array([[234]])) - 234.0) <= err)
<del> assert_(abs(t(array([234], "b")) + 22.0) <= err)
<del> assert_(abs(t(array([234], "h")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "i")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "l")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "q")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "f")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "d")) - 234.0) <= err)
<del> assert_(abs(t(array([234 + 3j], "F")) - (234 + 3j)) <= err)
<del> assert_(abs(t(array([234], "D")) - 234.0) <= err)
<add> assert abs(t(234j) - 234.0j) <= err
<add> assert abs(t(234.6) - 234.6) <= err
<add> assert abs(t(234) - 234.0) <= err
<add> assert abs(t(234.6 + 3j) - (234.6 + 3j)) <= err
<add> # assert abs(t('234')-234.)<=err
<add> # assert abs(t('234.6')-234.6)<=err
<add> assert abs(t(-234) + 234.0) <= err
<add> assert abs(t([234]) - 234.0) <= err
<add> assert abs(t((234, )) - 234.0) <= err
<add> assert abs(t(array(234)) - 234.0) <= err
<add> assert abs(t(array(23 + 4j, "F")) - (23 + 4j)) <= err
<add> assert abs(t(array([234])) - 234.0) <= err
<add> assert abs(t(array([[234]])) - 234.0) <= err
<add> assert abs(t(array([234], "b")) + 22.0) <= err
<add> assert abs(t(array([234], "h")) - 234.0) <= err
<add> assert abs(t(array([234], "i")) - 234.0) <= err
<add> assert abs(t(array([234], "l")) - 234.0) <= err
<add> assert abs(t(array([234], "q")) - 234.0) <= err
<add> assert abs(t(array([234], "f")) - 234.0) <= err
<add> assert abs(t(array([234], "d")) - 234.0) <= err
<add> assert abs(t(array([234 + 3j], "F")) - (234 + 3j)) <= err
<add> assert abs(t(array([234], "D")) - 234.0) <= err
<ide>
<del> # assert_raises(TypeError, t, array([234], 'a1'))
<del> assert_raises(TypeError, t, "abc")
<add> # pytest.raises(TypeError, t, array([234], 'a1'))
<add> pytest.raises(TypeError, t, "abc")
<ide>
<del> assert_raises(IndexError, t, [])
<del> assert_raises(IndexError, t, ())
<add> pytest.raises(IndexError, t, [])
<add> pytest.raises(IndexError, t, ())
<ide>
<del> assert_raises(TypeError, t, t)
<del> assert_raises(TypeError, t, {})
<add> pytest.raises(TypeError, t, t)
<add> pytest.raises(TypeError, t, {})
<ide>
<ide> try:
<ide> r = t(10**400)
<del> assert_(repr(r) in ["(inf+0j)", "(Infinity+0j)"], repr(r))
<add> assert repr(r) in ["(inf+0j)", "(Infinity+0j)"]
<ide> except OverflowError:
<ide> pass
<ide>
<ide><path>numpy/f2py/tests/test_return_integer.py
<ide> import pytest
<ide>
<ide> from numpy import array
<del>from numpy.testing import assert_, assert_raises
<ide> from . import util
<ide>
<ide>
<ide> class TestReturnInteger(util.F2PyTest):
<ide> def check_function(self, t, tname):
<del> assert_(t(123) == 123, repr(t(123)))
<del> assert_(t(123.6) == 123)
<del> assert_(t("123") == 123)
<del> assert_(t(-123) == -123)
<del> assert_(t([123]) == 123)
<del> assert_(t((123, )) == 123)
<del> assert_(t(array(123)) == 123)
<del> assert_(t(array([123])) == 123)
<del> assert_(t(array([[123]])) == 123)
<del> assert_(t(array([123], "b")) == 123)
<del> assert_(t(array([123], "h")) == 123)
<del> assert_(t(array([123], "i")) == 123)
<del> assert_(t(array([123], "l")) == 123)
<del> assert_(t(array([123], "B")) == 123)
<del> assert_(t(array([123], "f")) == 123)
<del> assert_(t(array([123], "d")) == 123)
<del>
<del> # assert_raises(ValueError, t, array([123],'S3'))
<del> assert_raises(ValueError, t, "abc")
<del>
<del> assert_raises(IndexError, t, [])
<del> assert_raises(IndexError, t, ())
<del>
<del> assert_raises(Exception, t, t)
<del> assert_raises(Exception, t, {})
<add> assert t(123) == 123
<add> assert t(123.6) == 123
<add> assert t("123") == 123
<add> assert t(-123) == -123
<add> assert t([123]) == 123
<add> assert t((123, )) == 123
<add> assert t(array(123)) == 123
<add> assert t(array([123])) == 123
<add> assert t(array([[123]])) == 123
<add> assert t(array([123], "b")) == 123
<add> assert t(array([123], "h")) == 123
<add> assert t(array([123], "i")) == 123
<add> assert t(array([123], "l")) == 123
<add> assert t(array([123], "B")) == 123
<add> assert t(array([123], "f")) == 123
<add> assert t(array([123], "d")) == 123
<add>
<add> # pytest.raises(ValueError, t, array([123],'S3'))
<add> pytest.raises(ValueError, t, "abc")
<add>
<add> pytest.raises(IndexError, t, [])
<add> pytest.raises(IndexError, t, ())
<add>
<add> pytest.raises(Exception, t, t)
<add> pytest.raises(Exception, t, {})
<ide>
<ide> if tname in ["t8", "s8"]:
<del> assert_raises(OverflowError, t, 100000000000000000000000)
<del> assert_raises(OverflowError, t, 10000000011111111111111.23)
<add> pytest.raises(OverflowError, t, 100000000000000000000000)
<add> pytest.raises(OverflowError, t, 10000000011111111111111.23)
<ide>
<ide>
<ide> class TestFReturnInteger(TestReturnInteger):
<ide><path>numpy/f2py/tests/test_return_logical.py
<ide> import pytest
<ide>
<ide> from numpy import array
<del>from numpy.testing import assert_, assert_raises
<ide> from . import util
<ide>
<ide>
<ide> class TestReturnLogical(util.F2PyTest):
<ide> def check_function(self, t):
<del> assert_(t(True) == 1, repr(t(True)))
<del> assert_(t(False) == 0, repr(t(False)))
<del> assert_(t(0) == 0)
<del> assert_(t(None) == 0)
<del> assert_(t(0.0) == 0)
<del> assert_(t(0j) == 0)
<del> assert_(t(1j) == 1)
<del> assert_(t(234) == 1)
<del> assert_(t(234.6) == 1)
<del> assert_(t(234.6 + 3j) == 1)
<del> assert_(t("234") == 1)
<del> assert_(t("aaa") == 1)
<del> assert_(t("") == 0)
<del> assert_(t([]) == 0)
<del> assert_(t(()) == 0)
<del> assert_(t({}) == 0)
<del> assert_(t(t) == 1)
<del> assert_(t(-234) == 1)
<del> assert_(t(10**100) == 1)
<del> assert_(t([234]) == 1)
<del> assert_(t((234, )) == 1)
<del> assert_(t(array(234)) == 1)
<del> assert_(t(array([234])) == 1)
<del> assert_(t(array([[234]])) == 1)
<del> assert_(t(array([234], "b")) == 1)
<del> assert_(t(array([234], "h")) == 1)
<del> assert_(t(array([234], "i")) == 1)
<del> assert_(t(array([234], "l")) == 1)
<del> assert_(t(array([234], "f")) == 1)
<del> assert_(t(array([234], "d")) == 1)
<del> assert_(t(array([234 + 3j], "F")) == 1)
<del> assert_(t(array([234], "D")) == 1)
<del> assert_(t(array(0)) == 0)
<del> assert_(t(array([0])) == 0)
<del> assert_(t(array([[0]])) == 0)
<del> assert_(t(array([0j])) == 0)
<del> assert_(t(array([1])) == 1)
<del> assert_raises(ValueError, t, array([0, 0]))
<add> assert t(True) == 1
<add> assert t(False) == 0
<add> assert t(0) == 0
<add> assert t(None) == 0
<add> assert t(0.0) == 0
<add> assert t(0j) == 0
<add> assert t(1j) == 1
<add> assert t(234) == 1
<add> assert t(234.6) == 1
<add> assert t(234.6 + 3j) == 1
<add> assert t("234") == 1
<add> assert t("aaa") == 1
<add> assert t("") == 0
<add> assert t([]) == 0
<add> assert t(()) == 0
<add> assert t({}) == 0
<add> assert t(t) == 1
<add> assert t(-234) == 1
<add> assert t(10**100) == 1
<add> assert t([234]) == 1
<add> assert t((234, )) == 1
<add> assert t(array(234)) == 1
<add> assert t(array([234])) == 1
<add> assert t(array([[234]])) == 1
<add> assert t(array([234], "b")) == 1
<add> assert t(array([234], "h")) == 1
<add> assert t(array([234], "i")) == 1
<add> assert t(array([234], "l")) == 1
<add> assert t(array([234], "f")) == 1
<add> assert t(array([234], "d")) == 1
<add> assert t(array([234 + 3j], "F")) == 1
<add> assert t(array([234], "D")) == 1
<add> assert t(array(0)) == 0
<add> assert t(array([0])) == 0
<add> assert t(array([[0]])) == 0
<add> assert t(array([0j])) == 0
<add> assert t(array([1])) == 1
<add> pytest.raises(ValueError, t, array([0, 0]))
<ide>
<ide>
<ide> class TestFReturnLogical(TestReturnLogical):
<ide><path>numpy/f2py/tests/test_return_real.py
<ide> import pytest
<ide>
<ide> from numpy import array
<del>from numpy.testing import assert_, assert_raises
<ide> from . import util
<ide>
<ide>
<ide> def check_function(self, t, tname):
<ide> err = 1e-5
<ide> else:
<ide> err = 0.0
<del> assert_(abs(t(234) - 234.0) <= err)
<del> assert_(abs(t(234.6) - 234.6) <= err)
<del> assert_(abs(t("234") - 234) <= err)
<del> assert_(abs(t("234.6") - 234.6) <= err)
<del> assert_(abs(t(-234) + 234) <= err)
<del> assert_(abs(t([234]) - 234) <= err)
<del> assert_(abs(t((234, )) - 234.0) <= err)
<del> assert_(abs(t(array(234)) - 234.0) <= err)
<del> assert_(abs(t(array([234])) - 234.0) <= err)
<del> assert_(abs(t(array([[234]])) - 234.0) <= err)
<del> assert_(abs(t(array([234], "b")) + 22) <= err)
<del> assert_(abs(t(array([234], "h")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "i")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "l")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "B")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "f")) - 234.0) <= err)
<del> assert_(abs(t(array([234], "d")) - 234.0) <= err)
<add> assert abs(t(234) - 234.0) <= err
<add> assert abs(t(234.6) - 234.6) <= err
<add> assert abs(t("234") - 234) <= err
<add> assert abs(t("234.6") - 234.6) <= err
<add> assert abs(t(-234) + 234) <= err
<add> assert abs(t([234]) - 234) <= err
<add> assert abs(t((234, )) - 234.0) <= err
<add> assert abs(t(array(234)) - 234.0) <= err
<add> assert abs(t(array([234])) - 234.0) <= err
<add> assert abs(t(array([[234]])) - 234.0) <= err
<add> assert abs(t(array([234], "b")) + 22) <= err
<add> assert abs(t(array([234], "h")) - 234.0) <= err
<add> assert abs(t(array([234], "i")) - 234.0) <= err
<add> assert abs(t(array([234], "l")) - 234.0) <= err
<add> assert abs(t(array([234], "B")) - 234.0) <= err
<add> assert abs(t(array([234], "f")) - 234.0) <= err
<add> assert abs(t(array([234], "d")) - 234.0) <= err
<ide> if tname in ["t0", "t4", "s0", "s4"]:
<del> assert_(t(1e200) == t(1e300)) # inf
<add> assert t(1e200) == t(1e300) # inf
<ide>
<del> # assert_raises(ValueError, t, array([234], 'S1'))
<del> assert_raises(ValueError, t, "abc")
<add> # pytest.raises(ValueError, t, array([234], 'S1'))
<add> pytest.raises(ValueError, t, "abc")
<ide>
<del> assert_raises(IndexError, t, [])
<del> assert_raises(IndexError, t, ())
<add> pytest.raises(IndexError, t, [])
<add> pytest.raises(IndexError, t, ())
<ide>
<del> assert_raises(Exception, t, t)
<del> assert_raises(Exception, t, {})
<add> pytest.raises(Exception, t, t)
<add> pytest.raises(Exception, t, {})
<ide>
<ide> try:
<ide> r = t(10**400)
<del> assert_(repr(r) in ["inf", "Infinity"], repr(r))
<add> assert repr(r) in ["inf", "Infinity"]
<ide> except OverflowError:
<ide> pass
<ide>
<ide><path>numpy/f2py/tests/test_semicolon_split.py
<ide> import pytest
<ide>
<ide> from . import util
<del>from numpy.testing import assert_equal
<ide>
<ide>
<ide> @pytest.mark.skipif(
<ide> class TestMultiline(util.F2PyTest):
<ide> """
<ide>
<ide> def test_multiline(self):
<del> assert_equal(self.module.foo(), 42)
<add> assert self.module.foo() == 42
<ide>
<ide>
<ide> @pytest.mark.skipif(
<ide> class TestCallstatement(util.F2PyTest):
<ide> """
<ide>
<ide> def test_callstatement(self):
<del> assert_equal(self.module.foo(), 42)
<add> assert self.module.foo() == 42
<ide><path>numpy/f2py/tests/test_size.py
<ide> import os
<ide> import pytest
<add>import numpy as np
<ide>
<del>from numpy.testing import assert_equal
<ide> from . import util
<ide>
<ide>
<ide> class TestSizeSumExample(util.F2PyTest):
<ide> @pytest.mark.slow
<ide> def test_all(self):
<ide> r = self.module.foo([[]])
<del> assert_equal(r, [0], repr(r))
<add> assert r == [0]
<ide>
<ide> r = self.module.foo([[1, 2]])
<del> assert_equal(r, [3], repr(r))
<add> assert r == [3]
<ide>
<ide> r = self.module.foo([[1, 2], [3, 4]])
<del> assert_equal(r, [3, 7], repr(r))
<add> assert np.allclose(r, [3, 7])
<ide>
<ide> r = self.module.foo([[1, 2], [3, 4], [5, 6]])
<del> assert_equal(r, [3, 7, 11], repr(r))
<add> assert np.allclose(r, [3, 7, 11])
<ide>
<ide> @pytest.mark.slow
<ide> def test_transpose(self):
<ide> r = self.module.trans([[]])
<del> assert_equal(r.T, [[]], repr(r))
<add> assert np.allclose(r.T, np.array([[]]))
<ide>
<ide> r = self.module.trans([[1, 2]])
<del> assert_equal(r, [[1], [2]], repr(r))
<add> assert np.allclose(r, [[1.], [2.]])
<ide>
<ide> r = self.module.trans([[1, 2, 3], [4, 5, 6]])
<del> assert_equal(r, [[1, 4], [2, 5], [3, 6]], repr(r))
<add> assert np.allclose(r, [[1, 4], [2, 5], [3, 6]])
<ide>
<ide> @pytest.mark.slow
<ide> def test_flatten(self):
<ide> r = self.module.flatten([[]])
<del> assert_equal(r, [], repr(r))
<add> assert np.allclose(r, [])
<ide>
<ide> r = self.module.flatten([[1, 2]])
<del> assert_equal(r, [1, 2], repr(r))
<add> assert np.allclose(r, [1, 2])
<ide>
<ide> r = self.module.flatten([[1, 2, 3], [4, 5, 6]])
<del> assert_equal(r, [1, 2, 3, 4, 5, 6], repr(r))
<add> assert np.allclose(r, [1, 2, 3, 4, 5, 6])
<ide><path>numpy/f2py/tests/test_string.py
<ide> import os
<ide> import pytest
<ide> import textwrap
<del>from numpy.testing import assert_array_equal
<ide> import numpy as np
<ide> from . import util
<ide>
<ide> def test_char(self):
<ide> strings = np.array(["ab", "cd", "ef"], dtype="c").T
<ide> inp, out = self.module.char_test.change_strings(
<ide> strings, strings.shape[1])
<del> assert_array_equal(inp, strings)
<add> assert inp == pytest.approx(strings)
<ide> expected = strings.copy()
<ide> expected[1, :] = "AAA"
<del> assert_array_equal(out, expected)
<add> assert out == pytest.approx(expected)
<ide>
<ide>
<ide> class TestDocStringArguments(util.F2PyTest):
<ide><path>numpy/f2py/tests/test_symbolic.py
<del>from numpy.testing import assert_raises
<add>import pytest
<add>
<ide> from numpy.f2py.symbolic import (
<ide> Expr,
<ide> Op,
<ide> def test_linear_solve(self):
<ide> assert ((z + y) * x + y).linear_solve(x) == (z + y, y)
<ide> assert (z * y * x + y).linear_solve(x) == (z * y, y)
<ide>
<del> assert_raises(RuntimeError, lambda: (x * x).linear_solve(x))
<add> pytest.raises(RuntimeError, lambda: (x * x).linear_solve(x))
<ide>
<ide> def test_as_numer_denom(self):
<ide> x = as_symbol("x") | 23 |
Javascript | Javascript | preserve error types during translation | f5fd24a61f8f77b1090c8278cc6446739ff44f9c | <ide><path>web/app.js
<ide> const PDFViewerApplication = {
<ide>
<ide> return loadingErrorMessage.then(msg => {
<ide> this.error(msg, { message });
<del> throw new Error(msg);
<add> throw exception;
<ide> });
<ide> }
<ide> ); | 1 |
Javascript | Javascript | improve console logging | 0f6762ba50b92a16fa11f10142b4416aace57f5e | <ide><path>Libraries/Utilities/PerformanceLogger.js
<ide> let timespans: {[key: string]: Timespan} = {};
<ide> let extras: {[key: string]: any} = {};
<ide> const cookies: {[key: string]: number} = {};
<ide>
<del>const PRINT_TO_CONSOLE = false;
<add>const PRINT_TO_CONSOLE: false = false; // Type as false to prevent accidentally committing `true`;
<ide>
<ide> /**
<ide> * This is meant to collect and log performance data in production, which means
<ide> const PerformanceLogger = {
<ide> startTime: performanceNow(),
<ide> };
<ide> cookies[key] = Systrace.beginAsyncEvent(key);
<del> if (__DEV__ && PRINT_TO_CONSOLE) {
<add> if (PRINT_TO_CONSOLE) {
<ide> infoLog('PerformanceLogger.js', 'start: ' + key);
<ide> }
<ide> },
<ide> const PerformanceLogger = {
<ide>
<ide> timespan.endTime = performanceNow();
<ide> timespan.totalTime = timespan.endTime - (timespan.startTime || 0);
<del> if (__DEV__ && PRINT_TO_CONSOLE) {
<add> if (PRINT_TO_CONSOLE) {
<ide> infoLog('PerformanceLogger.js', 'end: ' + key);
<ide> }
<ide>
<ide> const PerformanceLogger = {
<ide> clear() {
<ide> timespans = {};
<ide> extras = {};
<del> if (__DEV__ && PRINT_TO_CONSOLE) {
<add> if (PRINT_TO_CONSOLE) {
<ide> infoLog('PerformanceLogger.js', 'clear');
<ide> }
<ide> },
<ide> const PerformanceLogger = {
<ide> }
<ide> }
<ide> extras = {};
<del> if (__DEV__ && PRINT_TO_CONSOLE) {
<add> if (PRINT_TO_CONSOLE) {
<ide> infoLog('PerformanceLogger.js', 'clearCompleted');
<ide> }
<ide> },
<ide> const PerformanceLogger = {
<ide> return previous;
<ide> }, {});
<ide> extras = {};
<add> if (PRINT_TO_CONSOLE) {
<add> infoLog('PerformanceLogger.js', 'clearExceptTimespans', keys);
<add> }
<ide> },
<ide>
<ide> currentTimestamp() { | 1 |
Python | Python | update examples in stack docstrings | ab12dc87f4717fc0fdeca314cd32cd5924928595 | <ide><path>numpy/core/shape_base.py
<ide> def vstack(tup):
<ide> Examples
<ide> --------
<ide> >>> a = np.array([1, 2, 3])
<del> >>> b = np.array([2, 3, 4])
<add> >>> b = np.array([4, 5, 6])
<ide> >>> np.vstack((a,b))
<ide> array([[1, 2, 3],
<del> [2, 3, 4]])
<add> [4, 5, 6]])
<ide>
<ide> >>> a = np.array([[1], [2], [3]])
<del> >>> b = np.array([[2], [3], [4]])
<add> >>> b = np.array([[4], [5], [6]])
<ide> >>> np.vstack((a,b))
<ide> array([[1],
<ide> [2],
<ide> [3],
<del> [2],
<del> [3],
<del> [4]])
<add> [4],
<add> [5],
<add> [6]])
<ide>
<ide> """
<ide> if not overrides.ARRAY_FUNCTION_ENABLED:
<ide> def hstack(tup):
<ide> Examples
<ide> --------
<ide> >>> a = np.array((1,2,3))
<del> >>> b = np.array((2,3,4))
<add> >>> b = np.array((4,5,6))
<ide> >>> np.hstack((a,b))
<del> array([1, 2, 3, 2, 3, 4])
<add> array([1, 2, 3, 4, 5, 6])
<ide> >>> a = np.array([[1],[2],[3]])
<del> >>> b = np.array([[2],[3],[4]])
<add> >>> b = np.array([[4],[5],[6]])
<ide> >>> np.hstack((a,b))
<del> array([[1, 2],
<del> [2, 3],
<del> [3, 4]])
<add> array([[1, 4],
<add> [2, 5],
<add> [3, 6]])
<ide>
<ide> """
<ide> if not overrides.ARRAY_FUNCTION_ENABLED:
<ide> def stack(arrays, axis=0, out=None):
<ide> (3, 4, 10)
<ide>
<ide> >>> a = np.array([1, 2, 3])
<del> >>> b = np.array([2, 3, 4])
<add> >>> b = np.array([4, 5, 6])
<ide> >>> np.stack((a, b))
<ide> array([[1, 2, 3],
<del> [2, 3, 4]])
<add> [4, 5, 6]])
<ide>
<ide> >>> np.stack((a, b), axis=-1)
<del> array([[1, 2],
<del> [2, 3],
<del> [3, 4]])
<add> array([[1, 4],
<add> [2, 5],
<add> [3, 6]])
<ide>
<ide> """
<ide> if not overrides.ARRAY_FUNCTION_ENABLED:
<ide> def block(arrays):
<ide> array([1, 2, 3])
<ide>
<ide> >>> a = np.array([1, 2, 3])
<del> >>> b = np.array([2, 3, 4])
<add> >>> b = np.array([4, 5, 6])
<ide> >>> np.block([a, b, 10]) # hstack([a, b, 10])
<del> array([ 1, 2, 3, 2, 3, 4, 10])
<add> array([ 1, 2, 3, 4, 5, 6, 10])
<ide>
<ide> >>> A = np.ones((2, 2), int)
<ide> >>> B = 2 * A
<ide> def block(arrays):
<ide> With a list of depth 2, `block` can be used in place of `vstack`:
<ide>
<ide> >>> a = np.array([1, 2, 3])
<del> >>> b = np.array([2, 3, 4])
<add> >>> b = np.array([4, 5, 6])
<ide> >>> np.block([[a], [b]]) # vstack([a, b])
<ide> array([[1, 2, 3],
<del> [2, 3, 4]])
<add> [4, 5, 6]])
<ide>
<ide> >>> A = np.ones((2, 2), int)
<ide> >>> B = 2 * A | 1 |
Python | Python | add numpy prefix | 84a5dc190a21757c14bcbd6f2a114f7f27546a96 | <ide><path>numpy/core/_add_newdocs.py
<ide>
<ide> See Also
<ide> --------
<del> linspace : Evenly spaced numbers with careful handling of endpoints.
<del> ogrid: Arrays of evenly spaced numbers in N-dimensions.
<del> mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
<add> numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
<add> numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
<add> numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
<ide>
<ide> Examples
<ide> --------
<ide> See Also
<ide> --------
<ide> numpy.sort : Return a sorted copy of an array.
<del> argsort : Indirect sort.
<del> lexsort : Indirect stable sort on multiple keys.
<del> searchsorted : Find elements in sorted array.
<del> partition: Partial sort.
<add> numpy.argsort : Indirect sort.
<add> numpy.lexsort : Indirect stable sort on multiple keys.
<add> numpy.searchsorted : Find elements in sorted array.
<add> numpy.partition: Partial sort.
<ide>
<ide> Notes
<ide> -----
<ide><path>numpy/ma/core.py
<ide> def all(self, axis=None, out=None, keepdims=np._NoValue):
<ide>
<ide> See Also
<ide> --------
<del> ndarray.all : corresponding function for ndarrays
<add> numpy.ndarray.all : corresponding function for ndarrays
<ide> numpy.all : equivalent function
<ide>
<ide> Examples
<ide> def any(self, axis=None, out=None, keepdims=np._NoValue):
<ide>
<ide> See Also
<ide> --------
<del> ndarray.any : corresponding function for ndarrays
<add> numpy.ndarray.any : corresponding function for ndarrays
<ide> numpy.any : equivalent function
<ide>
<ide> """
<ide> def nonzero(self):
<ide> flatnonzero :
<ide> Return indices that are non-zero in the flattened version of the input
<ide> array.
<del> ndarray.nonzero :
<add> numpy.ndarray.nonzero :
<ide> Equivalent ndarray method.
<ide> count_nonzero :
<ide> Counts the number of non-zero elements in the input array.
<ide> def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
<ide>
<ide> See Also
<ide> --------
<del> ndarray.sum : corresponding function for ndarrays
<add> numpy.ndarray.sum : corresponding function for ndarrays
<ide> numpy.sum : equivalent function
<ide>
<ide> Examples
<ide> def cumsum(self, axis=None, dtype=None, out=None):
<ide>
<ide> See Also
<ide> --------
<del> ndarray.cumsum : corresponding function for ndarrays
<add> numpy.ndarray.cumsum : corresponding function for ndarrays
<ide> numpy.cumsum : equivalent function
<ide>
<ide> Examples
<ide> def prod(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
<ide>
<ide> See Also
<ide> --------
<del> ndarray.prod : corresponding function for ndarrays
<add> numpy.ndarray.prod : corresponding function for ndarrays
<ide> numpy.prod : equivalent function
<ide> """
<ide> kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
<ide> def cumprod(self, axis=None, dtype=None, out=None):
<ide>
<ide> See Also
<ide> --------
<del> ndarray.cumprod : corresponding function for ndarrays
<add> numpy.ndarray.cumprod : corresponding function for ndarrays
<ide> numpy.cumprod : equivalent function
<ide> """
<ide> result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out)
<ide> def mean(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
<ide>
<ide> See Also
<ide> --------
<del> ndarray.mean : corresponding function for ndarrays
<add> numpy.ndarray.mean : corresponding function for ndarrays
<ide> numpy.mean : Equivalent function
<ide> numpy.ma.average: Weighted average.
<ide>
<ide> def var(self, axis=None, dtype=None, out=None, ddof=0,
<ide>
<ide> See Also
<ide> --------
<del> ndarray.var : corresponding function for ndarrays
<add> numpy.ndarray.var : corresponding function for ndarrays
<ide> numpy.var : Equivalent function
<ide> """
<ide> kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
<ide> def std(self, axis=None, dtype=None, out=None, ddof=0,
<ide>
<ide> See Also
<ide> --------
<del> ndarray.std : corresponding function for ndarrays
<add> numpy.ndarray.std : corresponding function for ndarrays
<ide> numpy.std : Equivalent function
<ide> """
<ide> kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
<ide> def round(self, decimals=0, out=None):
<ide>
<ide> See Also
<ide> --------
<del> ndarray.around : corresponding function for ndarrays
<add> numpy.ndarray.around : corresponding function for ndarrays
<ide> numpy.around : equivalent function
<ide> """
<ide> result = self._data.round(decimals=decimals, out=out).view(type(self))
<ide> def argsort(self, axis=np._NoValue, kind=None, order=None,
<ide> --------
<ide> MaskedArray.sort : Describes sorting algorithms used.
<ide> lexsort : Indirect stable sort with multiple keys.
<del> ndarray.sort : Inplace sort.
<add> numpy.ndarray.sort : Inplace sort.
<ide>
<ide> Notes
<ide> -----
<ide> def sort(self, axis=-1, kind=None, order=None,
<ide>
<ide> See Also
<ide> --------
<del> ndarray.sort : Method to sort an array in-place.
<add> numpy.ndarray.sort : Method to sort an array in-place.
<ide> argsort : Indirect sort.
<ide> lexsort : Indirect stable sort on multiple keys.
<ide> searchsorted : Find elements in a sorted array.
<ide> def tobytes(self, fill_value=None, order='C'):
<ide>
<ide> See Also
<ide> --------
<del> ndarray.tobytes
<add> numpy.ndarray.tobytes
<ide> tolist, tofile
<ide>
<ide> Notes | 2 |
Java | Java | initialize native modules in a separate thread | 8bd570b7baf229e19c70955b631ad5b322ab91a0 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public void onNewIntent(Intent intent) {
<ide> currentContext.getNativeModule(DeviceEventManagerModule.class);
<ide> deviceEventManagerModule.emitNewIntentReceived(uri);
<ide> }
<del>
<ide> currentContext.onNewIntent(mCurrentActivity, intent);
<ide> }
<ide> } | 1 |
Javascript | Javascript | add code for generating remote assets | a75fef48bfb440a22fdc9605d4e677b87ebf290f | <ide><path>local-cli/core/Constants.js
<ide> 'use strict';
<ide>
<ide> const ASSET_REGISTRY_PATH = 'react-native/Libraries/Image/AssetRegistry';
<add>const ASSET_SOURCE_RESOLVER_PATH =
<add> 'react-native/Libraries/Image/AssetSourceResolver';
<ide>
<del>module.exports = {ASSET_REGISTRY_PATH};
<add>module.exports = {
<add> ASSET_REGISTRY_PATH,
<add> ASSET_SOURCE_RESOLVER_PATH,
<add>}; | 1 |
Go | Go | remove uses of pkg/urlutil.isurl() | 87206a10b9b3d95b768d1c0b6ea19c8bce92c749 | <ide><path>daemon/logger/splunk/splunk.go
<ide> import (
<ide> "github.com/docker/docker/daemon/logger"
<ide> "github.com/docker/docker/daemon/logger/loggerutils"
<ide> "github.com/docker/docker/pkg/pools"
<del> "github.com/docker/docker/pkg/urlutil"
<ide> "github.com/google/uuid"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide> func parseURL(info logger.Info) (*url.URL, error) {
<ide> return nil, fmt.Errorf("%s: failed to parse %s as url value in %s", driverName, splunkURLStr, splunkURLKey)
<ide> }
<ide>
<del> if !urlutil.IsURL(splunkURLStr) ||
<del> !splunkURL.IsAbs() ||
<add> if !splunkURL.IsAbs() ||
<add> (splunkURL.Scheme != "http" && splunkURL.Scheme != "https") ||
<ide> (splunkURL.Path != "" && splunkURL.Path != "/") ||
<ide> splunkURL.RawQuery != "" ||
<ide> splunkURL.Fragment != "" { | 1 |
Java | Java | change parallel to use long instead of int | 36dceba61a98e5b63026576b9fa84d860e91dd2e | <ide><path>rxjava-core/src/main/java/rx/operators/OperatorParallel.java
<ide>
<ide> private final Scheduler scheduler;
<ide> private final Func1<Observable<T>, Observable<R>> f;
<add> private final int degreeOfParallelism;
<ide>
<ide> public OperatorParallel(Func1<Observable<T>, Observable<R>> f, Scheduler scheduler) {
<ide> this.scheduler = scheduler;
<ide> this.f = f;
<add> this.degreeOfParallelism = scheduler.degreeOfParallelism();
<ide> }
<ide>
<ide> @Override
<ide> public Subscriber<? super T> call(Subscriber<? super R> op) {
<ide>
<del> Func1<Subscriber<? super GroupedObservable<Integer, T>>, Subscriber<? super T>> groupBy =
<del> new OperatorGroupBy<Integer, T>(new Func1<T, Integer>() {
<add> Func1<Subscriber<? super GroupedObservable<Long, T>>, Subscriber<? super T>> groupBy =
<add> new OperatorGroupBy<Long, T>(new Func1<T, Long>() {
<ide>
<del> int i = 0;
<add> long i = 0;
<ide>
<ide> @Override
<del> public Integer call(T t) {
<del> return i++ % scheduler.degreeOfParallelism();
<add> public Long call(T t) {
<add> return i++ % degreeOfParallelism;
<ide> }
<ide>
<ide> });
<ide>
<del> Func1<Subscriber<? super Observable<R>>, Subscriber<? super GroupedObservable<Integer, T>>> map =
<del> new OperatorMap<GroupedObservable<Integer, T>, Observable<R>>(
<del> new Func1<GroupedObservable<Integer, T>, Observable<R>>() {
<add> Func1<Subscriber<? super Observable<R>>, Subscriber<? super GroupedObservable<Long, T>>> map =
<add> new OperatorMap<GroupedObservable<Long, T>, Observable<R>>(
<add> new Func1<GroupedObservable<Long, T>, Observable<R>>() {
<ide>
<ide> @Override
<del> public Observable<R> call(GroupedObservable<Integer, T> g) {
<add> public Observable<R> call(GroupedObservable<Long, T> g) {
<ide> // Must use observeOn not subscribeOn because we have a single source behind groupBy.
<ide> // The origin is already subscribed to, we are moving each group on to a new thread
<ide> // but the origin itself can only be on a single thread.
<ide><path>rxjava-core/src/perf/java/rx/operators/OperatorParallelPerformance.java
<add>package rx.operators;
<add>
<add>import rx.Observable;
<add>import rx.functions.Action0;
<add>import rx.functions.Func1;
<add>import rx.perf.AbstractPerformanceTester;
<add>import rx.perf.IntegerSumObserver;
<add>
<add>public class OperatorParallelPerformance extends AbstractPerformanceTester {
<add>
<add> private final static int REPS = 10000000;
<add>
<add> OperatorParallelPerformance() {
<add> super(REPS);
<add> }
<add>
<add> public static void main(String args[]) {
<add>
<add> final OperatorParallelPerformance spt = new OperatorParallelPerformance();
<add> try {
<add> spt.runTest(new Action0() {
<add>
<add> @Override
<add> public void call() {
<add> spt.parallelSum();
<add> }
<add> });
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> }
<add>
<add> }
<add>
<add> /**
<add> *
<add> * Run: 10 - 11,220,888 ops/sec
<add> * Run: 11 - 12,372,424 ops/sec
<add> * Run: 12 - 11,028,921 ops/sec
<add> * Run: 13 - 11,813,711 ops/sec
<add> * Run: 14 - 12,098,364 ops/sec
<add> *
<add> */
<add> public long parallelSum() {
<add>
<add> Observable<Integer> s = Observable.range(1, REPS).parallel(new Func1<Observable<Integer>, Observable<Integer>>() {
<add>
<add> @Override
<add> public Observable<Integer> call(Observable<Integer> l) {
<add> return l.map(new Func1<Integer, Integer>() {
<add>
<add> @Override
<add> public Integer call(Integer i) {
<add> return i + 1;
<add> }
<add>
<add> });
<add> }
<add>
<add> });
<add> IntegerSumObserver o = new IntegerSumObserver();
<add>
<add> s.subscribe(o);
<add> return o.sum;
<add> }
<add>
<add>}
<ide>\ No newline at end of file | 2 |
Python | Python | expose all the pipeline argument on serve command | 3b29322d4c197fec46ae48f62aa2870d00d0852a | <ide><path>transformers/commands/serving.py
<ide> def serve_command_factory(args: Namespace):
<ide> Factory function used to instantiate serving server from provided command line arguments.
<ide> :return: ServeCommand
<ide> """
<del> nlp = pipeline(args.task, args.model)
<del> return ServeCommand(nlp, args.host, args.port, args.model, args.graphql)
<add> nlp = pipeline(task=args.task, model=args.model, config=args.config, tokenizer=args.tokenizer, device=args.device)
<add> return ServeCommand(nlp, args.host, args.port)
<ide>
<ide>
<del>class ServeResult(BaseModel):
<del> """
<del> Base class for serving result
<del> """
<del> model: str
<del>
<del>
<del>class ServeModelInfoResult(ServeResult):
<add>class ServeModelInfoResult(BaseModel):
<ide> """
<ide> Expose model information
<ide> """
<ide> infos: dict
<ide>
<ide>
<del>class ServeTokenizeResult(ServeResult):
<add>class ServeTokenizeResult(BaseModel):
<ide> """
<ide> Tokenize result model
<ide> """
<ide> tokens: List[str]
<ide> tokens_ids: Optional[List[int]]
<ide>
<ide>
<del>class ServeDeTokenizeResult(ServeResult):
<add>class ServeDeTokenizeResult(BaseModel):
<ide> """
<ide> DeTokenize result model
<ide> """
<ide> text: str
<ide>
<ide>
<del>class ServeForwardResult(ServeResult):
<add>class ServeForwardResult(BaseModel):
<ide> """
<ide> Forward result model
<ide> """
<ide> def register_subcommand(parser: ArgumentParser):
<ide> serve_parser.add_argument('--device', type=int, default=-1, help='Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)')
<ide> serve_parser.add_argument('--host', type=str, default='localhost', help='Interface the server will listen on.')
<ide> serve_parser.add_argument('--port', type=int, default=8888, help='Port the serving will listen to.')
<del> serve_parser.add_argument('--model', type=str, required=True, help='Model\'s name or path to stored model to infer from.')
<del> serve_parser.add_argument('--graphql', action='store_true', default=False, help='Enable GraphQL endpoints.')
<add> serve_parser.add_argument('--model', type=str, required=True, help='Model\'s name or path to stored model.')
<add> serve_parser.add_argument('--config', type=str, help='Model\'s config name or path to stored model.')
<add> serve_parser.add_argument('--tokenizer', type=str, help='Tokenizer name to use.')
<ide> serve_parser.set_defaults(func=serve_command_factory)
<ide>
<del> def __init__(self, pipeline: Pipeline, host: str, port: int, model: str, graphql: bool):
<add> def __init__(self, pipeline: Pipeline, host: str, port: int):
<ide> self._logger = getLogger('transformers-cli/serving')
<ide>
<ide> self._pipeline = pipeline
<ide> def run(self):
<ide> run(self._app, host=self._host, port=self._port)
<ide>
<ide> def model_info(self):
<del> return ServeModelInfoResult(model='', infos=vars(self._pipeline.model.config))
<add> return ServeModelInfoResult(infos=vars(self._pipeline.model.config))
<ide>
<ide> def tokenize(self, text_input: str = Body(None, embed=True), return_ids: bool = Body(False, embed=True)):
<ide> """
<ide> def tokenize(self, text_input: str = Body(None, embed=True), return_ids: bool =
<ide>
<ide> if return_ids:
<ide> tokens_ids = self._pipeline.tokenizer.convert_tokens_to_ids(tokens_txt)
<del> return ServeTokenizeResult(model='', tokens=tokens_txt, tokens_ids=tokens_ids)
<add> return ServeTokenizeResult(tokens=tokens_txt, tokens_ids=tokens_ids)
<ide> else:
<del> return ServeTokenizeResult(model='', tokens=tokens_txt)
<add> return ServeTokenizeResult(tokens=tokens_txt)
<ide>
<ide> except Exception as e:
<ide> raise HTTPException(status_code=500, detail={"model": '', "error": str(e)})
<ide> def forward(self, inputs: Union[str, dict, List[str], List[int], List[dict]] = B
<ide>
<ide> # Check we don't have empty string
<ide> if len(inputs) == 0:
<del> return ServeForwardResult(model='', output=[], attention=[])
<add> return ServeForwardResult(output=[], attention=[])
<ide>
<ide> try:
<ide> # Forward through the model
<ide> output = self._pipeline(inputs)
<del> return ServeForwardResult(
<del> model='', output=output
<del> )
<add> return ServeForwardResult(output=output)
<ide> except Exception as e:
<ide> raise HTTPException(500, {"error": str(e)}) | 1 |
PHP | PHP | fix save with habtm returning false | a8e410ee20008c2fb6e38867b2da59d1ccf63da9 | <ide><path>lib/Cake/Model/Model.php
<ide> public function save($data = null, $validate = true, $fieldList = array()) {
<ide> if (empty($this->data[$this->alias][$this->primaryKey])) {
<ide> unset($this->data[$this->alias][$this->primaryKey]);
<ide> }
<del> $fields = $values = array();
<add> $joined = $fields = $values = array();
<ide>
<ide> foreach ($this->data as $n => $v) {
<ide> if (isset($this->hasAndBelongsToMany[$n])) {
<ide> public function save($data = null, $validate = true, $fieldList = array()) {
<ide> }
<ide> }
<ide>
<del> if (!empty($joined) && $success === true) {
<del> $this->_saveMulti($joined, $this->id, $db);
<del> }
<del>
<del> if ($success && $count === 0) {
<del> $success = false;
<add> if ($success) {
<add> if (!empty($joined)) {
<add> $this->_saveMulti($joined, $this->id, $db);
<add> } else if ($count === 0) {
<add> $success = false;
<add> }
<ide> }
<ide>
<del> if ($success && $count > 0) {
<del> if (!empty($this->data)) {
<del> if ($created) {
<del> $this->data[$this->alias][$this->primaryKey] = $this->id;
<add> if ($success) {
<add> if ($count > 0) {
<add> if (!empty($this->data)) {
<add> if ($created) {
<add> $this->data[$this->alias][$this->primaryKey] = $this->id;
<add> }
<ide> }
<del> }
<ide>
<del> if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
<del> $event = new CakeEvent('Model.afterSave', $this, array($created, $options));
<del> $this->getEventManager()->dispatch($event);
<add> if ($options['callbacks'] === true || $options['callbacks'] === 'after') {
<add> $event = new CakeEvent('Model.afterSave', $this, array($created, $options));
<add> $this->getEventManager()->dispatch($event);
<add> }
<ide> }
<ide>
<ide> if (!empty($this->data)) {
<ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php
<ide> public function testSaveHabtmNoPrimaryData() {
<ide>
<ide> $data = array('Item' => array('Item' => array(1, 2)));
<ide> $TestModel->id = 2;
<del> $TestModel->save($data);
<add> $result = $TestModel->save($data);
<add> $this->assertTrue((bool)$result);
<add>
<ide> $result = $TestModel->findById(2);
<ide> $result['Item'] = Hash::sort($result['Item'], '{n}.id', 'asc');
<ide> $expected = array( | 2 |
Ruby | Ruby | add quiet flag | ff4544eebd4fb711b44b80bdd6e569caf1dce9a8 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def update_report_args
<ide> switch "--preinstall",
<ide> description: "Run in 'auto-update' mode (faster, less output)."
<ide> switch :force
<add> switch :quiet
<ide> switch :debug
<ide> switch :verbose
<ide> hide_from_man_page! | 1 |
PHP | PHP | use foreach instead of array_filter | 2c36545960acbdf32a48b9aa852deb85a3f4c52a | <ide><path>src/ORM/ResultSet.php
<ide> protected function _groupResult($row) {
<ide> if ($assoc['canBeJoined']) {
<ide> $results[$alias] = $this->_castValues($target, $results[$alias]);
<ide>
<del> $hasData = array_filter($results[$alias], function ($v) {
<del> return $v !== null;
<del> });
<add> $hasData = false;
<add> foreach ($results[$alias] as $v) {
<add> if ($v !== null) {
<add> $hasData = true;
<add> break;
<add> }
<add> }
<ide>
<ide> if (!$hasData) {
<ide> continue; | 1 |
Javascript | Javascript | unify attribute bindings logic and fix some bugs | 3a07b4df1ee579b9fb92eb26db495120c37a870f | <ide><path>packages/ember-handlebars/lib/helpers/binding.js
<ide> Ember.Handlebars.registerHelper('bindAttr', function(options) {
<ide> return;
<ide> }
<ide>
<del> var currentValue = elem.attr(attr);
<del>
<del> // A false result will remove the attribute from the element. This is
<del> // to support attributes such as disabled, whose presence is meaningful.
<del> if (result === false && currentValue) {
<del> elem.removeAttr(attr);
<del>
<del> // Likewise, a true result will set the attribute's name as the value.
<del> } else if (result === true && currentValue !== attr) {
<del> elem.attr(attr, attr);
<del>
<del> } else if (currentValue !== result) {
<del> elem.attr(attr, result);
<del> }
<add> Ember.View.applyAttributeBindings(elem, attr, result);
<ide> };
<ide>
<ide> /** @private */
<ide> Ember.Handlebars.registerHelper('bindAttr', function(options) {
<ide> // unique data id and update the attribute to the new value.
<ide> Ember.addObserver(ctx, property, invoker);
<ide>
<del> // Use the attribute's name as the value when it is YES
<del> if (value === true) {
<del> value = attr;
<del> }
<add> var type = typeof value;
<ide>
<del> // Do not add the attribute when the value is false
<del> if (value !== false) {
<del> // Return the current value, in the form src="foo.jpg"
<add> if ((type === 'string' || (type === 'number' && !isNaN(value)))) {
<ide> ret.push(attr + '="' + value + '"');
<add> } else if (value && type === 'boolean') {
<add> ret.push(attr + '="' + attr + '"');
<ide> }
<ide> }, this);
<ide>
<ide><path>packages/ember-views/lib/system/render_buffer.js
<ide> Ember._RenderBuffer = Ember.Object.extend(
<ide> return this;
<ide> },
<ide>
<add> // duck type attribute functionality like jQuery so a render buffer
<add> // can be used like a jQuery object in attribute binding scenarios.
<add>
<ide> /**
<ide> Adds an attribute which will be rendered to the element.
<ide>
<ide> @param {String} name The name of the attribute
<ide> @param {String} value The value to add to the attribute
<del> @returns {Ember.RenderBuffer} this
<add> @returns {Ember.RenderBuffer|String} this or the current attribute value
<ide> */
<ide> attr: function(name, value) {
<del> get(this, 'elementAttributes')[name] = value;
<add> var attributes = get(this, 'elementAttributes');
<add>
<add> if (arguments.length === 1) {
<add> return attributes[name]
<add> } else {
<add> attributes[name] = value;
<add> }
<add>
<add> return this;
<add> },
<add>
<add> /**
<add> Remove an attribute from the list of attributes to render.
<add>
<add> @param {String} name The name of the attribute
<add> @returns {Ember.RenderBuffer} this
<add> */
<add> removeAttr: function(name) {
<add> var attributes = get(this, 'elementAttributes');
<add> delete attributes[name];
<add>
<ide> return this;
<ide> },
<ide>
<ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.View = Ember.Object.extend(
<ide>
<ide> if (!attributeBindings) { return; }
<ide>
<del> attributeBindings.forEach(function(attribute) {
<add> attributeBindings.forEach(function(attributeName) {
<ide> // Create an observer to add/remove/change the attribute if the
<ide> // JavaScript property changes.
<ide> var observer = function() {
<ide> elem = this.$();
<del> var currentValue = elem.attr(attribute);
<del> attributeValue = get(this, attribute);
<add> attributeValue = get(this, attributeName);
<ide>
<del> type = typeof attributeValue;
<del>
<del> if ((type === 'string' || (type === 'number' && !isNaN(attributeValue))) && attributeValue !== currentValue) {
<del> elem.attr(attribute, attributeValue);
<del> } else if (attributeValue && type === 'boolean') {
<del> elem.attr(attribute, attribute);
<del> } else if (!attributeValue) {
<del> elem.removeAttr(attribute);
<del> }
<add> Ember.View.applyAttributeBindings(elem, attributeName, attributeValue)
<ide> };
<ide>
<del> addObserver(this, attribute, observer);
<add> addObserver(this, attributeName, observer);
<ide>
<ide> // Determine the current value and add it to the render buffer
<ide> // if necessary.
<del> attributeValue = get(this, attribute);
<del> type = typeof attributeValue;
<del>
<del> if (type === 'string' || type === 'number') {
<del> buffer.attr(attribute, attributeValue);
<del> } else if (attributeValue && type === 'boolean') {
<del> // Apply boolean attributes in the form attribute="attribute"
<del> buffer.attr(attribute, attribute);
<del> }
<add> attributeValue = get(this, attributeName);
<add> Ember.View.applyAttributeBindings(buffer, attributeName, attributeValue);
<ide> }, this);
<ide> },
<ide>
<ide> Ember.View.views = {};
<ide> // at view initialization time. This happens in Ember.ContainerView's init
<ide> // method.
<ide> Ember.View.childViewsProperty = childViewsProperty;
<add>
<add>Ember.View.applyAttributeBindings = function(elem, name, value) {
<add> var type = typeof value;
<add> var currentValue = elem.attr(name);
<add>
<add> // if this changes, also change the logic in ember-handlebars/lib/helpers/binding.js
<add> if ((type === 'string' || (type === 'number' && !isNaN(value))) && value !== currentValue) {
<add> elem.attr(name, value);
<add> } else if (value && type === 'boolean') {
<add> elem.attr(name, name);
<add> } else if (!value) {
<add> elem.removeAttr(name);
<add> }
<add>};
<ide><path>packages/ember-views/tests/views/view/attribute_bindings_test.js
<ide> require('ember-views/views/view');
<ide>
<ide> module("Ember.View - Attribute Bindings");
<ide>
<del>test("should render and update attribute bindings", function() {
<add>test("should render attribute bindings", function() {
<add> var view = Ember.View.create({
<add> classNameBindings: ['priority', 'isUrgent', 'isClassified:classified', 'canIgnore'],
<add> attributeBindings: ['type', 'exploded', 'destroyed', 'exists', 'nothing', 'notDefined', 'notNumber', 'explosions'],
<add>
<add> type: 'submit',
<add> exploded: false,
<add> destroyed: false,
<add> exists: true,
<add> nothing: null,
<add> notDefined: undefined,
<add> notNumber: NaN,
<add> });
<add>
<add> view.createElement();
<add>
<add> equals(view.$().attr('type'), 'submit', "updates type attribute");
<add> ok(!view.$().attr('exploded'), "removes exploded attribute when false");
<add> ok(!view.$().attr('destroyed'), "removes destroyed attribute when false");
<add> ok(view.$().attr('exists'), "adds exists attribute when true");
<add> ok(!view.$().attr('nothing'), "removes nothing attribute when null");
<add> ok(!view.$().attr('notDefined'), "removes notDefined attribute when undefined");
<add> ok(!view.$().attr('notNumber'), "removes notNumber attribute when NaN");
<add>});
<add>
<add>test("should update attribute bindings", function() {
<ide> var view = Ember.View.create({
<ide> classNameBindings: ['priority', 'isUrgent', 'isClassified:classified', 'canIgnore'],
<ide> attributeBindings: ['type', 'exploded', 'destroyed', 'exists', 'nothing', 'notDefined', 'notNumber', 'explosions'], | 4 |
PHP | PHP | incorporate feedback thus far | b160b2c72410c67d6ddc88ce100f61282f7f7c1d | <ide><path>src/Database/Type/DateTimeType.php
<ide> use Cake\Database\Driver;
<ide> use Cake\Database\Type;
<ide> use DateTimeInterface;
<del>use DateTimeImmutable;
<ide> use Exception;
<ide> use RuntimeException;
<ide>
<ide> public function toPHP($value, Driver $driver)
<ide> */
<ide> public function marshal($value)
<ide> {
<del> if ($value instanceof DateTime || $value instanceof DateTimeImmutable) {
<add> if ($value instanceof DateTimeInterface) {
<ide> return $value;
<ide> }
<ide>
<ide><path>src/I18n/Date.php
<ide> class Date extends BaseDate implements JsonSerializable
<ide> protected static $_toStringFormat = [IntlDateFormatter::SHORT, -1];
<ide>
<ide> /**
<del> * The format to use when formatting a time using `Cake\I18n\Time::timeAgoInWords()`
<del> * and the difference is more than `Cake\I18n\Time::$wordEnd`
<add> * The format to use when formatting a time using `Cake\I18n\Date::timeAgoInWords()`
<add> * and the difference is more than `Cake\I18n\Date::$wordEnd`
<ide> *
<ide> * @var string
<ide> * @see \Cake\I18n\DateFormatTrait::parseDate()
<ide> */
<ide> public static $wordFormat = [IntlDateFormatter::SHORT, -1];
<ide>
<ide> /**
<del> * The format to use when formatting a time using `Cake\I18n\Time::nice()`
<add> * The format to use when formatting a time using `Cake\I18n\Date::nice()`
<ide> *
<ide> * The format should be either the formatting constants from IntlDateFormatter as
<ide> * described in (http://www.php.net/manual/en/class.intldateformatter.php) or a pattern
<ide> class Date extends BaseDate implements JsonSerializable
<ide> public static $niceFormat = [IntlDateFormatter::MEDIUM, -1];
<ide>
<ide> /**
<del> * The format to use when formatting a time using `Time::timeAgoInWords()`
<del> * and the difference is less than `Time::$wordEnd`
<add> * The format to use when formatting a time using `Date::timeAgoInWords()`
<add> * and the difference is less than `Date::$wordEnd`
<ide> *
<ide> * @var array
<ide> * @see \Cake\I18n\Date::timeAgoInWords() | 2 |
Javascript | Javascript | add --expose_internals switch | 99a2dd03cd286176d639ec898a08f27c1567f85c | <ide><path>benchmark/common.js
<ide> Benchmark.prototype._run = function() {
<ide> }
<ide>
<ide> const child = child_process.fork(require.main.filename, childArgs, {
<del> env: childEnv
<add> env: childEnv,
<add> execArgv: ['--expose_internals'].concat(process.execArgv)
<ide> });
<ide> child.on('message', sendResult);
<ide> child.on('close', function(code) {
<ide><path>benchmark/misc/freelist.js
<ide> 'use strict';
<ide>
<ide> var common = require('../common.js');
<del>var FreeList = require('internal/freelist').FreeList;
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> n: [100000]
<ide> });
<ide>
<ide> function main(conf) {
<add> // Using internal/freelist requires node to be run with --expose_internals
<add> // switch. common.js will do that when calling main(), so we require
<add> // this module here
<add> const FreeList = require('internal/freelist').FreeList;
<ide> var n = conf.n;
<ide> var poolSize = 1000;
<ide> var list = new FreeList('test', poolSize, Object); | 2 |
Javascript | Javascript | show time when zero | 20fe1ed007d72ab16d70883bd8d0fd2e69258610 | <ide><path>lib/Stats.js
<ide> Stats.jsonToString = function jsonToString(obj, useColors) {
<ide> bold(obj.version);
<ide> newline();
<ide> }
<del> if(obj.time) {
<add> if(typeof obj.time === "number") {
<ide> normal("Time: ");
<ide> bold(obj.time);
<ide> normal("ms"); | 1 |
Python | Python | use invalid_data key for error message. closes | 003c42b0f51f9bfa93964be69fb8cb68b7394280 | <ide><path>rest_framework/serializers.py
<ide> from django.db.models.fields import FieldDoesNotExist
<ide> from django.utils import six
<ide> from django.utils.datastructures import SortedDict
<add>from django.utils.translation import ugettext_lazy as _
<ide> from rest_framework.exceptions import ValidationError
<ide> from rest_framework.fields import empty, set_value, Field, SkipField
<ide> from rest_framework.settings import api_settings
<ide> def __new__(cls, name, bases, attrs):
<ide>
<ide> @six.add_metaclass(SerializerMetaclass)
<ide> class Serializer(BaseSerializer):
<add> default_error_messages = {
<add> 'invalid': _('Invalid data. Expected a dictionary, but got {datatype}.')
<add> }
<add>
<ide> @property
<ide> def fields(self):
<ide> if not hasattr(self, '_fields'):
<ide> def run_validation(self, data=empty):
<ide> return None
<ide>
<ide> if not isinstance(data, dict):
<add> message = self.error_messages['invalid'].format(
<add> datatype=type(data).__name__
<add> )
<ide> raise ValidationError({
<del> api_settings.NON_FIELD_ERRORS_KEY: ['Invalid data']
<add> api_settings.NON_FIELD_ERRORS_KEY: [message]
<ide> })
<ide>
<ide> value = self.to_internal_value(data)
<ide><path>tests/test_validation.py
<ide> class TestAvoidValidation(TestCase):
<ide> def test_serializer_errors_has_only_invalid_data_error(self):
<ide> serializer = ValidationSerializer(data='invalid data')
<ide> self.assertFalse(serializer.is_valid())
<del> self.assertDictEqual(serializer.errors,
<del> {'non_field_errors': ['Invalid data']})
<add> self.assertDictEqual(serializer.errors, {
<add> 'non_field_errors': [
<add> 'Invalid data. Expected a dictionary, but got unicode.'
<add> ]
<add> })
<ide>
<ide>
<ide> # regression tests for issue: 1493 | 2 |
Javascript | Javascript | add mymuesli to website showcase | fc52a65e64ec3082753772992bca65dc886d9f57 | <ide><path>website/src/react-native/showcase.js
<ide> var featured = [
<ide> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.movielala.trailers',
<ide> author: 'MovieLaLa'
<ide> },
<add> {
<add> name: 'MyMuesli',
<add> icon: 'https://lh3.googleusercontent.com/1dCCeiyjuWRgY-Cnv-l-lOA1sVH3Cn0vkVWWZnaBQbhHOhsngLcnfy68WEerudPUysc=w300-rw',
<add> link: 'https://play.google.com/store/apps/details?id=com.mymuesli',
<add> author: 'Shawn Khameneh (@shawnscode), 3DWD'
<add> },
<ide> {
<ide> name: 'Myntra',
<ide> icon: 'http://a5.mzstatic.com/us/r30/Purple6/v4/9c/78/df/9c78dfa6-0061-1af2-5026-3e1d5a073c94/icon350x350.png', | 1 |
Java | Java | fix mockhttpservletrequest reference in javadoc | cf4e77907f7056cbee60efb5842989d9266f091d | <ide><path>spring-test/src/main/java/org/springframework/mock/web/MockHttpServletMapping.java
<ide> /**
<ide> * Mock implementation of {@link HttpServletMapping}.
<ide> *
<del> * <p>Currently not exposed in {@link MockHttpServletMapping} as a setter to
<add> * <p>Currently not exposed in {@link MockHttpServletRequest} as a setter to
<ide> * avoid issues for Maven builds in applications with a Servlet 3.1 runtime
<ide> * requirement.
<ide> * | 1 |
PHP | PHP | implement contract on manager | 68ac51a3c85d039799d32f53a045328e14debfea | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function base_path($path = '')
<ide> * Hash the given value against the bcrypt algorithm.
<ide> *
<ide> * @param string $value
<del> * @param array $options
<add> * @param array $options
<ide> * @return string
<ide> */
<ide> function bcrypt($value, $options = [])
<ide> {
<del> return app('hash')
<del> ->driver('bcrypt')
<del> ->make($value, $options);
<add> return app('hash')->driver('bcrypt')->make($value, $options);
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Hashing/HashManager.php
<ide> namespace Illuminate\Hashing;
<ide>
<ide> use Illuminate\Support\Manager;
<add>use Illuminate\Contracts\Hashing\Hasher;
<ide>
<del>class HashManager extends Manager
<add>class HashManager extends Manager implements Hasher
<ide> {
<del> /**
<del> * Get the default driver name.
<del> *
<del> * @return string
<del> */
<del> public function getDefaultDriver()
<del> {
<del> return $this->app['config']['hashing.driver'];
<del> }
<del>
<ide> /**
<ide> * Create an instance of the Brycrypt hash Driver.
<ide> *
<ide> public function createArgonDriver()
<ide> {
<ide> return new ArgonHasher;
<ide> }
<del>}
<ide>\ No newline at end of file
<add>
<add> /**
<add> * Hash the given value.
<add> *
<add> * @param string $value
<add> * @param array $options
<add> * @return string
<add> */
<add> public function make($value, array $options = [])
<add> {
<add> return $this->driver()->make($value, $options);
<add> }
<add>
<add> /**
<add> * Check the given plain value against a hash.
<add> *
<add> * @param string $value
<add> * @param string $hashedValue
<add> * @param array $options
<add> * @return bool
<add> */
<add> public function check($value, $hashedValue, array $options = [])
<add> {
<add> return $this->driver()->check($value, $hashedValue, $options);
<add> }
<add>
<add> /**
<add> * Check if the given hash has been hashed using the given options.
<add> *
<add> * @param string $hashedValue
<add> * @param array $options
<add> * @return bool
<add> */
<add> public function needsRehash($hashedValue, array $options = [])
<add> {
<add> return $this->driver()->needsRehash($hashedValue, $options);
<add> }
<add>
<add> /**
<add> * Get the default driver name.
<add> *
<add> * @return string
<add> */
<add> public function getDefaultDriver()
<add> {
<add> return $this->app['config']['hashing.driver'];
<add> }
<add>} | 2 |
Python | Python | fix error with driver param | e2f2818e0198e2caa96befa61990daa20565d83c | <ide><path>libcloud/compute/drivers/openstack.py
<ide> class OpenStack_2_Router(object):
<ide> A Virtual Router.
<ide> """
<ide>
<del> def __init__(self, id, name, status, extra=None):
<add> def __init__(self, id, name, status, driver, extra=None):
<ide> self.id = str(id)
<ide> self.name = name
<ide> self.status = status
<add> self.driver = driver
<ide> self.extra = extra or {}
<ide>
<ide> def __repr__(self): | 1 |
PHP | PHP | add assertnothingpushed method to queuefake | 331850ecb54c140358cba5f5e9141e830491812c | <ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php
<ide> public function assertNotPushed($job, $callback = null)
<ide> );
<ide> }
<ide>
<add> /**
<add> * Assert that no jobs were pushed.
<add> *
<add> * @return void
<add> */
<add> public function assertNothingPushed()
<add> {
<add> PHPUnit::assertEmpty($this->jobs, 'Jobs were pushed unexpectedly.');
<add> }
<add>
<ide> /**
<ide> * Get all of the jobs matching a truth-test callback.
<ide> *
<ide><path>tests/Support/SupportTestingQueueFakeTest.php
<ide> public function testAssertPushedTimes()
<ide>
<ide> $this->fake->assertPushed(JobStub::class, 2);
<ide> }
<add>
<add> /**
<add> * @expectedException PHPUnit\Framework\ExpectationFailedException
<add> * @expectedExceptionMessage Jobs were pushed unexpectedly.
<add> */
<add> public function testAssertNothingPushed()
<add> {
<add> $this->fake->assertNothingPushed();
<add>
<add> $this->fake->push($this->job);
<add>
<add> $this->fake->assertNothingPushed();
<add> }
<ide> }
<ide>
<ide> class JobStub | 2 |
Ruby | Ruby | use better duration aliases in tests | c7135d2c8ebf2263ebb82dfe1723c7435676e11f | <ide><path>actionmailer/test/message_delivery_test.rb
<ide> def test_should_enqueue_and_run_correctly_in_activejob
<ide>
<ide> test "should enqueue a delivery with a delay" do
<ide> travel_to Time.new(2004, 11, 24, 01, 04, 44) do
<del> assert_performed_with(job: ActionMailer::DeliveryJob, at: Time.current + 600.seconds, args: ["DelayedMailer", "test_message", "deliver_now", 1, 2, 3]) do
<del> @mail.deliver_later wait: 600.seconds
<add> assert_performed_with(job: ActionMailer::DeliveryJob, at: Time.current + 10.minutes, args: ["DelayedMailer", "test_message", "deliver_now", 1, 2, 3]) do
<add> @mail.deliver_later wait: 10.minutes
<ide> end
<ide> end
<ide> end | 1 |
Text | Text | fix variable notation | 07e813a3b3e05121e4d17b9bbb77ed7db5d3d907 | <ide><path>docs/Common-Issues.md
<ide> If, however, you do not have a `.curlrc` or removing it did not work, let’s se
<ide> The cask is outdated. Let’s fix it:
<ide>
<ide> 1. Look around the app’s website and find out what the latest version is. It will likely be expressed in the URL used to download it.
<del>2. Take a look at the cask’s version (`brew cat {{cask_name}}`) and verify it is indeed outdated. If the app’s version is `:latest`, it means the `url` itself is outdated. It will need to be changed to the new one.
<add>2. Take a look at the cask’s version (`brew cat <cask_name>`) and verify it is indeed outdated. If the app’s version is `:latest`, it means the `url` itself is outdated. It will need to be changed to the new one.
<ide>
<ide> Help us by [submitting a fix](https://github.com/Homebrew/homebrew-cask/blob/HEAD/CONTRIBUTING.md#updating-a-cask). If you get stumped, [open an issue](https://github.com/Homebrew/homebrew-cask/issues/new?template=01_bug_report.md) explaining your steps so far and where you’re having trouble.
<ide> | 1 |
Go | Go | remove hacked windows oci spec, compile fixups | 02309170a5fb97d40260d0ee9e24b44be8c780b2 | <ide><path>daemon/exec_linux.go
<ide> import (
<ide> "github.com/docker/docker/daemon/caps"
<ide> "github.com/docker/docker/daemon/exec"
<ide> "github.com/docker/docker/libcontainerd"
<add> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<ide> func execSetPlatformOpt(c *container.Container, ec *exec.Config, p *libcontainerd.Process) error {
<ide> func execSetPlatformOpt(c *container.Container, ec *exec.Config, p *libcontainer
<ide> if err != nil {
<ide> return err
<ide> }
<del> p.User = &libcontainerd.User{
<add> p.User = &specs.User{
<ide> UID: uid,
<ide> GID: gid,
<ide> AdditionalGids: additionalGids,
<ide><path>daemon/oci_linux.go
<ide> import (
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/daemon/caps"
<del> "github.com/docker/docker/libcontainerd"
<ide> "github.com/docker/docker/oci"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> "github.com/docker/docker/pkg/mount"
<ide> func (daemon *Daemon) populateCommonSpec(s *specs.Spec, c *container.Container)
<ide> return nil
<ide> }
<ide>
<del>func (daemon *Daemon) createSpec(c *container.Container) (*libcontainerd.Spec, error) {
<add>func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) {
<ide> s := oci.DefaultSpec()
<ide> if err := daemon.populateCommonSpec(&s, c); err != nil {
<ide> return nil, err
<ide> func (daemon *Daemon) createSpec(c *container.Container) (*libcontainerd.Spec, e
<ide> s.Process.NoNewPrivileges = c.NoNewPrivileges
<ide> s.Linux.MountLabel = c.MountLabel
<ide>
<del> return (*libcontainerd.Spec)(&s), nil
<add> return (*specs.Spec)(&s), nil
<ide> }
<ide>
<ide> func clearReadOnly(m *specs.Mount) {
<ide><path>daemon/oci_solaris.go
<ide> package daemon
<ide> import (
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/container"
<del> "github.com/docker/docker/libcontainerd"
<ide> "github.com/docker/docker/oci"
<add> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<del>func (daemon *Daemon) createSpec(c *container.Container) (*libcontainerd.Spec, error) {
<add>func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) {
<ide> s := oci.DefaultSpec()
<del> return (*libcontainerd.Spec)(&s), nil
<add> return (*specs.Spec)(&s), nil
<ide> }
<ide>
<ide> // mergeUlimits merge the Ulimits from HostConfig with daemon defaults, and update HostConfig
<ide><path>daemon/oci_windows.go
<ide> import (
<ide>
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/container"
<del> "github.com/docker/docker/libcontainerd"
<del> "github.com/docker/docker/libcontainerd/windowsoci"
<ide> "github.com/docker/docker/oci"
<add> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<del>func (daemon *Daemon) createSpec(c *container.Container) (*libcontainerd.Spec, error) {
<add>func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) {
<ide> s := oci.DefaultSpec()
<ide>
<ide> linkedEnv, err := daemon.setupLinkedContainers(c)
<ide> func (daemon *Daemon) createSpec(c *container.Container) (*libcontainerd.Spec, e
<ide> return nil, err
<ide> }
<ide> for _, mount := range mounts {
<del> m := windowsoci.Mount{
<add> m := specs.Mount{
<ide> Source: mount.Source,
<ide> Destination: mount.Destination,
<ide> }
<ide> func (daemon *Daemon) createSpec(c *container.Container) (*libcontainerd.Spec, e
<ide>
<ide> // In s.Windows.Resources
<ide> // @darrenstahlmsft implement these resources
<del> cpuShares := uint64(c.HostConfig.CPUShares)
<del> s.Windows.Resources = &windowsoci.WindowsResources{
<del> CPU: &windowsoci.WindowsCPU{
<del> Percent: &c.HostConfig.CPUPercent,
<add> cpuShares := uint16(c.HostConfig.CPUShares)
<add> cpuPercent := uint8(c.HostConfig.CPUPercent)
<add> memoryLimit := uint64(c.HostConfig.Memory)
<add> s.Windows.Resources = &specs.WindowsResources{
<add> CPU: &specs.WindowsCPUResources{
<add> Percent: &cpuPercent,
<ide> Shares: &cpuShares,
<ide> },
<del> Memory: &windowsoci.WindowsMemory{
<del> Limit: &c.HostConfig.Memory,
<add> Memory: &specs.WindowsMemoryResources{
<add> Limit: &memoryLimit,
<ide> //TODO Reservation: ...,
<ide> },
<del> Network: &windowsoci.WindowsNetwork{
<add> Network: &specs.WindowsNetworkResources{
<ide> //TODO Bandwidth: ...,
<ide> },
<del> Storage: &windowsoci.WindowsStorage{
<add> Storage: &specs.WindowsStorageResources{
<ide> Bps: &c.HostConfig.IOMaximumBandwidth,
<ide> Iops: &c.HostConfig.IOMaximumIOps,
<ide> },
<ide> }
<del> return (*libcontainerd.Spec)(&s), nil
<add> return (*specs.Spec)(&s), nil
<ide> }
<ide>
<ide> func escapeArgs(args []string) []string {
<ide><path>daemon/volumes_windows.go
<ide> import (
<ide> // It also ensures each of the mounts are lexographically sorted.
<ide>
<ide> // BUGBUG TODO Windows containerd. This would be much better if it returned
<del>// an array of windowsoci mounts, not container mounts. Then no need to
<add>// an array of runtime spec mounts, not container mounts. Then no need to
<ide> // do multiple transitions.
<ide>
<ide> func (daemon *Daemon) setupMounts(c *container.Container) ([]container.Mount, error) {
<ide><path>libcontainerd/client_linux.go
<ide> func (clnt *client) prepareBundleDir(uid, gid int) (string, error) {
<ide> return p, nil
<ide> }
<ide>
<del>func (clnt *client) Create(containerID string, checkpoint string, checkpointDir string, spec Spec, options ...CreateOption) (err error) {
<add>func (clnt *client) Create(containerID string, checkpoint string, checkpointDir string, spec specs.Spec, options ...CreateOption) (err error) {
<ide> clnt.lock(containerID)
<ide> defer clnt.unlock(containerID)
<ide>
<ide><path>libcontainerd/client_windows.go
<ide> import (
<ide>
<ide> "github.com/Microsoft/hcsshim"
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<ide> type client struct {
<ide> const defaultOwner = "docker"
<ide> // },
<ide> // "Servicing": false
<ide> //}
<del>func (clnt *client) Create(containerID string, checkpoint string, checkpointDir string, spec Spec, options ...CreateOption) error {
<add>func (clnt *client) Create(containerID string, checkpoint string, checkpointDir string, spec specs.Spec, options ...CreateOption) error {
<ide> clnt.lock(containerID)
<ide> defer clnt.unlock(containerID)
<ide> logrus.Debugln("libcontainerd: client.Create() with spec", spec)
<ide> func (clnt *client) Create(containerID string, checkpoint string, checkpointDir
<ide> if spec.Windows.Resources != nil {
<ide> if spec.Windows.Resources.CPU != nil {
<ide> if spec.Windows.Resources.CPU.Shares != nil {
<del> configuration.ProcessorWeight = *spec.Windows.Resources.CPU.Shares
<add> configuration.ProcessorWeight = uint64(*spec.Windows.Resources.CPU.Shares)
<ide> }
<ide> if spec.Windows.Resources.CPU.Percent != nil {
<del> configuration.ProcessorMaximum = *spec.Windows.Resources.CPU.Percent * 100 // ProcessorMaximum is a value between 1 and 10000
<add> configuration.ProcessorMaximum = int64(*spec.Windows.Resources.CPU.Percent * 100) // ProcessorMaximum is a value between 1 and 10000
<ide> }
<ide> }
<ide> if spec.Windows.Resources.Memory != nil {
<ide> if spec.Windows.Resources.Memory.Limit != nil {
<del> configuration.MemoryMaximumInMB = *spec.Windows.Resources.Memory.Limit / 1024 / 1024
<add> configuration.MemoryMaximumInMB = int64(*spec.Windows.Resources.Memory.Limit / 1024 / 1024)
<ide> }
<ide> }
<ide> if spec.Windows.Resources.Storage != nil {
<ide><path>libcontainerd/container_windows.go
<ide> import (
<ide>
<ide> "github.com/Microsoft/hcsshim"
<ide> "github.com/Sirupsen/logrus"
<add> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<ide> type container struct {
<ide> type container struct {
<ide> // The ociSpec is required, as client.Create() needs a spec,
<ide> // but can be called from the RestartManager context which does not
<ide> // otherwise have access to the Spec
<del> ociSpec Spec
<add> ociSpec specs.Spec
<ide>
<ide> manualStopRequested bool
<ide> hcsContainer hcsshim.Container
<ide><path>libcontainerd/types.go
<ide> package libcontainerd
<ide> import (
<ide> "io"
<ide>
<add> "github.com/opencontainers/runtime-spec/specs-go"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> type Backend interface {
<ide>
<ide> // Client provides access to containerd features.
<ide> type Client interface {
<del> Create(containerID string, checkpoint string, checkpointDir string, spec Spec, options ...CreateOption) error
<add> Create(containerID string, checkpoint string, checkpointDir string, spec specs.Spec, options ...CreateOption) error
<ide> Signal(containerID string, sig int) error
<ide> SignalProcess(containerID string, processFriendlyName string, sig int) error
<ide> AddProcess(ctx context.Context, containerID, processFriendlyName string, process Process) error
<ide><path>libcontainerd/types_linux.go
<ide> import (
<ide> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<del>// Spec is the base configuration for the container. It specifies platform
<del>// independent configuration. This information must be included when the
<del>// bundle is packaged for distribution.
<del>type Spec specs.Spec
<del>
<ide> // Process contains information to start a specific application inside the container.
<ide> type Process struct {
<ide> // Terminal creates an interactive terminal for the container.
<ide> Terminal bool `json:"terminal"`
<ide> // User specifies user information for the process.
<del> User *User `json:"user"`
<add> User *specs.User `json:"user"`
<ide> // Args specifies the binary and arguments for the application to execute.
<ide> Args []string `json:"args"`
<ide> // Env populates the process environment for the process.
<ide> type Stats containerd.StatsResponse
<ide> // Summary contains a container summary from containerd
<ide> type Summary struct{}
<ide>
<del>// User specifies linux specific user and group information for the container's
<del>// main process.
<del>type User specs.User
<del>
<ide> // Resources defines updatable container resource values.
<ide> type Resources containerd.UpdateResource
<ide>
<ide><path>libcontainerd/types_solaris.go
<ide> package libcontainerd
<ide>
<del>import (
<del> "github.com/opencontainers/runtime-spec/specs-go"
<del>)
<del>
<del>// Spec is the base configuration for the container. It specifies platform
<del>// independent configuration. This information must be included when the
<del>// bundle is packaged for distribution.
<del>type Spec specs.Spec
<del>
<ide> // Process contains information to start a specific application inside the container.
<ide> type Process struct {
<ide> // Terminal creates an interactive terminal for the container.
<ide> type StateInfo struct {
<ide> // Platform specific StateInfo
<ide> }
<ide>
<del>// User specifies Solaris specific user and group information for the container's
<del>// main process.
<del>type User specs.User
<del>
<ide> // Resources defines updatable container resource values.
<ide> type Resources struct{}
<ide><path>libcontainerd/types_windows.go
<ide> package libcontainerd
<ide>
<ide> import (
<ide> "github.com/Microsoft/hcsshim"
<del> "github.com/docker/docker/libcontainerd/windowsoci"
<add> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<del>// Spec is the base configuration for the container.
<del>type Spec windowsoci.Spec
<del>
<ide> // Process contains information to start a specific application inside the container.
<del>type Process windowsoci.Process
<del>
<del>// User specifies user information for the containers main process.
<del>type User windowsoci.User
<add>type Process specs.Process
<ide>
<ide> // Summary contains a ProcessList item from HCS to support `top`
<ide> type Summary hcsshim.ProcessListItem
<ide><path>libcontainerd/windowsoci/oci_windows.go
<del>package windowsoci
<del>
<del>// This file contains the Windows spec for a container. At the time of
<del>// writing, Windows does not have a spec defined in opencontainers/specs,
<del>// hence this is an interim workaround. TODO Windows: FIXME @jhowardmsft
<del>
<del>import "fmt"
<del>
<del>// Spec is the base configuration for the container.
<del>type Spec struct {
<del> // Version of the Open Container Runtime Specification with which the bundle complies.
<del> Version string `json:"ociVersion"`
<del> // Platform specifies the configuration's target platform.
<del> Platform Platform `json:"platform"`
<del> // Process configures the container process.
<del> Process Process `json:"process"`
<del> // Root configures the container's root filesystem.
<del> Root Root `json:"root"`
<del> // Hostname configures the container's hostname.
<del> Hostname string `json:"hostname,omitempty"`
<del> // Mounts configures additional mounts (on top of Root).
<del> Mounts []Mount `json:"mounts,omitempty"`
<del> // Hooks configures callbacks for container lifecycle events.
<del> Hooks Hooks `json:"hooks"`
<del> // Annotations contains arbitrary metadata for the container.
<del> Annotations map[string]string `json:"annotations,omitempty"`
<del>
<del> // Linux is platform specific configuration for Linux based containers.
<del> Linux *Linux `json:"linux,omitempty" platform:"linux"`
<del> // Solaris is platform specific configuration for Solaris containers.
<del> Solaris *Solaris `json:"solaris,omitempty" platform:"solaris"`
<del> // Windows is platform specific configuration for Windows based containers, including Hyper-V containers.
<del> Windows *Windows `json:"windows,omitempty" platform:"windows"`
<del>}
<del>
<del>// Windows contains platform specific configuration for Windows based containers.
<del>type Windows struct {
<del> // Resources contains information for handling resource constraints for the container
<del> Resources *WindowsResources `json:"resources,omitempty"`
<del>}
<del>
<del>// Process contains information to start a specific application inside the container.
<del>type Process struct {
<del> // Terminal creates an interactive terminal for the container.
<del> Terminal bool `json:"terminal,omitempty"`
<del> // User specifies user information for the process.
<del> User User `json:"user"`
<del> // Args specifies the binary and arguments for the application to execute.
<del> Args []string `json:"args"`
<del> // Env populates the process environment for the process.
<del> Env []string `json:"env,omitempty"`
<del> // Cwd is the current working directory for the process and must be
<del> // relative to the container's root.
<del> Cwd string `json:"cwd"`
<del> // Capabilities are Linux capabilities that are kept for the container.
<del> Capabilities []string `json:"capabilities,omitempty" platform:"linux"`
<del> // Rlimits specifies rlimit options to apply to the process.
<del> Rlimits []Rlimit `json:"rlimits,omitempty" platform:"linux"`
<del> // NoNewPrivileges controls whether additional privileges could be gained by processes in the container.
<del> NoNewPrivileges bool `json:"noNewPrivileges,omitempty" platform:"linux"`
<del> // ApparmorProfile specifies the apparmor profile for the container.
<del> ApparmorProfile string `json:"apparmorProfile,omitempty" platform:"linux"`
<del> // SelinuxLabel specifies the selinux context that the container process is run as.
<del> SelinuxLabel string `json:"selinuxLabel,omitempty" platform:"linux"`
<del> // ConsoleSize contains the initial size of the console.
<del> ConsoleSize Box `json:"consoleSize" platform:"windows"`
<del>}
<del>
<del>// Box specifies height and width dimensions. Used for sizing of a console.
<del>type Box struct {
<del> Height uint
<del> Width uint
<del>}
<del>
<del>// User specifies specific user (and group) information for the container process.
<del>type User struct {
<del> // UID is the user id.
<del> UID uint32 `json:"uid" platform:"linux,solaris"`
<del> // GID is the group id.
<del> GID uint32 `json:"gid" platform:"linux,solaris"`
<del> // AdditionalGids are additional group ids set for the container's process.
<del> AdditionalGids []uint32 `json:"additionalGids,omitempty" platform:"linux,solaris"`
<del> // Username is the user name.
<del> Username string `json:"username,omitempty" platform:"windows"`
<del>}
<del>
<del>// Root contains information about the container's root filesystem on the host.
<del>type Root struct {
<del> // Path is the absolute path to the container's root filesystem.
<del> Path string `json:"path"`
<del> // Readonly makes the root filesystem for the container readonly before the process is executed.
<del> Readonly bool `json:"readonly"`
<del>}
<del>
<del>// Platform specifies OS and arch information for the host system that the container
<del>// is created for.
<del>type Platform struct {
<del> // OS is the operating system.
<del> OS string `json:"os"`
<del> // Arch is the architecture
<del> Arch string `json:"arch"`
<del>}
<del>
<del>// Mount specifies a mount for a container.
<del>type Mount struct {
<del> // Destination is the path where the mount will be placed relative to the container's root. The path and child directories MUST exist, a runtime MUST NOT create directories automatically to a mount point.
<del> Destination string `json:"destination"`
<del> // Type specifies the mount kind.
<del> Type string `json:"type"`
<del> // Source specifies the source path of the mount. In the case of bind mounts on
<del> // Linux based systems this would be the file on the host.
<del> Source string `json:"source"`
<del> // Options are fstab style mount options.
<del> Options []string `json:"options,omitempty"`
<del>}
<del>
<del>// WindowsStorage contains storage resource management settings
<del>type WindowsStorage struct {
<del> // Specifies maximum Iops for the system drive
<del> Iops *uint64 `json:"iops,omitempty"`
<del> // Specifies maximum bytes per second for the system drive
<del> Bps *uint64 `json:"bps,omitempty"`
<del> // Sandbox size indicates the size to expand the system drive to if it is currently smaller
<del> SandboxSize *uint64 `json:"sandbox_size,omitempty"`
<del>}
<del>
<del>// WindowsMemory contains memory settings for the container
<del>type WindowsMemory struct {
<del> // Memory limit (in bytes).
<del> Limit *int64 `json:"limit,omitempty"`
<del> // Memory reservation (in bytes).
<del> Reservation *uint64 `json:"reservation,omitempty"`
<del>}
<del>
<del>// WindowsCPU contains information for cpu resource management
<del>type WindowsCPU struct {
<del> // Number of CPUs available to the container. This is an appoximation for Windows Server Containers.
<del> Count *uint64 `json:"count,omitempty"`
<del> // CPU shares (relative weight (ratio) vs. other containers with cpu shares). Range is from 1 to 10000.
<del> Shares *uint64 `json:"shares,omitempty"`
<del> // Percent of available CPUs usable by the container.
<del> Percent *int64 `json:"percent,omitempty"`
<del>}
<del>
<del>// WindowsNetwork contains network resource management information
<del>type WindowsNetwork struct {
<del> // Bandwidth is the maximum egress bandwidth in bytes per second
<del> Bandwidth *uint64 `json:"bandwidth,omitempty"`
<del>}
<del>
<del>// WindowsResources has container runtime resource constraints
<del>// TODO Windows containerd. This structure needs ratifying with the old resources
<del>// structure used on Windows and the latest OCI spec.
<del>type WindowsResources struct {
<del> // Memory restriction configuration
<del> Memory *WindowsMemory `json:"memory,omitempty"`
<del> // CPU resource restriction configuration
<del> CPU *WindowsCPU `json:"cpu,omitempty"`
<del> // Storage restriction configuration
<del> Storage *WindowsStorage `json:"storage,omitempty"`
<del> // Network restriction configuration
<del> Network *WindowsNetwork `json:"network,omitempty"`
<del>}
<del>
<del>const (
<del> // VersionMajor is for an API incompatible changes
<del> VersionMajor = 0
<del> // VersionMinor is for functionality in a backwards-compatible manner
<del> VersionMinor = 3
<del> // VersionPatch is for backwards-compatible bug fixes
<del> VersionPatch = 0
<del>
<del> // VersionDev indicates development branch. Releases will be empty string.
<del> VersionDev = ""
<del>)
<del>
<del>// Version is the specification version that the package types support.
<del>var Version = fmt.Sprintf("%d.%d.%d%s (Windows)", VersionMajor, VersionMinor, VersionPatch, VersionDev)
<del>
<del>//
<del>// Temporary structures. Ultimately this whole file will be removed.
<del>//
<del>
<del>// Linux contains platform specific configuration for Linux based containers.
<del>type Linux struct {
<del>}
<del>
<del>// Solaris contains platform specific configuration for Solaris application containers.
<del>type Solaris struct {
<del>}
<del>
<del>// Hooks for container setup and teardown
<del>type Hooks struct {
<del>}
<del>
<del>// Rlimit type and restrictions. Placeholder only to support the Process structure.
<del>// Not used on Windows, only present for compilation purposes.
<del>type Rlimit struct {
<del>}
<ide><path>libcontainerd/windowsoci/unsupported.go
<del>// +build !windows
<del>
<del>package windowsoci
<ide><path>oci/defaults_linux.go
<ide> func DefaultSpec() specs.Spec {
<ide> "CAP_AUDIT_WRITE",
<ide> }
<ide>
<del> s.Linux = specs.Linux{
<add> s.Linux = &specs.Linux{
<ide> MaskedPaths: []string{
<ide> "/proc/kcore",
<ide> "/proc/latency_stats",
<ide><path>oci/defaults_windows.go
<ide> package oci
<ide> import (
<ide> "runtime"
<ide>
<del> "github.com/docker/docker/libcontainerd/windowsoci"
<add> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<ide> // DefaultSpec returns default spec used by docker.
<del>func DefaultSpec() windowsoci.Spec {
<del> return windowsoci.Spec{
<del> Version: windowsoci.Version,
<del> Platform: windowsoci.Platform{
<add>func DefaultSpec() specs.Spec {
<add> return specs.Spec{
<add> Version: specs.Version,
<add> Platform: specs.Platform{
<ide> OS: runtime.GOOS,
<ide> Arch: runtime.GOARCH,
<ide> },
<del> Windows: &windowsoci.Windows{},
<add> Windows: &specs.Windows{},
<ide> }
<ide> }
<ide><path>plugin/manager_linux.go
<ide> import (
<ide> "github.com/docker/docker/pkg/plugins"
<ide> "github.com/docker/docker/plugin/v2"
<ide> "github.com/docker/docker/restartmanager"
<add> "github.com/opencontainers/runtime-spec/specs-go"
<ide> )
<ide>
<ide> func (pm *Manager) enable(p *v2.Plugin, force bool) error {
<ide> func (pm *Manager) enable(p *v2.Plugin, force bool) error {
<ide> }
<ide>
<ide> p.RestartManager = restartmanager.New(container.RestartPolicy{Name: "always"}, 0)
<del> if err := pm.containerdClient.Create(p.GetID(), "", "", libcontainerd.Spec(*spec), libcontainerd.WithRestartManager(p.RestartManager)); err != nil {
<add> if err := pm.containerdClient.Create(p.GetID(), "", "", specs.Spec(*spec), libcontainerd.WithRestartManager(p.RestartManager)); err != nil {
<ide> if err := p.RestartManager.Cancel(); err != nil {
<ide> logrus.Errorf("enable: restartManager.Cancel failed due to %v", err)
<ide> } | 17 |
Javascript | Javascript | remove var in rntester | 5af577439b9c58ab3891bc651fb5ca71a68df841 | <ide><path>RNTester/js/VibrationExample.js
<ide>
<ide> 'use strict';
<ide>
<del>var React = require('react');
<del>var ReactNative = require('react-native');
<del>var {
<add>const React = require('react');
<add>const ReactNative = require('react-native');
<add>const {
<ide> StyleSheet,
<ide> View,
<ide> Text,
<ide> exports.framework = 'React';
<ide> exports.title = 'Vibration';
<ide> exports.description = 'Vibration API';
<ide>
<del>var pattern, patternLiteral, patternDescription;
<add>let pattern, patternLiteral, patternDescription;
<ide> if (Platform.OS === 'android') {
<ide> pattern = [0, 500, 200, 500];
<ide> patternLiteral = '[0, 500, 200, 500]';
<ide> exports.examples = [
<ide> },
<ide> ];
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> wrapper: {
<ide> borderRadius: 5,
<ide> marginBottom: 5,
<ide><path>RNTester/js/ViewPagerAndroidExample.android.js
<ide>
<ide> 'use strict';
<ide>
<del>var React = require('react');
<del>var ReactNative = require('react-native');
<del>var {
<add>const React = require('react');
<add>const ReactNative = require('react-native');
<add>const {
<ide> Image,
<ide> StyleSheet,
<ide> Text,
<ide> var {
<ide>
<ide> import type {ViewPagerScrollState} from 'ViewPagerAndroid';
<ide>
<del>var PAGES = 5;
<del>var BGCOLOR = ['#fdc08e', '#fff6b9', '#99d1b7', '#dde5fe', '#f79273'];
<del>var IMAGE_URIS = [
<add>const PAGES = 5;
<add>const BGCOLOR = ['#fdc08e', '#fff6b9', '#99d1b7', '#dde5fe', '#f79273'];
<add>const IMAGE_URIS = [
<ide> 'https://apod.nasa.gov/apod/image/1410/20141008tleBaldridge001h990.jpg',
<ide> 'https://apod.nasa.gov/apod/image/1409/volcanicpillar_vetter_960.jpg',
<ide> 'https://apod.nasa.gov/apod/image/1409/m27_snyder_960.jpg',
<ide> class LikeCount extends React.Component {
<ide> };
<ide>
<ide> render() {
<del> var thumbsUp = '\uD83D\uDC4D';
<add> const thumbsUp = '\uD83D\uDC4D';
<ide> return (
<ide> <View style={styles.likeContainer}>
<ide> <TouchableOpacity onPress={this.onClick} style={styles.likeButton}>
<ide> class Button extends React.Component {
<ide>
<ide> class ProgressBar extends React.Component {
<ide> render() {
<del> var fractionalPosition =
<add> const fractionalPosition =
<ide> this.props.progress.position + this.props.progress.offset;
<del> var progressBarSize = (fractionalPosition / (PAGES - 1)) * this.props.size;
<add> const progressBarSize =
<add> (fractionalPosition / (PAGES - 1)) * this.props.size;
<ide> return (
<ide> <View style={[styles.progressBarContainer, {width: this.props.size}]}>
<ide> <View style={[styles.progressBar, {width: progressBarSize}]} />
<ide> class ViewPagerAndroidExample extends React.Component {
<ide> };
<ide>
<ide> move = delta => {
<del> var page = this.state.page + delta;
<add> const page = this.state.page + delta;
<ide> this.go(page);
<ide> };
<ide>
<ide> class ViewPagerAndroidExample extends React.Component {
<ide> };
<ide>
<ide> render() {
<del> var pages = [];
<del> for (var i = 0; i < PAGES; i++) {
<del> var pageStyle = {
<add> const pages = [];
<add> for (let i = 0; i < PAGES; i++) {
<add> const pageStyle = {
<ide> backgroundColor: BGCOLOR[i % BGCOLOR.length],
<ide> alignItems: 'center',
<ide> padding: 20,
<ide> class ViewPagerAndroidExample extends React.Component {
<ide> </View>,
<ide> );
<ide> }
<del> var {page, animationsAreEnabled} = this.state;
<add> const {page, animationsAreEnabled} = this.state;
<ide> return (
<ide> <View style={styles.container}>
<ide> <ViewPagerAndroid
<ide> class ViewPagerAndroidExample extends React.Component {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> buttons: {
<ide> flexDirection: 'row',
<ide> height: 30,
<ide><path>RNTester/js/WebViewExample.js
<ide>
<ide> 'use strict';
<ide>
<del>var React = require('react');
<del>var ReactNative = require('react-native');
<del>var {
<add>const React = require('react');
<add>const ReactNative = require('react-native');
<add>const {
<ide> StyleSheet,
<ide> Text,
<ide> TextInput,
<ide> var {
<ide> WebView,
<ide> } = ReactNative;
<ide>
<del>var HEADER = '#3b5998';
<del>var BGWASH = 'rgba(255,255,255,0.8)';
<del>var DISABLED_WASH = 'rgba(255,255,255,0.25)';
<add>const HEADER = '#3b5998';
<add>const BGWASH = 'rgba(255,255,255,0.8)';
<add>const DISABLED_WASH = 'rgba(255,255,255,0.25)';
<ide>
<del>var TEXT_INPUT_REF = 'urlInput';
<del>var WEBVIEW_REF = 'webview';
<del>var DEFAULT_URL = 'https://m.facebook.com';
<add>const TEXT_INPUT_REF = 'urlInput';
<add>const WEBVIEW_REF = 'webview';
<add>const DEFAULT_URL = 'https://m.facebook.com';
<ide> const FILE_SYSTEM_ORIGIN_WHITE_LIST = ['file://*', 'http://*', 'https://*'];
<ide>
<ide> class WebViewExample extends React.Component<{}, $FlowFixMeState> {
<ide> class WebViewExample extends React.Component<{}, $FlowFixMeState> {
<ide> inputText = '';
<ide>
<ide> handleTextInputChange = event => {
<del> var url = event.nativeEvent.text;
<add> let url = event.nativeEvent.text;
<ide> if (!/^[a-zA-Z-_]+:/.test(url)) {
<ide> url = 'http://' + url;
<ide> }
<ide> class WebViewExample extends React.Component<{}, $FlowFixMeState> {
<ide> };
<ide>
<ide> pressGoButton = () => {
<del> var url = this.inputText.toLowerCase();
<add> const url = this.inputText.toLowerCase();
<ide> if (url === this.state.url) {
<ide> this.reload();
<ide> } else {
<ide> class InjectJS extends React.Component<{}> {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> container: {
<ide> flex: 1,
<ide> backgroundColor: HEADER,
<ide><path>RNTester/js/XHRExample.js
<ide>
<ide> 'use strict';
<ide>
<del>var React = require('react');
<add>const React = require('react');
<ide>
<del>var XHRExampleDownload = require('./XHRExampleDownload');
<del>var XHRExampleBinaryUpload = require('./XHRExampleBinaryUpload');
<del>var XHRExampleFormData = require('./XHRExampleFormData');
<del>var XHRExampleHeaders = require('./XHRExampleHeaders');
<del>var XHRExampleFetch = require('./XHRExampleFetch');
<del>var XHRExampleOnTimeOut = require('./XHRExampleOnTimeOut');
<del>var XHRExampleCookies = require('./XHRExampleCookies');
<add>const XHRExampleDownload = require('./XHRExampleDownload');
<add>const XHRExampleBinaryUpload = require('./XHRExampleBinaryUpload');
<add>const XHRExampleFormData = require('./XHRExampleFormData');
<add>const XHRExampleHeaders = require('./XHRExampleHeaders');
<add>const XHRExampleFetch = require('./XHRExampleFetch');
<add>const XHRExampleOnTimeOut = require('./XHRExampleOnTimeOut');
<add>const XHRExampleCookies = require('./XHRExampleCookies');
<ide>
<ide> exports.framework = 'React';
<ide> exports.title = 'XMLHttpRequest';
<ide><path>RNTester/js/XHRExampleBinaryUpload.js
<ide> class XHRExampleBinaryUpload extends React.Component<{}, $FlowFixMeState> {
<ide> Alert.alert('Upload failed', 'No response payload.');
<ide> return;
<ide> }
<del> var index = xhr.responseText.indexOf('http://www.posttestserver.com/');
<add> const index = xhr.responseText.indexOf('http://www.posttestserver.com/');
<ide> if (index === -1) {
<ide> Alert.alert('Upload failed', 'Invalid response payload.');
<ide> return;
<ide> }
<del> var url = xhr.responseText.slice(index).split('\n')[0];
<add> const url = xhr.responseText.slice(index).split('\n')[0];
<ide> console.log('Upload successful: ' + url);
<ide> Linking.openURL(url);
<ide> }
<ide> class XHRExampleBinaryUpload extends React.Component<{}, $FlowFixMeState> {
<ide> };
<ide>
<ide> _upload = () => {
<del> var xhr = new XMLHttpRequest();
<add> const xhr = new XMLHttpRequest();
<ide> xhr.open('POST', 'http://posttestserver.com/post.php');
<ide> xhr.onload = () => XHRExampleBinaryUpload.handlePostTestServerUpload(xhr);
<ide> xhr.setRequestHeader('Content-Type', 'text/plain');
<ide><path>RNTester/js/XHRExampleCookies.js
<ide>
<ide> 'use strict';
<ide>
<del>var React = require('react');
<del>var ReactNative = require('react-native');
<del>var {StyleSheet, Text, TouchableHighlight, View, WebView} = ReactNative;
<add>const React = require('react');
<add>const ReactNative = require('react-native');
<add>const {StyleSheet, Text, TouchableHighlight, View, WebView} = ReactNative;
<ide>
<del>var RCTNetworking = require('RCTNetworking');
<add>const RCTNetworking = require('RCTNetworking');
<ide>
<ide> class XHRExampleCookies extends React.Component<any, any> {
<ide> cancelled: boolean;
<ide> class XHRExampleCookies extends React.Component<any, any> {
<ide> }
<ide>
<ide> setCookie(domain: string) {
<del> var {a, b} = this.state;
<del> var url = `https://${domain}/cookies/set?a=${a}&b=${b}`;
<add> const {a, b} = this.state;
<add> const url = `https://${domain}/cookies/set?a=${a}&b=${b}`;
<ide> fetch(url).then(response => {
<ide> this.setStatus(`Cookies a=${a}, b=${b} set`);
<ide> this.refreshWebview();
<ide> class XHRExampleCookies extends React.Component<any, any> {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> wrapper: {
<ide> borderRadius: 5,
<ide> marginBottom: 5,
<ide><path>RNTester/js/XHRExampleFetch.js
<ide>
<ide> 'use strict';
<ide>
<del>var React = require('react');
<del>var ReactNative = require('react-native');
<del>var {StyleSheet, Text, TextInput, View, Platform} = ReactNative;
<add>const React = require('react');
<add>const ReactNative = require('react-native');
<add>const {StyleSheet, Text, TextInput, View, Platform} = ReactNative;
<ide>
<ide> class XHRExampleFetch extends React.Component<any, any> {
<ide> responseURL: ?string;
<ide> class XHRExampleFetch extends React.Component<any, any> {
<ide> return null;
<ide> }
<ide>
<del> var responseHeaders = [];
<del> var keys = Object.keys(this.responseHeaders.map);
<del> for (var i = 0; i < keys.length; i++) {
<del> var key = keys[i];
<del> var value = this.responseHeaders.get(key);
<add> const responseHeaders = [];
<add> const keys = Object.keys(this.responseHeaders.map);
<add> for (let i = 0; i < keys.length; i++) {
<add> const key = keys[i];
<add> const value = this.responseHeaders.get(key);
<ide> responseHeaders.push(
<ide> <Text>
<ide> {key}: {value}
<ide> class XHRExampleFetch extends React.Component<any, any> {
<ide> }
<ide>
<ide> render() {
<del> var responseURL = this.responseURL ? (
<add> const responseURL = this.responseURL ? (
<ide> <View style={{marginTop: 10}}>
<ide> <Text style={styles.label}>Server response URL:</Text>
<ide> <Text>{this.responseURL}</Text>
<ide> </View>
<ide> ) : null;
<ide>
<del> var responseHeaders = this.responseHeaders ? (
<add> const responseHeaders = this.responseHeaders ? (
<ide> <View style={{marginTop: 10}}>
<ide> <Text style={styles.label}>Server response headers:</Text>
<ide> {this._renderHeaders()}
<ide> </View>
<ide> ) : null;
<ide>
<del> var response = this.state.responseText ? (
<add> const response = this.state.responseText ? (
<ide> <View style={{marginTop: 10}}>
<ide> <Text style={styles.label}>Server response:</Text>
<ide> <TextInput
<ide> class XHRExampleFetch extends React.Component<any, any> {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> textInput: {
<ide> flex: 1,
<ide> borderRadius: 3,
<ide><path>RNTester/js/XHRExampleFormData.js
<ide> class XHRExampleFormData extends React.Component<Object, Object> {
<ide> if (!this._isMounted) {
<ide> return;
<ide> }
<del> var edges = data.edges;
<del> var edge = edges[Math.floor(Math.random() * edges.length)];
<del> var randomPhoto = edge && edge.node && edge.node.image;
<add> const edges = data.edges;
<add> const edge = edges[Math.floor(Math.random() * edges.length)];
<add> const randomPhoto = edge && edge.node && edge.node.image;
<ide> if (randomPhoto) {
<ide> let {width, height} = randomPhoto;
<ide> width *= 0.25;
<ide> class XHRExampleFormData extends React.Component<Object, Object> {
<ide> };
<ide>
<ide> _addTextParam = () => {
<del> var textParams = this.state.textParams;
<add> const textParams = this.state.textParams;
<ide> textParams.push({name: '', value: ''});
<ide> this.setState({textParams});
<ide> };
<ide>
<ide> _onTextParamNameChange(index, text) {
<del> var textParams = this.state.textParams;
<add> const textParams = this.state.textParams;
<ide> textParams[index].name = text;
<ide> this.setState({textParams});
<ide> }
<ide>
<ide> _onTextParamValueChange(index, text) {
<del> var textParams = this.state.textParams;
<add> const textParams = this.state.textParams;
<ide> textParams[index].value = text;
<ide> this.setState({textParams});
<ide> }
<ide>
<ide> _upload = () => {
<del> var xhr = new XMLHttpRequest();
<add> const xhr = new XMLHttpRequest();
<ide> xhr.open('POST', 'http://posttestserver.com/post.php');
<ide> xhr.onload = () => {
<ide> this.setState({isUploading: false});
<ide> XHRExampleBinaryUpload.handlePostTestServerUpload(xhr);
<ide> };
<del> var formdata = new FormData();
<add> const formdata = new FormData();
<ide> if (this.state.randomPhoto) {
<ide> formdata.append('image', {
<ide> ...this.state.randomPhoto,
<ide> class XHRExampleFormData extends React.Component<Object, Object> {
<ide> };
<ide>
<ide> render() {
<del> var image = null;
<add> let image = null;
<ide> if (this.state.randomPhoto) {
<ide> image = (
<ide> <Image source={this.state.randomPhoto} style={styles.randomPhoto} />
<ide> );
<ide> }
<del> var textItems = this.state.textParams.map((item, index) => (
<add> const textItems = this.state.textParams.map((item, index) => (
<ide> <View style={styles.paramRow}>
<ide> <TextInput
<ide> autoCapitalize="none"
<ide> class XHRExampleFormData extends React.Component<Object, Object> {
<ide> />
<ide> </View>
<ide> ));
<del> var uploadButtonLabel = this.state.isUploading ? 'Uploading...' : 'Upload';
<del> var uploadProgress = this.state.uploadProgress;
<add> let uploadButtonLabel = this.state.isUploading ? 'Uploading...' : 'Upload';
<add> const uploadProgress = this.state.uploadProgress;
<ide> if (uploadProgress !== null) {
<ide> uploadButtonLabel += ' ' + Math.round(uploadProgress * 100) + '%';
<ide> }
<del> var uploadButton = (
<add> let uploadButton = (
<ide> <View style={styles.uploadButtonBox}>
<ide> <Text style={styles.uploadButtonLabel}>{uploadButtonLabel}</Text>
<ide> </View>
<ide><path>RNTester/js/XHRExampleHeaders.js
<ide>
<ide> 'use strict';
<ide>
<del>var React = require('react');
<del>var ReactNative = require('react-native');
<del>var {StyleSheet, Text, TouchableHighlight, View} = ReactNative;
<add>const React = require('react');
<add>const ReactNative = require('react-native');
<add>const {StyleSheet, Text, TouchableHighlight, View} = ReactNative;
<ide>
<ide> class XHRExampleHeaders extends React.Component {
<ide> xhr: XMLHttpRequest;
<ide> class XHRExampleHeaders extends React.Component {
<ide> download() {
<ide> this.xhr && this.xhr.abort();
<ide>
<del> var xhr = this.xhr || new XMLHttpRequest();
<add> const xhr = this.xhr || new XMLHttpRequest();
<ide> xhr.onreadystatechange = () => {
<ide> if (xhr.readyState === xhr.DONE) {
<ide> if (this.cancelled) {
<ide> class XHRExampleHeaders extends React.Component {
<ide> }
<ide>
<ide> render() {
<del> var button =
<add> const button =
<ide> this.state.status === 'Downloading...' ? (
<ide> <View style={styles.wrapper}>
<ide> <View style={styles.button}>
<ide> class XHRExampleHeaders extends React.Component {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> wrapper: {
<ide> borderRadius: 5,
<ide> marginBottom: 5,
<ide><path>RNTester/js/XHRExampleOnTimeOut.js
<ide>
<ide> 'use strict';
<ide>
<del>var React = require('react');
<del>var ReactNative = require('react-native');
<del>var {StyleSheet, Text, TouchableHighlight, View} = ReactNative;
<add>const React = require('react');
<add>const ReactNative = require('react-native');
<add>const {StyleSheet, Text, TouchableHighlight, View} = ReactNative;
<ide>
<ide> class XHRExampleOnTimeOut extends React.Component<any, any> {
<ide> xhr: XMLHttpRequest;
<ide> class XHRExampleOnTimeOut extends React.Component<any, any> {
<ide> loadTimeOutRequest() {
<ide> this.xhr && this.xhr.abort();
<ide>
<del> var xhr = this.xhr || new XMLHttpRequest();
<add> const xhr = this.xhr || new XMLHttpRequest();
<ide>
<ide> xhr.onerror = () => {
<ide> console.log('Status ', xhr.status);
<ide> class XHRExampleOnTimeOut extends React.Component<any, any> {
<ide> }
<ide>
<ide> render() {
<del> var button = this.state.loading ? (
<add> const button = this.state.loading ? (
<ide> <View style={styles.wrapper}>
<ide> <View style={styles.button}>
<ide> <Text>Loading...</Text>
<ide> class XHRExampleOnTimeOut extends React.Component<any, any> {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> wrapper: {
<ide> borderRadius: 5,
<ide> marginBottom: 5, | 10 |
Text | Text | fix typo in link in example's readme | c6ec289c55063b4e7a8eb0ad78df93660cbbefd7 | <ide><path>examples/with-jest-react-testing-library/README.md
<ide> yarn create next-app --example with-jest-react-testing-library with-rtl-app
<ide> Download the example:
<ide>
<ide> ```bash
<del>curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-jest
<add>curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-jest-react-testing-library
<ide> cd with-jest-react-testing-library
<ide> ```
<ide> | 1 |
Text | Text | add changelog for 0.70.1 | 2f94476c01ec5e14f4866e3380a36221e975231d | <ide><path>CHANGELOG.md
<ide> # Changelog
<ide>
<add>## v0.70.1
<add>
<add>### Added
<add>
<add>- Add more debugging settings for *HermesExecutorFactory* ([32d12e89f8](https://github.com/facebook/react-native/commit/32d12e89f864a106433c8e54c10691d7876333ee) by [@Kudo](https://github.com/Kudo))
<add>- Support TypeScript array types for turbo module (component only) ([33d1291e1a](https://github.com/facebook/react-native/commit/33d1291e1a96497a4f994e9d622248a745ee1ea6) by [@ZihanChen-MSFT](https://github.com/ZihanChen-MSFT))
<add>
<add>### Changed
<add>
<add>- Accept TypeScript type `T | null | undefined` as a maybe type of T in turbo module. ([9ecd203eec](https://github.com/facebook/react-native/commit/9ecd203eec97e7d21d10311d950c9f8f30c7a4b1) by [@ZihanChen-MSFT](https://github.com/ZihanChen-MSFT))
<add>- Bump react-native-gradle-plugin to 0.70.3 ([e33633644c](https://github.com/facebook/react-native/commit/e33633644c70ea39af6e450fcf31d9458051fd5f) by [@dmytrorykun](https://github.com/dmytrorykun))
<add>- Bump react-native-codegen to 0.70.5 ([6a8c38eef2](https://github.com/facebook/react-native/commit/6a8c38eef272e79e52a35941afa9c3fe9e8fc191) by [@dmytrorykun](https://github.com/dmytrorykun))
<add>- Hermes version bump for 0.70.1 ([5132211228](https://github.com/facebook/react-native/commit/5132211228a5b9e36d58c1f7e2c99ccaabe1ba3d) by [@dmytrorykun](https://github.com/dmytrorykun))
<add>
<add>### Fixed
<add>
<add>- Fix hermes profiler ([81564c1a3d](https://github.com/facebook/react-native/commit/81564c1a3dae4222858de2a9a34089097f665e82) by [@janicduplessis](https://github.com/janicduplessis))
<add>
<add>#### Android specific
<add>
<add>- Support PlatformColor in borderColor ([2d5db284b0](https://github.com/facebook/react-native/commit/2d5db284b061aec33af671b25065632e20217f62) by [@danilobuerger](https://github.com/danilobuerger))
<add>- Avoid crash in ForwardingCookieHandler if webview is disabled ([5451cd48bd](https://github.com/facebook/react-native/commit/5451cd48bd0166ba70d516e3a11c6786bc22171a) by [@Pajn](https://github.com/Pajn))
<add>- Correctly resolve classes with FindClass(..) ([361b310bcc](https://github.com/facebook/react-native/commit/361b310bcc8dddbff42cf63495649291c894d661) by [@evancharlton](https://github.com/evancharlton))
<add>
<add>#### iOS specific
<add>
<add>- Fix KeyboardAvoidingView height when "Prefer Cross-Fade Transitions" is enabled ([4b9382c250](https://github.com/facebook/react-native/commit/4b9382c250261aab89b271618f8b68083ba01785) by [@gabrieldonadel](https://github.com/gabrieldonadel))
<add>- Fix React module build error with swift integration on new architecture mode ([3afef3c167](https://github.com/facebook/react-native/commit/3afef3c16702cefa5115b059a08741fba255b2db) by [@Kudo](https://github.com/Kudo))
<add>- Fix ios pod install error ([0cae4959b7](https://github.com/facebook/react-native/commit/0cae4959b750ea051dcd04e4c9374e02b1de6e7a) by [@Romick2005](https://github.com/Romick2005))
<add>
<ide> ## 0.70.0
<ide>
<ide> ### Breaking | 1 |
Go | Go | fix data space reporting from kb/mb to kb/mb | a327d9b91edf6d36ee5b286ebe968bcca6658f5b | <ide><path>daemon/graphdriver/devmapper/driver.go
<ide> import (
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/pkg/mount"
<add> "github.com/docker/docker/pkg/units"
<ide> )
<ide>
<ide> func init() {
<ide> func (d *Driver) Status() [][2]string {
<ide>
<ide> status := [][2]string{
<ide> {"Pool Name", s.PoolName},
<del> {"Pool Blocksize", fmt.Sprintf("%d Kb", s.SectorSize/1024)},
<add> {"Pool Blocksize", fmt.Sprintf("%s", units.HumanSize(int64(s.SectorSize)))},
<ide> {"Data file", s.DataLoopback},
<ide> {"Metadata file", s.MetadataLoopback},
<del> {"Data Space Used", fmt.Sprintf("%.1f Mb", float64(s.Data.Used)/(1024*1024))},
<del> {"Data Space Total", fmt.Sprintf("%.1f Mb", float64(s.Data.Total)/(1024*1024))},
<del> {"Metadata Space Used", fmt.Sprintf("%.1f Mb", float64(s.Metadata.Used)/(1024*1024))},
<del> {"Metadata Space Total", fmt.Sprintf("%.1f Mb", float64(s.Metadata.Total)/(1024*1024))},
<add> {"Data Space Used", fmt.Sprintf("%s", units.HumanSize(int64(s.Data.Used)))},
<add> {"Data Space Total", fmt.Sprintf("%s", units.HumanSize(int64(s.Data.Total)))},
<add> {"Metadata Space Used", fmt.Sprintf("%s", units.HumanSize(int64(s.Metadata.Used)))},
<add> {"Metadata Space Total", fmt.Sprintf("%s", units.HumanSize(int64(s.Metadata.Total)))},
<ide> }
<ide> return status
<ide> } | 1 |
Javascript | Javascript | expose pendingrequests and configuration object | fdcc2dbfd37d14ca5f3c830b589c091611ab54bd | <ide><path>src/service/http.js
<ide> function transform(data, fns, param) {
<ide> * @requires $exceptionHandler
<ide> * @requires $cacheFactory
<ide> *
<add> * @property {Array.<XhrFuture>} pendingRequests Array of pending requests.
<add> *
<ide> * @description
<ide> */
<ide> function $HttpProvider() {
<ide> function $HttpProvider() {
<ide> this.$get = ['$httpBackend', '$browser', '$exceptionHandler', '$cacheFactory', '$rootScope',
<ide> function($httpBackend, $browser, $exceptionHandler, $cacheFactory, $rootScope) {
<ide>
<del> var cache = $cacheFactory('$http'),
<del> pendingRequestsCount = 0;
<add> var cache = $cacheFactory('$http');
<ide>
<ide> // the actual service
<ide> function $http(config) {
<ide> return new XhrFuture().retry(config);
<ide> }
<ide>
<del> /**
<del> * @workInProgress
<del> * @ngdoc method
<del> * @name angular.service.$http#pendingCount
<del> * @methodOf angular.service.$http
<del> *
<del> * @description
<del> * Return number of pending requests
<del> *
<del> * @returns {number} Number of pending requests
<del> */
<del> $http.pendingCount = function() {
<del> return pendingRequestsCount;
<del> };
<add> $http.pendingRequests = [];
<ide>
<ide> /**
<ide> * @ngdoc method
<ide> function $HttpProvider() {
<ide> /**
<ide> * Represents Request object, returned by $http()
<ide> *
<del> * !!! ACCESS CLOSURE VARS: $httpBackend, $browser, $config, $log, $rootScope, cache, pendingRequestsCount
<add> * !!! ACCESS CLOSURE VARS:
<add> * $httpBackend, $browser, $config, $log, $rootScope, cache, $http.pendingRequests
<ide> */
<ide> function XhrFuture() {
<del> var rawRequest, cfg = {}, callbacks = [],
<add> var rawRequest, parsedHeaders,
<add> cfg = {}, callbacks = [],
<ide> defHeaders = $config.headers,
<del> parsedHeaders;
<add> self = this;
<ide>
<ide> /**
<ide> * Callback registered to $httpBackend():
<ide> function $HttpProvider() {
<ide> response = transform(response, cfg.transformResponse || $config.transformResponse, rawRequest);
<ide>
<ide> var regexp = statusToRegexp(status),
<del> pattern, callback;
<add> pattern, callback, idx;
<ide>
<del> pendingRequestsCount--;
<add> // remove from pending requests
<add> if ((idx = indexOf($http.pendingRequests, self)) !== -1)
<add> $http.pendingRequests.splice(idx, 1);
<ide>
<ide> // normalize internal statuses to 0
<ide> status = Math.max(status, 0);
<ide> function $HttpProvider() {
<ide> rawRequest = $httpBackend(cfg.method, cfg.url, data, done, headers, cfg.timeout);
<ide> }
<ide>
<del> pendingRequestsCount++;
<add> $http.pendingRequests.push(self);
<ide> return this;
<ide> };
<ide>
<ide> function $HttpProvider() {
<ide>
<ide> return this;
<ide> };
<add>
<add> /**
<add> * Configuration object of the request
<add> */
<add> this.config = cfg;
<ide> }
<ide> }];
<ide> }
<ide><path>test/service/httpSpec.js
<ide> describe('$http', function() {
<ide> });
<ide>
<ide>
<del> describe('pendingCount', function() {
<add> describe('pendingRequests', function() {
<ide>
<del> it('should return number of pending requests', function() {
<add> it('should be an array of pending requests', function() {
<ide> $httpBackend.when('GET').then(200);
<del> expect($http.pendingCount()).toBe(0);
<add> expect($http.pendingRequests.length).toBe(0);
<ide>
<ide> $http({method: 'get', url: '/some'});
<del> expect($http.pendingCount()).toBe(1);
<add> expect($http.pendingRequests.length).toBe(1);
<ide>
<ide> $httpBackend.flush();
<del> expect($http.pendingCount()).toBe(0);
<add> expect($http.pendingRequests.length).toBe(0);
<ide> });
<ide>
<ide>
<del> it('should decrement the counter when request aborted', function() {
<add> it('should remove the request when aborted', function() {
<ide> $httpBackend.when('GET').then(0);
<ide> future = $http({method: 'get', url: '/x'});
<del> expect($http.pendingCount()).toBe(1);
<add> expect($http.pendingRequests.length).toBe(1);
<ide>
<ide> future.abort();
<ide> $httpBackend.flush();
<ide>
<del> expect($http.pendingCount()).toBe(0);
<add> expect($http.pendingRequests.length).toBe(0);
<ide> });
<ide>
<ide>
<del> it('should decrement the counter when served from cache', function() {
<add> it('should remove the request when served from cache', function() {
<ide> $httpBackend.when('GET').then(200);
<ide>
<ide> $http({method: 'get', url: '/cached', cache: true});
<ide> $httpBackend.flush();
<del> expect($http.pendingCount()).toBe(0);
<add> expect($http.pendingRequests.length).toBe(0);
<ide>
<ide> $http({method: 'get', url: '/cached', cache: true});
<del> expect($http.pendingCount()).toBe(1);
<add> expect($http.pendingRequests.length).toBe(1);
<ide>
<ide> $browser.defer.flush();
<del> expect($http.pendingCount()).toBe(0);
<add> expect($http.pendingRequests.length).toBe(0);
<ide> });
<ide>
<ide>
<del> it('should decrement the counter before firing callbacks', function() {
<add> it('should remove the request before firing callbacks', function() {
<ide> $httpBackend.when('GET').then(200);
<ide> $http({method: 'get', url: '/url'}).on('xxx', function() {
<del> expect($http.pendingCount()).toBe(0);
<add> expect($http.pendingRequests.length).toBe(0);
<ide> });
<ide>
<del> expect($http.pendingCount()).toBe(1);
<add> expect($http.pendingRequests.length).toBe(1);
<ide> $httpBackend.flush();
<ide> });
<ide> }); | 2 |
Javascript | Javascript | use push() for readable.wrap() | 530585b2d10eea72e71007cb5d8ab18149653c99 | <ide><path>lib/_stream_readable.js
<ide> Readable.prototype.wrap = function(stream) {
<ide> state.ended = true;
<ide> if (state.decoder) {
<ide> var chunk = state.decoder.end();
<del> if (chunk && chunk.length) {
<del> state.buffer.push(chunk);
<del> state.length += chunk.length;
<del> }
<add> if (chunk && chunk.length)
<add> self.push(chunk);
<ide> }
<ide>
<del> if (state.length > 0)
<del> self.emit('readable');
<del> else
<del> endReadable(self);
<add> self.push(null);
<ide> });
<ide>
<ide> stream.on('data', function(chunk) {
<ide> Readable.prototype.wrap = function(stream) {
<ide> if (!chunk || !chunk.length)
<ide> return;
<ide>
<del> state.buffer.push(chunk);
<del> state.length += chunk.length;
<del> self.emit('readable');
<del>
<del> // if not consumed, then pause the stream.
<del> if (state.length > state.lowWaterMark && !paused) {
<add> var ret = self.push(chunk);
<add> if (!ret) {
<ide> paused = true;
<ide> stream.pause();
<ide> }
<ide> Readable.prototype.wrap = function(stream) {
<ide> stream.on(ev, self.emit.bind(self, ev));
<ide> });
<ide>
<del> // consume some bytes. if not all is consumed, then
<del> // pause the underlying stream.
<del> this.read = function(n) {
<del> if (state.length === 0) {
<del> state.needReadable = true;
<del> return null;
<del> }
<del>
<del> if (isNaN(n) || n <= 0)
<del> n = state.length;
<del>
<del> if (n > state.length) {
<del> if (!state.ended) {
<del> state.needReadable = true;
<del> return null;
<del> } else
<del> n = state.length;
<del> }
<del>
<del> var ret = fromList(n, state.buffer, state.length, !!state.decoder);
<del> state.length -= n;
<del>
<del> if (state.length === 0 && !state.ended)
<del> state.needReadable = true;
<del>
<del> if (state.length <= state.lowWaterMark && paused) {
<add> // when we try to consume some more bytes, simply unpause the
<add> // underlying stream.
<add> self._read = function(n, cb) {
<add> if (paused) {
<ide> stream.resume();
<ide> paused = false;
<ide> }
<del>
<del> if (state.length === 0 && state.ended)
<del> endReadable(this);
<del>
<del> return ret;
<ide> };
<ide> };
<ide> | 1 |
Javascript | Javascript | fix typos in example descriptions | 77154a7581776b82744ec79603817aea9083fe8c | <ide><path>Examples/UIExplorer/ToastAndroidExample.android.js
<ide> var ToastExample = React.createClass({
<ide>
<ide> statics: {
<ide> title: 'Toast Example',
<del> description: 'Example that demostrates the use of an Android Toast to provide feedback.',
<add> description: 'Example that demonstrates the use of an Android Toast to provide feedback.',
<ide> },
<ide>
<ide> getInitialState: function() {
<ide><path>Examples/UIExplorer/XHRExample.android.js
<ide> class FormUploader extends React.Component {
<ide>
<ide> exports.framework = 'React';
<ide> exports.title = 'XMLHttpRequest';
<del>exports.description = 'Example that demostrates upload and download requests ' +
<add>exports.description = 'Example that demonstrates upload and download requests ' +
<ide> 'using XMLHttpRequest.';
<ide> exports.examples = [{
<ide> title: 'File Download', | 2 |
Text | Text | add changelog entry for | 2d2f35ddf24bca89ef8c8e012bb230b721b40294 | <ide><path>actionpack/CHANGELOG.md
<add>* Use a case insensitive URI Regexp for #asset_path.
<add>
<add> This fix a problem where the same asset path using different case are generating
<add> different URIs.
<add>
<add> Before:
<add>
<add> image_tag("HTTP://google.com")
<add> # => "<img alt=\"Google\" src=\"/assets/HTTP://google.com\" />"
<add> image_tag("http://google.com")
<add> # => "<img alt=\"Google\" src=\"http://google.com\" />"
<add>
<add> After:
<add>
<add> image_tag("HTTP://google.com")
<add> # => "<img alt=\"Google\" src=\"HTTP://google.com\" />"
<add> image_tag("http://google.com")
<add> # => "<img alt=\"Google\" src=\"http://google.com\" />"
<add>
<add> *David Celis*
<add>
<ide> * Element of the `collection_check_boxes` and `collection_radio_buttons` can
<ide> optionally contain html attributes as the last element of the array.
<ide> | 1 |
Javascript | Javascript | fix incorrect assumptions on uid and gid | 42c740212d6c0b910463414ee7d9865e3fc0bb0c | <ide><path>test/parallel/test-child-process-spawnsync-validation-errors.js
<ide> const spawnSync = require('child_process').spawnSync;
<ide> const signals = process.binding('constants').os.signals;
<ide>
<ide> let invalidArgTypeError;
<add>let invalidArgTypeErrorCount = 62;
<ide>
<ide> if (common.isWindows) {
<ide> invalidArgTypeError =
<ide> common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError }, 42);
<ide> } else {
<ide> invalidArgTypeError =
<del> common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError }, 62);
<add> common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError },
<add> invalidArgTypeErrorCount);
<ide> }
<ide>
<ide> const invalidRangeError =
<ide> if (!common.isWindows) {
<ide> fail('uid', Infinity, invalidArgTypeError);
<ide> fail('uid', 3.1, invalidArgTypeError);
<ide> fail('uid', -3.1, invalidArgTypeError);
<add> } else {
<add> //Decrement invalidArgTypeErrorCount if validation isn't possible
<add> invalidArgTypeErrorCount -= 10;
<ide> }
<ide> }
<ide>
<ide> if (!common.isWindows) {
<ide> fail('gid', Infinity, invalidArgTypeError);
<ide> fail('gid', 3.1, invalidArgTypeError);
<ide> fail('gid', -3.1, invalidArgTypeError);
<add> } else {
<add> //Decrement invalidArgTypeErrorCount if validation isn't possible
<add> invalidArgTypeErrorCount -= 10;
<ide> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | support marginheight and marginwidth attributes | 96bd155cbdf03c67d88f1facb13fabfa86e094d4 | <ide><path>src/browser/ui/dom/HTMLDOMPropertyConfig.js
<ide> var HTMLDOMPropertyConfig = {
<ide> list: MUST_USE_ATTRIBUTE,
<ide> loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
<ide> manifest: MUST_USE_ATTRIBUTE,
<add> marginHeight: MUST_USE_ATTRIBUTE,
<add> marginWidth: MUST_USE_ATTRIBUTE,
<ide> max: null,
<ide> maxLength: MUST_USE_ATTRIBUTE,
<ide> media: MUST_USE_ATTRIBUTE, | 1 |
Go | Go | add the variable maps to the api functions | ff67da9c867d82192020e3840bd588acc959bcd3 | <ide><path>api.go
<ide> func httpError(w http.ResponseWriter, err error) {
<ide> }
<ide> }
<ide>
<del>func getAuth(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func getAuth(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> var out auth.AuthConfig
<ide> out.Username = srv.runtime.authConfig.Username
<ide> out.Email = srv.runtime.authConfig.Email
<ide> func getAuth(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error
<ide> return b, nil
<ide> }
<ide>
<del>func postAuth(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postAuth(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> var config auth.AuthConfig
<ide> if err := json.NewDecoder(r.Body).Decode(&config); err != nil {
<ide> return nil, err
<ide> func postAuth(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, erro
<ide> return nil, nil
<ide> }
<ide>
<del>func getVersion(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func getVersion(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> m := srv.DockerVersion()
<ide> b, err := json.Marshal(m)
<ide> if err != nil {
<ide> func getVersion(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, er
<ide> return b, nil
<ide> }
<ide>
<del>func postContainersKill(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<del> vars := mux.Vars(r)
<add>func postContainersKill(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide> if err := srv.ContainerKill(name); err != nil {
<ide> return nil, err
<ide> func postContainersKill(srv *Server, w http.ResponseWriter, r *http.Request) ([]
<ide> return nil, nil
<ide> }
<ide>
<del>func getContainersExport(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<del> vars := mux.Vars(r)
<add>func getContainersExport(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide>
<ide> if err := srv.ContainerExport(name, w); err != nil {
<ide> func getContainersExport(srv *Server, w http.ResponseWriter, r *http.Request) ([
<ide> return nil, nil
<ide> }
<ide>
<del>func getImages(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func getImages(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide> func getImages(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, err
<ide> return b, nil
<ide> }
<ide>
<del>func getImagesViz(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func getImagesViz(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := srv.ImagesViz(w); err != nil {
<ide> return nil, err
<ide> }
<ide> return nil, nil
<ide> }
<ide>
<del>func getInfo(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func getInfo(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> out := srv.DockerInfo()
<ide> b, err := json.Marshal(out)
<ide> if err != nil {
<ide> func getInfo(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error
<ide> return b, nil
<ide> }
<ide>
<del>func getImagesHistory(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<del> vars := mux.Vars(r)
<add>func getImagesHistory(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<add> log.Printf("----------> %s\n", name)
<ide> outs, err := srv.ImageHistory(name)
<ide> if err != nil {
<ide> return nil, err
<ide> func getImagesHistory(srv *Server, w http.ResponseWriter, r *http.Request) ([]by
<ide> return b, nil
<ide> }
<ide>
<del>func getContainersChanges(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<del> vars := mux.Vars(r)
<add>func getContainersChanges(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide> changesStr, err := srv.ContainerChanges(name)
<ide> if err != nil {
<ide> func getContainersChanges(srv *Server, w http.ResponseWriter, r *http.Request) (
<ide> return b, nil
<ide> }
<ide>
<del>func getContainers(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func getContainers(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide> func getContainers(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte,
<ide> return b, nil
<ide> }
<ide>
<del>func postImagesTag(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postImagesTag(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide> repo := r.Form.Get("repo")
<ide> tag := r.Form.Get("tag")
<del> vars := mux.Vars(r)
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide> force := r.Form.Get("force") == "1"
<ide>
<ide> func postImagesTag(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte,
<ide> return nil, nil
<ide> }
<ide>
<del>func postCommit(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postCommit(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide> func postCommit(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, er
<ide> return b, nil
<ide> }
<ide>
<del>func postImages(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postImages(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide> func postImages(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, er
<ide> return nil, nil
<ide> }
<ide>
<del>func getImagesSearch(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func getImagesSearch(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide> func getImagesSearch(srv *Server, w http.ResponseWriter, r *http.Request) ([]byt
<ide> return b, nil
<ide> }
<ide>
<del>func postImagesInsert(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postImagesInsert(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> url := r.Form.Get("url")
<ide> path := r.Form.Get("path")
<del> vars := mux.Vars(r)
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide>
<ide> in, out, err := hijackServer(w)
<ide> func postImagesInsert(srv *Server, w http.ResponseWriter, r *http.Request) ([]by
<ide> return nil, nil
<ide> }
<ide>
<del>func postImagesPush(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postImagesPush(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide> registry := r.Form.Get("registry")
<ide>
<del> vars := mux.Vars(r)
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide>
<ide> in, out, err := hijackServer(w)
<ide> func postImagesPush(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte
<ide> return nil, nil
<ide> }
<ide>
<del>func postBuild(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postBuild(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> in, out, err := hijackServer(w)
<ide> if err != nil {
<ide> return nil, err
<ide> func postBuild(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, err
<ide> return nil, nil
<ide> }
<ide>
<del>func postContainers(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postContainers(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> var config Config
<ide> if err := json.NewDecoder(r.Body).Decode(&config); err != nil {
<ide> return nil, err
<ide> func postContainers(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte
<ide> return b, nil
<ide> }
<ide>
<del>func postContainersRestart(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postContainersRestart(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide> t, err := strconv.Atoi(r.Form.Get("t"))
<ide> if err != nil || t < 0 {
<ide> t = 10
<ide> }
<del> vars := mux.Vars(r)
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide> if err := srv.ContainerRestart(name, t); err != nil {
<ide> return nil, err
<ide> func postContainersRestart(srv *Server, w http.ResponseWriter, r *http.Request)
<ide> return nil, nil
<ide> }
<ide>
<del>func deleteContainers(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func deleteContainers(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<del> vars := mux.Vars(r)
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide> v := r.Form.Get("v") == "1"
<ide>
<ide> func deleteContainers(srv *Server, w http.ResponseWriter, r *http.Request) ([]by
<ide> return nil, nil
<ide> }
<ide>
<del>func deleteImages(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<del> vars := mux.Vars(r)
<add>func deleteImages(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide> if err := srv.ImageDelete(name); err != nil {
<ide> return nil, err
<ide> func deleteImages(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte,
<ide> return nil, nil
<ide> }
<ide>
<del>func postContainersStart(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<del> vars := mux.Vars(r)
<add>func postContainersStart(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide> if err := srv.ContainerStart(name); err != nil {
<ide> return nil, err
<ide> func postContainersStart(srv *Server, w http.ResponseWriter, r *http.Request) ([
<ide> return nil, nil
<ide> }
<ide>
<del>func postContainersStop(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postContainersStop(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide> t, err := strconv.Atoi(r.Form.Get("t"))
<ide> if err != nil || t < 0 {
<ide> t = 10
<ide> }
<del> vars := mux.Vars(r)
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide>
<ide> if err := srv.ContainerStop(name, t); err != nil {
<ide> func postContainersStop(srv *Server, w http.ResponseWriter, r *http.Request) ([]
<ide> return nil, nil
<ide> }
<ide>
<del>func postContainersWait(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<del> vars := mux.Vars(r)
<add>func postContainersWait(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide> status, err := srv.ContainerWait(name)
<ide> if err != nil {
<ide> func postContainersWait(srv *Server, w http.ResponseWriter, r *http.Request) ([]
<ide> return b, nil
<ide> }
<ide>
<del>func postContainersAttach(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<add>func postContainersAttach(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<ide> if err := parseForm(r); err != nil {
<ide> return nil, err
<ide> }
<ide> func postContainersAttach(srv *Server, w http.ResponseWriter, r *http.Request) (
<ide> stdin := r.Form.Get("stdin") == "1"
<ide> stdout := r.Form.Get("stdout") == "1"
<ide> stderr := r.Form.Get("stderr") == "1"
<del> vars := mux.Vars(r)
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide>
<ide> in, out, err := hijackServer(w)
<ide> func postContainersAttach(srv *Server, w http.ResponseWriter, r *http.Request) (
<ide> return nil, nil
<ide> }
<ide>
<del>func getContainersByName(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<del> vars := mux.Vars(r)
<add>func getContainersByName(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide>
<ide> container, err := srv.ContainerInspect(name)
<ide> func getContainersByName(srv *Server, w http.ResponseWriter, r *http.Request) ([
<ide> return b, nil
<ide> }
<ide>
<del>func getImagesByName(srv *Server, w http.ResponseWriter, r *http.Request) ([]byte, error) {
<del> vars := mux.Vars(r)
<add>func getImagesByName(srv *Server, w http.ResponseWriter, r *http.Request, vars map[string]string) ([]byte, error) {
<add> if vars == nil {
<add> return nil, fmt.Errorf("Missing parameter")
<add> }
<ide> name := vars["name"]
<ide>
<ide> image, err := srv.ImageInspect(name)
<ide> func ListenAndServe(addr string, srv *Server, logging bool) error {
<ide> r := mux.NewRouter()
<ide> log.Printf("Listening for HTTP on %s\n", addr)
<ide>
<del> m := map[string]map[string]func(*Server, http.ResponseWriter, *http.Request) ([]byte, error){
<add> m := map[string]map[string]func(*Server, http.ResponseWriter, *http.Request, map[string]string) ([]byte, error){
<ide> "GET": {
<ide> "/auth": getAuth,
<ide> "/version": getVersion,
<ide> func ListenAndServe(addr string, srv *Server, logging bool) error {
<ide> Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], VERSION)
<ide> }
<ide> }
<del> json, err := localFct(srv, w, r)
<add> json, err := localFct(srv, w, r, mux.Vars(r))
<ide> if err != nil {
<ide> httpError(w, err)
<ide> }
<ide><path>api_test.go
<ide> func TestAuth(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := postAuth(srv, r, req)
<add> body, err := postAuth(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestAuth(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err = getAuth(srv, nil, req)
<add> body, err = getAuth(srv, nil, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestVersion(t *testing.T) {
<ide>
<ide> srv := &Server{runtime: runtime}
<ide>
<del> body, err := getVersion(srv, nil, nil)
<add> body, err := getVersion(srv, nil, nil, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestImages(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := getImages(srv, nil, req)
<add> body, err := getImages(srv, nil, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestInfo(t *testing.T) {
<ide>
<ide> srv := &Server{runtime: runtime}
<ide>
<del> body, err := getInfo(srv, nil, nil)
<add> body, err := getInfo(srv, nil, nil, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func testCreateContainer(t *testing.T, srv *Server) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := postContainers(srv, r, req)
<add> body, err := postContainers(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func testListContainers(t *testing.T, srv *Server, expected int) []ApiContainers
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := getContainers(srv, r, req)
<add> body, err := getContainers(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func testContainerStart(t *testing.T, srv *Server, id string) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := postContainersStart(srv, r, req)
<add> body, err := postContainersStart(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func testContainerRestart(t *testing.T, srv *Server, id string) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := postContainersRestart(srv, r, req)
<add> body, err := postContainersRestart(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func testContainerStop(t *testing.T, srv *Server, id string) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := postContainersStop(srv, r, req)
<add> body, err := postContainersStop(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func testContainerKill(t *testing.T, srv *Server, id string) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := postContainersKill(srv, r, req)
<add> body, err := postContainersKill(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func testContainerWait(t *testing.T, srv *Server, id string) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := postContainersWait(srv, r, req)
<add> body, err := postContainersWait(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func testDeleteContainer(t *testing.T, srv *Server, id string) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := deleteContainers(srv, r, req)
<add> body, err := deleteContainers(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func testContainerChanges(t *testing.T, srv *Server, id string) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> body, err := getContainersChanges(srv, r, req)
<add> body, err := getContainersChanges(srv, r, req, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> } | 2 |
Go | Go | complete the "--graph" / "-g" deprecation | b58de39ca78a42e01f4e0d80c53ed11f8357be83 | <ide><path>cmd/dockerd/config.go
<ide> func installCommonConfigFlags(conf *config.Config, flags *pflag.FlagSet) error {
<ide>
<ide> // Deprecated flags / options
<ide>
<del> // "--graph" is "soft-deprecated" in favor of "data-root". This flag was added
<del> // before Docker 1.0, so won't be removed, only hidden, to discourage its usage.
<del> flags.StringVarP(&conf.Root, "graph", "g", conf.Root, "Root of the Docker runtime")
<del> _ = flags.MarkHidden("graph")
<add> //nolint:staticcheck // TODO(thaJeztah): remove in next release.
<add> flags.StringVarP(&conf.RootDeprecated, "graph", "g", conf.RootDeprecated, "Root of the Docker runtime")
<add> _ = flags.MarkDeprecated("graph", "Use --data-root instead")
<ide> flags.BoolVarP(&conf.AutoRestart, "restart", "r", true, "--restart on the daemon has been deprecated in favor of --restart policies on docker run")
<ide> _ = flags.MarkDeprecated("restart", "Please use a restart policy on docker run")
<ide>
<ide><path>cmd/dockerd/daemon.go
<ide> func loadDaemonCliConfig(opts *daemonOptions) (*config.Config, error) {
<ide> conf.Hosts = opts.Hosts
<ide> conf.LogLevel = opts.LogLevel
<ide>
<del> if flags.Changed("graph") && flags.Changed("data-root") {
<del> return nil, errors.New(`cannot specify both "--graph" and "--data-root" option`)
<del> }
<ide> if flags.Changed(FlagTLS) {
<ide> conf.TLS = &opts.TLS
<ide> }
<ide> func loadDaemonCliConfig(opts *daemonOptions) (*config.Config, error) {
<ide> return nil, err
<ide> }
<ide>
<del> if flags.Changed("graph") {
<del> logrus.Warnf(`The "-g / --graph" flag is deprecated. Please use "--data-root" instead`)
<del> }
<del>
<ide> // Check if duplicate label-keys with different values are found
<ide> newLabels, err := config.GetConflictFreeLabels(conf.Labels)
<ide> if err != nil {
<ide><path>daemon/config/config.go
<ide> type CommonConfig struct {
<ide> NetworkDiagnosticPort int `json:"network-diagnostic-port,omitempty"`
<ide> Pidfile string `json:"pidfile,omitempty"`
<ide> RawLogs bool `json:"raw-logs,omitempty"`
<del> RootDeprecated string `json:"graph,omitempty"`
<add> RootDeprecated string `json:"graph,omitempty"` // Deprecated: use Root instead. TODO(thaJeztah): remove in next release.
<ide> Root string `json:"data-root,omitempty"`
<ide> ExecRoot string `json:"exec-root,omitempty"`
<ide> SocketGroup string `json:"group,omitempty"`
<ide> func getConflictFreeConfiguration(configFile string, flags *pflag.FlagSet) (*Con
<ide> return nil, err
<ide> }
<ide>
<del> if config.RootDeprecated != "" {
<del> logrus.Warn(`The "graph" config file option is deprecated. Please use "data-root" instead.`)
<del>
<del> if config.Root != "" {
<del> return nil, errors.New(`cannot specify both "graph" and "data-root" config file options`)
<del> }
<del>
<del> config.Root = config.RootDeprecated
<del> }
<del>
<ide> return &config, nil
<ide> }
<ide>
<ide> func findConfigurationConflicts(config map[string]interface{}, flags *pflag.Flag
<ide> // such as config.DNS, config.Labels, config.DNSSearch,
<ide> // as well as config.MaxConcurrentDownloads, config.MaxConcurrentUploads and config.MaxDownloadAttempts.
<ide> func Validate(config *Config) error {
<add> //nolint:staticcheck // TODO(thaJeztah): remove in next release.
<add> if config.RootDeprecated != "" {
<add> return errors.New(`the "graph" config file option is deprecated; use "data-root" instead`)
<add> }
<add>
<ide> // validate log-level
<ide> if config.LogLevel != "" {
<ide> if _, err := logrus.ParseLevel(config.LogLevel); err != nil { | 3 |
PHP | PHP | add more detail to doc blocks | 3afcd7ace7af639c94cb76cc8b65b16230632e06 | <ide><path>src/Validation/Validator.php
<ide> public function allowEmptyString($field, $when = true, $message = null)
<ide> /**
<ide> * Requires a field to be not be an empty string.
<ide> *
<del> * Creates rules that are complements to allowEmptyString()
<add> * Opposite to allowEmptyString()
<ide> *
<ide> * @param string $field The name of the field.
<ide> * @param string|null $message The message to show if the field is not
<ide> public function allowEmptyString($field, $when = true, $message = null)
<ide> * callable is passed then the field will allowed to be empty only when
<ide> * the callback returns false.
<ide> * @return $this
<add> * @see \Cake\Validation\Validator::allowEmptyString()
<ide> * @since 3.8.0
<ide> */
<ide> public function notEmptyString($field, $message = null, $when = false)
<ide> public function allowEmptyArray($field, $when = true, $message = null)
<ide> /**
<ide> * Require a field to be a non-empty array
<ide> *
<del> * This method is equivalent to calling allowEmptyFor() with EMPTY_STRING +
<del> * EMPTY_ARRAY flags.
<add> * Opposite to allowEmptyArray()
<ide> *
<ide> * @param string $field The name of the field.
<ide> * @param bool|string|callable $when Indicates when the field is allowed to be empty
<ide> * @param string|null $message The message to show if the field is not
<ide> * Valid values are false (always), 'create', 'update'. If a callable is passed then
<ide> * the field will allowed to be empty only when the callback returns false.
<ide> * @return $this
<add> * @see \Cake\Validation\Validator::allowEmptyArray()
<ide> * @since 3.8.0
<ide> */
<ide> public function notEmptyArray($field, $message = null, $when = false)
<ide> public function notEmptyArray($field, $message = null, $when = false)
<ide> * Allows a field to be an empty file.
<ide> *
<ide> * This method is equivalent to calling allowEmptyFor() with EMPTY_FILE flag.
<add> * File fields will not accept `''`, or `[]` as empty values. Only `null` and a file
<add> * upload with `error` equal to `UPLOAD_ERR_NO_FILE` will be treated as empty.
<ide> *
<ide> * @param string $field The name of the field.
<ide> * @param bool|string|callable $when Indicates when the field is allowed to be empty
<del> * Valid values are true, false, 'create', 'update'. If a callable is passed then
<del> * the field will allowed to be empty only when the callback returns true.
<add> * Valid values are true, 'create', 'update'. If a callable is passed then
<add> * the field will allowed to be empty only when the callback returns true.
<ide> * @param string|null $message The message to show if the field is not
<ide> * @return $this
<ide> * @since 3.7.0
<ide> public function allowEmptyFile($field, $when = true, $message = null)
<ide> /**
<ide> * Require a field to be a not-empty file.
<ide> *
<del> * Empty string, and empty array values will not be caught as empty
<del> * and you should use additional validators to check uploaded files.
<add> * Opposite to allowEmptyFile()
<ide> *
<ide> * @param string $field The name of the field.
<ide> * @param string|null $message The message to show if the field is not
<ide> public function allowEmptyFile($field, $when = true, $message = null)
<ide> * the field will required to be not empty when the callback returns false.
<ide> * @return $this
<ide> * @since 3.7.0
<del> * @see \Cake\Validation\Validator::allowEmptyFor() For detail usage
<add> * @see \Cake\Validation\Validator::allowEmptyFile()
<ide> */
<ide> public function notEmptyFile($field, $message = null, $when = false)
<ide> {
<ide> public function notEmptyFile($field, $message = null, $when = false)
<ide> /**
<ide> * Allows a field to be an empty date.
<ide> *
<del> * This method is equivalent to calling allowEmptyFor() with EMPTY_STRING +
<del> * EMPTY_DATE flags.
<add> * Empty date values are `null`, `''`, `[]` and arrays where all values are `''`
<add> * and the `year` key is present.
<ide> *
<ide> * @param string $field The name of the field.
<ide> * @param bool|string|callable $when Indicates when the field is allowed to be empty
<ide> public function allowEmptyDate($field, $when = true, $message = null)
<ide> /**
<ide> * Allows a field to be an empty time.
<ide> *
<add> * Empty date values are `null`, `''`, `[]` and arrays where all values are `''`
<add> * and the `hour` key is present.
<add> *
<ide> * This method is equivalent to calling allowEmptyFor() with EMPTY_STRING +
<ide> * EMPTY_TIME flags.
<ide> *
<ide> public function allowEmptyTime($field, $when = true, $message = null)
<ide> /**
<ide> * Allows a field to be an empty date/time.
<ide> *
<add> * Empty date values are `null`, `''`, `[]` and arrays where all values are `''`
<add> * and the `year` and `hour` keys are present.
<add> *
<ide> * This method is equivalent to calling allowEmptyFor() with EMPTY_STRING +
<ide> * EMPTY_DATE + EMPTY_TIME flags.
<ide> * | 1 |
Text | Text | fix typo in docs | 76e6a3dfadd68902544663e51056c48da804ffb1 | <ide><path>docs/recipes/ReducingBoilerplate.md
<ide> export const removeTodo = makeActionCreator('REMOVE_TODO', 'id');
<ide> See [redux-action-utils](https://github.com/insin/redux-action-utils) and [redux-actions](https://github.com/acdlite/redux-actions) for examples of such utilities.
<ide>
<ide> Note that such utilities add magic to your code.
<del>Are magic and indirection really worth it to avoid a few extra few lines of code?
<add>Are magic and indirection really worth it to avoid a few extra lines of code?
<ide>
<ide> ## Async Action Creators
<ide> | 1 |
Java | Java | fix padding for text views in fabric | 7b2030bceaa67789f330b3838c07505263169821 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactTextShadowNode.java
<ide> /**
<ide> * Copyright (c) Facebook, Inc. and its affiliates.
<ide> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<add> * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
<add> * directory of this source tree.
<ide> */
<del>
<ide> package com.facebook.react.views.text;
<ide>
<del>import android.graphics.Rect;
<ide> import android.os.Build;
<ide> import android.text.BoringLayout;
<ide> import android.text.Layout;
<ide> import android.text.Spannable;
<ide> import android.text.Spanned;
<ide> import android.text.StaticLayout;
<ide> import android.text.TextPaint;
<del>import android.util.DisplayMetrics;
<ide> import android.view.Gravity;
<ide> import android.widget.TextView;
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.bridge.Arguments;
<ide> import com.facebook.react.bridge.WritableArray;
<ide> import com.facebook.react.bridge.WritableMap;
<del>import com.facebook.react.uimanager.LayoutShadowNode;
<del>import com.facebook.react.uimanager.ReactShadowNodeImpl;
<ide> import com.facebook.react.uimanager.Spacing;
<ide> import com.facebook.react.uimanager.UIViewOperationQueue;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<ide> public long measure(
<ide> YogaMeasureMode widthMode,
<ide> float height,
<ide> YogaMeasureMode heightMode) {
<add>
<ide> // TODO(5578671): Handle text direction (see View#getTextDirectionHeuristic)
<ide> TextPaint textPaint = sTextPaintInstance;
<ide> textPaint.setTextSize(mFontSize != UNSET ? mFontSize : getDefaultFontSize());
<ide> Layout layout;
<del> Spanned text = Assertions.assertNotNull(
<del> mPreparedSpannableText,
<del> "Spannable element has not been prepared in onBeforeLayout");
<add> Spanned text =
<add> Assertions.assertNotNull(
<add> mPreparedSpannableText,
<add> "Spannable element has not been prepared in onBeforeLayout");
<ide> BoringLayout.Metrics boring = BoringLayout.isBoring(text, textPaint);
<del> float desiredWidth = boring == null ?
<del> Layout.getDesiredWidth(text, textPaint) : Float.NaN;
<add> float desiredWidth = boring == null ? Layout.getDesiredWidth(text, textPaint) : Float.NaN;
<ide>
<ide> // technically, width should never be negative, but there is currently a bug in
<ide> boolean unconstrainedWidth = widthMode == YogaMeasureMode.UNDEFINED || width < 0;
<ide> public long measure(
<ide> break;
<ide> }
<ide>
<del> if (boring == null &&
<del> (unconstrainedWidth ||
<del> (!YogaConstants.isUndefined(desiredWidth) && desiredWidth <= width))) {
<add> if (boring == null
<add> && (unconstrainedWidth
<add> || (!YogaConstants.isUndefined(desiredWidth) && desiredWidth <= width))) {
<ide> // Is used when the width is not known and the text is not boring, ie. if it contains
<ide> // unicode characters.
<ide>
<ide> int hintWidth = (int) Math.ceil(desiredWidth);
<ide> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
<del> layout = new StaticLayout(
<del> text,
<del> textPaint,
<del> hintWidth,
<del> alignment,
<del> 1.f,
<del> 0.f,
<del> mIncludeFontPadding);
<add> layout =
<add> new StaticLayout(
<add> text, textPaint, hintWidth, alignment, 1.f, 0.f, mIncludeFontPadding);
<ide> } else {
<del> layout = StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, hintWidth)
<del> .setAlignment(alignment)
<del> .setLineSpacing(0.f, 1.f)
<del> .setIncludePad(mIncludeFontPadding)
<del> .setBreakStrategy(mTextBreakStrategy)
<del> .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL)
<del> .build();
<add> layout =
<add> StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, hintWidth)
<add> .setAlignment(alignment)
<add> .setLineSpacing(0.f, 1.f)
<add> .setIncludePad(mIncludeFontPadding)
<add> .setBreakStrategy(mTextBreakStrategy)
<add> .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL)
<add> .build();
<ide> }
<ide>
<ide> } else if (boring != null && (unconstrainedWidth || boring.width <= width)) {
<ide> // Is used for single-line, boring text when the width is either unknown or bigger
<ide> // than the width of the text.
<del> layout = BoringLayout.make(
<del> text,
<del> textPaint,
<del> boring.width,
<del> alignment,
<del> 1.f,
<del> 0.f,
<del> boring,
<del> mIncludeFontPadding);
<add> layout =
<add> BoringLayout.make(
<add> text,
<add> textPaint,
<add> boring.width,
<add> alignment,
<add> 1.f,
<add> 0.f,
<add> boring,
<add> mIncludeFontPadding);
<ide> } else {
<ide> // Is used for multiline, boring text and the width is known.
<ide>
<ide> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
<del> layout = new StaticLayout(
<del> text,
<del> textPaint,
<del> (int) width,
<del> alignment,
<del> 1.f,
<del> 0.f,
<del> mIncludeFontPadding);
<add> layout =
<add> new StaticLayout(
<add> text, textPaint, (int) width, alignment, 1.f, 0.f, mIncludeFontPadding);
<ide> } else {
<del> layout = StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, (int) width)
<del> .setAlignment(alignment)
<del> .setLineSpacing(0.f, 1.f)
<del> .setIncludePad(mIncludeFontPadding)
<del> .setBreakStrategy(mTextBreakStrategy)
<del> .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL)
<del> .build();
<add> layout =
<add> StaticLayout.Builder.obtain(text, 0, text.length(), textPaint, (int) width)
<add> .setAlignment(alignment)
<add> .setLineSpacing(0.f, 1.f)
<add> .setIncludePad(mIncludeFontPadding)
<add> .setBreakStrategy(mTextBreakStrategy)
<add> .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NORMAL)
<add> .build();
<ide> }
<ide> }
<ide>
<ide> if (mShouldNotifyOnTextLayout) {
<ide> WritableArray lines =
<del> FontMetricsUtil.getFontMetrics(text, layout, sTextPaintInstance, getThemedContext());
<add> FontMetricsUtil.getFontMetrics(
<add> text, layout, sTextPaintInstance, getThemedContext());
<ide> WritableMap event = Arguments.createMap();
<ide> event.putArray("lines", lines);
<ide> getThemedContext()
<ide> public long measure(
<ide> }
<ide>
<ide> if (mNumberOfLines != UNSET && mNumberOfLines < layout.getLineCount()) {
<del> return YogaMeasureOutput.make(layout.getWidth(), layout.getLineBottom(mNumberOfLines - 1));
<add> return YogaMeasureOutput.make(
<add> layout.getWidth(), layout.getLineBottom(mNumberOfLines - 1));
<ide> } else {
<ide> return YogaMeasureOutput.make(layout.getWidth(), layout.getHeight());
<ide> }
<ide> public void onCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue) {
<ide>
<ide> if (mPreparedSpannableText != null) {
<ide> ReactTextUpdate reactTextUpdate =
<del> new ReactTextUpdate(
<del> mPreparedSpannableText,
<del> UNSET,
<del> mContainsImages,
<del> getPadding(Spacing.START),
<del> getPadding(Spacing.TOP),
<del> getPadding(Spacing.END),
<del> getPadding(Spacing.BOTTOM),
<del> getTextAlign(),
<del> mTextBreakStrategy
<del> );
<add> new ReactTextUpdate(
<add> mPreparedSpannableText,
<add> UNSET,
<add> mContainsImages,
<add> getPadding(Spacing.START),
<add> getPadding(Spacing.TOP),
<add> getPadding(Spacing.END),
<add> getPadding(Spacing.BOTTOM),
<add> getTextAlign(),
<add> mTextBreakStrategy);
<ide> uiViewOperationQueue.enqueueUpdateExtraData(getReactTag(), reactTextUpdate);
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java
<ide> private static int parseNumericFontWeight(String fontWeightString) {
<ide> : -1;
<ide> }
<ide>
<del> //TODO remove this from here
<add> //TODO T31905686 remove this from here and add support to RTL
<ide> private YogaDirection getLayoutDirection() {
<ide> return YogaDirection.LTR;
<ide> }
<ide>
<ide> public float getBottomPadding() {
<del> // TODO convert into constants
<del> return getFloatProp("bottomPadding", 0f);
<add> return getPaddingProp(ViewProps.PADDING_BOTTOM);
<ide> }
<ide>
<ide> public float getLeftPadding() {
<del> return getFloatProp("leftPadding", 0f);
<add> return getPaddingProp(ViewProps.PADDING_LEFT);
<ide> }
<ide>
<ide> public float getStartPadding() {
<del> return getFloatProp("startPadding", 0f);
<add> return getPaddingProp(ViewProps.PADDING_START);
<ide> }
<ide>
<ide> public float getEndPadding() {
<del> return getFloatProp("endPadding", 0f);
<add> return getPaddingProp(ViewProps.PADDING_END);
<ide> }
<ide>
<ide> public float getTopPadding() {
<del> return getFloatProp("topPadding", 0f);
<add> return getPaddingProp(ViewProps.PADDING_TOP);
<ide> }
<ide>
<ide> public float getRightPadding() {
<del> return getFloatProp("rightPadding", 0f);
<add> return getPaddingProp(ViewProps.PADDING_RIGHT);
<add> }
<add>
<add> private float getPaddingProp(String paddingType) {
<add> if (mProps.hasKey(ViewProps.PADDING)) {
<add> return PixelUtil.toPixelFromDIP(getFloatProp(ViewProps.PADDING, 0f));
<add> }
<add>
<add> return PixelUtil.toPixelFromDIP(getFloatProp(paddingType, 0f));
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.java
<ide> import com.facebook.react.bridge.ReadableNativeMap;
<ide> import com.facebook.react.uimanager.PixelUtil;
<ide> import com.facebook.react.uimanager.ReactStylesDiffMap;
<add>import com.facebook.react.uimanager.ViewDefaults;
<ide> import com.facebook.yoga.YogaConstants;
<ide> import com.facebook.yoga.YogaMeasureMode;
<add>import java.awt.font.TextAttribute;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide> private static void buildSpannedFromShadowNode(
<ide> new CustomLetterSpacingSpan(textAttributes.mLetterSpacing)));
<ide> }
<ide> }
<del> if (textAttributes.mFontSize != UNSET) {
<del> ops.add(
<del> new SetSpanOperation(
<del> start, end, new AbsoluteSizeSpan((int) (textAttributes.mFontSize))));
<del> }
<add> ops.add(
<add> new SetSpanOperation(
<add> start, end, new AbsoluteSizeSpan(textAttributes.mFontSize)));
<ide> if (textAttributes.mFontStyle != UNSET
<ide> || textAttributes.mFontWeight != UNSET
<ide> || textAttributes.mFontFamily != null) {
<ide> protected static Spannable spannedFromTextFragments(
<ide>
<ide> buildSpannedFromShadowNode(context, fragments, sb, ops);
<ide>
<del> // TODO: add support for AllowScaling in C++
<del>// if (textShadowNode.mFontSize == UNSET) {
<del>// int defaultFontSize =
<del>// textShadowNode.mAllowFontScaling
<del>// ? (int) Math.ceil(PixelUtil.toPixelFromSP(ViewDefaults.FONT_SIZE_SP))
<del>// : (int) Math.ceil(PixelUtil.toPixelFromDIP(ViewDefaults.FONT_SIZE_SP));
<del>//
<del>// ops.add(new SetSpanOperation(0, sb.length(), new AbsoluteSizeSpan(defaultFontSize)));
<del>// }
<del>//
<add>// TODO T31905686: add support for inline Images
<ide> // textShadowNode.mContainsImages = false;
<ide> // textShadowNode.mHeightOfTallestInlineImage = Float.NaN;
<ide>
<ide> // While setting the Spans on the final text, we also check whether any of them are images.
<ide> int priority = 0;
<ide> for (SetSpanOperation op : ops) {
<del>// TODO: add support for TextInlineImage in C++
<add>// TODO T31905686: add support for TextInlineImage in C++
<ide> // if (op.what instanceof TextInlineImageSpan) {
<ide> // int height = ((TextInlineImageSpan) op.what).getHeight();
<ide> // textShadowNode.mContainsImages = true; | 3 |
Python | Python | fix indexerror in dimensiondata list_images | 0a502252161f8b8c48aecef5c8be7d300bf00e07 | <ide><path>libcloud/compute/drivers/dimensiondata.py
<ide> def _to_images(self, object, el_name='osImage'):
<ide> images = []
<ide> locations = self.list_locations()
<ide>
<add> # The CloudControl API will return all images
<add> # in the current geographic region (even ones in
<add> # datacenters the user's organisation does not have access to)
<add> #
<add> # We therefore need to filter out those images (since we can't
<add> # get a NodeLocation for them)
<add> location_ids = set(location.id for location in locations)
<add>
<ide> for element in object.findall(fixxpath(el_name, TYPES_URN)):
<del> images.append(self._to_image(element, locations))
<add> location_id = element.get('datacenterId')
<add> if location_id in location_ids:
<add> images.append(self._to_image(element, locations))
<ide>
<ide> return images
<ide>
<ide> def _to_image(self, element, locations=None):
<ide> location_id = element.get('datacenterId')
<ide> if locations is None:
<ide> locations = self.list_locations(location_id)
<del> location = list(filter(lambda x: x.id == location_id,
<del> locations))[0]
<ide>
<add> location = filter(lambda x: x.id == location_id, locations)[0]
<ide> cpu_spec = self._to_cpu_spec(element.find(fixxpath('cpu', TYPES_URN)))
<ide>
<ide> if LooseVersion(self.connection.active_api_version) > LooseVersion( | 1 |
Java | Java | return wrapped subscription | 95ce9aaae00621ce0bc45d89ae89ad6bf867c773 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public final Subscription subscribe(Subscriber<? super T> observer) {
<ide> if (isInternalImplementation(observer)) {
<ide> onSubscribeFunction.call(observer);
<ide> } else {
<del> onSubscribeFunction.call(new SafeSubscriber<T>(observer));
<add> // assign to `observer` so we return the protected version
<add> observer = new SafeSubscriber<T>(observer);
<add> onSubscribeFunction.call(observer);
<ide> }
<del> return hook.onSubscribeReturn(this, observer);
<add> final Subscription returnSubscription = hook.onSubscribeReturn(this, observer);
<add> // we return it inside a Subscription so it can't be cast back to Subscriber
<add> return Subscriptions.create(new Action0() {
<add>
<add> @Override
<add> public void call() {
<add> returnSubscription.unsubscribe();
<add> }
<add>
<add> });
<ide> } catch (OnErrorNotImplementedException e) {
<ide> // special handling when onError is not implemented ... we just rethrow
<ide> throw e; | 1 |
PHP | PHP | fix lint errors | f70f533d075445bd54f9231925d3b0de8c9aa9c9 | <ide><path>src/Http/Middleware/CsrfProtectionMiddleware.php
<ide> protected function _createToken(): string
<ide> public function createToken(): string
<ide> {
<ide> $value = Security::randomString(static::TOKEN_VALUE_LENGTH);
<add>
<ide> return $value . hash_hmac('sha1', $value, Security::getSalt());
<ide> }
<ide>
<ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> use Cake\Utility\CookieCryptTrait;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Security;
<del>use Cake\Utility\Text;
<ide> use Exception;
<ide> use Laminas\Diactoros\Uri;
<ide> use LogicException;
<ide><path>tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Http\Middleware;
<ide>
<del>use \Cake\Http\Exception\InvalidCsrfTokenException;
<add>use Cake\Http\Exception\InvalidCsrfTokenException;
<ide> use Cake\Http\Middleware\CsrfProtectionMiddleware;
<ide> use Cake\Http\Response;
<ide> use Cake\Http\ServerRequest; | 3 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.