content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
add onpressin & onpressout props to text
1d924549cad75912191005c8f68dd73e15b07183
<ide><path>Libraries/Text/Text.js <ide> const Text: React.AbstractComponent< <ide> ellipsizeMode, <ide> onLongPress, <ide> onPress, <add> onPressIn, <add> onPressOut, <ide> onResponderGrant, <ide> onResponderMove, <ide> onResponderRelease, <ide> const Text: React.AbstractComponent< <ide> onPress, <ide> onPressIn(event) { <ide> setHighlighted(!suppressHighlighting); <add> onPressIn?.(event); <ide> }, <ide> onPressOut(event) { <ide> setHighlighted(false); <add> onPressOut?.(event); <ide> }, <ide> onResponderTerminationRequest_DEPRECATED: onResponderTerminationRequest, <ide> onStartShouldSetResponder_DEPRECATED: onStartShouldSetResponder, <ide> const Text: React.AbstractComponent< <ide> pressRetentionOffset, <ide> onLongPress, <ide> onPress, <add> onPressIn, <add> onPressOut, <ide> onResponderTerminationRequest, <ide> onStartShouldSetResponder, <ide> suppressHighlighting, <ide><path>Libraries/Text/TextProps.js <ide> export type TextProps = $ReadOnly<{| <ide> * See https://reactnative.dev/docs/text.html#onpress <ide> */ <ide> onPress?: ?(event: PressEvent) => mixed, <add> onPressIn?: ?(event: PressEvent) => mixed, <add> onPressOut?: ?(event: PressEvent) => mixed, <ide> onResponderGrant?: ?(event: PressEvent) => void, <ide> onResponderMove?: ?(event: PressEvent) => void, <ide> onResponderRelease?: ?(event: PressEvent) => void,
2
Javascript
Javascript
add location change on successful job creation
d6f21b01e61ee42eb16c5f8e283617d4cffb0768
<ide><path>common/app/routes/Jobs/redux/save-job-saga.js <ide> import { Observable } from 'rx'; <add>import { push } from 'react-router-redux'; <ide> <ide> import { saveJobCompleted } from './actions'; <ide> import { saveJob } from './types'; <ide> export default ({ services }) => ({ dispatch }) => next => { <ide> service: 'jobs', <ide> params: { job } <ide> }) <del> .map(job => saveJobCompleted(job)) <add> .retry(3) <add> .flatMap(job => Observable.of( <add> saveJobCompleted(job), <add> push('/jobs/new/preview') <add> )) <ide> .catch(error => Observable.just({ <ide> type: handleError, <ide> error
1
Text
Text
fix modelfield docs. closes #909
ffa27b840f66d24562de9f66a9ac7a4142da51db
<ide><path>docs/api-guide/fields.md <ide> A field that supports both read and write operations. By itself `WritableField` <ide> <ide> A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to it's associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. <ide> <del>**Signature:** `ModelField(model_field=<Django ModelField class>)` <add>The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))` <add> <add>**Signature:** `ModelField(model_field=<Django ModelField instance>)` <ide> <ide> ## SerializerMethodField <ide> <ide><path>docs/index.md <ide> <p class="badges"> <ide> <iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&amp;repo=django-rest-framework&amp;type=watch&amp;count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe> <ide> <del><a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none">Tweet</a> <add><a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none"></a> <ide> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> <ide> <del><img alt="Travis build image" src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image"> <add><img src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image"> <ide> </p> <ide> <ide> # Django REST framework
2
Go
Go
catch error on console creation
93f6cf035156d3b17cbf61f1a61926c068bd8e92
<ide><path>daemon/execdriver/native/driver.go <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba <ide> } else { <ide> term, err = execdriver.NewStdConsole(c, pipes) <ide> } <add> if err != nil { <add> return -1, err <add> } <ide> c.Terminal = term <ide> <ide> d.Lock()
1
Ruby
Ruby
add convenience methods for checking migrations
e5b39862cb4f8f3097cc8ab2dc606ddb1bd1febb
<ide><path>activerecord/lib/active_record/migration.rb <ide> def current_version <ide> end <ide> end <ide> <add> def needs_migration? <add> current_version != last_version <add> end <add> <add> def last_version <add> migrations(migrations_paths).last.try(:version)||0 <add> end <add> <ide> def proper_table_name(name) <ide> # Use the Active Record objects own table_name, or pre/suffix from ActiveRecord::Base if name is a symbol/string <ide> name.table_name rescue "#{ActiveRecord::Base.table_name_prefix}#{name}#{ActiveRecord::Base.table_name_suffix}" <ide><path>activerecord/test/cases/migration_test.rb <ide> def teardown <ide> Person.reset_column_information <ide> end <ide> <add> def test_migrator_versions <add> migrations_path = MIGRATIONS_ROOT + "/valid" <add> ActiveRecord::Migrator.migrations_paths = migrations_path <add> <add> ActiveRecord::Migrator.up(migrations_path) <add> assert_equal 3, ActiveRecord::Migrator.current_version <add> assert_equal 3, ActiveRecord::Migrator.last_version <add> assert_equal false, ActiveRecord::Migrator.needs_migration? <add> <add> ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid") <add> assert_equal 0, ActiveRecord::Migrator.current_version <add> assert_equal 3, ActiveRecord::Migrator.last_version <add> assert_equal true, ActiveRecord::Migrator.needs_migration? <add> end <add> <ide> def test_create_table_with_force_true_does_not_drop_nonexisting_table <ide> if Person.connection.table_exists?(:testings2) <ide> Person.connection.drop_table :testings2
2
PHP
PHP
remove test that wasn't reverted properly
288a307a42dbc67a93cd2e6e57d01dc67e096714
<ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php <ide> public function testHandleException() <ide> $this->assertContains('was not found', '' . $result->getBody()); <ide> } <ide> <del> /** <del> * Test rendering an error page holds onto the original request. <del> * <del> * @return void <del> */ <del> public function testHandleExceptionPreserveRequest() <del> { <del> $request = ServerRequestFactory::fromGlobals(); <del> $request = $request->withHeader('Accept', 'application/json'); <del> <del> $response = new Response(); <del> $middleware = new ErrorHandlerMiddleware(); <del> $next = function ($req, $res) { <del> throw new \Cake\Http\Exception\NotFoundException('whoops'); <del> }; <del> $result = $middleware($request, $response, $next); <del> $this->assertInstanceOf('Cake\Http\Response', $result); <del> $this->assertNotSame($result, $response); <del> $this->assertEquals(404, $result->getStatusCode()); <del> $this->assertContains('"message": "whoops"', '' . $result->getBody()); <del> $this->assertEquals('application/json; charset=UTF-8', $result->getHeaderLine('Content-type')); <del> } <del> <ide> /** <ide> * Test handling PHP 7's Error instance. <ide> *
1
Python
Python
fix typo in test_dask_executor.py
f957de622e6b87567b874cdcd64e5a1f95143e0d
<ide><path>tests/executors/test_dask_executor.py <ide> def assert_tasks_on_executor(self, executor): <ide> if timezone.utcnow() > timeout: <ide> raise ValueError( <ide> 'The futures should have finished; there is probably ' <del> 'an error communciating with the Dask cluster.') <add> 'an error communicating with the Dask cluster.') <ide> <ide> # both tasks should have finished <ide> self.assertTrue(success_future.done())
1
Java
Java
fix event dispatcher timestamp sorting bug
f5a349021d3e9ccaf1a1590dc984c0ea16a177ca
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcher.java <ide> <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <del>import java.util.Collections; <ide> import java.util.Comparator; <ide> import java.util.Map; <ide> <ide> public int compare(Event lhs, Event rhs) { <ide> return 1; <ide> } <ide> <del> return lhs.getTimestampMs() < rhs.getTimestampMs() ? -1 : 1; <add> long diff = lhs.getTimestampMs() - rhs.getTimestampMs(); <add> if (diff == 0) { <add> return 0; <add> } else if (diff < 0) { <add> return -1; <add> } else { <add> return 1; <add> } <ide> } <ide> }; <ide>
1
Text
Text
add changelog for 15.6.2
e858ed5b14fe5f511ad2d2146e1607c84e308ca6
<ide><path>CHANGELOG.md <ide> <ide> </details> <ide> <add>## 15.6.2 (September 25, 2017) <add> <add>### All Packages <add>* Switch from BSD + Patents to MIT license <add> <add>### React DOM <add> <add>* Fix a bug where modifying `document.documentMode` would trigger IE detection in other browsers, breaking change events. ([@aweary](https://github.com/aweary) in [#10032](https://github.com/facebook/react/pull/10032)) <add>* CSS Columns are treated as unitless numbers. ([@aweary](https://github.com/aweary) in [#10115](https://github.com/facebook/react/pull/10115)) <add>* Fix bug in QtWebKit when wrapping synthetic events in proxies. ([@walrusfruitcake](https://github.com/walrusfruitcake) in [#10115](https://github.com/facebook/react/pull/10011)) <add>* Prevent event handlers from receiving extra argument in development. ([@aweary](https://github.com/aweary) in [#10115](https://github.com/facebook/react/pull/8363)) <add>* Fix cases where `onChange` would not fire with `defaultChecked` on radio inputs. ([@jquense](https://github.com/jquense) in [#10156](https://github.com/facebook/react/pull/10156)) <add>* Add support for `controlList` attribute to DOM property whitelist ([@nhunzaker](https://github.com/nhunzaker) in [#9940](https://github.com/facebook/react/pull/9940)) <add>* Fix a bug where creating an element with a ref in a constructor did not throw an error in development. ([@iansu](https://github.com/iansu) in [#10025](https://github.com/facebook/react/pull/10025)) <add> <ide> ## 15.6.1 (June 14, 2017) <ide> <ide> ### React DOM
1
Javascript
Javascript
add a space in donate text
033606ec8d15699deb2860256d19d3241f4c4d43
<ide><path>client/src/components/Supporters.js <ide> function Supporters({ isDonating, activeDonations }) { <ide> them to join the community. <ide> </Fragment> <ide> ) : ( <del> `Join ${donationsLocale} supporters. Your $5 / month` + <add> `Join ${donationsLocale} supporters. Your $5 / month ` + <ide> 'donation will help keep tech education free and open.' <ide> )} <ide> </p>
1
Javascript
Javascript
remove special case for ngif and ngrepeat
5b620653f61ae3d9f1de8346de271752fa12f26f
<ide><path>src/ng/compile.js <ide> function $CompileProvider($provide) { <ide> } <ide> <ide> if (directiveValue = directive.transclude) { <del> // Special case ngRepeat so that we don't complain about duplicate transclusion, ngRepeat <del> // knows how to handle this on its own. <del> if (directiveName !== 'ngRepeat' && directiveName !== 'ngIf') { <add> // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. <add> // This option should only be used by directives that know how to how to safely handle element transclusion, <add> // where the transcluded nodes are added or replaced after linking. <add> if (!directive.$$tlb) { <ide> assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); <ide> transcludeDirective = directive; <ide> } <ide><path>src/ng/directive/ngIf.js <ide> var ngIfDirective = ['$animate', function($animate) { <ide> priority: 600, <ide> terminal: true, <ide> restrict: 'A', <add> $$tlb: true, <ide> compile: function (element, attr, transclude) { <ide> return function ($scope, $element, $attr) { <ide> var block = {}, childScope; <ide><path>src/ng/directive/ngRepeat.js <ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { <ide> transclude: 'element', <ide> priority: 1000, <ide> terminal: true, <add> $$tlb: true, <ide> compile: function(element, attr, linker) { <ide> return function($scope, $element, $attr){ <ide> var expression = $attr.ngRepeat;
3
Ruby
Ruby
handle non-ascii output encoded as ascii
03488424cb8faf5d82f81767fa9a1442d5ce386a
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def run <ide> failure = testcase.add_element 'failure' if step.failed? <ide> if step.has_output? <ide> # Remove invalid XML CData characters from step output. <del> output = REXML::CData.new step.output.delete("\000\a\b\e\f") <add> output = step.output <add> if output.respond_to?(:force_encoding) && !output.valid_encoding? <add> output.force_encoding(Encoding::UTF_8) <add> end <add> output = REXML::CData.new output.delete("\000\a\b\e\f") <ide> if step.passed? <ide> system_out = testcase.add_element 'system-out' <ide> system_out.text = output
1
Ruby
Ruby
apply suggestions from code review
457de40117188880f15a864d1ac3dd437274ea07
<ide><path>Library/Homebrew/extend/os/mac/keg_relocate.rb <ide> def prepare_relocation_to_locations <ide> end <ide> relocation.add_replacement_pair(:perl, PERL_PLACEHOLDER, perl_path) <ide> <del> openjdk = openjdk_dep_name_if_applicable <del> if openjdk <add> if (openjdk = openjdk_dep_name_if_applicable) <ide> openjdk_path = HOMEBREW_PREFIX/"opt"/openjdk/"libexec/openjdk.jdk/Contents/Home" <ide> relocation.add_replacement_pair(:java, JAVA_PLACEHOLDER, openjdk_path.to_s) <ide> end <ide><path>Library/Homebrew/keg_relocate.rb <ide> def prepare_relocation_to_locations <ide> relocation.add_replacement_pair(:repository, REPOSITORY_PLACEHOLDER, HOMEBREW_REPOSITORY.to_s) <ide> relocation.add_replacement_pair(:library, LIBRARY_PLACEHOLDER, HOMEBREW_LIBRARY.to_s) <ide> relocation.add_replacement_pair(:perl, PERL_PLACEHOLDER, "#{HOMEBREW_PREFIX}/opt/perl/bin/perl") <del> openjdk = openjdk_dep_name_if_applicable <del> relocation.add_replacement_pair(:java, JAVA_PLACEHOLDER, "#{HOMEBREW_PREFIX}/opt/#{openjdk}/libexec") if openjdk <add> if (openjdk = openjdk_dep_name_if_applicable) <add> relocation.add_replacement_pair(:java, JAVA_PLACEHOLDER, "#{HOMEBREW_PREFIX}/opt/#{openjdk}/libexec") <add> end <ide> <ide> relocation <ide> end <ide> def replace_placeholders_with_locations(files, skip_linkage: false) <ide> end <ide> <ide> def openjdk_dep_name_if_applicable <del> runtime_dependencies&.find do |dep| <del> dep["full_name"].match? Version.formula_optionally_versioned_regex(:openjdk) <del> end&.fetch("full_name") <add> deps = runtime_dependencies <add> return if deps.blank? <add> <add> dep_names = deps.map { |d| d["full_name"] } <add> dep_names.find { |d| d.match? Version.formula_optionally_versioned_regex(:openjdk) } <ide> end <ide> <ide> def replace_text_in_files(relocation, files: nil)
2
Javascript
Javascript
update sc reference to ember
86edd79b43134c8d20490b6979f6a21f8b77b39c
<ide><path>packages/ember-states/tests/state_manager_test.js <ide> test("it automatically transitions to a default state specified using the initia <ide> }); <ide> <ide> test("it reports the view associated with the current view state, if any", function() { <del> var view = SC.View.create(); <add> var view = Ember.View.create(); <ide> <del> stateManager = SC.StateManager.create({ <del> foo: SC.ViewState.create({ <add> stateManager = Ember.StateManager.create({ <add> foo: Ember.ViewState.create({ <ide> view: view, <del> bar: SC.State.create() <add> bar: Ember.State.create() <ide> }) <ide> }); <ide>
1
Javascript
Javascript
have faith in var hoisting
af95b35f27a16a9e1714c5e8efd2cd79e3f56b42
<ide><path>src/test/all.js <ide> require("./mock-timers"); <ide> <ide> exports.enableTest = function(testID) { <ide> describe(testID, function() { <del> var mockMap; <ide> beforeEach(function() { <ide> require("mock-modules").setMockMap(mockMap); <ide> }); <ide> <ide> require("mock-modules").clearMockMap(); <ide> require("../" + testID); <del> mockMap = require("mock-modules").getMockMap(); <add> var mockMap = require("mock-modules").getMockMap(); <ide> }); <ide> }; <ide>
1
Go
Go
fix minor typo
d56c2ea9edf0a6f5abfb5be8d241ecf8375054ff
<ide><path>libcontainerd/types_windows.go <ide> type Stats struct{} <ide> // Resources defines updatable container resource values. <ide> type Resources struct{} <ide> <del>// ServicingOption is an empty CreateOption with a no-op application that siginifies <del>// the container needs to be use for a Windows servicing operation. <add>// ServicingOption is an empty CreateOption with a no-op application that signifies <add>// the container needs to be used for a Windows servicing operation. <ide> type ServicingOption struct { <ide> IsServicing bool <ide> }
1
Go
Go
remove manifest v2 schema 1 push tests
238180d292a27a4b7b7bb669867e04236b4acc43
<ide><path>integration-cli/docker_cli_push_test.go <ide> import ( <ide> "gotest.tools/v3/icmd" <ide> ) <ide> <del>// Pushing an image to a private registry. <del>func testPushBusyboxImage(c *testing.T) { <add>func (s *DockerRegistrySuite) TestPushBusyboxImage(c *testing.T) { <ide> repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) <ide> // tag the image to upload it to the private registry <ide> dockerCmd(c, "tag", "busybox", repoName) <ide> // push the image to the registry <ide> dockerCmd(c, "push", repoName) <ide> } <ide> <del>func (s *DockerRegistrySuite) TestPushBusyboxImage(c *testing.T) { <del> testPushBusyboxImage(c) <del>} <del> <del>func (s *DockerSchema1RegistrySuite) TestPushBusyboxImage(c *testing.T) { <del> testPushBusyboxImage(c) <del>} <del> <ide> // pushing an image without a prefix should throw an error <ide> func (s *DockerSuite) TestPushUnprefixedRepo(c *testing.T) { <ide> out, _, err := dockerCmdWithError("push", "busybox") <ide> assert.ErrorContains(c, err, "", "pushing an unprefixed repo didn't result in a non-zero exit status: %s", out) <ide> } <ide> <del>func testPushUntagged(c *testing.T) { <add>func (s *DockerRegistrySuite) TestPushUntagged(c *testing.T) { <ide> repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) <ide> expected := "An image does not exist locally with the tag" <ide> <ide> func testPushUntagged(c *testing.T) { <ide> assert.Assert(c, strings.Contains(out, expected), "pushing the image failed") <ide> } <ide> <del>func (s *DockerRegistrySuite) TestPushUntagged(c *testing.T) { <del> testPushUntagged(c) <del>} <del> <del>func (s *DockerSchema1RegistrySuite) TestPushUntagged(c *testing.T) { <del> testPushUntagged(c) <del>} <del> <del>func testPushBadTag(c *testing.T) { <add>func (s *DockerRegistrySuite) TestPushBadTag(c *testing.T) { <ide> repoName := fmt.Sprintf("%v/dockercli/busybox:latest", privateRegistryURL) <ide> expected := "does not exist" <ide> <ide> func testPushBadTag(c *testing.T) { <ide> assert.Assert(c, strings.Contains(out, expected), "pushing the image failed") <ide> } <ide> <del>func (s *DockerRegistrySuite) TestPushBadTag(c *testing.T) { <del> testPushBadTag(c) <del>} <del> <del>func (s *DockerSchema1RegistrySuite) TestPushBadTag(c *testing.T) { <del> testPushBadTag(c) <del>} <del> <del>func testPushMultipleTags(c *testing.T) { <add>func (s *DockerRegistrySuite) TestPushMultipleTags(c *testing.T) { <ide> repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) <ide> repoTag1 := fmt.Sprintf("%v/dockercli/busybox:t1", privateRegistryURL) <ide> repoTag2 := fmt.Sprintf("%v/dockercli/busybox:t2", privateRegistryURL) <ide> func testPushMultipleTags(c *testing.T) { <ide> assert.DeepEqual(c, out1Lines, out2Lines) <ide> } <ide> <del>func (s *DockerRegistrySuite) TestPushMultipleTags(c *testing.T) { <del> testPushMultipleTags(c) <del>} <del> <del>func (s *DockerSchema1RegistrySuite) TestPushMultipleTags(c *testing.T) { <del> testPushMultipleTags(c) <del>} <del> <del>func testPushEmptyLayer(c *testing.T) { <add>func (s *DockerRegistrySuite) TestPushEmptyLayer(c *testing.T) { <ide> repoName := fmt.Sprintf("%v/dockercli/emptylayer", privateRegistryURL) <ide> emptyTarball, err := os.CreateTemp("", "empty_tarball") <ide> assert.NilError(c, err, "Unable to create test file") <ide> func testPushEmptyLayer(c *testing.T) { <ide> assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out) <ide> } <ide> <del>func (s *DockerRegistrySuite) TestPushEmptyLayer(c *testing.T) { <del> testPushEmptyLayer(c) <del>} <del> <del>func (s *DockerSchema1RegistrySuite) TestPushEmptyLayer(c *testing.T) { <del> testPushEmptyLayer(c) <del>} <del> <del>// testConcurrentPush pushes multiple tags to the same repo <add>// TestConcurrentPush pushes multiple tags to the same repo <ide> // concurrently. <del>func testConcurrentPush(c *testing.T) { <add>func (s *DockerRegistrySuite) TestConcurrentPush(c *testing.T) { <ide> repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) <ide> <ide> var repos []string <ide> func testConcurrentPush(c *testing.T) { <ide> } <ide> } <ide> <del>func (s *DockerRegistrySuite) TestConcurrentPush(c *testing.T) { <del> testConcurrentPush(c) <del>} <del> <del>func (s *DockerSchema1RegistrySuite) TestConcurrentPush(c *testing.T) { <del> testConcurrentPush(c) <del>} <del> <ide> func (s *DockerRegistrySuite) TestCrossRepositoryLayerPush(c *testing.T) { <ide> sourceRepoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) <ide> // tag the image to upload it to the private registry <ide> func (s *DockerRegistrySuite) TestCrossRepositoryLayerPush(c *testing.T) { <ide> assert.Equal(c, out4, "hello world") <ide> } <ide> <del>func (s *DockerSchema1RegistrySuite) TestCrossRepositoryLayerPushNotSupported(c *testing.T) { <del> sourceRepoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) <del> // tag the image to upload it to the private registry <del> dockerCmd(c, "tag", "busybox", sourceRepoName) <del> // push the image to the registry <del> out1, _, err := dockerCmdWithError("push", sourceRepoName) <del> assert.NilError(c, err, fmt.Sprintf("pushing the image to the private registry has failed: %s", out1)) <del> // ensure that none of the layers were mounted from another repository during push <del> assert.Assert(c, !strings.Contains(out1, "Mounted from")) <del> <del> digest1 := reference.DigestRegexp.FindString(out1) <del> assert.Assert(c, len(digest1) > 0, "no digest found for pushed manifest") <del> <del> destRepoName := fmt.Sprintf("%v/dockercli/crossrepopush", privateRegistryURL) <del> // retag the image to upload the same layers to another repo in the same registry <del> dockerCmd(c, "tag", "busybox", destRepoName) <del> // push the image to the registry <del> out2, _, err := dockerCmdWithError("push", destRepoName) <del> assert.NilError(c, err, fmt.Sprintf("pushing the image to the private registry has failed: %s", out2)) <del> // schema1 registry should not support cross-repo layer mounts, so ensure that this does not happen <del> assert.Assert(c, !strings.Contains(out2, "Mounted from")) <del> <del> digest2 := reference.DigestRegexp.FindString(out2) <del> assert.Assert(c, len(digest2) > 0, "no digest found for pushed manifest") <del> assert.Assert(c, digest1 != digest2) <del> <del> // ensure that we can pull and run the second pushed repository <del> dockerCmd(c, "rmi", destRepoName) <del> dockerCmd(c, "pull", destRepoName) <del> out3, _ := dockerCmd(c, "run", destRepoName, "echo", "-n", "hello world") <del> assert.Assert(c, out3 == "hello world") <del>} <del> <ide> func (s *DockerRegistryAuthHtpasswdSuite) TestPushNoCredentialsNoRetry(c *testing.T) { <ide> repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) <ide> dockerCmd(c, "tag", "busybox", repoName)
1
Javascript
Javascript
make tls.checkserveridentity() more strict
c34e58e68416b34a976dfae72c7123b3b334a6b0
<ide><path>lib/tls.js <ide> exports.convertALPNProtocols = function(protocols, out) { <ide> } <ide> }; <ide> <del>exports.checkServerIdentity = function checkServerIdentity(host, cert) { <del> // Create regexp to much hostnames <del> function regexpify(host, wildcards) { <del> // Add trailing dot (make hostnames uniform) <del> if (!host || !host.endsWith('.')) host += '.'; <del> <del> // The same applies to hostname with more than one wildcard, <del> // if hostname has wildcard when wildcards are not allowed, <del> // or if there are less than two dots after wildcard (i.e. *.com or *d.com) <del> // <del> // also <del> // <del> // "The client SHOULD NOT attempt to match a presented identifier in <del> // which the wildcard character comprises a label other than the <del> // left-most label (e.g., do not match bar.*.example.net)." <del> // RFC6125 <del> if (!wildcards && /\*/.test(host) || /[\.\*].*\*/.test(host) || <del> /\*/.test(host) && !/\*.*\..+\..+/.test(host)) { <del> return /$./; <del> } <add>function unfqdn(host) { <add> return host.replace(/[.]$/, ''); <add>} <ide> <del> // Replace wildcard chars with regexp's wildcard and <del> // escape all characters that have special meaning in regexps <del> // (i.e. '.', '[', '{', '*', and others) <del> var re = host.replace( <del> /\*([a-z0-9\\-_\.])|[\.,\-\\\^\$+?*\[\]\(\):!\|{}]/g, <del> function(all, sub) { <del> if (sub) return '[a-z0-9\\-_]*' + (sub === '-' ? '\\-' : sub); <del> return '\\' + all; <del> }); <del> <del> return new RegExp('^' + re + '$', 'i'); <del> } <add>function splitHost(host) { <add> // String#toLowerCase() is locale-sensitive so we use <add> // a conservative version that only lowercases A-Z. <add> const replacer = (c) => String.fromCharCode(32 + c.charCodeAt(0)); <add> return unfqdn(host).replace(/[A-Z]/g, replacer).split('.'); <add>} <add> <add>function check(hostParts, pattern, wildcards) { <add> // Empty strings, null, undefined, etc. never match. <add> if (!pattern) <add> return false; <add> <add> const patternParts = splitHost(pattern); <add> <add> if (hostParts.length !== patternParts.length) <add> return false; <add> <add> // Pattern has empty components, e.g. "bad..example.com". <add> if (patternParts.includes('')) <add> return false; <add> <add> // RFC 6125 allows IDNA U-labels (Unicode) in names but we have no <add> // good way to detect their encoding or normalize them so we simply <add> // reject them. Control characters and blanks are rejected as well <add> // because nothing good can come from accepting them. <add> const isBad = (s) => /[^\u0021-\u007F]/u.test(s); <add> if (patternParts.some(isBad)) <add> return false; <add> <add> // Check host parts from right to left first. <add> for (let i = hostParts.length - 1; i > 0; i -= 1) <add> if (hostParts[i] !== patternParts[i]) <add> return false; <add> <add> const hostSubdomain = hostParts[0]; <add> const patternSubdomain = patternParts[0]; <add> const patternSubdomainParts = patternSubdomain.split('*'); <add> <add> // Short-circuit when the subdomain does not contain a wildcard. <add> // RFC 6125 does not allow wildcard substitution for components <add> // containing IDNA A-labels (Punycode) so match those verbatim. <add> if (patternSubdomainParts.length === 1 || patternSubdomain.includes('xn--')) <add> return hostSubdomain === patternSubdomain; <add> <add> if (!wildcards) <add> return false; <add> <add> // More than one wildcard is always wrong. <add> if (patternSubdomainParts.length > 2) <add> return false; <add> <add> // *.tld wildcards are not allowed. <add> if (patternParts.length <= 2) <add> return false; <add> <add> const [prefix, suffix] = patternSubdomainParts; <add> <add> if (prefix.length + suffix.length > hostSubdomain.length) <add> return false; <ide> <del> var dnsNames = []; <del> var uriNames = []; <add> if (!hostSubdomain.startsWith(prefix)) <add> return false; <add> <add> if (!hostSubdomain.endsWith(suffix)) <add> return false; <add> <add> return true; <add>} <add> <add>exports.checkServerIdentity = function checkServerIdentity(host, cert) { <add> const subject = cert.subject; <add> const altNames = cert.subjectaltname; <add> const dnsNames = []; <add> const uriNames = []; <ide> const ips = []; <del> var matchCN = true; <del> var valid = false; <del> var reason = 'Unknown reason'; <del> <del> // There're several names to perform check against: <del> // CN and altnames in certificate extension <del> // (DNS names, IP addresses, and URIs) <del> // <del> // Walk through altnames and generate lists of those names <del> if (cert.subjectaltname) { <del> cert.subjectaltname.split(/, /g).forEach(function(altname) { <del> var option = altname.match(/^(DNS|IP Address|URI):(.*)$/); <del> if (!option) <del> return; <del> if (option[1] === 'DNS') { <del> dnsNames.push(option[2]); <del> } else if (option[1] === 'IP Address') { <del> ips.push(option[2]); <del> } else if (option[1] === 'URI') { <del> var uri = url.parse(option[2]); <del> if (uri) uriNames.push(uri.hostname); <del> } <del> }); <del> } <ide> <del> // If hostname is an IP address, it should be present in the list of IP <del> // addresses. <del> if (net.isIP(host)) { <del> valid = ips.some(function(ip) { <del> return ip === host; <del> }); <del> if (!valid) { <del> reason = `IP: ${host} is not in the cert's list: ${ips.join(', ')}`; <del> } <del> } else if (cert.subject) { <del> // Transform hostname to canonical form <del> if (!host || !host.endsWith('.')) host += '.'; <del> <del> // Otherwise check all DNS/URI records from certificate <del> // (with allowed wildcards) <del> dnsNames = dnsNames.map(function(name) { <del> return regexpify(name, true); <del> }); <del> <del> // Wildcards ain't allowed in URI names <del> uriNames = uriNames.map(function(name) { <del> return regexpify(name, false); <del> }); <del> <del> dnsNames = dnsNames.concat(uriNames); <del> <del> if (dnsNames.length > 0) matchCN = false; <del> <del> // Match against Common Name (CN) only if no supported identifiers are <del> // present. <del> // <del> // "As noted, a client MUST NOT seek a match for a reference identifier <del> // of CN-ID if the presented identifiers include a DNS-ID, SRV-ID, <del> // URI-ID, or any application-specific identifier types supported by the <del> // client." <del> // RFC6125 <del> if (matchCN) { <del> var commonNames = cert.subject.CN; <del> if (Array.isArray(commonNames)) { <del> for (var i = 0, k = commonNames.length; i < k; ++i) { <del> dnsNames.push(regexpify(commonNames[i], true)); <del> } <del> } else { <del> dnsNames.push(regexpify(commonNames, true)); <add> host = '' + host; <add> <add> if (altNames) { <add> for (const name of altNames.split(', ')) { <add> if (name.startsWith('DNS:')) { <add> dnsNames.push(name.slice(4)); <add> } else if (name.startsWith('URI:')) { <add> const uri = url.parse(name.slice(4)); <add> uriNames.push(uri.hostname); // TODO(bnoordhuis) Also use scheme. <add> } else if (name.startsWith('IP Address:')) { <add> ips.push(name.slice(11)); <ide> } <ide> } <add> } <ide> <del> valid = dnsNames.some(function(re) { <del> return re.test(host); <del> }); <add> let valid = false; <add> let reason = 'Unknown reason'; <ide> <del> if (!valid) { <del> if (cert.subjectaltname) { <del> reason = <del> `Host: ${host} is not in the cert's altnames: ` + <del> `${cert.subjectaltname}`; <del> } else { <del> reason = `Host: ${host} is not cert's CN: ${cert.subject.CN}`; <del> } <add> if (net.isIP(host)) { <add> valid = ips.includes(host); <add> if (!valid) <add> reason = `IP: ${host} is not in the cert's list: ${ips.join(', ')}`; <add> // TODO(bnoordhuis) Also check URI SANs that are IP addresses. <add> } else if (subject) { <add> host = unfqdn(host); // Remove trailing dot for error messages. <add> const hostParts = splitHost(host); <add> const wildcard = (pattern) => check(hostParts, pattern, true); <add> const noWildcard = (pattern) => check(hostParts, pattern, false); <add> <add> // Match against Common Name only if no supported identifiers are present. <add> if (dnsNames.length === 0 && ips.length === 0 && uriNames.length === 0) { <add> const cn = subject.CN; <add> <add> if (Array.isArray(cn)) <add> valid = cn.some(wildcard); <add> else if (cn) <add> valid = wildcard(cn); <add> <add> if (!valid) <add> reason = `Host: ${host}. is not cert's CN: ${cn}`; <add> } else { <add> valid = dnsNames.some(wildcard) || uriNames.some(noWildcard); <add> if (!valid) <add> reason = `Host: ${host}. is not in the cert's altnames: ${altNames}`; <ide> } <ide> } else { <ide> reason = 'Cert is empty'; <ide> } <ide> <ide> if (!valid) { <del> var err = new Error( <add> const err = new Error( <ide> `Hostname/IP doesn't match certificate's altnames: "${reason}"`); <ide> err.reason = reason; <ide> err.host = host; <ide><path>test/parallel/test-tls-check-server-identity.js <ide> var tls = require('tls'); <ide> <ide> <ide> var tests = [ <add> // False-y values. <add> { <add> host: false, <add> cert: { subject: { CN: 'a.com' } }, <add> error: 'Host: false. is not cert\'s CN: a.com' <add> }, <add> { <add> host: null, <add> cert: { subject: { CN: 'a.com' } }, <add> error: 'Host: null. is not cert\'s CN: a.com' <add> }, <add> { <add> host: undefined, <add> cert: { subject: { CN: 'a.com' } }, <add> error: 'Host: undefined. is not cert\'s CN: a.com' <add> }, <add> <ide> // Basic CN handling <ide> { host: 'a.com', cert: { subject: { CN: 'a.com' } } }, <ide> { host: 'a.com', cert: { subject: { CN: 'A.COM' } } }, <ide> var tests = [ <ide> error: 'Host: a.com. is not cert\'s CN: b.com' <ide> }, <ide> { host: 'a.com', cert: { subject: { CN: 'a.com.' } } }, <add> { <add> host: 'a.com', <add> cert: { subject: { CN: '.a.com' } }, <add> error: 'Host: a.com. is not cert\'s CN: .a.com' <add> }, <ide> <ide> // Wildcards in CN <ide> { host: 'b.a.com', cert: { subject: { CN: '*.a.com' } } }, <add> { <add> host: 'ba.com', <add> cert: { subject: { CN: '*.a.com' } }, <add> error: 'Host: ba.com. is not cert\'s CN: *.a.com' <add> }, <add> { <add> host: '\n.b.com', <add> cert: { subject: { CN: '*n.b.com' } }, <add> error: 'Host: \n.b.com. is not cert\'s CN: *n.b.com' <add> }, <ide> { host: 'b.a.com', cert: { <ide> subjectaltname: 'DNS:omg.com', <ide> subject: { CN: '*.a.com' } }, <ide> error: 'Host: b.a.com. is not in the cert\'s altnames: ' + <ide> 'DNS:omg.com' <ide> }, <add> { <add> host: 'b.a.com', <add> cert: { subject: { CN: 'b*b.a.com' } }, <add> error: 'Host: b.a.com. is not cert\'s CN: b*b.a.com' <add> }, <ide> <ide> // Empty Cert <ide> { <ide> var tests = [ <ide> error: 'Host: localhost. is not in the cert\'s altnames: ' + <ide> 'DNS:a.com' <ide> }, <add> // IDNA <add> { <add> host: 'xn--bcher-kva.example.com', <add> cert: { subject: { CN: '*.example.com' } }, <add> }, <add> // RFC 6125, section 6.4.3: "[...] the client SHOULD NOT attempt to match <add> // a presented identifier where the wildcard character is embedded within <add> // an A-label [...]" <add> { <add> host: 'xn--bcher-kva.example.com', <add> cert: { subject: { CN: 'xn--*.example.com' } }, <add> error: 'Host: xn--bcher-kva.example.com. is not cert\'s CN: ' + <add> 'xn--*.example.com', <add> }, <ide> ]; <ide> <ide> tests.forEach(function(test, i) {
2
Ruby
Ruby
remove redundant namespacing
33ce424399b429be79c8cc6f009fd14530350721
<ide><path>Library/Homebrew/cask/audit.rb <ide> def check_untrusted_pkg <ide> return if tap.nil? <ide> return if tap.user != "Homebrew" <ide> <del> return unless cask.artifacts.any? { |k| k.is_a?(Hbc::Artifact::Pkg) && k.stanza_options.key?(:allow_untrusted) } <add> return unless cask.artifacts.any? { |k| k.is_a?(Artifact::Pkg) && k.stanza_options.key?(:allow_untrusted) } <ide> add_warning "allow_untrusted is not permitted in official Homebrew Cask taps" <ide> end <ide> <ide> def check_stanza_requires_uninstall <ide> odebug "Auditing stanzas which require an uninstall" <ide> <del> return if cask.artifacts.none? { |k| k.is_a?(Hbc::Artifact::Pkg) || k.is_a?(Hbc::Artifact::Installer) } <del> return if cask.artifacts.any? { |k| k.is_a?(Hbc::Artifact::Uninstall) } <add> return if cask.artifacts.none? { |k| k.is_a?(Artifact::Pkg) || k.is_a?(Artifact::Installer) } <add> return if cask.artifacts.any? { |k| k.is_a?(Artifact::Uninstall) } <ide> add_warning "installer and pkg stanzas require an uninstall stanza" <ide> end <ide> <ide> def check_single_pre_postflight <ide> odebug "Auditing preflight and postflight stanzas" <ide> <del> if cask.artifacts.count { |k| k.is_a?(Hbc::Artifact::PreflightBlock) && k.directives.key?(:preflight) } > 1 <add> if cask.artifacts.count { |k| k.is_a?(Artifact::PreflightBlock) && k.directives.key?(:preflight) } > 1 <ide> add_warning "only a single preflight stanza is allowed" <ide> end <ide> <ide> count = cask.artifacts.count do |k| <del> k.is_a?(Hbc::Artifact::PostflightBlock) && <add> k.is_a?(Artifact::PostflightBlock) && <ide> k.directives.key?(:postflight) <ide> end <ide> return unless count > 1 <ide> def check_single_pre_postflight <ide> def check_single_uninstall_zap <ide> odebug "Auditing single uninstall_* and zap stanzas" <ide> <del> if cask.artifacts.count { |k| k.is_a?(Hbc::Artifact::Uninstall) } > 1 <add> if cask.artifacts.count { |k| k.is_a?(Artifact::Uninstall) } > 1 <ide> add_warning "only a single uninstall stanza is allowed" <ide> end <ide> <ide> count = cask.artifacts.count do |k| <del> k.is_a?(Hbc::Artifact::PreflightBlock) && <add> k.is_a?(Artifact::PreflightBlock) && <ide> k.directives.key?(:uninstall_preflight) <ide> end <ide> <ide> def check_single_uninstall_zap <ide> end <ide> <ide> count = cask.artifacts.count do |k| <del> k.is_a?(Hbc::Artifact::PostflightBlock) && <add> k.is_a?(Artifact::PostflightBlock) && <ide> k.directives.key?(:uninstall_postflight) <ide> end <ide> <ide> if count > 1 <ide> add_warning "only a single uninstall_postflight stanza is allowed" <ide> end <ide> <del> return unless cask.artifacts.count { |k| k.is_a?(Hbc::Artifact::Zap) } > 1 <add> return unless cask.artifacts.count { |k| k.is_a?(Artifact::Zap) } > 1 <ide> add_warning "only a single zap stanza is allowed" <ide> end <ide> <ide> def bad_osdn_url? <ide> end <ide> <ide> def check_generic_artifacts <del> cask.artifacts.select { |a| a.is_a?(Hbc::Artifact::Artifact) }.each do |artifact| <add> cask.artifacts.select { |a| a.is_a?(Artifact::Artifact) }.each do |artifact| <ide> unless artifact.target.absolute? <ide> add_error "target must be absolute path for #{artifact.class.english_name} #{artifact.source}" <ide> end <ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/generic-artifact-absolute-target.rb <ide> cask 'generic-artifact-absolute-target' do <del> artifact 'Caffeine.app', target: "#{Hbc::Config.global.appdir}/Caffeine.app" <add> artifact 'Caffeine.app', target: "#{appdir}/Caffeine.app" <ide> end <ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-generic-artifact.rb <ide> url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip" <ide> homepage 'https://example.com/with-generic-artifact' <ide> <del> artifact 'Caffeine.app', target: "#{Hbc::Config.global.appdir}/Caffeine.app" <add> artifact 'Caffeine.app', target: "#{appdir}/Caffeine.app" <ide> end
3
Ruby
Ruby
read runtime dependencies from more tabs
191724ce83b165479e2663625cf18ef4b50c11ee
<ide><path>Library/Homebrew/formula.rb <ide> def opt_or_installed_prefix_keg <ide> # @private <ide> def runtime_dependencies(read_from_tab: true) <ide> if read_from_tab && <del> installed_prefix.directory? && <ide> (keg = opt_or_installed_prefix_keg) && <ide> (tab_deps = keg.runtime_dependencies) <ide> return tab_deps.map { |d| Dependency.new d["full_name"] }.compact
1
Javascript
Javascript
stop editor competing with modal for focus
c483940da090d3ded148dfc6c179f6d6d352a768
<ide><path>client/src/templates/Challenges/classic/Editor.js <ide> import { connect } from 'react-redux'; <ide> import { createSelector } from 'reselect'; <ide> <ide> import { executeChallenge, updateFile } from '../redux'; <del>import { userSelector } from '../../../redux'; <add>import { userSelector, isDonationModalOpenSelector } from '../../../redux'; <ide> import { Loader } from '../../../components/helpers'; <ide> <ide> const MonacoEditor = React.lazy(() => import('react-monaco-editor')); <ide> <ide> const propTypes = { <add> canFocus: PropTypes.bool, <ide> contents: PropTypes.string, <ide> dimensions: PropTypes.object, <ide> executeChallenge: PropTypes.func.isRequired, <ide> const propTypes = { <ide> }; <ide> <ide> const mapStateToProps = createSelector( <add> isDonationModalOpenSelector, <ide> userSelector, <del> ({ theme = 'night' }) => ({ theme }) <add> (open, { theme = 'night' }) => ({ <add> canFocus: !open, <add> theme <add> }) <ide> ); <ide> <ide> const mapDispatchToProps = dispatch => <ide> class Editor extends Component { <ide> <ide> editorDidMount = (editor, monaco) => { <ide> this._editor = editor; <del> this._editor.focus(); <add> if (this.props.canFocus) this._editor.focus(); <ide> this._editor.addAction({ <ide> id: 'execute-challenge', <ide> label: 'Run tests',
1
Python
Python
remove v2 test
5424b70e51277049fac470a5c5458830202d03f0
<ide><path>spacy/tests/test_misc.py <ide> def test_load_model_blank_shortcut(): <ide> util.load_model("blank:fjsfijsdof") <ide> <ide> <del>def test_load_model_version_compat(): <del> """Test warnings for various spacy_version specifications in meta. Since <del> this is more of a hack for v2, manually specify the current major.minor <del> version to simplify test creation.""" <del> nlp = util.load_model("blank:en") <del> assert nlp.meta["spacy_version"].startswith(">=2.3") <del> with make_tempdir() as d: <del> # no change: compatible <del> nlp.to_disk(d) <del> meta_path = Path(d / "meta.json") <del> util.get_model_meta(d) <del> <del> # additional compatible upper pin <del> nlp.meta["spacy_version"] = ">=2.3.0,<2.4.0" <del> srsly.write_json(meta_path, nlp.meta) <del> util.get_model_meta(d) <del> <del> # incompatible older version <del> nlp.meta["spacy_version"] = ">=2.2.5" <del> srsly.write_json(meta_path, nlp.meta) <del> with pytest.warns(UserWarning): <del> util.get_model_meta(d) <del> <del> # invalid version specification <del> nlp.meta["spacy_version"] = ">@#$%_invalid_version" <del> srsly.write_json(meta_path, nlp.meta) <del> with pytest.warns(UserWarning): <del> util.get_model_meta(d) <del> <del> <ide> @pytest.mark.parametrize( <ide> "version,constraint,compatible", <ide> [
1
Ruby
Ruby
add tests which were incorrectly removed
b8d8ce7ba8e5e83e9b41e48fb6ef449bd36a97e3
<ide><path>railties/lib/rails/generators/erb/mailer/mailer_generator.rb <ide> def copy_view_files <ide> @action = action <ide> <ide> formats.each do |format| <del> @view_path = File.join(view_base_path, filename_with_extensions(action, format)) <del> template filename_with_extensions(:view, format), @view_path <add> @path = File.join(view_base_path, filename_with_extensions(action, format)) <add> template filename_with_extensions(:view, format), @path <ide> <del> @layout_path = File.join(layout_base_path, filename_with_extensions("mailer", format)) <del> template filename_with_extensions(:layout, format), @layout_path <add> layout_path = File.join(layout_base_path, filename_with_extensions("mailer", format)) <add> template filename_with_extensions(:layout, format), layout_path <ide> end <ide> end <ide> <ide><path>railties/test/generators/mailer_generator_test.rb <ide> def test_check_preview_class_collision <ide> def test_invokes_default_text_template_engine <ide> run_generator <ide> assert_file "app/views/notifier/foo.text.erb" do |view| <add> assert_match(%r(\sapp/views/notifier/foo\.text\.erb), view) <ide> assert_match(/<%= @greeting %>/, view) <ide> end <ide> <ide> assert_file "app/views/notifier/bar.text.erb" do |view| <add> assert_match(%r(\sapp/views/notifier/bar\.text\.erb), view) <ide> assert_match(/<%= @greeting %>/, view) <ide> end <ide> <ide> def test_invokes_default_text_template_engine <ide> def test_invokes_default_html_template_engine <ide> run_generator <ide> assert_file "app/views/notifier/foo.html.erb" do |view| <add> assert_match(%r(\sapp/views/notifier/foo\.html\.erb), view) <ide> assert_match(/<%= @greeting %>/, view) <ide> end <ide> <ide> assert_file "app/views/notifier/bar.html.erb" do |view| <add> assert_match(%r(\sapp/views/notifier/bar\.html\.erb), view) <ide> assert_match(/<%= @greeting %>/, view) <ide> end <ide> <ide><path>railties/test/generators/namespaced_generators_test.rb <ide> def test_invokes_default_test_framework <ide> def test_invokes_default_template_engine <ide> run_generator <ide> assert_file "app/views/test_app/notifier/foo.text.erb" do |view| <add> assert_match(%r(app/views/test_app/notifier/foo\.text\.erb), view) <ide> assert_match(/<%= @greeting %>/, view) <ide> end <ide> <ide> assert_file "app/views/test_app/notifier/bar.text.erb" do |view| <add> assert_match(%r(app/views/test_app/notifier/bar\.text\.erb), view) <ide> assert_match(/<%= @greeting %>/, view) <ide> end <ide> end
3
Javascript
Javascript
improve allocation performance
13a4887ee94d61d990dd22100aa7c17c39e3200a
<ide><path>benchmark/buffers/buffer-from.js <ide> const bench = common.createBenchmark(main, { <ide> 'buffer', <ide> 'uint8array', <ide> 'string', <del> 'string-base64' <add> 'string-base64', <add> 'object' <ide> ], <ide> len: [10, 2048], <ide> n: [1024] <ide> function main(conf) { <ide> const str = 'a'.repeat(len); <ide> const buffer = Buffer.allocUnsafe(len); <ide> const uint8array = new Uint8Array(len); <add> const obj = { length: null }; // Results in a new, empty Buffer <ide> <ide> var i; <ide> <ide> function main(conf) { <ide> } <ide> bench.end(n); <ide> break; <add> case 'object': <add> bench.start(); <add> for (i = 0; i < n * 1024; i++) { <add> Buffer.from(obj); <add> } <add> bench.end(n); <add> break; <ide> default: <ide> assert.fail(null, null, 'Should not get here'); <ide> } <ide><path>lib/buffer.js <ide> Buffer.from = function(value, encodingOrOffset, length) { <ide> <ide> Object.setPrototypeOf(Buffer, Uint8Array); <ide> <add>// The 'assertSize' method will remove itself from the callstack when an error <add>// occurs. This is done simply to keep the internal details of the <add>// implementation from bleeding out to users. <ide> function assertSize(size) { <ide> let err = null; <ide> <ide> function assertSize(size) { <ide> 'than ' + binding.kMaxLength); <ide> <ide> if (err) { <del> // The following hides the 'assertSize' method from the <del> // callstack. This is done simply to hide the internal <del> // details of the implementation from bleeding out to users. <ide> Error.captureStackTrace(err, assertSize); <ide> throw err; <ide> } <ide> function fromObject(obj) { <ide> } <ide> <ide> if (obj) { <del> if ('length' in obj || isArrayBuffer(obj.buffer) || <add> if (obj.length !== undefined || isArrayBuffer(obj.buffer) || <ide> isSharedArrayBuffer(obj.buffer)) { <ide> if (typeof obj.length !== 'number' || obj.length !== obj.length) { <ide> return new FastBuffer();
2
Python
Python
clarify docs of np.resize()
2eb0b12b75363f539870a09e155bf8e7a6ca8afa
<ide><path>numpy/core/fromnumeric.py <ide> def resize(a, new_shape): <ide> reshaped_array : ndarray <ide> The new array is formed from the data in the old array, repeated <ide> if necessary to fill out the required number of elements. The <del> data are repeated in the order that they are stored in memory. <add> data are repeated iterating over the array in C-order. <ide> <ide> See Also <ide> -------- <ide> def resize(a, new_shape): <ide> <ide> Warning: This functionality does **not** consider axes separately, <ide> i.e. it does not apply interpolation/extrapolation. <del> It fills the return array with the required number of elements, taken <del> from `a` as they are laid out in memory, disregarding strides and axes. <del> (This is in case the new shape is smaller. For larger, see above.) <del> This functionality is therefore not suitable to resize images, <del> or data where each axis represents a separate and distinct entity. <add> It fills the return array with the required number of elements, iterating <add> over `a` in C-order, disregarding axes (and cycling back from the start if <add> the new shape is larger). This functionality is therefore not suitable to <add> resize images, or data where each axis represents a separate and distinct <add> entity. <ide> <ide> Examples <ide> --------
1
Java
Java
use unmodifiable set in abstractsockjssession
b42f258c54c84fe268002394ce37d8a2b8aed83d
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java <ide> import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.Date; <del>import java.util.HashMap; <add>import java.util.HashSet; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Set; <ide> import org.springframework.web.socket.sockjs.transport.SockJsSession; <ide> <ide> /** <del> * An abstract base class SockJS sessions implementing {@link SockJsSession}. <del> * <add> * An abstract base class for SockJS sessions implementing {@link SockJsSession}. <add> * <ide> * @author Rossen Stoyanchev <add> * @author Sam Brannen <ide> * @since 4.0 <ide> */ <ide> public abstract class AbstractSockJsSession implements SockJsSession { <ide> public abstract class AbstractSockJsSession implements SockJsSession { <ide> */ <ide> protected static final Log disconnectedClientLogger = LogFactory.getLog(DISCONNECTED_CLIENT_LOG_CATEGORY); <ide> <del> <del> private final static Set<String> disconnectedClientExceptions = <del> Collections.newSetFromMap(new HashMap<String, Boolean>(2)); <add> private static final Set<String> disconnectedClientExceptions; <ide> <ide> static { <del> disconnectedClientExceptions.add("ClientAbortException"); // Tomcat <del> disconnectedClientExceptions.add("EofException"); // Jetty <add> Set<String> set = new HashSet<String>(2); <add> set.add("ClientAbortException"); // Tomcat <add> set.add("EofException"); // Jetty <ide> // IOException("Broken pipe") on WildFly and Glassfish <add> disconnectedClientExceptions = Collections.unmodifiableSet(set); <ide> } <ide> <ide>
1
Javascript
Javascript
fix typo in common/index.js
74cd70e568dafefdf16845e2e7738d053456d290
<ide><path>test/common/index.js <ide> const process = global.process; // Some tests tamper with the process global. <ide> const assert = require('assert'); <ide> const { exec, execSync, spawnSync } = require('child_process'); <ide> const fs = require('fs'); <del>// Do not require 'os' until needed so that test-os-checked-fucnction can <add>// Do not require 'os' until needed so that test-os-checked-function can <ide> // monkey patch it. If 'os' is required here, that test will fail. <ide> const path = require('path'); <ide> const util = require('util');
1
Javascript
Javascript
use cmap.foreach instead of array.foreach
b0a8c0fa400d6e236c16f0c733eb0324d38e430f
<ide><path>src/core/evaluator.js <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> if (cmap instanceof IdentityCMap) { <ide> return new IdentityToUnicodeMap(0, 0xFFFF); <ide> } <del> cmap = cmap.getMap(); <add> var map = []; <ide> // Convert UTF-16BE <ide> // NOTE: cmap can be a sparse array, so use forEach instead of for(;;) <ide> // to iterate over all keys. <del> cmap.forEach(function(token, i) { <add> cmap.forEach(function(charCode, token) { <ide> var str = []; <ide> for (var k = 0; k < token.length; k += 2) { <ide> var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1); <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1); <ide> str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000); <ide> } <del> cmap[i] = String.fromCharCode.apply(String, str); <add> map[charCode] = String.fromCharCode.apply(String, str); <ide> }); <del> return new ToUnicodeMap(cmap); <add> return new ToUnicodeMap(map); <ide> } <ide> return null; <ide> },
1
Python
Python
fix pipeline tests
70fa1a8d2652fea2e079bb253fa62d478d00647c
<ide><path>src/transformers/pipelines/__init__.py <ide> def pipeline( <ide> <ide> # Retrieve the task <ide> if task in custom_tasks: <add> normalized_task = task <ide> targeted_task, task_options = clean_custom_task(custom_tasks[task]) <ide> if pipeline_class is None: <ide> if not trust_remote_code: <ide><path>tests/pipelines/test_pipelines_common.py <ide> def test_warning_logs(self): <ide> alias = "text-classification" <ide> # Get the original task, so we can restore it at the end. <ide> # (otherwise the subsequential tests in `TextClassificationPipelineTests` will fail) <del> original_task, original_task_options = PIPELINE_REGISTRY.check_task(alias) <add> _, original_task, _ = PIPELINE_REGISTRY.check_task(alias) <ide> <ide> try: <ide> with CaptureLogger(logger_) as cm: <ide> def test_register_pipeline(self): <ide> ) <ide> assert "custom-text-classification" in PIPELINE_REGISTRY.get_supported_tasks() <ide> <del> task_def, _ = PIPELINE_REGISTRY.check_task("custom-text-classification") <add> _, task_def, _ = PIPELINE_REGISTRY.check_task("custom-text-classification") <ide> self.assertEqual(task_def["pt"], (AutoModelForSequenceClassification,) if is_torch_available() else ()) <ide> self.assertEqual(task_def["tf"], (TFAutoModelForSequenceClassification,) if is_tf_available() else ()) <ide> self.assertEqual(task_def["type"], "text") <ide><path>utils/tests_fetcher.py <ide> def create_reverse_dependency_map(): <ide> ], <ide> "optimization.py": "optimization/test_optimization.py", <ide> "optimization_tf.py": "optimization/test_optimization_tf.py", <add> "pipelines/__init__.py": "pipelines/test_pipelines_*.py", <ide> "pipelines/base.py": "pipelines/test_pipelines_*.py", <ide> "pipelines/text2text_generation.py": [ <ide> "pipelines/test_pipelines_text2text_generation.py",
3
Text
Text
fix nits in dgram.md
ddcd2359f4adc9fe34e793ad5c1ed33ce500eed7
<ide><path>doc/api/dgram.md <ide> properties. <ide> ### socket.bind([port][, address][, callback]) <ide> <!-- YAML <ide> added: v0.1.99 <add>changes: <add> - version: v0.10 <add> description: The method was changed to an asynchronous execution model. <add> Legacy code would need to be changed to pass a callback <add> function to the method call. <ide> --> <ide> <ide> * `port` {integer} <ide> Specifying both a `'listening'` event listener and passing a <ide> useful. <ide> <ide> The `options` object may contain an additional `exclusive` property that is <del>used when using `dgram.Socket` objects with the [`cluster`] module. When <add>used when using `dgram.Socket` objects with the [`cluster`][] module. When <ide> `exclusive` is set to `false` (the default), cluster workers will use the same <ide> underlying socket handle allowing connection handling duties to be shared. <ide> When `exclusive` is `true`, however, the handle is not shared and attempted <ide> added: v8.7.0 <ide> added: v0.9.1 <ide> --> <ide> <add>* Returns: {dgram.Socket} <add> <ide> By default, binding a socket will cause it to block the Node.js process from <ide> exiting as long as the socket is open. The `socket.unref()` method can be used <ide> to exclude the socket from the reference counting that keeps the Node.js <ide> client.connect(41234, 'localhost', (err) => { <ide> }); <ide> ``` <ide> <del>**A Note about UDP datagram size** <add>#### Note about UDP datagram size <ide> <ide> The maximum size of an `IPv4/v6` datagram depends on the `MTU` <ide> (_Maximum Transmission Unit_) and on the `Payload Length` field size. <ide> The default on most systems is 64 but can vary. <ide> added: v0.9.1 <ide> --> <ide> <add>* Returns: {dgram.Socket} <add> <ide> By default, binding a socket will cause it to block the Node.js process from <ide> exiting as long as the socket is open. The `socket.unref()` method can be used <ide> to exclude the socket from the reference counting that keeps the Node.js <ide> Calling `socket.unref()` multiple times will have no addition effect. <ide> The `socket.unref()` method returns a reference to the socket so calls can be <ide> chained. <ide> <del>### Change to asynchronous `socket.bind()` behavior <del> <del>As of Node.js v0.10, [`dgram.Socket#bind()`][] changed to an asynchronous <del>execution model. Legacy code would use synchronous behavior: <del> <del>```js <del>const s = dgram.createSocket('udp4'); <del>s.bind(1234); <del>s.addMembership('224.0.0.114'); <del>``` <del> <del>Such legacy code would need to be changed to pass a callback function to the <del>[`dgram.Socket#bind()`][] function: <del> <del>```js <del>const s = dgram.createSocket('udp4'); <del>s.bind(1234, () => { <del> s.addMembership('224.0.0.114'); <del>}); <del>``` <del> <ide> ## `dgram` module functions <ide> <ide> ### dgram.createSocket(options[, callback]) <ide> added: v0.1.99 <ide> * `callback` {Function} - Attached as a listener to `'message'` events. <ide> * Returns: {dgram.Socket} <ide> <del>Creates a `dgram.Socket` object of the specified `type`. The `type` argument <del>can be either `'udp4'` or `'udp6'`. An optional `callback` function can be <del>passed which is added as a listener for `'message'` events. <add>Creates a `dgram.Socket` object of the specified `type`. <ide> <ide> Once the socket is created, calling [`socket.bind()`][] will instruct the <ide> socket to begin listening for datagram messages. When `address` and `port` are <ide> and `udp6` sockets). The bound address and port can be retrieved using <ide> [`socket.address().address`][] and [`socket.address().port`][]. <ide> <ide> [`'close'`]: #dgram_event_close <del>[`Error`]: errors.html#errors_class_error <ide> [`ERR_SOCKET_DGRAM_IS_CONNECTED`]: errors.html#errors_err_socket_dgram_is_connected <ide> [`ERR_SOCKET_DGRAM_NOT_CONNECTED`]: errors.html#errors_err_socket_dgram_not_connected <add>[`Error`]: errors.html#errors_class_error <ide> [`System Error`]: errors.html#errors_class_systemerror <ide> [`close()`]: #dgram_socket_close_callback <ide> [`cluster`]: cluster.html <ide> [`connect()`]: #dgram_socket_connect_port_address_callback <del>[`dgram.Socket#bind()`]: #dgram_socket_bind_options_callback <ide> [`dgram.createSocket()`]: #dgram_dgram_createsocket_options_callback <ide> [`dns.lookup()`]: dns.html#dns_dns_lookup_hostname_options_callback <ide> [`socket.address().address`]: #dgram_socket_address
1
Java
Java
upgrade test to hibernate 5.2
016fa0eb39ac38d95f90bf62bce69aebf17c8f3e
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/orm/repository/hibernate/HibernatePersonRepository.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public Person save(Person person) { <ide> @Override <ide> public Person findByName(String name) { <ide> return (Person) this.sessionFactory.getCurrentSession().createQuery( <del> "from Person person where person.name = :name").setString("name", name).uniqueResult(); <add> "from Person person where person.name = :name").setParameter("name", name).getSingleResult(); <ide> } <add> <ide> }
1
Ruby
Ruby
add generic flag. (#212)
bb7226060681d287619981940a78302beed1c1d6
<ide><path>Library/Homebrew/cmd/tests.rb <ide> def tests <ide> ENV["HOMEBREW_NO_ANALYTICS_THIS_RUN"] = "1" <ide> ENV["TESTOPTS"] = "-v" if ARGV.verbose? <ide> ENV["HOMEBREW_NO_COMPAT"] = "1" if ARGV.include? "--no-compat" <add> ENV["HOMEBREW_TEST_GENERIC_OS"] = "1" if ARGV.include? "--generic" <ide> if ARGV.include? "--coverage" <ide> ENV["HOMEBREW_TESTS_COVERAGE"] = "1" <ide> FileUtils.rm_f "coverage/.resultset.json"
1
Java
Java
fix typo in @componentscan javadoc
352ed517c5fd74f3549a36050c325b8a3fc00f28
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/ComponentScan.java <ide> <ide> /** <ide> * Declares the type filter to be used as an {@linkplain ComponentScan#includeFilters() <del> * include filter} or {@linkplain ComponentScan#includeFilters() exclude filter}. <add> * include filter} or {@linkplain ComponentScan#excludeFilters() exclude filter}. <ide> */ <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Target({})
1
Text
Text
improve blurb about angularjs in readme.md
d3952b79c7d3fe024ba2cf886dc9225d3107d342
<ide><path>README.md <ide> synchronizes data from your UI (view) with your JavaScript objects (model) throu <ide> binding. To help you structure your application better and make it easy to test AngularJS teaches <ide> the browser how to do dependency injection and inversion of control. Oh yeah and it also helps with <ide> server-side communication, taming async callbacks with promises and deferreds; and make client-side <del>navigation and deeplinking with hashbang urls or HTML5 pushState a piece of cake. The most important <del>of all: it makes development fun! <add>navigation and deeplinking with hashbang urls or HTML5 pushState a piece of cake. The best of all: <add>it makes development fun! <ide> <ide> * Web site: http://angularjs.org <ide> * Tutorial: http://docs.angularjs.org/tutorial
1
Javascript
Javascript
add a cache system to limit the amount of ram used
26bf2735fdacf9112975b30ba82314e8efd74ffd
<ide><path>web/viewer.js <ide> var kDefaultURL = 'compressed.tracemonkey-pldi-09.pdf'; <ide> var kDefaultScale = 150; <ide> <add>var kCacheSize = 20; <add> <add>var Cache = function(size) { <add> var data = []; <add> this.push = function(view) { <add> data.push(view); <add> if (data.length > size) <add> data.shift().update(); <add> }; <add>}; <add> <add>var cache = new Cache(kCacheSize); <add> <ide> var PDFView = { <ide> pages: [], <ide> thumbnails: [], <ide> var PDFView = { <ide> var windowBottom = window.pageYOffset + window.innerHeight; <ide> for (; i <= pages.length && currentHeight < windowBottom; i++) { <ide> var page = pages[i - 1]; <del> visiblePages.push({ id: page.id, y: currentHeight }); <add> visiblePages.push({ id: page.id, y: currentHeight, view: page }); <ide> currentHeight += page.height * page.scale + kBottomMargin; <ide> } <ide> <ide> var PageView = function(container, content, id, width, height, stats) { <ide> container.appendChild(div); <ide> <ide> this.update = function(scale) { <del> this.scale = scale; <add> this.scale = scale || this.scale; <ide> div.style.width = (this.width * this.scale)+ 'px'; <ide> div.style.height = (this.height * this.scale) + 'px'; <ide> <ide> var PageView = function(container, content, id, width, height, stats) { <ide> this.draw = function() { <ide> if (div.hasChildNodes()) { <ide> this.updateStats(); <del> return; <add> return false; <ide> } <ide> <ide> var canvas = document.createElement('canvas'); <ide> var PageView = function(container, content, id, width, height, stats) { <ide> <ide> stats.begin = Date.now(); <ide> this.content.startRendering(ctx, this.updateStats); <add> <add> return true; <ide> }; <ide> <ide> this.updateStats = function() { <ide> window.addEventListener('pdfloaded', function(evt) { <ide> <ide> window.addEventListener('scroll', function(evt) { <ide> var visiblePages = PDFView.getVisiblePages(); <del> for (var i = 0; i < visiblePages.length; i++) <del> PDFView.pages[visiblePages[i].id - 1].draw(); <add> for (var i = 0; i < visiblePages.length; i++) { <add> var page = visiblePages[i]; <add> if (PDFView.pages[page.id - 1].draw()) <add> cache.push(page.view); <add> } <ide> <ide> if (!visiblePages.length) <ide> return;
1
Ruby
Ruby
ignore spill for certain system paths
80b555057c6518a27afb22aa8098910ed77984ac
<ide><path>Library/Homebrew/beer_events.rb <ide> def watch_out_for_spill <ide> spill = events.map { |e| e.files }.flatten <ide> spill.reject! { |f| File.mtime(f) < start } <ide> spill.reject! { |path| path =~ /^#{HOMEBREW_PREFIX}/ } <add> # irrelevent files that change a lot <add> spill.reject! { |path| path == "/Library/Preferences/SystemConfiguration/com.apple.PowerManagement.plist-lock" } <add> spill.reject! { |path| path == "/System/Library/Caches/com.apple.Components2.SystemCache.Components" } <ide> unless spill.empty? <ide> opoo "Detected installation of files outside the Homebrew prefix:" <ide> puts *spill
1
Text
Text
fix typos and auto-format [ci skip]
a9e5b840ee43746cd39213da9d27a01188be1904
<ide><path>website/docs/api/goldparse.md <ide> expects true examples of a label to have the value `1.0`, and negative examples <ide> of a label to have the value `0.0`. Labels not in the dictionary are treated as <ide> missing – the gradient for those labels will be zero. <ide> <del>| Name | Type | Description | <del>| ----------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | <del>| `doc` | `Doc` | The document the annotations refer to. | <del>| `words` | iterable | A sequence of unicode word strings. | <del>| `tags` | iterable | A sequence of strings, representing tag annotations. | <del>| `heads` | iterable | A sequence of integers, representing syntactic head offsets. | <del>| `deps` | iterable | A sequence of strings, representing the syntactic relation types. | <del>| `entities` | iterable | A sequence of named entity annotations, either as BILUO tag strings, or as `(start_char, end_char, label)` tuples, representing the entity positions. If BILUO tag strings, you can specify missing values by setting the tag to None. | <del>| `cats` | dict | Labels for text classification. Each key in the dictionary is a string label for the category and each value is `1.0` (positive) or `0.0` (negative). | <del>| `links` | dict | Labels for entity linking. A dict with `(start_char, end_char)` keys, and the values being dicts with `kb_id:value` entries, representing external KB IDs mapped to either `1.0` (positive) or `0.0` (negative). | <del>| `make_projective` | bool | Whether to projectivize the dependency tree. Defaults to `False.`. | <del>| **RETURNS** | `GoldParse` | The newly constructed object. | <add>| Name | Type | Description | <add>| ----------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | <add>| `doc` | `Doc` | The document the annotations refer to. | <add>| `words` | iterable | A sequence of unicode word strings. | <add>| `tags` | iterable | A sequence of strings, representing tag annotations. | <add>| `heads` | iterable | A sequence of integers, representing syntactic head offsets. | <add>| `deps` | iterable | A sequence of strings, representing the syntactic relation types. | <add>| `entities` | iterable | A sequence of named entity annotations, either as BILUO tag strings, or as `(start_char, end_char, label)` tuples, representing the entity positions. If BILUO tag strings, you can specify missing values by setting the tag to None. | <add>| `cats` | dict | Labels for text classification. Each key in the dictionary is a string label for the category and each value is `1.0` (positive) or `0.0` (negative). | <add>| `links` | dict | Labels for entity linking. A dict with `(start_char, end_char)` keys, and the values being dicts with `kb_id:value` entries, representing external KB IDs mapped to either `1.0` (positive) or `0.0` (negative). | <add>| `make_projective` | bool | Whether to projectivize the dependency tree. Defaults to `False`. | <add>| **RETURNS** | `GoldParse` | The newly constructed object. | <ide> <ide> ## GoldParse.\_\_len\_\_ {#len tag="method"} <ide> <ide> Whether the provided syntactic annotations form a projective dependency tree. <ide> <ide> ## Attributes {#attributes} <ide> <del>| Name | Type | Description | <del>| ------------------------------------ | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | <del>| `words` | list | The words. | <del>| `tags` | list | The part-of-speech tag annotations. | <del>| `heads` | list | The syntactic head annotations. | <del>| `labels` | list | The syntactic relation-type annotations. | <del>| `ner` | list | The named entity annotations as BILUO tags. | <del>| `cand_to_gold` | list | The alignment from candidate tokenization to gold tokenization. | <del>| `gold_to_cand` | list | The alignment from gold tokenization to candidate tokenization. | <del>| `cats` <Tag variant="new">2</Tag> | dict | Keys in the dictionary are string category labels with values `1.0` or `0.0`. | <del>| `links` <Tag variant="new">2.2</Tag> | dict | Keys in the dictionary are `(start_char, end_char)` triples, and the values are dictionaries with `kb_id:value` entries. | <add>| Name | Type | Description | <add>| ------------------------------------ | ---- | ------------------------------------------------------------------------------------------------------------------------ | <add>| `words` | list | The words. | <add>| `tags` | list | The part-of-speech tag annotations. | <add>| `heads` | list | The syntactic head annotations. | <add>| `labels` | list | The syntactic relation-type annotations. | <add>| `ner` | list | The named entity annotations as BILUO tags. | <add>| `cand_to_gold` | list | The alignment from candidate tokenization to gold tokenization. | <add>| `gold_to_cand` | list | The alignment from gold tokenization to candidate tokenization. | <add>| `cats` <Tag variant="new">2</Tag> | dict | Keys in the dictionary are string category labels with values `1.0` or `0.0`. | <add>| `links` <Tag variant="new">2.2</Tag> | dict | Keys in the dictionary are `(start_char, end_char)` triples, and the values are dictionaries with `kb_id:value` entries. | <ide> <ide> ## Utilities {#util} <ide> <ide> ### gold.docs_to_json {#docs_to_json tag="function"} <ide> <ide> Convert a list of Doc objects into the <ide> [JSON-serializable format](/api/annotation#json-input) used by the <del>[`spacy train`](/api/cli#train) command. Each input doc will be treated as a 'paragraph' in the output doc. <add>[`spacy train`](/api/cli#train) command. Each input doc will be treated as a <add>'paragraph' in the output doc. <ide> <ide> > #### Example <ide> > <ide><path>website/docs/api/matcher.md <ide> spaCy v2.3, the `Matcher` can also be called on `Span` objects. <ide> <ide> | Name | Type | Description | <ide> | ----------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | <del>| `doclike` | `Doc`/`Span` | The document to match over or a `Span` (as of v2.3).. | <add>| `doclike` | `Doc`/`Span` | The document to match over or a `Span` (as of v2.3). | <ide> | **RETURNS** | list | A list of `(match_id, start, end)` tuples, describing the matches. A match tuple describes a span `doc[start:end`]. The `match_id` is the ID of the added match pattern. | <ide> <ide> <Infobox title="Important note" variant="warning">
2
PHP
PHP
remove unused use
eb61dd8a936c0a5a610a329c6b96c5f7d3a44bb3
<ide><path>tests/TestCase/ORM/TableTest.php <ide> use Cake\Event\Event; <ide> use Cake\Event\EventManager; <ide> use Cake\I18n\Time; <del>use Cake\ORM\Association\BelongsTo; <ide> use Cake\ORM\AssociationCollection; <ide> use Cake\ORM\Association\BelongsToMany; <ide> use Cake\ORM\Association\HasMany;
1
Ruby
Ruby
remove autoload for non-existent file
8d827325d08e2e080be3d1ed4a827eaa97d20bf9
<ide><path>actionpack/lib/action_dispatch/routing.rb <ide> module ActionDispatch <ide> # <ide> module Routing <ide> autoload :Mapper, 'action_dispatch/routing/mapper' <del> autoload :Route, 'action_dispatch/routing/route' <ide> autoload :RouteSet, 'action_dispatch/routing/route_set' <ide> autoload :RoutesProxy, 'action_dispatch/routing/routes_proxy' <ide> autoload :UrlFor, 'action_dispatch/routing/url_for'
1
Ruby
Ruby
use real repo to run tests
6278e08aec7697f15bfdc1c9a1032f8612f5357b
<ide><path>Library/Homebrew/test/test_ENV.rb <ide> def setup <ide> class SuperenvTests < Homebrew::TestCase <ide> include SharedEnvTests <ide> <del> attr_reader :env, :bin <del> <ide> def setup <ide> @env = {}.extend(Superenv) <del> @bin = HOMEBREW_REPOSITORY/"Library/ENV/#{MacOS::Xcode.version}" <del> bin.mkpath <del> end <del> <del> def test_bin <del> assert_equal bin, Superenv.bin <ide> end <ide> <ide> def test_initializes_deps <del> assert_equal [], env.deps <del> assert_equal [], env.keg_only_deps <del> end <del> <del> def teardown <del> bin.rmtree <add> assert_equal [], @env.deps <add> assert_equal [], @env.keg_only_deps <ide> end <ide> end <ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_path <ide> end <ide> <ide> def test_factory <del> name = 'foo-bar' <del> path = HOMEBREW_PREFIX+"Library/Formula/#{name}.rb" <del> path.dirname.mkpath <del> File.open(path, 'w') do |f| <del> f << %{ <del> class #{Formulary.class_s(name)} < Formula <del> url 'foo-1.0' <del> end <del> } <del> end <del> assert_kind_of Formula, Formulary.factory(name) <del> ensure <del> path.unlink <add> assert_kind_of Formula, Formulary.factory("tree") <ide> end <ide> <ide> def test_class_specs_are_always_initialized <ide><path>Library/Homebrew/test/testing_env.rb <ide> # Require this file to build a testing environment. <ide> <del>$:.push(File.expand_path(__FILE__+'/../..')) <add>repo_root = Pathname.new File.expand_path("../../../..", __FILE__) <add>$: << repo_root.join("Library", "Homebrew").to_s <ide> <ide> require 'extend/module' <ide> require 'extend/fileutils' <ide> <ide> # Constants normally defined in global.rb <ide> HOMEBREW_PREFIX = Pathname.new(TEST_TMPDIR).join("prefix") <del>HOMEBREW_REPOSITORY = HOMEBREW_PREFIX <add>HOMEBREW_REPOSITORY = repo_root <add>HOMEBREW_BREW_FILE = HOMEBREW_REPOSITORY+"bin"+"brew" <ide> HOMEBREW_LIBRARY = HOMEBREW_REPOSITORY+'Library' <add>HOMEBREW_LIBRARY_PATH = HOMEBREW_LIBRARY+"Homebrew" <ide> HOMEBREW_CACHE = HOMEBREW_PREFIX.parent+'cache' <ide> HOMEBREW_CACHE_FORMULA = HOMEBREW_PREFIX.parent+'formula_cache' <ide> HOMEBREW_CELLAR = HOMEBREW_PREFIX.parent+'cellar' <ide> ORIGINAL_PATHS = ENV['PATH'].split(File::PATH_SEPARATOR).map{ |p| Pathname.new(p).expand_path rescue nil }.compact.freeze <ide> <ide> # Test environment setup <del>%w{ENV Formula}.each { |d| HOMEBREW_LIBRARY.join(d).mkpath } <del>%w{cache formula_cache cellar logs}.each { |d| HOMEBREW_PREFIX.parent.join(d).mkpath } <add>%w{prefix cache formula_cache cellar logs}.each { |d| HOMEBREW_PREFIX.parent.join(d).mkpath } <ide> <ide> # Test fixtures and files can be found relative to this path <ide> TEST_DIRECTORY = File.dirname(File.expand_path(__FILE__))
3
PHP
PHP
return the index instead of the choice
fbb24e5eadbb47152645e25d5b63bbdffe023058
<ide><path>src/Illuminate/Console/Command.php <ide> public function choice($question, array $choices, $default = null, $attempts = f <ide> { <ide> $dialog = $this->getHelperSet()->get('dialog'); <ide> <del> $choice = $dialog->select($this->output, "<question>$question</question>", $choices, $default, $attempts); <del> <del> return $choices[$choice]; <add> return $dialog->select($this->output, "<question>$question</question>", $choices, $default, $attempts); <ide> } <ide> <ide> /**
1
Java
Java
add more unit tests
46544c38c74e9df451a880ceaf460ad786d2c26e
<ide><path>rxjava-core/src/test/java/rx/ObservableTests.java <ide> public void testRangeWithScheduler() { <ide> <ide> @Test <ide> public void testStartWithAction() { <del> TestScheduler scheduler = new TestScheduler(); <del> <ide> Action0 action = mock(Action0.class); <del> Observable<Void> observable = Observable.start(action, scheduler); <del> scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); <del> <del> assertEquals(null, observable.toBlockingObservable().single()); <del> assertEquals(null, observable.toBlockingObservable().single()); <del> verify(action, times(1)).call(); <add> assertEquals(null, Observable.start(action).toBlockingObservable().single()); <ide> } <ide> <ide> @Test(expected = RuntimeException.class) <ide> public void call() { <ide> throw new RuntimeException("Some error"); <ide> } <ide> }; <add> Observable.start(action).toBlockingObservable().single(); <add> } <add> <add> @Test <add> public void testStartWhenSubscribeRunBeforeAction() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> Action0 action = mock(Action0.class); <add> <add> Observable<Void> observable = Observable.start(action, scheduler); <add> <add> @SuppressWarnings("unchecked") <add> Observer<Void> observer = mock(Observer.class); <add> observable.subscribe(observer); <add> <add> InOrder inOrder = inOrder(observer); <add> inOrder.verifyNoMoreInteractions(); <add> <add> // Run action <add> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); <ide> <del> Observable<Void> observable = Observable.start(action); <del> observable.toBlockingObservable().single(); <add> inOrder.verify(observer, times(1)).onNext(null); <add> inOrder.verify(observer, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <ide> } <ide> <ide> @Test <del> public void testStartWithFunc() { <add> public void testStartWhenSubscribeRunAfterAction() { <ide> TestScheduler scheduler = new TestScheduler(); <ide> <add> Action0 action = mock(Action0.class); <add> <add> Observable<Void> observable = Observable.start(action, scheduler); <add> <add> // Run action <add> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); <add> <ide> @SuppressWarnings("unchecked") <del> Func0<String> func = (Func0<String>) mock(Func0.class); <del> doAnswer(new Answer<String>() { <add> Observer<Void> observer = mock(Observer.class); <add> observable.subscribe(observer); <add> <add> InOrder inOrder = inOrder(observer); <add> inOrder.verify(observer, times(1)).onNext(null); <add> inOrder.verify(observer, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> } <add> <add> @Test <add> public void testStartWithActionAndMultipleObservers() { <add> TestScheduler scheduler = new TestScheduler(); <ide> <add> Action0 action = mock(Action0.class); <add> <add> Observable<Void> observable = Observable.start(action, scheduler); <add> <add> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); <add> <add> @SuppressWarnings("unchecked") <add> Observer<Void> observer1 = mock(Observer.class); <add> @SuppressWarnings("unchecked") <add> Observer<Void> observer2 = mock(Observer.class); <add> @SuppressWarnings("unchecked") <add> Observer<Void> observer3 = mock(Observer.class); <add> <add> observable.subscribe(observer1); <add> observable.subscribe(observer2); <add> observable.subscribe(observer3); <add> <add> InOrder inOrder; <add> inOrder = inOrder(observer1); <add> inOrder.verify(observer1, times(1)).onNext(null); <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> inOrder = inOrder(observer2); <add> inOrder.verify(observer2, times(1)).onNext(null); <add> inOrder.verify(observer2, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> inOrder = inOrder(observer3); <add> inOrder.verify(observer3, times(1)).onNext(null); <add> inOrder.verify(observer3, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> verify(action, times(1)).call(); <add> } <add> <add> @Test <add> public void testStartWithFunc() { <add> Func0<String> func = new Func0<String>() { <ide> @Override <del> public String answer(InvocationOnMock invocation) throws Throwable { <add> public String call() { <ide> return "one"; <ide> } <add> }; <add> assertEquals("one", Observable.start(func).toBlockingObservable().single()); <add> } <ide> <del> }).when(func).call(); <add> @Test(expected = RuntimeException.class) <add> public void testStartWithFuncError() { <add> Func0<String> func = new Func0<String>() { <add> @Override <add> public String call() { <add> throw new RuntimeException("Some error"); <add> } <add> }; <add> Observable.start(func).toBlockingObservable().single(); <add> } <add> <add> @Test <add> public void testStartWhenSubscribeRunBeforeFunc() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> Func0<String> func = new Func0<String>() { <add> @Override <add> public String call() { <add> return "one"; <add> } <add> }; <ide> <ide> Observable<String> observable = Observable.start(func, scheduler); <del> scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); <ide> <del> assertEquals("one", observable.toBlockingObservable().single()); <del> assertEquals("one", observable.toBlockingObservable().single()); <del> verify(func, times(1)).call(); <add> @SuppressWarnings("unchecked") <add> Observer<String> observer = mock(Observer.class); <add> observable.subscribe(observer); <add> <add> InOrder inOrder = inOrder(observer); <add> inOrder.verifyNoMoreInteractions(); <add> <add> // Run func <add> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); <add> <add> inOrder.verify(observer, times(1)).onNext("one"); <add> inOrder.verify(observer, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <ide> } <ide> <del> @Test(expected = RuntimeException.class) <del> public void testStartWithFuncError() { <add> @Test <add> public void testStartWhenSubscribeRunAfterFunc() { <add> TestScheduler scheduler = new TestScheduler(); <add> <ide> Func0<String> func = new Func0<String>() { <ide> @Override <ide> public String call() { <del> throw new RuntimeException("Some error"); <add> return "one"; <ide> } <ide> }; <ide> <del> Observable<String> observable = Observable.start(func); <del> observable.toBlockingObservable().single(); <add> Observable<String> observable = Observable.start(func, scheduler); <add> <add> // Run func <add> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); <add> <add> @SuppressWarnings("unchecked") <add> Observer<String> observer = mock(Observer.class); <add> observable.subscribe(observer); <add> <add> InOrder inOrder = inOrder(observer); <add> inOrder.verify(observer, times(1)).onNext("one"); <add> inOrder.verify(observer, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <ide> } <del>} <ide>\ No newline at end of file <add> <add> @Test <add> public void testStartWithFuncAndMultipleObservers() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> @SuppressWarnings("unchecked") <add> Func0<String> func = (Func0<String>) mock(Func0.class); <add> doAnswer(new Answer<String>() { <add> @Override <add> public String answer(InvocationOnMock invocation) throws Throwable { <add> return "one"; <add> } <add> }).when(func).call(); <add> <add> Observable<String> observable = Observable.start(func, scheduler); <add> <add> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); <add> <add> @SuppressWarnings("unchecked") <add> Observer<String> observer1 = mock(Observer.class); <add> @SuppressWarnings("unchecked") <add> Observer<String> observer2 = mock(Observer.class); <add> @SuppressWarnings("unchecked") <add> Observer<String> observer3 = mock(Observer.class); <add> <add> observable.subscribe(observer1); <add> observable.subscribe(observer2); <add> observable.subscribe(observer3); <add> <add> InOrder inOrder; <add> inOrder = inOrder(observer1); <add> inOrder.verify(observer1, times(1)).onNext("one"); <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> inOrder = inOrder(observer2); <add> inOrder.verify(observer2, times(1)).onNext("one"); <add> inOrder.verify(observer2, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> inOrder = inOrder(observer3); <add> inOrder.verify(observer3, times(1)).onNext("one"); <add> inOrder.verify(observer3, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> verify(func, times(1)).call(); <add> } <add> <add>}
1
Text
Text
add v3.25.0-beta.5 to changelog
002e4e86a763c6814e8035b411d41e384d76f61f
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.25.0-beta.5 (February 02, 2021) <add> <add>- [#19370](https://github.com/emberjs/ember.js/pull/19370) [BUGFIX] Update glimmer-vm to prevent errors for older inline precompilation <add> <ide> ### v3.25.0-beta.4 (February 01, 2021) <ide> <ide> - [#19363](https://github.com/emberjs/ember.js/pull/19363) [BUGFIX] Update VM, fix component name preprocessing
1
Java
Java
extend websocket scope to event publication
a99ef6d9b2ca77f60e2838ff20a7957254a80fc4
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java <ide> public void handleMessageFromClient(WebSocketSession session, <ide> headerAccessor.setUser(session.getPrincipal()); <ide> headerAccessor.setImmutable(); <ide> <del> if (this.eventPublisher != null) { <del> if (StompCommand.CONNECT.equals(headerAccessor.getCommand())) { <del> this.stats.incrementConnectCount(); <del> publishEvent(new SessionConnectEvent(this, message)); <del> } <del> else if (StompCommand.DISCONNECT.equals(headerAccessor.getCommand())) { <del> this.stats.incrementDisconnectCount(); <del> } <del> else if (StompCommand.SUBSCRIBE.equals(headerAccessor.getCommand())) { <del> publishEvent(new SessionSubscribeEvent(this, message)); <del> } <del> else if (StompCommand.UNSUBSCRIBE.equals(headerAccessor.getCommand())) { <del> publishEvent(new SessionUnsubscribeEvent(this, message)); <del> } <add> if (StompCommand.CONNECT.equals(headerAccessor.getCommand())) { <add> this.stats.incrementConnectCount(); <add> } <add> else if (StompCommand.DISCONNECT.equals(headerAccessor.getCommand())) { <add> this.stats.incrementDisconnectCount(); <ide> } <ide> <ide> try { <ide> SimpAttributesContextHolder.setAttributesFromMessage(message); <add> if (this.eventPublisher != null) { <add> if (StompCommand.CONNECT.equals(headerAccessor.getCommand())) { <add> publishEvent(new SessionConnectEvent(this, message)); <add> } <add> else if (StompCommand.SUBSCRIBE.equals(headerAccessor.getCommand())) { <add> publishEvent(new SessionSubscribeEvent(this, message)); <add> } <add> else if (StompCommand.UNSUBSCRIBE.equals(headerAccessor.getCommand())) { <add> publishEvent(new SessionUnsubscribeEvent(this, message)); <add> } <add> } <ide> outputChannel.send(message); <ide> } <ide> finally { <ide> else if (StompCommand.CONNECTED.equals(command)) { <ide> this.stats.incrementConnectedCount(); <ide> stompAccessor = afterStompSessionConnected(message, stompAccessor, session); <ide> if (this.eventPublisher != null && StompCommand.CONNECTED.equals(command)) { <del> publishEvent(new SessionConnectedEvent(this, (Message<byte[]>) message)); <add> try { <add> SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes()); <add> SimpAttributesContextHolder.setAttributes(simpAttributes); <add> publishEvent(new SessionConnectedEvent(this, (Message<byte[]>) message)); <add> } <add> finally { <add> SimpAttributesContextHolder.resetAttributes(); <add> } <ide> } <ide> } <ide> try { <ide> public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus, <ide> this.userSessionRegistry.unregisterSessionId(userName, session.getId()); <ide> } <ide> Message<byte[]> message = createDisconnectMessage(session); <del> if (this.eventPublisher != null) { <del> publishEvent(new SessionDisconnectEvent(this, message, session.getId(), closeStatus)); <del> } <ide> SimpAttributes simpAttributes = SimpAttributes.fromMessage(message); <ide> try { <ide> SimpAttributesContextHolder.setAttributes(simpAttributes); <add> if (this.eventPublisher != null) { <add> publishEvent(new SessionDisconnectEvent(this, message, session.getId(), closeStatus)); <add> } <ide> outputChannel.send(message); <ide> } <ide> finally {
1
Go
Go
fix benchmarks and remove more unnecessary code
a06ad2792ab92d4f246e4b4cc4c3529eb060651e
<ide><path>daemon/logger/jsonfilelog/jsonfilelog.go <ide> import ( <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/daemon/logger/loggerutils" <ide> "github.com/docker/docker/pkg/jsonlog" <del> "github.com/docker/go-units" <add> units "github.com/docker/go-units" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func writeMessageBuf(w io.Writer, m *logger.Message, extra json.RawMessage, buf <ide> return err <ide> } <ide> logger.PutMessage(m) <del> if _, err := w.Write(buf.Bytes()); err != nil { <del> return errors.Wrap(err, "error writing log entry") <del> } <del> return nil <add> _, err := w.Write(buf.Bytes()) <add> return errors.Wrap(err, "error writing log entry") <ide> } <ide> <ide> func marshalMessage(msg *logger.Message, extra json.RawMessage, buf *bytes.Buffer) error { <ide><path>daemon/logger/jsonfilelog/jsonfilelog_test.go <ide> package jsonfilelog <ide> <ide> import ( <add> "bytes" <ide> "encoding/json" <ide> "io/ioutil" <ide> "os" <ide> import ( <ide> <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/pkg/jsonlog" <add> "github.com/gotestyourself/gotestyourself/fs" <add> "github.com/stretchr/testify/require" <ide> ) <ide> <ide> func TestJSONFileLogger(t *testing.T) { <ide> func TestJSONFileLogger(t *testing.T) { <ide> } <ide> } <ide> <del>func BenchmarkJSONFileLogger(b *testing.B) { <del> cid := "a7317399f3f857173c6179d44823594f8294678dea9999662e5c625b5a1c7657" <del> tmp, err := ioutil.TempDir("", "docker-logger-") <del> if err != nil { <del> b.Fatal(err) <del> } <del> defer os.RemoveAll(tmp) <del> filename := filepath.Join(tmp, "container.log") <del> l, err := New(logger.Info{ <del> ContainerID: cid, <del> LogPath: filename, <add>func BenchmarkJSONFileLoggerLog(b *testing.B) { <add> tmp := fs.NewDir(b, "bench-jsonfilelog") <add> defer tmp.Remove() <add> <add> jsonlogger, err := New(logger.Info{ <add> ContainerID: "a7317399f3f857173c6179d44823594f8294678dea9999662e5c625b5a1c7657", <add> LogPath: tmp.Join("container.log"), <add> Config: map[string]string{ <add> "labels": "first,second", <add> }, <add> ContainerLabels: map[string]string{ <add> "first": "label_value", <add> "second": "label_foo", <add> }, <ide> }) <del> if err != nil { <del> b.Fatal(err) <del> } <del> defer l.Close() <add> require.NoError(b, err) <add> defer jsonlogger.Close() <ide> <del> testLine := "Line that thinks that it is log line from docker\n" <del> msg := &logger.Message{Line: []byte(testLine), Source: "stderr", Timestamp: time.Now().UTC()} <del> jsonlog, err := (&jsonlog.JSONLog{Log: string(msg.Line) + "\n", Stream: msg.Source, Created: msg.Timestamp}).MarshalJSON() <del> if err != nil { <del> b.Fatal(err) <add> msg := &logger.Message{ <add> Line: []byte("Line that thinks that it is log line from docker\n"), <add> Source: "stderr", <add> Timestamp: time.Now().UTC(), <ide> } <del> b.SetBytes(int64(len(jsonlog)+1) * 30) <add> <add> buf := bytes.NewBuffer(nil) <add> require.NoError(b, marshalMessage(msg, jsonlogger.(*JSONFileLogger).extra, buf)) <add> b.SetBytes(int64(buf.Len())) <add> <ide> b.ResetTimer() <ide> for i := 0; i < b.N; i++ { <del> for j := 0; j < 30; j++ { <del> if err := l.Log(msg); err != nil { <del> b.Fatal(err) <del> } <add> if err := jsonlogger.Log(msg); err != nil { <add> b.Fatal(err) <ide> } <ide> } <ide> } <ide> func TestJSONFileLoggerWithLabelsEnv(t *testing.T) { <ide> t.Fatalf("Wrong log attrs: %q, expected %q", extra, expected) <ide> } <ide> } <del> <del>func BenchmarkJSONFileLoggerWithReader(b *testing.B) { <del> b.StopTimer() <del> b.ResetTimer() <del> cid := "a7317399f3f857173c6179d44823594f8294678dea9999662e5c625b5a1c7657" <del> dir, err := ioutil.TempDir("", "json-logger-bench") <del> if err != nil { <del> b.Fatal(err) <del> } <del> defer os.RemoveAll(dir) <del> <del> l, err := New(logger.Info{ <del> ContainerID: cid, <del> LogPath: filepath.Join(dir, "container.log"), <del> }) <del> if err != nil { <del> b.Fatal(err) <del> } <del> defer l.Close() <del> msg := &logger.Message{Line: []byte("line"), Source: "src1"} <del> jsonlog, err := (&jsonlog.JSONLog{Log: string(msg.Line) + "\n", Stream: msg.Source, Created: msg.Timestamp}).MarshalJSON() <del> if err != nil { <del> b.Fatal(err) <del> } <del> b.SetBytes(int64(len(jsonlog)+1) * 30) <del> <del> b.StartTimer() <del> <del> go func() { <del> for i := 0; i < b.N; i++ { <del> for j := 0; j < 30; j++ { <del> l.Log(msg) <del> } <del> } <del> l.Close() <del> }() <del> <del> lw := l.(logger.LogReader).ReadLogs(logger.ReadConfig{Follow: true}) <del> watchClose := lw.WatchClose() <del> for { <del> select { <del> case <-lw.Msg: <del> case <-watchClose: <del> return <del> } <del> } <del>} <ide><path>daemon/logger/jsonfilelog/read_test.go <add>package jsonfilelog <add> <add>import ( <add> "testing" <add> <add> "bytes" <add> "time" <add> <add> "github.com/docker/docker/daemon/logger" <add> "github.com/gotestyourself/gotestyourself/fs" <add> "github.com/stretchr/testify/require" <add>) <add> <add>func BenchmarkJSONFileLoggerReadLogs(b *testing.B) { <add> tmp := fs.NewDir(b, "bench-jsonfilelog") <add> defer tmp.Remove() <add> <add> jsonlogger, err := New(logger.Info{ <add> ContainerID: "a7317399f3f857173c6179d44823594f8294678dea9999662e5c625b5a1c7657", <add> LogPath: tmp.Join("container.log"), <add> Config: map[string]string{ <add> "labels": "first,second", <add> }, <add> ContainerLabels: map[string]string{ <add> "first": "label_value", <add> "second": "label_foo", <add> }, <add> }) <add> require.NoError(b, err) <add> defer jsonlogger.Close() <add> <add> msg := &logger.Message{ <add> Line: []byte("Line that thinks that it is log line from docker\n"), <add> Source: "stderr", <add> Timestamp: time.Now().UTC(), <add> } <add> <add> buf := bytes.NewBuffer(nil) <add> require.NoError(b, marshalMessage(msg, jsonlogger.(*JSONFileLogger).extra, buf)) <add> b.SetBytes(int64(buf.Len())) <add> <add> b.ResetTimer() <add> <add> chError := make(chan error, b.N+1) <add> go func() { <add> for i := 0; i < b.N; i++ { <add> chError <- jsonlogger.Log(msg) <add> } <add> chError <- jsonlogger.Close() <add> }() <add> <add> lw := jsonlogger.(*JSONFileLogger).ReadLogs(logger.ReadConfig{Follow: true}) <add> watchClose := lw.WatchClose() <add> for { <add> select { <add> case <-lw.Msg: <add> case <-watchClose: <add> return <add> case err := <-chError: <add> if err != nil { <add> b.Fatal(err) <add> } <add> } <add> } <add>} <ide><path>pkg/jsonlog/jsonlog.go <ide> import ( <ide> "time" <ide> ) <ide> <del>// JSONLog represents a log message, typically a single entry from a given log stream. <del>// JSONLogs can be easily serialized to and from JSON and support custom formatting. <add>// JSONLog is a log message, typically a single entry from a given log stream. <ide> type JSONLog struct { <ide> // Log is the log message <ide> Log string `json:"log,omitempty"` <ide><path>pkg/jsonlog/jsonlogbytes.go <ide> type JSONLogs struct { <ide> RawAttrs json.RawMessage `json:"attrs,omitempty"` <ide> } <ide> <del>// MarshalJSONBuf is based on the same method from JSONLog <del>// It has been modified to take into account the necessary changes. <add>// MarshalJSONBuf is an optimized JSON marshaller that avoids reflection <add>// and unnecessary allocation. <ide> func (mj *JSONLogs) MarshalJSONBuf(buf *bytes.Buffer) error { <ide> var first = true <ide> <ide> func (mj *JSONLogs) MarshalJSONBuf(buf *bytes.Buffer) error { <ide> buf.WriteString(`,`) <ide> } <ide> buf.WriteString(`"stream":`) <del> ffjsonWriteJSONString(buf, mj.Stream) <add> ffjsonWriteJSONBytesAsString(buf, []byte(mj.Stream)) <ide> } <ide> if len(mj.RawAttrs) > 0 { <ide> if first { <ide> func (mj *JSONLogs) MarshalJSONBuf(buf *bytes.Buffer) error { <ide> return nil <ide> } <ide> <del>func ffjsonWriteJSONString(buf *bytes.Buffer, s string) { <del> const hex = "0123456789abcdef" <del> <del> buf.WriteByte('"') <del> start := 0 <del> for i := 0; i < len(s); { <del> if b := s[i]; b < utf8.RuneSelf { <del> if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' { <del> i++ <del> continue <del> } <del> if start < i { <del> buf.WriteString(s[start:i]) <del> } <del> switch b { <del> case '\\', '"': <del> buf.WriteByte('\\') <del> buf.WriteByte(b) <del> case '\n': <del> buf.WriteByte('\\') <del> buf.WriteByte('n') <del> case '\r': <del> buf.WriteByte('\\') <del> buf.WriteByte('r') <del> default: <del> <del> buf.WriteString(`\u00`) <del> buf.WriteByte(hex[b>>4]) <del> buf.WriteByte(hex[b&0xF]) <del> } <del> i++ <del> start = i <del> continue <del> } <del> c, size := utf8.DecodeRuneInString(s[i:]) <del> if c == utf8.RuneError && size == 1 { <del> if start < i { <del> buf.WriteString(s[start:i]) <del> } <del> buf.WriteString(`\ufffd`) <del> i += size <del> start = i <del> continue <del> } <del> <del> if c == '\u2028' || c == '\u2029' { <del> if start < i { <del> buf.WriteString(s[start:i]) <del> } <del> buf.WriteString(`\u202`) <del> buf.WriteByte(hex[c&0xF]) <del> i += size <del> start = i <del> continue <del> } <del> i += size <del> } <del> if start < len(s) { <del> buf.WriteString(s[start:]) <del> } <del> buf.WriteByte('"') <del>} <del> <del>// This is based on ffjsonWriteJSONString. It has been changed <del>// to accept a string passed as a slice of bytes. <del>// TODO: remove duplication with ffjsonWriteJSONString <ide> func ffjsonWriteJSONBytesAsString(buf *bytes.Buffer, s []byte) { <ide> const hex = "0123456789abcdef" <ide>
5
Python
Python
fix escaping of html in displacy ent (closes )
80bdcb99c54e5e84ee746a7633633d434cb3728b
<ide><path>spacy/displacy/render.py <ide> def render_ents(self, text, spans, title): <ide> label = span["label"] <ide> start = span["start"] <ide> end = span["end"] <del> entity = text[start:end] <add> entity = escape_html(text[start:end]) <ide> fragments = text[offset:start].split("\n") <ide> for i, fragment in enumerate(fragments): <del> markup += fragment <add> markup += escape_html(fragment) <ide> if len(fragments) > 1 and i != len(fragments) - 1: <ide> markup += "</br>" <ide> if self.ents is None or label.upper() in self.ents: <ide> def render_ents(self, text, spans, title): <ide> else: <ide> markup += entity <ide> offset = end <del> markup += text[offset:] <add> markup += escape_html(text[offset:]) <ide> markup = TPL_ENTS.format(content=markup, colors=self.colors) <ide> if title: <ide> markup = TPL_TITLE.format(title=title) + markup <ide><path>spacy/tests/regression/test_issue2728.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <add>from spacy import displacy <add>from spacy.tokens import Doc, Span <add> <add> <add>def test_issue2728(en_vocab): <add> """Test that displaCy ENT visualizer escapes HTML correctly.""" <add> doc = Doc(en_vocab, words=["test", "<RELEASE>", "test"]) <add> doc.ents = [Span(doc, 0, 1, label="TEST")] <add> html = displacy.render(doc, style="ent") <add> assert "&lt;RELEASE&gt;" in html <add> doc.ents = [Span(doc, 1, 2, label="TEST")] <add> html = displacy.render(doc, style="ent") <add> assert "&lt;RELEASE&gt;" in html
2
Python
Python
add api conversion interface for dropout layer
1606dc6a110ea49e9ea095ff88d684f87e398aa7
<ide><path>keras/layers/core.py <ide> class Dropout(Layer): <ide> # References <ide> - [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) <ide> """ <del> <add> @interfaces.legacy_dropout_support <ide> def __init__(self, rate, noise_shape=None, seed=None, **kwargs): <ide> super(Dropout, self).__init__(**kwargs) <ide> self.rate = min(1., max(0., rate)) <ide><path>keras/legacy/interfaces.py <ide> def wrapper(*args, **kwargs): <ide> <ide> return func(*args, **kwargs) <ide> return wrapper <add> <add> <add>def legacy_dropout_support(func): <add> """Function wrapper to convert the `Dropout` constructor from Keras 1 to 2. <add> <add> # Arguments <add> func: `__init__` method of `Dropout`. <add> <add> # Returns <add> A constructor conversion wrapper. <add> """ <add> @six.wraps(func) <add> def wrapper(*args, **kwargs): <add> if len(args) > 2: <add> # The first entry in `args` is `self`. <add> raise TypeError('The `Dropout` layer can have at most ' <add> 'one positional argument (the `rate` argument).') <add> <add> # Convert `p` to `rate` if keyword arguement is used <add> if 'p' in kwargs: <add> if len(args) > 1: <add> raise TypeError('Got both a positional argument ' <add> 'and keyword argument for argument ' <add> '`rate` ' <add> '(`p` in the legacy interface).') <add> if 'rate' in kwargs: <add> raise_duplicate_arg_error('p', 'rate') <add> rate = kwargs.pop('p') <add> args = (args[0], rate) <add> signature = '`Dropout(rate=' + str(args[1]) <add> for kwarg in kwargs: <add> signature += ', ' + kwarg + "=" <add> if isinstance(kwargs[kwarg], six.string_types): <add> signature += ('"' + kwargs[kwarg] + '"') <add> else: <add> signature += str(kwargs[kwarg]) <add> signature += ')`' <add> warnings.warn('Update your `Dropout` layer call to Keras 2 API: ' + signature) <add> <add> return func(*args, **kwargs) <add> return wrapper <ide><path>tests/keras/legacy/interface_test.py <ide> def test_dense_legacy_interface(): <ide> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config()) <ide> <ide> <add>@keras_test <add>def test_dropout_legacy_interface(): <add> old_layer = keras.layers.Dropout(p=3, name='drop') <add> new_layer_1 = keras.layers.Dropout(rate=3, name='drop') <add> new_layer_2 = keras.layers.Dropout(3, name='drop') <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer_1.get_config()) <add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer_2.get_config()) <add> <ide> if __name__ == '__main__': <ide> pytest.main([__file__])
3
Text
Text
add axes challenge
f991a487a1a715651ec01be9f512dece0bdd370a
<ide><path>guide/english/certifications/data-visualization/data-visualization-with-d3/add-axes-to-a-visualization/index.md <ide> title: Add Axes to a Visualization <ide> --- <ide> ## Add Axes to a Visualization <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/data-visualization/data-visualization-with-d3/add-axes-to-a-visualization/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>### Hint 1 <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add>Set the y-axis variable using `const yAxis = d3.axisLeft(yScale);`. <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>### Hint 2 <add> <add>Append the y-axis using `svg.append()`. <add> <add>### Spoiler Alert | Solution Ahead <add>### Solution <add> <add>To solve the challenge, use: <add>```html <add><body> <add> <script> <add> const dataset = [ <add> [ 34, 78 ], <add> [ 109, 280 ], <add> [ 310, 120 ], <add> [ 79, 411 ], <add> [ 420, 220 ], <add> [ 233, 145 ], <add> [ 333, 96 ], <add> [ 222, 333 ], <add> [ 78, 320 ], <add> [ 21, 123 ] <add> ]; <add> <add> const w = 500; <add> const h = 500; <add> const padding = 60; <add> <add> const xScale = d3.scaleLinear() <add> .domain([0, d3.max(dataset, (d) => d[0])]) <add> .range([padding, w - padding]); <add> <add> const yScale = d3.scaleLinear() <add> .domain([0, d3.max(dataset, (d) => d[1])]) <add> .range([h - padding, padding]); <add> <add> const svg = d3.select("body") <add> .append("svg") <add> .attr("width", w) <add> .attr("height", h); <add> <add> svg.selectAll("circle") <add> .data(dataset) <add> .enter() <add> .append("circle") <add> .attr("cx", (d) => xScale(d[0])) <add> .attr("cy",(d) => yScale(d[1])) <add> .attr("r", (d) => 5); <add> <add> svg.selectAll("text") <add> .data(dataset) <add> .enter() <add> .append("text") <add> .text((d) => (d[0] + "," + d[1])) <add> .attr("x", (d) => xScale(d[0] + 10)) <add> .attr("y", (d) => yScale(d[1])) <add> <add> const xAxis = d3.axisBottom(xScale); <add> const yAxis = d3.axisLeft(yScale); <add> <add> svg.append("g") <add> .attr("transform", "translate(0," + (h - padding) + ")") <add> .call(xAxis); <add> <add> svg.append("g") <add> .attr("transform", "translate(" + padding + ", 0)") <add> .call(yAxis); <add> </script> <add></body> <add>```
1
PHP
PHP
update doc block
226c9dc2ba0c9f8d79f816e523eafd8f94f37dfe
<ide><path>src/Routing/Route/Route.php <ide> public function setMethods(array $methods) <ide> } <ide> <ide> /** <del> * Set routing key patterns for routing parameters <add> * Set regexp patterns for routing parameters <ide> * <ide> * @param array $patterns The patterns to apply to routing elements <ide> * @return $this
1
Ruby
Ruby
remove unnecessary require
98e10209243b1048d2e9f7deca1494dc5096d352
<ide><path>activerecord/lib/active_record/middleware/shard_selector.rb <ide> # frozen_string_literal: true <ide> <del>require "active_record/middleware/database_selector/resolver" <del> <ide> module ActiveRecord <ide> module Middleware <ide> # The ShardSelector Middleware provides a framework for automatically
1
Javascript
Javascript
allow bound outlet names
6e63de48f3a94aa4ef3e76b484074807faa8df77
<ide><path>packages/ember-htmlbars/lib/keywords/real_outlet.js <ide> <ide> import { get } from "ember-metal/property_get"; <ide> import ComponentNode from "ember-htmlbars/system/component-node"; <del>import { isStream } from "ember-metal/streams/utils"; <ide> import topLevelViewTemplate from "ember-htmlbars/templates/top-level-view"; <ide> topLevelViewTemplate.revision = 'Ember@VERSION_STRING_PLACEHOLDER'; <ide> <ide> export default { <ide> setupState(state, env, scope, params, hash) { <ide> var outletState = env.outletState; <ide> var read = env.hooks.getValue; <del> <del> Ember.assert( <del> "Using {{outlet}} with an unquoted name is not supported.", <del> !params[0] || !isStream(params[0]) <del> ); <del> <ide> var outletName = read(params[0]) || 'main'; <ide> var selectedOutletState = outletState[outletName]; <ide> <ide><path>packages/ember-routing-htmlbars/tests/helpers/outlet_test.js <ide> QUnit.test("should not throw deprecations if {{outlet}} is used with a quoted na <ide> runAppend(top); <ide> }); <ide> <del>QUnit.test("should throw an assertion if {{outlet}} used with unquoted name", function() { <del> top.setOutletState(withTemplate("{{outlet foo}}")); <del> expectAssertion(function() { <del> runAppend(top); <del> }, "Using {{outlet}} with an unquoted name is not supported."); <add>QUnit.test("{{outlet}} should work with an unquoted name", function() { <add> var routerState = { <add> render: { <add> controller: Ember.Controller.create({ <add> outletName: 'magical' <add> }), <add> template: compile('{{outlet outletName}}') <add> }, <add> outlets: { <add> magical: withTemplate("It's magic") <add> } <add> }; <add> <add> top.setOutletState(routerState); <add> runAppend(top); <add> <add> equal(top.$().text().trim(), "It's magic"); <ide> }); <ide> <add>QUnit.test("{{outlet}} should rerender when bound name changes", function() { <add> var routerState = { <add> render: { <add> controller: Ember.Controller.create({ <add> outletName: 'magical' <add> }), <add> template: compile('{{outlet outletName}}') <add> }, <add> outlets: { <add> magical: withTemplate("It's magic"), <add> second: withTemplate("second") <add> } <add> }; <add> <add> top.setOutletState(routerState); <add> runAppend(top); <add> equal(top.$().text().trim(), "It's magic"); <add> run(function() { <add> routerState.render.controller.set('outletName', 'second'); <add> }); <add> equal(top.$().text().trim(), "second"); <add>}); <add> <add> <ide> function withTemplate(string) { <ide> return { <ide> render: {
2
Javascript
Javascript
upgrade tapable for compilation
7787b4ad132f7ee1deda8f57f6a06ed0b32d1b3b
<ide><path>lib/Compilation.js <ide> <ide> const asyncLib = require("async"); <ide> const util = require("util"); <del>const Tapable = require("tapable-old"); <add>const Tapable = require("tapable").Tapable; <add>const SyncHook = require("tapable").SyncHook; <add>const SyncBailHook = require("tapable").SyncBailHook; <add>const SyncWaterfallHook = require("tapable").SyncWaterfallHook; <add>const AsyncSeriesHook = require("tapable").AsyncSeriesHook; <ide> const EntryModuleNotFoundError = require("./EntryModuleNotFoundError"); <ide> const ModuleNotFoundError = require("./ModuleNotFoundError"); <ide> const ModuleDependencyWarning = require("./ModuleDependencyWarning"); <ide> function addAllToSet(set, otherSet) { <ide> class Compilation extends Tapable { <ide> constructor(compiler) { <ide> super(); <add> this.hooks = { <add> buildModule: new SyncHook(["module"]), <add> failedModule: new SyncHook(["module", "error"]), <add> succeedModule: new SyncHook(["module"]), <add> <add> finishModules: new SyncHook(["modules"]), <add> <add> unseal: new SyncHook([]), <add> seal: new SyncHook([]), <add> <add> optimizeDependenciesBasic: new SyncBailHook(["modules"]), <add> optimizeDependencies: new SyncBailHook(["modules"]), <add> optimizeDependenciesAdvanced: new SyncBailHook(["modules"]), <add> afterOptimizeDependencies: new SyncHook(["modules"]), <add> <add> optimize: new SyncHook([]), <add> <add> optimizeModulesBasic: new SyncBailHook(["modules"]), <add> optimizeModules: new SyncBailHook(["modules"]), <add> optimizeModulesAdvanced: new SyncBailHook(["modules"]), <add> afterOptimizeModules: new SyncHook(["modules"]), <add> <add> optimizeChunksBasic: new SyncBailHook(["chunks"]), <add> optimizeChunks: new SyncBailHook(["chunks"]), <add> optimizeChunksAdvanced: new SyncBailHook(["chunks"]), <add> afterOptimizeChunks: new SyncHook(["chunks"]), <add> <add> optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), <add> afterOptimizeTree: new SyncHook(["chunks", "modules"]), <add> <add> optimizeChunkModulesBasic: new SyncBailHook(["chunks", "modules"]), <add> optimizeChunkModules: new SyncBailHook(["chunks", "modules"]), <add> optimizeChunkModulesAdvanced: new SyncBailHook(["chunks", "modules"]), <add> afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), <add> shouldRecord: new SyncBailHook([]), <add> <add> reviveModules: new SyncHook(["modules", "records"]), <add> optimizeModuleOrder: new SyncHook(["modules"]), <add> advancedOptimizeModuleOrder: new SyncHook(["modules"]), <add> beforeModuleIds: new SyncHook(["modules"]), <add> moduleIds: new SyncHook(["modules"]), <add> optimizeModuleIds: new SyncHook(["modules"]), <add> afterOptimizeModuleIds: new SyncHook(["modules"]), <add> <add> reviveChunks: new SyncHook(["chunks", "records"]), <add> optimizeChunkOrder: new SyncHook(["chunks"]), <add> beforeChunkIds: new SyncHook(["chunks"]), <add> optimizeChunkIds: new SyncHook(["chunks"]), <add> afterOptimizeChunkIds: new SyncHook(["chunks"]), <add> <add> recordModules: new SyncHook(["modules", "records"]), <add> recordChunks: new SyncHook(["chunks", "records"]), <add> <add> beforeHash: new SyncHook([]), <add> afterHash: new SyncHook([]), <add> <add> recordHash: new SyncHook(["records"]), <add> <add> record: new SyncHook(["compilation", "records"]), <add> <add> beforeModuleAssets: new SyncHook([]), <add> shouldGenerateChunkAssets: new SyncBailHook([]), <add> beforeChunkAssets: new SyncHook([]), <add> additionalChunkAssets: new SyncHook(["chunks"]), <add> <add> records: new SyncHook(["compilation", "records"]), <add> <add> additionalAssets: new AsyncSeriesHook([]), <add> optimizeChunkAssets: new AsyncSeriesHook(["chunks"]), <add> afterOptimizeChunkAssets: new SyncHook(["chunks"]), <add> optimizeAssets: new AsyncSeriesHook(["assets"]), <add> afterOptimizeAssets: new SyncHook(["assets"]), <add> <add> needAdditionalSeal: new SyncBailHook([]), <add> afterSeal: new AsyncSeriesHook([]), <add> <add> chunkHash: new SyncHook(["chunk", "chunkHash"]), <add> moduleAsset: new SyncHook(["module", "filename"]), <add> chunkAsset: new SyncHook(["chunk", "filename"]), <add> <add> assetPath: new SyncWaterfallHook(["filename", "data"]), // TODO MainTemplate <add> <add> needAdditionalPass: new SyncBailHook([]), <add> childCompiler: new SyncHook(["childCompiler", "compilerName", "compilerIndex"]), <add> <add> // TODO the following hooks are weirdly located here <add> // TODO move them for webpack 5 <add> normalModuleLoader: new SyncHook(["loaderContext", "module"]), <add> <add> optimizeExtractedChunksBasic: new SyncBailHook(["chunks"]), <add> optimizeExtractedChunks: new SyncBailHook(["chunks"]), <add> optimizeExtractedChunksAdvanced: new SyncBailHook(["chunks"]), <add> afterOptimizeExtractedChunks: new SyncHook(["chunks"]), <add> }; <add> this._pluginCompat.tap("Compilation", options => { <add> switch(options.name) { <add> case "optimize-tree": <add> case "additional-assets": <add> case "optimize-chunk-assets": <add> case "optimize-assets": <add> case "after-seal": <add> options.async = true; <add> break; <add> } <add> }); <ide> this.compiler = compiler; <ide> this.resolverFactory = compiler.resolverFactory; <ide> this.inputFileSystem = compiler.inputFileSystem; <ide> class Compilation extends Tapable { <ide> } <ide> <ide> buildModule(module, optional, origin, dependencies, thisCallback) { <del> this.applyPlugins1("build-module", module); <add> this.hooks.buildModule.call(module); <ide> let callbackList = this._buildingModules.get(module); <ide> if(callbackList) { <ide> callbackList.push(thisCallback); <ide> class Compilation extends Tapable { <ide> } <ide> module.dependencies.sort(Dependency.compare); <ide> if(error) { <del> this.applyPlugins2("failed-module", module, error); <add> this.hooks.failedModule.call(module, error); <ide> return callback(error); <ide> } <del> this.applyPlugins1("succeed-module", module); <add> this.hooks.succeedModule.call(module); <ide> return callback(); <ide> }); <ide> } <ide> class Compilation extends Tapable { <ide> <ide> finish() { <ide> const modules = this.modules; <del> this.applyPlugins1("finish-modules", modules); <add> this.hooks.finishModules.call(modules); <ide> <ide> for(let index = 0; index < modules.length; index++) { <ide> const module = modules[index]; <ide> class Compilation extends Tapable { <ide> } <ide> <ide> unseal() { <del> this.applyPlugins0("unseal"); <add> this.hooks.unseal.call(); <ide> this.chunks.length = 0; <ide> this.namedChunks = {}; <ide> this.additionalChunkAssets.length = 0; <ide> class Compilation extends Tapable { <ide> } <ide> <ide> seal(callback) { <del> this.applyPlugins0("seal"); <add> this.hooks.seal.call(); <ide> <del> while(this.applyPluginsBailResult1("optimize-dependencies-basic", this.modules) || <del> this.applyPluginsBailResult1("optimize-dependencies", this.modules) || <del> this.applyPluginsBailResult1("optimize-dependencies-advanced", this.modules)) { /* empty */ } <del> this.applyPlugins1("after-optimize-dependencies", this.modules); <add> while(this.hooks.optimizeDependenciesBasic.call(this.modules) || <add> this.hooks.optimizeDependencies.call(this.modules) || <add> this.hooks.optimizeDependenciesAdvanced.call(this.modules)) { /* empty */ } <add> this.hooks.afterOptimizeDependencies.call(this.modules); <ide> <ide> this.nextFreeModuleIndex = 0; <ide> this.nextFreeModuleIndex2 = 0; <ide> class Compilation extends Tapable { <ide> }); <ide> this.processDependenciesBlocksForChunks(this.chunks.slice()); <ide> this.sortModules(this.modules); <del> this.applyPlugins0("optimize"); <add> this.hooks.optimize.call(); <ide> <del> while(this.applyPluginsBailResult1("optimize-modules-basic", this.modules) || <del> this.applyPluginsBailResult1("optimize-modules", this.modules) || <del> this.applyPluginsBailResult1("optimize-modules-advanced", this.modules)) { /* empty */ } <del> this.applyPlugins1("after-optimize-modules", this.modules); <add> while(this.hooks.optimizeModulesBasic.call(this.modules) || <add> this.hooks.optimizeModules.call(this.modules) || <add> this.hooks.optimizeModulesAdvanced.call(this.modules)) { /* empty */ } <add> this.hooks.afterOptimizeModules.call(this.modules); <ide> <del> while(this.applyPluginsBailResult1("optimize-chunks-basic", this.chunks) || <del> this.applyPluginsBailResult1("optimize-chunks", this.chunks) || <del> this.applyPluginsBailResult1("optimize-chunks-advanced", this.chunks)) { /* empty */ } <del> this.applyPlugins1("after-optimize-chunks", this.chunks); <add> while(this.hooks.optimizeChunksBasic.call(this.chunks) || <add> this.hooks.optimizeChunks.call(this.chunks) || <add> this.hooks.optimizeChunksAdvanced.call(this.chunks)) { /* empty */ } <add> this.hooks.afterOptimizeChunks.call(this.chunks); <ide> <del> this.applyPluginsAsyncSeries("optimize-tree", this.chunks, this.modules, err => { <add> this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { <ide> if(err) { <ide> return callback(err); <ide> } <ide> <del> this.applyPlugins2("after-optimize-tree", this.chunks, this.modules); <add> this.hooks.afterOptimizeTree.call(this.chunks, this.modules); <ide> <del> while(this.applyPluginsBailResult("optimize-chunk-modules-basic", this.chunks, this.modules) || <del> this.applyPluginsBailResult("optimize-chunk-modules", this.chunks, this.modules) || <del> this.applyPluginsBailResult("optimize-chunk-modules-advanced", this.chunks, this.modules)) { /* empty */ } <del> this.applyPlugins2("after-optimize-chunk-modules", this.chunks, this.modules); <add> while(this.hooks.optimizeChunkModulesBasic.call(this.chunks, this.modules) || <add> this.hooks.optimizeChunkModules.call(this.chunks, this.modules) || <add> this.hooks.optimizeChunkModulesAdvanced.call(this.chunks, this.modules)) { /* empty */ } <add> this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); <ide> <del> const shouldRecord = this.applyPluginsBailResult("should-record") !== false; <add> const shouldRecord = this.hooks.shouldRecord.call() !== false; <ide> <del> this.applyPlugins2("revive-modules", this.modules, this.records); <del> this.applyPlugins1("optimize-module-order", this.modules); <del> this.applyPlugins1("advanced-optimize-module-order", this.modules); <del> this.applyPlugins1("before-module-ids", this.modules); <del> this.applyPlugins1("module-ids", this.modules); <add> this.hooks.reviveModules.call(this.modules, this.records); <add> this.hooks.optimizeModuleOrder.call(this.modules); <add> this.hooks.advancedOptimizeModuleOrder.call(this.modules); <add> this.hooks.beforeModuleIds.call(this.modules); <add> this.hooks.moduleIds.call(this.modules); <ide> this.applyModuleIds(); <del> this.applyPlugins1("optimize-module-ids", this.modules); <del> this.applyPlugins1("after-optimize-module-ids", this.modules); <add> this.hooks.optimizeModuleIds.call(this.modules); <add> this.hooks.afterOptimizeModuleIds.call(this.modules); <ide> <ide> this.sortItemsWithModuleIds(); <ide> <del> this.applyPlugins2("revive-chunks", this.chunks, this.records); <del> this.applyPlugins1("optimize-chunk-order", this.chunks); <del> this.applyPlugins1("before-chunk-ids", this.chunks); <add> this.hooks.reviveChunks.call(this.chunks, this.records); <add> this.hooks.optimizeChunkOrder.call(this.chunks); <add> this.hooks.beforeChunkIds.call(this.chunks); <ide> this.applyChunkIds(); <del> this.applyPlugins1("optimize-chunk-ids", this.chunks); <del> this.applyPlugins1("after-optimize-chunk-ids", this.chunks); <add> this.hooks.optimizeChunkIds.call(this.chunks); <add> this.hooks.afterOptimizeChunkIds.call(this.chunks); <ide> <ide> this.sortItemsWithChunkIds(); <ide> <ide> if(shouldRecord) <del> this.applyPlugins2("record-modules", this.modules, this.records); <add> this.hooks.recordModules.call(this.modules, this.records); <ide> if(shouldRecord) <del> this.applyPlugins2("record-chunks", this.chunks, this.records); <add> this.hooks.recordChunks.call(this.chunks, this.records); <ide> <del> this.applyPlugins0("before-hash"); <add> this.hooks.beforeHash.call(); <ide> this.createHash(); <del> this.applyPlugins0("after-hash"); <add> this.hooks.afterHash.call(); <ide> <ide> if(shouldRecord) <del> this.applyPlugins1("record-hash", this.records); <add> this.hooks.recordHash.call(this.records); <ide> <del> this.applyPlugins0("before-module-assets"); <add> this.hooks.beforeModuleAssets.call(); <ide> this.createModuleAssets(); <del> if(this.applyPluginsBailResult("should-generate-chunk-assets") !== false) { <del> this.applyPlugins0("before-chunk-assets"); <add> if(this.hooks.shouldGenerateChunkAssets.call() !== false) { <add> this.hooks.beforeChunkAssets.call(); <ide> this.createChunkAssets(); <ide> } <del> this.applyPlugins1("additional-chunk-assets", this.chunks); <add> this.hooks.additionalChunkAssets.call(this.chunks); <ide> this.summarizeDependencies(); <ide> if(shouldRecord) <del> this.applyPlugins2("record", this, this.records); <add> this.hooks.record.call(this, this.records); <ide> <del> this.applyPluginsAsync("additional-assets", err => { <add> this.hooks.additionalAssets.callAsync(err => { <ide> if(err) { <ide> return callback(err); <ide> } <del> this.applyPluginsAsync("optimize-chunk-assets", this.chunks, err => { <add> this.hooks.optimizeChunkAssets.callAsync(this.chunks, err => { <ide> if(err) { <ide> return callback(err); <ide> } <del> this.applyPlugins1("after-optimize-chunk-assets", this.chunks); <del> this.applyPluginsAsync("optimize-assets", this.assets, err => { <add> this.hooks.afterOptimizeChunkAssets.call(this.chunks); <add> this.hooks.optimizeAssets.callAsync(this.assets, err => { <ide> if(err) { <ide> return callback(err); <ide> } <del> this.applyPlugins1("after-optimize-assets", this.assets); <del> if(this.applyPluginsBailResult("need-additional-seal")) { <add> this.hooks.afterOptimizeAssets.call(this.assets); <add> if(this.hooks.needAdditionalSeal.call()) { <ide> this.unseal(); <ide> return this.seal(callback); <ide> } <del> return this.applyPluginsAsync("after-seal", callback); <add> return this.hooks.afterSeal.callAsync(callback); <ide> }); <ide> }); <ide> }); <ide> class Compilation extends Tapable { <ide> } else { <ide> this.chunkTemplate.updateHashForChunk(chunkHash, chunk); <ide> } <del> this.applyPlugins2("chunk-hash", chunk, chunkHash); <add> this.hooks.chunkHash.call(chunk, chunkHash); <ide> chunk.hash = chunkHash.digest(hashDigest); <ide> hash.update(chunk.hash); <ide> chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); <ide> class Compilation extends Tapable { <ide> Object.keys(module.assets).forEach((assetName) => { <ide> const fileName = this.getPath(assetName); <ide> this.assets[fileName] = module.assets[assetName]; <del> this.applyPlugins2("module-asset", module, fileName); <add> this.hooks.moduleAsset.call(module, fileName); <ide> }); <ide> } <ide> } <ide> class Compilation extends Tapable { <ide> throw new Error(`Conflict: Multiple assets emit to the same filename ${file}`); <ide> this.assets[file] = source; <ide> chunk.files.push(file); <del> this.applyPlugins2("chunk-asset", chunk, file); <add> this.hooks.chunkAsset.call(chunk, file); <ide> } <ide> } catch(err) { <ide> this.errors.push(new ChunkRenderError(chunk, file || filenameTemplate, err)); <ide> class Compilation extends Tapable { <ide> chunk.checkConstraints(); <ide> } <ide> } <add> <add> applyPlugins(name, ...args) { <add> this.hooks[name.replace(/[- ]([a-z])/g, match => match[1].toUpperCase())].call(...args); <add> } <ide> } <ide> <ide> Object.defineProperty(Compilation.prototype, "moduleTemplate", { <ide><path>lib/Compiler.js <ide> class Watching { <ide> this.compiler.emitRecords(err => { <ide> if(err) return this._done(err); <ide> <del> if(compilation.applyPluginsBailResult("need-additional-pass")) { <add> if(compilation.hooks.needAdditionalPass.call()) { <ide> compilation.needAdditionalPass = true; <ide> <ide> const stats = new Stats(compilation); <ide> class Compiler extends Tapable { <ide> this.emitAssets(compilation, err => { <ide> if(err) return callback(err); <ide> <del> if(compilation.applyPluginsBailResult("need-additional-pass")) { <add> if(compilation.hooks.needAdditionalPass.call()) { <ide> compilation.needAdditionalPass = true; <ide> <ide> const stats = new Stats(compilation); <ide> class Compiler extends Tapable { <ide> } <ide> childCompiler.parentCompilation = compilation; <ide> <del> compilation.applyPlugins("child-compiler", childCompiler, compilerName, compilerIndex); <add> compilation.hooks.childCompiler.call(childCompiler, compilerName, compilerIndex); <ide> <ide> return childCompiler; <ide> } <ide><path>lib/NormalModule.js <ide> class NormalModule extends Module { <ide> fs: fs, <ide> }; <ide> <del> compilation.applyPlugins("normal-module-loader", loaderContext, this); <add> compilation.hooks.normalModuleLoader.call(loaderContext, this); <ide> if(options.loader) <ide> Object.assign(loaderContext, options.loader); <ide>
3
Ruby
Ruby
add a comment for sanity of other people to come
e7facb35eb67836d446283bcb7d15d665b1bb668
<ide><path>activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb <ide> def test_habtm_respects_select_query_method <ide> end <ide> <ide> def test_join_table_alias <add> # FIXME: `references` has no impact on the aliases generated for the join <add> # query. The fact that we pass `:developers_projects_join` to `references` <add> # and that the SQL string contains `developers_projects_join` is merely a <add> # coincidence. <ide> assert_equal( <ide> 3, <ide> Developer.references(:developers_projects_join).merge( <ide> def test_join_table_alias <ide> end <ide> <ide> def test_join_with_group <add> # FIXME: `references` has no impact on the aliases generated for the join <add> # query. The fact that we pass `:developers_projects_join` to `references` <add> # and that the SQL string contains `developers_projects_join` is merely a <add> # coincidence. <ide> group = Developer.columns.inject([]) do |g, c| <ide> g << "developers.#{c.name}" <ide> g << "developers_projects_2.#{c.name}"
1
Javascript
Javascript
eliminate vestigial yes and no
dc40aa710789e5789802a9d5045ff5787fc75da4
<ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> EmberHandlebars.registerHelper('bindAttr', function(options) { <ide> change, the correct class name will be reapplied to the DOM element. <ide> <ide> For example, if you pass the string "fooBar", it will first look up the <del> "fooBar" value of the context. If that value is YES, it will add the <add> "fooBar" value of the context. If that value is true, it will add the <ide> "foo-bar" class to the current element (i.e., the dasherized form of <ide> "fooBar"). If the value is a string, it will add that string as the class. <ide> Otherwise, it will not add any new class name. <ide> EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId) <ide> var parts = property.split('.'); <ide> return Ember.String.dasherize(parts[parts.length-1]); <ide> <del> // If the value is not NO, undefined, or null, return the current <add> // If the value is not false, undefined, or null, return the current <ide> // value of the property. <ide> } else if (val !== false && val !== undefined && val !== null) { <ide> return val; <ide><path>packages/ember-handlebars/lib/views/bindable_span.js <ide> Ember._BindableSpanView = Ember.View.extend(Ember.Metamorph, <ide> <ide> For example, this is true when using the `{{#if}}` helper, because the <ide> template inside the helper should look up properties relative to the same <del> object as outside the block. This would be NO when used with `{{#with <add> object as outside the block. This would be false when used with `{{#with <ide> foo}}` because the template should receive the object found by evaluating <ide> `foo`. <ide> <ide><path>packages/ember-handlebars/tests/controls/text_area_test.js <ide> test("should call the cancel method when escape key is pressed", function() { <ide> <ide> // textArea.insertNewline = function() { <ide> // insertNewlineCalled++; <del>// return YES; <add>// return true; <ide> // }; <ide> // textArea.cancel = function() { <ide> // cancelCalled++; <del>// return YES; <add>// return true; <ide> // }; <ide> <ide> // textArea.$().focus(); <ide><path>packages/ember-handlebars/tests/controls/text_field_test.js <ide> test("should call the cancel method when escape key is pressed", function() { <ide> <ide> // textField.insertNewline = function() { <ide> // insertNewlineCalled++; <del>// return YES; <add>// return true; <ide> // }; <ide> // textField.cancel = function() { <ide> // cancelCalled++; <del>// return YES; <add>// return true; <ide> // }; <ide> <ide> // textField.$().focus(); <ide><path>packages/ember-metal/lib/binding.js <ide> Binding.prototype = /** @scope Ember.Binding.prototype */ { <ide> <ide> @param {Boolean} flag <ide> (Optional) passing nothing here will make the binding oneWay. You can <del> instead pass NO to disable oneWay, making the binding two way again. <add> instead pass false to disable oneWay, making the binding two way again. <ide> <ide> @returns {Ember.Binding} receiver <ide> */ <ide> Binding.prototype = /** @scope Ember.Binding.prototype */ { <ide> <ide> /** <ide> Adds a transform to convert the value to a bool value. If the value is <del> an array it will return YES if array is not empty. If the value is a <del> string it will return YES if the string is not empty. <add> an array it will return true if array is not empty. If the value is a <add> string it will return true if the string is not empty. <ide> <ide> @returns {Ember.Binding} this <ide> */ <ide> Binding.prototype = /** @scope Ember.Binding.prototype */ { <ide> }, <ide> <ide> /** <del> Adds a transform that will return YES if the value is null or undefined, NO otherwise. <add> Adds a transform that will return true if the value is null or undefined, false otherwise. <ide> <ide> @returns {Ember.Binding} this <ide> */ <ide><path>packages/ember-metal/lib/utils.js <ide> Ember.wrap = function(func, superFunc) { <ide> /** <ide> @function <ide> <del> Returns YES if the passed object is an array or Array-like. <add> Returns true if the passed object is an array or Array-like. <ide> <ide> Ember Array Protocol: <ide> <ide><path>packages/ember-runtime/lib/core.js <ide> require('ember-metal'); <ide> // GLOBAL CONSTANTS <ide> // <ide> <del>/** <del> @name YES <del> @static <del> @type Boolean <del> @default true <del> @constant <del>*/ <del>YES = true; <del> <del>/** <del> @name NO <del> @static <del> @type Boolean <del> @default NO <del> @constant <del>*/ <del>NO = false; <del> <ide> // ensure no undefined errors in browsers where console doesn't exist <ide> if (typeof console === 'undefined') { <ide> window.console = {}; <ide> if (typeof console === 'undefined') { <ide> /** <ide> @static <ide> @type Boolean <del> @default YES <add> @default true <ide> @constant <ide> <ide> Determines whether Ember should enhances some built-in object <ide> Ember.typeOf = function(item) { <ide> }; <ide> <ide> /** <del> Returns YES if the passed value is null or undefined. This avoids errors <add> Returns true if the passed value is null or undefined. This avoids errors <ide> from JSLint complaining about use of ==, which can be technically <ide> confusing. <ide> <ide><path>packages/ember-runtime/lib/mixins/comparable.js <ide> Ember.Comparable = Ember.Mixin.create( /** @scope Ember.Comparable.prototype */{ <ide> walk like a duck. Indicates that the object can be compared. <ide> <ide> @type Boolean <del> @default YES <add> @default true <ide> @constant <ide> */ <ide> isComparable: true, <ide><path>packages/ember-runtime/lib/mixins/enumerable.js <ide> Ember.Enumerable = Ember.Mixin.create( /** @lends Ember.Enumerable */ { <ide> <ide> /** <ide> Returns an array with all of the items in the enumeration that the passed <del> function returns YES for. This method corresponds to filter() defined in <add> function returns true for. This method corresponds to filter() defined in <ide> JavaScript 1.6. <ide> <ide> The callback method you provide should have the following signature (all <ide> Ember.Enumerable = Ember.Mixin.create( /** @lends Ember.Enumerable */ { <ide> - *index* is the current index in the iteration <ide> - *enumerable* is the enumerable object itself. <ide> <del> It should return the YES to include the item in the results, NO otherwise. <add> It should return the true to include the item in the results, false otherwise. <ide> <ide> Note that in addition to a callback, you can also pass an optional target <ide> object that will be set as "this" on the context. This is a good way <ide> Ember.Enumerable = Ember.Mixin.create( /** @lends Ember.Enumerable */ { <ide> }, <ide> <ide> /** <del> Returns the first item in the array for which the callback returns YES. <add> Returns the first item in the array for which the callback returns true. <ide> This method works similar to the filter() method defined in JavaScript 1.6 <ide> except that it will stop working on the array once a match is found. <ide> <ide> Ember.Enumerable = Ember.Mixin.create( /** @lends Ember.Enumerable */ { <ide> - *index* is the current index in the iteration <ide> - *enumerable* is the enumerable object itself. <ide> <del> It should return the YES to include the item in the results, NO otherwise. <add> It should return the true to include the item in the results, false otherwise. <ide> <ide> Note that in addition to a callback, you can also pass an optional target <ide> object that will be set as "this" on the context. This is a good way <ide> Ember.Enumerable = Ember.Mixin.create( /** @lends Ember.Enumerable */ { <ide> }, <ide> <ide> /** <del> Returns YES if the passed function returns YES for every item in the <add> Returns true if the passed function returns true for every item in the <ide> enumeration. This corresponds with the every() method in JavaScript 1.6. <ide> <ide> The callback method you provide should have the following signature (all <ide> Ember.Enumerable = Ember.Mixin.create( /** @lends Ember.Enumerable */ { <ide> - *index* is the current index in the iteration <ide> - *enumerable* is the enumerable object itself. <ide> <del> It should return the YES or NO. <add> It should return the true or false. <ide> <ide> Note that in addition to a callback, you can also pass an optional target <ide> object that will be set as "this" on the context. This is a good way <ide> Ember.Enumerable = Ember.Mixin.create( /** @lends Ember.Enumerable */ { <ide> <ide> <ide> /** <del> Returns YES if the passed function returns true for any item in the <add> Returns true if the passed function returns true for any item in the <ide> enumeration. This corresponds with the every() method in JavaScript 1.6. <ide> <ide> The callback method you provide should have the following signature (all <ide> Ember.Enumerable = Ember.Mixin.create( /** @lends Ember.Enumerable */ { <ide> - *index* is the current index in the iteration <ide> - *enumerable* is the enumerable object itself. <ide> <del> It should return the YES to include the item in the results, NO otherwise. <add> It should return the true to include the item in the results, false otherwise. <ide> <ide> Note that in addition to a callback, you can also pass an optional target <ide> object that will be set as "this" on the context. This is a good way <ide><path>packages/ember-runtime/lib/mixins/freezable.js <ide> Ember.Freezable = Ember.Mixin.create( <ide> /** @scope Ember.Freezable.prototype */ { <ide> <ide> /** <del> Set to YES when the object is frozen. Use this property to detect whether <add> Set to true when the object is frozen. Use this property to detect whether <ide> your object is frozen or not. <ide> <ide> @property {Boolean} <ide><path>packages/ember-runtime/lib/mixins/observable.js <ide> Ember.Observable = Ember.Mixin.create(/** @scope Ember.Observable.prototype */ { <ide> }, <ide> <ide> /** <del> Returns YES if the object currently has observers registered for a <add> Returns true if the object currently has observers registered for a <ide> particular key. You can use this method to potentially defer performing <ide> an expensive action until someone begins observing a particular property <ide> on the object. <ide><path>packages/ember-runtime/tests/legacy_1x/mixins/observable/observable_test.js <ide> test("change dependent should clear cache when observers of dependent are called <ide> <ide> test('setting one of two computed properties that depend on a third property should clear the kvo cache', function() { <ide> // we have to call set twice to fill up the cache <del> object.set('isOff', YES); <del> object.set('isOn', YES); <add> object.set('isOff', true); <add> object.set('isOn', true); <ide> <del> // setting isOff to YES should clear the kvo cache <del> object.set('isOff', YES); <del> equal(object.get('isOff'), YES, 'object.isOff should be YES'); <del> equal(object.get('isOn'), NO, 'object.isOn should be NO'); <add> // setting isOff to true should clear the kvo cache <add> object.set('isOff', true); <add> equal(object.get('isOff'), true, 'object.isOff should be true'); <add> equal(object.get('isOn'), false, 'object.isOn should be false'); <ide> }); <ide> <ide> test("dependent keys should be able to be specified as property paths", function() { <ide> test("should unregister an observer for a property - special case when key has a <ide> test("removing an observer inside of an observer shouldn’t cause any problems", function() { <ide> // The observable system should be protected against clients removing <ide> // observers in the middle of observer notification. <del> var encounteredError = NO; <add> var encounteredError = false; <ide> try { <ide> ObjectD.addObserver('observableValue', null, 'observer1'); <ide> ObjectD.addObserver('observableValue', null, 'observer2'); <ide> ObjectD.addObserver('observableValue', null, 'observer3'); <ide> Ember.run(function() { ObjectD.set('observableValue', "hi world"); }); <ide> } <ide> catch(e) { <del> encounteredError = YES; <add> encounteredError = true; <ide> } <del> equal(encounteredError, NO); <add> equal(encounteredError, false); <ide> }); <ide> <ide> <ide><path>packages/ember-runtime/tests/legacy_1x/mixins/observable/propertyChanges_test.js <ide> <ide> var ObservableObject = Ember.Object.extend(Ember.Observable); <ide> <del>var revMatches = NO , ObjectA; <add>var revMatches = false , ObjectA; <ide> <ide> module("object.propertyChanges", { <ide> setup: function() { <ide><path>packages/ember-runtime/tests/legacy_1x/system/binding_test.js <ide> test("changing first output should propograte to third after flush", function() <ide> equal("change", get(first, "output"), "first.output") ; <ide> ok("change" !== get(third, "input"), "third.input") ; <ide> <del> var didChange = YES; <add> var didChange = true; <ide> while(didChange) didChange = Ember.run.sync() ; <ide> <ide> equal("change", get(first, "output"), "first.output") ; <ide> module("AND binding", { <ide> setup: function() { <ide> // temporarily set up two source objects in the Ember namespace so we can <ide> // use property paths to access them <del> Ember.set(Ember, 'testControllerA', Ember.Object.create({ value: NO })); <del> Ember.set(Ember, 'testControllerB', Ember.Object.create({ value: NO })); <add> Ember.set(Ember, 'testControllerA', Ember.Object.create({ value: false })); <add> Ember.set(Ember, 'testControllerB', Ember.Object.create({ value: false })); <ide> <ide> toObject = Ember.Object.create({ <ide> value: null, <ide> module("AND binding", { <ide> <ide> }); <ide> <del>test("toObject.value should be YES if both sources are YES", function() { <add>test("toObject.value should be true if both sources are true", function() { <ide> Ember.RunLoop.begin(); <del> set(Ember.testControllerA, 'value', YES); <del> set(Ember.testControllerB, 'value', YES); <add> set(Ember.testControllerA, 'value', true); <add> set(Ember.testControllerB, 'value', true); <ide> Ember.RunLoop.end(); <ide> <ide> Ember.run.sync(); <del> equal(get(toObject, 'value'), YES); <add> equal(get(toObject, 'value'), true); <ide> }); <ide> <del>test("toObject.value should be NO if either source is NO", function() { <add>test("toObject.value should be false if either source is false", function() { <ide> Ember.RunLoop.begin(); <del> set(Ember.testControllerA, 'value', YES); <del> set(Ember.testControllerB, 'value', NO); <add> set(Ember.testControllerA, 'value', true); <add> set(Ember.testControllerB, 'value', false); <ide> Ember.RunLoop.end(); <ide> <ide> Ember.run.sync(); <del> equal(get(toObject, 'value'), NO); <add> equal(get(toObject, 'value'), false); <ide> <ide> Ember.RunLoop.begin(); <del> set(Ember.testControllerA, 'value', YES); <del> set(Ember.testControllerB, 'value', YES); <add> set(Ember.testControllerA, 'value', true); <add> set(Ember.testControllerB, 'value', true); <ide> Ember.RunLoop.end(); <ide> <ide> Ember.run.sync(); <del> equal(get(toObject, 'value'), YES); <add> equal(get(toObject, 'value'), true); <ide> <ide> Ember.RunLoop.begin(); <del> set(Ember.testControllerA, 'value', NO); <del> set(Ember.testControllerB, 'value', YES); <add> set(Ember.testControllerA, 'value', false); <add> set(Ember.testControllerB, 'value', true); <ide> Ember.RunLoop.end(); <ide> <ide> Ember.run.sync(); <del> equal(get(toObject, 'value'), NO); <add> equal(get(toObject, 'value'), false); <ide> }); <ide> <ide> // .......................................................... <ide> module("OR binding", { <ide> setup: function() { <ide> // temporarily set up two source objects in the Ember namespace so we can <ide> // use property paths to access them <del> Ember.set(Ember, 'testControllerA', Ember.Object.create({ value: NO })); <add> Ember.set(Ember, 'testControllerA', Ember.Object.create({ value: false })); <ide> Ember.set(Ember, 'testControllerB', Ember.Object.create({ value: null })); <ide> <ide> toObject = Ember.Object.create({ <ide> test("toObject.value should be first value if first value is truthy", function() <ide> <ide> test("toObject.value should be second value if first is falsy", function() { <ide> Ember.RunLoop.begin(); <del> set(Ember.testControllerA, 'value', NO); <add> set(Ember.testControllerA, 'value', false); <ide> set(Ember.testControllerB, 'value', 'second value'); <ide> Ember.RunLoop.end(); <ide> <ide><path>packages/ember-runtime/tests/legacy_1x/system/object/base_test.js <ide> module("A new Ember.Object instance", { <ide> aMethodThatExists: function() {}, <ide> aMethodThatReturnsTrue: function() { return true; }, <ide> aMethodThatReturnsFoobar: function() { return "Foobar"; }, <del> aMethodThatReturnsFalse: function() { return NO; } <add> aMethodThatReturnsFalse: function() { return false; } <ide> }); <ide> }, <ide> <ide> module("Ember.Object observers", { <ide> <ide> // normal observer <ide> observer: Ember.observer(function(){ <del> this._normal = YES; <add> this._normal = true; <ide> }, "prop1"), <ide> <ide> globalObserver: Ember.observer(function() { <del> this._global = YES; <add> this._global = true; <ide> }, "TestNamespace.obj.value"), <ide> <ide> bothObserver: Ember.observer(function() { <del> this._both = YES; <add> this._both = true; <ide> }, "prop1", "TestNamespace.obj.value") <ide> }); <ide> <ide> } <ide> }); <ide> <ide> test("Local observers work", function() { <del> obj._normal = NO; <del> set(obj, "prop1", NO); <del> equal(obj._normal, YES, "Normal observer did change."); <add> obj._normal = false; <add> set(obj, "prop1", false); <add> equal(obj._normal, true, "Normal observer did change."); <ide> }); <ide> <ide> test("Global observers work", function() { <del> obj._global = NO; <add> obj._global = false; <ide> set(TestNamespace.obj, "value", "test2"); <del> equal(obj._global, YES, "Global observer did change."); <add> equal(obj._global, true, "Global observer did change."); <ide> }); <ide> <ide> test("Global+Local observer works", function() { <del> obj._both = NO; <del> set(obj, "prop1", NO); <del> equal(obj._both, YES, "Both observer did change."); <add> obj._both = false; <add> set(obj, "prop1", false); <add> equal(obj._both, true, "Both observer did change."); <ide> }); <ide> <ide> <ide> module("Ember.Object superclass and subclasses", { <ide> }); <ide> <ide> test("Checking the detect() function on an object and its subclass", function(){ <del> equal(obj.detect(obj1), YES); <del> equal(obj1.detect(obj), NO); <add> equal(obj.detect(obj1), true); <add> equal(obj1.detect(obj), false); <ide> }); <ide> <ide> test("Checking the detectInstance() function on an object and its subclass", function() { <ide><path>packages/ember-runtime/tests/legacy_1x/system/object/bindings_test.js <ide> test("Ember.Binding.bool(TestNamespace.fromObject.bar)) should create binding wi <ide> set(fromObject, "bar", 1) ; <ide> <ide> Ember.run.sync(); <del> equal(YES, get(testObject, "foo"), "testObject.foo == YES"); <add> equal(true, get(testObject, "foo"), "testObject.foo == true"); <ide> <ide> set(fromObject, "bar", 0) ; <ide> <ide> Ember.run.sync(); <del> equal(NO, get(testObject, "foo"), "testObject.foo == NO"); <add> equal(false, get(testObject, "foo"), "testObject.foo == false"); <ide> }); <ide> <ide> test("bind(TestNamespace.fromObject*extraObject.foo) should create chained binding", function() { <ide> test("fooBinding: Ember.Binding.bool(TestNamespace.fromObject.bar should create <ide> set(fromObject, "bar", 1) ; <ide> <ide> Ember.run.sync(); <del> equal(YES, get(testObject, "foo"), "testObject.foo == YES"); <add> equal(true, get(testObject, "foo"), "testObject.foo == true"); <ide> <ide> set(fromObject, "bar", 0) ; <ide> <ide> Ember.run.sync(); <del> equal(NO, get(testObject, "foo"), "testObject.foo == NO"); <add> equal(false, get(testObject, "foo"), "testObject.foo == false"); <ide> }); <ide> <ide> test("fooBinding: TestNamespace.fromObject*extraObject.foo should create chained binding", function() { <ide> test("fooBinding: TestNamespace.fromObject.bar should have bool binding", functi <ide> set(fromObject, "bar", 1) ; <ide> <ide> Ember.run.sync(); <del> equal(YES, get(testObject, "foo"), "testObject.foo == YES"); <add> equal(true, get(testObject, "foo"), "testObject.foo == true"); <ide> <ide> set(fromObject, "bar", 0) ; <ide> <ide> Ember.run.sync(); <del> equal(NO, get(testObject, "foo"), "testObject.foo == NO"); <add> equal(false, get(testObject, "foo"), "testObject.foo == false"); <ide> }); <ide> <ide> test("fooBinding: Ember.Binding.not(TestNamespace.fromObject.bar should override default", function() { <ide> test("fooBinding: Ember.Binding.not(TestNamespace.fromObject.bar should override <ide> set(fromObject, "bar", 1) ; <ide> <ide> Ember.run.sync(); <del> equal(NO, get(testObject, "foo"), "testObject.foo == NO"); <add> equal(false, get(testObject, "foo"), "testObject.foo == false"); <ide> <ide> set(fromObject, "bar", 0) ; <ide> <ide> Ember.run.sync(); <del> equal(YES, get(testObject, "foo"), "testObject.foo == YES"); <add> equal(true, get(testObject, "foo"), "testObject.foo == true"); <ide> }); <ide> <ide> module("fooBindingDefault: Ember.Binding.bool() (new style)", { <ide> test("fooBinding: TestNamespace.fromObject.bar should have bool binding", functi <ide> set(fromObject, "bar", 1) ; <ide> <ide> Ember.run.sync(); <del> equal(YES, get(testObject, "foo"), "testObject.foo == YES"); <add> equal(true, get(testObject, "foo"), "testObject.foo == true"); <ide> <ide> set(fromObject, "bar", 0) ; <ide> <ide> Ember.run.sync(); <del> equal(NO, get(testObject, "foo"), "testObject.foo == NO"); <add> equal(false, get(testObject, "foo"), "testObject.foo == false"); <ide> }); <ide> <ide> test("fooBinding: Ember.Binding.not(TestNamespace.fromObject.bar should override default", function() { <ide> test("fooBinding: Ember.Binding.not(TestNamespace.fromObject.bar should override <ide> set(fromObject, "bar", 1) ; <ide> <ide> Ember.run.sync(); <del> equal(NO, get(testObject, "foo"), "testObject.foo == NO"); <add> equal(false, get(testObject, "foo"), "testObject.foo == false"); <ide> <ide> set(fromObject, "bar", 0) ; <ide> <ide> Ember.run.sync(); <del> equal(YES, get(testObject, "foo"), "testObject.foo == YES"); <add> equal(true, get(testObject, "foo"), "testObject.foo == true"); <ide> }); <ide> <ide> test("Chained binding should be null if intermediate object in chain is null", function() { <ide><path>packages/ember-runtime/tests/legacy_1x/system/set_test.js <ide> test("Ember.Set.create() should create empty set", function() { <ide> test("Ember.Set.create([1,2,3]) should create set with three items in them", function() { <ide> var set = Ember.Set.create(Ember.A([a,b,c])) ; <ide> equal(set.length, 3) ; <del> equal(set.contains(a), YES) ; <del> equal(set.contains(b), YES) ; <del> equal(set.contains(c), YES) ; <add> equal(set.contains(a), true) ; <add> equal(set.contains(b), true) ; <add> equal(set.contains(c), true) ; <ide> }); <ide> <ide> test("Ember.Set.create() should accept anything that implements Ember.Array", function() { <ide> test("Ember.Set.create() should accept anything that implements Ember.Array", fu <ide> <ide> var set = Ember.Set.create(arrayLikeObject) ; <ide> equal(set.length, 3) ; <del> equal(set.contains(a), YES) ; <del> equal(set.contains(b), YES) ; <del> equal(set.contains(c), YES) ; <add> equal(set.contains(a), true) ; <add> equal(set.contains(b), true) ; <add> equal(set.contains(c), true) ; <ide> }); <ide> <ide> var set ; // global variables <ide> test("should add an Ember.Object", function() { <ide> <ide> var oldLength = set.length ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES, "contains()") ; <add> equal(set.contains(obj), true, "contains()") ; <ide> equal(set.length, oldLength+1, "new set length") ; <ide> }); <ide> <ide> test("should add a regular hash", function() { <ide> <ide> var oldLength = set.length ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES, "contains()") ; <add> equal(set.contains(obj), true, "contains()") ; <ide> equal(set.length, oldLength+1, "new set length") ; <ide> }); <ide> <ide> test("should add a string", function() { <ide> <ide> var oldLength = set.length ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES, "contains()") ; <add> equal(set.contains(obj), true, "contains()") ; <ide> equal(set.length, oldLength+1, "new set length") ; <ide> }); <ide> <ide> test("should add a number", function() { <ide> <ide> var oldLength = set.length ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES, "contains()") ; <add> equal(set.contains(obj), true, "contains()") ; <ide> equal(set.length, oldLength+1, "new set length") ; <ide> }); <ide> <ide> test("should add bools", function() { <ide> var oldLength = set.length ; <ide> <ide> set.add(true) ; <del> equal(set.contains(true), YES, "contains(true)"); <add> equal(set.contains(true), true, "contains(true)"); <ide> equal(set.length, oldLength+1, "new set length"); <ide> <ide> set.add(false); <del> equal(set.contains(false), YES, "contains(false)"); <add> equal(set.contains(false), true, "contains(false)"); <ide> equal(set.length, oldLength+2, "new set length"); <ide> }); <ide> <ide> test("should add 0", function() { <ide> var oldLength = set.length ; <ide> <ide> set.add(0) ; <del> equal(set.contains(0), YES, "contains(0)"); <add> equal(set.contains(0), true, "contains(0)"); <ide> equal(set.length, oldLength+1, "new set length"); <ide> }); <ide> <ide> test("should add a function", function() { <ide> <ide> var oldLength = set.length ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES, "contains()") ; <add> equal(set.contains(obj), true, "contains()") ; <ide> equal(set.length, oldLength+1, "new set length") ; <ide> }); <ide> <ide> test("should NOT add a null", function() { <ide> set.add(null) ; <ide> equal(set.length, 0) ; <del> equal(set.contains(null), NO) ; <add> equal(set.contains(null), false) ; <ide> }); <ide> <ide> test("should NOT add an undefined", function() { <ide> set.add(undefined) ; <ide> equal(set.length, 0) ; <del> equal(set.contains(undefined), NO) ; <add> equal(set.contains(undefined), false) ; <ide> }); <ide> <ide> test("adding an item, removing it, adding another item", function() { <ide> test("adding an item, removing it, adding another item", function() { <ide> set.remove(item1) ; //remove from set <ide> set.add(item2) ; <ide> <del> equal(set.contains(item1), NO, "set.contains(item1)") ; <add> equal(set.contains(item1), false, "set.contains(item1)") ; <ide> <ide> set.add(item1) ; // re-add to set <ide> equal(set.length, 2, "set.length") ; <ide> module("Ember.Set.remove + Ember.Set.contains", { <ide> // ones we add in the tests below... <ide> setup: function() { <ide> set = Ember.Set.create(Ember.A([ <del> Ember.Object.create({ dummy: YES }), <del> { isHash: YES }, <add> Ember.Object.create({ dummy: true }), <add> { isHash: true }, <ide> "Not the String", <ide> 16, true, false, 0])) ; <ide> }, <ide> module("Ember.Set.remove + Ember.Set.contains", { <ide> test("should remove an Ember.Object and reduce length", function() { <ide> var obj = Ember.Object.create() ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES) ; <add> equal(set.contains(obj), true) ; <ide> var oldLength = set.length ; <ide> <ide> set.remove(obj) ; <del> equal(set.contains(obj), NO, "should be removed") ; <add> equal(set.contains(obj), false, "should be removed") ; <ide> equal(set.length, oldLength-1, "should be 1 shorter") ; <ide> }); <ide> <ide> test("should remove a regular hash and reduce length", function() { <ide> var obj = {} ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES) ; <add> equal(set.contains(obj), true) ; <ide> var oldLength = set.length ; <ide> <ide> set.remove(obj) ; <del> equal(set.contains(obj), NO, "should be removed") ; <add> equal(set.contains(obj), false, "should be removed") ; <ide> equal(set.length, oldLength-1, "should be 1 shorter") ; <ide> }); <ide> <ide> test("should remove a string and reduce length", function() { <ide> var obj = "String!" ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES) ; <add> equal(set.contains(obj), true) ; <ide> var oldLength = set.length ; <ide> <ide> set.remove(obj) ; <del> equal(set.contains(obj), NO, "should be removed") ; <add> equal(set.contains(obj), false, "should be removed") ; <ide> equal(set.length, oldLength-1, "should be 1 shorter") ; <ide> }); <ide> <ide> test("should remove a number and reduce length", function() { <ide> var obj = 23 ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES) ; <add> equal(set.contains(obj), true) ; <ide> var oldLength = set.length ; <ide> <ide> set.remove(obj) ; <del> equal(set.contains(obj), NO, "should be removed") ; <add> equal(set.contains(obj), false, "should be removed") ; <ide> equal(set.length, oldLength-1, "should be 1 shorter") ; <ide> }); <ide> <ide> test("should remove a bools and reduce length", function() { <ide> var oldLength = set.length ; <ide> set.remove(true) ; <del> equal(set.contains(true), NO, "should be removed") ; <add> equal(set.contains(true), false, "should be removed") ; <ide> equal(set.length, oldLength-1, "should be 1 shorter") ; <ide> <ide> set.remove(false); <del> equal(set.contains(false), NO, "should be removed") ; <add> equal(set.contains(false), false, "should be removed") ; <ide> equal(set.length, oldLength-2, "should be 2 shorter") ; <ide> }); <ide> <ide> test("should remove 0 and reduce length", function(){ <ide> var oldLength = set.length; <ide> set.remove(0) ; <del> equal(set.contains(0), NO, "should be removed") ; <add> equal(set.contains(0), false, "should be removed") ; <ide> equal(set.length, oldLength-1, "should be 1 shorter") ; <ide> }); <ide> <ide> test("should remove a function and reduce length", function() { <ide> var obj = function() { return "Test function"; } ; <ide> set.add(obj) ; <del> equal(set.contains(obj), YES) ; <add> equal(set.contains(obj), true) ; <ide> var oldLength = set.length ; <ide> <ide> set.remove(obj) ; <del> equal(set.contains(obj), NO, "should be removed") ; <add> equal(set.contains(obj), false, "should be removed") ; <ide> equal(set.length, oldLength-1, "should be 1 shorter") ; <ide> }); <ide> <ide> module("Ember.Set.pop + Ember.Set.copy", { <ide> // ones we add in the tests below... <ide> setup: function() { <ide> set = Ember.Set.create(Ember.A([ <del> Ember.Object.create({ dummy: YES }), <del> { isHash: YES }, <add> Ember.Object.create({ dummy: true }), <add> { isHash: true }, <ide> "Not the String", <ide> 16, false])) ; <ide> }, <ide> test("the copy() should return an indentical set", function() { <ide> var oldLength = set.length ; <ide> var obj = set.copy(); <ide> equal(oldLength,obj.length,'length of the clone should be same'); <del> equal(obj.contains(set[0]), YES); <del> equal(obj.contains(set[1]), YES); <del> equal(obj.contains(set[2]), YES); <del> equal(obj.contains(set[3]), YES); <del> equal(obj.contains(set[4]), YES); <add> equal(obj.contains(set[0]), true); <add> equal(obj.contains(set[1]), true); <add> equal(obj.contains(set[2]), true); <add> equal(obj.contains(set[3]), true); <add> equal(obj.contains(set[4]), true); <ide> }); <ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.Object.extend( <ide> <ide> /** <ide> @type Boolean <del> @default YES <add> @default true <ide> @constant <ide> */ <del> isView: YES, <add> isView: true, <ide> <ide> // .......................................................... <ide> // TEMPLATE SUPPORT <ide> Ember.View = Ember.Object.extend( <ide> <ide> // If value is a Boolean and true, return the dasherized property <ide> // name. <del> if (val === YES) { <add> if (val === true) { <ide> if (className) { return className; } <ide> <ide> // Normalize property path to be suitable for use <ide> Ember.View = Ember.Object.extend( <ide> var parts = property.split('.'); <ide> return Ember.String.dasherize(parts[parts.length-1]); <ide> <del> // If the value is not NO, undefined, or null, return the current <add> // If the value is not false, undefined, or null, return the current <ide> // value of the property. <del> } else if (val !== NO && val !== undefined && val !== null) { <add> } else if (val !== false && val !== undefined && val !== null) { <ide> return val; <ide> <ide> // Nothing to display. Return null so that the old class is removed <ide><path>packages/ember-views/tests/views/view/create_child_view_test.js <ide> var view, myViewClass ; <ide> module("Ember.View#createChildView", { <ide> setup: function() { <ide> view = Ember.View.create(); <del> myViewClass = Ember.View.extend({ isMyView: YES, foo: 'bar' }); <add> myViewClass = Ember.View.extend({ isMyView: true, foo: 'bar' }); <ide> } <ide> }); <ide>
19
Text
Text
add pgp key
2d8c307a3cfdb85dd462ab6acc0f1d24015b1a38
<ide><path>README.md <ide> Second, read the [Troubleshooting Checklist](https://github.com/Homebrew/homebre <ide> ## Security <ide> Please report security issues to security@brew.sh. <ide> <add>This is our PGP key which is valid until June 17, 2016. <add>* Key ID: `CE59E297` <add>* Fingeprint: `C657 8F76 2E23 441E C879 EC5C E33A 3D3C CE59 E297` <add>* Full key: https://keybase.io/homebrew/key.asc <add> <ide> ## Who Are You? <ide> Homebrew's current maintainers are [Misty De Meo](https://github.com/mistydemeo), [Adam Vandenberg](https://github.com/adamv), [Jack Nagel](https://github.com/jacknagel), [Xu Cheng](https://github.com/xu-cheng), [Mike McQuaid](https://github.com/mikemcquaid), [Baptiste Fontaine](https://github.com/bfontaine), [Brett Koonce](https://github.com/asparagui), [Dominyk Tiller](https://github.com/DomT4) and [Tim Smith](https://github.com/tdsmith). <ide>
1
Text
Text
add pronouns for ofrobots
2a6ab9b37bdb3cecfe124f5ffeac5093e298d4df
<ide><path>README.md <ide> For more information about the governance of the Node.js project, see <ide> * [MylesBorins](https://github.com/MylesBorins) - <ide> **Myles Borins** &lt;myles.borins@gmail.com&gt; (he/him) <ide> * [ofrobots](https://github.com/ofrobots) - <del>**Ali Ijaz Sheikh** &lt;ofrobots@google.com&gt; <add>**Ali Ijaz Sheikh** &lt;ofrobots@google.com&gt; (he/him) <ide> * [rvagg](https://github.com/rvagg) - <ide> **Rod Vagg** &lt;rod@vagg.org&gt; <ide> * [targos](https://github.com/targos) - <ide> For more information about the governance of the Node.js project, see <ide> * [not-an-aardvark](https://github.com/not-an-aardvark) - <ide> **Teddy Katz** &lt;teddy.katz@gmail.com&gt; <ide> * [ofrobots](https://github.com/ofrobots) - <del>**Ali Ijaz Sheikh** &lt;ofrobots@google.com&gt; <add>**Ali Ijaz Sheikh** &lt;ofrobots@google.com&gt; (he/him) <ide> * [orangemocha](https://github.com/orangemocha) - <ide> **Alexis Campailla** &lt;orangemocha@nodejs.org&gt; <ide> * [othiym23](https://github.com/othiym23) -
1
Text
Text
add v3.15.0-beta.3 to changelog
fbae785fefebc8935e33315e23e76682a42fbd75
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.15.0-beta.3 (November 18, 2019) <add> <add>- [#18549](https://github.com/emberjs/ember.js/pull/18549) [BUGFIX] Add component reference to the mouse event handler deprecation warnings <add> <ide> ### v3.15.0-beta.2 (November 11, 2019) <ide> <ide> - [#18539](https://github.com/emberjs/ember.js/pull/18539) [BUGFIX] Add ID to `CapturedRenderNode`
1
PHP
PHP
add virtual fields into __debuginfo() output
d6b0f18366791d861ab2ab3fb37654a32109af13
<ide><path>src/Datasource/EntityTrait.php <ide> public function __toString() <ide> */ <ide> public function __debugInfo() <ide> { <del> return $this->_properties + [ <add> $properties = $this->_properties; <add> foreach ($this->_virtual as $field) { <add> $properties[$field] = $this->$field; <add> } <add> <add> return $properties + [ <ide> '[new]' => $this->isNew(), <ide> '[accessible]' => $this->_accessible, <ide> '[dirty]' => $this->_dirty, <ide><path>tests/TestCase/ORM/EntityTest.php <ide> public function testDebugInfo() <ide> $expected = [ <ide> 'foo' => 'bar', <ide> 'somethingElse' => 'value', <add> 'baz' => null, <ide> '[new]' => true, <ide> '[accessible]' => ['*' => true, 'id' => false, 'name' => true], <ide> '[dirty]' => ['somethingElse' => true, 'foo' => true],
2
Python
Python
fix merge layer docstring
66e59447995bcdf0c2adad98766efa666fb2684f
<ide><path>keras/engine/topology.py <ide> class Merge(Layer): <ide> model1.add(Dense(32, input_dim=32)) <ide> <ide> model2 = Sequential() <del> model2.add(Dense(32)) <add> model2.add(Dense(32, input_dim=32)) <ide> <ide> merged_model = Sequential() <ide> merged_model.add(Merge([model1, model2], mode='concat', concat_axis=1)
1
Python
Python
add smallest_normal to the array api finfo
90537b5dac1d0c569baa794967b919ae4f6fdcca
<ide><path>numpy/array_api/_data_type_functions.py <ide> class finfo_object: <ide> eps: float <ide> max: float <ide> min: float <del> # Note: smallest_normal is part of the array API spec, but cannot be used <del> # until https://github.com/numpy/numpy/pull/18536 is merged. <del> <del> # smallest_normal: float <add> smallest_normal: float <ide> <ide> <ide> @dataclass <ide> def finfo(type: Union[Dtype, Array], /) -> finfo_object: <ide> float(fi.eps), <ide> float(fi.max), <ide> float(fi.min), <del> # TODO: Uncomment this when #18536 is merged. <del> # float(fi.smallest_normal), <add> float(fi.smallest_normal), <ide> ) <ide> <ide>
1
Text
Text
fix code snippet and typo in tutorial
994bed5819c3d444f3bf89ce23798cabdcd49d18
<ide><path>docs/tutorials/essentials/part-6-performance-normalization.md <ide> const notificationsSlice = createSlice({ <ide> }, <ide> extraReducers(builder) { <ide> builder.addCase(fetchNotifications.fulfilled, (state, action) => { <add> state.push(...action.payload) <ide> // highlight-start <ide> state.forEach(notification => { <ide> // Any notifications we've read are no longer new <ide> notification.isNew = !notification.read <ide> }) <ide> // highlight-end <del> state.push(...action.payload) <ide> // Sort with newest first <ide> state.sort((a, b) => b.date.localeCompare(a.date)) <ide> }) <ide> export const NotificationsList = () => { <ide> <ide> This works, but actually has a slightly surprising bit of behavior. Any time there are new notifications (either because we've just switched to this tab, or we've fetched some new notifications from the API), you'll actually see _two_ `"notifications/allNotificationsRead"` actions dispatched. Why is that? <ide> <del>Let's say we have fetched some notifications while looking at the `<PostsList>`, and then click the "Notifications" tab. The `<NotificationsList>` component will mount, and the `useEffect` callback will run after that first render and dispatch `allNotificationsRead`. Our `notificationsSlice` will handle that by updating the notification entries in the store. This creates a new `state.notifications` array containing the immutably-updated entries, which forces our component to render again because it sees a new array returned from the `useSelector`, and the `useEffect` hook runs again and dispatches `allNotificationsRead` a second time. The reducer runs again, but this time no data changes, so the component doesn't re-render. <add>Let's say we have fetched some notifications while looking at the `<PostsList>`, and then click the "Notifications" tab. The `<NotificationsList>` component will mount, and the `useLayoutEffect` callback will run after that first render and dispatch `allNotificationsRead`. Our `notificationsSlice` will handle that by updating the notification entries in the store. This creates a new `state.notifications` array containing the immutably-updated entries, which forces our component to render again because it sees a new array returned from the `useSelector`, and the `useLayoutEffect` hook runs again and dispatches `allNotificationsRead` a second time. The reducer runs again, but this time no data changes, so the component doesn't re-render. <ide> <ide> There's a couple ways we could potentially avoid that second dispatch, like splitting the logic to dispatch once when the component mounts, and only dispatch again if the size of the notifications array changes. But, this isn't actually hurting anything, so we can leave it alone. <ide>
1
Javascript
Javascript
remove unused variables and helper function
4fffc17412c126590d1bc4cce8a0620af5d3a419
<ide><path>packages/ember-metal/lib/events.js <ide> var o_create = Ember.create, <ide> metaFor = Ember.meta, <ide> META_KEY = Ember.META_KEY, <ide> /* listener flags */ <del> ONCE = 1, SUSPENDED = 2, IMMEDIATE = 4; <add> ONCE = 1, SUSPENDED = 2; <ide> <ide> /* <ide> The event system uses a series of nested hashes to store listeners on an <ide><path>packages/ember-metal/lib/mixin.js <ide> function mergeMixins(mixins, m, descs, values, base, keys) { <ide> } <ide> } <ide> <del>function writableReq(obj) { <del> var m = Ember.meta(obj), req = m.required; <del> if (!req || !m.hasOwnProperty('required')) { <del> req = m.required = req ? o_create(req) : {}; <del> } <del> return req; <del>} <del> <ide> var IS_BINDING = Ember.IS_BINDING = /^.+Binding$/; <ide> <ide> function detectBinding(obj, key, value, m) { <ide><path>packages/ember-metal/lib/observer.js <ide> require('ember-metal/array'); <ide> var AFTER_OBSERVERS = ':change'; <ide> var BEFORE_OBSERVERS = ':before'; <ide> <del>var guidFor = Ember.guidFor; <del> <ide> function changeEvent(keyName) { <ide> return keyName+AFTER_OBSERVERS; <ide> } <ide><path>packages/ember-metal/lib/properties.js <ide> var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; <ide> @private <ide> @constructor <ide> */ <del>var Descriptor = Ember.Descriptor = function() {}; <add>Ember.Descriptor = function() {}; <ide> <ide> // .......................................................... <ide> // DEFINING PROPERTIES API <ide><path>packages/ember-metal/lib/property_events.js <ide> var endPropertyChanges = Ember.endPropertyChanges = function() { <ide> @param {Function} callback <ide> @param [binding] <ide> */ <del>var changeProperties = Ember.changeProperties = function(cb, binding){ <add>Ember.changeProperties = function(cb, binding){ <ide> beginPropertyChanges(); <ide> tryFinally(cb, endPropertyChanges, binding); <ide> }; <ide><path>packages/ember-metal/lib/utils.js <ide> Ember.guidFor = function guidFor(obj) { <ide> if (obj === undefined) return "(undefined)"; <ide> if (obj === null) return "(null)"; <ide> <del> var cache, ret; <add> var ret; <ide> var type = typeof obj; <ide> <ide> // Don't allow prototype changes to String etc. to change the guidFor <ide> if (needsFinallyFix) { <ide> */ <ide> if (needsFinallyFix) { <ide> Ember.tryCatchFinally = function(tryable, catchable, finalizer, binding) { <del> var result, finalResult, finalError, finalReturn; <add> var result, finalResult, finalError; <ide> <ide> binding = binding || this; <ide> <ide><path>packages/ember-metal/lib/watch_path.js <ide> Ember.watchPath = function(obj, keyPath) { <ide> }; <ide> <ide> Ember.unwatchPath = function(obj, keyPath) { <del> var m = metaFor(obj), watching = m.watching, desc; <add> var m = metaFor(obj), watching = m.watching; <ide> <ide> if (watching[keyPath] === 1) { <ide> watching[keyPath] = 0;
7
Ruby
Ruby
add update migration for double dashes
4065c1742dbcfb1105827f89a0026fe8b4578da5
<ide><path>Library/Homebrew/cmd/update-report.rb <ide> def update_report <ide> end <ide> <ide> migrate_legacy_cache_if_necessary <add> migrate_cache_entries_to_double_dashes <ide> migrate_legacy_keg_symlinks_if_necessary <ide> <ide> if !updated <ide> def migrate_legacy_cache_if_necessary <ide> end <ide> end <ide> <add> def migrate_cache_entries_to_double_dashes <add> HOMEBREW_CACHE.children.each do |child| <add> next unless child.file? <add> <add> next unless /^(?<prefix>[^\.]+[^\-])\-(?<suffix>[^\-].*)/ =~ child.basename.to_s <add> target = HOMEBREW_CACHE/"#{prefix}--#{suffix}" <add> <add> if target.exist? <add> FileUtils.rm_rf child <add> else <add> FileUtils.mv child, target, force: true <add> end <add> end <add> end <add> <ide> def migrate_legacy_repository_if_necessary <ide> return unless HOMEBREW_PREFIX.to_s == "/usr/local" <ide> return unless HOMEBREW_REPOSITORY.to_s == "/usr/local"
1
Ruby
Ruby
add missing require
05b7b80bcaeeb0357cdb6143fbeca1b3c73b5fb9
<ide><path>activestorage/lib/active_storage/downloading.rb <ide> # frozen_string_literal: true <ide> <add>require "tmpdir" <add> <ide> module ActiveStorage <ide> module Downloading <ide> private <ide> # Opens a new tempfile in #tempdir and copies blob data into it. Yields the tempfile. <del> def download_blob_to_tempfile # :doc: <add> def download_blob_to_tempfile #:doc: <ide> Tempfile.open([ "ActiveStorage", blob.filename.extension_with_delimiter ], tempdir) do |file| <ide> download_blob_to file <ide> yield file <ide> end <ide> end <ide> <ide> # Efficiently downloads blob data into the given file. <del> def download_blob_to(file) # :doc: <add> def download_blob_to(file) #:doc: <ide> file.binmode <ide> blob.download { |chunk| file.write(chunk) } <ide> file.rewind <ide> end <ide> <ide> # Returns the directory in which tempfiles should be opened. Defaults to +Dir.tmpdir+. <del> def tempdir # :doc: <add> def tempdir #:doc: <ide> Dir.tmpdir <ide> end <ide> end
1
Python
Python
adjust textcat model
c99a65307037440406a3b35d04440bb671e931d8
<ide><path>spacy/ml/models/textcat.py <ide> def build_text_classifier_lowdata(width, pretrained_vectors, dropout, nO=None): <ide> model = ( <ide> StaticVectors(width) <ide> >> list2ragged() <del> >> with_ragged(0, Linear(width, vector_dim)) <ide> >> ParametricAttention(width) <ide> >> reduce_sum() <ide> >> residual(Relu(width, width)) ** 2
1
PHP
PHP
fix different format of $results in afterfind
c246695518ec87fc3b45e5c645cc9c79f7869d39
<ide><path>lib/Cake/Model/Datasource/DboSource.php <ide> public function queryAssociation(Model $Model, Model $LinkModel, $type, $associa <ide> $this->_mergeAssociation($row, $merge, $association, $type); <ide> } <ide> } else { <add> if (!$prefetched && $LinkModel->useConsistentAfterFind) { <add> if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') { <add> $this->_filterResultsInclusive($assocResultSet, $Model, array($association)); <add> } <add> } <ide> $this->_mergeAssociation($row, $assocResultSet, $association, $type, $selfJoin); <ide> } <ide> <del> if ($type !== 'hasAndBelongsToMany' && isset($row[$association]) && !$prefetched) { <add> if ($type !== 'hasAndBelongsToMany' && isset($row[$association]) && !$prefetched && !$LinkModel->useConsistentAfterFind) { <ide> $row[$association] = $LinkModel->afterFind($row[$association], false); <ide> } <ide> <ide><path>lib/Cake/Model/Model.php <ide> class Model extends Object implements CakeEventListener { <ide> <ide> // @codingStandardsIgnoreEnd <ide> <add>/** <add> * If true, afterFind will be passed consistent formatted $results in case of $primary is false. <add> * The format will be such as the following. <add> * <add> * {{{ <add> * $results = array( <add> * 0 => array( <add> * 'ModelName' => array( <add> * 'field1' => 'value1', <add> * 'field2' => 'value2' <add> * ) <add> * ) <add> * ); <add> * }}} <add> * <add> * @var bool <add> */ <add> public $useConsistentAfterFind = true; <add> <ide> /** <ide> * The ID of the model record that was last inserted. <ide> * <ide><path>lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php <ide> public function testCountAfterFindCalls() { <ide> $this->assertCount(4, $result['Article'][0]['Comment']); <ide> $this->assertCount(0, $result['Article'][1]['Comment']); <ide> } <add> <add>/** <add> * Test format of $results in afterFind <add> * <add> * @return void <add> */ <add> public function testUseConsistentAfterFind() { <add> $this->loadFixtures('Author', 'Post'); <add> <add> $expected = array( <add> 'Author' => array( <add> 'id' => '1', <add> 'user' => 'mariano', <add> 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', <add> 'created' => '2007-03-17 01:16:23', <add> 'updated' => '2007-03-17 01:18:31', <add> 'test' => 'working', <add> ), <add> 'Post' => array( <add> array( <add> 'id' => '1', <add> 'author_id' => '1', <add> 'title' => 'First Post', <add> 'body' => 'First Post Body', <add> 'published' => 'Y', <add> 'created' => '2007-03-18 10:39:23', <add> 'updated' => '2007-03-18 10:41:31', <add> ), <add> array( <add> 'id' => '3', <add> 'author_id' => '1', <add> 'title' => 'Third Post', <add> 'body' => 'Third Post Body', <add> 'published' => 'Y', <add> 'created' => '2007-03-18 10:43:23', <add> 'updated' => '2007-03-18 10:45:31', <add> ), <add> ), <add> ); <add> <add> $Author = new Author(); <add> $Post = $this->getMock('Post', array('afterFind'), array(), '', true); <add> $Post->expects($this->at(0))->method('afterFind')->with(array(array('Post' => $expected['Post'][0])), $this->isFalse())->will($this->returnArgument(0)); <add> $Post->expects($this->at(1))->method('afterFind')->with(array(array('Post' => $expected['Post'][1])), $this->isFalse())->will($this->returnArgument(0)); <add> <add> $Author->bindModel(array('hasMany' => array('Post' => array('limit' => 2, 'order' => 'Post.id')))); <add> $Author->Post = $Post; <add> <add> $result = $Author->find('first', array('conditions' => array('Author.id' => 1), 'recursive' => 1)); <add> $this->assertEquals($expected, $result); <add> <add> // Backward compatiblity <add> $Author = new Author(); <add> $Post = $this->getMock('Post', array('afterFind'), array(), '', true); <add> $Post->expects($this->once())->method('afterFind')->with($expected['Post'], $this->isFalse())->will($this->returnArgument(0)); <add> $Post->useConsistentAfterFind = false; <add> <add> $Author->bindModel(array('hasMany' => array('Post' => array('limit' => 2, 'order' => 'Post.id')))); <add> $Author->Post = $Post; <add> <add> $result = $Author->find('first', array('conditions' => array('Author.id' => 1), 'recursive' => 1)); <add> $this->assertEquals($expected, $result); <add> } <ide> } <ide><path>lib/Cake/Test/Case/Model/models.php <ide> class ModifiedAttachment extends CakeTestModel { <ide> * @return void <ide> */ <ide> public function afterFind($results, $primary = false) { <del> if (isset($results['id'])) { <del> $results['callback'] = 'Fired'; <add> if ($this->useConsistentAfterFind) { <add> if (isset($results[0][$this->alias]['id'])) { <add> $results[0][$this->alias]['callback'] = 'Fired'; <add> } <add> } else { <add> if (isset($results['id'])) { <add> $results['callback'] = 'Fired'; <add> } <ide> } <ide> return $results; <ide> }
4
Text
Text
fix typo in challenge
5e5015e47d52f08de4c24019a704f6670bd3a5ef
<ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-184-triangles-containing-the-origin.md <ide> How many triangles are there containing the origin in the interior and having al <ide> <ide> # --hints-- <ide> <del>`trianglesConttainingOrigin()` should return `1725323624056`. <add>`trianglesContainingOrigin()` should return `1725323624056`. <ide> <ide> ```js <del>assert.strictEqual(trianglesConttainingOrigin(), 1725323624056); <add>assert.strictEqual(trianglesContainingOrigin(), 1725323624056); <ide> ``` <ide> <ide> # --seed--
1
Python
Python
remove mock to debug kokoro failures
63f5827dbfb791fe39be36d3d0357e37ceb45765
<ide><path>official/recommendation/data_test.py <ide> import hashlib <ide> import os <ide> <del>import mock <ide> import numpy as np <ide> import scipy.stats <ide> import tensorflow as tf <ide> def mock_download(*args, **kwargs): <ide> return <ide> <del># The forkpool used by data producers interacts badly with the threading <del># used by TestCase. Without this patch tests will hang, and no amount <del># of diligent closing and joining within the producer will prevent it. <del>@mock.patch.object(popen_helper, "get_forkpool", popen_helper.get_fauxpool) <add> <ide> class BaseTest(tf.test.TestCase): <ide> def setUp(self): <add> # The forkpool used by data producers interacts badly with the threading <add> # used by TestCase. Without this patch tests will hang, and no amount <add> # of diligent closing and joining within the producer will prevent it. <add> self._get_forkpool = popen_helper.get_forkpool <add> popen_helper.get_forkpool = popen_helper.get_fauxpool <add> <ide> self.temp_data_dir = self.get_temp_dir() <ide> ratings_folder = os.path.join(self.temp_data_dir, DATASET) <ide> tf.gfile.MakeDirs(ratings_folder) <ide> def setUp(self): <ide> data_preprocessing.DATASET_TO_NUM_USERS_AND_ITEMS[DATASET] = (NUM_USERS, <ide> NUM_ITEMS) <ide> <add> def tearDown(self): <add> popen_helper.get_forkpool = self._get_forkpool <add> <ide> def make_params(self, train_epochs=1): <ide> return { <ide> "train_epochs": train_epochs,
1
Ruby
Ruby
add hardware.is_64_bit? method
e339a2a73ffa0e8e5a8d63ca49089a24ec2835e9
<ide><path>Library/Homebrew/hardware.rb <ide> def self.processor_count <ide> @@processor_count ||= `/usr/sbin/sysctl -n hw.ncpu`.to_i <ide> end <ide> <add> def self.is_64_bit? <add> self.sysctl_bool("hw.cpu64bit_capable") <add> end <add> <ide> protected <ide> def self.sysctl_bool(property) <ide> result = nil
1
Ruby
Ruby
use new xcode module
4eeb0e64413065c2454c206a2733a8010204b45a
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_git_newline_settings <ide> end <ide> <ide> def check_for_autoconf <del> return if MacOS::Xcode.version >= "4.3" <add> return unless MacOS::Xcode.provides_autotools? <ide> <ide> autoconf = which('autoconf') <ide> safe_autoconfs = %w[/usr/bin/autoconf /Developer/usr/bin/autoconf] <ide><path>Library/Homebrew/dependencies.rb <ide> def parse_symbol_spec spec, tag <ide> case spec <ide> when :autoconf, :automake, :bsdmake, :libtool <ide> # Xcode no longer provides autotools or some other build tools <del> MacOS.xcode_version >= "4.3" ? Dependency.new(spec.to_s) : nil <add> Dependency.new(spec.to_s) unless MacOS::Xcode.provides_autotools? <ide> when :x11, :libpng <ide> X11Dependency.new(tag) <ide> else <ide><path>Library/Homebrew/extend/ENV.rb <ide> def setup_build_environment <ide> remove_cc_etc <ide> <ide> # make any aclocal stuff installed in Homebrew available <del> self['ACLOCAL_PATH'] = "#{HOMEBREW_PREFIX}/share/aclocal" if MacOS::Xcode.version < "4.3" <add> self['ACLOCAL_PATH'] = "#{HOMEBREW_PREFIX}/share/aclocal" if MacOS::Xcode.provides_autotools? <ide> <ide> self['MAKEFLAGS'] = "-j#{self.make_jobs}" <ide>
3
Text
Text
fix lint errors for docs/recipes/
fa27b7faaebe7ad01c7e475fcb8179b0e34b8c00
<ide><path>docs/recipes/ComputingDerivedData.md <ide> Let's revisit the [Todos List example](../basics/UsageWithReact.md): <ide> #### `containers/App.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <del>import { connect } from 'react-redux'; <del>import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from '../actions'; <del>import AddTodo from '../components/AddTodo'; <del>import TodoList from '../components/TodoList'; <del>import Footer from '../components/Footer'; <add>import React, { Component, PropTypes } from 'react' <add>import { connect } from 'react-redux' <add>import { addTodo, completeTodo, setVisibilityFilter, VisibilityFilters } from '../actions' <add>import AddTodo from '../components/AddTodo' <add>import TodoList from '../components/TodoList' <add>import Footer from '../components/Footer' <ide> <ide> class App extends Component { <ide> render() { <ide> // Injected by connect() call: <del> const { dispatch, visibleTodos, visibilityFilter } = this.props; <add> const { dispatch, visibleTodos, visibilityFilter } = this.props <ide> return ( <ide> <div> <ide> <AddTodo <ide> class App extends Component { <ide> dispatch(setVisibilityFilter(nextFilter)) <ide> } /> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> <ide> App.propTypes = { <ide> 'SHOW_COMPLETED', <ide> 'SHOW_ACTIVE' <ide> ]).isRequired <del>}; <add>} <ide> <ide> function selectTodos(todos, filter) { <ide> switch (filter) { <del> case VisibilityFilters.SHOW_ALL: <del> return todos; <del> case VisibilityFilters.SHOW_COMPLETED: <del> return todos.filter(todo => todo.completed); <del> case VisibilityFilters.SHOW_ACTIVE: <del> return todos.filter(todo => !todo.completed); <add> case VisibilityFilters.SHOW_ALL: <add> return todos <add> case VisibilityFilters.SHOW_COMPLETED: <add> return todos.filter(todo => todo.completed) <add> case VisibilityFilters.SHOW_ACTIVE: <add> return todos.filter(todo => !todo.completed) <ide> } <ide> } <ide> <ide> function select(state) { <ide> return { <ide> visibleTodos: selectTodos(state.todos, state.visibilityFilter), <ide> visibilityFilter: state.visibilityFilter <del> }; <add> } <ide> } <ide> <ide> // Wrap the component to inject dispatch and state into it <del>export default connect(select)(App); <add>export default connect(select)(App) <ide> ``` <ide> <ide> In the above example, `select` calls `selectTodos` to calculate `visibleTodos`. This works great, but there is a drawback: `visibleTodos` is calculated every time the component is updated. If the state tree is large, or the calculation expensive, repeating the calculation on every update may cause performance problems. Reselect can help to avoid these unnecessary recalculations. <ide> Let's define a memoized selector named `visibleTodosSelector` to replace `select <ide> #### `selectors/TodoSelectors.js` <ide> <ide> ```js <del>import { createSelector } from 'reselect'; <del>import { VisibilityFilters } from './actions'; <add>import { createSelector } from 'reselect' <add>import { VisibilityFilters } from './actions' <ide> <ide> function selectTodos(todos, filter) { <ide> switch (filter) { <del> case VisibilityFilters.SHOW_ALL: <del> return todos; <del> case VisibilityFilters.SHOW_COMPLETED: <del> return todos.filter(todo => todo.completed); <del> case VisibilityFilters.SHOW_ACTIVE: <del> return todos.filter(todo => !todo.completed); <add> case VisibilityFilters.SHOW_ALL: <add> return todos <add> case VisibilityFilters.SHOW_COMPLETED: <add> return todos.filter(todo => todo.completed) <add> case VisibilityFilters.SHOW_ACTIVE: <add> return todos.filter(todo => !todo.completed) <ide> } <ide> } <ide> <del>const visibilityFilterSelector = (state) => state.visibilityFilter; <del>const todosSelector = (state) => state.todos; <add>const visibilityFilterSelector = (state) => state.visibilityFilter <add>const todosSelector = (state) => state.todos <ide> <ide> export const visibleTodosSelector = createSelector( <del> [visibilityFilterSelector, todosSelector], <add> [ visibilityFilterSelector, todosSelector ], <ide> (visibilityFilter, todos) => { <ide> return { <ide> visibleTodos: selectTodos(todos, visibilityFilter), <ide> visibilityFilter <del> }; <add> } <ide> } <del>); <add>) <ide> ``` <ide> <ide> In the example above, `visibilityFilterSelector` and `todosSelector` are input-selectors. They are created as ordinary non-memoized selector functions because they do not transform the data they select. `visibleTodosSelector` on the other hand is a memoized selector. It takes `visibilityFilterSelector` and `todosSelector` as input-selectors, and a transform function that calculates the filtered todos list. <ide> In the example above, `visibilityFilterSelector` and `todosSelector` are input-s <ide> A memoized selector can itself be an input-selector to another memoized selector. Here is `visibleTodosSelector` being used as an input-selector to a selector that further filters the todos by keyword: <ide> <ide> ```js <del>const keywordSelector = (state) => state.keyword; <add>const keywordSelector = (state) => state.keyword <ide> <ide> const keywordFilterSelector = createSelector( <del> [visibleTodosSelector, keywordSelector], <add> [ visibleTodosSelector, keywordSelector ], <ide> (visibleTodos, keyword) => visibleTodos.filter( <ide> todo => todo.indexOf(keyword) > -1 <ide> ) <del>); <add>) <ide> ``` <ide> <ide> ### Connecting a Selector to the Redux Store <ide> If you are using react-redux, you connect a memoized selector to the Redux store <ide> #### `containers/App.js` <ide> <ide> ```js <del>import React, { Component, PropTypes } from 'react'; <del>import { connect } from 'react-redux'; <del>import { addTodo, completeTodo, setVisibilityFilter } from '../actions'; <del>import AddTodo from '../components/AddTodo'; <del>import TodoList from '../components/TodoList'; <del>import Footer from '../components/Footer'; <del>import { visibleTodosSelector } from '../selectors/todoSelectors.js'; <add>import React, { Component, PropTypes } from 'react' <add>import { connect } from 'react-redux' <add>import { addTodo, completeTodo, setVisibilityFilter } from '../actions' <add>import AddTodo from '../components/AddTodo' <add>import TodoList from '../components/TodoList' <add>import Footer from '../components/Footer' <add>import { visibleTodosSelector } from '../selectors/todoSelectors.js' <ide> <ide> class App extends Component { <ide> render() { <ide> // Injected by connect() call: <del> const { dispatch, visibleTodos, visibilityFilter } = this.props; <add> const { dispatch, visibleTodos, visibilityFilter } = this.props <ide> return ( <ide> <div> <ide> <AddTodo <ide> class App extends Component { <ide> dispatch(setVisibilityFilter(nextFilter)) <ide> } /> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> <ide> App.propTypes = { <ide> 'SHOW_COMPLETED', <ide> 'SHOW_ACTIVE' <ide> ]).isRequired <del>}; <add>} <ide> <ide> // Pass the selector to the connect component <del>export default connect(visibleTodosSelector)(App); <add>export default connect(visibleTodosSelector)(App) <ide> ``` <ide> <ide><path>docs/recipes/ImplementingUndoHistory.md <ide> It is reasonable to suggest that our state shape should change to answer these q <ide> ```js <ide> { <ide> counter: { <del> past: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], <add> past: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], <ide> present: 10, <ide> future: [] <ide> } <ide> Now, if user presses “Undo”, we want it to change to move into the past: <ide> ```js <ide> { <ide> counter: { <del> past: [0, 1, 2, 3, 4, 5, 6, 7, 8], <add> past: [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ], <ide> present: 9, <del> future: [10] <add> future: [ 10 ] <ide> } <ide> } <ide> ``` <ide> And further yet: <ide> ```js <ide> { <ide> counter: { <del> past: [0, 1, 2, 3, 4, 5, 6, 7], <add> past: [ 0, 1, 2, 3, 4, 5, 6, 7 ], <ide> present: 8, <del> future: [9, 10] <add> future: [ 9, 10 ] <ide> } <ide> } <ide> ``` <ide> When the user presses “Redo”, we want to move one step back into the future: <ide> ```js <ide> { <ide> counter: { <del> past: [0, 1, 2, 3, 4, 5, 6, 7, 8], <add> past: [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ], <ide> present: 9, <del> future: [10] <add> future: [ 10 ] <ide> } <ide> } <ide> ``` <ide> Finally, if the user performs an action (e.g. decrement the counter) while we’ <ide> ```js <ide> { <ide> counter: { <del> past: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], <add> past: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], <ide> present: 8, <ide> future: [] <ide> } <ide> The interesting part here is that it does not matter whether we want to keep an <ide> ```js <ide> { <ide> counter: { <del> past: [0, 1, 2], <add> past: [ 0, 1, 2 ], <ide> present: 3, <del> future: [4] <add> future: [ 4 ] <ide> } <ide> } <ide> ``` <ide> The interesting part here is that it does not matter whether we want to keep an <ide> todos: { <ide> past: [ <ide> [], <del> [{ text: 'Use Redux' }], <del> [{ text: 'Use Redux', complete: true }] <add> [ { text: 'Use Redux' } ], <add> [ { text: 'Use Redux', complete: true } ] <ide> ], <del> present: [{ text: 'Use Redux', complete: true }, { text: 'Implement Undo' }], <add> present: [ { text: 'Use Redux', complete: true }, { text: 'Implement Undo' } ], <ide> future: [ <del> [{ text: 'Use Redux', complete: true }, { text: 'Implement Undo', complete: true }] <add> [ { text: 'Use Redux', complete: true }, { text: 'Implement Undo', complete: true } ] <ide> ] <ide> } <ide> } <ide> Or many granular histories so user can undo and redo actions in them independent <ide> ```js <ide> { <ide> counterA: { <del> past: [1, 0], <add> past: [ 1, 0 ], <ide> present: 2, <ide> future: [] <ide> }, <ide> counterB: { <del> past: [0], <add> past: [ 0 ], <ide> present: 1, <ide> future: [] <ide> } <ide> const initialState = { <ide> past: [], <ide> present: null, // (?) How do we initialize the present? <ide> future: [] <del>}; <add>} <ide> <ide> function undoable(state = initialState, action) { <del> const { past, present, future } = state; <add> const { past, present, future } = state <ide> <ide> switch (action.type) { <del> case 'UNDO': <del> const previous = past[past.length - 1]; <del> const newPast = past.slice(0, past.length - 1); <del> return { <del> past: newPast, <del> present: previous, <del> future: [present, ...future] <del> }; <del> case 'REDO': <del> const next = future[0]; <del> const newFuture = future.slice(1); <del> return { <del> past: [...past, present], <del> present: next, <del> future: newFuture <del> }; <del> default: <del> // (?) How do we handle other actions? <del> return state; <add> case 'UNDO': <add> const previous = past[past.length - 1] <add> const newPast = past.slice(0, past.length - 1) <add> return { <add> past: newPast, <add> present: previous, <add> future: [ present, ...future ] <add> } <add> case 'REDO': <add> const next = future[0] <add> const newFuture = future.slice(1) <add> return { <add> past: [ ...past, present ], <add> present: next, <add> future: newFuture <add> } <add> default: <add> // (?) How do we handle other actions? <add> return state <ide> } <ide> } <ide> ```` <ide> A reducer enhancer that doesn’t do anything looks like this: <ide> function doNothingWith(reducer) { <ide> return function (state, action) { <ide> // Just call the passed reducer <del> return reducer(state, action); <del> }; <add> return reducer(state, action) <add> } <ide> } <ide> ``` <ide> <ide> function combineReducers(reducers) { <ide> return function (state = {}, action) { <ide> return Object.keys(reducers).reduce((nextState, key) => { <ide> // Call every reducer with the part of the state it manages <del> nextState[key] = reducers[key](state[key], action); <del> return nextState; <del> }, {}); <del> }; <add> nextState[key] = reducers[key](state[key], action) <add> return nextState <add> }, {}) <add> } <ide> } <ide> ``` <ide> <ide> function undoable(reducer) { <ide> past: [], <ide> present: reducer(undefined, {}), <ide> future: [] <del> }; <add> } <ide> <ide> // Return a reducer that handles undo and redo <ide> return function (state = initialState, action) { <del> const { past, present, future } = state; <add> const { past, present, future } = state <ide> <ide> switch (action.type) { <del> case 'UNDO': <del> const previous = past[past.length - 1]; <del> const newPast = past.slice(0, past.length - 1); <del> return { <del> past: newPast, <del> present: previous, <del> future: [present, ...future] <del> }; <del> case 'REDO': <del> const next = future[0]; <del> const newFuture = future.slice(1); <del> return { <del> past: [...past, present], <del> present: next, <del> future: newFuture <del> }; <del> default: <del> // Delegate handling the action to the passed reducer <del> const newPresent = reducer(present, action); <del> if (present === newPresent) { <del> return state; <del> } <del> return { <del> past: [...past, present], <del> present: newPresent, <del> future: [] <del> }; <add> case 'UNDO': <add> const previous = past[past.length - 1] <add> const newPast = past.slice(0, past.length - 1) <add> return { <add> past: newPast, <add> present: previous, <add> future: [ present, ...future ] <add> } <add> case 'REDO': <add> const next = future[0] <add> const newFuture = future.slice(1) <add> return { <add> past: [ ...past, present ], <add> present: next, <add> future: newFuture <add> } <add> default: <add> // Delegate handling the action to the passed reducer <add> const newPresent = reducer(present, action) <add> if (present === newPresent) { <add> return state <add> } <add> return { <add> past: [ ...past, present ], <add> present: newPresent, <add> future: [] <add> } <ide> } <del> }; <add> } <ide> } <ide> ``` <ide> <ide> function todos(state = [], action) { <ide> } <ide> <ide> // This is also a reducer! <del>const undoableTodos = undoable(todos); <add>const undoableTodos = undoable(todos) <ide> <del>import { createStore } from 'redux'; <del>const store = createStore(undoableTodos); <add>import { createStore } from 'redux' <add>const store = createStore(undoableTodos) <ide> <ide> store.dispatch({ <ide> type: 'ADD_TODO', <ide> text: 'Use Redux' <del>}); <add>}) <ide> <ide> store.dispatch({ <ide> type: 'ADD_TODO', <ide> text: 'Implement Undo' <del>}); <add>}) <ide> <ide> store.dispatch({ <ide> type: 'UNDO' <del>}); <add>}) <ide> ``` <ide> <ide> There is an important gotcha: you need to remember to append `.present` to the current state when you retrieve it. You may also check `.past.length` and `.future.length` to determine whether to enable or to disable the Undo and Redo buttons, respectively. <ide> You will need to wrap the reducer you wish to enhance with `undoable` function. <ide> #### `reducers.js` <ide> <ide> ```js <del>import undoable, { distinctState } from 'redux-undo'; <add>import undoable, { distinctState } from 'redux-undo' <ide> <ide> /* ... */ <ide> <ide> const todoApp = combineReducers({ <ide> visibilityFilter, <ide> todos: undoable(todos, { filter: distinctState() }) <del>}); <add>}) <ide> ``` <ide> <ide> The `distinctState()` filter serves to ignore the actions that didn’t result in a state change. There are [many other options](https://github.com/omnidan/redux-undo#configuration) to configure your undoable reducer, like setting the action type for Undo and Redo actions. <ide> Now the `todos` part of the state looks like this: <ide> todos: { <ide> past: [ <ide> [], <del> [{ text: 'Use Redux' }], <del> [{ text: 'Use Redux', complete: true }] <add> [ { text: 'Use Redux' } ], <add> [ { text: 'Use Redux', complete: true } ] <ide> ], <del> present: [{ text: 'Use Redux', complete: true }, { text: 'Implement Undo' }], <add> present: [ { text: 'Use Redux', complete: true }, { text: 'Implement Undo' } ], <ide> future: [ <del> [{ text: 'Use Redux', complete: true }, { text: 'Implement Undo', complete: true }] <add> [ { text: 'Use Redux', complete: true }, { text: 'Implement Undo', complete: true } ] <ide> ] <ide> } <ide> } <ide> just `state.todos`: <ide> <ide> ```js <ide> function select(state) { <del> const presentTodos = state.todos.present; <add> const presentTodos = state.todos.present <ide> return { <ide> visibleTodos: selectTodos(presentTodos, state.visibilityFilter), <ide> visibilityFilter: state.visibilityFilter <del> }; <add> } <ide> } <ide> ``` <ide> <ide> First of all, you need to import `ActionCreators` from `redux-undo` and pass the <ide> #### `containers/App.js` <ide> <ide> ```js <del>import { ActionCreators } from 'redux-undo'; <add>import { ActionCreators } from 'redux-undo' <ide> <ide> /* ... */ <ide> <ide> class App extends Component { <ide> render() { <del> const { dispatch, visibleTodos, visibilityFilter } = this.props; <add> const { dispatch, visibleTodos, visibilityFilter } = this.props <ide> return ( <ide> <div> <ide> {/* ... */} <ide> class App extends Component { <ide> undoDisabled={this.props.undoDisabled} <ide> redoDisabled={this.props.redoDisabled} /> <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> ``` <ide> export default class Footer extends Component { <ide> <button onClick={this.props.onUndo} disabled={this.props.undoDisabled}>Undo</button> <ide> <button onClick={this.props.onRedo} disabled={this.props.redoDisabled}>Redo</button> <ide> </p> <del> ); <add> ) <ide> } <ide> <ide> render() { <ide> export default class Footer extends Component { <ide> {this.renderFilters()} <ide> {this.renderUndo()} <ide> </div> <del> ); <add> ) <ide> } <ide> } <ide> ``` <ide><path>docs/recipes/ReducingBoilerplate.md <ide> It is a common convention that actions have a constant type that helps reducers <ide> In Flux, it is traditionally thought that you would define every action type as a string constant: <ide> <ide> ```js <del>const ADD_TODO = 'ADD_TODO'; <del>const REMOVE_TODO = 'REMOVE_TODO'; <del>const LOAD_ARTICLE = 'LOAD_ARTICLE'; <add>const ADD_TODO = 'ADD_TODO' <add>const REMOVE_TODO = 'REMOVE_TODO' <add>const LOAD_ARTICLE = 'LOAD_ARTICLE' <ide> ``` <ide> <ide> Why is this beneficial? **It is often claimed that constants are unnecessary, and for small projects, this might be correct.** For larger projects, there are some benefits to defining action types as constants: <ide> For example, instead of calling `dispatch` with an object literal: <ide> dispatch({ <ide> type: 'ADD_TODO', <ide> text: 'Use Redux' <del>}); <add>}) <ide> ``` <ide> <ide> You might write an action creator in a separate file, and import it from your component: <ide> export function addTodo(text) { <ide> return { <ide> type: 'ADD_TODO', <ide> text <del> }; <add> } <ide> } <ide> ``` <ide> <ide> #### `AddTodo.js` <ide> <ide> ```js <del>import { addTodo } from './actionCreators'; <add>import { addTodo } from './actionCreators' <ide> <ide> // somewhere in an event handler <ide> dispatch(addTodo('Use Redux')) <ide> function addTodoWithoutCheck(text) { <ide> return { <ide> type: 'ADD_TODO', <ide> text <del> }; <add> } <ide> } <ide> <ide> export function addTodo(text) { <ide> export function addTodo(text) { <ide> return function (dispatch, getState) { <ide> if (getState().todos.length === 3) { <ide> // Exit early <del> return; <add> return <ide> } <ide> <del> dispatch(addTodoWithoutCheck(text)); <add> dispatch(addTodoWithoutCheck(text)) <ide> } <ide> } <ide> ``` <ide> export function addTodo(text) { <ide> return { <ide> type: 'ADD_TODO', <ide> text <del> }; <add> } <ide> } <ide> <ide> export function editTodo(id, text) { <ide> return { <ide> type: 'EDIT_TODO', <ide> id, <ide> text <del> }; <add> } <ide> } <ide> <ide> export function removeTodo(id) { <ide> return { <ide> type: 'REMOVE_TODO', <ide> id <del> }; <add> } <ide> } <ide> ``` <ide> <ide> You can always write a function that generates an action creator: <ide> ```js <ide> function makeActionCreator(type, ...argNames) { <ide> return function(...args) { <del> let action = { type }; <add> let action = { type } <ide> argNames.forEach((arg, index) => { <del> action[argNames[index]] = args[index]; <del> }); <del> return action; <add> action[argNames[index]] = args[index] <add> }) <add> return action <ide> } <ide> } <ide> <del>const ADD_TODO = 'ADD_TODO'; <del>const EDIT_TODO = 'EDIT_TODO'; <del>const REMOVE_TODO = 'REMOVE_TODO'; <add>const ADD_TODO = 'ADD_TODO' <add>const EDIT_TODO = 'EDIT_TODO' <add>const REMOVE_TODO = 'REMOVE_TODO' <ide> <del>export const addTodo = makeActionCreator(ADD_TODO, 'todo'); <del>export const editTodo = makeActionCreator(EDIT_TODO, 'id', 'todo'); <del>export const removeTodo = makeActionCreator(REMOVE_TODO, 'id'); <add>export const addTodo = makeActionCreator(ADD_TODO, 'todo') <add>export const editTodo = makeActionCreator(EDIT_TODO, 'id', 'todo') <add>export const removeTodo = makeActionCreator(REMOVE_TODO, 'id') <ide> ``` <ide> There are also utility libraries to aid in generating action creators, such as [redux-action-utils](https://github.com/insin/redux-action-utils) and [redux-actions](https://github.com/acdlite/redux-actions). These can help with reducing your boilerplate code and adhering to standards such as [Flux Standard Action (FSA)](https://github.com/acdlite/flux-standard-action). <ide> <ide> export function loadPostsSuccess(userId, response) { <ide> type: 'LOAD_POSTS_SUCCESS', <ide> userId, <ide> response <del> }; <add> } <ide> } <ide> <ide> export function loadPostsFailure(userId, error) { <ide> return { <ide> type: 'LOAD_POSTS_FAILURE', <ide> userId, <ide> error <del> }; <add> } <ide> } <ide> <ide> export function loadPostsRequest(userId) { <ide> return { <ide> type: 'LOAD_POSTS_REQUEST', <ide> userId <del> }; <add> } <ide> } <ide> ``` <ide> <ide> #### `UserInfo.js` <ide> <ide> ```js <del>import { Component } from 'react'; <del>import { connect } from 'react-redux'; <del>import { loadPostsRequest, loadPostsSuccess, loadPostsFailure } from './actionCreators'; <add>import { Component } from 'react' <add>import { connect } from 'react-redux' <add>import { loadPostsRequest, loadPostsSuccess, loadPostsFailure } from './actionCreators' <ide> <ide> class Posts extends Component { <ide> loadData(userId) { <ide> // Injected into props by React Redux `connect()` call: <del> let { dispatch, posts } = this.props; <add> let { dispatch, posts } = this.props <ide> <ide> if (posts[userId]) { <ide> // There is cached data! Don't do anything. <del> return; <add> return <ide> } <ide> <ide> // Reducer can react to this action by setting <ide> // `isFetching` and thus letting us show a spinner. <del> dispatch(loadPostsRequest(userId)); <add> dispatch(loadPostsRequest(userId)) <ide> <ide> // Reducer can react to these actions by filling the `users`. <ide> fetch(`http://myapi.com/users/${userId}/posts`).then( <ide> response => dispatch(loadPostsSuccess(userId, response)), <ide> error => dispatch(loadPostsFailure(userId, error)) <del> ); <add> ) <ide> } <ide> <ide> componentDidMount() { <del> this.loadData(this.props.userId); <add> this.loadData(this.props.userId) <ide> } <ide> <ide> componentWillReceiveProps(nextProps) { <ide> if (nextProps.userId !== this.props.userId) { <del> this.loadData(nextProps.userId); <add> this.loadData(nextProps.userId) <ide> } <ide> } <ide> <ide> render() { <ide> if (this.props.isFetching) { <del> return <p>Loading...</p>; <add> return <p>Loading...</p> <ide> } <ide> <ide> let posts = this.props.posts.map(post => <ide> <Post post={post} key={post.id} /> <del> ); <add> ) <ide> <del> return <div>{posts}</div>; <add> return <div>{posts}</div> <ide> } <ide> } <ide> <ide> export default connect(state => ({ <ide> posts: state.posts <del>}))(Posts); <add>}))(Posts) <ide> ``` <ide> <ide> However, this quickly gets repetitive because different components request data from the same API endpoints. Moreover, we want to reuse some of this logic (e.g., early exit when there is cached data available) from many components. <ide> Consider the code above rewritten with [redux-thunk](https://github.com/gaearon/ <ide> export function loadPosts(userId) { <ide> // Interpreted by the thunk middleware: <ide> return function (dispatch, getState) { <del> let { posts } = getState(); <add> let { posts } = getState() <ide> if (posts[userId]) { <ide> // There is cached data! Don't do anything. <del> return; <add> return <ide> } <ide> <ide> dispatch({ <ide> type: 'LOAD_POSTS_REQUEST', <ide> userId <del> }); <add> }) <ide> <ide> // Dispatch vanilla actions asynchronously <ide> fetch(`http://myapi.com/users/${userId}/posts`).then( <ide> export function loadPosts(userId) { <ide> userId, <ide> error <ide> }) <del> ); <add> ) <ide> } <ide> } <ide> ``` <ide> <ide> #### `UserInfo.js` <ide> <ide> ```js <del>import { Component } from 'react'; <del>import { connect } from 'react-redux'; <del>import { loadPosts } from './actionCreators'; <add>import { Component } from 'react' <add>import { connect } from 'react-redux' <add>import { loadPosts } from './actionCreators' <ide> <ide> class Posts extends Component { <ide> componentDidMount() { <del> this.props.dispatch(loadPosts(this.props.userId)); <add> this.props.dispatch(loadPosts(this.props.userId)) <ide> } <ide> <ide> componentWillReceiveProps(nextProps) { <ide> if (nextProps.userId !== this.props.userId) { <del> this.props.dispatch(loadPosts(nextProps.userId)); <add> this.props.dispatch(loadPosts(nextProps.userId)) <ide> } <ide> } <ide> <ide> render() { <ide> if (this.props.isFetching) { <del> return <p>Loading...</p>; <add> return <p>Loading...</p> <ide> } <ide> <ide> let posts = this.props.posts.map(post => <ide> <Post post={post} key={post.id} /> <del> ); <add> ) <ide> <del> return <div>{posts}</div>; <add> return <div>{posts}</div> <ide> } <ide> } <ide> <ide> export default connect(state => ({ <ide> posts: state.posts <del>}))(Posts); <add>}))(Posts) <ide> ``` <ide> <ide> This is much less typing! If you’d like, you can still have “vanilla” action creators like `loadPostsSuccess` which you’d use from a “smart” `loadPosts` action creator. <ide> export function loadPosts(userId) { <ide> callAPI: () => fetch(`http://myapi.com/users/${userId}/posts`), <ide> // Arguments to inject in begin/end actions <ide> payload: { userId } <del> }; <add> } <ide> } <ide> ``` <ide> <ide> function callAPIMiddleware({ dispatch, getState }) { <ide> callAPI, <ide> shouldCallAPI = () => true, <ide> payload = {} <del> } = action; <add> } = action <ide> <ide> if (!types) { <ide> // Normal action: pass it on <del> return next(action); <add> return next(action) <ide> } <ide> <ide> if ( <ide> !Array.isArray(types) || <ide> types.length !== 3 || <ide> !types.every(type => typeof type === 'string') <ide> ) { <del> throw new Error('Expected an array of three string types.'); <add> throw new Error('Expected an array of three string types.') <ide> } <ide> <ide> if (typeof callAPI !== 'function') { <del> throw new Error('Expected fetch to be a function.'); <add> throw new Error('Expected fetch to be a function.') <ide> } <ide> <ide> if (!shouldCallAPI(getState())) { <del> return; <add> return <ide> } <ide> <del> const [requestType, successType, failureType] = types; <add> const [ requestType, successType, failureType ] = types <ide> <ide> dispatch(Object.assign({}, payload, { <ide> type: requestType <del> })); <add> })) <ide> <ide> return callAPI().then( <ide> response => dispatch(Object.assign({}, payload, { <ide> function callAPIMiddleware({ dispatch, getState }) { <ide> error: error, <ide> type: failureType <ide> })) <del> ); <del> }; <del> }; <add> ) <add> } <add> } <ide> } <ide> ``` <ide> <ide> export function loadPosts(userId) { <ide> shouldCallAPI: (state) => !state.users[userId], <ide> callAPI: () => fetch(`http://myapi.com/users/${userId}/posts`), <ide> payload: { userId } <del> }; <add> } <ide> } <ide> <ide> export function loadComments(postId) { <ide> export function loadComments(postId) { <ide> shouldCallAPI: (state) => !state.posts[postId], <ide> callAPI: () => fetch(`http://myapi.com/posts/${postId}/comments`), <ide> payload: { postId } <del> }; <add> } <ide> } <ide> <ide> export function addComment(postId, message) { <ide> export function addComment(postId, message) { <ide> body: JSON.stringify({ message }) <ide> }), <ide> payload: { postId, message } <del> }; <add> } <ide> } <ide> ``` <ide> <ide> Redux reduces the boilerplate of Flux stores considerably by describing the upda <ide> Consider this Flux store: <ide> <ide> ```js <del>let _todos = []; <add>let _todos = [] <ide> <del>export default const TodoStore = assign({}, EventEmitter.prototype, { <add>const TodoStore = Object.assign({}, EventEmitter.prototype, { <ide> getAll() { <del> return _todos; <add> return _todos <ide> } <del>}); <add>}) <ide> <ide> AppDispatcher.register(function (action) { <ide> switch (action.type) { <del> case ActionTypes.ADD_TODO: <del> let text = action.text.trim(); <del> _todos.push(text); <del> TodoStore.emitChange(); <add> case ActionTypes.ADD_TODO: <add> let text = action.text.trim() <add> _todos.push(text) <add> TodoStore.emitChange() <ide> } <del>}); <add>}) <add> <add>export default TodoStore <ide> ``` <ide> <ide> With Redux, the same update logic can be described as a reducing function: <ide> With Redux, the same update logic can be described as a reducing function: <ide> export function todos(state = [], action) { <ide> switch (action.type) { <ide> case ActionTypes.ADD_TODO: <del> let text = action.text.trim(); <del> return [...state, text]; <add> let text = action.text.trim() <add> return [ ...state, text ] <ide> default: <del> return state; <add> return state <ide> } <ide> } <ide> ``` <ide> Let’s write a function that lets us express reducers as an object mapping from <ide> ```js <ide> export const todos = createReducer([], { <ide> [ActionTypes.ADD_TODO](state, action) { <del> let text = action.text.trim(); <del> return [...state, text]; <add> let text = action.text.trim() <add> return [ ...state, text ] <ide> } <ide> }) <ide> ``` <ide> We can write the following helper to accomplish this: <ide> function createReducer(initialState, handlers) { <ide> return function reducer(state = initialState, action) { <ide> if (handlers.hasOwnProperty(action.type)) { <del> return handlers[action.type](state, action); <add> return handlers[action.type](state, action) <ide> } else { <del> return state; <add> return state <ide> } <ide> } <ide> } <ide><path>docs/recipes/ServerRendering.md <ide> The following is the outline for what our server side is going to look like. We <ide> ##### `server.js` <ide> <ide> ```js <del>import path from 'path'; <del>import Express from 'express'; <del>import React from 'react'; <del>import { createStore } from 'redux'; <del>import { Provider } from 'react-redux'; <del>import counterApp from './reducers'; <del>import App from './containers/App'; <add>import path from 'path' <add>import Express from 'express' <add>import React from 'react' <add>import { createStore } from 'redux' <add>import { Provider } from 'react-redux' <add>import counterApp from './reducers' <add>import App from './containers/App' <ide> <del>const app = Express(); <del>const port = 3000; <add>const app = Express() <add>const port = 3000 <ide> <ide> // This is fired every time the server side receives a request <del>app.use(handleRender); <add>app.use(handleRender) <ide> <ide> // We are going to fill these out in the sections to follow <ide> function handleRender(req, res) { /* ... */ } <ide> function renderFullPage(html, initialState) { /* ... */ } <ide> <del>app.listen(port); <add>app.listen(port) <ide> ``` <ide> <ide> ### Handling the Request <ide> The key step in server side rendering is to render the initial HTML of our compo <ide> We then get the initial state from our Redux store using [`store.getState()`](../api/Store.md#getState). We will see how this is passed along in our `renderFullPage` function. <ide> <ide> ```js <del>import { renderToString } from 'react-dom/server'; <add>import { renderToString } from 'react-dom/server' <ide> <ide> function handleRender(req, res) { <ide> // Create a new Redux store instance <del> const store = createStore(counterApp); <add> const store = createStore(counterApp) <ide> <ide> // Render the component to a string <ide> const html = renderToString( <ide> <Provider store={store}> <ide> <App /> <ide> </Provider> <del> ); <add> ) <ide> <ide> // Grab the initial state from our Redux store <del> const initialState = store.getState(); <add> const initialState = store.getState() <ide> <ide> // Send the rendered page back to the client <del> res.send(renderFullPage(html, initialState)); <add> res.send(renderFullPage(html, initialState)) <ide> } <ide> ``` <ide> <ide> function renderFullPage(html, initialState) { <ide> <body> <ide> <div id="app">${html}</div> <ide> <script> <del> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; <add> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)} <ide> </script> <ide> <script src="/static/bundle.js"></script> <ide> </body> <ide> </html> <del> `; <add> ` <ide> } <ide> ``` <ide> <ide> Let’s take a look at our new client file: <ide> #### `client.js` <ide> <ide> ```js <del>import React from 'react'; <del>import { render } from 'react-dom'; <del>import { createStore } from 'redux'; <del>import { Provider } from 'react-redux'; <del>import App from './containers/App'; <del>import counterApp from './reducers'; <add>import React from 'react' <add>import { render } from 'react-dom' <add>import { createStore } from 'redux' <add>import { Provider } from 'react-redux' <add>import App from './containers/App' <add>import counterApp from './reducers' <ide> <ide> // Grab the state from a global injected into server-generated HTML <del>const initialState = window.__INITIAL_STATE__; <add>const initialState = window.__INITIAL_STATE__ <ide> <ide> // Create Redux store with initial state <del>const store = createStore(counterApp, initialState); <add>const store = createStore(counterApp, initialState) <ide> <ide> render( <ide> <Provider store={store}> <ide> <App /> <ide> </Provider>, <ide> document.getElementById('root') <del>); <add>) <ide> ``` <ide> <ide> You can set up your build tool of choice (Webpack, Browserify, etc.) to compile a bundle file into `dist/bundle.js`. <ide> The request contains information about the URL requested, including any query pa <ide> #### `server.js` <ide> <ide> ```js <del>import qs from 'qs'; // Add this at the top of the file <del>import { renderToString } from 'react-dom/server'; <add>import qs from 'qs' // Add this at the top of the file <add>import { renderToString } from 'react-dom/server' <ide> <ide> function handleRender(req, res) { <ide> // Read the counter from the request, if provided <del> const params = qs.parse(req.query); <del> const counter = parseInt(params.counter) || 0; <add> const params = qs.parse(req.query) <add> const counter = parseInt(params.counter) || 0 <ide> <ide> // Compile an initial state <del> let initialState = { counter }; <add> let initialState = { counter } <ide> <ide> // Create a new Redux store instance <del> const store = createStore(counterApp, initialState); <add> const store = createStore(counterApp, initialState) <ide> <ide> // Render the component to a string <ide> const html = renderToString( <ide> <Provider store={store}> <ide> <App /> <ide> </Provider> <del> ); <add> ) <ide> <ide> // Grab the initial state from our Redux store <del> const finalState = store.getState(); <add> const finalState = store.getState() <ide> <ide> // Send the rendered page back to the client <del> res.send(renderFullPage(html, finalState)); <add> res.send(renderFullPage(html, finalState)) <ide> } <ide> ``` <ide> <ide> For our example, we’ll imagine there is an external datastore that contains th <ide> <ide> ```js <ide> function getRandomInt(min, max) { <del> return Math.floor(Math.random() * (max - min)) + min; <add> return Math.floor(Math.random() * (max - min)) + min <ide> } <ide> <ide> export function fetchCounter(callback) { <ide> setTimeout(() => { <del> callback(getRandomInt(1, 100)); <del> }, 500); <add> callback(getRandomInt(1, 100)) <add> }, 500) <ide> } <ide> ``` <ide> <ide> On the server side, we simply wrap our existing code in the `fetchCounter` and r <ide> <ide> ```js <ide> // Add this to our imports <del>import { fetchCounter } from './api/counter'; <del>import { renderToString } from 'react-dom/server'; <add>import { fetchCounter } from './api/counter' <add>import { renderToString } from 'react-dom/server' <ide> <ide> function handleRender(req, res) { <ide> // Query our mock API asynchronously <ide> fetchCounter(apiResult => { <ide> // Read the counter from the request, if provided <del> const params = qs.parse(req.query); <del> const counter = parseInt(params.counter) || apiResult || 0; <add> const params = qs.parse(req.query) <add> const counter = parseInt(params.counter) || apiResult || 0 <ide> <ide> // Compile an initial state <del> let initialState = { counter }; <add> let initialState = { counter } <ide> <ide> // Create a new Redux store instance <del> const store = createStore(counterApp, initialState); <add> const store = createStore(counterApp, initialState) <ide> <ide> // Render the component to a string <ide> const html = renderToString( <ide> <Provider store={store}> <ide> <App /> <ide> </Provider> <del> ); <add> ) <ide> <ide> // Grab the initial state from our Redux store <del> const finalState = store.getState(); <add> const finalState = store.getState() <ide> <ide> // Send the rendered page back to the client <del> res.send(renderFullPage(html, finalState)); <del> }); <add> res.send(renderFullPage(html, finalState)) <add> }) <ide> } <ide> ``` <ide> <ide><path>docs/recipes/WritingTests.md <ide> export function addTodo(text) { <ide> return { <ide> type: 'ADD_TODO', <ide> text <del> }; <add> } <ide> } <ide> ``` <ide> can be tested like: <ide> <ide> ```js <del>import expect from 'expect'; <del>import * as actions from '../../actions/TodoActions'; <del>import * as types from '../../constants/ActionTypes'; <add>import expect from 'expect' <add>import * as actions from '../../actions/TodoActions' <add>import * as types from '../../constants/ActionTypes' <ide> <ide> describe('actions', () => { <ide> it('should create an action to add a todo', () => { <del> const text = 'Finish docs'; <add> const text = 'Finish docs' <ide> const expectedAction = { <ide> type: types.ADD_TODO, <ide> text <del> }; <del> expect(actions.addTodo(text)).toEqual(expectedAction); <del> }); <del>}); <add> } <add> expect(actions.addTodo(text)).toEqual(expectedAction) <add> }) <add>}) <ide> ``` <ide> <ide> ### Async Action Creators <ide> For async action creators using [Redux Thunk](https://github.com/gaearon/redux-t <ide> function fetchTodosRequest() { <ide> return { <ide> type: FETCH_TODOS_REQUEST <del> }; <add> } <ide> } <ide> <ide> function fetchTodosSuccess(body) { <ide> return { <ide> type: FETCH_TODOS_SUCCESS, <ide> body <del> }; <add> } <ide> } <ide> <ide> function fetchTodosFailure(ex) { <ide> return { <ide> type: FETCH_TODOS_FAILURE, <ide> ex <del> }; <add> } <ide> } <ide> <ide> export function fetchTodos() { <ide> return dispatch => { <del> dispatch(fetchTodosRequest()); <add> dispatch(fetchTodosRequest()) <ide> return fetch('http://example.com/todos') <ide> .then(res => res.json()) <ide> .then(json => dispatch(fetchTodosSuccess(json.body))) <del> .catch(ex => dispatch(fetchTodosFailure(ex))); <del> }; <add> .catch(ex => dispatch(fetchTodosFailure(ex))) <add> } <ide> } <ide> ``` <ide> <ide> can be tested like: <ide> <ide> ```js <del>import expect from 'expect'; <del>import { applyMiddleware } from 'redux'; <del>import thunk from 'redux-thunk'; <del>import * as actions from '../../actions/counter'; <del>import * as types from '../../constants/ActionTypes'; <del>import nock from 'nock'; <add>import expect from 'expect' <add>import { applyMiddleware } from 'redux' <add>import thunk from 'redux-thunk' <add>import * as actions from '../../actions/counter' <add>import * as types from '../../constants/ActionTypes' <add>import nock from 'nock' <ide> <del>const middlewares = [thunk]; <add>const middlewares = [ thunk ] <ide> <ide> /** <ide> * Creates a mock of Redux store with middleware. <ide> */ <ide> function mockStore(getState, expectedActions, done) { <ide> if (!Array.isArray(expectedActions)) { <del> throw new Error('expectedActions should be an array of expected actions.'); <add> throw new Error('expectedActions should be an array of expected actions.') <ide> } <ide> if (typeof done !== 'undefined' && typeof done !== 'function') { <del> throw new Error('done should either be undefined or function.'); <add> throw new Error('done should either be undefined or function.') <ide> } <ide> <ide> function mockStoreWithoutMiddleware() { <ide> return { <ide> getState() { <ide> return typeof getState === 'function' ? <ide> getState() : <del> getState; <add> getState <ide> }, <ide> <ide> dispatch(action) { <del> const expectedAction = expectedActions.shift(); <add> const expectedAction = expectedActions.shift() <ide> <ide> try { <del> expect(action).toEqual(expectedAction); <add> expect(action).toEqual(expectedAction) <ide> if (done && !expectedActions.length) { <del> done(); <add> done() <ide> } <del> return action; <add> return action <ide> } catch (e) { <del> done(e); <add> done(e) <ide> } <ide> } <ide> } <ide> } <ide> <ide> const mockStoreWithMiddleware = applyMiddleware( <ide> ...middlewares <del> )(mockStoreWithoutMiddleware); <add> )(mockStoreWithoutMiddleware) <ide> <del> return mockStoreWithMiddleware(); <add> return mockStoreWithMiddleware() <ide> } <ide> <ide> describe('async actions', () => { <ide> afterEach(() => { <del> nock.cleanAll(); <del> }); <add> nock.cleanAll() <add> }) <ide> <ide> it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', (done) => { <ide> nock('http://example.com/') <ide> .get('/todos') <del> .reply(200, { todos: ['do something'] }); <add> .reply(200, { todos: ['do something'] }) <ide> <ide> const expectedActions = [ <ide> { type: types.FETCH_TODOS_REQUEST }, <ide> { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something'] } } <ide> ] <del> const store = mockStore({ todos: [] }, expectedActions, done); <del> store.dispatch(actions.fetchTodos()); <del> }); <del>}); <add> const store = mockStore({ todos: [] }, expectedActions, done) <add> store.dispatch(actions.fetchTodos()) <add> }) <add>}) <ide> ``` <ide> <ide> ### Reducers <ide> A reducer should return the new state after applying the action to the previous <ide> #### Example <ide> <ide> ```js <del>import { ADD_TODO } from '../constants/ActionTypes'; <add>import { ADD_TODO } from '../constants/ActionTypes' <ide> <del>const initialState = [{ <del> text: 'Use Redux', <del> completed: false, <del> id: 0 <del>}]; <add>const initialState = [ <add> { <add> text: 'Use Redux', <add> completed: false, <add> id: 0 <add> } <add>] <ide> <ide> export default function todos(state = initialState, action) { <ide> switch (action.type) { <del> case ADD_TODO: <del> return [{ <del> id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1, <del> completed: false, <del> text: action.text <del> }, ...state]; <del> <del> default: <del> return state; <add> case ADD_TODO: <add> return [ <add> { <add> id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1, <add> completed: false, <add> text: action.text <add> }, <add> ...state <add> ] <add> <add> default: <add> return state <ide> } <ide> } <ide> ``` <ide> can be tested like: <ide> <ide> ```js <del>import expect from 'expect'; <del>import reducer from '../../reducers/todos'; <del>import * as types from '../../constants/ActionTypes'; <add>import expect from 'expect' <add>import reducer from '../../reducers/todos' <add>import * as types from '../../constants/ActionTypes' <ide> <ide> describe('todos reducer', () => { <ide> it('should return the initial state', () => { <ide> expect( <ide> reducer(undefined, {}) <del> ).toEqual([{ <del> text: 'Use Redux', <del> completed: false, <del> id: 0 <del> }]); <del> }); <add> ).toEqual([ <add> { <add> text: 'Use Redux', <add> completed: false, <add> id: 0 <add> } <add> ]) <add> }) <ide> <ide> it('should handle ADD_TODO', () => { <ide> expect( <ide> reducer([], { <ide> type: types.ADD_TODO, <ide> text: 'Run the tests' <ide> }) <del> ).toEqual([{ <del> text: 'Run the tests', <del> completed: false, <del> id: 0 <del> }]); <add> ).toEqual( <add> [ <add> { <add> text: 'Run the tests', <add> completed: false, <add> id: 0 <add> } <add> ] <add> ) <ide> <ide> expect( <del> reducer([{ <del> text: 'Use Redux', <del> completed: false, <del> id: 0 <del> }], { <del> type: types.ADD_TODO, <del> text: 'Run the tests' <del> }) <del> ).toEqual([{ <del> text: 'Run the tests', <del> completed: false, <del> id: 1 <del> }, { <del> text: 'Use Redux', <del> completed: false, <del> id: 0 <del> }]); <del> }); <del>}); <add> reducer( <add> [ <add> { <add> text: 'Use Redux', <add> completed: false, <add> id: 0 <add> } <add> ], <add> { <add> type: types.ADD_TODO, <add> text: 'Run the tests' <add> } <add> ) <add> ).toEqual( <add> [ <add> { <add> text: 'Run the tests', <add> completed: false, <add> id: 1 <add> }, <add> { <add> text: 'Use Redux', <add> completed: false, <add> id: 0 <add> } <add> ] <add> ) <add> }) <add>}) <ide> ``` <ide> <ide> ### Components <ide> To test the components we make a `setup()` helper that passes the stubbed callba <ide> #### Example <ide> <ide> ```js <del>import React, { PropTypes, Component } from 'react'; <del>import TodoTextInput from './TodoTextInput'; <add>import React, { PropTypes, Component } from 'react' <add>import TodoTextInput from './TodoTextInput' <ide> <ide> class Header extends Component { <ide> handleSave(text) { <ide> if (text.length !== 0) { <del> this.props.addTodo(text); <add> this.props.addTodo(text) <ide> } <ide> } <ide> <ide> class Header extends Component { <ide> onSave={this.handleSave.bind(this)} <ide> placeholder='What needs to be done?' /> <ide> </header> <del> ); <add> ) <ide> } <ide> } <ide> <ide> Header.propTypes = { <ide> addTodo: PropTypes.func.isRequired <del>}; <add>} <ide> <del>export default Header; <add>export default Header <ide> ``` <ide> <ide> can be tested like: <ide> <ide> ```js <del>import expect from 'expect'; <del>import React from 'react'; <del>import TestUtils from 'react-addons-test-utils'; <del>import Header from '../../components/Header'; <del>import TodoTextInput from '../../components/TodoTextInput'; <add>import expect from 'expect' <add>import React from 'react' <add>import TestUtils from 'react-addons-test-utils' <add>import Header from '../../components/Header' <add>import TodoTextInput from '../../components/TodoTextInput' <ide> <ide> function setup() { <ide> let props = { <ide> addTodo: expect.createSpy() <del> }; <add> } <ide> <del> let renderer = TestUtils.createRenderer(); <del> renderer.render(<Header {...props} />); <del> let output = renderer.getRenderOutput(); <add> let renderer = TestUtils.createRenderer() <add> renderer.render(<Header {...props} />) <add> let output = renderer.getRenderOutput() <ide> <ide> return { <ide> props, <ide> output, <ide> renderer <del> }; <add> } <ide> } <ide> <ide> describe('components', () => { <ide> describe('Header', () => { <ide> it('should render correctly', () => { <del> const { output } = setup(); <add> const { output } = setup() <ide> <del> expect(output.type).toBe('header'); <del> expect(output.props.className).toBe('header'); <add> expect(output.type).toBe('header') <add> expect(output.props.className).toBe('header') <ide> <del> let [h1, input] = output.props.children; <add> let [ h1, input ] = output.props.children <ide> <del> expect(h1.type).toBe('h1'); <del> expect(h1.props.children).toBe('todos'); <add> expect(h1.type).toBe('h1') <add> expect(h1.props.children).toBe('todos') <ide> <del> expect(input.type).toBe(TodoTextInput); <del> expect(input.props.newTodo).toBe(true); <del> expect(input.props.placeholder).toBe('What needs to be done?'); <del> }); <add> expect(input.type).toBe(TodoTextInput) <add> expect(input.props.newTodo).toBe(true) <add> expect(input.props.placeholder).toBe('What needs to be done?') <add> }) <ide> <ide> it('should call addTodo if length of text is greater than 0', () => { <del> const { output, props } = setup(); <del> let input = output.props.children[1]; <del> input.props.onSave(''); <del> expect(props.addTodo.calls.length).toBe(0); <del> input.props.onSave('Use Redux'); <del> expect(props.addTodo.calls.length).toBe(1); <del> }); <del> }); <del>}); <add> const { output, props } = setup() <add> let input = output.props.children[1] <add> input.props.onSave('') <add> expect(props.addTodo.calls.length).toBe(0) <add> input.props.onSave('Use Redux') <add> expect(props.addTodo.calls.length).toBe(1) <add> }) <add> }) <add>}) <ide> ``` <ide> <ide> #### Fixing Broken `setState()` <ide> npm install --save-dev jsdom <ide> Then create a `setup.js` file in your test directory: <ide> <ide> ```js <del>import { jsdom } from 'jsdom'; <add>import { jsdom } from 'jsdom' <ide> <del>global.document = jsdom('<!doctype html><html><body></body></html>'); <del>global.window = document.defaultView; <del>global.navigator = global.window.navigator; <add>global.document = jsdom('<!doctype html><html><body></body></html>') <add>global.window = document.defaultView <add>global.navigator = global.window.navigator <ide> ``` <ide> <ide> It’s important that this code is evaluated *before* React is imported. To ensure this, modify your `mocha` command to include `--require ./test/setup.js` in the options in your `package.json`: <ide> If you use a library like [React Redux](https://github.com/rackt/react-redux), y <ide> Consider the following `App` component: <ide> <ide> ```js <del>import { connect } from 'react-redux'; <add>import { connect } from 'react-redux' <ide> <ide> class App extends Component { /* ... */ } <ide> <del>export default connect(mapStateToProps)(App); <add>export default connect(mapStateToProps)(App) <ide> ``` <ide> <ide> In a unit test, you would normally import the `App` component like this: <ide> <ide> ```js <del>import App from './App'; <add>import App from './App' <ide> ``` <ide> <ide> However, when you import it, you’re actually holding the wrapper component returned by `connect()`, and not the `App` component itself. If you want to test its interaction with Redux, this is good news: you can wrap it in a [`<Provider>`](https://github.com/rackt/react-redux#provider-store) with a store created specifically for this unit test. But sometimes you want to test just the rendering of the component, without a Redux store. <ide> <ide> In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component: <ide> <ide> ```js <del>import { connect } from 'react-redux'; <add>import { connect } from 'react-redux' <ide> <ide> // Use named export for unconnected component (for tests) <ide> export class App extends Component { /* ... */ } <ide> <ide> // Use default export for the connected component (for app) <del>export default connect(mapDispatchToProps)(App); <add>export default connect(mapDispatchToProps)(App) <ide> ``` <ide> <ide> Since the default export is still the decorated component, the import statement pictured above will work as before so you won’t have to change your application code. However, you can now import the undecorated `App` components in your test file like this: <ide> <ide> ```js <ide> // Note the curly braces: grab the named export instead of default export <del>import { App } from './App'; <add>import { App } from './App' <ide> ``` <ide> <ide> And if you need both: <ide> <ide> ```js <del>import ConnectedApp, { App } from './App'; <add>import ConnectedApp, { App } from './App' <ide> ``` <ide> <ide> In the app itself, you would still import it normally: <ide> <ide> ```js <del>import App from './App'; <add>import App from './App' <ide> ``` <ide> <ide> You would only use the named export for tests. <ide> Middleware functions wrap behavior of `dispatch` calls in Redux, so to test this <ide> #### Example <ide> <ide> ```js <del>import expect from 'expect'; <del>import * as types from '../../constants/ActionTypes'; <del>import singleDispatch from '../../middleware/singleDispatch'; <add>import expect from 'expect' <add>import * as types from '../../constants/ActionTypes' <add>import singleDispatch from '../../middleware/singleDispatch' <ide> <ide> const createFakeStore = fakeData => ({ <ide> getState() { <del> return fakeData; <add> return fakeData <ide> } <del>}); <add>}) <ide> <ide> const dispatchWithStoreOf = (storeData, action) => { <del> let dispatched = null; <del> const dispatch = singleDispatch(createFakeStore(storeData))(actionAttempt => dispatched = actionAttempt); <del> dispatch(action); <del> return dispatched; <add> let dispatched = null <add> const dispatch = singleDispatch(createFakeStore(storeData))(actionAttempt => dispatched = actionAttempt) <add> dispatch(action) <add> return dispatched <ide> }; <ide> <ide> describe('middleware', () => { <ide> it('should dispatch if store is empty', () => { <ide> const action = { <ide> type: types.ADD_TODO <del> }; <add> } <ide> <ide> expect( <ide> dispatchWithStoreOf({}, action) <del> ).toEqual(action); <del> }); <add> ).toEqual(action) <add> }) <ide> <ide> it('should not dispatch if store already has type', () => { <ide> const action = { <ide> type: types.ADD_TODO <del> }; <add> } <ide> <ide> expect( <ide> dispatchWithStoreOf({ <ide> [types.ADD_TODO]: 'dispatched' <ide> }, action) <del> ).toNotExist(); <del> }); <del>}); <add> ).toNotExist() <add> }) <add>}) <ide> ``` <ide> <ide> ### Glossary
5
Mixed
Ruby
add the new index before removing the old one
6eba8d27e6feecca88303df6500ef6b376344e29
<ide><path>activerecord/CHANGELOG.md <add>* `rename_index` adds the new index before removing the old one. This allows <add> to rename indexes on columns with a foreign key and prevents the following error: <add> <add> `Cannot drop index 'index_engines_on_car_id': needed in a foreign key constraint` <add> <add> *Cody Cutrer*, *Yves Senn* <add> <ide> * Raise `ActiveRecord::RecordNotDestroyed` when a replaced child marked with `dependent: destroy` fails to be destroyed. <ide> <ide> Fix #12812 <ide> <ide> *Brian Thomas Storti* <ide> <add> <ide> * Fix validation on uniqueness of empty association. <ide> <ide> *Evgeny Li* <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def rename_index(table_name, old_name, new_name) <ide> # this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance) <ide> old_index_def = indexes(table_name).detect { |i| i.name == old_name } <ide> return unless old_index_def <del> remove_index(table_name, :name => old_name) <del> add_index(table_name, old_index_def.columns, :name => new_name, :unique => old_index_def.unique) <add> add_index(table_name, old_index_def.columns, name: new_name, unique: old_index_def.unique) <add> remove_index(table_name, name: old_name) <ide> end <ide> <ide> def index_name(table_name, options) #:nodoc: <ide><path>activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> class Mysql2Adapter <ide> class SchemaMigrationsTest < ActiveRecord::TestCase <del> def test_initializes_schema_migrations_for_encoding_utf8mb4 <del> conn = ActiveRecord::Base.connection <add> def test_renaming_index_on_foreign_key <add> connection.add_index "engines", "car_id" <add> connection.execute "ALTER TABLE engines ADD CONSTRAINT fk_engines_cars FOREIGN KEY (car_id) REFERENCES cars(id)" <add> <add> connection.rename_index("engines", "index_engines_on_car_id", "idx_renamed") <add> assert_equal ["idx_renamed"], connection.indexes("engines").map(&:name) <add> ensure <add> connection.execute "ALTER TABLE engines DROP FOREIGN KEY fk_engines_cars" <add> end <ide> <add> def test_initializes_schema_migrations_for_encoding_utf8mb4 <ide> smtn = ActiveRecord::Migrator.schema_migrations_table_name <del> conn.drop_table(smtn) if conn.table_exists?(smtn) <add> connection.drop_table(smtn) if connection.table_exists?(smtn) <ide> <del> config = conn.instance_variable_get(:@config) <add> config = connection.instance_variable_get(:@config) <ide> original_encoding = config[:encoding] <ide> <ide> config[:encoding] = 'utf8mb4' <del> conn.initialize_schema_migrations_table <add> connection.initialize_schema_migrations_table <ide> <del> assert conn.column_exists?(smtn, :version, :string, limit: Mysql2Adapter::MAX_INDEX_LENGTH_FOR_UTF8MB4) <add> assert connection.column_exists?(smtn, :version, :string, limit: Mysql2Adapter::MAX_INDEX_LENGTH_FOR_UTF8MB4) <ide> ensure <ide> config[:encoding] = original_encoding <ide> end <add> <add> private <add> def connection <add> @connection ||= ActiveRecord::Base.connection <add> end <ide> end <ide> end <ide> end
3
PHP
PHP
add a method to forget all queued event handlers
2e3f5533a77837aa1b2781bc5ffa9fce01846827
<ide><path>src/Illuminate/Events/Dispatcher.php <ide> public function forget($event) <ide> unset($this->listeners[$event], $this->sorted[$event]); <ide> } <ide> <add> /** <add> * Forget all of the queued listeners. <add> * <add> * @return void <add> */ <add> public function forgetQueued() <add> { <add> foreach ($this->listeners as $key => $value) <add> { <add> if (ends_with($key, '_queue')) $this->forget($key); <add> } <add> } <add> <ide> } <ide><path>tests/Events/EventsDispatcherTest.php <ide> public function testQueuedEventsAreFired() <ide> } <ide> <ide> <add> public function testQueuedEventsCanBeForgotten() <add> { <add> $_SERVER['__event.test'] = 'unset'; <add> $d = new Dispatcher; <add> $d->queue('update', array('name' => 'taylor')); <add> $d->listen('update', function($name) <add> { <add> $_SERVER['__event.test'] = $name; <add> }); <add> <add> $d->forgetQueued(); <add> $d->flush('update'); <add> $this->assertEquals('unset', $_SERVER['__event.test']); <add> } <add> <add> <ide> public function testWildcardListeners() <ide> { <ide> unset($_SERVER['__event.test']);
2
PHP
PHP
send parameters as urlencoded by default
02228fc6351a0ca9bed68dad9583205eb9df6a83
<ide><path>src/Network/Http/Adapter/Stream.php <ide> protected function _buildContent(Request $request, $options) <ide> if (is_array($content)) { <ide> $formData = new FormData(); <ide> $formData->addMany($content); <del> $type = 'multipart/form-data; boundary="' . $formData->boundary() . '"'; <add> $type = $formData->contentType(); <ide> $request->header('Content-Type', $type); <ide> $this->_contextOptions['content'] = (string)$formData; <ide> return; <ide><path>src/Network/Http/Client.php <ide> * ### Sending request bodies <ide> * <ide> * By default any POST/PUT/PATCH/DELETE request with $data will <del> * send their data as `multipart/form-data`. <add> * send their data as `application/x-www-form-urlencoded` unless <add> * there are attached files. In that case `multipart/form-data` <add> * will be used. <ide> * <ide> * When sending request bodies you can use the `type` option to <ide> * set the Content-Type for the request: <ide><path>src/Network/Http/FormData.php <ide> class FormData implements Countable <ide> */ <ide> protected $_boundary; <ide> <add> /** <add> * Whether or not this formdata object has attached files. <add> * <add> * @var boolean <add> */ <add> protected $_hasFile = false; <add> <ide> /** <ide> * The parts in the form data. <ide> * <ide> public function addMany(array $data) <ide> */ <ide> public function addFile($name, $value) <ide> { <add> $this->_hasFile = true; <add> <ide> $filename = false; <ide> $contentType = 'application/octet-stream'; <ide> if (is_resource($value)) { <ide> public function count() <ide> return count($this->_parts); <ide> } <ide> <add> /** <add> * Check whether or not the current payload <add> * has any files. <add> * <add> * @return boolean <add> */ <add> public function hasFile() <add> { <add> return $this->_hasFile; <add> } <add> <add> /** <add> * Get the content type for this payload. <add> * <add> * If this object contains files, `multipart/form-data` will be used, <add> * otherwise `application/x-www-form-urlencoded` will be used. <add> * <add> * @return string <add> */ <add> public function contentType() <add> { <add> if (!$this->hasFile()) { <add> return 'application/x-www-form-urlencoded'; <add> } <add> return 'multipart/form-data; boundary="' . $this->boundary() . '"'; <add> } <add> <ide> /** <ide> * Converts the FormData and its parts into a string suitable <ide> * for use in an HTTP request. <ide> public function count() <ide> */ <ide> public function __toString() <ide> { <del> $boundary = $this->boundary(); <del> $out = ''; <add> if ($this->hasFile()) { <add> $boundary = $this->boundary(); <add> $out = ''; <add> foreach ($this->_parts as $part) { <add> $out .= "--$boundary\r\n"; <add> $out .= (string)$part; <add> $out .= "\r\n"; <add> } <add> $out .= "--$boundary--\r\n\r\n"; <add> return $out; <add> } <add> $data = []; <ide> foreach ($this->_parts as $part) { <del> $out .= "--$boundary\r\n"; <del> $out .= (string)$part; <del> $out .= "\r\n"; <add> $data[$part->name()] = $part->value(); <ide> } <del> $out .= "--$boundary--\r\n\r\n"; <del> return $out; <add> return http_build_query($data); <ide> } <ide> } <ide><path>src/Network/Http/FormData/Part.php <ide> public function transferEncoding($type) <ide> $this->_transferEncoding = $type; <ide> } <ide> <add> /** <add> * Get the part name. <add> * <add> * @return string <add> */ <add> public function name() <add> { <add> return $this->_name; <add> } <add> <add> /** <add> * Get the value. <add> * <add> * @return string <add> */ <add> public function value() <add> { <add> return $this->_value; <add> } <add> <ide> /** <ide> * Convert the part into a string. <ide> * <ide><path>tests/TestCase/Network/Http/Adapter/StreamTest.php <ide> public function testSendContextContentArray() <ide> $expected = [ <ide> 'Connection: close', <ide> 'User-Agent: CakePHP', <del> 'Content-Type: multipart/form-data; boundary="', <add> 'Content-Type: application/x-www-form-urlencoded', <ide> ]; <ide> $this->assertStringStartsWith(implode("\r\n", $expected), $result['header']); <del> $this->assertContains('Content-Disposition: form-data; name="a"', $result['content']); <del> $this->assertContains('my value', $result['content']); <add> $this->assertContains('a=my+value', $result['content']); <add> $this->assertContains('my+value', $result['content']); <add> } <add> <add> /** <add> * Test send() + context options with array content. <add> * <add> * @return void <add> */ <add> public function testSendContextContentArrayFiles() <add> { <add> $request = new Request(); <add> $request->url('http://localhost') <add> ->header([ <add> 'Content-Type' => 'application/json' <add> ]) <add> ->body(['upload' => fopen(CORE_PATH . 'VERSION.txt', 'r')]); <add> <add> $this->stream->send($request, []); <add> $result = $this->stream->contextOptions(); <add> $expected = [ <add> 'Connection: close', <add> 'User-Agent: CakePHP', <add> 'Content-Type: multipart/form-data', <add> ]; <add> $this->assertStringStartsWith(implode("\r\n", $expected), $result['header']); <add> $this->assertContains('name="upload"', $result['content']); <add> $this->assertContains('filename="VERSION.txt"', $result['content']); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Network/Http/FormDataTest.php <ide> public function testAddSimple() <ide> $this->assertCount(4, $data); <ide> $boundary = $data->boundary(); <ide> $result = (string)$data; <del> $expected = [ <del> '--' . $boundary, <del> 'Content-Disposition: form-data; name="test"', <del> '', <del> 'value', <del> '--' . $boundary, <del> 'Content-Disposition: form-data; name="empty"', <del> '', <del> '', <del> '--' . $boundary, <del> 'Content-Disposition: form-data; name="int"', <del> '', <del> '1', <del> '--' . $boundary, <del> 'Content-Disposition: form-data; name="float"', <del> '', <del> '2.3', <del> '--' . $boundary . '--', <del> '', <del> '', <del> ]; <del> $this->assertEquals(implode("\r\n", $expected), $result); <add> $expected = 'test=value&empty=&int=1&float=2.3'; <add> $this->assertEquals($expected, $result); <ide> } <ide> <ide> /** <ide> public function testAddArray() <ide> 'published' => 'Y', <ide> 'tags' => ['blog', 'cakephp'] <ide> ]); <del> $boundary = $data->boundary(); <ide> $result = (string)$data; <del> <del> $expected = [ <del> '--' . $boundary, <del> 'Content-Disposition: form-data; name="Article[title]"', <del> '', <del> 'first post', <del> '--' . $boundary, <del> 'Content-Disposition: form-data; name="Article[published]"', <del> '', <del> 'Y', <del> '--' . $boundary, <del> 'Content-Disposition: form-data; name="Article[tags][0]"', <del> '', <del> 'blog', <del> '--' . $boundary, <del> 'Content-Disposition: form-data; name="Article[tags][1]"', <del> '', <del> 'cakephp', <del> '--' . $boundary . '--', <del> '', <del> '', <del> ]; <del> $this->assertEquals(implode("\r\n", $expected), $result); <add> $expected = 'Article%5Btitle%5D=first+post&Article%5Bpublished%5D=Y&' . <add> 'Article%5Btags%5D%5B0%5D=blog&Article%5Btags%5D%5B1%5D=cakephp'; <add> $this->assertEquals($expected, $result); <ide> } <ide> <ide> /**
6
Python
Python
remove unittest dependencies in numpy/core/tests
a3d0647c4be537e064703087bf09208f9f9a67ba
<ide><path>numpy/core/tests/test_abc.py <ide> from __future__ import division, absolute_import, print_function <ide> <del>from numpy.testing import TestCase, assert_, run_module_suite <add>from numpy.testing import assert_, run_module_suite <ide> <ide> import numbers <ide> from numpy.core.numerictypes import sctypes <ide> <del>class ABC(TestCase): <add>class TestABC(object): <ide> def test_floats(self): <ide> for t in sctypes['float']: <del> assert_(isinstance(t(), numbers.Real), <add> assert_(isinstance(t(), numbers.Real), <ide> "{0} is not instance of Real".format(t.__name__)) <ide> assert_(issubclass(t, numbers.Real), <ide> "{0} is not subclass of Real".format(t.__name__)) <del> assert_(not isinstance(t(), numbers.Rational), <add> assert_(not isinstance(t(), numbers.Rational), <ide> "{0} is instance of Rational".format(t.__name__)) <ide> assert_(not issubclass(t, numbers.Rational), <ide> "{0} is subclass of Rational".format(t.__name__)) <ide> <ide> def test_complex(self): <ide> for t in sctypes['complex']: <del> assert_(isinstance(t(), numbers.Complex), <add> assert_(isinstance(t(), numbers.Complex), <ide> "{0} is not instance of Complex".format(t.__name__)) <ide> assert_(issubclass(t, numbers.Complex), <ide> "{0} is not subclass of Complex".format(t.__name__)) <del> assert_(not isinstance(t(), numbers.Real), <add> assert_(not isinstance(t(), numbers.Real), <ide> "{0} is instance of Real".format(t.__name__)) <ide> assert_(not issubclass(t, numbers.Real), <ide> "{0} is subclass of Real".format(t.__name__)) <ide> <ide> def test_int(self): <ide> for t in sctypes['int']: <del> assert_(isinstance(t(), numbers.Integral), <add> assert_(isinstance(t(), numbers.Integral), <ide> "{0} is not instance of Integral".format(t.__name__)) <ide> assert_(issubclass(t, numbers.Integral), <ide> "{0} is not subclass of Integral".format(t.__name__)) <ide> <ide> def test_uint(self): <ide> for t in sctypes['uint']: <del> assert_(isinstance(t(), numbers.Integral), <add> assert_(isinstance(t(), numbers.Integral), <ide> "{0} is not instance of Integral".format(t.__name__)) <ide> assert_(issubclass(t, numbers.Integral), <ide> "{0} is not subclass of Integral".format(t.__name__)) <ide><path>numpy/core/tests/test_arrayprint.py <ide> <ide> import numpy as np <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal <add> run_module_suite, assert_, assert_equal <ide> ) <ide> <ide> class TestArrayRepr(object): <ide> def test_containing_list(self): <ide> 'array([list([1, 2]), list([3])], dtype=object)') <ide> <ide> <del>class TestComplexArray(TestCase): <add>class TestComplexArray(object): <ide> def test_str(self): <ide> rvals = [0, 1, -1, np.inf, -np.inf, np.nan] <ide> cvals = [complex(rp, ip) for rp in rvals for ip in rvals] <ide> def test_str(self): <ide> for res, val in zip(actual, wanted): <ide> assert_(res == val) <ide> <del>class TestArray2String(TestCase): <add>class TestArray2String(object): <ide> def test_basic(self): <ide> """Basic test of array2string.""" <ide> a = np.arange(3) <ide> def test_structure_format(self): <ide> assert_equal(np.array2string(array_scalar), "( 1., 2.12345679, 3.)") <ide> <ide> <del>class TestPrintOptions: <add>class TestPrintOptions(object): <ide> """Test getting and setting global print options.""" <ide> <del> def setUp(self): <add> def setup(self): <ide> self.oldopts = np.get_printoptions() <ide> <del> def tearDown(self): <add> def teardown(self): <ide> np.set_printoptions(**self.oldopts) <ide> <ide> def test_basic(self): <ide><path>numpy/core/tests/test_datetime.py <ide> import numpy as np <ide> import datetime <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_raises, <add> run_module_suite, assert_, assert_equal, assert_raises, <ide> assert_warns, dec, suppress_warnings <ide> ) <ide> <ide> _has_pytz = False <ide> <ide> <del>class TestDateTime(TestCase): <add>class TestDateTime(object): <ide> def test_datetime_dtype_creation(self): <ide> for unit in ['Y', 'M', 'W', 'D', <ide> 'h', 'm', 's', 'ms', 'us', <ide> def test_datetime_compare_nat(self): <ide> assert_(np.not_equal(dt_other, dt_nat)) <ide> assert_(np.not_equal(td_nat, td_other)) <ide> assert_(np.not_equal(td_other, td_nat)) <del> self.assertEqual(len(sup.log), 0) <add> assert_equal(len(sup.log), 0) <ide> <ide> def test_datetime_minmax(self): <ide> # The metadata of the result should become the GCD <ide> def test_divisor_conversion_second(self): <ide> <ide> def test_divisor_conversion_fs(self): <ide> assert_(np.dtype('M8[fs/100]') == np.dtype('M8[10as]')) <del> self.assertRaises(ValueError, lambda: np.dtype('M8[3fs/10000]')) <add> assert_raises(ValueError, lambda: np.dtype('M8[3fs/10000]')) <ide> <ide> def test_divisor_conversion_as(self): <del> self.assertRaises(ValueError, lambda: np.dtype('M8[as/10]')) <add> assert_raises(ValueError, lambda: np.dtype('M8[as/10]')) <ide> <ide> def test_string_parser_variants(self): <ide> # Allow space instead of 'T' between date and time <ide> def test_isnat_error(self): <ide> assert_raises(ValueError, np.isnat, np.zeros(10, t)) <ide> <ide> <del>class TestDateTimeData(TestCase): <add>class TestDateTimeData(object): <ide> <ide> def test_basic(self): <ide> a = np.array(['1980-03-23'], dtype=np.datetime64) <ide><path>numpy/core/tests/test_defchararray.py <ide> import numpy as np <ide> from numpy.core.multiarray import _vec_string <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_array_equal <add> run_module_suite, assert_, assert_equal, assert_array_equal, assert_raises, <ide> ) <ide> <ide> kw_unicode_true = {'unicode': True} # make 2to3 work properly <ide> kw_unicode_false = {'unicode': False} <ide> <del>class TestBasic(TestCase): <add>class TestBasic(object): <ide> def test_from_object_array(self): <ide> A = np.array([['abc', 2], <ide> ['long ', '0123456789']], dtype='O') <ide> def test_from_object_array(self): <ide> def test_from_object_array_unicode(self): <ide> A = np.array([['abc', u'Sigma \u03a3'], <ide> ['long ', '0123456789']], dtype='O') <del> self.assertRaises(ValueError, np.char.array, (A,)) <add> assert_raises(ValueError, np.char.array, (A,)) <ide> B = np.char.array(A, **kw_unicode_true) <ide> assert_equal(B.dtype.itemsize, 10 * np.array('a', 'U').dtype.itemsize) <ide> assert_array_equal(B, [['abc', u'Sigma \u03a3'], <ide> def test_from_unicode_array(self): <ide> def fail(): <ide> np.char.array(A, **kw_unicode_false) <ide> <del> self.assertRaises(UnicodeEncodeError, fail) <add> assert_raises(UnicodeEncodeError, fail) <ide> <ide> def test_unicode_upconvert(self): <ide> A = np.char.array(['abc']) <ide> def test_from_unicode(self): <ide> assert_equal(A.itemsize, 4) <ide> assert_(issubclass(A.dtype.type, np.unicode_)) <ide> <del>class TestVecString(TestCase): <add>class TestVecString(object): <ide> def test_non_existent_method(self): <ide> <ide> def fail(): <ide> _vec_string('a', np.string_, 'bogus') <ide> <del> self.assertRaises(AttributeError, fail) <add> assert_raises(AttributeError, fail) <ide> <ide> def test_non_string_array(self): <ide> <ide> def fail(): <ide> _vec_string(1, np.string_, 'strip') <ide> <del> self.assertRaises(TypeError, fail) <add> assert_raises(TypeError, fail) <ide> <ide> def test_invalid_args_tuple(self): <ide> <ide> def fail(): <ide> _vec_string(['a'], np.string_, 'strip', 1) <ide> <del> self.assertRaises(TypeError, fail) <add> assert_raises(TypeError, fail) <ide> <ide> def test_invalid_type_descr(self): <ide> <ide> def fail(): <ide> _vec_string(['a'], 'BOGUS', 'strip') <ide> <del> self.assertRaises(TypeError, fail) <add> assert_raises(TypeError, fail) <ide> <ide> def test_invalid_function_args(self): <ide> <ide> def fail(): <ide> _vec_string(['a'], np.string_, 'strip', (1,)) <ide> <del> self.assertRaises(TypeError, fail) <add> assert_raises(TypeError, fail) <ide> <ide> def test_invalid_result_type(self): <ide> <ide> def fail(): <ide> _vec_string(['a'], np.integer, 'strip') <ide> <del> self.assertRaises(TypeError, fail) <add> assert_raises(TypeError, fail) <ide> <ide> def test_broadcast_error(self): <ide> <ide> def fail(): <ide> _vec_string([['abc', 'def']], np.integer, 'find', (['a', 'd', 'j'],)) <ide> <del> self.assertRaises(ValueError, fail) <add> assert_raises(ValueError, fail) <ide> <ide> <del>class TestWhitespace(TestCase): <del> def setUp(self): <add>class TestWhitespace(object): <add> def setup(self): <ide> self.A = np.array([['abc ', '123 '], <ide> ['789 ', 'xyz ']]).view(np.chararray) <ide> self.B = np.array([['abc', '123'], <ide> def test1(self): <ide> assert_(not np.any(self.A < self.B)) <ide> assert_(not np.any(self.A != self.B)) <ide> <del>class TestChar(TestCase): <del> def setUp(self): <add>class TestChar(object): <add> def setup(self): <ide> self.A = np.array('abc1', dtype='c').view(np.chararray) <ide> <ide> def test_it(self): <ide> assert_equal(self.A.shape, (4,)) <ide> assert_equal(self.A.upper()[:2].tobytes(), b'AB') <ide> <del>class TestComparisons(TestCase): <del> def setUp(self): <add>class TestComparisons(object): <add> def setup(self): <ide> self.A = np.array([['abc', '123'], <ide> ['789', 'xyz']]).view(np.chararray) <ide> self.B = np.array([['efg', '123 '], <ide> def test_less(self): <ide> class TestComparisonsMixed1(TestComparisons): <ide> """Ticket #1276""" <ide> <del> def setUp(self): <del> TestComparisons.setUp(self) <add> def setup(self): <add> TestComparisons.setup(self) <ide> self.B = np.array([['efg', '123 '], <ide> ['051', 'tuv']], np.unicode_).view(np.chararray) <ide> <ide> class TestComparisonsMixed2(TestComparisons): <ide> """Ticket #1276""" <ide> <del> def setUp(self): <del> TestComparisons.setUp(self) <add> def setup(self): <add> TestComparisons.setup(self) <ide> self.A = np.array([['abc', '123'], <ide> ['789', 'xyz']], np.unicode_).view(np.chararray) <ide> <del>class TestInformation(TestCase): <del> def setUp(self): <add>class TestInformation(object): <add> def setup(self): <ide> self.A = np.array([[' abc ', ''], <ide> ['12345', 'MixedCase'], <ide> ['123 \t 345 \0 ', 'UPPER']]).view(np.chararray) <ide> def test_endswith(self): <ide> def fail(): <ide> self.A.endswith('3', 'fdjk') <ide> <del> self.assertRaises(TypeError, fail) <add> assert_raises(TypeError, fail) <ide> <ide> def test_find(self): <ide> assert_(issubclass(self.A.find('a').dtype.type, np.integer)) <ide> def test_index(self): <ide> def fail(): <ide> self.A.index('a') <ide> <del> self.assertRaises(ValueError, fail) <add> assert_raises(ValueError, fail) <ide> assert_(np.char.index('abcba', 'b') == 1) <ide> assert_(issubclass(np.char.index('abcba', 'b').dtype.type, np.integer)) <ide> <ide> def test_rindex(self): <ide> def fail(): <ide> self.A.rindex('a') <ide> <del> self.assertRaises(ValueError, fail) <add> assert_raises(ValueError, fail) <ide> assert_(np.char.rindex('abcba', 'b') == 3) <ide> assert_(issubclass(np.char.rindex('abcba', 'b').dtype.type, np.integer)) <ide> <ide> def test_startswith(self): <ide> def fail(): <ide> self.A.startswith('3', 'fdjk') <ide> <del> self.assertRaises(TypeError, fail) <add> assert_raises(TypeError, fail) <ide> <ide> <del>class TestMethods(TestCase): <del> def setUp(self): <add>class TestMethods(object): <add> def setup(self): <ide> self.A = np.array([[' abc ', ''], <ide> ['12345', 'MixedCase'], <ide> ['123 \t 345 \0 ', 'UPPER']], <ide> def test_isnumeric(self): <ide> def fail(): <ide> self.A.isnumeric() <ide> <del> self.assertRaises(TypeError, fail) <add> assert_raises(TypeError, fail) <ide> assert_(issubclass(self.B.isnumeric().dtype.type, np.bool_)) <ide> assert_array_equal(self.B.isnumeric(), [ <ide> [False, False], [True, False], [False, False]]) <ide> def test_isdecimal(self): <ide> def fail(): <ide> self.A.isdecimal() <ide> <del> self.assertRaises(TypeError, fail) <add> assert_raises(TypeError, fail) <ide> assert_(issubclass(self.B.isdecimal().dtype.type, np.bool_)) <ide> assert_array_equal(self.B.isdecimal(), [ <ide> [False, False], [True, False], [False, False]]) <ide> <ide> <del>class TestOperations(TestCase): <del> def setUp(self): <add>class TestOperations(object): <add> def setup(self): <ide> self.A = np.array([['abc', '123'], <ide> ['789', 'xyz']]).view(np.chararray) <ide> self.B = np.array([['efg', '456'], <ide><path>numpy/core/tests/test_deprecations.py <ide> class _DeprecationTestCase(object): <ide> message = '' <ide> warning_cls = DeprecationWarning <ide> <del> def setUp(self): <add> def setup(self): <ide> self.warn_ctx = warnings.catch_warnings(record=True) <ide> self.log = self.warn_ctx.__enter__() <ide> <ide> def setUp(self): <ide> warnings.filterwarnings("always", message=self.message, <ide> category=self.warning_cls) <ide> <del> def tearDown(self): <add> def teardown(self): <ide> self.warn_ctx.__exit__() <ide> <ide> def assert_deprecated(self, function, num=1, ignore_others=False, <ide> def test_all_dtypes(self): <ide> class TestTestDeprecated(object): <ide> def test_assert_deprecated(self): <ide> test_case_instance = _DeprecationTestCase() <del> test_case_instance.setUp() <add> test_case_instance.setup() <ide> assert_raises(AssertionError, <ide> test_case_instance.assert_deprecated, <ide> lambda: None) <ide> def foo(): <ide> warnings.warn("foo", category=DeprecationWarning, stacklevel=2) <ide> <ide> test_case_instance.assert_deprecated(foo) <del> test_case_instance.tearDown() <add> test_case_instance.teardown() <ide> <ide> <ide> class TestClassicIntDivision(_DeprecationTestCase): <ide><path>numpy/core/tests/test_dtype.py <ide> import numpy as np <ide> from numpy.core.test_rational import rational <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_raises, <add> run_module_suite, assert_, assert_equal, assert_raises, <ide> dec <ide> ) <ide> <ide> def assert_dtype_not_equal(a, b): <ide> assert_(hash(a) != hash(b), <ide> "two different types hash to the same value !") <ide> <del>class TestBuiltin(TestCase): <add>class TestBuiltin(object): <ide> def test_run(self): <ide> """Only test hash runs at all.""" <ide> for t in [np.int, np.float, np.complex, np.int32, np.str, np.object, <ide> def test_dtype(self): <ide> dt2 = dt.newbyteorder("<") <ide> dt3 = dt.newbyteorder(">") <ide> if dt == dt2: <del> self.assertTrue(dt.byteorder != dt2.byteorder, "bogus test") <add> assert_(dt.byteorder != dt2.byteorder, "bogus test") <ide> assert_dtype_equal(dt, dt2) <ide> else: <ide> self.assertTrue(dt.byteorder != dt3.byteorder, "bogus test") <ide> def test_equivalent_dtype_hashing(self): <ide> else: <ide> left = uintp <ide> right = np.dtype(np.ulonglong) <del> self.assertTrue(left == right) <del> self.assertTrue(hash(left) == hash(right)) <add> assert_(left == right) <add> assert_(hash(left) == hash(right)) <ide> <ide> def test_invalid_types(self): <ide> # Make sure invalid type strings raise an error <ide> def test_bad_param(self): <ide> 'formats':['i1', 'f4'], <ide> 'offsets':[0, 2]}, align=True) <ide> <del>class TestRecord(TestCase): <add>class TestRecord(object): <ide> def test_equivalent_record(self): <ide> """Test whether equivalent record dtypes hash the same.""" <ide> a = np.dtype([('yo', np.int)]) <ide> def test_not_lists(self): <ide> """Test if an appropriate exception is raised when passing bad values to <ide> the dtype constructor. <ide> """ <del> self.assertRaises(TypeError, np.dtype, <del> dict(names=set(['A', 'B']), formats=['f8', 'i4'])) <del> self.assertRaises(TypeError, np.dtype, <del> dict(names=['A', 'B'], formats=set(['f8', 'i4']))) <add> assert_raises(TypeError, np.dtype, <add> dict(names=set(['A', 'B']), formats=['f8', 'i4'])) <add> assert_raises(TypeError, np.dtype, <add> dict(names=['A', 'B'], formats=set(['f8', 'i4']))) <ide> <ide> def test_aligned_size(self): <ide> # Check that structured dtypes get padded to an aligned size <ide> def test_bool_commastring(self): <ide> def test_nonint_offsets(self): <ide> # gh-8059 <ide> def make_dtype(off): <del> return np.dtype({'names': ['A'], 'formats': ['i4'], <add> return np.dtype({'names': ['A'], 'formats': ['i4'], <ide> 'offsets': [off]}) <del> <add> <ide> assert_raises(TypeError, make_dtype, 'ASD') <ide> assert_raises(OverflowError, make_dtype, 2**70) <ide> assert_raises(TypeError, make_dtype, 2.3) <ide> def make_dtype(off): <ide> np.zeros(1, dtype=dt)[0].item() <ide> <ide> <del>class TestSubarray(TestCase): <add>class TestSubarray(object): <ide> def test_single_subarray(self): <ide> a = np.dtype((np.int, (2))) <ide> b = np.dtype((np.int, (2,))) <ide> def test_alignment(self): <ide> assert_equal(t1.alignment, t2.alignment) <ide> <ide> <del>class TestMonsterType(TestCase): <add>class TestMonsterType(object): <ide> """Test deeply nested subtypes.""" <ide> <ide> def test1(self): <ide> def test1(self): <ide> ('yi', np.dtype((a, (3, 2))))]) <ide> assert_dtype_equal(c, d) <ide> <del>class TestMetadata(TestCase): <add>class TestMetadata(object): <ide> def test_no_metadata(self): <ide> d = np.dtype(int) <del> self.assertEqual(d.metadata, None) <add> assert_(d.metadata is None) <ide> <ide> def test_metadata_takes_dict(self): <ide> d = np.dtype(int, metadata={'datum': 1}) <del> self.assertEqual(d.metadata, {'datum': 1}) <add> assert_(d.metadata == {'datum': 1}) <ide> <ide> def test_metadata_rejects_nondict(self): <del> self.assertRaises(TypeError, np.dtype, int, metadata='datum') <del> self.assertRaises(TypeError, np.dtype, int, metadata=1) <del> self.assertRaises(TypeError, np.dtype, int, metadata=None) <add> assert_raises(TypeError, np.dtype, int, metadata='datum') <add> assert_raises(TypeError, np.dtype, int, metadata=1) <add> assert_raises(TypeError, np.dtype, int, metadata=None) <ide> <ide> def test_nested_metadata(self): <ide> d = np.dtype([('a', np.dtype(int, metadata={'datum': 1}))]) <del> self.assertEqual(d['a'].metadata, {'datum': 1}) <add> assert_(d['a'].metadata == {'datum': 1}) <ide> <del> def base_metadata_copied(self): <add> def test_base_metadata_copied(self): <ide> d = np.dtype((np.void, np.dtype('i4,i4', metadata={'datum': 1}))) <del> assert_equal(d.metadata, {'datum': 1}) <add> assert_(d.metadata == {'datum': 1}) <ide> <del>class TestString(TestCase): <add>class TestString(object): <ide> def test_complex_dtype_str(self): <ide> dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)), <ide> ('rtile', '>f4', (64, 36))], (3,)), <ide> def test_empty_string_to_object(self): <ide> # Pull request #4722 <ide> np.array(["", ""]).astype(object) <ide> <del>class TestDtypeAttributeDeletion(TestCase): <add>class TestDtypeAttributeDeletion(object): <ide> <ide> def test_dtype_non_writable_attributes_deletion(self): <ide> dt = np.dtype(np.double) <ide> def test_dtype_writable_attributes_deletion(self): <ide> assert_raises(AttributeError, delattr, dt, s) <ide> <ide> <del>class TestDtypeAttributes(TestCase): <add>class TestDtypeAttributes(object): <ide> def test_descr_has_trailing_void(self): <ide> # see gh-6359 <ide> dtype = np.dtype({ <ide> class user_def_subcls(np.void): <ide> assert_equal(np.dtype(user_def_subcls).name, 'user_def_subcls') <ide> <ide> <del>class TestPickling(TestCase): <add>class TestPickling(object): <ide> <ide> def check_pickling(self, dtype): <ide> for proto in range(pickle.HIGHEST_PROTOCOL + 1): <ide> pickled = pickle.loads(pickle.dumps(dtype, proto)) <ide> assert_equal(pickled, dtype) <ide> assert_equal(pickled.descr, dtype.descr) <del> if dtype.metadata: <add> if dtype.metadata is not None: <ide> assert_equal(pickled.metadata, dtype.metadata) <del> else: <del> self.assertFalse(pickled.metadata) # may be None <ide> # Check the reconstructed dtype is functional <ide> x = np.zeros(3, dtype=dtype) <ide> y = np.zeros(3, dtype=pickled) <ide><path>numpy/core/tests/test_einsum.py <ide> <ide> import numpy as np <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_array_equal, <add> run_module_suite, assert_, assert_equal, assert_array_equal, <ide> assert_almost_equal, assert_raises, suppress_warnings <ide> ) <ide> <ide> global_size_dict[char] = size <ide> <ide> <del>class TestEinSum(TestCase): <add>class TestEinSum(object): <ide> def test_einsum_errors(self): <ide> for do_opt in [True, False]: <ide> # Need enough arguments <ide> def test_random_cases(self): <ide> self.optimize_compare('aef,fbc,dca->bde') <ide> <ide> <del>class TestEinSumPath(TestCase): <add>class TestEinSumPath(object): <ide> def build_operands(self, string): <ide> <ide> # Builds views based off initial operands <ide><path>numpy/core/tests/test_errstate.py <ide> import platform <ide> <ide> import numpy as np <del>from numpy.testing import TestCase, assert_, run_module_suite, dec <add>from numpy.testing import assert_, run_module_suite, dec <ide> <ide> <del>class TestErrstate(TestCase): <add>class TestErrstate(object): <ide> @dec.skipif(platform.machine() == "armv5tel", "See gh-413.") <ide> def test_invalid(self): <ide> with np.errstate(all='raise', under='ignore'): <ide><path>numpy/core/tests/test_function_base.py <ide> from numpy import (logspace, linspace, geomspace, dtype, array, sctypes, <ide> arange, isnan, ndarray, sqrt, nextafter) <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_raises, <add> run_module_suite, assert_, assert_equal, assert_raises, <ide> assert_array_equal, assert_allclose, suppress_warnings <ide> ) <ide> <ide> class PhysicalQuantity2(ndarray): <ide> __array_priority__ = 10 <ide> <ide> <del>class TestLogspace(TestCase): <add>class TestLogspace(object): <ide> <ide> def test_basic(self): <ide> y = logspace(0, 6) <ide> def test_subclass(self): <ide> assert_equal(ls, logspace(1.0, 7.0, 1)) <ide> <ide> <del>class TestGeomspace(TestCase): <add>class TestGeomspace(object): <ide> <ide> def test_basic(self): <ide> y = geomspace(1, 1e6) <ide> def test_bounds(self): <ide> assert_raises(ValueError, geomspace, 0, 0) <ide> <ide> <del>class TestLinspace(TestCase): <add>class TestLinspace(object): <ide> <ide> def test_basic(self): <ide> y = linspace(0, 10) <ide><path>numpy/core/tests/test_getlimits.py <ide> from numpy.core import finfo, iinfo <ide> from numpy import half, single, double, longdouble <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_equal, assert_ <add> run_module_suite, assert_equal, assert_, assert_raises <ide> ) <ide> from numpy.core.getlimits import (_discovered_machar, _float16_ma, _float32_ma, <ide> _float64_ma, _float128_ma, _float80_ma) <ide> <ide> ################################################## <ide> <del>class TestPythonFloat(TestCase): <add>class TestPythonFloat(object): <ide> def test_singleton(self): <ide> ftype = finfo(float) <ide> ftype2 = finfo(float) <ide> assert_equal(id(ftype), id(ftype2)) <ide> <del>class TestHalf(TestCase): <add>class TestHalf(object): <ide> def test_singleton(self): <ide> ftype = finfo(half) <ide> ftype2 = finfo(half) <ide> assert_equal(id(ftype), id(ftype2)) <ide> <del>class TestSingle(TestCase): <add>class TestSingle(object): <ide> def test_singleton(self): <ide> ftype = finfo(single) <ide> ftype2 = finfo(single) <ide> assert_equal(id(ftype), id(ftype2)) <ide> <del>class TestDouble(TestCase): <add>class TestDouble(object): <ide> def test_singleton(self): <ide> ftype = finfo(double) <ide> ftype2 = finfo(double) <ide> assert_equal(id(ftype), id(ftype2)) <ide> <del>class TestLongdouble(TestCase): <add>class TestLongdouble(object): <ide> def test_singleton(self,level=2): <ide> ftype = finfo(longdouble) <ide> ftype2 = finfo(longdouble) <ide> assert_equal(id(ftype), id(ftype2)) <ide> <del>class TestFinfo(TestCase): <add>class TestFinfo(object): <ide> def test_basic(self): <ide> dts = list(zip(['f2', 'f4', 'f8', 'c8', 'c16'], <ide> [np.float16, np.float32, np.float64, np.complex64, <ide> def test_basic(self): <ide> 'nmant', 'precision', 'resolution', 'tiny'): <ide> assert_equal(getattr(finfo(dt1), attr), <ide> getattr(finfo(dt2), attr), attr) <del> self.assertRaises(ValueError, finfo, 'i4') <add> assert_raises(ValueError, finfo, 'i4') <ide> <del>class TestIinfo(TestCase): <add>class TestIinfo(object): <ide> def test_basic(self): <ide> dts = list(zip(['i1', 'i2', 'i4', 'i8', <ide> 'u1', 'u2', 'u4', 'u8'], <ide> def test_basic(self): <ide> for attr in ('bits', 'min', 'max'): <ide> assert_equal(getattr(iinfo(dt1), attr), <ide> getattr(iinfo(dt2), attr), attr) <del> self.assertRaises(ValueError, iinfo, 'f4') <add> assert_raises(ValueError, iinfo, 'f4') <ide> <ide> def test_unsigned_max(self): <ide> types = np.sctypes['uint'] <ide> for T in types: <ide> assert_equal(iinfo(T).max, T(-1)) <ide> <del>class TestRepr(TestCase): <add>class TestRepr(object): <ide> def test_iinfo_repr(self): <ide> expected = "iinfo(min=-32768, max=32767, dtype=int16)" <ide> assert_equal(repr(np.iinfo(np.int16)), expected) <ide><path>numpy/core/tests/test_half.py <ide> <ide> import numpy as np <ide> from numpy import uint16, float16, float32, float64 <del>from numpy.testing import TestCase, run_module_suite, assert_, assert_equal, \ <del> dec <add>from numpy.testing import run_module_suite, assert_, assert_equal, dec <ide> <ide> <ide> def assert_raises_fpe(strmatch, callable, *args, **kwargs): <ide> def assert_raises_fpe(strmatch, callable, *args, **kwargs): <ide> assert_(False, <ide> "Did not raise floating point %s error" % strmatch) <ide> <del>class TestHalf(TestCase): <del> def setUp(self): <add>class TestHalf(object): <add> def setup(self): <ide> # An array of all possible float16 values <ide> self.all_f16 = np.arange(0x10000, dtype=uint16) <ide> self.all_f16.dtype = float16 <ide><path>numpy/core/tests/test_indexerrors.py <ide> from __future__ import division, absolute_import, print_function <ide> <ide> import numpy as np <del>from numpy.testing import TestCase, run_module_suite, assert_raises <add>from numpy.testing import run_module_suite, assert_raises <ide> <del>class TestIndexErrors(TestCase): <add>class TestIndexErrors(object): <ide> '''Tests to exercise indexerrors not covered by other tests.''' <ide> <ide> def test_arraytypes_fasttake(self): <ide><path>numpy/core/tests/test_indexing.py <ide> from numpy.core.multiarray_tests import array_indexing <ide> from itertools import product <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_raises, <add> run_module_suite, assert_, assert_equal, assert_raises, <ide> assert_array_equal, assert_warns, HAS_REFCOUNT <ide> ) <ide> <ide> _HAS_CTYPE = False <ide> <ide> <del>class TestIndexing(TestCase): <add>class TestIndexing(object): <ide> def test_index_no_floats(self): <ide> a = np.array([[[5]]]) <ide> <ide> def test_indexing_array_negative_strides(self): <ide> arr[slices] = 10 <ide> assert_array_equal(arr, 10.) <ide> <del>class TestFieldIndexing(TestCase): <add>class TestFieldIndexing(object): <ide> def test_scalar_return_type(self): <ide> # Field access on an array should return an array, even if it <ide> # is 0-d. <ide> def test_scalar_return_type(self): <ide> assert_(isinstance(a[['a']], np.ndarray)) <ide> <ide> <del>class TestBroadcastedAssignments(TestCase): <add>class TestBroadcastedAssignments(object): <ide> def assign(self, a, ind, val): <ide> a[ind] = val <ide> return a <ide> def test_broadcast_subspace(self): <ide> assert_((a[::-1] == v).all()) <ide> <ide> <del>class TestSubclasses(TestCase): <add>class TestSubclasses(object): <ide> def test_basic(self): <ide> class SubClass(np.ndarray): <ide> pass <ide> def __array_finalize__(self, old): <ide> assert_array_equal(new_s.finalize_status, new_s) <ide> assert_array_equal(new_s.old, s) <ide> <del>class TestFancyIndexingCast(TestCase): <add>class TestFancyIndexingCast(object): <ide> def test_boolean_index_cast_assign(self): <ide> # Setup the boolean index and float arrays. <ide> shape = (8, 63) <ide> def test_boolean_index_cast_assign(self): <ide> zero_array.__setitem__, bool_index, np.array([1j])) <ide> assert_equal(zero_array[0, 1], 0) <ide> <del>class TestFancyIndexingEquivalence(TestCase): <add>class TestFancyIndexingEquivalence(object): <ide> def test_object_assign(self): <ide> # Check that the field and object special case using copyto is active. <ide> # The right hand side cannot be converted to an array here. <ide> def test_cast_equivalence(self): <ide> assert_array_equal(a, b[0]) <ide> <ide> <del>class TestMultiIndexingAutomated(TestCase): <add>class TestMultiIndexingAutomated(object): <ide> """ <ide> These tests use code to mimic the C-Code indexing for selection. <ide> <ide> class TestMultiIndexingAutomated(TestCase): <ide> <ide> """ <ide> <del> def setUp(self): <add> def setup(self): <ide> self.a = np.arange(np.prod([3, 1, 5, 6])).reshape(3, 1, 5, 6) <ide> self.b = np.empty((3, 0, 5, 6)) <ide> self.complex_indices = ['skip', Ellipsis, <ide> def test_1d(self): <ide> for index in self.complex_indices: <ide> self._check_single_index(a, index) <ide> <del>class TestFloatNonIntegerArgument(TestCase): <add>class TestFloatNonIntegerArgument(object): <ide> """ <ide> These test that ``TypeError`` is raised when you try to use <ide> non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]`` <ide> def test_reduce_axis_float_index(self): <ide> assert_raises(TypeError, np.min, d, (.2, 1.2)) <ide> <ide> <del>class TestBooleanIndexing(TestCase): <add>class TestBooleanIndexing(object): <ide> # Using a boolean as integer argument/indexing is an error. <ide> def test_bool_as_int_argument_errors(self): <ide> a = np.array([[[1]]]) <ide> def test_boolean_indexing_weirdness(self): <ide> assert_raises(IndexError, lambda: a[False, [0, 1], ...]) <ide> <ide> <del>class TestArrayToIndexDeprecation(TestCase): <add>class TestArrayToIndexDeprecation(object): <ide> """Creating an an index from array not 0-D is an error. <ide> <ide> """ <ide> def test_array_to_index_error(self): <ide> assert_raises(TypeError, np.take, a, [0], a) <ide> <ide> <del>class TestNonIntegerArrayLike(TestCase): <add>class TestNonIntegerArrayLike(object): <ide> """Tests that array_likes only valid if can safely cast to integer. <ide> <ide> For instance, lists give IndexError when they cannot be safely cast to <ide> def test_basic(self): <ide> a.__getitem__([]) <ide> <ide> <del>class TestMultipleEllipsisError(TestCase): <add>class TestMultipleEllipsisError(object): <ide> """An index can only have a single ellipsis. <ide> <ide> """ <ide> def test_basic(self): <ide> assert_raises(IndexError, a.__getitem__, ((Ellipsis,) * 3,)) <ide> <ide> <del>class TestCApiAccess(TestCase): <add>class TestCApiAccess(object): <ide> def test_getitem(self): <ide> subscript = functools.partial(array_indexing, 0) <ide> <ide><path>numpy/core/tests/test_item_selection.py <ide> <ide> import numpy as np <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_raises, <add> run_module_suite, assert_, assert_raises, <ide> assert_array_equal, HAS_REFCOUNT <ide> ) <ide> <ide> <del>class TestTake(TestCase): <add>class TestTake(object): <ide> def test_simple(self): <ide> a = [[1, 2], [3, 4]] <ide> a_str = [[b'1', b'2'], [b'3', b'4']] <ide><path>numpy/core/tests/test_longdouble.py <ide> import numpy as np <ide> from numpy.testing import ( <ide> run_module_suite, assert_, assert_equal, dec, assert_raises, <del> assert_array_equal, TestCase, temppath, <add> assert_array_equal, temppath, <ide> ) <ide> from test_print import in_foreign_locale <ide> <ide> def test_fromstring_missing(): <ide> np.array([1])) <ide> <ide> <del>class FileBased(TestCase): <add>class TestFileBased(object): <ide> <ide> ldbl = 1 + LD_INFO.eps <ide> tgt = np.array([ldbl]*5) <ide><path>numpy/core/tests/test_machar.py <add>""" <add>Test machar. Given recent changes to hardcode type data, we might want to get <add>rid of both MachAr and this test at some point. <add> <add>""" <ide> from __future__ import division, absolute_import, print_function <ide> <ide> from numpy.core.machar import MachAr <ide> import numpy.core.numerictypes as ntypes <ide> from numpy import errstate, array <del>from numpy.testing import TestCase, run_module_suite <add>from numpy.testing import run_module_suite <ide> <del>class TestMachAr(TestCase): <add>class TestMachAr(object): <ide> def _run_machar_highprec(self): <ide> # Instantiate MachAr instance with high enough precision to cause <ide> # underflow <ide> try: <ide> hiprec = ntypes.float96 <ide> MachAr(lambda v:array([v], hiprec)) <ide> except AttributeError: <add> # Fixme, this needs to raise a 'skip' exception. <ide> "Skipping test: no ntypes.float96 available on this platform." <ide> <ide> def test_underlow(self): <ide> def test_underlow(self): <ide> try: <ide> self._run_machar_highprec() <ide> except FloatingPointError as e: <del> self.fail("Caught %s exception, should not have been raised." % e) <add> msg = "Caught %s exception, should not have been raised." % e <add> raise AssertionError(msg) <ide> <ide> <ide> if __name__ == "__main__": <ide><path>numpy/core/tests/test_memmap.py <ide> <ide> from numpy import arange, allclose, asarray <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_array_equal, <add> run_module_suite, assert_, assert_equal, assert_array_equal, <ide> dec, suppress_warnings <ide> ) <ide> <del>class TestMemmap(TestCase): <del> def setUp(self): <add>class TestMemmap(object): <add> def setup(self): <ide> self.tmpfp = NamedTemporaryFile(prefix='mmap') <ide> self.tempdir = mkdtemp() <ide> self.shape = (3, 4) <ide> self.dtype = 'float32' <ide> self.data = arange(12, dtype=self.dtype) <ide> self.data.resize(self.shape) <ide> <del> def tearDown(self): <add> def teardown(self): <ide> self.tmpfp.close() <ide> shutil.rmtree(self.tempdir) <ide> <ide> def test_roundtrip(self): <ide> shape=self.shape) <ide> assert_(allclose(self.data, newfp)) <ide> assert_array_equal(self.data, newfp) <del> self.assertEqual(newfp.flags.writeable, False) <add> assert_equal(newfp.flags.writeable, False) <ide> <ide> def test_open_with_filename(self): <ide> tmpname = mktemp('', 'mmap', dir=self.tempdir) <ide> def test_attributes(self): <ide> mode = "w+" <ide> fp = memmap(self.tmpfp, dtype=self.dtype, mode=mode, <ide> shape=self.shape, offset=offset) <del> self.assertEqual(offset, fp.offset) <del> self.assertEqual(mode, fp.mode) <add> assert_equal(offset, fp.offset) <add> assert_equal(mode, fp.mode) <ide> del fp <ide> <ide> def test_filename(self): <ide> def test_filename(self): <ide> shape=self.shape) <ide> abspath = os.path.abspath(tmpname) <ide> fp[:] = self.data[:] <del> self.assertEqual(abspath, fp.filename) <add> assert_equal(abspath, fp.filename) <ide> b = fp[:1] <del> self.assertEqual(abspath, b.filename) <add> assert_equal(abspath, b.filename) <ide> del b <ide> del fp <ide> <ide> def test_path(self): <ide> shape=self.shape) <ide> abspath = os.path.realpath(os.path.abspath(tmpname)) <ide> fp[:] = self.data[:] <del> self.assertEqual(abspath, str(fp.filename.resolve())) <add> assert_equal(abspath, str(fp.filename.resolve())) <ide> b = fp[:1] <del> self.assertEqual(abspath, str(b.filename.resolve())) <add> assert_equal(abspath, str(b.filename.resolve())) <ide> del b <ide> del fp <ide> <ide> def test_filename_fileobj(self): <ide> fp = memmap(self.tmpfp, dtype=self.dtype, mode="w+", <ide> shape=self.shape) <del> self.assertEqual(fp.filename, self.tmpfp.name) <add> assert_equal(fp.filename, self.tmpfp.name) <ide> <ide> @dec.knownfailureif(sys.platform == 'gnu0', "This test is known to fail on hurd") <ide> def test_flush(self): <ide><path>numpy/core/tests/test_multiarray.py <ide> test_inplace_increment, get_buffer_info, test_as_c_array, <ide> ) <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_raises, assert_warns, <add> run_module_suite, assert_, assert_raises, assert_warns, <ide> assert_equal, assert_almost_equal, assert_array_equal, assert_raises_regex, <ide> assert_array_almost_equal, assert_allclose, IS_PYPY, HAS_REFCOUNT, <ide> assert_array_less, runstring, dec, SkipTest, temppath, suppress_warnings <ide> def _aligned_zeros(shape, dtype=float, order="C", align=None): <ide> return data <ide> <ide> <del>class TestFlags(TestCase): <del> def setUp(self): <add>class TestFlags(object): <add> def setup(self): <ide> self.a = np.arange(10) <ide> <ide> def test_writeable(self): <ide> mydict = locals() <ide> self.a.flags.writeable = False <del> self.assertRaises(ValueError, runstring, 'self.a[0] = 3', mydict) <del> self.assertRaises(ValueError, runstring, 'self.a[0:1].itemset(3)', mydict) <add> assert_raises(ValueError, runstring, 'self.a[0] = 3', mydict) <add> assert_raises(ValueError, runstring, 'self.a[0:1].itemset(3)', mydict) <ide> self.a.flags.writeable = True <ide> self.a[0] = 5 <ide> self.a[0] = 0 <ide> def test_void_align(self): <ide> assert_(a.flags.aligned) <ide> <ide> <del>class TestHash(TestCase): <add>class TestHash(object): <ide> # see #3793 <ide> def test_int(self): <ide> for st, ut, s in [(np.int8, np.uint8, 8), <ide> def test_int(self): <ide> err_msg="%r: 2**%d - 1" % (ut, i)) <ide> <ide> <del>class TestAttributes(TestCase): <del> def setUp(self): <add>class TestAttributes(object): <add> def setup(self): <ide> self.one = np.arange(10) <ide> self.two = np.arange(20).reshape(4, 5) <ide> self.three = np.arange(60, dtype=np.float64).reshape(2, 5, 6) <ide> def test_dtypeattr(self): <ide> assert_equal(self.three.dtype, np.dtype(np.float_)) <ide> assert_equal(self.one.dtype.char, 'l') <ide> assert_equal(self.three.dtype.char, 'd') <del> self.assertTrue(self.three.dtype.str[0] in '<>') <add> assert_(self.three.dtype.str[0] in '<>') <ide> assert_equal(self.one.dtype.str[1], 'i') <ide> assert_equal(self.three.dtype.str[1], 'f') <ide> <ide> def make_array(size, offset, strides): <ide> strides=strides*x.itemsize) <ide> <ide> assert_equal(make_array(4, 4, -1), np.array([4, 3, 2, 1])) <del> self.assertRaises(ValueError, make_array, 4, 4, -2) <del> self.assertRaises(ValueError, make_array, 4, 2, -1) <del> self.assertRaises(ValueError, make_array, 8, 3, 1) <add> assert_raises(ValueError, make_array, 4, 4, -2) <add> assert_raises(ValueError, make_array, 4, 2, -1) <add> assert_raises(ValueError, make_array, 8, 3, 1) <ide> assert_equal(make_array(8, 3, 0), np.array([3]*8)) <ide> # Check behavior reported in gh-2503: <del> self.assertRaises(ValueError, make_array, (2, 3), 5, np.array([-2, -3])) <add> assert_raises(ValueError, make_array, (2, 3), 5, np.array([-2, -3])) <ide> make_array(0, 0, 10) <ide> <ide> def test_set_stridesattr(self): <ide> def make_array(size, offset, strides): <ide> <ide> assert_equal(make_array(4, 4, -1), np.array([4, 3, 2, 1])) <ide> assert_equal(make_array(7, 3, 1), np.array([3, 4, 5, 6, 7, 8, 9])) <del> self.assertRaises(ValueError, make_array, 4, 4, -2) <del> self.assertRaises(ValueError, make_array, 4, 2, -1) <del> self.assertRaises(RuntimeError, make_array, 8, 3, 1) <add> assert_raises(ValueError, make_array, 4, 4, -2) <add> assert_raises(ValueError, make_array, 4, 2, -1) <add> assert_raises(RuntimeError, make_array, 8, 3, 1) <ide> # Check that the true extent of the array is used. <ide> # Test relies on as_strided base not exposing a buffer. <ide> x = np.lib.stride_tricks.as_strided(np.arange(1), (10, 10), (0, 0)) <ide> <ide> def set_strides(arr, strides): <ide> arr.strides = strides <ide> <del> self.assertRaises(ValueError, set_strides, x, (10*x.itemsize, x.itemsize)) <add> assert_raises(ValueError, set_strides, x, (10*x.itemsize, x.itemsize)) <ide> <ide> # Test for offset calculations: <ide> x = np.lib.stride_tricks.as_strided(np.arange(10, dtype=np.int8)[-1], <ide> shape=(10,), strides=(-1,)) <del> self.assertRaises(ValueError, set_strides, x[::-1], -1) <add> assert_raises(ValueError, set_strides, x[::-1], -1) <ide> a = x[::-1] <ide> a.strides = 1 <ide> a[::2].strides = 2 <ide> def test_fill_struct_array(self): <ide> assert_array_equal(x['b'], [-2, -2]) <ide> <ide> <del>class TestArrayConstruction(TestCase): <add>class TestArrayConstruction(object): <ide> def test_array(self): <ide> d = np.ones(6) <ide> r = np.array([d, d]) <ide> def test_array_cont(self): <ide> assert_(np.asfortranarray(d).flags.f_contiguous) <ide> <ide> <del>class TestAssignment(TestCase): <add>class TestAssignment(object): <ide> def test_assignment_broadcasting(self): <ide> a = np.arange(6).reshape(2, 3) <ide> <ide> def test_longdouble_assignment(self): <ide> assert_equal(arr[0], tinya) <ide> <ide> <del>class TestDtypedescr(TestCase): <add>class TestDtypedescr(object): <ide> def test_construction(self): <ide> d1 = np.dtype('i4') <ide> assert_equal(d1, np.dtype(np.int32)) <ide> d2 = np.dtype('f8') <ide> assert_equal(d2, np.dtype(np.float64)) <ide> <ide> def test_byteorders(self): <del> self.assertNotEqual(np.dtype('<i4'), np.dtype('>i4')) <del> self.assertNotEqual(np.dtype([('a', '<i4')]), np.dtype([('a', '>i4')])) <add> assert_(np.dtype('<i4') != np.dtype('>i4')) <add> assert_(np.dtype([('a', '<i4')]) != np.dtype([('a', '>i4')])) <ide> <ide> <del>class TestZeroRank(TestCase): <del> def setUp(self): <add>class TestZeroRank(object): <add> def setup(self): <ide> self.d = np.array(0), np.array('x', object) <ide> <ide> def test_ellipsis_subscript(self): <ide> a, b = self.d <del> self.assertEqual(a[...], 0) <del> self.assertEqual(b[...], 'x') <del> self.assertTrue(a[...].base is a) # `a[...] is a` in numpy <1.9. <del> self.assertTrue(b[...].base is b) # `b[...] is b` in numpy <1.9. <add> assert_equal(a[...], 0) <add> assert_equal(b[...], 'x') <add> assert_(a[...].base is a) # `a[...] is a` in numpy <1.9. <add> assert_(b[...].base is b) # `b[...] is b` in numpy <1.9. <ide> <ide> def test_empty_subscript(self): <ide> a, b = self.d <del> self.assertEqual(a[()], 0) <del> self.assertEqual(b[()], 'x') <del> self.assertTrue(type(a[()]) is a.dtype.type) <del> self.assertTrue(type(b[()]) is str) <add> assert_equal(a[()], 0) <add> assert_equal(b[()], 'x') <add> assert_(type(a[()]) is a.dtype.type) <add> assert_(type(b[()]) is str) <ide> <ide> def test_invalid_subscript(self): <ide> a, b = self.d <del> self.assertRaises(IndexError, lambda x: x[0], a) <del> self.assertRaises(IndexError, lambda x: x[0], b) <del> self.assertRaises(IndexError, lambda x: x[np.array([], int)], a) <del> self.assertRaises(IndexError, lambda x: x[np.array([], int)], b) <add> assert_raises(IndexError, lambda x: x[0], a) <add> assert_raises(IndexError, lambda x: x[0], b) <add> assert_raises(IndexError, lambda x: x[np.array([], int)], a) <add> assert_raises(IndexError, lambda x: x[np.array([], int)], b) <ide> <ide> def test_ellipsis_subscript_assignment(self): <ide> a, b = self.d <ide> a[...] = 42 <del> self.assertEqual(a, 42) <add> assert_equal(a, 42) <ide> b[...] = '' <del> self.assertEqual(b.item(), '') <add> assert_equal(b.item(), '') <ide> <ide> def test_empty_subscript_assignment(self): <ide> a, b = self.d <ide> a[()] = 42 <del> self.assertEqual(a, 42) <add> assert_equal(a, 42) <ide> b[()] = '' <del> self.assertEqual(b.item(), '') <add> assert_equal(b.item(), '') <ide> <ide> def test_invalid_subscript_assignment(self): <ide> a, b = self.d <ide> <ide> def assign(x, i, v): <ide> x[i] = v <ide> <del> self.assertRaises(IndexError, assign, a, 0, 42) <del> self.assertRaises(IndexError, assign, b, 0, '') <del> self.assertRaises(ValueError, assign, a, (), '') <add> assert_raises(IndexError, assign, a, 0, 42) <add> assert_raises(IndexError, assign, b, 0, '') <add> assert_raises(ValueError, assign, a, (), '') <ide> <ide> def test_newaxis(self): <ide> a, b = self.d <del> self.assertEqual(a[np.newaxis].shape, (1,)) <del> self.assertEqual(a[..., np.newaxis].shape, (1,)) <del> self.assertEqual(a[np.newaxis, ...].shape, (1,)) <del> self.assertEqual(a[..., np.newaxis].shape, (1,)) <del> self.assertEqual(a[np.newaxis, ..., np.newaxis].shape, (1, 1)) <del> self.assertEqual(a[..., np.newaxis, np.newaxis].shape, (1, 1)) <del> self.assertEqual(a[np.newaxis, np.newaxis, ...].shape, (1, 1)) <del> self.assertEqual(a[(np.newaxis,)*10].shape, (1,)*10) <add> assert_equal(a[np.newaxis].shape, (1,)) <add> assert_equal(a[..., np.newaxis].shape, (1,)) <add> assert_equal(a[np.newaxis, ...].shape, (1,)) <add> assert_equal(a[..., np.newaxis].shape, (1,)) <add> assert_equal(a[np.newaxis, ..., np.newaxis].shape, (1, 1)) <add> assert_equal(a[..., np.newaxis, np.newaxis].shape, (1, 1)) <add> assert_equal(a[np.newaxis, np.newaxis, ...].shape, (1, 1)) <add> assert_equal(a[(np.newaxis,)*10].shape, (1,)*10) <ide> <ide> def test_invalid_newaxis(self): <ide> a, b = self.d <ide> <ide> def subscript(x, i): <ide> x[i] <ide> <del> self.assertRaises(IndexError, subscript, a, (np.newaxis, 0)) <del> self.assertRaises(IndexError, subscript, a, (np.newaxis,)*50) <add> assert_raises(IndexError, subscript, a, (np.newaxis, 0)) <add> assert_raises(IndexError, subscript, a, (np.newaxis,)*50) <ide> <ide> def test_constructor(self): <ide> x = np.ndarray(()) <ide> x[()] = 5 <del> self.assertEqual(x[()], 5) <add> assert_equal(x[()], 5) <ide> y = np.ndarray((), buffer=x) <ide> y[()] = 6 <del> self.assertEqual(x[()], 6) <add> assert_equal(x[()], 6) <ide> <ide> def test_output(self): <ide> x = np.array(2) <del> self.assertRaises(ValueError, np.add, x, [1], x) <add> assert_raises(ValueError, np.add, x, [1], x) <ide> <ide> <del>class TestScalarIndexing(TestCase): <del> def setUp(self): <add>class TestScalarIndexing(object): <add> def setup(self): <ide> self.d = np.array([0, 1])[0] <ide> <ide> def test_ellipsis_subscript(self): <ide> a = self.d <del> self.assertEqual(a[...], 0) <del> self.assertEqual(a[...].shape, ()) <add> assert_equal(a[...], 0) <add> assert_equal(a[...].shape, ()) <ide> <ide> def test_empty_subscript(self): <ide> a = self.d <del> self.assertEqual(a[()], 0) <del> self.assertEqual(a[()].shape, ()) <add> assert_equal(a[()], 0) <add> assert_equal(a[()].shape, ()) <ide> <ide> def test_invalid_subscript(self): <ide> a = self.d <del> self.assertRaises(IndexError, lambda x: x[0], a) <del> self.assertRaises(IndexError, lambda x: x[np.array([], int)], a) <add> assert_raises(IndexError, lambda x: x[0], a) <add> assert_raises(IndexError, lambda x: x[np.array([], int)], a) <ide> <ide> def test_invalid_subscript_assignment(self): <ide> a = self.d <ide> <ide> def assign(x, i, v): <ide> x[i] = v <ide> <del> self.assertRaises(TypeError, assign, a, 0, 42) <add> assert_raises(TypeError, assign, a, 0, 42) <ide> <ide> def test_newaxis(self): <ide> a = self.d <del> self.assertEqual(a[np.newaxis].shape, (1,)) <del> self.assertEqual(a[..., np.newaxis].shape, (1,)) <del> self.assertEqual(a[np.newaxis, ...].shape, (1,)) <del> self.assertEqual(a[..., np.newaxis].shape, (1,)) <del> self.assertEqual(a[np.newaxis, ..., np.newaxis].shape, (1, 1)) <del> self.assertEqual(a[..., np.newaxis, np.newaxis].shape, (1, 1)) <del> self.assertEqual(a[np.newaxis, np.newaxis, ...].shape, (1, 1)) <del> self.assertEqual(a[(np.newaxis,)*10].shape, (1,)*10) <add> assert_equal(a[np.newaxis].shape, (1,)) <add> assert_equal(a[..., np.newaxis].shape, (1,)) <add> assert_equal(a[np.newaxis, ...].shape, (1,)) <add> assert_equal(a[..., np.newaxis].shape, (1,)) <add> assert_equal(a[np.newaxis, ..., np.newaxis].shape, (1, 1)) <add> assert_equal(a[..., np.newaxis, np.newaxis].shape, (1, 1)) <add> assert_equal(a[np.newaxis, np.newaxis, ...].shape, (1, 1)) <add> assert_equal(a[(np.newaxis,)*10].shape, (1,)*10) <ide> <ide> def test_invalid_newaxis(self): <ide> a = self.d <ide> <ide> def subscript(x, i): <ide> x[i] <ide> <del> self.assertRaises(IndexError, subscript, a, (np.newaxis, 0)) <del> self.assertRaises(IndexError, subscript, a, (np.newaxis,)*50) <add> assert_raises(IndexError, subscript, a, (np.newaxis, 0)) <add> assert_raises(IndexError, subscript, a, (np.newaxis,)*50) <ide> <ide> def test_overlapping_assignment(self): <ide> # With positive strides <ide> def test_overlapping_assignment(self): <ide> assert_equal(a, [0, 1, 0, 1, 2]) <ide> <ide> <del>class TestCreation(TestCase): <add>class TestCreation(object): <ide> def test_from_attribute(self): <ide> class x(object): <ide> def __array__(self, dtype=None): <ide> pass <ide> <del> self.assertRaises(ValueError, np.array, x()) <add> assert_raises(ValueError, np.array, x()) <ide> <ide> def test_from_string(self): <ide> types = np.typecodes['AllInteger'] + np.typecodes['Float'] <ide> def test_array_too_big(self): <ide> shape=(max_bytes//itemsize + 1,), dtype=dtype) <ide> <ide> <del>class TestStructured(TestCase): <add>class TestStructured(object): <ide> def test_subarray_field_access(self): <ide> a = np.zeros((3, 5), dtype=[('a', ('i4', (2, 2)))]) <ide> a['a'] = np.arange(60).reshape(3, 5, 2, 2) <ide> def test_base_attr(self): <ide> assert_(b.base is a) <ide> <ide> <del>class TestBool(TestCase): <add>class TestBool(object): <ide> def test_test_interning(self): <ide> a0 = np.bool_(0) <ide> b0 = np.bool_(False) <del> self.assertTrue(a0 is b0) <add> assert_(a0 is b0) <ide> a1 = np.bool_(1) <ide> b1 = np.bool_(True) <del> self.assertTrue(a1 is b1) <del> self.assertTrue(np.array([True])[0] is a1) <del> self.assertTrue(np.array(True)[()] is a1) <add> assert_(a1 is b1) <add> assert_(np.array([True])[0] is a1) <add> assert_(np.array(True)[()] is a1) <ide> <ide> def test_sum(self): <ide> d = np.ones(101, dtype=np.bool) <ide> def check_count_nonzero(self, power, length): <ide> l = [(i & x) != 0 for x in powers] <ide> a = np.array(l, dtype=np.bool) <ide> c = builtins.sum(l) <del> self.assertEqual(np.count_nonzero(a), c) <add> assert_equal(np.count_nonzero(a), c) <ide> av = a.view(np.uint8) <ide> av *= 3 <del> self.assertEqual(np.count_nonzero(a), c) <add> assert_equal(np.count_nonzero(a), c) <ide> av *= 4 <del> self.assertEqual(np.count_nonzero(a), c) <add> assert_equal(np.count_nonzero(a), c) <ide> av[av != 0] = 0xFF <del> self.assertEqual(np.count_nonzero(a), c) <add> assert_equal(np.count_nonzero(a), c) <ide> <ide> def test_count_nonzero(self): <ide> # check all 12 bit combinations in a length 17 array <ide> def test_count_nonzero_unaligned(self): <ide> for o in range(7): <ide> a = np.zeros((18,), dtype=np.bool)[o+1:] <ide> a[:o] = True <del> self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist())) <add> assert_equal(np.count_nonzero(a), builtins.sum(a.tolist())) <ide> a = np.ones((18,), dtype=np.bool)[o+1:] <ide> a[:o] = False <del> self.assertEqual(np.count_nonzero(a), builtins.sum(a.tolist())) <add> assert_equal(np.count_nonzero(a), builtins.sum(a.tolist())) <ide> <ide> <del>class TestMethods(TestCase): <add>class TestMethods(object): <ide> def test_compress(self): <ide> tgt = [[5, 6, 7, 8, 9]] <ide> arr = np.arange(10).reshape(2, 5) <ide> def test_prod(self): <ide> a = np.array(ba, ctype) <ide> a2 = np.array(ba2, ctype) <ide> if ctype in ['1', 'b']: <del> self.assertRaises(ArithmeticError, a.prod) <del> self.assertRaises(ArithmeticError, a2.prod, axis=1) <add> assert_raises(ArithmeticError, a.prod) <add> assert_raises(ArithmeticError, a2.prod, axis=1) <ide> else: <ide> assert_equal(a.prod(axis=0), 26400) <ide> assert_array_equal(a2.prod(axis=0), <ide> def test_squeeze(self): <ide> def test_transpose(self): <ide> a = np.array([[1, 2], [3, 4]]) <ide> assert_equal(a.transpose(), [[1, 3], [2, 4]]) <del> self.assertRaises(ValueError, lambda: a.transpose(0)) <del> self.assertRaises(ValueError, lambda: a.transpose(0, 0)) <del> self.assertRaises(ValueError, lambda: a.transpose(0, 1, 2)) <add> assert_raises(ValueError, lambda: a.transpose(0)) <add> assert_raises(ValueError, lambda: a.transpose(0, 0)) <add> assert_raises(ValueError, lambda: a.transpose(0, 1, 2)) <ide> <ide> def test_sort(self): <ide> # test ordering for floats and complex containing nans. It is only <ide> def test_partition(self): <ide> <ide> # sorted <ide> d = np.arange(49) <del> self.assertEqual(np.partition(d, 5, kind=k)[5], 5) <del> self.assertEqual(np.partition(d, 15, kind=k)[15], 15) <add> assert_equal(np.partition(d, 5, kind=k)[5], 5) <add> assert_equal(np.partition(d, 15, kind=k)[15], 15) <ide> assert_array_equal(d[np.argpartition(d, 5, kind=k)], <ide> np.partition(d, 5, kind=k)) <ide> assert_array_equal(d[np.argpartition(d, 15, kind=k)], <ide> np.partition(d, 15, kind=k)) <ide> <ide> # rsorted <ide> d = np.arange(47)[::-1] <del> self.assertEqual(np.partition(d, 6, kind=k)[6], 6) <del> self.assertEqual(np.partition(d, 16, kind=k)[16], 16) <add> assert_equal(np.partition(d, 6, kind=k)[6], 6) <add> assert_equal(np.partition(d, 16, kind=k)[16], 16) <ide> assert_array_equal(d[np.argpartition(d, 6, kind=k)], <ide> np.partition(d, 6, kind=k)) <ide> assert_array_equal(d[np.argpartition(d, 16, kind=k)], <ide> def test_partition(self): <ide> tgt = np.sort(np.arange(47) % 7) <ide> np.random.shuffle(d) <ide> for i in range(d.size): <del> self.assertEqual(np.partition(d, i, kind=k)[i], tgt[i]) <add> assert_equal(np.partition(d, i, kind=k)[i], tgt[i]) <ide> assert_array_equal(d[np.argpartition(d, 6, kind=k)], <ide> np.partition(d, 6, kind=k)) <ide> assert_array_equal(d[np.argpartition(d, 16, kind=k)], <ide> def test_partition(self): <ide> for s in (9, 16)] <ide> for dt, s in td: <ide> aae = assert_array_equal <del> at = self.assertTrue <add> at = assert_ <ide> <ide> d = np.arange(s, dtype=dt) <ide> np.random.shuffle(d) <ide> def test_partition(self): <ide> d0 = np.transpose(d1) <ide> for i in range(d.size): <ide> p = np.partition(d, i, kind=k) <del> self.assertEqual(p[i], i) <add> assert_equal(p[i], i) <ide> # all before are smaller <ide> assert_array_less(p[:i], p[i]) <ide> # all after are larger <ide> class MyArray(np.ndarray): <ide> <ide> b = np.arange(8).reshape((2, 2, 2)).view(MyArray) <ide> t = b.trace() <del> assert isinstance(t, MyArray) <add> assert_(isinstance(t, MyArray)) <ide> <ide> def test_put(self): <ide> icodes = np.typecodes['AllInteger'] <ide> def __array_ufunc__(self, ufunc, method, *inputs, **kw): <ide> a ** 2 <ide> <ide> <del>class TestTemporaryElide(TestCase): <add>class TestTemporaryElide(object): <ide> # elision is only triggered on relatively large arrays <ide> <ide> def test_extension_incref_elide(self): <ide> def test_elide_updateifcopy(self): <ide> assert_equal(a, 1) <ide> <ide> <del>class TestCAPI(TestCase): <add>class TestCAPI(object): <ide> def test_IsPythonScalar(self): <ide> from numpy.core.multiarray_tests import IsPythonScalar <ide> assert_(IsPythonScalar(b'foobar')) <ide> def test_IsPythonScalar(self): <ide> assert_(IsPythonScalar("a")) <ide> <ide> <del>class TestSubscripting(TestCase): <add>class TestSubscripting(object): <ide> def test_test_zero_rank(self): <ide> x = np.array([1, 2, 3]) <del> self.assertTrue(isinstance(x[0], np.int_)) <add> assert_(isinstance(x[0], np.int_)) <ide> if sys.version_info[0] < 3: <del> self.assertTrue(isinstance(x[0], int)) <del> self.assertTrue(type(x[0, ...]) is np.ndarray) <add> assert_(isinstance(x[0], int)) <add> assert_(type(x[0, ...]) is np.ndarray) <ide> <ide> <del>class TestPickling(TestCase): <add>class TestPickling(object): <ide> def test_roundtrip(self): <ide> import pickle <ide> carray = np.array([[2, 9], [7, 0], [3, 8]]) <ide> def test_subarray_int_shape(self): <ide> assert_equal(a, p) <ide> <ide> <del>class TestFancyIndexing(TestCase): <add>class TestFancyIndexing(object): <ide> def test_list(self): <ide> x = np.ones((1, 1)) <ide> x[:, [0]] = 2.0 <ide> def test_assign_mask2(self): <ide> assert_array_equal(x, np.array([[1, 10, 3, 4], [5, 6, 7, 8]])) <ide> <ide> <del>class TestStringCompare(TestCase): <add>class TestStringCompare(object): <ide> def test_string(self): <ide> g1 = np.array(["This", "is", "example"]) <ide> g2 = np.array(["This", "was", "example"]) <ide> def test_unicode(self): <ide> assert_array_equal(g1 > g2, [g1[i] > g2[i] for i in [0, 1, 2]]) <ide> <ide> <del>class TestArgmax(TestCase): <add>class TestArgmax(object): <ide> <ide> nan_arr = [ <ide> ([0, 1, 2, 3, np.nan], 4), <ide> def test_object_argmax_with_NULLs(self): <ide> assert_equal(a.argmax(), 1) <ide> <ide> <del>class TestArgmin(TestCase): <add>class TestArgmin(object): <ide> <ide> nan_arr = [ <ide> ([0, 1, 2, 3, np.nan], 4), <ide> def test_object_argmin_with_NULLs(self): <ide> assert_equal(a.argmin(), 1) <ide> <ide> <del>class TestMinMax(TestCase): <add>class TestMinMax(object): <ide> <ide> def test_scalar(self): <ide> assert_raises(np.AxisError, np.amax, 1, 1) <ide> def test_datetime(self): <ide> assert_equal(np.amax(a), a[0]) <ide> <ide> <del>class TestNewaxis(TestCase): <add>class TestNewaxis(object): <ide> def test_basic(self): <ide> sk = np.array([0, -0.1, 0.1]) <ide> res = 250*sk[:, np.newaxis] <ide> assert_almost_equal(res.ravel(), 250*sk) <ide> <ide> <del>class TestClip(TestCase): <add>class TestClip(object): <ide> def _check_range(self, x, cmin, cmax): <ide> assert_(np.all(x >= cmin)) <ide> assert_(np.all(x <= cmax)) <ide> def test_nan(self): <ide> assert_array_equal(result, expected) <ide> <ide> <del>class TestCompress(TestCase): <add>class TestCompress(object): <ide> def test_axis(self): <ide> tgt = [[5, 6, 7, 8, 9]] <ide> arr = np.arange(10).reshape(2, 5) <ide> def test_record_array(self): <ide> assert_(rec1['x'] == 5.0 and rec1['y'] == 4.0) <ide> <ide> <del>class TestLexsort(TestCase): <add>class TestLexsort(object): <ide> def test_basic(self): <ide> a = [1, 2, 1, 3, 1, 5] <ide> b = [0, 4, 5, 6, 2, 3] <ide> def test_invalid_axis(self): # gh-7528 <ide> x = np.linspace(0., 1., 42*3).reshape(42, 3) <ide> assert_raises(np.AxisError, np.lexsort, x, axis=2) <ide> <del>class TestIO(TestCase): <add>class TestIO(object): <ide> """Test tofile, fromfile, tobytes, and fromstring""" <ide> <del> def setUp(self): <add> def setup(self): <ide> shape = (2, 4, 3) <ide> rand = np.random.random <ide> self.x = rand(shape) + rand(shape).astype(np.complex)*1j <ide> def setUp(self): <ide> self.tempdir = tempfile.mkdtemp() <ide> self.filename = tempfile.mktemp(dir=self.tempdir) <ide> <del> def tearDown(self): <add> def teardown(self): <ide> shutil.rmtree(self.tempdir) <ide> <ide> def test_nofile(self): <ide> def fail(*args, **kwargs): <ide> with io.open(self.filename, 'rb', buffering=0) as f: <ide> f.seek = fail <ide> f.tell = fail <del> self.assertRaises(IOError, np.fromfile, f, dtype=self.dtype) <add> assert_raises(IOError, np.fromfile, f, dtype=self.dtype) <ide> <ide> def test_io_open_unbuffered_fromfile(self): <ide> # gh-6632 <ide> def test_empty(self): <ide> yield self.tst_basic, b'', np.array([]), {} <ide> <ide> <del>class TestFlat(TestCase): <del> def setUp(self): <add>class TestFlat(object): <add> def setup(self): <ide> a0 = np.arange(20.0) <ide> a = a0.reshape(4, 5) <ide> a0.shape = (4, 5) <ide> def test___array__(self): <ide> assert_(f.base is self.b0) <ide> <ide> <del>class TestResize(TestCase): <add>class TestResize(object): <ide> def test_basic(self): <ide> x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) <ide> if IS_PYPY: <ide> def test_basic(self): <ide> def test_check_reference(self): <ide> x = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) <ide> y = x <del> self.assertRaises(ValueError, x.resize, (5, 1)) <add> assert_raises(ValueError, x.resize, (5, 1)) <ide> del y # avoid pyflakes unused variable warning. <ide> <ide> def test_int_shape(self): <ide> def test_0d_shape(self): <ide> assert_equal(x.size, 1) <ide> <ide> def test_invalid_arguments(self): <del> self.assertRaises(TypeError, np.eye(3).resize, 'hi') <del> self.assertRaises(ValueError, np.eye(3).resize, -1) <del> self.assertRaises(TypeError, np.eye(3).resize, order=1) <del> self.assertRaises(TypeError, np.eye(3).resize, refcheck='hi') <add> assert_raises(TypeError, np.eye(3).resize, 'hi') <add> assert_raises(ValueError, np.eye(3).resize, -1) <add> assert_raises(TypeError, np.eye(3).resize, order=1) <add> assert_raises(TypeError, np.eye(3).resize, refcheck='hi') <ide> <ide> def test_freeform_shape(self): <ide> x = np.eye(3) <ide> def test_obj_obj(self): <ide> assert_array_equal(a['k'][:-5], 1) <ide> <ide> <del>class TestRecord(TestCase): <add>class TestRecord(object): <ide> def test_field_rename(self): <ide> dt = np.dtype([('f', float), ('i', int)]) <ide> dt.names = ['p', 'q'] <ide> def test_record_hash(self): <ide> b.flags.writeable = False <ide> c = np.array([(1, 2), (3, 4)], dtype='i1,i2') <ide> c.flags.writeable = False <del> self.assertTrue(hash(a[0]) == hash(a[1])) <del> self.assertTrue(hash(a[0]) == hash(b[0])) <del> self.assertTrue(hash(a[0]) != hash(b[1])) <del> self.assertTrue(hash(c[0]) == hash(a[0]) and c[0] == a[0]) <add> assert_(hash(a[0]) == hash(a[1])) <add> assert_(hash(a[0]) == hash(b[0])) <add> assert_(hash(a[0]) != hash(b[1])) <add> assert_(hash(c[0]) == hash(a[0]) and c[0] == a[0]) <ide> <ide> def test_record_no_hash(self): <ide> a = np.array([(1, 2), (1, 2)], dtype='i1,i2') <del> self.assertRaises(TypeError, hash, a[0]) <add> assert_raises(TypeError, hash, a[0]) <ide> <ide> def test_empty_structure_creation(self): <ide> # make sure these do not raise errors (gh-5631) <ide> def test_empty_structure_creation(self): <ide> np.array([(), (), (), (), ()], dtype={'names': [], 'formats': [], <ide> 'offsets': [], 'itemsize': 12}) <ide> <del>class TestView(TestCase): <add>class TestView(object): <ide> def test_basic(self): <ide> x = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], <ide> dtype=[('r', np.int8), ('g', np.int8), <ide> def _std(a, **args): <ide> return a.std(**args) <ide> <ide> <del>class TestStats(TestCase): <add>class TestStats(object): <ide> <ide> funcs = [_mean, _var, _std] <ide> <del> def setUp(self): <add> def setup(self): <ide> np.random.seed(range(3)) <ide> self.rmat = np.random.random((4, 5)) <ide> self.cmat = self.rmat + 1j * self.rmat <ide> def test_mean_values(self): <ide> def test_mean_float16(self): <ide> # This fail if the sum inside mean is done in float16 instead <ide> # of float32. <del> assert _mean(np.ones(100000, dtype='float16')) == 1 <add> assert_(_mean(np.ones(100000, dtype='float16')) == 1) <ide> <ide> def test_var_values(self): <ide> for mat in [self.rmat, self.cmat, self.omat]: <ide> def __array_finalize__(self, obj): <ide> res = dat.var(1) <ide> assert_(res.info == dat.info) <ide> <del>class TestVdot(TestCase): <add>class TestVdot(object): <ide> def test_basic(self): <ide> dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger'] <ide> dt_complex = np.typecodes['Complex'] <ide> def test_vdot_uncontiguous(self): <ide> np.vdot(a.flatten(), b.flatten())) <ide> <ide> <del>class TestDot(TestCase): <del> def setUp(self): <add>class TestDot(object): <add> def setup(self): <ide> np.random.seed(128) <ide> self.A = np.random.rand(4, 2) <ide> self.b1 = np.random.rand(2, 1) <ide> def assert_dot_close(A, X, desired): <ide> assert_dot_close(A_f_12, X_f_2, desired) <ide> <ide> <del>class MatmulCommon(): <add>class MatmulCommon(object): <ide> """Common tests for '@' operator and numpy.matmul. <ide> <ide> Do not derive from TestCase to avoid nose running it. <ide> def test_matrix_matrix_values(self): <ide> assert_equal(res, tgt12_21) <ide> <ide> <del>class TestMatmul(MatmulCommon, TestCase): <add>class TestMatmul(MatmulCommon): <ide> matmul = np.matmul <ide> <ide> def test_out_arg(self): <ide> def test_out_arg(self): <ide> <ide> <ide> if sys.version_info[:2] >= (3, 5): <del> class TestMatmulOperator(MatmulCommon, TestCase): <add> class TestMatmulOperator(MatmulCommon): <ide> import operator <ide> matmul = operator.matmul <ide> <ide> def test_matmul_inplace(): <ide> assert_raises(TypeError, exec_, "a @= b", globals(), locals()) <ide> <ide> <del>class TestInner(TestCase): <add>class TestInner(object): <ide> <ide> def test_inner_type_mismatch(self): <ide> c = 1. <ide> def test_3d_tensor(self): <ide> assert_equal(np.inner(b, a).transpose(2,3,0,1), desired) <ide> <ide> <del>class TestSummarization(TestCase): <add>class TestSummarization(object): <ide> def test_1d(self): <ide> A = np.arange(1001) <ide> strA = '[ 0 1 2 ..., 998 999 1000]' <ide> def test_2d(self): <ide> assert_(repr(A) == reprA) <ide> <ide> <del>class TestAlen(TestCase): <add>class TestAlen(object): <ide> def test_basic(self): <ide> m = np.array([1, 2, 3]) <del> self.assertEqual(np.alen(m), 3) <add> assert_equal(np.alen(m), 3) <ide> <ide> m = np.array([[1, 2, 3], [4, 5, 7]]) <del> self.assertEqual(np.alen(m), 2) <add> assert_equal(np.alen(m), 2) <ide> <ide> m = [1, 2, 3] <del> self.assertEqual(np.alen(m), 3) <add> assert_equal(np.alen(m), 3) <ide> <ide> m = [[1, 2, 3], [4, 5, 7]] <del> self.assertEqual(np.alen(m), 2) <add> assert_equal(np.alen(m), 2) <ide> <ide> def test_singleton(self): <del> self.assertEqual(np.alen(5), 1) <add> assert_equal(np.alen(5), 1) <ide> <ide> <del>class TestChoose(TestCase): <del> def setUp(self): <add>class TestChoose(object): <add> def setup(self): <ide> self.x = 2*np.ones((3,), dtype=int) <ide> self.y = 3*np.ones((3,), dtype=int) <ide> self.x2 = 2*np.ones((2, 3), dtype=int) <ide> def test_broadcast2(self): <ide> assert_equal(A, [[2, 2, 3], [2, 2, 3]]) <ide> <ide> <del>class TestRepeat(TestCase): <del> def setUp(self): <add>class TestRepeat(object): <add> def setup(self): <ide> self.m = np.array([1, 2, 3, 4, 5, 6]) <ide> self.m_rect = self.m.reshape((2, 3)) <ide> <ide> def test_broadcast2(self): <ide> NEIGH_MODE = {'zero': 0, 'one': 1, 'constant': 2, 'circular': 3, 'mirror': 4} <ide> <ide> <del>class TestNeighborhoodIter(TestCase): <add>class TestNeighborhoodIter(object): <ide> # Simple, 2d tests <ide> def _test_simple2d(self, dt): <ide> # Test zero and one padding for simple data type <ide> def _test_mirror(self, dt): <ide> r = np.array([[2, 1, 1, 2, 3], [1, 1, 2, 3, 4], [1, 2, 3, 4, 5], <ide> [2, 3, 4, 5, 5], [3, 4, 5, 5, 4]], dtype=dt) <ide> l = test_neighborhood_iterator(x, [-2, 2], x[1], NEIGH_MODE['mirror']) <del> self.assertTrue([i.dtype == dt for i in l]) <add> assert_([i.dtype == dt for i in l]) <ide> assert_array_equal(l, r) <ide> <ide> def test_mirror(self): <ide> def test_circular_object(self): <ide> self._test_circular(Decimal) <ide> <ide> # Test stacking neighborhood iterators <del>class TestStackedNeighborhoodIter(TestCase): <add>class TestStackedNeighborhoodIter(object): <ide> # Simple, 1d test: stacking 2 constant-padded neigh iterators <ide> def test_simple_const(self): <ide> dt = np.float64 <ide> def test_scalar_element_deletion(): <ide> assert_raises(ValueError, a[0].__delitem__, 'x') <ide> <ide> <del>class TestMemEventHook(TestCase): <add>class TestMemEventHook(object): <ide> def test_mem_seteventhook(self): <ide> # The actual tests are within the C code in <ide> # multiarray/multiarray_tests.c.src <ide> def test_mem_seteventhook(self): <ide> gc.collect() <ide> test_pydatamem_seteventhook_end() <ide> <del>class TestMapIter(TestCase): <add>class TestMapIter(object): <ide> def test_mapiter(self): <ide> # The actual tests are within the C code in <ide> # multiarray/multiarray_tests.c.src <ide> def test_mapiter(self): <ide> assert_equal(b, [100.1, 51., 6., 3., 4., 5.]) <ide> <ide> <del>class TestAsCArray(TestCase): <add>class TestAsCArray(object): <ide> def test_1darray(self): <ide> array = np.arange(24, dtype=np.double) <ide> from_c = test_as_c_array(array, 3) <ide> def test_3darray(self): <ide> assert_equal(array[1, 2, 3], from_c) <ide> <ide> <del>class TestConversion(TestCase): <add>class TestConversion(object): <ide> def test_array_scalar_relational_operation(self): <ide> # All integer <ide> for dt1 in np.typecodes['AllInteger']: <ide> def __bool__(self): <ide> assert_raises(Error, bool, self_containing) # previously stack overflow <ide> <ide> <del>class TestWhere(TestCase): <add>class TestWhere(object): <ide> def test_basic(self): <ide> dts = [np.bool, np.int16, np.int32, np.int64, np.double, np.complex128, <ide> np.longdouble, np.clongdouble] <ide> def test_largedim(self): <ide> <ide> if not IS_PYPY: <ide> # sys.getsizeof() is not valid on PyPy <del> class TestSizeOf(TestCase): <add> class TestSizeOf(object): <ide> <ide> def test_empty_array(self): <ide> x = np.array([]) <ide> def test_error(self): <ide> assert_raises(TypeError, d.__sizeof__, "a") <ide> <ide> <del>class TestHashing(TestCase): <add>class TestHashing(object): <ide> <ide> def test_arrays_not_hashable(self): <ide> x = np.ones(3) <ide> assert_raises(TypeError, hash, x) <ide> <ide> def test_collections_hashable(self): <ide> x = np.array([]) <del> self.assertFalse(isinstance(x, collections.Hashable)) <add> assert_(not isinstance(x, collections.Hashable)) <ide> <ide> <del>class TestArrayPriority(TestCase): <add>class TestArrayPriority(object): <ide> # This will go away when __array_priority__ is settled, meanwhile <ide> # it serves to check unintended changes. <ide> op = operator <ide> def test_subclass_other(self): <ide> assert_(isinstance(f(b, a), self.Other), msg) <ide> <ide> <del>class TestBytestringArrayNonzero(TestCase): <add>class TestBytestringArrayNonzero(object): <ide> <ide> def test_empty_bstring_array_is_falsey(self): <del> self.assertFalse(np.array([''], dtype=np.str)) <add> assert_(not np.array([''], dtype=np.str)) <ide> <ide> def test_whitespace_bstring_array_is_falsey(self): <ide> a = np.array(['spam'], dtype=np.str) <ide> a[0] = ' \0\0' <del> self.assertFalse(a) <add> assert_(not a) <ide> <ide> def test_all_null_bstring_array_is_falsey(self): <ide> a = np.array(['spam'], dtype=np.str) <ide> a[0] = '\0\0\0\0' <del> self.assertFalse(a) <add> assert_(not a) <ide> <ide> def test_null_inside_bstring_array_is_truthy(self): <ide> a = np.array(['spam'], dtype=np.str) <ide> a[0] = ' \0 \0' <del> self.assertTrue(a) <add> assert_(a) <ide> <ide> <del>class TestUnicodeArrayNonzero(TestCase): <add>class TestUnicodeArrayNonzero(object): <ide> <ide> def test_empty_ustring_array_is_falsey(self): <del> self.assertFalse(np.array([''], dtype=np.unicode)) <add> assert_(not np.array([''], dtype=np.unicode)) <ide> <ide> def test_whitespace_ustring_array_is_falsey(self): <ide> a = np.array(['eggs'], dtype=np.unicode) <ide> a[0] = ' \0\0' <del> self.assertFalse(a) <add> assert_(not a) <ide> <ide> def test_all_null_ustring_array_is_falsey(self): <ide> a = np.array(['eggs'], dtype=np.unicode) <ide> a[0] = '\0\0\0\0' <del> self.assertFalse(a) <add> assert_(not a) <ide> <ide> def test_null_inside_ustring_array_is_truthy(self): <ide> a = np.array(['eggs'], dtype=np.unicode) <ide> a[0] = ' \0 \0' <del> self.assertTrue(a) <add> assert_(a) <ide> <ide> <del>class TestCTypes(TestCase): <add>class TestCTypes(object): <ide> <ide> def test_ctypes_is_available(self): <ide> test_arr = np.array([[1, 2, 3], [4, 5, 6]]) <ide> <del> self.assertEqual(ctypes, test_arr.ctypes._ctypes) <add> assert_equal(ctypes, test_arr.ctypes._ctypes) <ide> assert_equal(tuple(test_arr.ctypes.shape), (2, 3)) <ide> <ide> def test_ctypes_is_not_available(self): <ide> def test_ctypes_is_not_available(self): <ide> try: <ide> test_arr = np.array([[1, 2, 3], [4, 5, 6]]) <ide> <del> self.assertIsInstance( <del> test_arr.ctypes._ctypes, _internal._missing_ctypes) <add> assert_(isinstance(test_arr.ctypes._ctypes, <add> _internal._missing_ctypes)) <ide> assert_equal(tuple(test_arr.ctypes.shape), (2, 3)) <ide> finally: <ide> _internal.ctypes = ctypes <ide><path>numpy/core/tests/test_numeric.py <ide> from numpy.core import umath <ide> from numpy.random import rand, randint, randn <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_raises, <add> run_module_suite, assert_, assert_equal, assert_raises, <ide> assert_raises_regex, assert_array_equal, assert_almost_equal, <ide> assert_array_almost_equal, dec, HAS_REFCOUNT, suppress_warnings <ide> ) <ide> <ide> <del>class TestResize(TestCase): <add>class TestResize(object): <ide> def test_copies(self): <ide> A = np.array([[1, 2], [3, 4]]) <ide> Ar1 = np.array([[1, 2, 3, 4], [1, 2, 3, 4]]) <ide> def test_reshape_from_zero(self): <ide> assert_equal(A.dtype, Ar.dtype) <ide> <ide> <del>class TestNonarrayArgs(TestCase): <add>class TestNonarrayArgs(object): <ide> # check that non-array arguments to functions wrap them in arrays <ide> def test_choose(self): <ide> choices = [[0, 1, 2], <ide> def test_var(self): <ide> assert_(w[0].category is RuntimeWarning) <ide> <ide> <del>class TestBoolScalar(TestCase): <add>class TestBoolScalar(object): <ide> def test_logical(self): <ide> f = np.False_ <ide> t = np.True_ <ide> s = "xyz" <del> self.assertTrue((t and s) is s) <del> self.assertTrue((f and s) is f) <add> assert_((t and s) is s) <add> assert_((f and s) is f) <ide> <ide> def test_bitwise_or(self): <ide> f = np.False_ <ide> t = np.True_ <del> self.assertTrue((t | t) is t) <del> self.assertTrue((f | t) is t) <del> self.assertTrue((t | f) is t) <del> self.assertTrue((f | f) is f) <add> assert_((t | t) is t) <add> assert_((f | t) is t) <add> assert_((t | f) is t) <add> assert_((f | f) is f) <ide> <ide> def test_bitwise_and(self): <ide> f = np.False_ <ide> t = np.True_ <del> self.assertTrue((t & t) is t) <del> self.assertTrue((f & t) is f) <del> self.assertTrue((t & f) is f) <del> self.assertTrue((f & f) is f) <add> assert_((t & t) is t) <add> assert_((f & t) is f) <add> assert_((t & f) is f) <add> assert_((f & f) is f) <ide> <ide> def test_bitwise_xor(self): <ide> f = np.False_ <ide> t = np.True_ <del> self.assertTrue((t ^ t) is f) <del> self.assertTrue((f ^ t) is t) <del> self.assertTrue((t ^ f) is t) <del> self.assertTrue((f ^ f) is f) <add> assert_((t ^ t) is f) <add> assert_((f ^ t) is t) <add> assert_((t ^ f) is t) <add> assert_((f ^ f) is f) <ide> <ide> <del>class TestBoolArray(TestCase): <del> def setUp(self): <add>class TestBoolArray(object): <add> def setup(self): <ide> # offset for simd tests <ide> self.t = np.array([True] * 41, dtype=np.bool)[1::] <ide> self.f = np.array([False] * 41, dtype=np.bool)[1::] <ide> def setUp(self): <ide> self.im[-2] = False <ide> <ide> def test_all_any(self): <del> self.assertTrue(self.t.all()) <del> self.assertTrue(self.t.any()) <del> self.assertFalse(self.f.all()) <del> self.assertFalse(self.f.any()) <del> self.assertTrue(self.nm.any()) <del> self.assertTrue(self.im.any()) <del> self.assertFalse(self.nm.all()) <del> self.assertFalse(self.im.all()) <add> assert_(self.t.all()) <add> assert_(self.t.any()) <add> assert_(not self.f.all()) <add> assert_(not self.f.any()) <add> assert_(self.nm.any()) <add> assert_(self.im.any()) <add> assert_(not self.nm.all()) <add> assert_(not self.im.all()) <ide> # check bad element in all positions <ide> for i in range(256 - 7): <ide> d = np.array([False] * 256, dtype=np.bool)[7::] <ide> d[i] = True <del> self.assertTrue(np.any(d)) <add> assert_(np.any(d)) <ide> e = np.array([True] * 256, dtype=np.bool)[7::] <ide> e[i] = False <del> self.assertFalse(np.all(e)) <add> assert_(not np.all(e)) <ide> assert_array_equal(e, ~d) <ide> # big array test for blocked libc loops <ide> for i in list(range(9, 6000, 507)) + [7764, 90021, -10]: <ide> d = np.array([False] * 100043, dtype=np.bool) <ide> d[i] = True <del> self.assertTrue(np.any(d), msg="%r" % i) <add> assert_(np.any(d), msg="%r" % i) <ide> e = np.array([True] * 100043, dtype=np.bool) <ide> e[i] = False <del> self.assertFalse(np.all(e), msg="%r" % i) <add> assert_(not np.all(e), msg="%r" % i) <ide> <ide> def test_logical_not_abs(self): <ide> assert_array_equal(~self.t, self.f) <ide> def test_logical_and_or_xor(self): <ide> assert_array_equal(self.im ^ False, self.im) <ide> <ide> <del>class TestBoolCmp(TestCase): <del> def setUp(self): <add>class TestBoolCmp(object): <add> def setup(self): <ide> self.f = np.ones(256, dtype=np.float32) <ide> self.ef = np.ones(self.f.size, dtype=np.bool) <ide> self.d = np.ones(128, dtype=np.float64) <ide> def test_double(self): <ide> assert_array_equal(np.signbit(self.signd[i:]), self.ed[i:]) <ide> <ide> <del>class TestSeterr(TestCase): <add>class TestSeterr(object): <ide> def test_default(self): <ide> err = np.geterr() <del> self.assertEqual(err, dict( <del> divide='warn', <del> invalid='warn', <del> over='warn', <del> under='ignore', <del> )) <add> assert_equal(err, <add> dict(divide='warn', <add> invalid='warn', <add> over='warn', <add> under='ignore') <add> ) <ide> <ide> def test_set(self): <ide> with np.errstate(): <ide> err = np.seterr() <ide> old = np.seterr(divide='print') <del> self.assertTrue(err == old) <add> assert_(err == old) <ide> new = np.seterr() <del> self.assertTrue(new['divide'] == 'print') <add> assert_(new['divide'] == 'print') <ide> np.seterr(over='raise') <del> self.assertTrue(np.geterr()['over'] == 'raise') <del> self.assertTrue(new['divide'] == 'print') <add> assert_(np.geterr()['over'] == 'raise') <add> assert_(new['divide'] == 'print') <ide> np.seterr(**old) <del> self.assertTrue(np.geterr() == old) <add> assert_(np.geterr() == old) <ide> <ide> @dec.skipif(platform.machine() == "armv5tel", "See gh-413.") <ide> def test_divide_err(self): <ide> def test_errobj(self): <ide> with np.errstate(divide='warn'): <ide> np.seterrobj([20000, 1, None]) <ide> np.array([1.]) / np.array([0.]) <del> self.assertEqual(len(w), 1) <add> assert_equal(len(w), 1) <ide> <ide> def log_err(*args): <ide> self.called += 1 <ide> def log_err(*args): <ide> with np.errstate(divide='ignore'): <ide> np.seterrobj([20000, 3, log_err]) <ide> np.array([1.]) / np.array([0.]) <del> self.assertEqual(self.called, 1) <add> assert_equal(self.called, 1) <ide> <ide> np.seterrobj(olderrobj) <ide> with np.errstate(divide='ignore'): <ide> np.divide(1., 0., extobj=[20000, 3, log_err]) <del> self.assertEqual(self.called, 2) <add> assert_equal(self.called, 2) <ide> finally: <ide> np.seterrobj(olderrobj) <ide> del self.called <ide> def test_errobj_noerrmask(self): <ide> np.seterrobj(olderrobj) <ide> <ide> <del>class TestFloatExceptions(TestCase): <add>class TestFloatExceptions(object): <ide> def assert_raises_fpe(self, fpeerr, flop, x, y): <ide> ftype = type(x) <ide> try: <ide> def test_warnings(self): <ide> warnings.simplefilter("always") <ide> with np.errstate(all="warn"): <ide> np.divide(1, 0.) <del> self.assertEqual(len(w), 1) <del> self.assertTrue("divide by zero" in str(w[0].message)) <add> assert_equal(len(w), 1) <add> assert_("divide by zero" in str(w[0].message)) <ide> np.array(1e300) * np.array(1e300) <del> self.assertEqual(len(w), 2) <del> self.assertTrue("overflow" in str(w[-1].message)) <add> assert_equal(len(w), 2) <add> assert_("overflow" in str(w[-1].message)) <ide> np.array(np.inf) - np.array(np.inf) <del> self.assertEqual(len(w), 3) <del> self.assertTrue("invalid value" in str(w[-1].message)) <add> assert_equal(len(w), 3) <add> assert_("invalid value" in str(w[-1].message)) <ide> np.array(1e-300) * np.array(1e-300) <del> self.assertEqual(len(w), 4) <del> self.assertTrue("underflow" in str(w[-1].message)) <add> assert_equal(len(w), 4) <add> assert_("underflow" in str(w[-1].message)) <ide> <ide> <del>class TestTypes(TestCase): <add>class TestTypes(object): <ide> def check_promotion_cases(self, promote_func): <ide> # tests that the scalars get coerced correctly. <ide> b = np.bool_(0) <ide> class NIterError(Exception): <ide> pass <ide> <ide> <del>class TestFromiter(TestCase): <add>class TestFromiter(object): <ide> def makegen(self): <ide> for x in range(24): <ide> yield x**2 <ide> def test_types(self): <ide> ai32 = np.fromiter(self.makegen(), np.int32) <ide> ai64 = np.fromiter(self.makegen(), np.int64) <ide> af = np.fromiter(self.makegen(), float) <del> self.assertTrue(ai32.dtype == np.dtype(np.int32)) <del> self.assertTrue(ai64.dtype == np.dtype(np.int64)) <del> self.assertTrue(af.dtype == np.dtype(float)) <add> assert_(ai32.dtype == np.dtype(np.int32)) <add> assert_(ai64.dtype == np.dtype(np.int64)) <add> assert_(af.dtype == np.dtype(float)) <ide> <ide> def test_lengths(self): <ide> expected = np.array(list(self.makegen())) <ide> a = np.fromiter(self.makegen(), int) <ide> a20 = np.fromiter(self.makegen(), int, 20) <del> self.assertTrue(len(a) == len(expected)) <del> self.assertTrue(len(a20) == 20) <del> self.assertRaises(ValueError, np.fromiter, <add> assert_(len(a) == len(expected)) <add> assert_(len(a20) == 20) <add> assert_raises(ValueError, np.fromiter, <ide> self.makegen(), int, len(expected) + 10) <ide> <ide> def test_values(self): <ide> expected = np.array(list(self.makegen())) <ide> a = np.fromiter(self.makegen(), int) <ide> a20 = np.fromiter(self.makegen(), int, 20) <del> self.assertTrue(np.alltrue(a == expected, axis=0)) <del> self.assertTrue(np.alltrue(a20 == expected[:20], axis=0)) <add> assert_(np.alltrue(a == expected, axis=0)) <add> assert_(np.alltrue(a20 == expected[:20], axis=0)) <ide> <ide> def load_data(self, n, eindex): <ide> # Utility method for the issue 2592 tests. <ide> def load_data(self, n, eindex): <ide> def test_2592(self): <ide> # Test iteration exceptions are correctly raised. <ide> count, eindex = 10, 5 <del> self.assertRaises(NIterError, np.fromiter, <add> assert_raises(NIterError, np.fromiter, <ide> self.load_data(count, eindex), dtype=int, count=count) <ide> <ide> def test_2592_edge(self): <ide> # Test iter. exceptions, edge case (exception at end of iterator). <ide> count = 10 <ide> eindex = count-1 <del> self.assertRaises(NIterError, np.fromiter, <add> assert_raises(NIterError, np.fromiter, <ide> self.load_data(count, eindex), dtype=int, count=count) <ide> <ide> <del>class TestNonzero(TestCase): <add>class TestNonzero(object): <ide> def test_nonzero_trivial(self): <ide> assert_equal(np.count_nonzero(np.array([])), 0) <ide> assert_equal(np.count_nonzero(np.array([], dtype='?')), 0) <ide> def test_array_method(self): <ide> assert_equal(m.nonzero(), tgt) <ide> <ide> <del>class TestIndex(TestCase): <add>class TestIndex(object): <ide> def test_boolean(self): <ide> a = rand(3, 5, 8) <ide> V = rand(5, 8) <ide> def test_boolean_edgecase(self): <ide> assert_equal(c.dtype, np.dtype('int32')) <ide> <ide> <del>class TestBinaryRepr(TestCase): <add>class TestBinaryRepr(object): <ide> def test_zero(self): <ide> assert_equal(np.binary_repr(0), '0') <ide> <ide> def test_neg_width_boundaries(self): <ide> assert_equal(np.binary_repr(num, width=width), exp) <ide> <ide> <del>class TestBaseRepr(TestCase): <add>class TestBaseRepr(object): <ide> def test_base3(self): <ide> assert_equal(np.base_repr(3**5, 3), '100000') <ide> <ide> def test_negative(self): <ide> assert_equal(np.base_repr(-12, 4), '-30') <ide> <ide> def test_base_range(self): <del> with self.assertRaises(ValueError): <add> with assert_raises(ValueError): <ide> np.base_repr(1, 1) <del> with self.assertRaises(ValueError): <add> with assert_raises(ValueError): <ide> np.base_repr(1, 37) <ide> <ide> <del>class TestArrayComparisons(TestCase): <add>class TestArrayComparisons(object): <ide> def test_array_equal(self): <ide> res = np.array_equal(np.array([1, 2]), np.array([1, 2])) <ide> assert_(res) <ide> def assert_array_strict_equal(x, y): <ide> assert_(x.dtype.isnative == y.dtype.isnative) <ide> <ide> <del>class TestClip(TestCase): <del> def setUp(self): <add>class TestClip(object): <add> def setup(self): <ide> self.nr = 5 <ide> self.nc = 3 <ide> <ide> def test_clip_func_takes_out(self): <ide> a2 = np.clip(a, m, M, out=a) <ide> self.clip(a, m, M, ac) <ide> assert_array_strict_equal(a2, ac) <del> self.assertTrue(a2 is a) <add> assert_(a2 is a) <ide> <ide> def test_clip_nan(self): <ide> d = np.arange(7.) <ide> class TestAllclose(object): <ide> rtol = 1e-5 <ide> atol = 1e-8 <ide> <del> def setUp(self): <add> def setup(self): <ide> self.olderr = np.seterr(invalid='ignore') <ide> <del> def tearDown(self): <add> def teardown(self): <ide> np.seterr(**self.olderr) <ide> <ide> def tst_allclose(self, x, y): <ide> def test_non_finite_scalar(self): <ide> assert_(type(np.isclose(0, np.inf)) is bool) <ide> <ide> <del>class TestStdVar(TestCase): <del> def setUp(self): <add>class TestStdVar(object): <add> def setup(self): <ide> self.A = np.array([1, -1, 1, -1]) <ide> self.real_var = 1 <ide> <ide> def test_out_scalar(self): <ide> assert_array_equal(r, out) <ide> <ide> <del>class TestStdVarComplex(TestCase): <add>class TestStdVarComplex(object): <ide> def test_basic(self): <ide> A = np.array([1, 1.j, -1, -1.j]) <ide> real_var = 1 <ide> def test_scalars(self): <ide> assert_equal(np.std(1j), 0) <ide> <ide> <del>class TestCreationFuncs(TestCase): <add>class TestCreationFuncs(object): <ide> # Test ones, zeros, empty and full. <ide> <del> def setUp(self): <add> def setup(self): <ide> dtypes = {np.dtype(tp) for tp in itertools.chain(*np.sctypes.values())} <ide> # void, bytes, str <ide> variable_sized = {tp for tp in dtypes if tp.str.endswith('0')} <ide> def test_for_reference_leak(self): <ide> assert_(sys.getrefcount(dim) == beg) <ide> <ide> <del>class TestLikeFuncs(TestCase): <add>class TestLikeFuncs(object): <ide> '''Test ones_like, zeros_like, empty_like and full_like''' <ide> <del> def setUp(self): <add> def setup(self): <ide> self.data = [ <ide> # Array scalars <ide> (np.array(3.), None), <ide> def test_filled_like(self): <ide> self.check_like_function(np.full_like, np.inf, True) <ide> <ide> <del>class TestCorrelate(TestCase): <add>class TestCorrelate(object): <ide> def _setup(self, dt): <ide> self.x = np.array([1, 2, 3, 4, 5], dtype=dt) <ide> self.xs = np.arange(1, 20)[::3] <ide> def test_complex(self): <ide> assert_array_almost_equal(z, r_z) <ide> <ide> <del>class TestConvolve(TestCase): <add>class TestConvolve(object): <ide> def test_object(self): <ide> d = [1.] * 100 <ide> k = [1.] * 3 <ide> def test_set_string_function(self): <ide> assert_equal(str(a), "[1]") <ide> <ide> <del>class TestRoll(TestCase): <add>class TestRoll(object): <ide> def test_roll1d(self): <ide> x = np.arange(10) <ide> xr = np.roll(x, 2) <ide> def test_roll_empty(self): <ide> assert_equal(np.roll(x, 1), np.array([])) <ide> <ide> <del>class TestRollaxis(TestCase): <add>class TestRollaxis(object): <ide> <ide> # expected shape indexed by (axis, start) for array of <ide> # shape (1, 2, 3, 4) <ide> def test_results(self): <ide> assert_(not res.flags['OWNDATA']) <ide> <ide> <del>class TestMoveaxis(TestCase): <add>class TestMoveaxis(object): <ide> def test_move_to_end(self): <ide> x = np.random.randn(5, 6, 7) <ide> for source, expected in [(0, (6, 7, 5)), <ide> def test_array_likes(self): <ide> assert_(isinstance(result, np.ndarray)) <ide> <ide> <del>class TestCross(TestCase): <add>class TestCross(object): <ide> def test_2x2(self): <ide> u = [1, 2] <ide> v = [3, 4] <ide> class ArraySubclass(np.ndarray): <ide> yield self.set_and_check_flag, flag, None, a <ide> <ide> <del>class TestBroadcast(TestCase): <add>class TestBroadcast(object): <ide> def test_broadcast_in_args(self): <ide> # gh-5881 <ide> arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)), <ide> def test_number_of_arguments(self): <ide> assert_equal(mit.numiter, j) <ide> <ide> <del>class TestKeepdims(TestCase): <add>class TestKeepdims(object): <ide> <ide> class sub_array(np.ndarray): <ide> def sum(self, axis=None, dtype=None, out=None): <ide> def test_raise(self): <ide> assert_raises(TypeError, np.sum, x, keepdims=True) <ide> <ide> <del>class TestTensordot(TestCase): <add>class TestTensordot(object): <ide> <ide> def test_zero_dimension(self): <ide> # Test resolution to issue #5663 <ide><path>numpy/core/tests/test_numerictypes.py <ide> <ide> import numpy as np <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal <add> run_module_suite, assert_, assert_equal, assert_raises <ide> ) <ide> <ide> # This is the structure of the table used for plain objects: <ide> def normalize_descr(descr): <ide> # Creation tests <ide> ############################################################ <ide> <del>class create_zeros(object): <add>class CreateZeros(object): <ide> """Check the creation of heterogeneous arrays zero-valued""" <ide> <ide> def test_zeros0D(self): <ide> """Check creation of 0-dimensional objects""" <ide> h = np.zeros((), dtype=self._descr) <del> self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) <del> self.assertTrue(h.dtype.fields['x'][0].name[:4] == 'void') <del> self.assertTrue(h.dtype.fields['x'][0].char == 'V') <del> self.assertTrue(h.dtype.fields['x'][0].type == np.void) <add> assert_(normalize_descr(self._descr) == h.dtype.descr) <add> assert_(h.dtype.fields['x'][0].name[:4] == 'void') <add> assert_(h.dtype.fields['x'][0].char == 'V') <add> assert_(h.dtype.fields['x'][0].type == np.void) <ide> # A small check that data is ok <ide> assert_equal(h['z'], np.zeros((), dtype='u1')) <ide> <ide> def test_zerosSD(self): <ide> """Check creation of single-dimensional objects""" <ide> h = np.zeros((2,), dtype=self._descr) <del> self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) <del> self.assertTrue(h.dtype['y'].name[:4] == 'void') <del> self.assertTrue(h.dtype['y'].char == 'V') <del> self.assertTrue(h.dtype['y'].type == np.void) <add> assert_(normalize_descr(self._descr) == h.dtype.descr) <add> assert_(h.dtype['y'].name[:4] == 'void') <add> assert_(h.dtype['y'].char == 'V') <add> assert_(h.dtype['y'].type == np.void) <ide> # A small check that data is ok <ide> assert_equal(h['z'], np.zeros((2,), dtype='u1')) <ide> <ide> def test_zerosMD(self): <ide> """Check creation of multi-dimensional objects""" <ide> h = np.zeros((2, 3), dtype=self._descr) <del> self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) <del> self.assertTrue(h.dtype['z'].name == 'uint8') <del> self.assertTrue(h.dtype['z'].char == 'B') <del> self.assertTrue(h.dtype['z'].type == np.uint8) <add> assert_(normalize_descr(self._descr) == h.dtype.descr) <add> assert_(h.dtype['z'].name == 'uint8') <add> assert_(h.dtype['z'].char == 'B') <add> assert_(h.dtype['z'].type == np.uint8) <ide> # A small check that data is ok <ide> assert_equal(h['z'], np.zeros((2, 3), dtype='u1')) <ide> <ide> <del>class test_create_zeros_plain(create_zeros, TestCase): <add>class TestCreateZerosPlain(CreateZeros): <ide> """Check the creation of heterogeneous arrays zero-valued (plain)""" <ide> _descr = Pdescr <ide> <del>class test_create_zeros_nested(create_zeros, TestCase): <add>class TestCreateZerosNested(CreateZeros): <ide> """Check the creation of heterogeneous arrays zero-valued (nested)""" <ide> _descr = Ndescr <ide> <ide> <del>class create_values(object): <add>class CreateValues(object): <ide> """Check the creation of heterogeneous arrays with values""" <ide> <ide> def test_tuple(self): <ide> """Check creation from tuples""" <ide> h = np.array(self._buffer, dtype=self._descr) <del> self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) <add> assert_(normalize_descr(self._descr) == h.dtype.descr) <ide> if self.multiple_rows: <del> self.assertTrue(h.shape == (2,)) <add> assert_(h.shape == (2,)) <ide> else: <del> self.assertTrue(h.shape == ()) <add> assert_(h.shape == ()) <ide> <ide> def test_list_of_tuple(self): <ide> """Check creation from list of tuples""" <ide> h = np.array([self._buffer], dtype=self._descr) <del> self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) <add> assert_(normalize_descr(self._descr) == h.dtype.descr) <ide> if self.multiple_rows: <del> self.assertTrue(h.shape == (1, 2)) <add> assert_(h.shape == (1, 2)) <ide> else: <del> self.assertTrue(h.shape == (1,)) <add> assert_(h.shape == (1,)) <ide> <ide> def test_list_of_list_of_tuple(self): <ide> """Check creation from list of list of tuples""" <ide> h = np.array([[self._buffer]], dtype=self._descr) <del> self.assertTrue(normalize_descr(self._descr) == h.dtype.descr) <add> assert_(normalize_descr(self._descr) == h.dtype.descr) <ide> if self.multiple_rows: <del> self.assertTrue(h.shape == (1, 1, 2)) <add> assert_(h.shape == (1, 1, 2)) <ide> else: <del> self.assertTrue(h.shape == (1, 1)) <add> assert_(h.shape == (1, 1)) <ide> <ide> <del>class test_create_values_plain_single(create_values, TestCase): <add>class TestCreateValuesPlainSingle(CreateValues): <ide> """Check the creation of heterogeneous arrays (plain, single row)""" <ide> _descr = Pdescr <ide> multiple_rows = 0 <ide> _buffer = PbufferT[0] <ide> <del>class test_create_values_plain_multiple(create_values, TestCase): <add>class TestCreateValuesPlainMultiple(CreateValues): <ide> """Check the creation of heterogeneous arrays (plain, multiple rows)""" <ide> _descr = Pdescr <ide> multiple_rows = 1 <ide> _buffer = PbufferT <ide> <del>class test_create_values_nested_single(create_values, TestCase): <add>class TestCreateValuesNestedSingle(CreateValues): <ide> """Check the creation of heterogeneous arrays (nested, single row)""" <ide> _descr = Ndescr <ide> multiple_rows = 0 <ide> _buffer = NbufferT[0] <ide> <del>class test_create_values_nested_multiple(create_values, TestCase): <add>class TestCreateValuesNestedMultiple(CreateValues): <ide> """Check the creation of heterogeneous arrays (nested, multiple rows)""" <ide> _descr = Ndescr <ide> multiple_rows = 1 <ide> class test_create_values_nested_multiple(create_values, TestCase): <ide> # Reading tests <ide> ############################################################ <ide> <del>class read_values_plain(object): <add>class ReadValuesPlain(object): <ide> """Check the reading of values in heterogeneous arrays (plain)""" <ide> <ide> def test_access_fields(self): <ide> h = np.array(self._buffer, dtype=self._descr) <ide> if not self.multiple_rows: <del> self.assertTrue(h.shape == ()) <add> assert_(h.shape == ()) <ide> assert_equal(h['x'], np.array(self._buffer[0], dtype='i4')) <ide> assert_equal(h['y'], np.array(self._buffer[1], dtype='f8')) <ide> assert_equal(h['z'], np.array(self._buffer[2], dtype='u1')) <ide> else: <del> self.assertTrue(len(h) == 2) <add> assert_(len(h) == 2) <ide> assert_equal(h['x'], np.array([self._buffer[0][0], <ide> self._buffer[1][0]], dtype='i4')) <ide> assert_equal(h['y'], np.array([self._buffer[0][1], <ide> def test_access_fields(self): <ide> self._buffer[1][2]], dtype='u1')) <ide> <ide> <del>class test_read_values_plain_single(read_values_plain, TestCase): <add>class TestReadValuesPlainSingle(ReadValuesPlain): <ide> """Check the creation of heterogeneous arrays (plain, single row)""" <ide> _descr = Pdescr <ide> multiple_rows = 0 <ide> _buffer = PbufferT[0] <ide> <del>class test_read_values_plain_multiple(read_values_plain, TestCase): <add>class TestReadValuesPlainMultiple(ReadValuesPlain): <ide> """Check the values of heterogeneous arrays (plain, multiple rows)""" <ide> _descr = Pdescr <ide> multiple_rows = 1 <ide> _buffer = PbufferT <ide> <del>class read_values_nested(object): <add>class ReadValuesNested(object): <ide> """Check the reading of values in heterogeneous arrays (nested)""" <ide> <ide> def test_access_top_fields(self): <ide> """Check reading the top fields of a nested array""" <ide> h = np.array(self._buffer, dtype=self._descr) <ide> if not self.multiple_rows: <del> self.assertTrue(h.shape == ()) <add> assert_(h.shape == ()) <ide> assert_equal(h['x'], np.array(self._buffer[0], dtype='i4')) <ide> assert_equal(h['y'], np.array(self._buffer[4], dtype='f8')) <ide> assert_equal(h['z'], np.array(self._buffer[5], dtype='u1')) <ide> else: <del> self.assertTrue(len(h) == 2) <add> assert_(len(h) == 2) <ide> assert_equal(h['x'], np.array([self._buffer[0][0], <ide> self._buffer[1][0]], dtype='i4')) <ide> assert_equal(h['y'], np.array([self._buffer[0][4], <ide> def test_nested2_acessors(self): <ide> def test_nested1_descriptor(self): <ide> """Check access nested descriptors of a nested array (1st level)""" <ide> h = np.array(self._buffer, dtype=self._descr) <del> self.assertTrue(h.dtype['Info']['value'].name == 'complex128') <del> self.assertTrue(h.dtype['Info']['y2'].name == 'float64') <add> assert_(h.dtype['Info']['value'].name == 'complex128') <add> assert_(h.dtype['Info']['y2'].name == 'float64') <ide> if sys.version_info[0] >= 3: <del> self.assertTrue(h.dtype['info']['Name'].name == 'str256') <add> assert_(h.dtype['info']['Name'].name == 'str256') <ide> else: <del> self.assertTrue(h.dtype['info']['Name'].name == 'unicode256') <del> self.assertTrue(h.dtype['info']['Value'].name == 'complex128') <add> assert_(h.dtype['info']['Name'].name == 'unicode256') <add> assert_(h.dtype['info']['Value'].name == 'complex128') <ide> <ide> def test_nested2_descriptor(self): <ide> """Check access nested descriptors of a nested array (2nd level)""" <ide> h = np.array(self._buffer, dtype=self._descr) <del> self.assertTrue(h.dtype['Info']['Info2']['value'].name == 'void256') <del> self.assertTrue(h.dtype['Info']['Info2']['z3'].name == 'void64') <add> assert_(h.dtype['Info']['Info2']['value'].name == 'void256') <add> assert_(h.dtype['Info']['Info2']['z3'].name == 'void64') <ide> <ide> <del>class test_read_values_nested_single(read_values_nested, TestCase): <add>class TestReadValuesNestedSingle(ReadValuesNested): <ide> """Check the values of heterogeneous arrays (nested, single row)""" <ide> _descr = Ndescr <ide> multiple_rows = False <ide> _buffer = NbufferT[0] <ide> <del>class test_read_values_nested_multiple(read_values_nested, TestCase): <add>class TestReadValuesNestedMultiple(ReadValuesNested): <ide> """Check the values of heterogeneous arrays (nested, multiple rows)""" <ide> _descr = Ndescr <ide> multiple_rows = True <ide> _buffer = NbufferT <ide> <del>class TestEmptyField(TestCase): <add>class TestEmptyField(object): <ide> def test_assign(self): <ide> a = np.arange(10, dtype=np.float32) <ide> a.dtype = [("int", "<0i4"), ("float", "<2f4")] <ide> assert_(a['int'].shape == (5, 0)) <ide> assert_(a['float'].shape == (5, 2)) <ide> <del>class TestCommonType(TestCase): <add>class TestCommonType(object): <ide> def test_scalar_loses1(self): <ide> res = np.find_common_type(['f4', 'f4', 'i2'], ['f8']) <ide> assert_(res == 'f4') <ide> def test_scalar_wins3(self): # doesn't go up to 'f16' on purpose <ide> res = np.find_common_type(['u8', 'i8', 'i8'], ['f8']) <ide> assert_(res == 'f8') <ide> <del>class TestMultipleFields(TestCase): <del> def setUp(self): <add>class TestMultipleFields(object): <add> def setup(self): <ide> self.ary = np.array([(1, 2, 3, 4), (5, 6, 7, 8)], dtype='i4,f4,i2,c8') <ide> <ide> def _bad_call(self): <ide> return self.ary['f0', 'f1'] <ide> <ide> def test_no_tuple(self): <del> self.assertRaises(IndexError, self._bad_call) <add> assert_raises(IndexError, self._bad_call) <ide> <ide> def test_return(self): <ide> res = self.ary[['f0', 'f2']].tolist() <ide><path>numpy/core/tests/test_records.py <ide> <ide> import numpy as np <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_array_equal, <add> run_module_suite, assert_, assert_equal, assert_array_equal, <ide> assert_array_almost_equal, assert_raises, assert_warns <ide> ) <ide> <ide> <del>class TestFromrecords(TestCase): <add>class TestFromrecords(object): <ide> def test_fromrecords(self): <ide> r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]], <ide> names='col1,col2,col3') <ide> def test_zero_width_strings(self): <ide> assert_equal(rec['f1'], [b'', b'', b'']) <ide> <ide> <del>class TestRecord(TestCase): <del> def setUp(self): <add>class TestRecord(object): <add> def setup(self): <ide> self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)], <ide> dtype=[("col1", "<i4"), <ide> ("col2", "<i4"), <ide> def test_invalid_assignment(self): <ide> def assign_invalid_column(x): <ide> x[0].col5 = 1 <ide> <del> self.assertRaises(AttributeError, assign_invalid_column, a) <add> assert_raises(AttributeError, assign_invalid_column, a) <ide> <ide> def test_nonwriteable_setfield(self): <ide> # gh-8171 <ide><path>numpy/core/tests/test_regression.py <ide> <ide> import numpy as np <ide> from numpy.testing import ( <del> run_module_suite, TestCase, assert_, assert_equal, IS_PYPY, <add> run_module_suite, assert_, assert_equal, IS_PYPY, <ide> assert_almost_equal, assert_array_equal, assert_array_almost_equal, <ide> assert_raises, assert_warns, dec, suppress_warnings, <ide> _assert_valid_refcount, HAS_REFCOUNT, <ide> <ide> rlevel = 1 <ide> <del>class TestRegression(TestCase): <add>class TestRegression(object): <ide> def test_invalid_round(self, level=rlevel): <ide> # Ticket #3 <ide> v = 4.7599999999999998 <ide> def test_noncontiguous_fill(self, level=rlevel): <ide> def rs(): <ide> b.shape = (10,) <ide> <del> self.assertRaises(AttributeError, rs) <add> assert_raises(AttributeError, rs) <ide> <ide> def test_bool(self, level=rlevel): <ide> # Ticket #60 <ide> def test_scalar_compare(self, level=rlevel): <ide> # https://github.com/numpy/numpy/issues/565 <ide> a = np.array(['test', 'auto']) <ide> assert_array_equal(a == 'auto', np.array([False, True])) <del> self.assertTrue(a[1] == 'auto') <del> self.assertTrue(a[0] != 'auto') <add> assert_(a[1] == 'auto') <add> assert_(a[0] != 'auto') <ide> b = np.linspace(0, 10, 11) <ide> # This should return true for now, but will eventually raise an error: <ide> with suppress_warnings() as sup: <ide> sup.filter(FutureWarning) <del> self.assertTrue(b != 'auto') <del> self.assertTrue(b[0] != 'auto') <add> assert_(b != 'auto') <add> assert_(b[0] != 'auto') <ide> <ide> def test_unicode_swapping(self, level=rlevel): <ide> # Ticket #79 <ide> def test_object_array_fill(self, level=rlevel): <ide> <ide> def test_mem_dtype_align(self, level=rlevel): <ide> # Ticket #93 <del> self.assertRaises(TypeError, np.dtype, <add> assert_raises(TypeError, np.dtype, <ide> {'names':['a'], 'formats':['foo']}, align=1) <ide> <ide> @dec.knownfailureif((sys.version_info[0] >= 3) or <ide> def test_intp(self, level=rlevel): <ide> # Ticket #99 <ide> i_width = np.int_(0).nbytes*2 - 1 <ide> np.intp('0x' + 'f'*i_width, 16) <del> self.assertRaises(OverflowError, np.intp, '0x' + 'f'*(i_width+1), 16) <del> self.assertRaises(ValueError, np.intp, '0x1', 32) <add> assert_raises(OverflowError, np.intp, '0x' + 'f'*(i_width+1), 16) <add> assert_raises(ValueError, np.intp, '0x1', 32) <ide> assert_equal(255, np.intp('0xFF', 16)) <ide> assert_equal(1024, np.intp(1024)) <ide> <ide> def test_hstack_invalid_dims(self, level=rlevel): <ide> # Ticket #128 <ide> x = np.arange(9).reshape((3, 3)) <ide> y = np.array([0, 0, 0]) <del> self.assertRaises(ValueError, np.hstack, (x, y)) <add> assert_raises(ValueError, np.hstack, (x, y)) <ide> <ide> def test_squeeze_type(self, level=rlevel): <ide> # Ticket #133 <ide> def bfa(): <ide> def bfb(): <ide> x[:] = np.arange(3, dtype=float) <ide> <del> self.assertRaises(ValueError, bfa) <del> self.assertRaises(ValueError, bfb) <add> assert_raises(ValueError, bfa) <add> assert_raises(ValueError, bfb) <ide> <ide> def test_nonarray_assignment(self): <ide> # See also Issue gh-2870, test for non-array assignment <ide> def test_mem_array_creation_invalid_specification(self, level=rlevel): <ide> # Ticket #196 <ide> dt = np.dtype([('x', int), ('y', np.object_)]) <ide> # Wrong way <del> self.assertRaises(ValueError, np.array, [1, 'object'], dt) <add> assert_raises(ValueError, np.array, [1, 'object'], dt) <ide> # Correct way <ide> np.array([(1, 'object')], dt) <ide> <ide> def test_zero_sized_array_indexing(self, level=rlevel): <ide> def index_tmp(): <ide> tmp[np.array(10)] <ide> <del> self.assertRaises(IndexError, index_tmp) <add> assert_raises(IndexError, index_tmp) <ide> <ide> def test_chararray_rstrip(self, level=rlevel): <ide> # Ticket #222 <ide> def test_swap_real(self, level=rlevel): <ide> <ide> def test_object_array_from_list(self, level=rlevel): <ide> # Ticket #270 <del> self.assertEqual(np.array([1, 'A', None]).shape, (3,)) <add> assert_(np.array([1, 'A', None]).shape == (3,)) <ide> <ide> def test_multiple_assign(self, level=rlevel): <ide> # Ticket #273 <ide> def test_numeric_carray_compare(self, level=rlevel): <ide> <ide> def test_string_array_size(self, level=rlevel): <ide> # Ticket #342 <del> self.assertRaises(ValueError, <add> assert_raises(ValueError, <ide> np.array, [['X'], ['X', 'X', 'X']], '|S1') <ide> <ide> def test_dtype_repr(self, level=rlevel): <ide> def test_noncommutative_reduce_accumulate(self, level=rlevel): <ide> <ide> def test_convolve_empty(self, level=rlevel): <ide> # Convolve should raise an error for empty input array. <del> self.assertRaises(ValueError, np.convolve, [], [1]) <del> self.assertRaises(ValueError, np.convolve, [1], []) <add> assert_raises(ValueError, np.convolve, [], [1]) <add> assert_raises(ValueError, np.convolve, [1], []) <ide> <ide> def test_multidim_byteswap(self, level=rlevel): <ide> # Ticket #449 <ide> def test_mem_deallocation_leak(self, level=rlevel): <ide> <ide> def test_mem_on_invalid_dtype(self): <ide> "Ticket #583" <del> self.assertRaises(ValueError, np.fromiter, [['12', ''], ['13', '']], str) <add> assert_raises(ValueError, np.fromiter, [['12', ''], ['13', '']], str) <ide> <ide> def test_dot_negative_stride(self, level=rlevel): <ide> # Ticket #588 <ide> def rs(): <ide> y = np.zeros([484, 286]) <ide> x |= y <ide> <del> self.assertRaises(TypeError, rs) <add> assert_raises(TypeError, rs) <ide> <ide> def test_unicode_scalar(self, level=rlevel): <ide> # Ticket #600 <ide> def test_bool_flat_indexing_invalid_nr_elements(self, level=rlevel): <ide> def ia(x, s, v): <ide> x[(s > 0)] = v <ide> <del> self.assertRaises(IndexError, ia, x, s, np.zeros(9, dtype=float)) <del> self.assertRaises(IndexError, ia, x, s, np.zeros(11, dtype=float)) <add> assert_raises(IndexError, ia, x, s, np.zeros(9, dtype=float)) <add> assert_raises(IndexError, ia, x, s, np.zeros(11, dtype=float)) <ide> <ide> # Old special case (different code path): <del> self.assertRaises(ValueError, ia, x.flat, s, np.zeros(9, dtype=float)) <del> self.assertRaises(ValueError, ia, x.flat, s, np.zeros(11, dtype=float)) <add> assert_raises(ValueError, ia, x.flat, s, np.zeros(9, dtype=float)) <add> assert_raises(ValueError, ia, x.flat, s, np.zeros(11, dtype=float)) <ide> <ide> def test_mem_scalar_indexing(self, level=rlevel): <ide> # Ticket #603 <ide> def __del__(self): <ide> <ide> def test_mem_fromiter_invalid_dtype_string(self, level=rlevel): <ide> x = [1, 2, 3] <del> self.assertRaises(ValueError, <add> assert_raises(ValueError, <ide> np.fromiter, [xi for xi in x], dtype='S') <ide> <ide> def test_reduce_big_object_array(self, level=rlevel): <ide> def test_for_object_scalar_creation(self, level=rlevel): <ide> def test_array_resize_method_system_error(self): <ide> # Ticket #840 - order should be an invalid keyword. <ide> x = np.array([[0, 1], [2, 3]]) <del> self.assertRaises(TypeError, x.resize, (2, 2), order='C') <add> assert_raises(TypeError, x.resize, (2, 2), order='C') <ide> <ide> def test_for_zero_length_in_choose(self, level=rlevel): <ide> "Ticket #882" <ide> a = np.array(1) <del> self.assertRaises(ValueError, lambda x: x.choose([]), a) <add> assert_raises(ValueError, lambda x: x.choose([]), a) <ide> <ide> def test_array_ndmin_overflow(self): <ide> "Ticket #947." <del> self.assertRaises(ValueError, lambda: np.array([1], ndmin=33)) <add> assert_raises(ValueError, lambda: np.array([1], ndmin=33)) <ide> <ide> def test_void_scalar_with_titles(self, level=rlevel): <ide> # No ticket <ide> def test_huge_arange(self): <ide> good = 'Maximum allowed size exceeded' <ide> try: <ide> np.arange(sz) <del> self.assertTrue(np.size == sz) <add> assert_(np.size == sz) <ide> except ValueError as e: <ide> if not str(e) == good: <ide> self.fail("Got msg '%s', expected '%s'" % (e, good)) <ide> def test_unicode_to_string_cast(self): <ide> a = np.array([[u'abc', u'\u03a3'], <ide> [u'asdf', u'erw']], <ide> dtype='U') <del> self.assertRaises(UnicodeEncodeError, np.array, a, 'S4') <add> assert_raises(UnicodeEncodeError, np.array, a, 'S4') <ide> <ide> def test_mixed_string_unicode_array_creation(self): <ide> a = np.array(['1234', u'123']) <ide> def test_structured_arrays_with_objects2(self): <ide> def test_duplicate_title_and_name(self): <ide> # Ticket #1254 <ide> dtspec = [(('a', 'a'), 'i'), ('b', 'i')] <del> self.assertRaises(ValueError, np.dtype, dtspec) <add> assert_raises(ValueError, np.dtype, dtspec) <ide> <ide> def test_signed_integer_division_overflow(self): <ide> # Ticket #1317. <ide> def test_deepcopy_on_0d_array(self): <ide> assert_equal(arr, arr_cp) <ide> assert_equal(arr.shape, arr_cp.shape) <ide> assert_equal(int(arr), int(arr_cp)) <del> self.assertTrue(arr is not arr_cp) <del> self.assertTrue(isinstance(arr_cp, type(arr))) <add> assert_(arr is not arr_cp) <add> assert_(isinstance(arr_cp, type(arr))) <ide> <ide> def test_deepcopy_F_order_object_array(self): <ide> # Ticket #6456. <ide> def test_deepcopy_F_order_object_array(self): <ide> arr_cp = copy.deepcopy(arr) <ide> <ide> assert_equal(arr, arr_cp) <del> self.assertTrue(arr is not arr_cp) <add> assert_(arr is not arr_cp) <ide> # Ensure that we have actually copied the item. <del> self.assertTrue(arr[0, 1] is not arr_cp[1, 1]) <add> assert_(arr[0, 1] is not arr_cp[1, 1]) <ide> # Ensure we are allowed to have references to the same object. <del> self.assertTrue(arr[0, 1] is arr[1, 1]) <add> assert_(arr[0, 1] is arr[1, 1]) <ide> # Check the references hold for the copied objects. <del> self.assertTrue(arr_cp[0, 1] is arr_cp[1, 1]) <add> assert_(arr_cp[0, 1] is arr_cp[1, 1]) <ide> <ide> def test_deepcopy_empty_object_array(self): <ide> # Ticket #8536. <ide><path>numpy/core/tests/test_scalarinherit.py <ide> from __future__ import division, absolute_import, print_function <ide> <ide> import numpy as np <del>from numpy.testing import TestCase, run_module_suite, assert_ <add>from numpy.testing import run_module_suite, assert_ <ide> <ide> <ide> class A(object): <ide> class B0(np.float64, A): <ide> class C0(B0): <ide> pass <ide> <del>class TestInherit(TestCase): <add>class TestInherit(object): <ide> def test_init(self): <ide> x = B(1.0) <ide> assert_(str(x) == '1.0') <ide><path>numpy/core/tests/test_scalarmath.py <ide> <ide> import numpy as np <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_raises, <add> run_module_suite, assert_, assert_equal, assert_raises, <ide> assert_almost_equal, assert_allclose, assert_array_equal, IS_PYPY, <ide> suppress_warnings, dec, _gen_alignment_data, <ide> ) <ide> <ide> # This compares scalarmath against ufuncs. <ide> <del>class TestTypes(TestCase): <add>class TestTypes(object): <ide> def test_types(self, level=1): <ide> for atype in types: <ide> a = atype(1) <ide> def test_leak(self): <ide> np.add(1, 1) <ide> <ide> <del>class TestBaseMath(TestCase): <add>class TestBaseMath(object): <ide> def test_blocked(self): <ide> # test alignments offsets for simd instructions <ide> # alignments for vz + 2 * (vs - 1) + 1 <ide> def test_lower_align(self): <ide> np.add(d, np.ones_like(d)) <ide> <ide> <del>class TestPower(TestCase): <add>class TestPower(object): <ide> def test_small_types(self): <ide> for t in [np.int8, np.int16, np.float16]: <ide> a = t(3) <ide> def _signs(dt): <ide> return (+1, -1) <ide> <ide> <del>class TestModulus(TestCase): <add>class TestModulus(object): <ide> <ide> def test_modulus_basic(self): <ide> dt = np.typecodes['AllInteger'] + np.typecodes['Float'] <ide> def test_float_modulus_corner_cases(self): <ide> assert_(np.isnan(rem), 'dt: %s' % dt) <ide> <ide> <del>class TestComplexDivision(TestCase): <add>class TestComplexDivision(object): <ide> def test_zero_division(self): <ide> with np.errstate(all="ignore"): <ide> for t in [np.complex64, np.complex128]: <ide> def test_branches(self): <ide> assert_equal(result.imag, ex[1]) <ide> <ide> <del>class TestConversion(TestCase): <add>class TestConversion(object): <ide> def test_int_from_long(self): <ide> l = [1e6, 1e12, 1e18, -1e6, -1e12, -1e18] <ide> li = [10**6, 10**12, 10**18, -10**6, -10**12, -10**18] <ide> def test_longdouble_int(self): <ide> sup.record(np.ComplexWarning) <ide> x = np.clongdouble(np.inf) <ide> assert_raises(OverflowError, int, x) <del> self.assertEqual(len(sup.log), 1) <add> assert_equal(len(sup.log), 1) <ide> <ide> @dec.knownfailureif(not IS_PYPY) <ide> def test_clongdouble___int__(self): <ide> def test_scalar_comparison_to_none(self): <ide> assert_(np.equal(np.datetime64('NaT'), None)) <ide> <ide> <del>#class TestRepr(TestCase): <add>#class TestRepr(object): <ide> # def test_repr(self): <ide> # for t in types: <ide> # val = t(1197346475.0137341) <ide> def test_float_repr(self): <ide> <ide> if not IS_PYPY: <ide> # sys.getsizeof() is not valid on PyPy <del> class TestSizeOf(TestCase): <add> class TestSizeOf(object): <ide> <ide> def test_equal_nbytes(self): <ide> for type in types: <ide> def test_error(self): <ide> assert_raises(TypeError, d.__sizeof__, "a") <ide> <ide> <del>class TestMultiply(TestCase): <add>class TestMultiply(object): <ide> def test_seq_repeat(self): <ide> # Test that basic sequences get repeated when multiplied with <ide> # numpy integers. And errors are raised when multiplied with others. <ide> def __array__(self): <ide> assert_array_equal(np.int_(3) * arr_like, np.full(3, 3)) <ide> <ide> <del>class TestNegative(TestCase): <add>class TestNegative(object): <ide> def test_exceptions(self): <ide> a = np.ones((), dtype=np.bool_)[()] <ide> assert_raises(TypeError, operator.neg, a) <ide> def test_result(self): <ide> assert_equal(operator.neg(a) + a, 0) <ide> <ide> <del>class TestSubtract(TestCase): <add>class TestSubtract(object): <ide> def test_exceptions(self): <ide> a = np.ones((), dtype=np.bool_)[()] <ide> assert_raises(TypeError, operator.sub, a, a) <ide> def test_result(self): <ide> assert_equal(operator.sub(a, a), 0) <ide> <ide> <del>class TestAbs(TestCase): <add>class TestAbs(object): <ide> <ide> def _test_abs_func(self, absfunc): <ide> for tp in floating_types: <ide><path>numpy/core/tests/test_scalarprint.py <ide> from __future__ import division, absolute_import, print_function <ide> <ide> import numpy as np <del>from numpy.testing import TestCase, assert_, run_module_suite <add>from numpy.testing import assert_, run_module_suite <ide> <ide> <del>class TestRealScalars(TestCase): <add>class TestRealScalars(object): <ide> def test_str(self): <ide> svals = [0.0, -0.0, 1, -1, np.inf, -np.inf, np.nan] <ide> styps = [np.float16, np.float32, np.float64, np.longdouble] <ide><path>numpy/core/tests/test_shape_base.py <ide> import numpy as np <ide> from numpy.core import (array, arange, atleast_1d, atleast_2d, atleast_3d, <ide> block, vstack, hstack, newaxis, concatenate, stack) <del>from numpy.testing import (TestCase, assert_, assert_raises, <add>from numpy.testing import (assert_, assert_raises, <ide> assert_array_equal, assert_equal, run_module_suite, <ide> assert_raises_regex, assert_almost_equal) <ide> <ide> from numpy.compat import long <ide> <del>class TestAtleast1d(TestCase): <add>class TestAtleast1d(object): <ide> def test_0D_array(self): <ide> a = array(1) <ide> b = array(2) <ide> def test_r1array(self): <ide> assert_(atleast_1d([[2, 3], [4, 5]]).shape == (2, 2)) <ide> <ide> <del>class TestAtleast2d(TestCase): <add>class TestAtleast2d(object): <ide> def test_0D_array(self): <ide> a = array(1) <ide> b = array(2) <ide> def test_r2array(self): <ide> assert_(atleast_2d([[[3, 1], [4, 5]], [[3, 5], [1, 2]]]).shape == (2, 2, 2)) <ide> <ide> <del>class TestAtleast3d(TestCase): <add>class TestAtleast3d(object): <ide> def test_0D_array(self): <ide> a = array(1) <ide> b = array(2) <ide> def test_3D_array(self): <ide> assert_array_equal(res, desired) <ide> <ide> <del>class TestHstack(TestCase): <add>class TestHstack(object): <ide> def test_non_iterable(self): <ide> assert_raises(TypeError, hstack, 1) <ide> <ide> def test_2D_array(self): <ide> assert_array_equal(res, desired) <ide> <ide> <del>class TestVstack(TestCase): <add>class TestVstack(object): <ide> def test_non_iterable(self): <ide> assert_raises(TypeError, vstack, 1) <ide> <ide> def test_2D_array2(self): <ide> assert_array_equal(res, desired) <ide> <ide> <del>class TestConcatenate(TestCase): <add>class TestConcatenate(object): <ide> def test_exceptions(self): <ide> # test axis must be in bounds <ide> for ndim in [1, 2, 3]: <ide> def test_stack(): <ide> stack, [m, m]) <ide> <ide> <del>class TestBlock(TestCase): <add>class TestBlock(object): <ide> def test_block_simple_row_wise(self): <ide> a_2d = np.ones((2, 2)) <ide> b_2d = 2 * a_2d <ide><path>numpy/core/tests/test_ufunc.py <ide> import numpy.core.operand_flag_tests as opflag_tests <ide> from numpy.core.test_rational import rational, test_add, test_add_rationals <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_raises, <add> run_module_suite, assert_, assert_equal, assert_raises, <ide> assert_array_equal, assert_almost_equal, assert_array_almost_equal, <ide> assert_no_warnings <ide> ) <ide> <ide> <del>class TestUfuncKwargs(TestCase): <add>class TestUfuncKwargs(object): <ide> def test_kwarg_exact(self): <ide> assert_raises(TypeError, np.add, 1, 2, castingx='safe') <ide> assert_raises(TypeError, np.add, 1, 2, dtypex=np.int) <ide> def test_sig_dtype(self): <ide> dtype=np.int) <ide> <ide> <del>class TestUfunc(TestCase): <add>class TestUfunc(object): <ide> def test_pickle(self): <ide> import pickle <ide> assert_(pickle.loads(pickle.dumps(np.sin)) is np.sin) <ide> def test_inplace_fancy_indexing(self): <ide> <ide> # Test exception thrown <ide> values = np.array(['a', 1], dtype=np.object) <del> self.assertRaises(TypeError, np.add.at, values, [0, 1], 1) <add> assert_raises(TypeError, np.add.at, values, [0, 1], 1) <ide> assert_array_equal(values, np.array(['a', 1], dtype=np.object)) <ide> <ide> # Test multiple output ufuncs raise error, gh-5665 <ide><path>numpy/core/tests/test_umath.py <ide> from numpy.core import umath_tests as ncu_tests <ide> import numpy as np <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_raises, <add> run_module_suite, assert_, assert_equal, assert_raises, <ide> assert_raises_regex, assert_array_equal, assert_almost_equal, <ide> assert_array_almost_equal, dec, assert_allclose, assert_no_warnings, <ide> suppress_warnings, _gen_alignment_data, <ide> def tearDown(self): <ide> np.seterr(**self.olderr) <ide> <ide> <del>class TestConstants(TestCase): <add>class TestConstants(object): <ide> def test_pi(self): <ide> assert_allclose(ncu.pi, 3.141592653589793, 1e-15) <ide> <ide> def test_euler_gamma(self): <ide> assert_allclose(ncu.euler_gamma, 0.5772156649015329, 1e-15) <ide> <ide> <del>class TestOut(TestCase): <add>class TestOut(object): <ide> def test_out_subok(self): <ide> for subok in (True, False): <ide> a = np.array(0.5) <ide> def __array_wrap__(self, arr, context): <ide> assert_(w[0].category is DeprecationWarning) <ide> <ide> <del>class TestComparisons(TestCase): <add>class TestComparisons(object): <ide> def test_ignore_object_identity_in_equal(self): <ide> # Check error raised when comparing identical objects whose comparison <ide> # is not a simple boolean, e.g., arrays that are compared elementwise. <ide> def __ne__(self, other): <ide> assert_equal(np.not_equal(a, a), [True]) <ide> <ide> <del>class TestDivision(TestCase): <add>class TestDivision(object): <ide> def test_division_int(self): <ide> # int division should follow Python <ide> x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120]) <ide> def _signs(dt): <ide> return (+1, -1) <ide> <ide> <del>class TestRemainder(TestCase): <add>class TestRemainder(object): <ide> <ide> def test_remainder_basic(self): <ide> dt = np.typecodes['AllInteger'] + np.typecodes['Float'] <ide> def test_float_remainder_corner_cases(self): <ide> assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)) <ide> <ide> <del>class TestCbrt(TestCase): <add>class TestCbrt(object): <ide> def test_cbrt_scalar(self): <ide> assert_almost_equal((np.cbrt(np.float32(-2.5)**3)), -2.5) <ide> <ide> def test_cbrt(self): <ide> assert_equal(np.cbrt(-np.inf), -np.inf) <ide> <ide> <del>class TestPower(TestCase): <add>class TestPower(object): <ide> def test_power_float(self): <ide> x = np.array([1., 2., 3.]) <ide> assert_equal(x**0, [1., 1., 1.]) <ide> def test_integer_to_negative_power(self): <ide> assert_raises(ValueError, np.power, one, minusone) <ide> <ide> <del>class TestFloat_power(TestCase): <add>class TestFloat_power(object): <ide> def test_type_conversion(self): <ide> arg_type = '?bhilBHILefdgFDG' <ide> res_type = 'ddddddddddddgDDG' <ide> def test_type_conversion(self): <ide> assert_(res.dtype.name == np.dtype(dtout).name, msg) <ide> <ide> <del>class TestLog2(TestCase): <add>class TestLog2(object): <ide> def test_log2_values(self): <ide> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] <ide> y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <ide> def test_log2_special(self): <ide> assert_(w[2].category is RuntimeWarning) <ide> <ide> <del>class TestExp2(TestCase): <add>class TestExp2(object): <ide> def test_exp2_values(self): <ide> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] <ide> y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <ide> def test_nan(self): <ide> assert_(np.isnan(np.logaddexp2(np.nan, np.nan))) <ide> <ide> <del>class TestLog(TestCase): <add>class TestLog(object): <ide> def test_log_values(self): <ide> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] <ide> y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <ide> def test_log_values(self): <ide> assert_almost_equal(np.log(xf), yf) <ide> <ide> <del>class TestExp(TestCase): <add>class TestExp(object): <ide> def test_exp_values(self): <ide> x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] <ide> y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <ide> def test_nan(self): <ide> assert_(np.isnan(np.logaddexp(np.nan, np.nan))) <ide> <ide> <del>class TestLog1p(TestCase): <add>class TestLog1p(object): <ide> def test_log1p(self): <ide> assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2)) <ide> assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6)) <ide> def test_special(self): <ide> assert_equal(ncu.log1p(-np.inf), np.nan) <ide> <ide> <del>class TestExpm1(TestCase): <add>class TestExpm1(object): <ide> def test_expm1(self): <ide> assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1) <ide> assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1) <ide> def test_special(self): <ide> assert_equal(ncu.expm1(-np.inf), -1.) <ide> <ide> <del>class TestHypot(TestCase, object): <add>class TestHypot(object): <ide> def test_simple(self): <ide> assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2)) <ide> assert_almost_equal(ncu.hypot(0, 0), 0) <ide> def assert_hypot_isinf(x, y): <ide> "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y))) <ide> <ide> <del>class TestHypotSpecialValues(TestCase): <add>class TestHypotSpecialValues(object): <ide> def test_nan_outputs(self): <ide> assert_hypot_isnan(np.nan, np.nan) <ide> assert_hypot_isnan(np.nan, 1) <ide> def assert_arctan2_isnzero(x, y): <ide> assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not -0" % (x, y, ncu.arctan2(x, y))) <ide> <ide> <del>class TestArctan2SpecialValues(TestCase): <add>class TestArctan2SpecialValues(object): <ide> def test_one_one(self): <ide> # atan2(1, 1) returns pi/4. <ide> assert_almost_equal(ncu.arctan2(1, 1), 0.25 * np.pi) <ide> def test_nan_any(self): <ide> assert_arctan2_isnan(np.nan, np.nan) <ide> <ide> <del>class TestLdexp(TestCase): <add>class TestLdexp(object): <ide> def _check_ldexp(self, tp): <ide> assert_almost_equal(ncu.ldexp(np.array(2., np.float32), <ide> np.array(3, tp)), 16.) <ide> def test_complex_nans(self): <ide> assert_equal(np.fmin(arg1, arg2), out) <ide> <ide> <del>class TestBool(TestCase): <add>class TestBool(object): <ide> def test_exceptions(self): <ide> a = np.ones(1, dtype=np.bool_) <ide> assert_raises(TypeError, np.negative, a) <ide> def test_reduce(self): <ide> assert_equal(np.logical_xor.reduce(arr), arr.sum() % 2 == 1) <ide> <ide> <del>class TestBitwiseUFuncs(TestCase): <add>class TestBitwiseUFuncs(object): <ide> <ide> bitwise_types = [np.dtype(c) for c in '?' + 'bBhHiIlLqQ' + 'O'] <ide> <ide> def test_reduction(self): <ide> assert_(type(f.reduce(btype)) is bool, msg) <ide> <ide> <del>class TestInt(TestCase): <add>class TestInt(object): <ide> def test_logical_not(self): <ide> x = np.ones(10, dtype=np.int16) <ide> o = np.ones(10 * 2, dtype=np.bool) <ide> def test_logical_not(self): <ide> assert_array_equal(o, tgt) <ide> <ide> <del>class TestFloatingPoint(TestCase): <add>class TestFloatingPoint(object): <ide> def test_floating_point(self): <ide> assert_equal(ncu.FLOATING_POINT_SUPPORT, 1) <ide> <ide> <del>class TestDegrees(TestCase): <add>class TestDegrees(object): <ide> def test_degrees(self): <ide> assert_almost_equal(ncu.degrees(np.pi), 180.0) <ide> assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0) <ide> <ide> <del>class TestRadians(TestCase): <add>class TestRadians(object): <ide> def test_radians(self): <ide> assert_almost_equal(ncu.radians(180.0), np.pi) <ide> assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi) <ide> <ide> <del>class TestHeavside(TestCase): <add>class TestHeavside(object): <ide> def test_heaviside(self): <ide> x = np.array([[-30.0, -0.1, 0.0, 0.2], [7.5, np.nan, np.inf, -np.inf]]) <ide> expectedhalf = np.array([[0.0, 0.0, 0.5, 1.0], [1.0, np.nan, 1.0, 0.0]]) <ide> def test_heaviside(self): <ide> assert_equal(h, expected1.astype(np.float32)) <ide> <ide> <del>class TestSign(TestCase): <add>class TestSign(object): <ide> def test_sign(self): <ide> a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0]) <ide> out = np.zeros(a.shape) <ide> def test_nan(): <ide> <ide> assert_raises(TypeError, test_nan) <ide> <del>class TestMinMax(TestCase): <add>class TestMinMax(object): <ide> def test_minmax_blocked(self): <ide> # simd tests on max/min, test all alignments, slow but important <ide> # for 2 * vz + 2 * (vs - 1) + 1 (unrolled once) <ide> def test_lower_align(self): <ide> assert_equal(d.min(), d[0]) <ide> <ide> <del>class TestAbsoluteNegative(TestCase): <add>class TestAbsoluteNegative(object): <ide> def test_abs_neg_blocked(self): <ide> # simd tests on abs, test all alignments for vz + 2 * (vs - 1) + 1 <ide> for dt, sz in [(np.float32, 11), (np.float64, 5)]: <ide> def test_abs_neg_blocked(self): <ide> tgt = [ncu.absolute(i) for i in inp] <ide> np.absolute(inp, out=out) <ide> assert_equal(out, tgt, err_msg=msg) <del> self.assertTrue((out >= 0).all()) <add> assert_((out >= 0).all()) <ide> <ide> tgt = [-1*(i) for i in inp] <ide> np.negative(inp, out=out) <ide> def test_lower_align(self): <ide> np.abs(np.ones_like(d), out=d) <ide> <ide> <del>class TestPositive(TestCase): <add>class TestPositive(object): <ide> def test_valid(self): <ide> valid_dtypes = [int, float, complex, object] <ide> for dtype in valid_dtypes: <ide> def test_invalid(self): <ide> np.positive(np.array(['bar'], dtype=object)) <ide> <ide> <del>class TestSpecialMethods(TestCase): <add>class TestSpecialMethods(object): <ide> def test_wrap(self): <ide> <ide> class with_wrap(object): <ide> def __array_wrap__(self, arr, context): <ide> x = ncu.minimum(a, a) <ide> assert_equal(x.arr, np.zeros(1)) <ide> func, args, i = x.context <del> self.assertTrue(func is ncu.minimum) <del> self.assertEqual(len(args), 2) <add> assert_(func is ncu.minimum) <add> assert_equal(len(args), 2) <ide> assert_equal(args[0], a) <ide> assert_equal(args[1], a) <del> self.assertEqual(i, 0) <add> assert_equal(i, 0) <ide> <ide> def test_wrap_with_iterable(self): <ide> # test fix for bug #1026: <ide> def __array_wrap__(self, arr, context): <ide> <ide> a = with_wrap() <ide> x = ncu.multiply(a, (1, 2, 3)) <del> self.assertTrue(isinstance(x, with_wrap)) <add> assert_(isinstance(x, with_wrap)) <ide> assert_array_equal(x, np.array((1, 2, 3))) <ide> <ide> def test_priority_with_scalar(self): <ide> def __new__(cls): <ide> <ide> a = A() <ide> x = np.float64(1)*a <del> self.assertTrue(isinstance(x, A)) <add> assert_(isinstance(x, A)) <ide> assert_array_equal(x, np.array(1)) <ide> <ide> def test_old_wrap(self): <ide> class C(A): <ide> b = B() <ide> c = C() <ide> f = ncu.minimum <del> self.assertTrue(type(f(x, x)) is np.ndarray) <del> self.assertTrue(type(f(x, a)) is A) <del> self.assertTrue(type(f(x, b)) is B) <del> self.assertTrue(type(f(x, c)) is C) <del> self.assertTrue(type(f(a, x)) is A) <del> self.assertTrue(type(f(b, x)) is B) <del> self.assertTrue(type(f(c, x)) is C) <del> <del> self.assertTrue(type(f(a, a)) is A) <del> self.assertTrue(type(f(a, b)) is B) <del> self.assertTrue(type(f(b, a)) is B) <del> self.assertTrue(type(f(b, b)) is B) <del> self.assertTrue(type(f(b, c)) is C) <del> self.assertTrue(type(f(c, b)) is C) <del> self.assertTrue(type(f(c, c)) is C) <del> <del> self.assertTrue(type(ncu.exp(a) is A)) <del> self.assertTrue(type(ncu.exp(b) is B)) <del> self.assertTrue(type(ncu.exp(c) is C)) <add> assert_(type(f(x, x)) is np.ndarray) <add> assert_(type(f(x, a)) is A) <add> assert_(type(f(x, b)) is B) <add> assert_(type(f(x, c)) is C) <add> assert_(type(f(a, x)) is A) <add> assert_(type(f(b, x)) is B) <add> assert_(type(f(c, x)) is C) <add> <add> assert_(type(f(a, a)) is A) <add> assert_(type(f(a, b)) is B) <add> assert_(type(f(b, a)) is B) <add> assert_(type(f(b, b)) is B) <add> assert_(type(f(b, c)) is C) <add> assert_(type(f(c, b)) is C) <add> assert_(type(f(c, c)) is C) <add> <add> assert_(type(ncu.exp(a) is A)) <add> assert_(type(ncu.exp(b) is B)) <add> assert_(type(ncu.exp(c) is C)) <ide> <ide> def test_failing_wrap(self): <ide> <ide> def __array_wrap__(self, arr, context): <ide> raise RuntimeError <ide> <ide> a = A() <del> self.assertRaises(RuntimeError, ncu.maximum, a, a) <add> assert_raises(RuntimeError, ncu.maximum, a, a) <ide> <ide> def test_none_wrap(self): <ide> # Tests that issue #8507 is resolved. Previously, this would segfault <ide> def __array_prepare__(self, arr, context=None): <ide> raise RuntimeError <ide> <ide> a = A() <del> self.assertRaises(RuntimeError, ncu.maximum, a, a) <add> assert_raises(RuntimeError, ncu.maximum, a, a) <ide> <ide> def test_array_with_context(self): <ide> <ide> def __array__(self): <ide> <ide> a = A() <ide> ncu.maximum(np.zeros(1), a) <del> self.assertTrue(a.func is ncu.maximum) <add> assert_(a.func is ncu.maximum) <ide> assert_equal(a.args[0], 0) <del> self.assertTrue(a.args[1] is a) <del> self.assertTrue(a.i == 1) <add> assert_(a.args[1] is a) <add> assert_(a.i == 1) <ide> assert_equal(ncu.maximum(a, B()), 0) <ide> assert_equal(ncu.maximum(a, C()), 0) <ide> <ide> def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): <ide> assert_(a.info, {'inputs': [0, 2]}) <ide> <ide> <del>class TestChoose(TestCase): <add>class TestChoose(object): <ide> def test_mixed(self): <ide> c = np.array([True, True]) <ide> a = np.array([True, True]) <ide> def test_loss_of_precision_longcomplex(self): <ide> self.check_loss_of_precision(np.longcomplex) <ide> <ide> <del>class TestAttributes(TestCase): <add>class TestAttributes(object): <ide> def test_attributes(self): <ide> add = ncu.add <ide> assert_equal(add.__name__, 'add') <del> self.assertTrue(add.ntypes >= 18) # don't fail if types added <del> self.assertTrue('ii->i' in add.types) <add> assert_(add.ntypes >= 18) # don't fail if types added <add> assert_('ii->i' in add.types) <ide> assert_equal(add.nin, 2) <ide> assert_equal(add.nout, 1) <ide> assert_equal(add.identity, 0) <ide> def test_doc(self): <ide> "frexp(x[, out1, out2], / [, out=(None, None)], *, where=True")) <ide> <ide> <del>class TestSubclass(TestCase): <add>class TestSubclass(object): <ide> <ide> def test_subclass_op(self): <ide> <ide><path>numpy/core/tests/test_umath_complex.py <ide> import numpy as np <ide> import numpy.core.umath as ncu <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_equal, assert_array_equal, <add> run_module_suite, assert_raises, assert_equal, assert_array_equal, <ide> assert_almost_equal, dec <ide> ) <ide> <ide> def test_special_values2(self): <ide> <ide> yield check, f, np.nan, 0, np.nan, 0 <ide> <del>class TestClog(TestCase): <add>class TestClog(object): <ide> def test_simple(self): <ide> x = np.array([1+0j, 1+2j]) <ide> y_r = np.log(np.abs(x)) + 1j * np.angle(x) <ide> def test_special_values(self): <ide> with np.errstate(divide='raise'): <ide> x = np.array([np.NZERO], dtype=np.complex) <ide> y = np.complex(-np.inf, np.pi) <del> self.assertRaises(FloatingPointError, np.log, x) <add> assert_raises(FloatingPointError, np.log, x) <ide> with np.errstate(divide='ignore'): <ide> assert_almost_equal(np.log(x), y) <ide> <ide> def test_special_values(self): <ide> with np.errstate(divide='raise'): <ide> x = np.array([0], dtype=np.complex) <ide> y = np.complex(-np.inf, 0) <del> self.assertRaises(FloatingPointError, np.log, x) <add> assert_raises(FloatingPointError, np.log, x) <ide> with np.errstate(divide='ignore'): <ide> assert_almost_equal(np.log(x), y) <ide> <ide> def test_special_values(self): <ide> with np.errstate(invalid='raise'): <ide> x = np.array([complex(1., np.nan)], dtype=np.complex) <ide> y = np.complex(np.nan, np.nan) <del> #self.assertRaises(FloatingPointError, np.log, x) <add> #assert_raises(FloatingPointError, np.log, x) <ide> with np.errstate(invalid='ignore'): <ide> assert_almost_equal(np.log(x), y) <ide> <ide> def test_special_values(self): <ide> <ide> with np.errstate(invalid='raise'): <ide> x = np.array([np.inf + 1j * np.nan], dtype=np.complex) <del> #self.assertRaises(FloatingPointError, np.log, x) <add> #assert_raises(FloatingPointError, np.log, x) <ide> with np.errstate(invalid='ignore'): <ide> assert_almost_equal(np.log(x), y) <ide> <ide> def _check_ninf_nan(dummy): <ide> # XXX: check for conj(csqrt(z)) == csqrt(conj(z)) (need to fix branch <ide> # cuts first) <ide> <del>class TestCpow(TestCase): <add>class TestCpow(object): <ide> def setUp(self): <ide> self.olderr = np.seterr(invalid='ignore') <ide> <ide><path>numpy/core/tests/test_unicode.py <ide> import numpy as np <ide> from numpy.compat import unicode <ide> from numpy.testing import ( <del> TestCase, run_module_suite, assert_, assert_equal, assert_array_equal) <add> run_module_suite, assert_, assert_equal, assert_array_equal) <ide> <ide> # Guess the UCS length for this python interpreter <ide> if sys.version_info[:2] >= (3, 3): <ide> def test_string_cast(): <ide> # Creation tests <ide> ############################################################ <ide> <del>class create_zeros(object): <add>class CreateZeros(object): <ide> """Check the creation of zero-valued arrays""" <ide> <ide> def content_check(self, ua, ua_scalar, nbytes): <ide> <ide> # Check the length of the unicode base type <del> self.assertTrue(int(ua.dtype.str[2:]) == self.ulen) <add> assert_(int(ua.dtype.str[2:]) == self.ulen) <ide> # Check the length of the data buffer <del> self.assertTrue(buffer_length(ua) == nbytes) <add> assert_(buffer_length(ua) == nbytes) <ide> # Small check that data in array element is ok <del> self.assertTrue(ua_scalar == u'') <add> assert_(ua_scalar == u'') <ide> # Encode to ascii and double check <del> self.assertTrue(ua_scalar.encode('ascii') == b'') <add> assert_(ua_scalar.encode('ascii') == b'') <ide> # Check buffer lengths for scalars <ide> if ucs4: <del> self.assertTrue(buffer_length(ua_scalar) == 0) <add> assert_(buffer_length(ua_scalar) == 0) <ide> else: <del> self.assertTrue(buffer_length(ua_scalar) == 0) <add> assert_(buffer_length(ua_scalar) == 0) <ide> <ide> def test_zeros0D(self): <ide> # Check creation of 0-dimensional objects <ide> def test_zerosMD(self): <ide> self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4) <ide> <ide> <del>class test_create_zeros_1(create_zeros, TestCase): <add>class TestCreateZeros_1(CreateZeros): <ide> """Check the creation of zero-valued arrays (size 1)""" <ide> ulen = 1 <ide> <ide> <del>class test_create_zeros_2(create_zeros, TestCase): <add>class TestCreateZeros_2(CreateZeros): <ide> """Check the creation of zero-valued arrays (size 2)""" <ide> ulen = 2 <ide> <ide> <del>class test_create_zeros_1009(create_zeros, TestCase): <add>class TestCreateZeros_1009(CreateZeros): <ide> """Check the creation of zero-valued arrays (size 1009)""" <ide> ulen = 1009 <ide> <ide> <del>class create_values(object): <add>class CreateValues(object): <ide> """Check the creation of unicode arrays with values""" <ide> <ide> def content_check(self, ua, ua_scalar, nbytes): <ide> <ide> # Check the length of the unicode base type <del> self.assertTrue(int(ua.dtype.str[2:]) == self.ulen) <add> assert_(int(ua.dtype.str[2:]) == self.ulen) <ide> # Check the length of the data buffer <del> self.assertTrue(buffer_length(ua) == nbytes) <add> assert_(buffer_length(ua) == nbytes) <ide> # Small check that data in array element is ok <del> self.assertTrue(ua_scalar == self.ucs_value*self.ulen) <add> assert_(ua_scalar == self.ucs_value*self.ulen) <ide> # Encode to UTF-8 and double check <del> self.assertTrue(ua_scalar.encode('utf-8') == <add> assert_(ua_scalar.encode('utf-8') == <ide> (self.ucs_value*self.ulen).encode('utf-8')) <ide> # Check buffer lengths for scalars <ide> if ucs4: <del> self.assertTrue(buffer_length(ua_scalar) == 4*self.ulen) <add> assert_(buffer_length(ua_scalar) == 4*self.ulen) <ide> else: <ide> if self.ucs_value == ucs4_value: <ide> # In UCS2, the \U0010FFFF will be represented using a <ide> # surrogate *pair* <del> self.assertTrue(buffer_length(ua_scalar) == 2*2*self.ulen) <add> assert_(buffer_length(ua_scalar) == 2*2*self.ulen) <ide> else: <ide> # In UCS2, the \uFFFF will be represented using a <ide> # regular 2-byte word <del> self.assertTrue(buffer_length(ua_scalar) == 2*self.ulen) <add> assert_(buffer_length(ua_scalar) == 2*self.ulen) <ide> <ide> def test_values0D(self): <ide> # Check creation of 0-dimensional objects with values <ide> def test_valuesMD(self): <ide> self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4) <ide> <ide> <del>class test_create_values_1_ucs2(create_values, TestCase): <add>class TestCreateValues_1_UCS2(CreateValues): <ide> """Check the creation of valued arrays (size 1, UCS2 values)""" <ide> ulen = 1 <ide> ucs_value = ucs2_value <ide> <ide> <del>class test_create_values_1_ucs4(create_values, TestCase): <add>class TestCreateValues_1_UCS4(CreateValues): <ide> """Check the creation of valued arrays (size 1, UCS4 values)""" <ide> ulen = 1 <ide> ucs_value = ucs4_value <ide> <ide> <del>class test_create_values_2_ucs2(create_values, TestCase): <add>class TestCreateValues_2_UCS2(CreateValues): <ide> """Check the creation of valued arrays (size 2, UCS2 values)""" <ide> ulen = 2 <ide> ucs_value = ucs2_value <ide> <ide> <del>class test_create_values_2_ucs4(create_values, TestCase): <add>class TestCreateValues_2_UCS4(CreateValues): <ide> """Check the creation of valued arrays (size 2, UCS4 values)""" <ide> ulen = 2 <ide> ucs_value = ucs4_value <ide> <ide> <del>class test_create_values_1009_ucs2(create_values, TestCase): <add>class TestCreateValues_1009_UCS2(CreateValues): <ide> """Check the creation of valued arrays (size 1009, UCS2 values)""" <ide> ulen = 1009 <ide> ucs_value = ucs2_value <ide> <ide> <del>class test_create_values_1009_ucs4(create_values, TestCase): <add>class TestCreateValues_1009_UCS4(CreateValues): <ide> """Check the creation of valued arrays (size 1009, UCS4 values)""" <ide> ulen = 1009 <ide> ucs_value = ucs4_value <ide> class test_create_values_1009_ucs4(create_values, TestCase): <ide> # Assignment tests <ide> ############################################################ <ide> <del>class assign_values(object): <add>class AssignValues(object): <ide> """Check the assignment of unicode arrays with values""" <ide> <ide> def content_check(self, ua, ua_scalar, nbytes): <ide> <ide> # Check the length of the unicode base type <del> self.assertTrue(int(ua.dtype.str[2:]) == self.ulen) <add> assert_(int(ua.dtype.str[2:]) == self.ulen) <ide> # Check the length of the data buffer <del> self.assertTrue(buffer_length(ua) == nbytes) <add> assert_(buffer_length(ua) == nbytes) <ide> # Small check that data in array element is ok <del> self.assertTrue(ua_scalar == self.ucs_value*self.ulen) <add> assert_(ua_scalar == self.ucs_value*self.ulen) <ide> # Encode to UTF-8 and double check <del> self.assertTrue(ua_scalar.encode('utf-8') == <add> assert_(ua_scalar.encode('utf-8') == <ide> (self.ucs_value*self.ulen).encode('utf-8')) <ide> # Check buffer lengths for scalars <ide> if ucs4: <del> self.assertTrue(buffer_length(ua_scalar) == 4*self.ulen) <add> assert_(buffer_length(ua_scalar) == 4*self.ulen) <ide> else: <ide> if self.ucs_value == ucs4_value: <ide> # In UCS2, the \U0010FFFF will be represented using a <ide> # surrogate *pair* <del> self.assertTrue(buffer_length(ua_scalar) == 2*2*self.ulen) <add> assert_(buffer_length(ua_scalar) == 2*2*self.ulen) <ide> else: <ide> # In UCS2, the \uFFFF will be represented using a <ide> # regular 2-byte word <del> self.assertTrue(buffer_length(ua_scalar) == 2*self.ulen) <add> assert_(buffer_length(ua_scalar) == 2*self.ulen) <ide> <ide> def test_values0D(self): <ide> # Check assignment of 0-dimensional objects with values <ide> def test_valuesMD(self): <ide> self.content_check(ua, ua[-1, -1, -1], 4*self.ulen*2*3*4) <ide> <ide> <del>class test_assign_values_1_ucs2(assign_values, TestCase): <add>class TestAssignValues_1_UCS2(AssignValues): <ide> """Check the assignment of valued arrays (size 1, UCS2 values)""" <ide> ulen = 1 <ide> ucs_value = ucs2_value <ide> <ide> <del>class test_assign_values_1_ucs4(assign_values, TestCase): <add>class TestAssignValues_1_UCS4(AssignValues): <ide> """Check the assignment of valued arrays (size 1, UCS4 values)""" <ide> ulen = 1 <ide> ucs_value = ucs4_value <ide> <ide> <del>class test_assign_values_2_ucs2(assign_values, TestCase): <add>class TestAssignValues_2_UCS2(AssignValues): <ide> """Check the assignment of valued arrays (size 2, UCS2 values)""" <ide> ulen = 2 <ide> ucs_value = ucs2_value <ide> <ide> <del>class test_assign_values_2_ucs4(assign_values, TestCase): <add>class TestAssignValues_2_UCS4(AssignValues): <ide> """Check the assignment of valued arrays (size 2, UCS4 values)""" <ide> ulen = 2 <ide> ucs_value = ucs4_value <ide> <ide> <del>class test_assign_values_1009_ucs2(assign_values, TestCase): <add>class TestAssignValues_1009_UCS2(AssignValues): <ide> """Check the assignment of valued arrays (size 1009, UCS2 values)""" <ide> ulen = 1009 <ide> ucs_value = ucs2_value <ide> <ide> <del>class test_assign_values_1009_ucs4(assign_values, TestCase): <add>class TestAssignValues_1009_UCS4(AssignValues): <ide> """Check the assignment of valued arrays (size 1009, UCS4 values)""" <ide> ulen = 1009 <ide> ucs_value = ucs4_value <ide> class test_assign_values_1009_ucs4(assign_values, TestCase): <ide> # Byteorder tests <ide> ############################################################ <ide> <del>class byteorder_values: <add>class ByteorderValues(object): <ide> """Check the byteorder of unicode arrays in round-trip conversions""" <ide> <ide> def test_values0D(self): <ide> def test_values0D(self): <ide> # This changes the interpretation of the data region (but not the <ide> # actual data), therefore the returned scalars are not <ide> # the same (they are byte-swapped versions of each other). <del> self.assertTrue(ua[()] != ua2[()]) <add> assert_(ua[()] != ua2[()]) <ide> ua3 = ua2.newbyteorder() <ide> # Arrays must be equal after the round-trip <ide> assert_equal(ua, ua3) <ide> def test_valuesSD(self): <ide> # Check byteorder of single-dimensional objects <ide> ua = np.array([self.ucs_value*self.ulen]*2, dtype='U%s' % self.ulen) <ide> ua2 = ua.newbyteorder() <del> self.assertTrue((ua != ua2).all()) <del> self.assertTrue(ua[-1] != ua2[-1]) <add> assert_((ua != ua2).all()) <add> assert_(ua[-1] != ua2[-1]) <ide> ua3 = ua2.newbyteorder() <ide> # Arrays must be equal after the round-trip <ide> assert_equal(ua, ua3) <ide> def test_valuesMD(self): <ide> ua = np.array([[[self.ucs_value*self.ulen]*2]*3]*4, <ide> dtype='U%s' % self.ulen) <ide> ua2 = ua.newbyteorder() <del> self.assertTrue((ua != ua2).all()) <del> self.assertTrue(ua[-1, -1, -1] != ua2[-1, -1, -1]) <add> assert_((ua != ua2).all()) <add> assert_(ua[-1, -1, -1] != ua2[-1, -1, -1]) <ide> ua3 = ua2.newbyteorder() <ide> # Arrays must be equal after the round-trip <ide> assert_equal(ua, ua3) <ide> def test_values_cast(self): <ide> test2 = np.repeat(test1, 2)[::2] <ide> for ua in (test1, test2): <ide> ua2 = ua.astype(dtype=ua.dtype.newbyteorder()) <del> self.assertTrue((ua == ua2).all()) <del> self.assertTrue(ua[-1] == ua2[-1]) <add> assert_((ua == ua2).all()) <add> assert_(ua[-1] == ua2[-1]) <ide> ua3 = ua2.astype(dtype=ua.dtype) <ide> # Arrays must be equal after the round-trip <ide> assert_equal(ua, ua3) <ide> def test_values_updowncast(self): <ide> # Cast to a longer type with zero padding <ide> longer_type = np.dtype('U%s' % (self.ulen+1)).newbyteorder() <ide> ua2 = ua.astype(dtype=longer_type) <del> self.assertTrue((ua == ua2).all()) <del> self.assertTrue(ua[-1] == ua2[-1]) <add> assert_((ua == ua2).all()) <add> assert_(ua[-1] == ua2[-1]) <ide> # Cast back again with truncating: <ide> ua3 = ua2.astype(dtype=ua.dtype) <ide> # Arrays must be equal after the round-trip <ide> assert_equal(ua, ua3) <ide> <ide> <del>class test_byteorder_1_ucs2(byteorder_values, TestCase): <add>class TestByteorder_1_UCS2(ByteorderValues): <ide> """Check the byteorder in unicode (size 1, UCS2 values)""" <ide> ulen = 1 <ide> ucs_value = ucs2_value <ide> <ide> <del>class test_byteorder_1_ucs4(byteorder_values, TestCase): <add>class TestByteorder_1_UCS4(ByteorderValues): <ide> """Check the byteorder in unicode (size 1, UCS4 values)""" <ide> ulen = 1 <ide> ucs_value = ucs4_value <ide> <ide> <del>class test_byteorder_2_ucs2(byteorder_values, TestCase): <add>class TestByteorder_2_UCS2(ByteorderValues): <ide> """Check the byteorder in unicode (size 2, UCS2 values)""" <ide> ulen = 2 <ide> ucs_value = ucs2_value <ide> <ide> <del>class test_byteorder_2_ucs4(byteorder_values, TestCase): <add>class TestByteorder_2_UCS4(ByteorderValues): <ide> """Check the byteorder in unicode (size 2, UCS4 values)""" <ide> ulen = 2 <ide> ucs_value = ucs4_value <ide> <ide> <del>class test_byteorder_1009_ucs2(byteorder_values, TestCase): <add>class TestByteorder_1009_UCS2(ByteorderValues): <ide> """Check the byteorder in unicode (size 1009, UCS2 values)""" <ide> ulen = 1009 <ide> ucs_value = ucs2_value <ide> <ide> <del>class test_byteorder_1009_ucs4(byteorder_values, TestCase): <add>class TestByteorder_1009_UCS4(ByteorderValues): <ide> """Check the byteorder in unicode (size 1009, UCS4 values)""" <ide> ulen = 1009 <ide> ucs_value = ucs4_value
30
PHP
PHP
extend controller by default
0cd9ee1e90b66bdb2a3e4c385fa4b416e3ca8afa
<ide><path>app/Http/Controllers/Auth/AuthController.php <ide> <?php namespace App\Http\Controllers\Auth; <ide> <add>use Illuminate\Routing\Controller; <ide> use Illuminate\Contracts\Auth\Guard; <del> <ide> use App\Http\Requests\Auth\LoginRequest; <ide> use App\Http\Requests\Auth\RegisterRequest; <ide> <ide> /** <ide> * @Middleware("guest", except={"logout"}) <ide> */ <del>class AuthController { <add>class AuthController extends Controller { <ide> <ide> /** <ide> * The Guard implementation. <ide><path>app/Http/Controllers/Auth/PasswordController.php <ide> <?php namespace App\Http\Controllers\Auth; <ide> <ide> use Illuminate\Http\Request; <add>use Illuminate\Routing\Controller; <ide> use Illuminate\Contracts\Auth\PasswordBroker; <ide> use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; <ide> <ide> /** <ide> * @Middleware("guest") <ide> */ <del>class PasswordController { <add>class PasswordController extends Controller { <ide> <ide> /** <ide> * The password broker implementation. <ide><path>app/Http/Controllers/HomeController.php <ide> <?php namespace App\Http\Controllers; <ide> <del>class HomeController { <add>use Illuminate\Routing\Controller; <add> <add>class HomeController extends Controller { <ide> <ide> /* <ide> |-------------------------------------------------------------------------- <ide><path>config/app.php <ide> 'Illuminate\Auth\AuthServiceProvider', <ide> 'Illuminate\Cache\CacheServiceProvider', <ide> 'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider', <add> 'Illuminate\Routing\ControllerServiceProvider', <ide> 'Illuminate\Cookie\CookieServiceProvider', <ide> 'Illuminate\Database\DatabaseServiceProvider', <ide> 'Illuminate\Encryption\EncryptionServiceProvider',
4
Java
Java
add enablewebreactive + webreactiveconfigurer
3533024ab87468a9edcd95e762458e6af9516ba9
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/DelegatingWebReactiveConfiguration.java <add>package org.springframework.web.reactive.config; <add> <add>import java.util.List; <add> <add>import org.springframework.beans.factory.annotation.Autowired; <add>import org.springframework.context.annotation.Configuration; <add>import org.springframework.format.FormatterRegistry; <add>import org.springframework.http.codec.HttpMessageReader; <add>import org.springframework.http.codec.HttpMessageWriter; <add>import org.springframework.util.CollectionUtils; <add>import org.springframework.validation.MessageCodesResolver; <add>import org.springframework.validation.Validator; <add>import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; <add>import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver; <add>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter; <add>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping; <add> <add>/** <add> * A subclass of {@code WebReactiveConfigurationSupport} that detects and delegates <add> * to all beans of type {@link WebReactiveConfigurer} allowing them to customize the <add> * configuration provided by {@code WebReactiveConfigurationSupport}. This is the <add> * class actually imported by {@link EnableWebReactive @EnableWebReactive}. <add> * <add> * @author Brian Clozel <add> * @since 5.0 <add> */ <add>@Configuration <add>public class DelegatingWebReactiveConfiguration extends WebReactiveConfigurationSupport { <add> <add> private final WebReactiveConfigurerComposite configurers = new WebReactiveConfigurerComposite(); <add> <add> @Autowired(required = false) <add> public void setConfigurers(List<WebReactiveConfigurer> configurers) { <add> if (!CollectionUtils.isEmpty(configurers)) { <add> this.configurers.addWebReactiveConfigurers(configurers); <add> } <add> } <add> <add> @Override <add> protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() { <add> return this.configurers.createRequestMappingHandlerMapping() <add> .orElse(super.createRequestMappingHandlerMapping()); <add> } <add> <add> @Override <add> protected void configureRequestedContentTypeResolver(RequestedContentTypeResolverBuilder builder) { <add> this.configurers.configureRequestedContentTypeResolver(builder); <add> } <add> <add> @Override <add> protected void addCorsMappings(CorsRegistry registry) { <add> this.configurers.addCorsMappings(registry); <add> } <add> <add> @Override <add> public void configurePathMatching(PathMatchConfigurer configurer) { <add> this.configurers.configurePathMatching(configurer); <add> } <add> <add> @Override <add> protected void addResourceHandlers(ResourceHandlerRegistry registry) { <add> this.configurers.addResourceHandlers(registry); <add> } <add> <add> @Override <add> protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() { <add> return this.configurers.createRequestMappingHandlerAdapter() <add> .orElse(super.createRequestMappingHandlerAdapter()); <add> } <add> <add> @Override <add> protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { <add> this.configurers.addArgumentResolvers(resolvers); <add> } <add> <add> @Override <add> protected void configureMessageReaders(List<HttpMessageReader<?>> messageReaders) { <add> this.configurers.configureMessageReaders(messageReaders); <add> } <add> <add> @Override <add> protected void extendMessageReaders(List<HttpMessageReader<?>> messageReaders) { <add> this.configurers.extendMessageReaders(messageReaders); <add> } <add> <add> @Override <add> protected void addFormatters(FormatterRegistry registry) { <add> this.configurers.addFormatters(registry); <add> } <add> <add> @Override <add> protected Validator getValidator() { <add> return this.configurers.getValidator().orElse(super.getValidator()); <add> } <add> <add> @Override <add> protected MessageCodesResolver getMessageCodesResolver() { <add> return this.configurers.getMessageCodesResolver().orElse(super.getMessageCodesResolver()); <add> } <add> <add> @Override <add> protected void configureMessageWriters(List<HttpMessageWriter<?>> messageWriters) { <add> this.configurers.configureMessageWriters(messageWriters); <add> } <add> <add> @Override <add> protected void extendMessageWriters(List<HttpMessageWriter<?>> messageWriters) { <add> this.configurers.extendMessageWriters(messageWriters); <add> } <add> <add> @Override <add> protected void configureViewResolvers(ViewResolverRegistry registry) { <add> this.configurers.configureViewResolvers(registry); <add> } <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/EnableWebReactive.java <add>package org.springframework.web.reactive.config; <add> <add>import java.lang.annotation.Documented; <add>import java.lang.annotation.ElementType; <add>import java.lang.annotation.Retention; <add>import java.lang.annotation.RetentionPolicy; <add>import java.lang.annotation.Target; <add> <add>import org.springframework.context.annotation.Import; <add> <add>/** <add> * Adding this annotation to an {@code @Configuration} class imports the Spring Web <add> * Reactive configuration from {@link WebReactiveConfigurationSupport}, e.g.: <add> * <add> * <pre class="code"> <add> * &#064;Configuration <add> * &#064;EnableWebReactive <add> * &#064;ComponentScan(basePackageClasses = { MyConfiguration.class }) <add> * public class MyWebConfiguration { <add> * <add> * } <add> * </pre> <add> * <add> * <p>To customize the imported configuration, implement the interface <add> * {@link WebReactiveConfigurer} and override individual methods, e.g.: <add> * <add> * <pre class="code"> <add> * &#064;Configuration <add> * &#064;EnableWebMvc <add> * &#064;ComponentScan(basePackageClasses = { MyConfiguration.class }) <add> * public class MyConfiguration implements WebReactiveConfigurer { <add> * <add> * &#064;Override <add> * public void addFormatters(FormatterRegistry formatterRegistry) { <add> * formatterRegistry.addConverter(new MyConverter()); <add> * } <add> * <add> * &#064;Override <add> * public void configureMessageWriters(List&lt;HttpMessageWriter&lt;?&gt&gt messageWriters) { <add> * messageWriters.add(new MyHttpMessageWriter()); <add> * } <add> * <add> * // More overridden methods ... <add> * } <add> * </pre> <add> * <add> * <p>If {@link WebReactiveConfigurer} does not expose some advanced setting that <add> * needs to be configured, consider removing the {@code @EnableWebReactive} <add> * annotation and extending directly from {@link WebReactiveConfigurationSupport} <add> * or {@link DelegatingWebReactiveConfiguration}, e.g.: <add> * <add> * <pre class="code"> <add> * &#064;Configuration <add> * &#064;ComponentScan(basePackageClasses = { MyConfiguration.class }) <add> * public class MyConfiguration extends WebReactiveConfigurationSupport { <add> * <add> * &#064;Override <add> * public void addFormatters(FormatterRegistry formatterRegistry) { <add> * formatterRegistry.addConverter(new MyConverter()); <add> * } <add> * <add> * &#064;Bean <add> * public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { <add> * // Create or delegate to "super" to create and <add> * // customize properties of RequestMappingHandlerAdapter <add> * } <add> * } <add> * </pre> <add> * <add> * @author Brian Clozel <add> * @since 5.0 <add> * @see WebReactiveConfigurer <add> * @see WebReactiveConfigurationSupport <add> */ <add>@Retention(RetentionPolicy.RUNTIME) <add>@Target(ElementType.TYPE) <add>@Documented <add>@Import(DelegatingWebReactiveConfiguration.class) <add>public @interface EnableWebReactive { <add>} <add><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfigurationSupport.java <del><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.context.annotation.Bean; <del>import org.springframework.context.annotation.Configuration; <ide> import org.springframework.core.codec.ByteBufferDecoder; <ide> import org.springframework.core.codec.ByteBufferEncoder; <ide> import org.springframework.core.codec.CharSequenceEncoder; <ide> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> */ <del>@Configuration <del>public class WebReactiveConfiguration implements ApplicationContextAware { <add>public class WebReactiveConfigurationSupport implements ApplicationContextAware { <ide> <ide> private static final boolean jackson2Present = <ide> ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", <del> WebReactiveConfiguration.class.getClassLoader()) && <add> WebReactiveConfigurationSupport.class.getClassLoader()) && <ide> ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", <del> WebReactiveConfiguration.class.getClassLoader()); <add> WebReactiveConfigurationSupport.class.getClassLoader()); <ide> <ide> private static final boolean jaxb2Present = <del> ClassUtils.isPresent("javax.xml.bind.Binder", WebReactiveConfiguration.class.getClassLoader()); <add> ClassUtils.isPresent("javax.xml.bind.Binder", WebReactiveConfigurationSupport.class.getClassLoader()); <ide> <ide> <ide> private Map<String, CorsConfiguration> corsConfigurations; <ide> public HandlerMapping resourceHandlerMapping() { <ide> if (pathMatchConfigurer.getPathHelper() != null) { <ide> handlerMapping.setPathHelper(pathMatchConfigurer.getPathHelper()); <ide> } <del> <ide> } <ide> else { <ide> handlerMapping = new EmptyHandlerMapping(); <ide> protected final void addDefaultHttpMessageWriters(List<HttpMessageWriter<?>> wri <ide> writers.add(new ServerSentEventHttpMessageWriter(sseDataEncoders)); <ide> } <ide> } <add> <ide> /** <ide> * Override this to modify the list of message writers after it has been <ide> * configured, for example to add some in addition to the default ones. <ide> public ViewResolutionResultHandler viewResolutionResultHandler() { <ide> } <ide> <ide> /** <del> * Override this to configure view resolution. <add> * Configure view resolution for supporting template engines. <add> * @see ViewResolverRegistry <ide> */ <ide> protected void configureViewResolvers(ViewResolverRegistry registry) { <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfigurer.java <add>package org.springframework.web.reactive.config; <add> <add>import java.util.List; <add>import java.util.Optional; <add> <add>import org.springframework.core.convert.converter.Converter; <add>import org.springframework.format.Formatter; <add>import org.springframework.format.FormatterRegistry; <add>import org.springframework.http.codec.HttpMessageReader; <add>import org.springframework.http.codec.HttpMessageWriter; <add>import org.springframework.validation.MessageCodesResolver; <add>import org.springframework.validation.Validator; <add>import org.springframework.web.reactive.accept.CompositeContentTypeResolver; <add>import org.springframework.web.reactive.accept.RequestedContentTypeResolver; <add>import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; <add>import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver; <add>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter; <add>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping; <add> <add>/** <add> * Defines callback methods to customize the configuration for Web Reactive <add> * applications enabled via {@code @EnableWebReactive}. <add> * <add> * <p>{@code @EnableWebReactive}-annotated configuration classes may implement <add> * this interface to be called back and given a chance to customize the <add> * default configuration. Consider implementing this interface and <add> * overriding the relevant methods for your needs. <add> * <add> * @author Brian Clozel <add> * @since 5.0 <add> */ <add>public interface WebReactiveConfigurer { <add> <add> /** <add> * Provide a custom sub-class of {@link RequestMappingHandlerMapping} <add> * instead of the one created by default. <add> * The default implementation returns {@code Optional.empty()}. <add> */ <add> default Optional<RequestMappingHandlerMapping> createRequestMappingHandlerMapping() { <add> return Optional.empty(); <add> } <add> <add> /** <add> * Configure how the requested content type is resolved. <add> * <p>The given builder will create a composite of multiple <add> * {@link RequestedContentTypeResolver}s, each defining a way to resolve the <add> * the requested content type (accept HTTP header, path extension, parameter, etc). <add> * @param builder factory that creates a {@link CompositeContentTypeResolver} instance <add> */ <add> default void configureRequestedContentTypeResolver(RequestedContentTypeResolverBuilder builder) { <add> } <add> <add> /** <add> * Configure cross origin requests processing. <add> * @see CorsRegistry <add> */ <add> default void addCorsMappings(CorsRegistry registry) { <add> } <add> <add> /** <add> * Configure path matching options. <add> * <p>The given configurer assists with configuring <add> * {@code HandlerMapping}s with path matching options. <add> * @param configurer the {@link PathMatchConfigurer} instance <add> */ <add> default void configurePathMatching(PathMatchConfigurer configurer) { <add> } <add> <add> /** <add> * Add resource handlers for serving static resources. <add> * @see ResourceHandlerRegistry <add> */ <add> default void addResourceHandlers(ResourceHandlerRegistry registry) { <add> } <add> <add> /** <add> * Provide a custom sub-class of {@link RequestMappingHandlerAdapter} <add> * instead of the one created by default. <add> * The default implementation returns {@code Optional.empty()}. <add> */ <add> default Optional<RequestMappingHandlerAdapter> createRequestMappingHandlerAdapter() { <add> return Optional.empty(); <add> } <add> <add> /** <add> * Provide custom argument resolvers without overriding the built-in ones. <add> * @param resolvers a list of resolvers to add to the built-in ones <add> */ <add> default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { <add> } <add> <add> /** <add> * Configure the message readers to use for decoding controller method arguments. <add> * <p>If no message readers are specified, default readers will be added via <add> * {@link WebReactiveConfigurationSupport#addDefaultHttpMessageReaders}. <add> * @param messageReaders a list to add message readers to, initially an empty list <add> */ <add> default void configureMessageReaders(List<HttpMessageReader<?>> messageReaders) { <add> } <add> <add> /** <add> * Modify the list of message readers to use for decoding controller method arguments, <add> * for example to add some in addition to the ones already configured. <add> */ <add> default void extendMessageReaders(List<HttpMessageReader<?>> messageReaders) { <add> } <add> <add> /** <add> * Add custom {@link Converter}s and {@link Formatter}s. <add> */ <add> default void addFormatters(FormatterRegistry registry) { <add> } <add> <add> /** <add> * Provide a custom {@link Validator}, instead of the instance configured by default. <add> * <p>Only a single instance is allowed, an error will be thrown if multiple <add> * {@code Validator}s are returned by {@code WebReactiveConfigurer}s. <add> * The default implementation returns {@code Optional.empty()}. <add> */ <add> default Optional<Validator> getValidator() { <add> return Optional.empty(); <add> } <add> <add> /** <add> * Provide a custom {@link MessageCodesResolver}, instead of using the one <add> * provided by {@link org.springframework.validation.DataBinder} instances. <add> * The default implementation returns {@code Optional.empty()}. <add> */ <add> default Optional<MessageCodesResolver> getMessageCodesResolver() { <add> return Optional.empty(); <add> } <add> <add> /** <add> * Configure the message writers to use for encoding return values. <add> * <p>If no message writers are specified, default writers will be added via <add> * {@link WebReactiveConfigurationSupport#addDefaultHttpMessageWriters(List)}. <add> * @param messageWriters a list to add message writers to, initially an empty list <add> */ <add> default void configureMessageWriters(List<HttpMessageWriter<?>> messageWriters) { <add> } <add> <add> /** <add> * Modify the list of message writers to use for encoding return values, <add> * for example to add some in addition to the ones already configured. <add> */ <add> default void extendMessageWriters(List<HttpMessageWriter<?>> messageWriters) { <add> } <add> <add> /** <add> * Configure view resolution for supporting template engines. <add> * @see ViewResolverRegistry <add> */ <add> default void configureViewResolvers(ViewResolverRegistry registry) { <add> } <add> <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfigurerComposite.java <add>package org.springframework.web.reactive.config; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add>import java.util.Optional; <add> <add>import org.springframework.format.FormatterRegistry; <add>import org.springframework.http.codec.HttpMessageReader; <add>import org.springframework.http.codec.HttpMessageWriter; <add>import org.springframework.util.CollectionUtils; <add>import org.springframework.validation.MessageCodesResolver; <add>import org.springframework.validation.Validator; <add>import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; <add>import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver; <add>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter; <add>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping; <add> <add>/** <add> * A {@link WebReactiveConfigurer} that delegates to one or more others. <add> * <add> * @author Brian Clozel <add> * @since 5.0 <add> */ <add>public class WebReactiveConfigurerComposite implements WebReactiveConfigurer { <add> <add> private final List<WebReactiveConfigurer> delegates = new ArrayList<>(); <add> <add> public void addWebReactiveConfigurers(List<WebReactiveConfigurer> configurers) { <add> if (!CollectionUtils.isEmpty(configurers)) { <add> this.delegates.addAll(configurers); <add> } <add> } <add> <add> @Override <add> public Optional<RequestMappingHandlerMapping> createRequestMappingHandlerMapping() { <add> Optional<RequestMappingHandlerMapping> selected = Optional.empty(); <add> for (WebReactiveConfigurer configurer : this.delegates) { <add> Optional<RequestMappingHandlerMapping> handlerMapping = configurer.createRequestMappingHandlerMapping(); <add> if (handlerMapping.isPresent()) { <add> if (selected != null) { <add> throw new IllegalStateException("No unique RequestMappingHandlerMapping found: {" + <add> selected.get() + ", " + handlerMapping.get() + "}"); <add> } <add> selected = handlerMapping; <add> } <add> } <add> return selected; <add> } <add> <add> @Override <add> public void configureRequestedContentTypeResolver(RequestedContentTypeResolverBuilder builder) { <add> this.delegates.stream().forEach(delegate -> delegate.configureRequestedContentTypeResolver(builder)); <add> } <add> <add> @Override <add> public void addCorsMappings(CorsRegistry registry) { <add> this.delegates.stream().forEach(delegate -> delegate.addCorsMappings(registry)); <add> } <add> <add> @Override <add> public void configurePathMatching(PathMatchConfigurer configurer) { <add> this.delegates.stream().forEach(delegate -> delegate.configurePathMatching(configurer)); <add> } <add> <add> @Override <add> public void addResourceHandlers(ResourceHandlerRegistry registry) { <add> this.delegates.stream().forEach(delegate -> delegate.addResourceHandlers(registry)); <add> } <add> <add> @Override <add> public Optional<RequestMappingHandlerAdapter> createRequestMappingHandlerAdapter() { <add> Optional<RequestMappingHandlerAdapter> selected = Optional.empty(); <add> for (WebReactiveConfigurer configurer : this.delegates) { <add> Optional<RequestMappingHandlerAdapter> handlerAdapter = configurer.createRequestMappingHandlerAdapter(); <add> if (handlerAdapter.isPresent()) { <add> if (selected != null) { <add> throw new IllegalStateException("No unique RequestMappingHandlerAdapter found: {" + <add> selected.get() + ", " + handlerAdapter.get() + "}"); <add> } <add> selected = handlerAdapter; <add> } <add> } <add> return selected; <add> } <add> <add> @Override <add> public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { <add> this.delegates.stream().forEach(delegate -> delegate.addArgumentResolvers(resolvers)); <add> } <add> <add> @Override <add> public void configureMessageReaders(List<HttpMessageReader<?>> messageReaders) { <add> this.delegates.stream().forEach(delegate -> delegate.configureMessageReaders(messageReaders)); <add> } <add> <add> @Override <add> public void extendMessageReaders(List<HttpMessageReader<?>> messageReaders) { <add> this.delegates.stream().forEach(delegate -> delegate.extendMessageReaders(messageReaders)); <add> } <add> <add> @Override <add> public void addFormatters(FormatterRegistry registry) { <add> this.delegates.stream().forEach(delegate -> delegate.addFormatters(registry)); <add> } <add> <add> @Override <add> public Optional<Validator> getValidator() { <add> Optional<Validator> selected = Optional.empty(); <add> for (WebReactiveConfigurer configurer : this.delegates) { <add> Optional<Validator> validator = configurer.getValidator(); <add> if (validator.isPresent()) { <add> if (selected != null) { <add> throw new IllegalStateException("No unique Validator found: {" + <add> selected.get() + ", " + validator.get() + "}"); <add> } <add> selected = validator; <add> } <add> } <add> return selected; <add> } <add> <add> @Override <add> public Optional<MessageCodesResolver> getMessageCodesResolver() { <add> Optional<MessageCodesResolver> selected = Optional.empty(); <add> for (WebReactiveConfigurer configurer : this.delegates) { <add> Optional<MessageCodesResolver> messageCodesResolver = configurer.getMessageCodesResolver(); <add> if (messageCodesResolver.isPresent()) { <add> if (selected != null) { <add> throw new IllegalStateException("No unique MessageCodesResolver found: {" + <add> selected.get() + ", " + messageCodesResolver.get() + "}"); <add> } <add> selected = messageCodesResolver; <add> } <add> } <add> return selected; <add> } <add> <add> @Override <add> public void configureMessageWriters(List<HttpMessageWriter<?>> messageWriters) { <add> this.delegates.stream().forEach(delegate -> delegate.configureMessageWriters(messageWriters)); <add> } <add> <add> @Override <add> public void extendMessageWriters(List<HttpMessageWriter<?>> messageWriters) { <add> this.delegates.stream().forEach(delegate -> delegate.extendMessageWriters(messageWriters)); <add> } <add> <add> @Override <add> public void configureViewResolvers(ViewResolverRegistry registry) { <add> this.delegates.stream().forEach(delegate -> delegate.configureViewResolvers(registry)); <add> } <add>} <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/config/DelegatingWebReactiveConfigurationTests.java <add>package org.springframework.web.reactive.config; <add> <add>import java.util.Collections; <add>import java.util.List; <add>import java.util.Optional; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.mockito.ArgumentCaptor; <add>import org.mockito.Captor; <add>import org.mockito.Mock; <add>import org.mockito.MockitoAnnotations; <add> <add>import org.springframework.context.support.StaticApplicationContext; <add>import org.springframework.core.convert.ConversionService; <add>import org.springframework.format.FormatterRegistry; <add>import org.springframework.http.codec.HttpMessageReader; <add>import org.springframework.http.codec.HttpMessageWriter; <add>import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; <add>import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; <add>import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; <add>import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter; <add> <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertSame; <add>import static org.junit.Assert.assertTrue; <add>import static org.mockito.BDDMockito.given; <add>import static org.mockito.Matchers.any; <add>import static org.mockito.Mockito.doAnswer; <add>import static org.mockito.Mockito.verify; <add> <add>/** <add> * Test fixture for {@link DelegatingWebReactiveConfiguration} tests. <add> * <add> * @author Brian Clozel <add> */ <add>public class DelegatingWebReactiveConfigurationTests { <add> <add> private DelegatingWebReactiveConfiguration delegatingConfig; <add> <add> @Mock <add> private WebReactiveConfigurer webReactiveConfigurer; <add> <add> @Captor <add> private ArgumentCaptor<List<HttpMessageReader<?>>> readers; <add> <add> @Captor <add> private ArgumentCaptor<List<HttpMessageWriter<?>>> writers; <add> <add> @Captor <add> private ArgumentCaptor<FormatterRegistry> formatterRegistry; <add> <add> <add> @Before <add> public void setUp() { <add> MockitoAnnotations.initMocks(this); <add> delegatingConfig = new DelegatingWebReactiveConfiguration(); <add> delegatingConfig.setApplicationContext(new StaticApplicationContext()); <add> given(webReactiveConfigurer.createRequestMappingHandlerMapping()).willReturn(Optional.empty()); <add> given(webReactiveConfigurer.createRequestMappingHandlerAdapter()).willReturn(Optional.empty()); <add> given(webReactiveConfigurer.getValidator()).willReturn(Optional.empty()); <add> given(webReactiveConfigurer.getMessageCodesResolver()).willReturn(Optional.empty()); <add> } <add> <add> @Test <add> public void requestMappingHandlerAdapter() throws Exception { <add> delegatingConfig.setConfigurers(Collections.singletonList(webReactiveConfigurer)); <add> RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter(); <add> <add> ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); <add> ConversionService initializerConversionService = initializer.getConversionService(); <add> assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean); <add> <add> verify(webReactiveConfigurer).createRequestMappingHandlerAdapter(); <add> verify(webReactiveConfigurer).configureMessageReaders(readers.capture()); <add> verify(webReactiveConfigurer).extendMessageReaders(readers.capture()); <add> verify(webReactiveConfigurer).getValidator(); <add> verify(webReactiveConfigurer).getMessageCodesResolver(); <add> verify(webReactiveConfigurer).addFormatters(formatterRegistry.capture()); <add> verify(webReactiveConfigurer).addArgumentResolvers(any()); <add> <add> assertSame(formatterRegistry.getValue(), initializerConversionService); <add> assertEquals(5, readers.getValue().size()); <add> } <add> <add> @Test <add> public void requestMappingHandlerMapping() throws Exception { <add> delegatingConfig.setConfigurers(Collections.singletonList(webReactiveConfigurer)); <add> delegatingConfig.requestMappingHandlerMapping(); <add> <add> verify(webReactiveConfigurer).createRequestMappingHandlerMapping(); <add> verify(webReactiveConfigurer).configureRequestedContentTypeResolver(any(RequestedContentTypeResolverBuilder.class)); <add> verify(webReactiveConfigurer).addCorsMappings(any(CorsRegistry.class)); <add> verify(webReactiveConfigurer).configurePathMatching(any(PathMatchConfigurer.class)); <add> } <add> <add> @Test <add> public void resourceHandlerMapping() throws Exception { <add> delegatingConfig.setConfigurers(Collections.singletonList(webReactiveConfigurer)); <add> doAnswer(invocation -> { <add> ResourceHandlerRegistry registry = invocation.getArgumentAt(0, ResourceHandlerRegistry.class); <add> registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static"); <add> return null; <add> }).when(webReactiveConfigurer).addResourceHandlers(any(ResourceHandlerRegistry.class)); <add> <add> delegatingConfig.resourceHandlerMapping(); <add> verify(webReactiveConfigurer).addResourceHandlers(any(ResourceHandlerRegistry.class)); <add> verify(webReactiveConfigurer).configurePathMatching(any(PathMatchConfigurer.class)); <add> } <add> <add> @Test <add> public void responseBodyResultHandler() throws Exception { <add> delegatingConfig.setConfigurers(Collections.singletonList(webReactiveConfigurer)); <add> delegatingConfig.responseBodyResultHandler(); <add> <add> verify(webReactiveConfigurer).configureMessageWriters(writers.capture()); <add> verify(webReactiveConfigurer).extendMessageWriters(writers.capture()); <add> verify(webReactiveConfigurer).configureRequestedContentTypeResolver(any(RequestedContentTypeResolverBuilder.class)); <add> } <add> <add> @Test <add> public void viewResolutionResultHandler() throws Exception { <add> delegatingConfig.setConfigurers(Collections.singletonList(webReactiveConfigurer)); <add> delegatingConfig.viewResolutionResultHandler(); <add> <add> verify(webReactiveConfigurer).configureViewResolvers(any(ViewResolverRegistry.class)); <add> } <add>} <add><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/config/WebReactiveConfigurationSupportTests.java <del><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/config/WebReactiveConfigurationTests.java <ide> import static org.springframework.http.MediaType.TEXT_PLAIN; <ide> <ide> /** <del> * Unit tests for {@link WebReactiveConfiguration}. <add> * Unit tests for {@link WebReactiveConfigurationSupport}. <ide> * @author Rossen Stoyanchev <ide> */ <del>public class WebReactiveConfigurationTests { <add>public class WebReactiveConfigurationSupportTests { <ide> <ide> private MockServerHttpRequest request; <ide> <ide> public void setUp() throws Exception { <ide> <ide> @Test <ide> public void requestMappingHandlerMapping() throws Exception { <del> ApplicationContext context = loadConfig(WebReactiveConfiguration.class); <add> ApplicationContext context = loadConfig(WebReactiveConfig.class); <ide> <ide> String name = "requestMappingHandlerMapping"; <ide> RequestMappingHandlerMapping mapping = context.getBean(name, RequestMappingHandlerMapping.class); <ide> public void customPathMatchConfig() throws Exception { <ide> <ide> @Test <ide> public void requestMappingHandlerAdapter() throws Exception { <del> ApplicationContext context = loadConfig(WebReactiveConfiguration.class); <add> ApplicationContext context = loadConfig(WebReactiveConfig.class); <ide> <ide> String name = "requestMappingHandlerAdapter"; <del> RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class); <add> RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class); <ide> assertNotNull(adapter); <ide> <ide> List<HttpMessageReader<?>> readers = adapter.getMessageReaders(); <ide> public void customMessageConverterConfig() throws Exception { <ide> <ide> @Test <ide> public void responseEntityResultHandler() throws Exception { <del> ApplicationContext context = loadConfig(WebReactiveConfiguration.class); <add> ApplicationContext context = loadConfig(WebReactiveConfig.class); <ide> <ide> String name = "responseEntityResultHandler"; <ide> ResponseEntityResultHandler handler = context.getBean(name, ResponseEntityResultHandler.class); <ide> public void responseEntityResultHandler() throws Exception { <ide> <ide> @Test <ide> public void responseBodyResultHandler() throws Exception { <del> ApplicationContext context = loadConfig(WebReactiveConfiguration.class); <add> ApplicationContext context = loadConfig(WebReactiveConfig.class); <ide> <ide> String name = "responseBodyResultHandler"; <ide> ResponseBodyResultHandler handler = context.getBean(name, ResponseBodyResultHandler.class); <ide> public void resourceHandler() throws Exception { <ide> AbstractHandlerMapping handlerMapping = context.getBean(name, AbstractHandlerMapping.class); <ide> assertNotNull(handlerMapping); <ide> <del> assertEquals(Ordered.LOWEST_PRECEDENCE -1, handlerMapping.getOrder()); <add> assertEquals(Ordered.LOWEST_PRECEDENCE - 1, handlerMapping.getOrder()); <ide> <ide> assertNotNull(handlerMapping.getPathHelper()); <ide> assertNotNull(handlerMapping.getPathMatcher()); <ide> private ApplicationContext loadConfig(Class<?>... configurationClasses) { <ide> return context; <ide> } <ide> <add> @EnableWebReactive <add> static class WebReactiveConfig { <add> } <ide> <ide> @Configuration <del> static class CustomPatchMatchConfig extends WebReactiveConfiguration { <add> static class CustomPatchMatchConfig extends WebReactiveConfigurationSupport { <ide> <ide> @Override <ide> public void configurePathMatching(PathMatchConfigurer configurer) { <ide> public void configurePathMatching(PathMatchConfigurer configurer) { <ide> } <ide> <ide> @Configuration <del> static class CustomMessageConverterConfig extends WebReactiveConfiguration { <add> static class CustomMessageConverterConfig extends WebReactiveConfigurationSupport { <ide> <ide> @Override <ide> protected void configureMessageReaders(List<HttpMessageReader<?>> messageReaders) { <ide> protected void extendMessageWriters(List<HttpMessageWriter<?>> messageWriters) { <ide> } <ide> } <ide> <del> @Configuration @SuppressWarnings("unused") <del> static class CustomViewResolverConfig extends WebReactiveConfiguration { <add> @Configuration <add> @SuppressWarnings("unused") <add> static class CustomViewResolverConfig extends WebReactiveConfigurationSupport { <ide> <ide> @Override <ide> protected void configureViewResolvers(ViewResolverRegistry registry) { <ide> public FreeMarkerConfigurer freeMarkerConfig() { <ide> } <ide> <ide> @Configuration <del> static class CustomResourceHandlingConfig extends WebReactiveConfiguration { <add> static class CustomResourceHandlingConfig extends WebReactiveConfigurationSupport { <ide> <ide> @Override <ide> protected void addResourceHandlers(ResourceHandlerRegistry registry) { <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/function/DispatcherHandlerIntegrationTests.java <ide> import org.springframework.web.reactive.DispatcherHandler; <ide> import org.springframework.web.reactive.HandlerAdapter; <ide> import org.springframework.web.reactive.HandlerMapping; <del>import org.springframework.web.reactive.config.WebReactiveConfiguration; <add>import org.springframework.web.reactive.config.WebReactiveConfigurationSupport; <ide> import org.springframework.web.reactive.function.support.HandlerFunctionAdapter; <ide> import org.springframework.web.reactive.function.support.ResponseResultHandler; <ide> import org.springframework.web.reactive.result.view.ViewResolver; <ide> public void flux() throws Exception { <ide> <ide> <ide> @Configuration <del> static class TestConfiguration extends WebReactiveConfiguration { <add> static class TestConfiguration extends WebReactiveConfigurationSupport { <ide> <ide> @Bean <ide> public PersonHandler personHandler() { <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/CrossOriginAnnotationIntegrationTests.java <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> import org.springframework.web.bind.annotation.RestController; <ide> import org.springframework.web.client.RestTemplate; <del>import org.springframework.web.reactive.config.WebReactiveConfiguration; <add>import org.springframework.web.reactive.config.EnableWebReactive; <ide> <ide> import static org.junit.Assert.assertArrayEquals; <ide> import static org.junit.Assert.assertEquals; <ide> public void ambiguousProducesPreflightRequest() throws Exception { <ide> <ide> <ide> @Configuration <add> @EnableWebReactive <ide> @ComponentScan(resourcePattern = "**/CrossOriginAnnotationIntegrationTests*") <ide> @SuppressWarnings({"unused", "WeakerAccess"}) <del> static class WebConfig extends WebReactiveConfiguration { <add> static class WebConfig { <ide> } <ide> <ide> @RestController @SuppressWarnings("unused") <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/GlobalCorsConfigIntegrationTests.java <ide> import org.springframework.web.client.HttpClientErrorException; <ide> import org.springframework.web.client.RestTemplate; <ide> import org.springframework.web.reactive.config.CorsRegistry; <del>import org.springframework.web.reactive.config.WebReactiveConfiguration; <add>import org.springframework.web.reactive.config.WebReactiveConfigurationSupport; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertNull; <ide> public void preFlightRequestWithoutCorsEnabled() throws Exception { <ide> @Configuration <ide> @ComponentScan(resourcePattern = "**/GlobalCorsConfigIntegrationTests*.class") <ide> @SuppressWarnings({"unused", "WeakerAccess"}) <del> static class WebConfig extends WebReactiveConfiguration { <add> static class WebConfig extends WebReactiveConfigurationSupport { <ide> <ide> @Override <ide> protected void addCorsMappings(CorsRegistry registry) { <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/JacksonHintsIntegrationTests.java <ide> import org.springframework.web.bind.annotation.PostMapping; <ide> import org.springframework.web.bind.annotation.RequestBody; <ide> import org.springframework.web.bind.annotation.RestController; <del>import org.springframework.web.reactive.config.WebReactiveConfiguration; <add>import org.springframework.web.reactive.config.EnableWebReactive; <ide> <ide> /** <ide> * @author Sebastien Deleuze <ide> public void jsonViewWithFluxRequest() throws Exception { <ide> <ide> @Configuration <ide> @ComponentScan(resourcePattern = "**/JacksonHintsIntegrationTests*.class") <add> @EnableWebReactive <ide> @SuppressWarnings({"unused", "WeakerAccess"}) <del> static class WebConfig extends WebReactiveConfiguration { <add> static class WebConfig { <ide> } <ide> <ide> @RestController <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingExceptionHandlingIntegrationTests.java <ide> import org.springframework.web.bind.annotation.ExceptionHandler; <ide> import org.springframework.web.bind.annotation.GetMapping; <ide> import org.springframework.web.bind.annotation.RestController; <del>import org.springframework.web.reactive.config.WebReactiveConfiguration; <add>import org.springframework.web.reactive.config.EnableWebReactive; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> <ide> public void controllerReturnsMonoError() throws Exception { <ide> <ide> <ide> @Configuration <add> @EnableWebReactive <ide> @ComponentScan(resourcePattern = "**/RequestMappingExceptionHandlingIntegrationTests$*.class") <ide> @SuppressWarnings({"unused", "WeakerAccess"}) <del> static class WebConfig extends WebReactiveConfiguration { <add> static class WebConfig { <ide> <ide> } <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingIntegrationTests.java <ide> import org.springframework.web.bind.annotation.GetMapping; <ide> import org.springframework.web.bind.annotation.RequestParam; <ide> import org.springframework.web.bind.annotation.RestController; <del>import org.springframework.web.reactive.config.WebReactiveConfiguration; <add>import org.springframework.web.reactive.config.EnableWebReactive; <ide> <ide> import static org.junit.Assert.assertArrayEquals; <ide> import static org.junit.Assert.assertEquals; <ide> public void objectStreamResultWithAllMediaType() throws Exception { <ide> <ide> <ide> @Configuration <add> @EnableWebReactive <ide> @ComponentScan(resourcePattern = "**/RequestMappingIntegrationTests$*.class") <ide> @SuppressWarnings({"unused", "WeakerAccess"}) <del> static class WebConfig extends WebReactiveConfiguration { <add> static class WebConfig { <ide> } <ide> <ide> @RestController <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java <ide> import org.springframework.web.bind.annotation.RequestBody; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RestController; <del>import org.springframework.web.reactive.config.WebReactiveConfiguration; <add>import org.springframework.web.reactive.config.EnableWebReactive; <ide> <del>import static java.util.Arrays.*; <del>import static org.junit.Assert.*; <del>import static org.springframework.http.MediaType.*; <add>import static java.util.Arrays.asList; <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertTrue; <add>import static org.springframework.http.MediaType.APPLICATION_XML; <ide> <ide> /** <ide> * {@code @RequestMapping} integration tests focusing on serialization and <ide> public void personCreateWithFlowableXml() throws Exception { <ide> <ide> <ide> @Configuration <add> @EnableWebReactive <ide> @ComponentScan(resourcePattern = "**/RequestMappingMessageConversionIntegrationTests$*.class") <ide> @SuppressWarnings({"unused", "WeakerAccess"}) <del> static class WebConfig extends WebReactiveConfiguration { <add> static class WebConfig { <ide> } <ide> <ide> <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingViewResolutionIntegrationTests.java <ide> import org.springframework.web.bind.annotation.GetMapping; <ide> import org.springframework.web.bind.annotation.RequestParam; <ide> import org.springframework.web.reactive.config.ViewResolverRegistry; <del>import org.springframework.web.reactive.config.WebReactiveConfiguration; <add>import org.springframework.web.reactive.config.WebReactiveConfigurationSupport; <ide> import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer; <ide> import org.springframework.web.server.ServerWebExchange; <ide> <ide> public void etagCheckWithNotModifiedResponse() throws Exception { <ide> @Configuration <ide> @ComponentScan(resourcePattern = "**/RequestMappingViewResolutionIntegrationTests$*.class") <ide> @SuppressWarnings({"unused", "WeakerAccess"}) <del> static class WebConfig extends WebReactiveConfiguration { <add> static class WebConfig extends WebReactiveConfigurationSupport { <ide> <ide> @Override <ide> protected void configureViewResolvers(ViewResolverRegistry registry) { <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/SseIntegrationTests.java <ide> import org.springframework.web.bind.annotation.RestController; <ide> import org.springframework.web.client.reactive.WebClient; <ide> import org.springframework.web.reactive.DispatcherHandler; <del>import org.springframework.web.reactive.config.WebReactiveConfiguration; <add>import org.springframework.web.reactive.config.EnableWebReactive; <ide> import org.springframework.web.server.adapter.WebHttpHandlerBuilder; <ide> <ide> import static org.springframework.web.client.reactive.ClientWebRequestBuilders.get; <ide> Flux<ServerSentEvent<String>> sse() { <ide> } <ide> <ide> @Configuration <add> @EnableWebReactive <ide> @SuppressWarnings("unused") <del> static class TestConfiguration extends WebReactiveConfiguration { <add> static class TestConfiguration { <ide> <ide> @Bean <ide> public SseController sseController() {
16
Text
Text
add type for url parameter
ed1d0241db210f484beb1cc5ee5bd191816f0048
<ide><path>docs/api-reference/next/router.md <ide> Handles client-side transitions, this method is useful for cases where [`next/li <ide> router.push(url, as, options) <ide> ``` <ide> <del>- `url` - The URL to navigate to <del>- `as` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) <add>- `url`: `UrlObject | String` - The URL to navigate to (see [Node.JS URL module documentation](https://nodejs.org/api/url.html#legacy-urlobject) for `UrlObject` properties). <add>- `as`: `UrlObject | String` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) <ide> - `options` - Optional object with the following configuration options: <ide> - `scroll` - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to `true` <ide> - [`shallow`](/docs/routing/shallow-routing.md): Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation), [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false`
1
Ruby
Ruby
fix ember-source to handle non-rcs
b0ca8033ac69e2c4e6dcdc08f036dc317079b705
<ide><path>lib/ember/version.rb <ide> module Ember <ide> # we might want to unify this with the ember version string, <ide> # but consistency? <ide> def rubygems_version_string <del> major, rc = VERSION.sub('-','.').scan(/(\d+\.\d+\.\d+\.rc)\.(\d+)/).first <add> if VERSION =~ /rc/ <add> major, rc = VERSION.sub('-','.').scan(/(\d+\.\d+\.\d+\.rc)\.(\d+)/).first <ide> <del> "#{major}#{rc}" <add> "#{major}#{rc}" <add> else <add> VERSION <add> end <ide> end <ide> end
1
Javascript
Javascript
move reactelementvalidator to __dev__ block
d955ee9fae71e2037e9c876e2ab8cb537a8c7e43
<ide><path>src/isomorphic/React.js <ide> var ReactComponent = require('ReactComponent'); <ide> var ReactClass = require('ReactClass'); <ide> var ReactDOMFactories = require('ReactDOMFactories'); <ide> var ReactElement = require('ReactElement'); <del>var ReactElementValidator = require('ReactElementValidator'); <ide> var ReactPropTypes = require('ReactPropTypes'); <ide> var ReactVersion = require('ReactVersion'); <ide> <ide> var createFactory = ReactElement.createFactory; <ide> var cloneElement = ReactElement.cloneElement; <ide> <ide> if (__DEV__) { <add> var ReactElementValidator = require('ReactElementValidator'); <ide> createElement = ReactElementValidator.createElement; <ide> createFactory = ReactElementValidator.createFactory; <ide> cloneElement = ReactElementValidator.cloneElement; <ide><path>src/isomorphic/classic/element/ReactDOMFactories.js <ide> 'use strict'; <ide> <ide> var ReactElement = require('ReactElement'); <del>var ReactElementValidator = require('ReactElementValidator'); <ide> <ide> var mapObject = require('mapObject'); <ide> <ide> var mapObject = require('mapObject'); <ide> */ <ide> function createDOMFactory(tag) { <ide> if (__DEV__) { <add> var ReactElementValidator = require('ReactElementValidator'); <ide> return ReactElementValidator.createFactory(tag); <ide> } <ide> return ReactElement.createFactory(tag);
2
Ruby
Ruby
fix periodic timers
60173338ee0fb1667e226927e0034d50e3dd9d5a
<ide><path>lib/action_cable/channel/base.rb <ide> class Base <ide> <ide> on_unsubscribe :disconnect <ide> <del> attr_reader :params <add> attr_reader :params, :connection <ide> <ide> class_attribute :channel_name <ide> <ide> def disconnect <ide> end <ide> <ide> def broadcast(data) <del> @connection.broadcast({ identifier: @channel_identifier, message: data }.to_json) <add> connection.broadcast({ identifier: @channel_identifier, message: data }.to_json) <ide> end <ide> <ide> def start_periodic_timers
1
Javascript
Javascript
remove unused webpack
36ba3c19d40d8a825a3fc38c8efcdc16a7796af3
<ide><path>webpack.config.base.js <ide> 'use strict'; <ide> <del>var webpack = require('webpack'); <del> <ide> module.exports = { <ide> module: { <ide> loaders: [
1
Text
Text
add pcmpl-homebrew for homebrew emacs plugin
30779c32838bdcad3d6bb5ecb6833962cbde6657
<ide><path>docs/Tips-N'-Tricks.md <ide> inline patches in Vim. <ide> highlighting for inline patches as well as a number of helper functions <ide> for editing formula files. <ide> <add>[pcmpl-homebrew](https://github.com/hiddenlotus/pcmpl-homebrew) provides completion <add>for emacs shell-mode and eshell-mode. <add> <ide> ### Atom <ide> <ide> [language-homebrew-formula](https://atom.io/packages/language-homebrew-formula)
1
Text
Text
fix module.children description
98117a84d9e98246c48d2b61d08f02ce575545ee
<ide><path>doc/api/modules.md <ide> added: v0.1.16 <ide> <ide> * {module[]} <ide> <del>The module objects required by this one. <add>The module objects required for the first time by this one. <ide> <ide> ### module.exports <ide> <!-- YAML
1
Javascript
Javascript
remove duplicate checks in pummel/test-timers
986ae1e96b7bcf98d79ec8363c173e4614223fb9
<ide><path>test/pummel/test-timers.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> <del>const WINDOW = 200; // Why is does this need to be so big? <add>const WINDOW = 200; // Why does this need to be so big? <ide> <ide> let interval_count = 0; <ide> <del>// Check that these don't blow up. <del>clearTimeout(null); <del>clearInterval(null); <del> <ide> assert.strictEqual(setTimeout instanceof Function, true); <ide> const starttime = new Date(); <ide> setTimeout(common.mustCall(function() {
1
Ruby
Ruby
fix failing test
5a81dbf4894f112b73da160611c8be28b44c261f
<ide><path>actionpack/test/controller/new_base/base_test.rb <ide> class BaseTest < Rack::TestCase <ide> <ide> test "action methods" do <ide> assert_equal Set.new(%w( <add> index <ide> modify_response_headers <ide> modify_response_body_twice <del> index <ide> modify_response_body <ide> show_actions <ide> )), SimpleController.action_methods <ide> class BaseTest < Rack::TestCase <ide> assert_equal Set.new, Submodule::ContainedEmptyController.action_methods <ide> <ide> get "/dispatching/simple/show_actions" <del> assert_body "actions: modify_response_headers, modify_response_body_twice, index, modify_response_body, show_actions" <add> assert_body "actions: index, modify_response_body, modify_response_body_twice, modify_response_headers, show_actions" <ide> end <ide> end <ide> end
1
Javascript
Javascript
replace multiline variable assignments
984b42329eff7eed66c36a05d0d79fc54000cba7
<ide><path>packages/ember-debug/lib/main.js <ide> Ember.deprecate = function(message, test) { <ide> try { __fail__.fail(); } catch (e) { error = e; } <ide> <ide> if (Ember.LOG_STACKTRACE_ON_DEPRECATION && error.stack) { <del> var stack, stackStr = ''; <add> var stack; <add> var stackStr = ''; <add> <ide> if (error['arguments']) { <ide> // Chrome <ide> stack = error.stack.replace(/^\s+at\s+/gm, ''). <ide><path>packages/ember-extension-support/tests/container_debug_adapter_test.js <ide> import { default as EmberController } from "ember-runtime/controllers/controller <ide> import "ember-extension-support"; // Must be required to export Ember.ContainerDebugAdapter <ide> import Application from "ember-application/system/application"; <ide> <del>var adapter, App, Model = EmberObject.extend(); <add>var adapter, App; <add>var Model = EmberObject.extend(); <ide> <ide> <ide> function boot() { <ide><path>packages/ember-extension-support/tests/data_adapter_test.js <ide> import EmberDataAdapter from "ember-extension-support/data_adapter"; <ide> import EmberApplication from "ember-application/system/application"; <ide> import DefaultResolver from "ember-application/system/resolver"; <ide> <del>var adapter, App, Model = EmberObject.extend(); <add>var adapter, App; <add>var Model = EmberObject.extend(); <ide> <ide> var DataAdapter = EmberDataAdapter.extend({ <ide> detect: function(klass) { <ide><path>packages/ember-handlebars/lib/ext.js <ide> var resolveHelper, <ide> <ide> import isEmpty from 'ember-metal/is_empty'; <ide> <del>var slice = [].slice, originalTemplate = EmberHandlebars.template; <add>var slice = [].slice; <add>var originalTemplate = EmberHandlebars.template; <ide> <ide> /** <ide> If a path starts with a reserved keyword, returns the root <ide> function makeBoundHelper(fn) { <ide> <ide> // Override SimpleHandlebarsView's method for generating the view's content. <ide> bindView.normalizedValue = function() { <del> var args = [], boundOption; <add> var args = []; <add> var boundOption; <ide> <ide> // Copy over bound hash options. <ide> for (boundOption in boundOptions) { <ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer <ide> run.once(view, 'rerender'); <ide> }; <ide> <del> var template, context, result = handlebarsGet(currentContext, property, options); <add> var template, context; <add> var result = handlebarsGet(currentContext, property, options); <ide> <ide> result = valueNormalizer ? valueNormalizer(result) : result; <ide> <ide> function unboundIfHelper(property, fn) { <ide> @return {String} HTML string <ide> */ <ide> function withHelper(context, options) { <del> var bindContext, preserveContext, controller, helperName = 'with'; <add> var bindContext, preserveContext, controller; <add> var helperName = 'with'; <ide> <ide> if (arguments.length === 4) { <ide> var keywordName, path, rootPath, normalized, contextPath; <ide> function unlessHelper(context, options) { <ide> Ember.assert("You must pass exactly one argument to the unless helper", arguments.length === 2); <ide> Ember.assert("You must pass a block to the unless helper", options.fn && options.fn !== Handlebars.VM.noop); <ide> <del> var fn = options.fn, inverse = options.inverse, helperName = 'unless'; <add> var fn = options.fn; <add> var inverse = options.inverse; <add> var helperName = 'unless'; <ide> <ide> if (context) { <ide> helperName += ' ' + context; <ide> function bindAttrHelperDeprecated() { <ide> @return {Array} An array of class names to add <ide> */ <ide> function bindClasses(context, classBindings, view, bindAttrId, options) { <del> var ret = [], newClass, value, elem; <add> var ret = []; <add> var newClass, value, elem; <ide> <ide> // Helper method to retrieve the property from the context and <ide> // determine which class string to return, based on whether it is <ide><path>packages/ember-handlebars/lib/helpers/collection.js <ide> function collectionHelper(path, options) { <ide> collectionClass = CollectionView; <ide> } <ide> <del> var hash = options.hash, itemHash = {}, match; <add> var hash = options.hash; <add> var itemHash = {}; <add> var match; <ide> <ide> // Extract item view class if provided else default to the standard class <del> var collectionPrototype = collectionClass.proto(), itemViewClass; <add> var collectionPrototype = collectionClass.proto(); <add> var itemViewClass; <ide> <ide> if (hash.itemView) { <ide> controller = data.keywords.controller; <ide><path>packages/ember-handlebars/lib/helpers/each.js <ide> GroupedEach.prototype = { <ide> @param [options.groupedRows] {boolean} enable normal item-by-item rendering when inside a `#group` helper <ide> */ <ide> function eachHelper(path, options) { <del> var ctx, helperName = 'each'; <add> var ctx; <add> var helperName = 'each'; <ide> <ide> if (arguments.length === 4) { <ide> Ember.assert("If you pass more than one argument to the each helper, it must be in the form #each foo in bar", arguments[1] === "in"); <ide><path>packages/ember-handlebars/lib/helpers/view.js <ide> import { <ide> import EmberString from "ember-runtime/system/string"; <ide> <ide> <del>var LOWERCASE_A_Z = /^[a-z]/, <del> VIEW_PREFIX = /^view\./; <add>var LOWERCASE_A_Z = /^[a-z]/; <add>var VIEW_PREFIX = /^view\./; <ide> <ide> function makeBindings(thisContext, options) { <del> var hash = options.hash, <del> hashType = options.hashTypes; <add> var hash = options.hash; <add> var hashType = options.hashTypes; <ide> <ide> for (var prop in hash) { <ide> if (hashType[prop] === 'ID') { <ide><path>packages/ember-handlebars/lib/loader.js <ide> function bootstrap(ctx) { <ide> <ide> var compile = (script.attr('type') === 'text/x-raw-handlebars') ? <ide> jQuery.proxy(Handlebars.compile, Handlebars) : <del> jQuery.proxy(EmberHandlebars.compile, EmberHandlebars), <del> // Get the name of the script, used by Ember.View's templateName property. <del> // First look for data-template-name attribute, then fall back to its <del> // id if no name is found. <del> templateName = script.attr('data-template-name') || script.attr('id') || 'application', <del> template = compile(script.html()); <add> jQuery.proxy(EmberHandlebars.compile, EmberHandlebars); <add> // Get the name of the script, used by Ember.View's templateName property. <add> // First look for data-template-name attribute, then fall back to its <add> // id if no name is found. <add> var templateName = script.attr('data-template-name') || script.attr('id') || 'application'; <add> var template = compile(script.html()); <ide> <ide> // Check if template of same name already exists <ide> if (Ember.TEMPLATES[templateName] !== undefined) { <ide><path>packages/ember-handlebars/tests/controls/select_test.js <ide> test("can specify the property path for an option's label and value", function() <ide> }); <ide> <ide> test("can retrieve the current selected option when multiple=false", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> <ide> select.set('content', Ember.A([yehuda, tom])); <ide> <ide> append(); <ide> test("can retrieve the current selected option when multiple=false", function() <ide> }); <ide> <ide> test("can retrieve the current selected options when multiple=true", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }, <del> david = { id: 3, firstName: 'David' }, <del> brennain = { id: 4, firstName: 'Brennain' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> var david = { id: 3, firstName: 'David' }; <add> var brennain = { id: 4, firstName: 'Brennain' }; <add> <ide> select.set('content', Ember.A([yehuda, tom, david, brennain])); <ide> select.set('multiple', true); <ide> select.set('optionLabelPath', 'content.firstName'); <ide> test("can retrieve the current selected options when multiple=true", function() <ide> }); <ide> <ide> test("selection can be set when multiple=false", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <ide> <ide> run(function() { <ide> select.set('content', Ember.A([yehuda, tom])); <ide> test("selection can be set when multiple=false", function() { <ide> }); <ide> <ide> test("selection can be set when multiple=true", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }, <del> david = { id: 3, firstName: 'David' }, <del> brennain = { id: 4, firstName: 'Brennain' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> var david = { id: 3, firstName: 'David' }; <add> var brennain = { id: 4, firstName: 'Brennain' }; <ide> <ide> run(function() { <ide> select.set('content', Ember.A([yehuda, tom, david, brennain])); <ide> test("selection can be set when multiple=true", function() { <ide> }); <ide> <ide> test("selection can be set when multiple=true and prompt", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }, <del> david = { id: 3, firstName: 'David' }, <del> brennain = { id: 4, firstName: 'Brennain' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> var david = { id: 3, firstName: 'David' }; <add> var brennain = { id: 4, firstName: 'Brennain' }; <ide> <ide> run(function() { <ide> select.set('content', Ember.A([yehuda, tom, david, brennain])); <ide> test("selection can be set when multiple=true and prompt", function() { <ide> }); <ide> <ide> test("multiple selections can be set when multiple=true", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }, <del> david = { id: 3, firstName: 'David' }, <del> brennain = { id: 4, firstName: 'Brennain' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> var david = { id: 3, firstName: 'David' }; <add> var brennain = { id: 4, firstName: 'Brennain' }; <ide> <ide> run(function() { <ide> select.set('content', Ember.A([yehuda, tom, david, brennain])); <ide> test("multiple selections can be set when multiple=true", function() { <ide> }); <ide> <ide> test("multiple selections can be set by changing in place the selection array when multiple=true", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }, <del> david = { id: 3, firstName: 'David' }, <del> brennain = { id: 4, firstName: 'Brennain' }, <del> selection = Ember.A([yehuda, tom]); <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> var david = { id: 3, firstName: 'David' }; <add> var brennain = { id: 4, firstName: 'Brennain' }; <add> var selection = Ember.A([yehuda, tom]); <ide> <ide> run(function() { <ide> select.set('content', Ember.A([yehuda, tom, david, brennain])); <ide> test("multiple selections can be set by changing in place the selection array wh <ide> test("multiple selections can be set indirectly via bindings and in-place when multiple=true (issue #1058)", function() { <ide> var indirectContent = EmberObject.create(); <ide> <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }, <del> david = { id: 3, firstName: 'David' }, <del> brennain = { id: 4, firstName: 'Brennain' }, <del> cyril = { id: 5, firstName: 'Cyril' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> var david = { id: 3, firstName: 'David' }; <add> var brennain = { id: 4, firstName: 'Brennain' }; <add> var cyril = { id: 5, firstName: 'Cyril' }; <ide> <ide> run(function() { <ide> select.destroy(); // Destroy the existing select <ide> test("select with group whose content is undefined doesn't breaks", function() { <ide> }); <ide> <ide> test("selection uses the same array when multiple=true", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }, <del> david = { id: 3, firstName: 'David' }, <del> brennain = { id: 4, firstName: 'Brennain' }, <del> selection = Ember.A([yehuda, david]); <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> var david = { id: 3, firstName: 'David' }; <add> var brennain = { id: 4, firstName: 'Brennain' }; <add> var selection = Ember.A([yehuda, david]); <ide> <ide> run(function() { <ide> select.set('content', Ember.A([yehuda, tom, david, brennain])); <ide> test("selection uses the same array when multiple=true", function() { <ide> }); <ide> <ide> test("Ember.SelectedOption knows when it is selected when multiple=false", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }, <del> david = { id: 3, firstName: 'David' }, <del> brennain = { id: 4, firstName: 'Brennain' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> var david = { id: 3, firstName: 'David' }; <add> var brennain = { id: 4, firstName: 'Brennain' }; <ide> <ide> run(function() { <ide> select.set('content', Ember.A([yehuda, tom, david, brennain])); <ide> test("Ember.SelectedOption knows when it is selected when multiple=false", funct <ide> }); <ide> <ide> test("Ember.SelectedOption knows when it is selected when multiple=true", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }, <del> david = { id: 3, firstName: 'David' }, <del> brennain = { id: 4, firstName: 'Brennain' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <add> var david = { id: 3, firstName: 'David' }; <add> var brennain = { id: 4, firstName: 'Brennain' }; <ide> <ide> run(function() { <ide> select.set('content', Ember.A([yehuda, tom, david, brennain])); <ide> test("Ember.SelectedOption knows when it is selected when multiple=true and opti <ide> }); <ide> <ide> test("a prompt can be specified", function() { <del> var yehuda = { id: 1, firstName: 'Yehuda' }, <del> tom = { id: 2, firstName: 'Tom' }; <add> var yehuda = { id: 1, firstName: 'Yehuda' }; <add> var tom = { id: 2, firstName: 'Tom' }; <ide> <ide> run(function() { <ide> select.set('content', Ember.A([yehuda, tom])); <ide> test("works from a template with bindings", function() { <ide> }); <ide> <ide> test("upon content change, the DOM should reflect the selection (#481)", function() { <del> var userOne = {name: 'Mike', options: Ember.A(['a', 'b']), selectedOption: 'a'}, <del> userTwo = {name: 'John', options: Ember.A(['c', 'd']), selectedOption: 'd'}; <add> var userOne = {name: 'Mike', options: Ember.A(['a', 'b']), selectedOption: 'a'}; <add> var userTwo = {name: 'John', options: Ember.A(['c', 'd']), selectedOption: 'd'}; <ide> <ide> view = EmberView.create({ <ide> user: userOne, <ide> test("upon content change, the DOM should reflect the selection (#481)", functio <ide> view.appendTo('#qunit-fixture'); <ide> }); <ide> <del> var select = view.get('select'), <del> selectEl = select.$()[0]; <add> var select = view.get('select'); <add> var selectEl = select.$()[0]; <ide> <ide> equal(select.get('selection'), 'a', "Precond: Initial selection is correct"); <ide> equal(selectEl.selectedIndex, 0, "Precond: The DOM reflects the correct selection"); <ide> test("upon content change, the DOM should reflect the selection (#481)", functio <ide> }); <ide> <ide> test("upon content change with Array-like content, the DOM should reflect the selection", function() { <del> var tom = {id: 4, name: 'Tom'}, <del> sylvain = {id: 5, name: 'Sylvain'}; <add> var tom = {id: 4, name: 'Tom'}; <add> var sylvain = {id: 5, name: 'Sylvain'}; <ide> <ide> var proxy = ArrayProxy.create({ <ide> content: Ember.A(), <ide> test("upon content change with Array-like content, the DOM should reflect the se <ide> view.appendTo('#qunit-fixture'); <ide> }); <ide> <del> var select = view.get('select'), <del> selectEl = select.$()[0]; <add> var select = view.get('select'); <add> var selectEl = select.$()[0]; <ide> <ide> equal(selectEl.selectedIndex, -1, "Precond: The DOM reflects the lack of selection"); <ide> <ide> function testValueBinding(templateString) { <ide> view.appendTo('#qunit-fixture'); <ide> }); <ide> <del> var select = view.get('select'), <del> selectEl = select.$()[0]; <add> var select = view.get('select'); <add> var selectEl = select.$()[0]; <ide> <ide> equal(view.get('val'), 'g', "Precond: Initial bound property is correct"); <ide> equal(select.get('value'), 'g', "Precond: Initial selection is correct"); <ide><path>packages/ember-handlebars/tests/handlebars_test.js <ide> var appendView = function() { <ide> run(function() { view.appendTo('#qunit-fixture'); }); <ide> }; <ide> <del>var originalLookup = Ember.lookup, lookup; <del>var TemplateTests, container; <add>var originalLookup = Ember.lookup; <add>var TemplateTests, container, lookup; <ide> <ide> /** <ide> This module specifically tests integration with Handlebars and Ember-specific <ide> test("View should bind properties in the parent context", function() { <ide> }); <ide> <ide> test("using Handlebars helper that doesn't exist should result in an error", function() { <del> var names = [{ name: 'Alex' }, { name: 'Stef' }], <del> context = { <add> var names = [{ name: 'Alex' }, { name: 'Stef' }]; <add> var context = { <ide> content: A(names) <ide> }; <ide> <ide> test("Child views created using the view helper and that have a viewName should <ide> <ide> appendView(); <ide> <del> var parentView = firstChild(view), <del> childView = firstGrandchild(view); <add> var parentView = firstChild(view); <add> var childView = firstGrandchild(view); <add> <ide> equal(get(parentView, 'ohai'), childView); <ide> }); <ide> <ide> test("should be able to bind use {{bind-attr}} more than once on an element", fu <ide> <ide> test("{{bindAttr}} is aliased to {{bind-attr}}", function() { <ide> <del> var originalBindAttr = EmberHandlebars.helpers['bind-attr'], <del> originalWarn = Ember.warn; <add> var originalBindAttr = EmberHandlebars.helpers['bind-attr']; <add> var originalWarn = Ember.warn; <ide> <ide> Ember.warn = function(msg) { <ide> equal(msg, "The 'bindAttr' view helper is deprecated in favor of 'bind-attr'", 'Warning called'); <ide> test("should be able to use unbound helper in #each helper (with objects)", func <ide> }); <ide> <ide> test("should work with precompiled templates", function() { <del> var templateString = EmberHandlebars.precompile("{{view.value}}"), <del> compiledTemplate = EmberHandlebars.template(eval(templateString)); <add> var templateString = EmberHandlebars.precompile("{{view.value}}"); <add> var compiledTemplate = EmberHandlebars.template(eval(templateString)); <add> <ide> view = EmberView.create({ <ide> value: "rendered", <ide> template: compiledTemplate <ide><path>packages/ember-handlebars/tests/helpers/debug_test.js <ide> import EmberView from "ember-views/views/view"; <ide> import EmberHandlebars from "ember-handlebars-compiler"; <ide> import { logHelper } from "ember-handlebars/helpers/debug"; <ide> <del>var originalLookup = Ember.lookup, lookup; <add>var originalLookup = Ember.lookup; <add>var lookup; <ide> var originalLog, logCalls; <ide> var originalLogHelper; <ide> var view; <ide><path>packages/ember-handlebars/tests/helpers/each_test.js <ide> function templateFor(template) { <ide> return EmberHandlebars.compile(template); <ide> } <ide> <del>var originalLookup = Ember.lookup, lookup; <add>var originalLookup = Ember.lookup; <add>var lookup; <ide> <ide> QUnit.module("the #each helper", { <ide> setup: function() { <ide> test("itemController specified in template gets a parentController property", fu <ide> controllerName: computed(function() { <ide> return "controller:" + get(this, 'model.name') + ' of ' + get(this, 'parentController.company'); <ide> }) <del> }), <del> parentController = { <add> }); <add> var parentController = { <ide> container: container, <ide> company: 'Yapp' <ide> }; <ide> test("itemController specified in ArrayController gets a parentController proper <ide> controllerName: computed(function() { <ide> return "controller:" + get(this, 'model.name') + ' of ' + get(this, 'parentController.company'); <ide> }) <del> }), <del> PeopleController = ArrayController.extend({ <add> }); <add> var PeopleController = ArrayController.extend({ <ide> model: people, <ide> itemController: 'person', <ide> company: 'Yapp' <ide> test("itemController's parentController property, when the ArrayController has a <ide> controllerName: computed(function() { <ide> return "controller:" + get(this, 'model.name') + ' of ' + get(this, 'parentController.company'); <ide> }) <del> }), <del> PeopleController = ArrayController.extend({ <add> }); <add> var PeopleController = ArrayController.extend({ <ide> model: people, <ide> itemController: 'person', <ide> parentController: computed(function(){ <ide> return this.container.lookup('controller:company'); <ide> }), <ide> company: 'Yapp' <del> }), <del> CompanyController = EmberController.extend(); <add> }); <add> var CompanyController = EmberController.extend(); <ide> <ide> container.register('controller:company', CompanyController); <ide> container.register('controller:people', PeopleController); <ide> test("#each accepts a name binding", function() { <ide> test("#each accepts a name binding and does not change the context", function() { <ide> var controller = EmberController.create({ <ide> name: 'bob the controller' <del> }), <del> obj = EmberObject.create({ <add> }); <add> var obj = EmberObject.create({ <ide> name: 'henry the item' <ide> }); <ide> <ide> test("itemController specified in ArrayController with name binding does not cha <ide> controllerName: computed(function() { <ide> return "controller:" + get(this, 'model.name') + ' of ' + get(this, 'parentController.company'); <ide> }) <del> }), <del> PeopleController = ArrayController.extend({ <add> }); <add> var PeopleController = ArrayController.extend({ <ide> model: people, <ide> itemController: 'person', <ide> company: 'Yapp', <ide> controllerName: 'controller:people' <del> }), <del> container = new Container(); <add> }); <add> var container = new Container(); <ide> <ide> container.register('controller:people', PeopleController); <ide> container.register('controller:person', PersonController); <ide><path>packages/ember-handlebars/tests/helpers/partial_test.js <ide> import EmberHandlebars from "ember-handlebars-compiler"; <ide> <ide> var compile = EmberHandlebars.compile; <ide> <del>var MyApp; <del>var originalLookup = Ember.lookup, lookup, TemplateTests, view, container; <add>var MyApp, lookup, TemplateTests, view, container; <add>var originalLookup = Ember.lookup; <ide> <ide> QUnit.module("Support for {{partial}} helper", { <ide> setup: function() { <ide><path>packages/ember-handlebars/tests/helpers/template_test.js <ide> var trim = jQuery.trim; <ide> import Container from "ember-runtime/system/container"; <ide> import EmberHandlebars from "ember-handlebars-compiler"; <ide> <del>var MyApp; <del>var originalLookup = Ember.lookup, lookup, TemplateTests, view, container; <add>var MyApp, lookup, TemplateTests, view, container; <add>var originalLookup = Ember.lookup; <ide> <ide> QUnit.module("Support for {{template}} helper", { <ide> setup: function() { <ide><path>packages/ember-handlebars/tests/helpers/unbound_test.js <ide> function appendView(view) { <ide> run(function() { view.appendTo('#qunit-fixture'); }); <ide> } <ide> <del>var view; <del>var originalLookup = Ember.lookup, lookup; <del>var container; <add>var view, lookup, container; <add>var originalLookup = Ember.lookup; <ide> <ide> QUnit.module("Handlebars {{#unbound}} helper -- classic single-property usage", { <ide> setup: function() { <ide><path>packages/ember-handlebars/tests/helpers/with_test.js <ide> function appendView(view) { <ide> run(function() { view.appendTo('#qunit-fixture'); }); <ide> } <ide> <del>var view; <del>var originalLookup = Ember.lookup, lookup; <add>var view, lookup; <add>var originalLookup = Ember.lookup; <ide> <ide> QUnit.module("Handlebars {{#with}} helper", { <ide> setup: function() { <ide><path>packages/ember-handlebars/tests/helpers/yield_test.js <ide> import { A } from "ember-runtime/system/native_array"; <ide> import Component from "ember-views/views/component"; <ide> import EmberError from "ember-metal/error"; <ide> <del>var originalLookup = Ember.lookup, lookup, TemplateTests, view, container; <add>var originalLookup = Ember.lookup; <add>var lookup, TemplateTests, view, container; <ide> <ide> QUnit.module("Support for {{yield}} helper", { <ide> setup: function() { <ide> test("templates should yield to block, when the yield is embedded in a hierarchy <ide> layout: EmberHandlebars.compile('<div class="times">{{#each view.index}}{{yield}}{{/each}}</div>'), <ide> n: null, <ide> index: computed(function() { <del> var n = get(this, 'n'), indexArray = A(); <add> var n = get(this, 'n'); <add> var indexArray = A(); <ide> for (var i=0; i < n; i++) { <ide> indexArray[i] = i; <ide> } <ide><path>packages/ember-handlebars/tests/loader_test.js <ide> import run from "ember-metal/run_loop"; <ide> import EmberView from "ember-views/views/view"; <ide> var trim = jQuery.trim; <ide> <del>var originalLookup = Ember.lookup, lookup, Tobias, App, view; <add>var originalLookup = Ember.lookup; <add>var lookup, Tobias, App, view; <ide> <ide> QUnit.module("test Ember.Handlebars.bootstrap", { <ide> setup: function() { <ide><path>packages/ember-handlebars/tests/views/collection_view_test.js <ide> function nthChild(view, nth) { <ide> <ide> var firstChild = nthChild; <ide> <del>var originalLookup = Ember.lookup, lookup, TemplateTests, view; <add>var originalLookup = Ember.lookup; <add>var lookup, TemplateTests, view; <ide> <ide> QUnit.module("ember-handlebars/tests/views/collection_view_test", { <ide> setup: function() {
20
Java
Java
add forwardedheaderfilter requestonly
5f868b493a7ba63c2dc2622475ecc29f34e4346b
<ide><path>spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java <ide> public class ForwardedHeaderFilter extends OncePerRequestFilter { <ide> <ide> private boolean removeOnly; <ide> <add> private boolean requestOnly; <add> <ide> <ide> public ForwardedHeaderFilter() { <ide> this.pathHelper = new UrlPathHelper(); <ide> public void setRemoveOnly(boolean removeOnly) { <ide> this.removeOnly = removeOnly; <ide> } <ide> <add> /** <add> * Enables mode in which only the HttpServletRequest is modified. This means that <add> * {@link HttpServletResponse#sendRedirect(String)} will only work when the application is configured to use <add> * relative redirects. This can be done with Servlet Container specific setup. For example, using Tomcat's <add> * <a href="https://tomcat.apache.org/tomcat-8.0-doc/config/context.html#Common_Attributes">useRelativeRedirects</a> <add> * attribute. <add> * <add> * @param requestOnly whether to customize the {@code HttpServletResponse} or not. Default is false (customize the <add> * {@code HttpServletResponse}) <add> * @since 4.3.10 <add> */ <add> public void setRequestOnly(boolean requestOnly) { <add> this.requestOnly = requestOnly; <add> } <ide> <ide> @Override <ide> protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException { <ide> protected void doFilterInternal(HttpServletRequest request, HttpServletResponse <ide> } <ide> else { <ide> HttpServletRequest theRequest = new ForwardedHeaderExtractingRequest(request, this.pathHelper); <del> HttpServletResponse theResponse = new ForwardedHeaderExtractingResponse(response, theRequest); <add> HttpServletResponse theResponse = this.requestOnly ? response : <add> new ForwardedHeaderExtractingResponse(response, theRequest); <ide> filterChain.doFilter(theRequest, theResponse); <ide> } <ide> } <ide><path>spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java <ide> public void sendRedirectWithNoXForwardedAndDotDotPath() throws Exception { <ide> assertEquals("../foo/bar", redirectedUrl); <ide> } <ide> <add> @Test <add> public void sendRedirectWhenRequestOnlyAndXForwardedThenUsesRelativeRedirects() throws Exception { <add> this.request.addHeader(X_FORWARDED_PROTO, "https"); <add> this.request.addHeader(X_FORWARDED_HOST, "example.com"); <add> this.request.addHeader(X_FORWARDED_PORT, "443"); <add> this.filter.setRequestOnly(true); <add> <add> String location = sendRedirect("/a"); <add> <add> assertEquals("/a", location); <add> } <add> <add> @Test <add> public void sendRedirectWhenRequestOnlyAndNoXForwardedThenUsesRelativeRedirects() throws Exception { <add> this.filter.setRequestOnly(true); <add> <add> String location = sendRedirect("/a"); <add> <add> assertEquals("/a", location); <add> } <ide> <ide> private String sendRedirect(final String location) throws ServletException, IOException { <ide> MockHttpServletResponse response = doWithFiltersAndGetResponse(this.filter, new OncePerRequestFilter() {
2
Python
Python
set version to v2.1.0a10
656edcb98400352d80e37d29fe88a53b85c18168
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy-nightly" <del>__version__ = "2.1.0a9" <add>__version__ = "2.1.0a10" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI"
1
Java
Java
introduce base class for webmvcconfiguration
00d57907a3589972aec8ce9a72c41b93511f257c
<ide><path>org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/EnableWebMvc.java <ide> <ide> import org.springframework.context.annotation.Configuration; <ide> import org.springframework.context.annotation.Import; <del>import org.springframework.stereotype.Controller; <ide> import org.springframework.web.servlet.DispatcherServlet; <ide> <ide> /** <ide> * Enables default Spring MVC configuration and registers Spring MVC infrastructure components expected by the <del> * {@link DispatcherServlet}. To use this annotation simply place it on an application @{@link Configuration} class <del> * and that will in turn import default Spring MVC configuration including support for annotated methods <del> * in @{@link Controller} classes. <add> * {@link DispatcherServlet}. Add this annotation to an application @{@link Configuration} class. It will in <add> * turn import the @{@link Configuration} class {@link WebMvcConfiguration}, which provides default Spring MVC <add> * configuration. <ide> * <pre> <ide> * &#064;Configuration <ide> * &#064;EnableWebMvc <ide> * <ide> * } <ide> * </pre> <del> * <p>To customize the imported configuration you simply implement {@link WebMvcConfigurer}, or more likely extend <del> * {@link WebMvcConfigurerAdapter} overriding selected methods only. The most obvious place to do this is <del> * the @{@link Configuration} class that enabled the Spring MVC configuration via @{@link EnableWebMvc}. <del> * However any @{@link Configuration} class and more generally any Spring bean can implement {@link WebMvcConfigurer} <del> * to be detected and given an opportunity to customize Spring MVC configuration at startup. <add> * <p>To customize the imported configuration implement {@link WebMvcConfigurer}, or more conveniently extend <add> * {@link WebMvcConfigurerAdapter} overriding specific methods. Your @{@link Configuration} class and any other <add> * Spring bean that implements {@link WebMvcConfigurer} will be detected and given an opportunity to customize <add> * the default Spring MVC configuration through the callback methods on the {@link WebMvcConfigurer} interface. <ide> * <pre> <ide> * &#064;Configuration <ide> * &#064;EnableWebMvc <ide><path>org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/InterceptorConfigurer.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.context.request.WebRequestInterceptor; <ide> import org.springframework.web.servlet.HandlerInterceptor; <del>import org.springframework.web.servlet.HandlerMapping; <ide> import org.springframework.web.servlet.handler.MappedInterceptor; <ide> import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter; <ide> <ide> /** <ide> * Helps with configuring an ordered set of Spring MVC interceptors of type {@link HandlerInterceptor} or <del> * {@link WebRequestInterceptor}. Registered interceptors will generally be detected by all {@link HandlerMapping} <del> * instances in a Spring MVC web application context. Interceptors can be added with a set of path patterns to <del> * which they should apply. <add> * {@link WebRequestInterceptor}. Interceptors can be registered with a set of path patterns. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 3.1 <ide> */ <ide> public class InterceptorConfigurer { <ide> <del> private final List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>(); <add> private final List<Object> interceptors = new ArrayList<Object>(); <ide> <ide> /** <ide> * Add a {@link HandlerInterceptor} that should apply to any request. <ide> */ <ide> public void addInterceptor(HandlerInterceptor interceptor) { <del> register(null, interceptor); <add> register(interceptor); <ide> } <ide> <ide> /** <ide> * Add a {@link WebRequestInterceptor} that should apply to any request. <ide> */ <ide> public void addInterceptor(WebRequestInterceptor interceptor) { <del> register(null, asHandlerInterceptorArray(interceptor)); <add> register(asHandlerInterceptorArray(interceptor)); <ide> } <ide> <ide> /** <ide> * Add {@link HandlerInterceptor}s that should apply to any request. <ide> */ <ide> public void addInterceptors(HandlerInterceptor... interceptors) { <del> register(null, interceptors); <add> register( interceptors); <ide> } <ide> <ide> /** <ide> * Add {@link WebRequestInterceptor}s that should apply to any request. <ide> */ <ide> public void addInterceptors(WebRequestInterceptor... interceptors) { <del> register(null, asHandlerInterceptorArray(interceptors)); <add> register(asHandlerInterceptorArray(interceptors)); <ide> } <ide> <ide> /** <ide> * Add a {@link HandlerInterceptor} with a set of URL path patterns it should apply to. <ide> */ <ide> public void mapInterceptor(String[] pathPatterns, HandlerInterceptor interceptor) { <del> register(pathPatterns, interceptor); <add> registerMappedInterceptors(pathPatterns, interceptor); <ide> } <ide> <ide> /** <ide> * Add a {@link WebRequestInterceptor} with a set of URL path patterns it should apply to. <ide> */ <ide> public void mapInterceptor(String[] pathPatterns, WebRequestInterceptor interceptors) { <del> register(pathPatterns, asHandlerInterceptorArray(interceptors)); <add> registerMappedInterceptors(pathPatterns, asHandlerInterceptorArray(interceptors)); <ide> } <ide> <ide> /** <ide> * Add {@link HandlerInterceptor}s with a set of URL path patterns they should apply to. <ide> */ <ide> public void mapInterceptors(String[] pathPatterns, HandlerInterceptor... interceptors) { <del> register(pathPatterns, interceptors); <add> registerMappedInterceptors(pathPatterns, interceptors); <ide> } <ide> <ide> /** <ide> * Add {@link WebRequestInterceptor}s with a set of URL path patterns they should apply to. <ide> */ <ide> public void mapInterceptors(String[] pathPatterns, WebRequestInterceptor... interceptors) { <del> register(pathPatterns, asHandlerInterceptorArray(interceptors)); <add> registerMappedInterceptors(pathPatterns, asHandlerInterceptorArray(interceptors)); <ide> } <ide> <ide> private static HandlerInterceptor[] asHandlerInterceptorArray(WebRequestInterceptor...interceptors) { <ide> private static HandlerInterceptor[] asHandlerInterceptorArray(WebRequestIntercep <ide> return result; <ide> } <ide> <add> /** <add> * Stores the given set of {@link HandlerInterceptor}s internally. <add> * @param interceptors one or more interceptors to be stored <add> */ <add> protected void register(HandlerInterceptor...interceptors) { <add> Assert.notEmpty(interceptors, "At least one interceptor must be provided"); <add> for (HandlerInterceptor interceptor : interceptors) { <add> this.interceptors.add(interceptor); <add> } <add> } <add> <ide> /** <ide> * Stores the given set of {@link HandlerInterceptor}s and path patterns internally. <ide> * @param pathPatterns path patterns or {@code null} <ide> * @param interceptors one or more interceptors to be stored <ide> */ <del> protected void register(String[] pathPatterns, HandlerInterceptor...interceptors) { <add> protected void registerMappedInterceptors(String[] pathPatterns, HandlerInterceptor...interceptors) { <ide> Assert.notEmpty(interceptors, "At least one interceptor must be provided"); <add> Assert.notEmpty(pathPatterns, "Path patterns must be provided"); <ide> for (HandlerInterceptor interceptor : interceptors) { <del> mappedInterceptors.add(new MappedInterceptor(pathPatterns, interceptor)); <add> this.interceptors.add(new MappedInterceptor(pathPatterns, interceptor)); <ide> } <ide> } <ide> <ide> /** <ide> * Returns all registered interceptors. <ide> */ <del> protected List<MappedInterceptor> getInterceptors() { <del> return mappedInterceptors; <add> protected List<Object> getInterceptors() { <add> return interceptors; <ide> } <ide> <ide> } <ide><path>org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfiguration.java <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> <del>import javax.servlet.ServletContext; <del>import javax.xml.transform.Source; <del> <del>import org.springframework.beans.BeanUtils; <del>import org.springframework.beans.BeansException; <del>import org.springframework.beans.factory.BeanInitializationException; <ide> import org.springframework.beans.factory.annotation.Autowired; <del>import org.springframework.context.ApplicationContext; <del>import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <del>import org.springframework.format.support.DefaultFormattingConversionService; <ide> import org.springframework.format.support.FormattingConversionService; <del>import org.springframework.http.converter.ByteArrayHttpMessageConverter; <ide> import org.springframework.http.converter.HttpMessageConverter; <del>import org.springframework.http.converter.ResourceHttpMessageConverter; <del>import org.springframework.http.converter.StringHttpMessageConverter; <del>import org.springframework.http.converter.feed.AtomFeedHttpMessageConverter; <del>import org.springframework.http.converter.feed.RssChannelHttpMessageConverter; <del>import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; <del>import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; <del>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <del>import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; <del>import org.springframework.util.ClassUtils; <del>import org.springframework.validation.Errors; <ide> import org.springframework.validation.Validator; <del>import org.springframework.web.HttpRequestHandler; <del>import org.springframework.web.bind.annotation.ExceptionHandler; <del>import org.springframework.web.bind.annotation.ResponseStatus; <del>import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; <del>import org.springframework.web.context.ServletContextAware; <ide> import org.springframework.web.method.support.HandlerMethodArgumentResolver; <ide> import org.springframework.web.method.support.HandlerMethodReturnValueHandler; <ide> import org.springframework.web.servlet.DispatcherServlet; <ide> import org.springframework.web.servlet.HandlerExceptionResolver; <del>import org.springframework.web.servlet.HandlerMapping; <del>import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; <del>import org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor; <ide> import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite; <del>import org.springframework.web.servlet.handler.MappedInterceptor; <del>import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; <del>import org.springframework.web.servlet.mvc.Controller; <del>import org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter; <del>import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter; <del>import org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver; <del>import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; <del>import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; <del>import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; <ide> <ide> /** <del> * Provides default configuration for Spring MVC applications. Registers Spring MVC infrastructure components to be <del> * detected by the {@link DispatcherServlet}. Further below is a list of registered instances. This configuration is <del> * enabled through the {@link EnableWebMvc} annotation. <del> * <del> * <p>A number of options are available for customizing the default configuration provided by this class. <del> * See {@link EnableWebMvc} and {@link WebMvcConfigurer} for details. <del> * <del> * <p>Registers these handler mappings: <del> * <ul> <del> * <li>{@link RequestMappingHandlerMapping} ordered at 0 for mapping requests to annotated controller methods. <del> * <li>{@link SimpleUrlHandlerMapping} ordered at 1 to map URL paths directly to view names. <del> * <li>{@link BeanNameUrlHandlerMapping} ordered at 2 to map URL paths to controller bean names. <del> * <li>{@link SimpleUrlHandlerMapping} ordered at {@code Integer.MAX_VALUE-1} to serve static resource requests. <del> * <li>{@link SimpleUrlHandlerMapping} ordered at {@code Integer.MAX_VALUE} to forward requests to the default servlet. <del> * </ul> <del> * <del> * <p><strong>Note:</strong> that the SimpleUrlHandlerMapping instances above will have empty URL maps and <del> * hence no effect until explicitly configured via one of the {@link WebMvcConfigurer} callbacks. <del> * <del> * <p>Registers these handler adapters: <del> * <ul> <del> * <li>{@link RequestMappingHandlerAdapter} for processing requests using annotated controller methods. <del> * <li>{@link HttpRequestHandlerAdapter} for processing requests with {@link HttpRequestHandler}s. <del> * <li>{@link SimpleControllerHandlerAdapter} for processing requests with interface-based {@link Controller}s. <del> * </ul> <del> * <del> * <p>Registers a {@link HandlerExceptionResolverComposite} with this chain of exception resolvers: <del> * <ul> <del> * <li>{@link ExceptionHandlerExceptionResolver} for handling exceptions through @{@link ExceptionHandler} methods. <del> * <li>{@link ResponseStatusExceptionResolver} for exceptions annotated with @{@link ResponseStatus}. <del> * <li>{@link DefaultHandlerExceptionResolver} for resolving known Spring exception types <del> * </ul> <del> * <del> * <p>Registers the following others: <del> * <ul> <del> * <li>{@link FormattingConversionService} for use with annotated controller methods and the spring:eval JSP tag. <del> * <li>{@link Validator} for validating model attributes on annotated controller methods. <del> * </ul> <add> * Provides default configuration for Spring MVC applications by registering Spring MVC infrastructure components <add> * to be detected by the {@link DispatcherServlet}. This class is imported whenever @{@link EnableWebMvc} is <add> * added to an @{@link Configuration} class. <add> * <add> * <p>See the base class {@link WebMvcConfigurationSupport} for a list of registered instances. This class is closed <add> * for extension. However, the configuration it provides can be customized by having your @{@link Configuration} <add> * class implement {@link WebMvcConfigurer} or more conveniently extend from {@link WebMvcConfigurerAdapter}. <add> * <add> * <p>This class will detect your @{@link Configuration} class and any other @{@link Configuration} classes that <add> * implement {@link WebMvcConfigurer} via autowiring and will allow each of them to participate in the process <add> * of configuring Spring MVC through the configuration callbacks defined in {@link WebMvcConfigurer}. <ide> * <ide> * @see EnableWebMvc <ide> * @see WebMvcConfigurer <ide> * @since 3.1 <ide> */ <ide> @Configuration <del>class WebMvcConfiguration implements ApplicationContextAware, ServletContextAware { <add>class WebMvcConfiguration extends WebMvcConfigurationSupport { <ide> <ide> private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite(); <ide> <del> private ServletContext servletContext; <del> <del> private ApplicationContext applicationContext; <del> <del> private List<MappedInterceptor> mappedInterceptors; <del> <del> private List<HttpMessageConverter<?>> messageConverters; <del> <ide> @Autowired(required = false) <ide> public void setConfigurers(List<WebMvcConfigurer> configurers) { <ide> if (configurers == null || configurers.isEmpty()) { <ide> public void setConfigurers(List<WebMvcConfigurer> configurers) { <ide> this.configurers.addWebMvcConfigurers(configurers); <ide> } <ide> <del> public void setServletContext(ServletContext servletContext) { <del> this.servletContext = servletContext; <add> @Override <add> protected void configureInterceptors(InterceptorConfigurer configurer) { <add> configurers.configureInterceptors(configurer); <ide> } <ide> <del> public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { <del> this.applicationContext = applicationContext; <del> } <del> <del> @Bean <del> public RequestMappingHandlerMapping requestMappingHandlerMapping() { <del> RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping(); <del> mapping.setInterceptors(getMappedInterceptors()); <del> mapping.setOrder(0); <del> return mapping; <del> } <del> <del> private Object[] getMappedInterceptors() { <del> if (mappedInterceptors == null) { <del> InterceptorConfigurer configurer = new InterceptorConfigurer(); <del> configurers.configureInterceptors(configurer); <del> configurer.addInterceptor(new ConversionServiceExposingInterceptor(conversionService())); <del> mappedInterceptors = configurer.getInterceptors(); <del> } <del> return mappedInterceptors.toArray(); <del> } <del> <del> @Bean <del> public HandlerMapping viewControllerHandlerMapping() { <del> ViewControllerConfigurer configurer = new ViewControllerConfigurer(); <del> configurer.setOrder(1); <add> @Override <add> protected void configureViewControllers(ViewControllerConfigurer configurer) { <ide> configurers.configureViewControllers(configurer); <del> <del> SimpleUrlHandlerMapping handlerMapping = configurer.getHandlerMapping(); <del> handlerMapping.setInterceptors(getMappedInterceptors()); <del> return handlerMapping; <del> } <del> <del> @Bean <del> public BeanNameUrlHandlerMapping beanNameHandlerMapping() { <del> BeanNameUrlHandlerMapping mapping = new BeanNameUrlHandlerMapping(); <del> mapping.setOrder(2); <del> mapping.setInterceptors(getMappedInterceptors()); <del> return mapping; <ide> } <ide> <del> @Bean <del> public HandlerMapping resourceHandlerMapping() { <del> ResourceConfigurer configurer = new ResourceConfigurer(applicationContext, servletContext); <del> configurer.setOrder(Integer.MAX_VALUE-1); <add> @Override <add> protected void configureResourceHandling(ResourceConfigurer configurer) { <ide> configurers.configureResourceHandling(configurer); <del> return configurer.getHandlerMapping(); <ide> } <ide> <del> @Bean <del> public HandlerMapping defaultServletHandlerMapping() { <del> DefaultServletHandlerConfigurer configurer = new DefaultServletHandlerConfigurer(servletContext); <add> @Override <add> protected void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { <ide> configurers.configureDefaultServletHandling(configurer); <del> return configurer.getHandlerMapping(); <ide> } <ide> <add> @Override <ide> @Bean <ide> public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { <del> RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter(); <del> adapter.setMessageConverters(getMessageConverters()); <del> <del> ConfigurableWebBindingInitializer bindingInitializer = new ConfigurableWebBindingInitializer(); <del> bindingInitializer.setConversionService(conversionService()); <del> bindingInitializer.setValidator(validator()); <del> adapter.setWebBindingInitializer(bindingInitializer); <add> RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter(); <ide> <ide> List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<HandlerMethodArgumentResolver>(); <ide> configurers.addArgumentResolvers(argumentResolvers); <ide> public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { <ide> List<HandlerMethodReturnValueHandler> returnValueHandlers = new ArrayList<HandlerMethodReturnValueHandler>(); <ide> configurers.addReturnValueHandlers(returnValueHandlers); <ide> adapter.setCustomReturnValueHandlers(returnValueHandlers); <del> <add> <ide> return adapter; <ide> } <ide> <del> private List<HttpMessageConverter<?>> getMessageConverters() { <del> if (messageConverters == null) { <del> messageConverters = new ArrayList<HttpMessageConverter<?>>(); <del> configurers.configureMessageConverters(messageConverters); <del> if (messageConverters.isEmpty()) { <del> addDefaultHttpMessageConverters(messageConverters); <del> } <del> } <del> return messageConverters; <del> } <del> <del> @Bean(name="webMvcConversionService") <del> public FormattingConversionService conversionService() { <del> FormattingConversionService conversionService = new DefaultFormattingConversionService(); <del> configurers.addFormatters(conversionService); <del> return conversionService; <del> } <del> <del> @Bean(name="webMvcValidator") <del> public Validator validator() { <del> Validator validator = configurers.getValidator(); <del> if (validator != null) { <del> return validator; <del> } <del> else if (ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) { <del> Class<?> clazz; <del> try { <del> String className = "org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"; <del> clazz = ClassUtils.forName(className, WebMvcConfiguration.class.getClassLoader()); <del> } catch (ClassNotFoundException e) { <del> throw new BeanInitializationException("Could not find default validator"); <del> } catch (LinkageError e) { <del> throw new BeanInitializationException("Could not find default validator"); <del> } <del> return (Validator) BeanUtils.instantiate(clazz); <del> } <del> else { <del> return NOOP_VALIDATOR; <del> } <del> } <del> <del> private void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) { <del> StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(); <del> stringConverter.setWriteAcceptCharset(false); <del> <del> messageConverters.add(new ByteArrayHttpMessageConverter()); <del> messageConverters.add(stringConverter); <del> messageConverters.add(new ResourceHttpMessageConverter()); <del> messageConverters.add(new SourceHttpMessageConverter<Source>()); <del> messageConverters.add(new XmlAwareFormHttpMessageConverter()); <del> <del> ClassLoader classLoader = getClass().getClassLoader(); <del> if (ClassUtils.isPresent("javax.xml.bind.Binder", classLoader)) { <del> messageConverters.add(new Jaxb2RootElementHttpMessageConverter()); <del> } <del> if (ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", classLoader)) { <del> messageConverters.add(new MappingJacksonHttpMessageConverter()); <del> } <del> if (ClassUtils.isPresent("com.sun.syndication.feed.WireFeed", classLoader)) { <del> messageConverters.add(new AtomFeedHttpMessageConverter()); <del> messageConverters.add(new RssChannelHttpMessageConverter()); <del> } <add> @Override <add> protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { <add> configurers.configureMessageConverters(converters); <ide> } <ide> <add> @Override <ide> @Bean <del> public HttpRequestHandlerAdapter httpRequestHandlerAdapter() { <del> return new HttpRequestHandlerAdapter(); <add> public FormattingConversionService mvcConversionService() { <add> FormattingConversionService conversionService = super.mvcConversionService(); <add> configurers.addFormatters(conversionService); <add> return conversionService; <ide> } <ide> <add> @Override <ide> @Bean <del> public SimpleControllerHandlerAdapter simpleControllerHandlerAdapter() { <del> return new SimpleControllerHandlerAdapter(); <add> public Validator mvcValidator() { <add> Validator validator = configurers.getValidator(); <add> return validator != null ? validator : super.mvcValidator(); <ide> } <ide> <ide> @Bean <del> public HandlerExceptionResolver handlerExceptionResolver() throws Exception { <add> public HandlerExceptionResolverComposite handlerExceptionResolver() throws Exception { <ide> List<HandlerExceptionResolver> resolvers = new ArrayList<HandlerExceptionResolver>(); <ide> configurers.configureHandlerExceptionResolvers(resolvers); <ide> <del> if (resolvers.size() == 0) { <del> resolvers.add(createExceptionHandlerExceptionResolver()); <del> resolvers.add(new ResponseStatusExceptionResolver()); <del> resolvers.add(new DefaultHandlerExceptionResolver()); <add> HandlerExceptionResolverComposite composite = super.handlerExceptionResolver(); <add> if (resolvers.size() != 0) { <add> composite.setExceptionResolvers(resolvers); <ide> } <del> <del> HandlerExceptionResolverComposite composite = new HandlerExceptionResolverComposite(); <del> composite.setOrder(0); <del> composite.setExceptionResolvers(resolvers); <ide> return composite; <ide> } <del> <del> private HandlerExceptionResolver createExceptionHandlerExceptionResolver() throws Exception { <del> ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver(); <del> resolver.setMessageConverters(getMessageConverters()); <del> resolver.afterPropertiesSet(); <del> return resolver; <del> } <ide> <del> private static final Validator NOOP_VALIDATOR = new Validator() { <del> <del> public boolean supports(Class<?> clazz) { <del> return false; <del> } <del> <del> public void validate(Object target, Errors errors) { <del> } <del> }; <del> <ide> } <ide><path>org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java <add>/* <add> * Copyright 2002-2011 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.servlet.config.annotation; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>import javax.servlet.ServletContext; <add>import javax.xml.transform.Source; <add> <add>import org.springframework.beans.BeanUtils; <add>import org.springframework.beans.BeansException; <add>import org.springframework.beans.factory.BeanInitializationException; <add>import org.springframework.context.ApplicationContext; <add>import org.springframework.context.ApplicationContextAware; <add>import org.springframework.context.annotation.Bean; <add>import org.springframework.context.annotation.Configuration; <add>import org.springframework.format.support.DefaultFormattingConversionService; <add>import org.springframework.format.support.FormattingConversionService; <add>import org.springframework.http.converter.ByteArrayHttpMessageConverter; <add>import org.springframework.http.converter.HttpMessageConverter; <add>import org.springframework.http.converter.ResourceHttpMessageConverter; <add>import org.springframework.http.converter.StringHttpMessageConverter; <add>import org.springframework.http.converter.feed.AtomFeedHttpMessageConverter; <add>import org.springframework.http.converter.feed.RssChannelHttpMessageConverter; <add>import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; <add>import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; <add>import org.springframework.http.converter.xml.SourceHttpMessageConverter; <add>import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; <add>import org.springframework.util.ClassUtils; <add>import org.springframework.validation.Errors; <add>import org.springframework.validation.MessageCodesResolver; <add>import org.springframework.validation.Validator; <add>import org.springframework.web.HttpRequestHandler; <add>import org.springframework.web.bind.annotation.ExceptionHandler; <add>import org.springframework.web.bind.annotation.ResponseStatus; <add>import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; <add>import org.springframework.web.context.ServletContextAware; <add>import org.springframework.web.servlet.DispatcherServlet; <add>import org.springframework.web.servlet.HandlerAdapter; <add>import org.springframework.web.servlet.HandlerExceptionResolver; <add>import org.springframework.web.servlet.HandlerMapping; <add>import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; <add>import org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor; <add>import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite; <add>import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; <add>import org.springframework.web.servlet.mvc.Controller; <add>import org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter; <add>import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter; <add>import org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver; <add>import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver; <add>import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; <add>import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; <add>import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; <add> <add>/** <add> * A base class that provides default configuration for Spring MVC applications by registering Spring MVC <add> * infrastructure components to be detected by the {@link DispatcherServlet}. Typically applications should not <add> * have to start by extending this class. A much easier place to start is to annotate your @{@link Configuration} <add> * class with @{@link EnableWebMvc}. See @{@link EnableWebMvc} and {@link WebMvcConfigurer}. <add> * <add> * <p>If using @{@link EnableWebMvc} and extending from {@link WebMvcConfigurerAdapter} does not give you the level <add> * of flexibility you need, consider extending directly from this class instead. Remember to add @{@link Configuration} <add> * to you subclass and @{@link Bean} to any @{@link Bean} methods you choose to override. A few example reasons for <add> * extending this class include providing a custom {@link MessageCodesResolver}, changing the order of <add> * {@link HandlerMapping} instances, plugging in a variant of any of the beans provided by this class, and so on. <add> * <add> * <p>This class registers the following {@link HandlerMapping}s:</p> <add> * <ul> <add> * <li>{@link RequestMappingHandlerMapping} ordered at 0 for mapping requests to annotated controller methods. <add> * <li>{@link SimpleUrlHandlerMapping} ordered at 1 to map URL paths directly to view names. <add> * <li>{@link BeanNameUrlHandlerMapping} ordered at 2 to map URL paths to controller bean names. <add> * <li>{@link SimpleUrlHandlerMapping} ordered at {@code Integer.MAX_VALUE-1} to serve static resource requests. <add> * <li>{@link SimpleUrlHandlerMapping} ordered at {@code Integer.MAX_VALUE} to forward requests to the default servlet. <add> * </ul> <add> * <add> * <p>Registers {@link HandlerAdapter}s: <add> * <ul> <add> * <li>{@link RequestMappingHandlerAdapter} for processing requests using annotated controller methods. <add> * <li>{@link HttpRequestHandlerAdapter} for processing requests with {@link HttpRequestHandler}s. <add> * <li>{@link SimpleControllerHandlerAdapter} for processing requests with interface-based {@link Controller}s. <add> * </ul> <add> * <add> * <p>Registers a {@link HandlerExceptionResolverComposite} with this chain of exception resolvers: <add> * <ul> <add> * <li>{@link ExceptionHandlerExceptionResolver} for handling exceptions through @{@link ExceptionHandler} methods. <add> * <li>{@link ResponseStatusExceptionResolver} for exceptions annotated with @{@link ResponseStatus}. <add> * <li>{@link DefaultHandlerExceptionResolver} for resolving known Spring exception types <add> * </ul> <add> * <add> * <p>Registers the following other instances: <add> * <ul> <add> * <li>{@link FormattingConversionService} for use with annotated controller methods and the spring:eval JSP tag. <add> * <li>{@link Validator} for validating model attributes on annotated controller methods. <add> * </ul> <add> * <add> * @see EnableWebMvc <add> * @see WebMvcConfigurer <add> * @see WebMvcConfigurerAdapter <add> * <add> * @author Rossen Stoyanchev <add> * @since 3.1 <add> */ <add>public abstract class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware { <add> <add> private ServletContext servletContext; <add> <add> private ApplicationContext applicationContext; <add> <add> private List<Object> interceptors; <add> <add> private List<HttpMessageConverter<?>> messageConverters; <add> <add> public void setServletContext(ServletContext servletContext) { <add> this.servletContext = servletContext; <add> } <add> <add> public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { <add> this.applicationContext = applicationContext; <add> } <add> <add> /** <add> * Returns a {@link RequestMappingHandlerMapping} ordered at 0 for mapping requests to annotated controllers. <add> */ <add> @Bean <add> public RequestMappingHandlerMapping requestMappingHandlerMapping() { <add> RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping(); <add> mapping.setInterceptors(getInterceptors()); <add> mapping.setOrder(0); <add> return mapping; <add> } <add> <add> /** <add> * Provides access to the shared handler interceptors used to configure {@link HandlerMapping} instances with. <add> * This method cannot be overridden, use {@link #configureInterceptors(InterceptorConfigurer)} instead. <add> */ <add> protected final Object[] getInterceptors() { <add> if (interceptors == null) { <add> InterceptorConfigurer configurer = new InterceptorConfigurer(); <add> configureInterceptors(configurer); <add> configurer.addInterceptor(new ConversionServiceExposingInterceptor(mvcConversionService())); <add> interceptors = configurer.getInterceptors(); <add> } <add> return interceptors.toArray(); <add> } <add> <add> /** <add> * Override this method to configure handler interceptors including interceptors mapped to path patterns. <add> * @see InterceptorConfigurer <add> */ <add> protected void configureInterceptors(InterceptorConfigurer configurer) { <add> } <add> <add> /** <add> * Returns a {@link SimpleUrlHandlerMapping} ordered at 1 to map URL paths directly to view names. <add> * To configure view controllers see {@link #configureViewControllers(ViewControllerConfigurer)}. <add> */ <add> @Bean <add> public SimpleUrlHandlerMapping viewControllerHandlerMapping() { <add> ViewControllerConfigurer configurer = new ViewControllerConfigurer(); <add> configurer.setOrder(1); <add> configureViewControllers(configurer); <add> <add> SimpleUrlHandlerMapping handlerMapping = configurer.getHandlerMapping(); <add> handlerMapping.setInterceptors(getInterceptors()); <add> return handlerMapping; <add> } <add> <add> /** <add> * Override this method to configure view controllers. View controllers provide a direct mapping between a <add> * URL path and view name. This is useful when serving requests that don't require application-specific <add> * controller logic and can be forwarded directly to a view for rendering. <add> * @see ViewControllerConfigurer <add> */ <add> protected void configureViewControllers(ViewControllerConfigurer configurer) { <add> } <add> <add> /** <add> * Returns a {@link BeanNameUrlHandlerMapping} ordered at 2 to map URL paths to controller bean names. <add> */ <add> @Bean <add> public BeanNameUrlHandlerMapping beanNameHandlerMapping() { <add> BeanNameUrlHandlerMapping mapping = new BeanNameUrlHandlerMapping(); <add> mapping.setOrder(2); <add> mapping.setInterceptors(getInterceptors()); <add> return mapping; <add> } <add> <add> /** <add> * Returns a {@link SimpleUrlHandlerMapping} ordered at Integer.MAX_VALUE-1 to serve static resource requests. <add> * To configure resource handling, see {@link #configureResourceHandling(ResourceConfigurer)}. <add> */ <add> @Bean <add> public SimpleUrlHandlerMapping resourceHandlerMapping() { <add> ResourceConfigurer configurer = new ResourceConfigurer(applicationContext, servletContext); <add> configurer.setOrder(Integer.MAX_VALUE-1); <add> configureResourceHandling(configurer); <add> return configurer.getHandlerMapping(); <add> } <add> <add> /** <add> * Override this method to configure serving static resources such as images and css files through Spring MVC. <add> * @see ResourceConfigurer <add> */ <add> protected void configureResourceHandling(ResourceConfigurer configurer) { <add> } <add> <add> /** <add> * Returns a {@link SimpleUrlHandlerMapping} ordered at Integer.MAX_VALUE to serve static resources by <add> * forwarding to the Servlet container's default servlet. To configure default servlet handling see <add> * {@link #configureDefaultServletHandling(DefaultServletHandlerConfigurer)}. <add> */ <add> @Bean <add> public SimpleUrlHandlerMapping defaultServletHandlerMapping() { <add> DefaultServletHandlerConfigurer configurer = new DefaultServletHandlerConfigurer(servletContext); <add> configureDefaultServletHandling(configurer); <add> return configurer.getHandlerMapping(); <add> } <add> <add> /** <add> * Override this method to configure serving static resources through the Servlet container's default Servlet. <add> * @see DefaultServletHandlerConfigurer <add> */ <add> protected void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { <add> } <add> <add> /** <add> * Returns a {@link RequestMappingHandlerAdapter} for processing requests using annotated controller methods. <add> * Also see {@link #initWebBindingInitializer()} for configuring data binding globally. <add> */ <add> @Bean <add> public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { <add> ConfigurableWebBindingInitializer webBindingInitializer = new ConfigurableWebBindingInitializer(); <add> webBindingInitializer.setConversionService(mvcConversionService()); <add> webBindingInitializer.setValidator(mvcValidator()); <add> extendWebBindingInitializer(webBindingInitializer); <add> <add> RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter(); <add> adapter.setMessageConverters(getMessageConverters()); <add> adapter.setWebBindingInitializer(webBindingInitializer); <add> return adapter; <add> } <add> <add> /** <add> * Override this method to customize the {@link ConfigurableWebBindingInitializer} the <add> * {@link RequestMappingHandlerAdapter} is configured with. <add> */ <add> protected void extendWebBindingInitializer(ConfigurableWebBindingInitializer webBindingInitializer) { <add> } <add> <add> /** <add> * Provides access to the shared {@link HttpMessageConverter}s used by the <add> * {@link RequestMappingHandlerAdapter} and the {@link ExceptionHandlerExceptionResolver}. <add> * This method cannot be extended directly, use {@link #configureMessageConverters(List)} add custom converters. <add> * Also see {@link #addDefaultHttpMessageConverters(List)} to easily add a set of default converters. <add> */ <add> protected final List<HttpMessageConverter<?>> getMessageConverters() { <add> if (messageConverters == null) { <add> messageConverters = new ArrayList<HttpMessageConverter<?>>(); <add> configureMessageConverters(messageConverters); <add> if (messageConverters.isEmpty()) { <add> addDefaultHttpMessageConverters(messageConverters); <add> } <add> } <add> return messageConverters; <add> } <add> <add> /** <add> * Override this method to add custom {@link HttpMessageConverter}s to use with <add> * the {@link RequestMappingHandlerAdapter} and the {@link ExceptionHandlerExceptionResolver}. <add> * If any converters are added, default converters will not be added automatically. <add> * See {@link #addDefaultHttpMessageConverters(List)} for adding default converters to the list. <add> * @param messageConverters the list to add converters to <add> */ <add> protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { <add> } <add> <add> /** <add> * A method available to subclasses for adding default {@link HttpMessageConverter}s. <add> * @param messageConverters the list to add converters to <add> */ <add> protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) { <add> StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(); <add> stringConverter.setWriteAcceptCharset(false); <add> <add> messageConverters.add(new ByteArrayHttpMessageConverter()); <add> messageConverters.add(stringConverter); <add> messageConverters.add(new ResourceHttpMessageConverter()); <add> messageConverters.add(new SourceHttpMessageConverter<Source>()); <add> messageConverters.add(new XmlAwareFormHttpMessageConverter()); <add> <add> ClassLoader classLoader = getClass().getClassLoader(); <add> if (ClassUtils.isPresent("javax.xml.bind.Binder", classLoader)) { <add> messageConverters.add(new Jaxb2RootElementHttpMessageConverter()); <add> } <add> if (ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", classLoader)) { <add> messageConverters.add(new MappingJacksonHttpMessageConverter()); <add> } <add> if (ClassUtils.isPresent("com.sun.syndication.feed.WireFeed", classLoader)) { <add> messageConverters.add(new AtomFeedHttpMessageConverter()); <add> messageConverters.add(new RssChannelHttpMessageConverter()); <add> } <add> } <add> <add> /** <add> * Returns a {@link FormattingConversionService} for use with annotated controller methods and the <add> * {@code spring:eval} JSP tag. <add> */ <add> @Bean <add> public FormattingConversionService mvcConversionService() { <add> return new DefaultFormattingConversionService(); <add> } <add> <add> /** <add> * Returns {@link Validator} for validating {@code @ModelAttribute} and {@code @RequestBody} arguments of <add> * annotated controller methods. If a JSR-303 implementation is available on the classpath, the returned <add> * instance is LocalValidatorFactoryBean. Otherwise a no-op validator is returned. <add> */ <add> @Bean <add> public Validator mvcValidator() { <add> if (ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) { <add> Class<?> clazz; <add> try { <add> String className = "org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"; <add> clazz = ClassUtils.forName(className, WebMvcConfigurationSupport.class.getClassLoader()); <add> } catch (ClassNotFoundException e) { <add> throw new BeanInitializationException("Could not find default validator"); <add> } catch (LinkageError e) { <add> throw new BeanInitializationException("Could not find default validator"); <add> } <add> return (Validator) BeanUtils.instantiate(clazz); <add> } <add> else { <add> return new Validator() { <add> public boolean supports(Class<?> clazz) { <add> return false; <add> } <add> public void validate(Object target, Errors errors) { <add> } <add> }; <add> } <add> } <add> <add> /** <add> * Returns a {@link HttpRequestHandlerAdapter} for processing requests with {@link HttpRequestHandler}s. <add> */ <add> @Bean <add> public HttpRequestHandlerAdapter httpRequestHandlerAdapter() { <add> return new HttpRequestHandlerAdapter(); <add> } <add> <add> /** <add> * Returns a {@link SimpleControllerHandlerAdapter} for processing requests with interface-based controllers. <add> */ <add> @Bean <add> public SimpleControllerHandlerAdapter simpleControllerHandlerAdapter() { <add> return new SimpleControllerHandlerAdapter(); <add> } <add> <add> /** <add> * Returns a {@link HandlerExceptionResolverComposite} with this chain of exception resolvers: <add> * <ul> <add> * <li>{@link ExceptionHandlerExceptionResolver} for handling exceptions through @{@link ExceptionHandler} methods. <add> * <li>{@link ResponseStatusExceptionResolver} for exceptions annotated with @{@link ResponseStatus}. <add> * <li>{@link DefaultHandlerExceptionResolver} for resolving known Spring exception types <add> * </ul> <add> */ <add> @Bean <add> public HandlerExceptionResolverComposite handlerExceptionResolver() throws Exception { <add> ExceptionHandlerExceptionResolver exceptionHandlerExceptionResolver = new ExceptionHandlerExceptionResolver(); <add> exceptionHandlerExceptionResolver.setMessageConverters(getMessageConverters()); <add> exceptionHandlerExceptionResolver.afterPropertiesSet(); <add> <add> List<HandlerExceptionResolver> exceptionResolvers = new ArrayList<HandlerExceptionResolver>(); <add> exceptionResolvers.add(exceptionHandlerExceptionResolver); <add> exceptionResolvers.add(new ResponseStatusExceptionResolver()); <add> exceptionResolvers.add(new DefaultHandlerExceptionResolver()); <add> <add> HandlerExceptionResolverComposite composite = new HandlerExceptionResolverComposite(); <add> composite.setOrder(0); <add> composite.setExceptionResolvers(exceptionResolvers); <add> return composite; <add> } <add> <add>} <ide><path>org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.java <ide> <ide> import java.util.List; <ide> <del>import org.springframework.context.annotation.Configuration; <ide> import org.springframework.core.convert.converter.Converter; <ide> import org.springframework.format.Formatter; <ide> import org.springframework.format.FormatterRegistry; <ide> import com.sun.corba.se.impl.presentation.rmi.ExceptionHandler; <ide> <ide> /** <del> * Defines options for customizing or adding to the default Spring MVC configuration enabled through the use <del> * of @{@link EnableWebMvc}. The @{@link Configuration} class annotated with @{@link EnableWebMvc} <del> * is the most obvious place to implement this interface. However all @{@link Configuration} classes and more generally <del> * all Spring beans that implement this interface will be detected at startup and given a chance to customize Spring <del> * MVC configuration provided it is enabled through @{@link EnableWebMvc}. <del> * <del> * <p>Implementations of this interface will find it convenient to extend {@link WebMvcConfigurerAdapter} that <del> * provides default method implementations and allows overriding only methods of interest. <add> * Defines configuration callback methods for customizing the default Spring MVC configuration enabled through the <add> * use of @{@link EnableWebMvc}. <add> * <add> * <p>Classes annotated with @{@link EnableWebMvc} can implement this interface in order to be called back and <add> * given a chance to customize the default configuration. The most convenient way to implement this interface is <add> * by extending from {@link WebMvcConfigurerAdapter}, which provides empty method implementations and allows <add> * overriding only the callback methods you're interested in. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @author Keith Donald <ide><path>org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/config/annotation/InterceptorConfigurerTests.java <ide> <ide> import static org.junit.Assert.assertEquals; <ide> import static org.junit.Assert.assertTrue; <add>import static org.junit.Assert.fail; <ide> <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> public void mapWebRequestInterceptor2() throws Exception { <ide> private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) { <ide> PathMatcher pathMatcher = new AntPathMatcher(); <ide> List<HandlerInterceptor> result = new ArrayList<HandlerInterceptor>(); <del> for (MappedInterceptor interceptor : configurer.getInterceptors()) { <del> if (interceptor.matches(lookupPath, pathMatcher)) { <del> result.add(interceptor.getInterceptor()); <add> for (Object i : configurer.getInterceptors()) { <add> if (i instanceof MappedInterceptor) { <add> MappedInterceptor mappedInterceptor = (MappedInterceptor) i; <add> if (mappedInterceptor.matches(lookupPath, pathMatcher)) { <add> result.add(mappedInterceptor.getInterceptor()); <add> } <add> } <add> else if (i instanceof HandlerInterceptor){ <add> result.add((HandlerInterceptor) i); <add> } <add> else { <add> fail("Unexpected interceptor type: " + i.getClass().getName()); <ide> } <ide> } <ide> return result; <ide><path>org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationTests.java <ide> <ide> import static org.easymock.EasyMock.capture; <ide> import static org.easymock.EasyMock.expect; <add>import static org.easymock.EasyMock.isA; <ide> import static org.easymock.EasyMock.replay; <ide> import static org.easymock.EasyMock.verify; <ide> import static org.junit.Assert.assertEquals; <ide> public void getCustomValidator() { <ide> replay(configurer); <ide> <ide> mvcConfiguration.setConfigurers(Arrays.asList(configurer)); <del> mvcConfiguration.validator(); <add> mvcConfiguration.mvcValidator(); <ide> <ide> verify(configurer); <ide> } <ide> public void configureValidator() { <ide> replay(configurer); <ide> <ide> mvcConfiguration.setConfigurers(Arrays.asList(configurer)); <del> mvcConfiguration.validator(); <add> mvcConfiguration.mvcValidator(); <ide> <ide> verify(configurer); <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> @Test <ide> public void handlerExceptionResolver() throws Exception { <del> Capture<List<HttpMessageConverter<?>>> converters = new Capture<List<HttpMessageConverter<?>>>(); <del> Capture<List<HandlerExceptionResolver>> exceptionResolvers = new Capture<List<HandlerExceptionResolver>>(); <del> <del> configurer.configureMessageConverters(capture(converters)); <del> configurer.configureHandlerExceptionResolvers(capture(exceptionResolvers)); <add> configurer.configureMessageConverters(isA(List.class)); <add> configurer.configureHandlerExceptionResolvers(isA(List.class)); <ide> replay(configurer); <ide> <ide> mvcConfiguration.setConfigurers(Arrays.asList(configurer)); <del> mvcConfiguration.handlerExceptionResolver(); <add> List<HandlerExceptionResolver> actual = mvcConfiguration.handlerExceptionResolver().getExceptionResolvers(); <ide> <del> assertEquals(3, exceptionResolvers.getValue().size()); <del> assertTrue(exceptionResolvers.getValue().get(0) instanceof ExceptionHandlerExceptionResolver); <del> assertTrue(exceptionResolvers.getValue().get(1) instanceof ResponseStatusExceptionResolver); <del> assertTrue(exceptionResolvers.getValue().get(2) instanceof DefaultHandlerExceptionResolver); <del> assertTrue(converters.getValue().size() > 0); <add> assertEquals(3, actual.size()); <add> assertTrue(actual.get(0) instanceof ExceptionHandlerExceptionResolver); <add> assertTrue(actual.get(1) instanceof ResponseStatusExceptionResolver); <add> assertTrue(actual.get(2) instanceof DefaultHandlerExceptionResolver); <ide> <ide> verify(configurer); <ide> }
7
Java
Java
fix absolute paths when transforming resources
2146e137873f51cddcff9b1d01bd6c229778098c
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceTransformerSupport.java <ide> protected Mono<String> resolveUrlPath(String resourcePath, ServerWebExchange exc <ide> */ <ide> protected String toAbsolutePath(String path, ServerWebExchange exchange) { <ide> String requestPath = exchange.getRequest().getURI().getPath(); <del> String absolutePath = StringUtils.applyRelativePath(requestPath, path); <add> String absolutePath = path.startsWith("/") ? path : StringUtils.applyRelativePath(requestPath, path); <ide> return StringUtils.cleanPath(absolutePath); <ide> } <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceTransformerSupportTests.java <ide> public void resolveUrlPathWithRelativePathInParentDirectory() { <ide> assertEquals("../bar-11e16cf79faee7ac698c805cf28248d2.css", actual); <ide> } <ide> <add> @Test <add> public void toAbsolutePath() { <add> MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/resources/main.css")); <add> String absolute = this.transformer.toAbsolutePath("img/image.png", exchange); <add> assertEquals("/resources/img/image.png", absolute); <add> <add> absolute = this.transformer.toAbsolutePath("/img/image.png", exchange); <add> assertEquals("/img/image.png", absolute); <add> } <add> <ide> private Resource getResource(String filePath) { <ide> return new ClassPathResource("test/" + filePath, getClass()); <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceTransformerSupport.java <ide> protected String resolveUrlPath(String resourcePath, HttpServletRequest request, <ide> * @return the absolute request path for the given resource path <ide> */ <ide> protected String toAbsolutePath(String path, HttpServletRequest request) { <del> ResourceUrlProvider urlProvider = findResourceUrlProvider(request); <del> Assert.state(urlProvider != null, "No ResourceUrlProvider"); <del> String requestPath = urlProvider.getUrlPathHelper().getRequestUri(request); <del> String absolutePath = StringUtils.applyRelativePath(requestPath, path); <add> String absolutePath = path; <add> if(!path.startsWith("/")) { <add> ResourceUrlProvider urlProvider = findResourceUrlProvider(request); <add> Assert.state(urlProvider != null, "No ResourceUrlProvider"); <add> String requestPath = urlProvider.getUrlPathHelper().getRequestUri(request); <add> absolutePath = StringUtils.applyRelativePath(requestPath, path); <add> } <ide> return StringUtils.cleanPath(absolutePath); <ide> } <ide> <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceTransformerSupportTests.java <ide> public class ResourceTransformerSupportTests { <ide> <ide> private TestResourceTransformerSupport transformer; <ide> <del> private final MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); <add> private final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); <ide> <ide> <ide> @Before <ide> public void resolveUrlPathWithRelativePathInParentDirectory() { <ide> assertEquals("../bar-11e16cf79faee7ac698c805cf28248d2.css", actual); <ide> } <ide> <add> @Test <add> public void toAbsolutePath() { <add> String absolute = this.transformer.toAbsolutePath("img/image.png", <add> new MockHttpServletRequest("GET", "/resources/style.css")); <add> assertEquals("/resources/img/image.png", absolute); <add> <add> absolute = this.transformer.toAbsolutePath("/img/image.png", <add> new MockHttpServletRequest("GET", "/resources/style.css")); <add> assertEquals("/img/image.png", absolute); <add> } <add> <ide> private Resource getResource(String filePath) { <ide> return new ClassPathResource("test/" + filePath, getClass()); <ide> }
4
Python
Python
fix error messages and style
1d68a60bcf39a433186797f8ad6f25ecf72cc7ca
<ide><path>keras/layers/attention/multi_head_attention.py <ide> def _compute_causal_mask(self, query, value=None): <ide> return tf.linalg.band_part( # creates a lower triangular matrix <ide> tf.ones((1, q_seq_length, v_seq_length), tf.bool), -1, 0 <ide> ) <add> <add> def compute_output_shape(self, query_shape, value_shape, key_shape=None): <add> <add> if key_shape is None: <add> key_shape = value_shape <add> <add> query_shape = tf.TensorShape(query_shape) <add> value_shape = tf.TensorShape(value_shape) <add> key_shape = tf.TensorShape(key_shape) <add> <add> if query_shape[-1] != value_shape[-1]: <add> raise ValueError( <add> "The last dimension of `query_shape` and `value_shape` " <add> f"must be equal, but are {query_shape[-1]}, {value_shape[-1]}. " <add> "Received: query_shape={query_shape}, value_shape={value_shape}" <add> ) <add> <add> if value_shape[1:-1] != key_shape[1:-1]: <add> raise ValueError( <add> "All dimensions of `value` and `key`, except the last one, " <add> f"must be equal. Received {value_shape} and " <add> f"{key_shape}" <add> ) <add> <add> if self._output_shape: <add> return query_shape[:-1].concatenate(self._output_shape) <add> <add> return query_shape <ide><path>keras/layers/attention/multi_head_attention_test.py <ide> def test_masks_are_cast_to_bool(self): <ide> attention_mask=float_mask, <ide> ) <ide> <add> @parameterized.named_parameters( <add> ("without_key_same_proj", [40, 80], [20, 80], None, None), <add> ("with_key_same_proj", [40, 80], [20, 80], [20, 30], None), <add> ("wihtout_key_different_proj", [40, 80], [20, 80], None, [30, 40]), <add> ("with_key_different_proj", [40, 80], [20, 80], [20, 30], [15, 50]), <add> ( <add> "high_dim_same_proj", <add> [40, 20, 30, 80], <add> [10, 10, 50, 80], <add> [10, 10, 50, 20], <add> None, <add> ), <add> ( <add> "high_dim_different_proj", <add> [40, 20, 30, 80], <add> [10, 10, 50, 80], <add> [10, 10, 50, 20], <add> [30, 20], <add> ), <add> ) <add> def test_compute_output_shape( <add> self, query_dims, value_dims, key_dims, output_shape <add> ): <add> """Test computed shape is equal to the layer output's shape.""" <add> test_layer = keras.layers.MultiHeadAttention( <add> num_heads=2, <add> key_dim=2, <add> value_dim=2, <add> output_shape=output_shape, <add> ) <add> batch_size = None <add> query_shape = [batch_size] + query_dims <add> value_shape = [batch_size] + value_dims <add> <add> if key_dims: <add> key_shape = [batch_size] + key_dims <add> else: <add> key_shape = None <add> <add> query = keras.Input(query_shape[1:]) <add> value = keras.Input(value_shape[1:]) <add> if key_shape: <add> key = keras.Input(key_shape[1:]) <add> else: <add> key = None <add> output = test_layer(query=query, value=value, key=key) <add> comp_output_shape = test_layer.compute_output_shape( <add> query_shape, value_shape, key_shape <add> ) <add> self.assertListEqual( <add> output.shape.as_list(), comp_output_shape.as_list() <add> ) <add> <add> @parameterized.named_parameters( <add> ("query_value_dim_mismatch", (None, 40, 80), (None, 20, 70), None), <add> ( <add> "key_value_dim_mismatch", <add> (None, 40, 80), <add> (None, 20, 80), <add> (None, 10, 70), <add> ), <add> ( <add> "key_value_dim_mismatch_high_dim", <add> (None, 40, 20, 30, 80), <add> (None, 10, 10, 50, 80), <add> (None, 10, 15, 50, 20), <add> ), <add> ) <add> def test_compute_output_shape_raises_error( <add> self, query_shape, value_shape, key_shape <add> ): <add> """Test dimension mismatches""" <add> test_layer = keras.layers.MultiHeadAttention( <add> num_heads=4, <add> key_dim=2, <add> value_dim=2, <add> ) <add> with self.assertRaisesRegex(ValueError, r"must be equal"): <add> test_layer.compute_output_shape(query_shape, value_shape, key_shape) <add> <ide> <ide> class SubclassAttention(keras.layers.MultiHeadAttention): <ide> def _build_attention(self, qkv_rank):
2
Python
Python
use getfqdn to make sure urls are fully qualified
181d37321ad08e3b87df2a1f87e16b8b74a24454
<ide><path>airflow/jobs.py <ide> def __init__( <ide> executor=executors.DEFAULT_EXECUTOR, <ide> heartrate=conf.getfloat('scheduler', 'JOB_HEARTBEAT_SEC'), <ide> *args, **kwargs): <del> self.hostname = socket.gethostname() <add> self.hostname = socket.getfqdn() <ide> self.executor = executor <ide> self.executor_class = executor.__class__.__name__ <ide> self.start_date = datetime.now() <ide><path>airflow/models.py <ide> def run( <ide> self.clear_xcom_data() <ide> self.job_id = job_id <ide> iso = datetime.now().isoformat() <del> self.hostname = socket.gethostname() <add> self.hostname = socket.getfqdn() <ide> self.operator = task.__class__.__name__ <ide> <ide> if self.state == State.RUNNING: <ide><path>airflow/www/app.py <ide> def integrate_plugins(): <ide> @app.context_processor <ide> def jinja_globals(): <ide> return { <del> 'hostname': socket.gethostname(), <add> 'hostname': socket.getfqdn(), <ide> } <ide> <ide> @app.teardown_appcontext <ide><path>airflow/www/views.py <ide> def dag_details(self): <ide> @current_app.errorhandler(404) <ide> def circles(self): <ide> return render_template( <del> 'airflow/circles.html', hostname=socket.gethostname()), 404 <add> 'airflow/circles.html', hostname=socket.getfqdn()), 404 <ide> <ide> @current_app.errorhandler(500) <ide> def show_traceback(self): <ide> from airflow.utils import asciiart as ascii_ <ide> return render_template( <ide> 'airflow/traceback.html', <del> hostname=socket.gethostname(), <add> hostname=socket.getfqdn(), <ide> nukular=ascii_.nukular, <ide> info=traceback.format_exc()), 500 <ide> <ide> def log(self): <ide> host = ti.hostname <ide> log_loaded = False <ide> <del> if socket.gethostname() == host: <add> if socket.getfqdn() == host: <ide> try: <ide> f = open(loc) <ide> log += "".join(f.readlines())
4
Go
Go
add api test for empty services list
65e72133a11ea3e6873f62039956bbd70548a5a7
<ide><path>integration-cli/daemon_swarm.go <ide> func (d *SwarmDaemon) listNodes(c *check.C) []swarm.Node { <ide> return nodes <ide> } <ide> <add>func (d *SwarmDaemon) listServices(c *check.C) []swarm.Service { <add> status, out, err := d.SockRequest("GET", "/services", nil) <add> c.Assert(err, checker.IsNil) <add> c.Assert(status, checker.Equals, http.StatusOK, check.Commentf("output: %q", string(out))) <add> <add> services := []swarm.Service{} <add> c.Assert(json.Unmarshal(out, &services), checker.IsNil) <add> return services <add>} <add> <ide> func (d *SwarmDaemon) updateSwarm(c *check.C, f ...specConstructor) { <ide> var sw swarm.Swarm <ide> status, out, err := d.SockRequest("GET", "/swarm", nil) <ide><path>integration-cli/docker_api_swarm_test.go <ide> func (s *DockerSwarmSuite) TestApiSwarmPromoteDemote(c *check.C) { <ide> waitAndAssert(c, defaultReconciliationTimeout, d2.checkControlAvailable, checker.True) <ide> } <ide> <add>func (s *DockerSwarmSuite) TestApiSwarmServicesEmptyList(c *check.C) { <add> testRequires(c, Network) <add> d := s.AddDaemon(c, true, true) <add> <add> services := d.listServices(c) <add> c.Assert(services, checker.NotNil) <add> c.Assert(len(services), checker.Equals, 0, check.Commentf("services: %#v", services)) <add>} <add> <ide> func (s *DockerSwarmSuite) TestApiSwarmServicesCreate(c *check.C) { <ide> testRequires(c, Network) <ide> d := s.AddDaemon(c, true, true)
2
Text
Text
add id property to common configuration
aed3d40263b77aa5014d8c3734e2dcbc9ca5122d
<ide><path>docs/02-Scales.md <ide> Name | Type | Default | Description <ide> type | String | Chart specific. | Type of scale being employed. Custom scales can be created and registered with a string key. Options: ["category"](#scales-category-scale), ["linear"](#scales-linear-scale), ["logarithmic"](#scales-logarithmic-scale), ["time"](#scales-time-scale), ["radialLinear"](#scales-radial-linear-scale) <ide> display | Boolean | true | If true, show the scale including gridlines, ticks, and labels. Overrides *gridLines.display*, *scaleLabel.display*, and *ticks.display*. <ide> position | String | "left" | Position of the scale. Possible values are 'top', 'left', 'bottom' and 'right'. <add>id | String | | The ID is used to link datasets and scale axes together. The properties `datasets.xAxisID` or `datasets.yAxisID` have to match the scale properties `scales.xAxes.id` or `scales.yAxes.id`. This is especially needed if multi-axes charts are used. <ide> beforeUpdate | Function | undefined | Callback called before the update process starts. Passed a single argument, the scale instance. <ide> beforeSetDimensions | Function | undefined | Callback that runs before dimensions are set. Passed a single argument, the scale instance. <ide> afterSetDimensions | Function | undefined | Callback that runs after dimensions are set. Passed a single argument, the scale instance.
1
Ruby
Ruby
use identifiers for template equality
682368d4ba0bb4548f896d02bc4e038ee8ba6b4d
<ide><path>actionpack/lib/action_view/renderer/template_renderer.rb <ide> def determine_template(options) #:nodoc: <ide> with_fallbacks { find_template(options[:file], options[:prefix], false, keys) } <ide> elsif options.key?(:inline) <ide> handler = Template.handler_class_for_extension(options[:type] || "erb") <del> Template.new(options[:inline], "inline template", handler, { :locals => keys }) <add> Template::Inline.new(options[:inline], handler, :locals => keys) <ide> elsif options.key?(:template) <ide> options[:template].respond_to?(:render) ? <ide> options[:template] : find_template(options[:template], options[:prefix], false, keys) <ide><path>actionpack/lib/action_view/template.rb <ide> class Template <ide> autoload :Error <ide> autoload :Handler <ide> autoload :Handlers <add> autoload :Inline <ide> autoload :Text <ide> end <ide> <ide> def rerender(view) <ide> end <ide> end <ide> <add> def hash <add> identifier.hash <add> end <add> <add> def eql?(other) <add> other.is_a?(Template) && other.identifier == identifier <add> end <add> <ide> def inspect <ide> @inspect ||= <ide> if defined?(Rails.root) <ide><path>actionpack/lib/action_view/template/inline.rb <add>require 'digest/md5' <add> <add>module ActionView <add> class Template <add> class Inline < ::ActionView::Template <add> def initialize(source, handler, options={}) <add> super(source, "inline template", handler, options) <add> end <add> <add> def md5_source <add> @md5_source ||= Digest::MD5.hexdigest(source) <add> end <add> <add> def eql?(other) <add> other.is_a?(Inline) && other.md5_source == md5_source <add> end <add> end <add> end <add>end <add> <ide>\ No newline at end of file <ide><path>actionpack/test/controller/new_base/render_once_test.rb <ide> class TestWithResolverCache < Rack::TestCase <ide> include Tests <ide> end <ide> <del> # TODO This still needs to be implemented and supported. <del> # class TestWithoutResolverCache < Rack::TestCase <del> # testing RenderTemplate::RenderOnceController <del> # include Tests <del> # <del> # def setup <del> # RenderTemplate::RenderOnceController::RESOLVER.stubs(:caching?).returns(false) <del> # end <del> # end <add> class TestWithoutResolverCache < Rack::TestCase <add> testing RenderTemplate::RenderOnceController <add> include Tests <add> <add> def setup <add> RenderTemplate::RenderOnceController::RESOLVER.stubs(:caching?).returns(false) <add> end <add> end <ide> end <ide><path>actionpack/test/template/template_test.rb <ide> def test_rerender_raises_an_error_without_virtual_path <ide> end <ide> end <ide> <add> def test_inline_template_is_only_equal_if_source_match <add> inline1 = ActionView::Template::Inline.new("sample", ERBHandler) <add> inline2 = ActionView::Template::Inline.new("sample", ERBHandler) <add> inline3 = ActionView::Template::Inline.new("other", ERBHandler) <add> assert inline1.eql?(inline2) <add> assert !inline1.eql?(inline3) <add> end <add> <ide> if "ruby".encoding_aware? <ide> def test_resulting_string_is_utf8 <ide> @template = new_template
5
Text
Text
move gibfahn to emeritus
8a57788efebe6e55242236119190b37bdf5b9d1b
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Jiawen Geng** &lt;technicalcute@gmail.com&gt; <ide> * [GeoffreyBooth](https://github.com/geoffreybooth) - <ide> **Geoffrey Booth** &lt;webmaster@geoffreybooth.com&gt; (he/him) <del>* [gibfahn](https://github.com/gibfahn) - <del>**Gibson Fahnestock** &lt;gibfahn@gmail.com&gt; (he/him) <ide> * [gireeshpunathil](https://github.com/gireeshpunathil) - <ide> **Gireesh Punathil** &lt;gpunathi@in.ibm.com&gt; (he/him) <ide> * [guybedford](https://github.com/guybedford) - <ide> For information about the governance of the Node.js project, see <ide> **Alexander Makarenko** &lt;estliberitas@gmail.com&gt; <ide> * [firedfox](https://github.com/firedfox) - <ide> **Daniel Wang** &lt;wangyang0123@gmail.com&gt; <add>* [gibfahn](https://github.com/gibfahn) - <add>**Gibson Fahnestock** &lt;gibfahn@gmail.com&gt; (he/him) <ide> * [glentiki](https://github.com/glentiki) - <ide> **Glen Keane** &lt;glenkeane.94@gmail.com&gt; (he/him) <ide> * [iarna](https://github.com/iarna) -
1
Ruby
Ruby
make detection of invalid plan locale-independent
d507ae2a74a6a995d90e8295a746c02d1df20a1a
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def exec_cache(sql, name, binds) <ide> # <ide> # Check here for more details: <ide> # https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573 <del> CACHED_PLAN_HEURISTIC = "cached plan must not change result type" <ide> def is_cached_plan_failure?(e) <ide> pgerror = e.cause <del> code = pgerror.result.result_error_field(PG::PG_DIAG_SQLSTATE) <del> code == FEATURE_NOT_SUPPORTED && pgerror.message.include?(CACHED_PLAN_HEURISTIC) <add> pgerror.result.result_error_field(PG::PG_DIAG_SQLSTATE) == FEATURE_NOT_SUPPORTED && <add> pgerror.result.result_error_field(PG::PG_DIAG_SOURCE_FUNCTION) == "RevalidateCachedQuery" <ide> rescue <ide> false <ide> end
1
Java
Java
use t instead of value to allow for ide naming
5b6d1f8c8e9e4adc3fe31388811aa4876a5afba2
<ide><path>src/main/java/io/reactivex/MaybeObserver.java <ide> * <p> <ide> * The {@link Maybe} will not call this method if it calls {@link #onError}. <ide> * <del> * @param value <add> * @param t <ide> * the item emitted by the Maybe <ide> */ <del> void onSuccess(T value); <add> void onSuccess(T t); <ide> <ide> /** <ide> * Notifies the MaybeObserver that the {@link Maybe} has experienced an error condition. <ide><path>src/main/java/io/reactivex/Observer.java <ide> * The {@code Observable} will not call this method again after it calls either {@link #onComplete} or <ide> * {@link #onError}. <ide> * <del> * @param value <add> * @param t <ide> * the item emitted by the Observable <ide> */ <del> void onNext(T value); <add> void onNext(T t); <ide> <ide> /** <ide> * Notifies the Observer that the {@link Observable} has experienced an error condition. <ide><path>src/main/java/io/reactivex/SingleObserver.java <ide> * <p> <ide> * The {@link Single} will not call this method if it calls {@link #onError}. <ide> * <del> * @param value <add> * @param t <ide> * the item emitted by the Single <ide> */ <del> void onSuccess(T value); <add> void onSuccess(T t); <ide> <ide> /** <ide> * Notifies the SingleObserver that the {@link Single} has experienced an error condition.
3
Javascript
Javascript
improve .from() error details
fc28761d771e676c57be92c99ab4e04f749c53f4
<ide><path>lib/buffer.js <ide> Buffer.from = function from(value, encodingOrOffset, length) { <ide> return fromArrayBuffer(value, encodingOrOffset, length); <ide> <ide> const valueOf = value.valueOf && value.valueOf(); <del> if (valueOf !== null && valueOf !== undefined && valueOf !== value) <del> return Buffer.from(valueOf, encodingOrOffset, length); <add> if (valueOf != null && <add> valueOf !== value && <add> (typeof valueOf === 'string' || typeof valueOf === 'object')) { <add> return from(valueOf, encodingOrOffset, length); <add> } <ide> <ide> const b = fromObject(value); <ide> if (b) <ide> return b; <ide> <ide> if (typeof value[SymbolToPrimitive] === 'function') { <del> return Buffer.from(value[SymbolToPrimitive]('string'), <del> encodingOrOffset, <del> length); <add> const primitive = value[SymbolToPrimitive]('string'); <add> if (typeof primitive === 'string') { <add> return fromString(primitive, encodingOrOffset); <add> } <ide> } <ide> } <ide>
1