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
Python
Python
fix funnel configuration doc
66828a19b1ae566abe325899467374a17c21970f
<ide><path>src/transformers/models/funnel/configuration_funnel.py <ide> class FunnelConfig(PretrainedConfig): <ide> type_vocab_size (`int`, *optional*, defaults to 3): <ide> The vocabulary size of the `token_type_ids` passed when calling [`FunnelModel`] or [`TFFunnelModel`]. <ide> initializer_range (`float`, *optional*, defaults to 0.1): <del> The standard deviation of the *uniform initializer* for initializing all weight matrices in attention <del> layers. <add> The upper bound of the *uniform initializer* for initializing all weight matrices in attention layers. <ide> initializer_std (`float`, *optional*): <ide> The standard deviation of the *normal initializer* for initializing the embedding matrix and the weight of <ide> linear layers. Will default to 1 for the embedding matrix and the value given by Xavier initialization for
1
Text
Text
update manual steps in getting started guide
5429e8f12e7bf54177ba68eafd65160017b90cde
<ide><path>docs/getting-started.md <ide> pnpm create next-app -- --typescript <ide> <ide> After the installation is complete: <ide> <del>- Run `npm run dev` or `yarn dev` to start the development server on `http://localhost:3000` <add>- Run `npm run dev` or `yarn dev` or `pnpm dev` to start the development server on `http://localhost:3000` <ide> - Visit `http://localhost:3000` to view your application <ide> - Edit `pages/index.js` and see the updated result in your browser <ide> <ide> Install `next`, `react` and `react-dom` in your project: <ide> npm install next react react-dom <ide> # or <ide> yarn add next react react-dom <add># or <add>pnpm add next react react-dom <ide> ``` <ide> <ide> Open `package.json` and add the following `scripts`: <ide> Open `package.json` and add the following `scripts`: <ide> <ide> These scripts refer to the different stages of developing an application: <ide> <del>- `dev` - Runs [`next dev`](/docs/api-reference/cli.md#development) which starts Next.js in development mode <del>- `build` - Runs [`next build`](/docs/api-reference/cli.md#build) which builds the application for production usage <del>- `start` - Runs [`next start`](/docs/api-reference/cli.md#production) which starts a Next.js production server <del>- `lint` - Runs [`next lint`](/docs/api-reference/cli.md#lint) which sets up Next.js' built-in ESLint configuration <add>- `dev` - Runs [`next dev`](/docs/api-reference/cli.md#development) to start Next.js in development mode <add>- `build` - Runs [`next build`](/docs/api-reference/cli.md#build) to build the application for production usage <add>- `start` - Runs [`next start`](/docs/api-reference/cli.md#production) to start a Next.js production server <add>- `lint` - Runs [`next lint`](/docs/api-reference/cli.md#lint) to set up Next.js' built-in ESLint configuration <add> <add>Create two directories `pages` and `public` at the root of your application: <ide> <del>Next.js is built around the concept of [pages](/docs/basic-features/pages.md). A page is a [React Component](https://reactjs.org/docs/components-and-props.html) exported from a `.js`, `.jsx`, `.ts`, or `.tsx` file in the `pages` directory. <add>- `pages` - Associated with a route based on their file name. For example `pages/about.js` is mapped to `/about` <add>- `public` - Stores static assets such as images, fonts, etc. Files inside `public` directory can then be referenced by your code starting from the base URL (`/`). <ide> <del>Pages are associated with a route based on their file name. For example `pages/about.js` is mapped to `/about`. You can even add dynamic route parameters with the filename. <add>Next.js is built around the concept of [pages](/docs/basic-features/pages.md). A page is a [React Component](https://reactjs.org/docs/components-and-props.html) exported from a `.js`, `.jsx`, `.ts`, or `.tsx` file in the `pages` directory. You can even add [dynamic route](/docs/routing/dynamic-routes) parameters with the filename. <ide> <del>Create a `pages` directory inside your project. <add>Inside the `pages` directory add the `index.js` file to get started. This is the page that is rendered when the user visits the root of your application <ide> <del>Populate `./pages/index.js` with the following contents: <add>Populate `pages/index.js` with the following contents: <ide> <ide> ```jsx <ide> function HomePage() { <ide> function HomePage() { <ide> export default HomePage <ide> ``` <ide> <add>After the set up is complete: <add> <add>- Run `npm run dev` or `yarn dev` or `pnpm dev` to start the development server on `http://localhost:3000` <add>- Visit `http://localhost:3000` to view your application <add>- Edit `pages/index.js` and see the updated result in your browser <add> <ide> So far, we get: <ide> <ide> - Automatic compilation and [bundling](/docs/advanced-features/compiler.md) <ide> - [React Fast Refresh](https://nextjs.org/blog/next-9-4#fast-refresh) <del>- [Static generation and server-side rendering](/docs/basic-features/data-fetching/overview.md) of [`./pages/`](/docs/basic-features/pages.md) <del>- [Static file serving](/docs/basic-features/static-file-serving.md). `./public/` is mapped to `/` <add>- [Static generation and server-side rendering](/docs/basic-features/data-fetching/overview.md) of [`pages/`](/docs/basic-features/pages.md) <add>- [Static file serving](/docs/basic-features/static-file-serving.md) through `public/` which is mapped to the base URL (`/`) <ide> <ide> In addition, any Next.js application is ready for production from the start. Read more in our [Deployment documentation](/docs/deployment.md). <ide>
1
Java
Java
fix typo in modelandviewmethodreturnvaluehandler
83ea0fb9e043670f8153147c1a79026acfa98f54
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * <ide> * <p>If the return value is {@code null}, the <ide> * {@link ModelAndViewContainer#setRequestHandled(boolean)} flag is set to <del> * {@code false} to indicate the request was handled directly. <add> * {@code true} to indicate the request was handled directly. <ide> * <ide> * <p>A {@link ModelAndView} return type has a set purpose. Therefore this <ide> * handler should be configured ahead of handlers that support any return
1
Javascript
Javascript
fix webp extension with no handler
33155151cd64bcac5797fec5c3cd856bd32048f5
<ide><path>examples/js/loaders/GLTFLoader.js <ide> THREE.GLTFLoader = ( function () { <ide> <ide> var extension = textureDef.extensions[ name ]; <ide> var source = json.images[ extension.source ]; <del> var loader = source.uri ? parser.options.manager.getHandler( source.uri ) : parser.textureLoader; <add> <add> var loader; <add> if ( source.uri ) { <add> <add> loader = parser.options.getHandler( source.uri ); <add> <add> } <add> <add> if ( ! loader ) { <add> <add> loader = parser.textureLoader; <add> <add> } <ide> <ide> return this.detectSupport().then( function ( isSupported ) { <ide> <ide><path>examples/jsm/loaders/GLTFLoader.js <ide> var GLTFLoader = ( function () { <ide> <ide> var extension = textureDef.extensions[ name ]; <ide> var source = json.images[ extension.source ]; <del> var loader = source.uri ? parser.options.manager.getHandler( source.uri ) : parser.textureLoader; <add> <add> var loader; <add> if ( source.uri ) { <add> <add> loader = parser.options.getHandler( source.uri ); <add> <add> } <add> <add> if ( ! loader ) { <add> <add> loader = parser.textureLoader; <add> <add> } <ide> <ide> return this.detectSupport().then( function ( isSupported ) { <ide>
2
Text
Text
add v3.6.0 to changelog
f4c7876f1ca0b3092a58121cff20d79d617c30de
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v3.6.0-beta.4 (November 12, 2018) <add>### v3.6.0 (December 6, 2018) <ide> <add>- [#17025](https://github.com/emberjs/ember.js/pull/17025) / [#17034](https://github.com/emberjs/ember.js/pull/17034) / [#17036](https://github.com/emberjs/ember.js/pull/17036) / [#17038](https://github.com/emberjs/ember.js/pull/17038) / [#17040](https://github.com/emberjs/ember.js/pull/17040) / [#17041](https://github.com/emberjs/ember.js/pull/17041) / [#17061](https://github.com/emberjs/ember.js/pull/17061) [FEATURE] Final stage of the router service RFC (see [emberjs/rfcs#95](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md) <add>- [#16795](https://github.com/emberjs/ember.js/pull/16795) [FEATURE] Native Class Constructor Update (see [emberjs/rfcs#337](https://github.com/emberjs/rfcs/blob/master/text/0337-native-class-constructor-update.md) <add>- [#17188](https://github.com/emberjs/ember.js/pull/17188) / [#17246](https://github.com/emberjs/ember.js/pull/17246) [BUGFIX] Adds a second dist build which targets IE and early Android versions. Enables avoiding errors when using native classes without transpilation. <add>- [#17238](https://github.com/emberjs/ember.js/pull/17238) [DEPRECATION] Deprecate calling `A` as a constructor <add>- [#16956](https://github.com/emberjs/ember.js/pull/16956) [DEPRECATION] Deprecate Ember.merge <add>- [#17220](https://github.com/emberjs/ember.js/pull/17220) [BUGFIX] Fix cycle detection in Ember.copy <add>- [#17227](https://github.com/emberjs/ember.js/pull/17227) [BUGFIX] Fix mouseEnter/Leave event delegation w/o jQuery for SVG & IE11 <add>- [#17233](https://github.com/emberjs/ember.js/pull/17233) [BUGFIX] Reverts EmberError to be a standard function <add>- [#17251](https://github.com/emberjs/ember.js/pull/17251) [BUGFIX] Prevent errors with debug compiled templates in prod. <add>- [#17241](https://github.com/emberjs/ember.js/pull/17241) [BUGFIX] Fix line endings of component blueprint on Windows <add>- [#17271](https://github.com/emberjs/ember.js/pull/17271) [BUGFIX] Update backburner.js to 2.4.2. <ide> - [#17184](https://github.com/emberjs/ember.js/pull/17184) [BUGFIX] Ensures removeAllListeners does not break subsequent adds <del>- [#17186](https://github.com/emberjs/ember.js/pull/17186) [BUGFIX] Fix RouteInfo QP mutability <del>- [#17192](https://github.com/emberjs/ember.js/pull/17192) [BUGFIX] currentRoute should respect substates <del> <del>### v3.6.0-beta.3 (November 5, 2018) <del> <ide> - [#17169](https://github.com/emberjs/ember.js/pull/17169) [BUGFIX] Add default implementations of Component lifecycle hooks <del>- [#17165](https://github.com/emberjs/ember.js/pull/17165) [BUGFIX] Fix RouteInfo.find and transition.froms <del>- [#17180](https://github.com/emberjs/ember.js/pull/17180) [BUGFIX] Router Service State should be correct in events <del> <del>### v3.6.0-beta.2 (October 29, 2018) <del> <del>- [#17130](https://github.com/emberjs/ember.js/pull/17130) [BUGFIX] Ensure that timers scheduled after a system sleep are fired properly. <ide> - [#17137](https://github.com/emberjs/ember.js/pull/17137) [BUGFIX] Assert when local variables shadow modifier invocations <ide> - [#17132](https://github.com/emberjs/ember.js/pull/17132) [BUGFIX] Assert when local variables shadow helper invocations <ide> - [#17135](https://github.com/emberjs/ember.js/pull/17135) [BUGFIX] Ensure local variables win over helper invocations <del>- [#16923](https://github.com/emberjs/ember.js/pull/16923) [BUGFIX] ES6 classes on/removeListener and observes/removeObserver interop v2 <del>- [#17128](https://github.com/emberjs/ember.js/pull/17128) [BUGFIX] Fix sourcemaping issues due to multiple sourcemap directives. <del>- [#17115](https://github.com/emberjs/ember.js/pull/17115) [BUGFIX] Pass the event parameter to sendAction <add>- [#16923](https://github.com/emberjs/ember.js/pull/16923) [BUGFIX] ES6 classes on/removeListener and observes/removeObserver interop <ide> - [#17153](https://github.com/emberjs/ember.js/pull/17153) [BUGFIX] Blueprints can generate components with a single word name <del> <del>### v3.6.0-beta.1 (October 8, 2018) <del> <del>- [#16956](https://github.com/emberjs/ember.js/pull/16956) [DEPRECATION] Deprecate Ember.merge <del>- [#16795](https://github.com/emberjs/ember.js/pull/16795) [FEATURE] Native Class Constructor Update (see [emberjs/rfcs#337](https://github.com/emberjs/rfcs/blob/master/text/0337-native-class-constructor-update.md) <ide> - [#16865](https://github.com/emberjs/ember.js/pull/16865) / [#16899](https://github.com/emberjs/ember.js/pull/16899) / [#16914](https://github.com/emberjs/ember.js/pull/16914) / [#16897](https://github.com/emberjs/ember.js/pull/16897) / [#16913](https://github.com/emberjs/ember.js/pull/16913) / [#16894](https://github.com/emberjs/ember.js/pull/16894) / [#16896](https://github.com/emberjs/ember.js/pull/16896) [BUGFIX] Support RFC 232 and RFC 268 style tests with Mocha blueprints <del>- [#17025](https://github.com/emberjs/ember.js/pull/17025) / [#17034](https://github.com/emberjs/ember.js/pull/17034) / [#17036](https://github.com/emberjs/ember.js/pull/17036) / [#17038](https://github.com/emberjs/ember.js/pull/17038) / [#17040](https://github.com/emberjs/ember.js/pull/17040) / [#17041](https://github.com/emberjs/ember.js/pull/17041) / [#17061](https://github.com/emberjs/ember.js/pull/17061) [FEATURE] Final stage of the router service RFC (see [emberjs/rfcs#95](https://github.com/emberjs/rfcs/blob/master/text/0095-router-service.md) <ide> - [#17051](https://github.com/emberjs/ember.js/pull/17051) Update glimmer-vm packages to 0.36.4 <ide> <ide> ### v3.5.1 (October 29, 2018)
1
Text
Text
add v15.4.0 link to changelog.md
04e54189348d0ec7b68947d90496f12d71b2479c
<ide><path>CHANGELOG.md <ide> release. <ide> </tr> <ide> <tr> <ide> <td valign="top"> <del><b><a href="doc/changelogs/CHANGELOG_V15.md#15.3.0">15.3.0</a></b><br/> <add><b><a href="doc/changelogs/CHANGELOG_V15.md#15.4.0">15.4.0</a></b><br/> <add><a href="doc/changelogs/CHANGELOG_V15.md#15.3.0">15.3.0</a><br/> <ide> <a href="doc/changelogs/CHANGELOG_V15.md#15.2.1">15.2.1</a><br/> <ide> <a href="doc/changelogs/CHANGELOG_V15.md#15.2.0">15.2.0</a><br/> <ide> <a href="doc/changelogs/CHANGELOG_V15.md#15.1.0">15.1.0</a><br/>
1
Ruby
Ruby
remove deprecated documentation
1a9b1edb49437076b0b9033876a7b7f57d38f4b9
<ide><path>actionpack/lib/action_dispatch/testing/performance_test.rb <ide> module ActionDispatch <ide> # An integration test that runs a code profiler on your test methods. <ide> # Profiling output for combinations of each test method, measurement, and <ide> # output format are written to your tmp/performance directory. <del> # <del> # By default, process_time is measured and both flat and graph_html output <del> # formats are written, so you'll have two output files per test method. <ide> class PerformanceTest < ActionDispatch::IntegrationTest <ide> include ActiveSupport::Testing::Performance <ide> end
1
Javascript
Javascript
make temp file path configurable
d610fad39018a7f21904f2f8fa496c21472f05cb
<ide><path>benchmark/fs/read-stream-throughput.js <ide> <ide> const path = require('path'); <ide> const common = require('../common.js'); <del>const filename = path.resolve(__dirname, <add>const filename = path.resolve(process.env.NODE_TMPDIR || __dirname, <ide> `.removeme-benchmark-garbage-${process.pid}`); <ide> const fs = require('fs'); <ide> const assert = require('assert'); <ide><path>benchmark/fs/readfile.js <ide> <ide> const path = require('path'); <ide> const common = require('../common.js'); <del>const filename = path.resolve(__dirname, <add>const filename = path.resolve(process.env.NODE_TMPDIR || __dirname, <ide> `.removeme-benchmark-garbage-${process.pid}`); <ide> const fs = require('fs'); <ide> <ide><path>benchmark/fs/write-stream-throughput.js <ide> <ide> const path = require('path'); <ide> const common = require('../common.js'); <del>const filename = path.resolve(__dirname, <add>const filename = path.resolve(process.env.NODE_TMPDIR || __dirname, <ide> `.removeme-benchmark-garbage-${process.pid}`); <ide> const fs = require('fs'); <ide> <ide><path>test/parallel/test-benchmark-fs.js <ide> 'use strict'; <ide> <del>require('../common'); <add>const common = require('../common'); <ide> const runBenchmark = require('../common/benchmark'); <ide> <ide> runBenchmark('fs', [ <ide> 'n=1', <ide> 'size=1', <del> 'dur=1', <add> 'dur=0.1', <ide> 'len=1024', <ide> 'concurrent=1', <ide> 'pathType=relative', <ide> 'statType=fstat', <ide> 'statSyncType=fstatSync', <ide> 'encodingType=buf', <ide> 'filesize=1024' <del>]); <add>], { NODE_TMPDIR: common.tmpDir });
4
Ruby
Ruby
remove unnecessary caching
ec9c6d5846a4048c131aae70c2d338d8a3896086
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> require 'action_dispatch/journey' <ide> require 'forwardable' <del>require 'thread_safe' <ide> require 'active_support/concern' <ide> require 'active_support/core_ext/object/to_query' <ide> require 'active_support/core_ext/hash/slice' <ide> class RouteSet <ide> class Dispatcher < Routing::Endpoint <ide> def initialize(raise_on_name_error) <ide> @raise_on_name_error = raise_on_name_error <del> @controller_class_names = ThreadSafe::Cache.new <ide> end <ide> <ide> def dispatcher?; true; end <ide> def controller(params, raise_on_name_error=true) <ide> <ide> protected <ide> <del> attr_reader :controller_class_names <del> <ide> def controller_reference(controller_param) <del> const_name = controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller" <add> const_name = "#{controller_param.camelize}Controller" <ide> ActiveSupport::Dependencies.constantize(const_name) <ide> end <ide>
1
Javascript
Javascript
add benchmark for vm.createcontext
1294c7e48564a549ef391786b67798d29238aace
<ide><path>benchmark/vm/create-context.js <add>'use strict'; <add> <add>const common = require('../common.js'); <add> <add>const bench = common.createBenchmark(main, { <add> n: [100] <add>}); <add> <add>const vm = require('vm'); <add> <add>const ctxFn = new vm.Script(` <add> var b = Math.random(); <add> var c = a + b; <add>`); <add> <add>function main({ n }) { <add> bench.start(); <add> let context; <add> for (let i = 0; i < n; i++) { <add> context = vm.createContext({ a: 'a' }); <add> } <add> bench.end(n); <add> ctxFn.runInContext(context); <add>}
1
Javascript
Javascript
consolidate hook events
0e976e136c0d0841aec71de4a4f6163963763d3f
<ide><path>src/isomorphic/hooks/ReactComponentTreeHook.js <ide> function remove(id) { <ide> delete itemByKey[key]; <ide> } <ide> <del>function create(id, element) { <add>function create(id, element, parentID) { <ide> var key = getKeyFromID(id); <ide> itemByKey[key] = { <ide> element, <del> parentID: null, <add> parentID, <ide> text: null, <ide> childIDs: [], <ide> isMounted: false, <ide> var ReactComponentTreeHook = { <ide> } <ide> invariant( <ide> nextChild.parentID === id, <del> 'Expected onSetParent() and onSetChildren() to be consistent (%s ' + <del> 'has parents %s and %s).', <add> 'Expected onBeforeMountComponent() parent and onSetChildren() to ' + <add> 'be consistent (%s has parents %s and %s).', <ide> nextChildID, <ide> nextChild.parentID, <ide> id <ide> ); <ide> } <ide> }, <ide> <del> onSetParent(id, parentID) { <del> var item = get(id); <del> item.parentID = parentID; <del> }, <add> onBeforeMountComponent(id, element, parentID) { <add> create(id, element, parentID); <ide> <del> onInstantiateComponent(id, element) { <del> create(id, element); <del> }, <del> <del> onBeforeMountComponent(id, element) { <del> var item = get(id); <del> item.element = element; <add> if (parentID === 0) { <add> rootIDs[id] = true; <add> } <ide> }, <ide> <ide> onBeforeUpdateComponent(id, element) { <ide> var ReactComponentTreeHook = { <ide> item.isMounted = true; <ide> }, <ide> <del> onMountRootComponent(id) { <del> rootIDs[id] = true; <del> }, <del> <ide> onUpdateComponent(id) { <ide> var item = get(id); <ide> if (!item || !item.isMounted) { <ide> var ReactComponentTreeHook = { <ide> <ide> onUnmountComponent(id) { <ide> var item = get(id); <del> item.isMounted = false; <add> if (item) { <add> // We need to check if it exists. <add> // `item` might not exist if it is inside an error boundary, and a sibling <add> // error boundary child threw while mounting. Then this instance never <add> // got a chance to mount, but it still gets an unmounting event during <add> // the error boundary cleanup. <add> item.isMounted = false; <add> } <ide> unmountedIDs[id] = true; <ide> delete rootIDs[id]; <ide> }, <ide><path>src/renderers/dom/client/ReactMount.js <ide> function mountComponentIntoNode( <ide> transaction, <ide> null, <ide> ReactDOMContainerInfo(wrapperInstance, container), <del> context <add> context, <add> 0 /* parentDebugID */ <ide> ); <ide> <ide> if (markerName) { <ide> var ReactMount = { <ide> var wrapperID = componentInstance._instance.rootID; <ide> instancesByReactRootID[wrapperID] = componentInstance; <ide> <del> if (__DEV__) { <del> // The instance here is TopLevelWrapper so we report mount for its child. <del> ReactInstrumentation.debugTool.onMountRootComponent( <del> componentInstance._renderedComponent._debugID <del> ); <del> } <del> <ide> return componentInstance; <ide> }, <ide> <ide><path>src/renderers/dom/server/ReactServerRendering.js <ide> function renderToStringImpl(element, makeStaticMarkup) { <ide> transaction, <ide> null, <ide> ReactDOMContainerInfo(), <del> emptyObject <add> emptyObject, <add> 0 /* parentDebugID */ <ide> ); <ide> if (__DEV__) { <ide> ReactInstrumentation.debugTool.onUnmountComponent( <ide><path>src/renderers/dom/shared/ReactDOMComponent.js <ide> if (__DEV__) { <ide> ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content); <ide> ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID); <ide> } else { <del> ReactInstrumentation.debugTool.onInstantiateComponent(contentDebugID, content); <del> ReactInstrumentation.debugTool.onSetParent(contentDebugID, debugID); <del> ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content); <add> ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID); <ide> ReactInstrumentation.debugTool.onMountComponent(contentDebugID); <ide> ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]); <ide> } <ide> ReactDOMComponent.Mixin = { <ide> break; <ide> } <ide> <del> if (__DEV__) { <del> if (this._debugID) { <del> var callback = () => ReactInstrumentation.debugTool.onComponentHasMounted(this._debugID); <del> transaction.getReactMountReady().enqueue(callback, this); <del> } <del> } <del> <ide> return mountImage; <ide> }, <ide> <ide> ReactDOMComponent.Mixin = { <ide> transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); <ide> break; <ide> } <del> <del> if (__DEV__) { <del> if (this._debugID) { <del> var callback = () => ReactInstrumentation.debugTool.onComponentHasUpdated(this._debugID); <del> transaction.getReactMountReady().enqueue(callback, this); <del> } <del> } <ide> }, <ide> <ide> /** <ide><path>src/renderers/native/ReactNativeMount.js <ide> function mountComponentIntoNode( <ide> transaction, <ide> null, <ide> ReactNativeContainerInfo(containerTag), <del> emptyObject <add> emptyObject, <add> 0 /* parentDebugID */ <ide> ); <ide> componentInstance._renderedComponent._topLevelWrapper = componentInstance; <ide> ReactNativeMount._mountImageIntoNode(markup, containerTag); <ide> var ReactNativeMount = { <ide> instance, <ide> containerTag <ide> ); <del> if (__DEV__) { <del> // The instance here is TopLevelWrapper so we report mount for its child. <del> ReactInstrumentation.debugTool.onMountRootComponent( <del> instance._renderedComponent._debugID <del> ); <del> } <ide> var component = instance.getPublicInstance(); <ide> if (callback) { <ide> callback.call(component); <ide><path>src/renderers/shared/ReactDebugTool.js <ide> function resetMeasurements() { <ide> currentFlushMeasurements = []; <ide> } <ide> <del>function checkDebugID(debugID) { <add>function checkDebugID(debugID, allowRoot = false) { <add> if (allowRoot && debugID === 0) { <add> return; <add> } <ide> if (!debugID) { <ide> warning(false, 'ReactDebugTool: debugID may not be empty.'); <ide> } <ide> var ReactDebugTool = { <ide> endLifeCycleTimer(debugID, timerType); <ide> emitEvent('onEndLifeCycleTimer', debugID, timerType); <ide> }, <del> onBeginReconcilerTimer(debugID, timerType) { <del> checkDebugID(debugID); <del> emitEvent('onBeginReconcilerTimer', debugID, timerType); <del> }, <del> onEndReconcilerTimer(debugID, timerType) { <del> checkDebugID(debugID); <del> emitEvent('onEndReconcilerTimer', debugID, timerType); <del> }, <ide> onError(debugID) { <ide> if (currentTimerDebugID != null) { <ide> endLifeCycleTimer(currentTimerDebugID, currentTimerType); <ide> var ReactDebugTool = { <ide> checkDebugID(debugID); <ide> emitEvent('onHostOperation', debugID, type, payload); <ide> }, <del> onComponentHasMounted(debugID) { <del> checkDebugID(debugID); <del> emitEvent('onComponentHasMounted', debugID); <del> }, <del> onComponentHasUpdated(debugID) { <del> checkDebugID(debugID); <del> emitEvent('onComponentHasUpdated', debugID); <del> }, <ide> onSetState() { <ide> emitEvent('onSetState'); <ide> }, <ide> var ReactDebugTool = { <ide> childDebugIDs.forEach(checkDebugID); <ide> emitEvent('onSetChildren', debugID, childDebugIDs); <ide> }, <del> onSetParent(debugID, parentDebugID) { <del> checkDebugID(debugID); <del> emitEvent('onSetParent', debugID, parentDebugID); <del> }, <del> onInstantiateComponent(debugID, element) { <del> checkDebugID(debugID); <del> emitEvent('onInstantiateComponent', debugID, element); <del> }, <del> onMountRootComponent(debugID) { <add> onBeforeMountComponent(debugID, element, parentDebugID) { <ide> checkDebugID(debugID); <del> emitEvent('onMountRootComponent', debugID); <del> }, <del> onBeforeMountComponent(debugID, element) { <del> checkDebugID(debugID); <del> emitEvent('onBeforeMountComponent', debugID, element); <add> checkDebugID(parentDebugID, true); <add> emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); <ide> }, <ide> onMountComponent(debugID) { <ide> checkDebugID(debugID); <ide> var ReactDebugTool = { <ide> checkDebugID(debugID); <ide> emitEvent('onUpdateComponent', debugID); <ide> }, <add> onBeforeUnmountComponent(debugID) { <add> checkDebugID(debugID); <add> emitEvent('onBeforeUnmountComponent', debugID); <add> }, <ide> onUnmountComponent(debugID) { <ide> checkDebugID(debugID); <ide> emitEvent('onUnmountComponent', debugID); <ide><path>src/renderers/shared/hooks/ReactChildrenMutationWarningHook.js <ide> var ReactChildrenMutationWarningHook = { <ide> onMountComponent(debugID) { <ide> handleElement(debugID, ReactComponentTreeHook.getElement(debugID)); <ide> }, <del> onComponentHasUpdated(debugID) { <add> onUpdateComponent(debugID) { <ide> handleElement(debugID, ReactComponentTreeHook.getElement(debugID)); <ide> }, <ide> }; <ide><path>src/renderers/shared/stack/reconciler/ReactChildReconciler.js <ide> var ReactChildReconciler = { <ide> nestedChildNodes, <ide> transaction, <ide> context, <del> selfDebugID // __DEV__ only <add> selfDebugID // 0 in production and for roots <ide> ) { <ide> if (nestedChildNodes == null) { <ide> return null; <ide> var ReactChildReconciler = { <ide> transaction, <ide> hostParent, <ide> hostContainerInfo, <del> context) { <add> context, <add> selfDebugID // 0 in production and for roots <add> ) { <ide> // We currently don't have a way to track moves here but if we use iterators <ide> // instead of for..in we can zip the iterators and check if an item has <ide> // moved. <ide> var ReactChildReconciler = { <ide> transaction, <ide> hostParent, <ide> hostContainerInfo, <del> context <add> context, <add> selfDebugID <ide> ); <ide> mountImages.push(nextChildMountImage); <ide> } <ide><path>src/renderers/shared/stack/reconciler/ReactCompositeComponent.js <ide> var ReactCompositeComponentMixin = { <ide> } <ide> } <ide> <del> if (__DEV__) { <del> if (this._debugID) { <del> var callback = (component) => ReactInstrumentation.debugTool.onComponentHasMounted(this._debugID); <del> transaction.getReactMountReady().enqueue(callback, this); <del> } <del> } <del> <ide> return markup; <ide> }, <ide> <ide> var ReactCompositeComponentMixin = { <ide> nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ <ide> ); <ide> this._renderedComponent = child; <add> <add> var selfDebugID = 0; <ide> if (__DEV__) { <del> if (child._debugID !== 0 && this._debugID !== 0) { <del> ReactInstrumentation.debugTool.onSetParent( <del> child._debugID, <del> this._debugID <del> ); <del> } <add> selfDebugID = this._debugID; <ide> } <del> <ide> var markup = ReactReconciler.mountComponent( <ide> child, <ide> transaction, <ide> hostParent, <ide> hostContainerInfo, <del> this._processChildContext(context) <add> this._processChildContext(context), <add> selfDebugID <ide> ); <ide> <ide> if (__DEV__) { <ide> var ReactCompositeComponentMixin = { <ide> ); <ide> } <ide> } <del> <del> if (__DEV__) { <del> if (this._debugID) { <del> var callback = () => ReactInstrumentation.debugTool.onComponentHasUpdated(this._debugID); <del> transaction.getReactMountReady().enqueue(callback, this); <del> } <del> } <ide> }, <ide> <ide> /** <ide> var ReactCompositeComponentMixin = { <ide> nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ <ide> ); <ide> this._renderedComponent = child; <add> <add> var selfDebugID = 0; <ide> if (__DEV__) { <del> if (child._debugID !== 0 && this._debugID !== 0) { <del> ReactInstrumentation.debugTool.onSetParent( <del> child._debugID, <del> this._debugID <del> ); <del> } <add> selfDebugID = this._debugID; <ide> } <del> <ide> var nextMarkup = ReactReconciler.mountComponent( <ide> child, <ide> transaction, <ide> this._hostParent, <ide> this._hostContainerInfo, <del> this._processChildContext(context) <add> this._processChildContext(context), <add> selfDebugID <ide> ); <ide> <ide> if (__DEV__) { <ide><path>src/renderers/shared/stack/reconciler/ReactMultiChild.js <ide> function processQueue(inst, updateQueue) { <ide> ); <ide> } <ide> <del>var setParentForInstrumentation = emptyFunction; <ide> var setChildrenForInstrumentation = emptyFunction; <ide> if (__DEV__) { <ide> var getDebugID = function(inst) { <ide> if (__DEV__) { <ide> } <ide> return inst._debugID; <ide> }; <del> setParentForInstrumentation = function(child) { <del> if (child._debugID !== 0) { <del> ReactInstrumentation.debugTool.onSetParent( <del> child._debugID, <del> getDebugID(this) <del> ); <del> } <del> }; <ide> setChildrenForInstrumentation = function(children) { <ide> var debugID = getDebugID(this); <ide> // TODO: React Native empty components are also multichild. <ide> var ReactMultiChild = { <ide> <ide> _reconcilerInstantiateChildren: function(nestedChildren, transaction, context) { <ide> if (__DEV__) { <add> var selfDebugID = getDebugID(this); <ide> if (this._currentElement) { <ide> try { <ide> ReactCurrentOwner.current = this._currentElement._owner; <ide> return ReactChildReconciler.instantiateChildren( <del> nestedChildren, transaction, context, this._debugID <add> nestedChildren, transaction, context, selfDebugID <ide> ); <ide> } finally { <ide> ReactCurrentOwner.current = null; <ide> var ReactMultiChild = { <ide> context <ide> ) { <ide> var nextChildren; <add> var selfDebugID = 0; <ide> if (__DEV__) { <add> selfDebugID = getDebugID(this); <ide> if (this._currentElement) { <ide> try { <ide> ReactCurrentOwner.current = this._currentElement._owner; <del> nextChildren = flattenChildren(nextNestedChildrenElements, this._debugID); <add> nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); <ide> } finally { <ide> ReactCurrentOwner.current = null; <ide> } <ide> var ReactMultiChild = { <ide> transaction, <ide> this, <ide> this._hostContainerInfo, <del> context <add> context, <add> selfDebugID <ide> ); <ide> return nextChildren; <ide> } <ide> } <del> nextChildren = flattenChildren(nextNestedChildrenElements); <add> nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); <ide> ReactChildReconciler.updateChildren( <ide> prevChildren, <ide> nextChildren, <ide> var ReactMultiChild = { <ide> transaction, <ide> this, <ide> this._hostContainerInfo, <del> context <add> context, <add> selfDebugID <ide> ); <ide> return nextChildren; <ide> }, <ide> var ReactMultiChild = { <ide> for (var name in children) { <ide> if (children.hasOwnProperty(name)) { <ide> var child = children[name]; <add> var selfDebugID = 0; <ide> if (__DEV__) { <del> setParentForInstrumentation.call(this, child); <add> selfDebugID = getDebugID(this); <ide> } <ide> var mountImage = ReactReconciler.mountComponent( <ide> child, <ide> transaction, <ide> this, <ide> this._hostContainerInfo, <del> context <add> context, <add> selfDebugID <ide> ); <ide> child._mountIndex = index++; <ide> mountImages.push(mountImage); <ide><path>src/renderers/shared/stack/reconciler/ReactReconciler.js <ide> var ReactReconciler = { <ide> transaction, <ide> hostParent, <ide> hostContainerInfo, <del> context <add> context, <add> parentDebugID // 0 in production and for roots <ide> ) { <ide> if (__DEV__) { <ide> if (internalInstance._debugID !== 0) { <ide> ReactInstrumentation.debugTool.onBeforeMountComponent( <ide> internalInstance._debugID, <del> internalInstance._currentElement <del> ); <del> ReactInstrumentation.debugTool.onBeginReconcilerTimer( <del> internalInstance._debugID, <del> 'mountComponent' <add> internalInstance._currentElement, <add> parentDebugID <ide> ); <ide> } <ide> } <ide> var markup = internalInstance.mountComponent( <ide> transaction, <ide> hostParent, <ide> hostContainerInfo, <del> context <add> context, <add> parentDebugID <ide> ); <ide> if (internalInstance._currentElement && <ide> internalInstance._currentElement.ref != null) { <ide> transaction.getReactMountReady().enqueue(attachRefs, internalInstance); <ide> } <ide> if (__DEV__) { <ide> if (internalInstance._debugID !== 0) { <del> ReactInstrumentation.debugTool.onEndReconcilerTimer( <del> internalInstance._debugID, <del> 'mountComponent' <del> ); <ide> ReactInstrumentation.debugTool.onMountComponent( <ide> internalInstance._debugID <ide> ); <ide> var ReactReconciler = { <ide> unmountComponent: function(internalInstance, safely) { <ide> if (__DEV__) { <ide> if (internalInstance._debugID !== 0) { <del> ReactInstrumentation.debugTool.onBeginReconcilerTimer( <del> internalInstance._debugID, <del> 'unmountComponent' <add> ReactInstrumentation.debugTool.onBeforeUnmountComponent( <add> internalInstance._debugID <ide> ); <ide> } <ide> } <ide> ReactRef.detachRefs(internalInstance, internalInstance._currentElement); <ide> internalInstance.unmountComponent(safely); <ide> if (__DEV__) { <ide> if (internalInstance._debugID !== 0) { <del> ReactInstrumentation.debugTool.onEndReconcilerTimer( <del> internalInstance._debugID, <del> 'unmountComponent' <del> ); <ide> ReactInstrumentation.debugTool.onUnmountComponent( <ide> internalInstance._debugID <ide> ); <ide> var ReactReconciler = { <ide> internalInstance._debugID, <ide> nextElement <ide> ); <del> ReactInstrumentation.debugTool.onBeginReconcilerTimer( <del> internalInstance._debugID, <del> 'receiveComponent' <del> ); <ide> } <ide> } <ide> <ide> var ReactReconciler = { <ide> <ide> if (__DEV__) { <ide> if (internalInstance._debugID !== 0) { <del> ReactInstrumentation.debugTool.onEndReconcilerTimer( <del> internalInstance._debugID, <del> 'receiveComponent' <del> ); <ide> ReactInstrumentation.debugTool.onUpdateComponent( <ide> internalInstance._debugID <ide> ); <ide> var ReactReconciler = { <ide> } <ide> if (__DEV__) { <ide> if (internalInstance._debugID !== 0) { <del> ReactInstrumentation.debugTool.onBeginReconcilerTimer( <del> internalInstance._debugID, <del> 'performUpdateIfNecessary' <del> ); <ide> ReactInstrumentation.debugTool.onBeforeUpdateComponent( <ide> internalInstance._debugID, <ide> internalInstance._currentElement <ide> var ReactReconciler = { <ide> internalInstance.performUpdateIfNecessary(transaction); <ide> if (__DEV__) { <ide> if (internalInstance._debugID !== 0) { <del> ReactInstrumentation.debugTool.onEndReconcilerTimer( <del> internalInstance._debugID, <del> 'performUpdateIfNecessary' <del> ); <ide> ReactInstrumentation.debugTool.onUpdateComponent( <ide> internalInstance._debugID <ide> ); <ide><path>src/renderers/shared/stack/reconciler/ReactSimpleEmptyComponent.js <ide> Object.assign(ReactSimpleEmptyComponent.prototype, { <ide> transaction, <ide> hostParent, <ide> hostContainerInfo, <del> context <add> context, <add> parentDebugID // 0 in production and for roots <ide> ) { <ide> return ReactReconciler.mountComponent( <ide> this._renderedComponent, <ide> transaction, <ide> hostParent, <ide> hostContainerInfo, <del> context <add> context, <add> parentDebugID <ide> ); <ide> }, <ide> receiveComponent: function() { <ide><path>src/renderers/shared/stack/reconciler/instantiateReactComponent.js <ide> var ReactCompositeComponent = require('ReactCompositeComponent'); <ide> var ReactEmptyComponent = require('ReactEmptyComponent'); <ide> var ReactHostComponent = require('ReactHostComponent'); <del>var ReactInstrumentation = require('ReactInstrumentation'); <ide> <ide> var invariant = require('invariant'); <ide> var warning = require('warning'); <ide> function instantiateReactComponent(node, shouldHaveDebugID) { <ide> instance._mountImage = null; <ide> <ide> if (__DEV__) { <del> if (shouldHaveDebugID) { <del> var debugID = nextDebugID++; <del> instance._debugID = debugID; <del> ReactInstrumentation.debugTool.onInstantiateComponent(debugID, node); <del> } else { <del> instance._debugID = 0; <del> } <add> instance._debugID = shouldHaveDebugID ? nextDebugID++ : 0; <ide> } <ide> <ide> // Internal instances should fully constructed at this point, so they should <ide><path>src/renderers/testing/ReactTestMount.js <ide> 'use strict'; <ide> <ide> var ReactElement = require('ReactElement'); <del>var ReactInstrumentation = require('ReactInstrumentation'); <ide> var ReactReconciler = require('ReactReconciler'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> <ide> var ReactTestMount = { <ide> batchedMountComponentIntoNode, <ide> instance <ide> ); <del> if (__DEV__) { <del> // The instance here is TopLevelWrapper so we report mount for its child. <del> ReactInstrumentation.debugTool.onMountRootComponent( <del> instance._renderedComponent._debugID <del> ); <del> } <ide> return new ReactTestInstance(instance); <ide> }, <ide> <ide><path>src/test/ReactTestUtils.js <ide> var ReactElement = require('ReactElement'); <ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); <ide> var ReactCompositeComponent = require('ReactCompositeComponent'); <ide> var ReactInstanceMap = require('ReactInstanceMap'); <del>var ReactInstrumentation = require('ReactInstrumentation'); <ide> var ReactReconciler = require('ReactReconciler'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> var SyntheticEvent = require('SyntheticEvent'); <ide> var nextDebugID = 1; <ide> var NoopInternalComponent = function(element) { <ide> this._renderedOutput = element; <ide> this._currentElement = element; <del> this._debugID = nextDebugID++; <del> ReactInstrumentation.debugTool.onInstantiateComponent(this._debugID, element); <add> <add> if (__DEV__) { <add> this._debugID = nextDebugID++; <add> } <ide> }; <ide> <ide> NoopInternalComponent.prototype = { <ide> var ShallowComponentWrapper = function(element) { <ide> // TODO: Consolidate with instantiateReactComponent <ide> if (__DEV__) { <ide> this._debugID = nextDebugID++; <del> ReactInstrumentation.debugTool.onInstantiateComponent(this._debugID, element); <ide> } <ide> <ide> this.construct(element); <ide> ReactShallowRenderer.prototype._render = function(element, transaction, context) <ide> ); <ide> } else { <ide> var instance = new ShallowComponentWrapper(element); <del> ReactReconciler.mountComponent(instance, transaction, null, null, context); <add> ReactReconciler.mountComponent(instance, transaction, null, null, context, 0); <ide> this._instance = instance; <ide> } <ide> };
15
Javascript
Javascript
verify threadid in reports
cb210110e9c7e4b8d7c64af4a45d4b1e7d429a0e
<ide><path>test/report/test-report-worker.js <ide> async function basic() { <ide> helper.validateContent(report); <ide> assert.strictEqual(report.workers.length, 1); <ide> helper.validateContent(report.workers[0]); <add> assert.strictEqual(report.workers[0].header.threadId, w.threadId); <ide> <ide> w.postMessage({}); <ide>
1
Text
Text
remove redundancy regarding 'latest react news'
5ba1831d76dda8ddf1ed215cf638d229f8ff21fe
<ide><path>docs/support.md <ide> Many developers and users idle on Freenode.net's IRC network in **[#reactjs on f <ide> <ide> ## Twitter <ide> <del>For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs). In addition, you can use the [**#reactjs** hashtag](https://twitter.com/search?q=%23reactjs) to keep up with the latest React news. <add>For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs) or use the [**#reactjs** hashtag](https://twitter.com/search?q=%23reactjs). <ide> <ide> <div><a class="twitter-timeline" data-dnt="true" data-chrome="nofooter noheader transparent" href="https://twitter.com/search?q=%23reactjs" data-widget-id="342522405270470656"></a></div>
1
Mixed
Ruby
raise an error on root route naming conflicts
dde9c488398293fb1cbdc02595b8c4e9860b03cc
<ide><path>actionpack/CHANGELOG.md <add>* Raise an error on root route naming conflicts. <add> <add> Raises an ArgumentError when multiple root routes are defined in the <add> same context instead of assigning nil names to subsequent roots. <add> <add> *Gannon McGibbon* <add> <ide> * Allow rescue from parameter parse errors: <ide> <ide> ``` <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def with_default_scope(scope, &block) <ide> <ide> # Query if the following named route was already defined. <ide> def has_named_route?(name) <del> @set.named_routes.key? name <add> @set.named_routes.key?(name) <ide> end <ide> <ide> private <ide> def add_route(action, controller, options, _path, to, via, formatted, anchor, op <ide> end <ide> <ide> def match_root_route(options) <del> name = has_named_route?(name_for_action(:root, nil)) ? nil : :root <del> args = ["/", { as: name, via: :get }.merge!(options)] <del> <add> args = ["/", { as: :root, via: :get }.merge(options)] <ide> match(*args) <ide> end <ide> end <ide><path>actionpack/test/dispatch/routing_test.rb <ide> def test_dynamic_action_segments_are_deprecated <ide> end <ide> end <ide> <del> def test_multiple_roots <add> def test_multiple_roots_raises_error <add> ex = assert_raises(ArgumentError) { <add> draw do <add> root "pages#index", constraints: { host: "www.example.com" } <add> root "admin/pages#index", constraints: { host: "admin.example.com" } <add> end <add> } <add> assert_match(/Invalid route name, already in use: 'root'/, ex.message) <add> end <add> <add> def test_multiple_named_roots <ide> draw do <ide> namespace :foo do <ide> root "pages#index", constraints: { host: "www.example.com" } <del> root "admin/pages#index", constraints: { host: "admin.example.com" } <add> root "admin/pages#index", constraints: { host: "admin.example.com" }, as: :admin_root <ide> end <ide> <ide> root "pages#index", constraints: { host: "www.example.com" } <del> root "admin/pages#index", constraints: { host: "admin.example.com" } <add> root "admin/pages#index", constraints: { host: "admin.example.com" }, as: :admin_root <ide> end <ide> <ide> get "http://www.example.com/foo"
3
Ruby
Ruby
add tests for nested lambda constraints
a21707116aab2a0b1038c719635eaf3d737ad644
<ide><path>actionpack/test/controller/routing_test.rb <ide> def test_lambda_constraints <ide> assert_equal 'clients', get(URI('http://clients.example.org/')) <ide> end <ide> <add> def test_scoped_lambda <add> scope_called = false <add> rs.draw do <add> scope '/foo', :constraints => lambda { |req| scope_called = true } do <add> get '/', :to => lambda { |env| [200, {}, %w{default}] } <add> end <add> end <add> <add> assert_equal 'default', get(URI('http://www.example.org/foo/')) <add> assert scope_called, "scope constraint should be called" <add> end <add> <add> def test_scoped_lambda_with_get_lambda <add> scope_called = false <add> inner_called = false <add> <add> rs.draw do <add> scope '/foo', :constraints => lambda { |req| flunk "should not be called" } do <add> get '/', :constraints => lambda { |req| inner_called = true }, <add> :to => lambda { |env| [200, {}, %w{default}] } <add> end <add> end <add> <add> assert_equal 'default', get(URI('http://www.example.org/foo/')) <add> assert inner_called, "inner constraint should be called" <add> end <add> <ide> def test_empty_string_match <ide> rs.draw do <ide> get '/:username', :constraints => { :username => /[^\/]+/ },
1
Go
Go
fix docker login
d22a39db265dbf68cec4ddbc5903372e936094a9
<ide><path>commands.go <ide> func (cli *DockerCli) CmdLogin(args ...string) error { <ide> authconfig.ServerAddress = serverAddress <ide> cli.configFile.Configs[serverAddress] = authconfig <ide> <del> body, statusCode, err := readBody(cli.call("POST", "/auth", cli.configFile.Configs[serverAddress], false)) <add> stream, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress], false) <ide> if statusCode == 401 { <ide> delete(cli.configFile.Configs, serverAddress) <ide> auth.SaveConfig(cli.configFile) <ide> func (cli *DockerCli) CmdLogin(args ...string) error { <ide> if err != nil { <ide> return err <ide> } <del> <ide> var out2 engine.Env <del> err = json.Unmarshal(body, &out2) <add> err = out2.Decode(stream) <ide> if err != nil { <ide> cli.configFile, _ = auth.LoadConfig(os.Getenv("HOME")) <ide> return err
1
Python
Python
remove overzealous automatic rst link
c092cd1122c09e25eb8fc463d0d5b557a64878ac
<ide><path>doc/neps/nep-0016-benchmark.py <del>.. _NEP16: <del> <ide> import perf <ide> import abc <ide> import numpy as np
1
Text
Text
expand explanation of middleware definition
32344fad69aa6125c0a79c5320e3e0886e098686
<ide><path>docs/faq/DesignDecisions.md <ide> Serialization enables the browser to store all actions that have been dispatched <ide> <ide> <a id="why-currying"></a> <ide> ### Why does the middleware signature use currying? <del>The [curried function signature](https://github.com/reactjs/redux/issues/1744) of declaring middleware is [deemed unnecessary](https://github.com/reactjs/redux/pull/784) by some, because both store and next are available when the applyMiddleware function is executed. This issue has been determined to not be [worth introducing breaking changes](https://github.com/reactjs/redux/issues/1744). <add> <add>Redux middleware are written using a triply-nested function structure that looks like `const middleware = storeAPI => next => action => {}`, rather than a single function that looks like `const middleware = (storeAPI, next, action) => {}`. There's a few reasons for this. <add> <add>One is that "currying" functions is a standard functional programming technique, and Redux was explicitly intended to use functional programming principles in its design. Another is that currying functions creates closures where you can declare variables that exist for the lifetime of the middleware (which could be considered a functional equivalent to instance variables that exist for the lifetime of a class instance). Finally, it's simply the approach that was chosen when Redux was initially designed. <add> <add>The [curried function signature](https://github.com/reactjs/redux/issues/1744) of declaring middleware is [deemed unnecessary](https://github.com/reactjs/redux/pull/784) by some, because both store and next are available when the applyMiddleware function is executed. This issue has been determined to not be [worth introducing breaking changes](https://github.com/reactjs/redux/issues/1744), as there are now hundreds of middleware in the Redux ecosystem that rely on the existing middleware definition. <ide> <ide> #### Further Information <ide> **Discussions** <ide> * Why does the middleware signature use currying? <del> * See - [#55](https://github.com/reactjs/redux/pull/55), [#534](https://github.com/reactjs/redux/issues/534), [#784](https://github.com/reactjs/redux/pull/784), [#922](https://github.com/reactjs/redux/issues/922), [#1744](https://github.com/reactjs/redux/issues/1744) <add> * Prior discussions: [#55](https://github.com/reactjs/redux/pull/55), [#534](https://github.com/reactjs/redux/issues/534), [#784](https://github.com/reactjs/redux/pull/784), [#922](https://github.com/reactjs/redux/issues/922), [#1744](https://github.com/reactjs/redux/issues/1744) <add> * [React Boston 2017: You Might Need Redux (And Its Ecosystem)](http://blog.isquaredsoftware.com/2017/09/presentation-might-need-redux-ecosystem/) <ide> <ide> <a id="closure-dispatch"></a> <ide> ### Why does `applyMiddleware` use a closure for `dispatch`?
1
Python
Python
remove viltforquestionanswering from check_repo
b83796ded7725d0cb64ea7258ef95e395151a211
<ide><path>utils/check_repo.py <ide> "DPTForDepthEstimation", <ide> "DecisionTransformerGPT2Model", <ide> "GLPNForDepthEstimation", <del> "ViltForQuestionAnswering", <ide> "ViltForImagesAndTextClassification", <ide> "ViltForImageAndTextRetrieval", <ide> "ViltForTokenClassification",
1
Ruby
Ruby
fix gratuitous use of ternary operator
3d3fd39caa8f938a44fffc1c39bde8f0170e8f18
<ide><path>actionpack/lib/action_view/renderer/template_renderer.rb <ide> def determine_template(options) #:nodoc: <ide> handler = Template.handler_for_extension(options[:type] || "erb") <ide> Template.new(options[:inline], "inline template", handler, :locals => keys) <ide> elsif options.key?(:template) <del> options[:template].respond_to?(:render) ? <del> options[:template] : find_template(options[:template], options[:prefixes], false, keys, @details) <add> if options[:template].respond_to?(:render) <add> options[:template] <add> else <add> find_template(options[:template], options[:prefixes], false, keys, @details) <add> end <ide> else <ide> raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file or :text option." <ide> end
1
Javascript
Javascript
improve sparse vector iteration perf
dc7961961f27b7817fd0c3ee019f3cdaf8b41c96
<ide><path>dist/Immutable.js <ide> var VectorIterator = function VectorIterator(vector, sparse) { <ide> if (rawIndex < SIZE && index > -step && index < stack.max) { <ide> var value = array && array[rawIndex]; <ide> if (stack.level === 0) { <del> if (!sparse || value || (array && array.hasOwnProperty(rawIndex))) { <add> if (!sparse || value || (array && rawIndex < array.length && array.hasOwnProperty(rawIndex))) { <ide> return iteratorValue(sparse ? [index, value] : value); <ide> } <ide> } else if (!sparse || value) { <ide><path>dist/Immutable.min.js <ide> this._object=t,this._keys=e,this.length=e.length};ge.createClass(Ie,{toObject:fu <ide> if(!c&&i===Ae)return this;var f=K(h&o-1),l=this.nodes,_=c?l[f]:null,g=U(_,t,e+Se,n,r,i,u,s);if(g===_)return this;if(!c&&g&&l.length>=Ye)return z(t,l,h,a,g);if(c&&!g&&2===l.length&&W(l[1^f]))return l[1^f];if(c&&g&&1===l.length&&W(g))return g;var v=t&&t===this.ownerID,p=c?g?h:h^o:h|o,m=c?g?N(l,f,g,v):G(l,f,v):F(l,f,g,v);return v?(this.bitmap=p,this.nodes=m,this):new Re(t,p,m)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++)if(n[e?i-r:r].iterate(t,e)===!1)return!1}},{});var ze=function(t,e,n){this.ownerID=t,this.count=e,this.nodes=n},Je=ze;ge.createClass(ze,{get:function(t,e,n,r){var i=e>>>t&Oe,u=this.nodes[i];return u?u.get(t+Se,e,n,r):r},update:function(t,e,n,r,i,u,s){var a=n>>>e&Oe,o=i===Ae,h=this.nodes,c=h[a];if(o&&!c)return this;var f=U(c,t,e+Se,n,r,i,u,s);if(f===c)return this;var l=this.count;if(c){if(!f&&(l--,Ze>l))return R(t,h,l,a)}else l++;var _=t&&t===this.ownerID,g=N(h,a,f,_);return _?(this.count=l,this.nodes=g,this):new Je(t,l,g)},iterate:function(t,e){for(var n=this.nodes,r=0,i=n.length-1;i>=r;r++){var u=n[e?i-r:r];if(u&&u.iterate(t,e)===!1)return!1}}},{});var Be=function(t,e,n){this.ownerID=t,this.hash=e,this.entries=n},Le=Be;ge.createClass(Be,{get:function(t,e,n,r){for(var i=this.entries,u=0,s=i.length;s>u;u++)if(C(n,i[u][0]))return i[u][1];return r},update:function(t,e,n,r,i,u,s){var a=i===Ae;if(n!==this.hash)return a?this:(I(s),I(u),P(this,t,e,n,[r,i]));for(var o=this.entries,h=0,c=o.length;c>h&&!C(r,o[h][0]);h++);var f=c>h;if(a&&!f)return this;if(I(s),(a||!f)&&I(u),a&&2===c)return new Ve(t,this.hash,o[1^h]);var l=t&&t===this.ownerID,_=l?o:D(o);return f?a?h===c-1?_.pop():_[h]=_.pop():_[h]=[r,i]:_.push([r,i]),l?(this.entries=_,this):new Le(t,this.hash,_)},iterate:function(t,e){for(var n=this.entries,r=0,i=n.length-1;i>=r;r++)if(t(n[e?i-r:r])===!1)return!1}},{});var Ve=function(t,e,n){this.ownerID=t,this.hash=e,this.entry=n},Ke=Ve;ge.createClass(Ve,{get:function(t,e,n,r){return C(n,this.entry[0])?this.entry[1]:r},update:function(t,e,n,r,i,u,s){var a=i===Ae,o=C(r,this.entry[0]);return(o?i===this.entry[1]:a)?this:(I(s),a?(I(u),null):o?t&&t===this.ownerID?(this.entry[1]=i,this):new Ke(t,n,[r,i]):(I(u),P(this,t,e,n,[r,i]))) <ide> },iterate:function(t){return t(this.entry)}},{});var Ne=function(t){this._stack=t._root&&x(t._root)};ge.createClass(Ne,{next:function(){for(var t=this._stack;t;){var e=t.node,n=t.index++;if(e.entry){if(0===n)return b(e.entry)}else if(e.entries){if(e.entries.length>n)return b(e.entries[n])}else if(e.nodes.length>n){var r=e.nodes[n];if(r){if(r.entry)return b(r.entry);t=this._stack=x(r,t)}continue}t=this._stack=this._stack.__prev}return S()}},{},De);var Fe,Ge=2147483647,He=16,Qe=255,Te=0,Xe={},Ye=Me/2,Ze=Me/4,$e=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return tn.from(t)},tn=$e;ge.createClass($e,{toString:function(){return this.__toString("Vector [","]")},get:function(t,e){if(t=ue(t,this._origin),t>=this._size)return e;var n=ne(this,t),r=t&Oe;return n&&(void 0===e||n.array.hasOwnProperty(r))?n.array[r]:e},first:function(){return this.get(0)},last:function(){return this.get(this.length?this.length-1:0)},set:function(t,e){return $(this,t,e)},"delete":function(t){return $(this,t,Ae)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=this._origin=this._size=0,this._level=Se,this._root=this._tail=null,this.__altered=!0,this):tn.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(n){re(n,0,e+t.length);for(var r=0;t.length>r;r++)n.set(e+r,t[r])})},pop:function(){return re(this,0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){re(e,-t.length);for(var n=0;t.length>n;n++)e.set(n,t[n])})},shift:function(){return re(this,1)},merge:function(){return ie(this,null,arguments)},mergeWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return ie(this,t,e)},mergeDeep:function(){return ie(this,B(null),arguments)},mergeDeepWith:function(t){for(var e=[],n=1;arguments.length>n;n++)e[n-1]=arguments[n];return ie(this,B(t),e)},setLength:function(t){return re(this,0,t)},slice:function(t,e,n){var r=ge.superCall(this,tn.prototype,"slice",[t,e,n]);if(!n&&r!==this){var i=this,u=i.length;r.toVector=function(){return re(i,0>t?Math.max(0,u+t):u?Math.min(u,t):t,null==e?u:0>e?Math.max(0,u+e):u?Math.min(u,e):e) <ide> }}return r},iterator:function(t){return new un(this,t)},__iterate:function(t,e,n){var r=this,i=0,u=r.length-1;n^=e;var s,a=function(e,s){return t(e,n?u-s:s,r)===!1?!1:(i=s,!0)},o=se(this._size);return s=e?X(this._tail,0,o-this._origin,this._size-this._origin,a,e)&&X(this._root,this._level,-this._origin,o-this._origin,a,e):X(this._root,this._level,-this._origin,o-this._origin,a,e)&&X(this._tail,0,o-this._origin,this._size-this._origin,a,e),(s?u:e?u-i:i)+1},__deepEquals:function(t){var e=this.iterator(!0);return t.every(function(t,n){var r=e.next().value;return r&&r[0]===n&&C(r[1],t)})},__ensureOwner:function(t){return t===this.__ownerID?this:t?Z(this._origin,this._size,this._level,this._root,this._tail,t):(this.__ownerID=t,this)}},{empty:function(){return sn||(sn=Z(0,0,Se))},from:function(t){if(!t||0===t.length)return tn.empty();if(t.constructor===tn)return t;var e=Array.isArray(t);return t.length>0&&Me>t.length?Z(0,t.length,Se,null,new nn(e?D(t):ve(t).toArray())):(e||(t=ve(t),t instanceof de||(t=t.values())),tn.empty().merge(t))}},de);var en=$e.prototype;en["@@iterator"]=en.iterator,en.update=We.update,en.updateIn=We.updateIn,en.cursor=We.cursor,en.withMutations=We.withMutations,en.asMutable=We.asMutable,en.asImmutable=We.asImmutable,en.wasAltered=We.wasAltered;var nn=function(t,e){this.array=t,this.ownerID=e},rn=nn;ge.createClass(nn,{removeBefore:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n>>>e&Oe;if(r>=this.array.length)return new rn([],t);var i,u=0===r;if(e>0){var s=this.array[r];if(i=s&&s.removeBefore(t,e-Se,n),i===s&&u)return this}if(u&&!i)return this;var a=ee(this,t);if(!u)for(var o=0;r>o;o++)delete a.array[o];return i&&(a.array[r]=i),a},removeAfter:function(t,e,n){if(n===e?1<<e:0||0===this.array.length)return this;var r=n-1>>>e&Oe;if(r>=this.array.length)return this;var i,u=r===this.array.length-1;if(e>0){var s=this.array[r];if(i=s&&s.removeAfter(t,e-Se,n),i===s&&u)return this}if(u&&!i)return this;var a=ee(this,t);return u||(a.array.length=r+1),i&&(a.array[r]=i),a}},{});var un=function(t,e){var n=se(t._size); <del>this._sparse=e,this._stack=Y(t._root&&t._root.array,t._level,-t._origin,n-t._origin,Y(t._tail&&t._tail.array,0,n-t._origin,t._size-t._origin))};ge.createClass(un,{next:function(){for(var t=this._sparse,e=this._stack;e;){var n=e.array,r=e.index++,i=1<<e.level,u=e.offset+r*i;if(Me>r&&u>-i&&e.max>u){var s=n&&n[r];if(0===e.level){if(!t||s||n&&n.hasOwnProperty(r))return b(t?[u,s]:s)}else(!t||s)&&(this._stack=e=Y(s&&s.array,e.level-Se,u,e.max,e))}else e=this._stack=this._stack.__prev}return S()}},{},De);var sn,an=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return on.from(t)},on=an;ge.createClass(an,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map.has(t)},get:function(t,e){return this.has(t)?t:e},add:function(t){var e=this._map.set(t,null);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:ae(e)},"delete":function(t){var e=this._map.delete(t);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:0===e.length?on.empty():ae(e)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this):on.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var n=0;t.length>n;n++)ve(t[n]).forEach(function(t){return e.add(t)})})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ve(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.every(function(t){return t.contains(n)})||e.delete(n)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ve(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.some(function(t){return t.contains(n)})&&e.delete(n)})})},isSubset:function(t){return t=ve(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=ve(t),t.every(function(t){return e.contains(t) <add>this._sparse=e,this._stack=Y(t._root&&t._root.array,t._level,-t._origin,n-t._origin,Y(t._tail&&t._tail.array,0,n-t._origin,t._size-t._origin))};ge.createClass(un,{next:function(){for(var t=this._sparse,e=this._stack;e;){var n=e.array,r=e.index++,i=1<<e.level,u=e.offset+r*i;if(Me>r&&u>-i&&e.max>u){var s=n&&n[r];if(0===e.level){if(!t||s||n&&n.length>r&&n.hasOwnProperty(r))return b(t?[u,s]:s)}else(!t||s)&&(this._stack=e=Y(s&&s.array,e.level-Se,u,e.max,e))}else e=this._stack=this._stack.__prev}return S()}},{},De);var sn,an=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return on.from(t)},on=an;ge.createClass(an,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map.has(t)},get:function(t,e){return this.has(t)?t:e},add:function(t){var e=this._map.set(t,null);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:ae(e)},"delete":function(t){var e=this._map.delete(t);return this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:0===e.length?on.empty():ae(e)},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this):on.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var n=0;t.length>n;n++)ve(t[n]).forEach(function(t){return e.add(t)})})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ve(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.every(function(t){return t.contains(n)})||e.delete(n)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return ve(t)});var n=this;return this.withMutations(function(e){n.forEach(function(n){t.some(function(t){return t.contains(n)})&&e.delete(n)})})},isSubset:function(t){return t=ve(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=ve(t),t.every(function(t){return e.contains(t) <ide> })},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var n=this;return this._map.__iterate(function(e,r){return t(r,r,n)},e)},__deepEquals:function(t){return this._map.equals(t._map)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t);return t?ae(e,t):(this.__ownerID=t,this._map=e,this)}},{empty:function(){return cn||(cn=ae(je.empty()))},from:function(t){var e=on.empty();return t?t.constructor===on?t:e.union(t):e},fromKeys:function(t){return on.from(ve(t).flip())}},ve);var hn=an.prototype;hn.contains=hn.has,hn.mergeDeep=hn.merge=hn.union,hn.mergeDeepWith=hn.mergeWith=function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return this.merge.apply(this,t)},hn.withMutations=We.withMutations,hn.asMutable=We.asMutable,hn.asImmutable=We.asImmutable,hn.__toJS=we.__toJS,hn.__toStringMapper=we.__toStringMapper;var cn,fn=function(t){var e=ln.empty();return t?t.constructor===ln?t:e.merge(t):e},ln=fn;ge.createClass(fn,{toString:function(){return this.__toString("OrderedMap {","}")},get:function(t,e){var n=this._map.get(t);return null!=n?this._vector.get(n)[1]:e},clear:function(){return 0===this.length?this:this.__ownerID?(this.length=0,this._map.clear(),this._vector.clear(),this):ln.empty()},set:function(t,e){var n=this._map.get(t),r=null!=n,i=r?this._map:this._map.set(t,this._vector.length),u=r?this._vector.set(n,[t,e]):this._vector.push([t,e]);return this.__ownerID?(this.length=i.length,this._map=i,this._vector=u,this):u===this._vector?this:oe(i,u)},"delete":function(t){var e=this._map.get(t);if(null==e)return this;var n=this._map.delete(t),r=this._vector.delete(e);return this.__ownerID?(this.length=n.length,this._map=n,this._vector=r,this):0===n.length?ln.empty():oe(n,r)},wasAltered:function(){return this._map.wasAltered()||this._vector.wasAltered()},iterator:function(){return this._vector.iterator()},__iterate:function(t,e){return this._vector.fromEntries().__iterate(t,e)},__deepEqual:function(t){var e=this._vector.iterator();return t.every(function(t,n){var r=e.next().value; <ide> return r&&C(r[0],n)&&C(r[1],t)})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map.__ensureOwner(t),n=this._vector.__ensureOwner(t);return t?oe(e,n,t):(this.__ownerID=t,this._map=e,this._vector=n,this)}},{empty:function(){return _n||(_n=oe(je.empty(),$e.empty()))}},je),fn.from=fn;var _n,gn=function(t,e){var n=function(t){this._map=je(t)};t=ve(t);var r=n.prototype=Object.create(pn);r.constructor=n,r._name=e,r._defaultValues=t;var i=Object.keys(t);return n.prototype.length=i.length,Object.defineProperty&&t.forEach(function(t,e){Object.defineProperty(n.prototype,e,{get:function(){return this.get(e)},set:function(t){E(this.__ownerID,"Cannot set on an immutable record."),this.set(e,t)}})}),n},vn=gn;ge.createClass(gn,{toString:function(){return this.__toString((this._name||"Record")+" {","}")},has:function(t){return this._defaultValues.has(t)},get:function(t,e){return void 0===e||this.has(t)?this._map.get(t,this._defaultValues.get(t)):e},clear:function(){if(this.__ownerID)return this._map.clear(),this;Object.getPrototypeOf(this).constructor;return vn._empty||(vn._empty=he(this,je.empty()))},set:function(t,e){if(null==t||!this.has(t))return this;var n=this._map.set(t,e);return this.__ownerID||n===this._map?this:he(this,n)},"delete":function(t){if(null==t||!this.has(t))return this;var e=this._map.delete(t);return this.__ownerID||e===this._map?this:he(this,e)},wasAltered:function(){return this._map.wasAltered()},__iterate:function(t,e){var n=this;return this._defaultValues.map(function(t,e){return n.get(e)}).__iterate(t,e)},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?he(this,e,t):(this.__ownerID=t,this._map=e,this)}},{},ve);var pn=gn.prototype;pn.__deepEqual=We.__deepEqual,pn.merge=We.merge,pn.mergeWith=We.mergeWith,pn.mergeDeep=We.mergeDeep,pn.mergeDeepWith=We.mergeDeepWith,pn.update=We.update,pn.updateIn=We.updateIn,pn.cursor=We.cursor,pn.withMutations=We.withMutations,pn.asMutable=We.asMutable,pn.asImmutable=We.asImmutable;var mn=function(t,e,n){return this instanceof dn?(E(0!==n,"Cannot step a Range by 0"),t=t||0,null==e&&(e=1/0),t===e&&wn?wn:(n=null==n?1:Math.abs(n),t>e&&(n=-n),this._start=t,this._end=e,this._step=n,void(this.length=Math.max(0,Math.ceil((e-t)/n-1)+1)))):new dn(t,e,n) <ide> },dn=mn;ge.createClass(mn,{toString:function(){return 0===this.length?"Range []":"Range [ "+this._start+"..."+this._end+(this._step>1?" by "+this._step:"")+" ]"},has:function(t){return E(t>=0,"Index out of bounds"),this.length>t},get:function(t,e){return E(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._start+t*this._step:e},contains:function(t){var e=(t-this._start)/this._step;return e>=0&&this.length>e&&e===Math.floor(e)},slice:function(t,e,n){return s(t,e,this.length)?this:n?ge.superCall(this,dn.prototype,"slice",[t,e,n]):(t=a(t,this.length),e=o(e,this.length),t>=e?wn:new dn(this.get(t,this._end),this.get(e,this._end),this._step))},indexOf:function(t){var e=t-this._start;if(e%this._step===0){var n=e/this._step;if(n>=0&&this.length>n)return n}return-1},lastIndexOf:function(t){return this.indexOf(t)},take:function(t){return this.slice(0,t)},skip:function(t,e){return e?ge.superCall(this,dn.prototype,"skip",[t]):this.slice(t)},__iterate:function(t,e,n){for(var r=e^n,i=this.length-1,u=this._step,s=e?this._start+i*u:this._start,a=0;i>=a&&t(s,r?i-a:a,this)!==!1;a++)s+=e?-u:u;return r?this.length:a},__deepEquals:function(t){return this._start===t._start&&this._end===t._end&&this._step===t._step}},{},de);var yn=mn.prototype;yn.__toJS=yn.toArray,yn.first=en.first,yn.last=en.last;var wn=mn(0,0),In=function(t,e){return 0===e&&bn?bn:this instanceof kn?(this._value=t,void(this.length=null==e?1/0:Math.max(0,e))):new kn(t,e)},kn=In;ge.createClass(In,{toString:function(){return 0===this.length?"Repeat []":"Repeat [ "+this._value+" "+this.length+" times ]"},get:function(t,e){return E(t>=0,"Index out of bounds"),1/0===this.length||this.length>t?this._value:e},first:function(){return this._value},contains:function(t){return C(this._value,t)},slice:function(t,e,n){if(n)return ge.superCall(this,kn.prototype,"slice",[t,e,n]);var r=this.length;return t=0>t?Math.max(0,r+t):Math.min(r,t),e=null==e?r:e>0?Math.min(r,e):Math.max(0,r+e),e>t?new kn(this._value,e-t):bn},reverse:function(t){return t?ge.superCall(this,kn.prototype,"reverse",[t]):this <ide><path>src/Vector.js <ide> class VectorIterator extends SequenceIterator { <ide> if (rawIndex < SIZE && index > -step && index < stack.max) { <ide> var value = array && array[rawIndex]; <ide> if (stack.level === 0) { <del> if (!sparse || value || (array && array.hasOwnProperty(rawIndex))) { <add> if (!sparse || value || (array && rawIndex < array.length && array.hasOwnProperty(rawIndex))) { <ide> return iteratorValue(sparse ? [index, value] : value); <ide> } <ide> } else if (!sparse || value) {
3
Text
Text
improve async_context introduction
40d890d31d6f7c61481566446a7a28d15e0eb4fc
<ide><path>doc/api/async_context.md <del># Asynchronous Context Tracking <add># Asynchronous context tracking <ide> <ide> <!--introduced_in=v16.4.0--> <ide> <ide> The `AsyncLocalStorage` and `AsyncResource` classes are part of the <ide> `async_hooks` module: <ide> <ide> ```mjs <del>import async_hooks from 'async_hooks'; <add>import { AsyncLocalStorage, AsyncResource } from 'async_hooks'; <ide> ``` <ide> <ide> ```cjs <del>const async_hooks = require('async_hooks'); <add>const { AsyncLocalStorage, AsyncResource } = require('async_hooks'); <ide> ``` <ide> <ide> ## Class: `AsyncLocalStorage` <ide><path>doc/api/index.md <ide> <hr class="line"/> <ide> <ide> * [Assertion testing](assert.md) <del>* [Async\_context](async\_context.md) <add>* [Asynchronous context tracking](async\_context.md) <ide> * [Async hooks](async\_hooks.md) <ide> * [Buffer](buffer.md) <ide> * [C++ addons](addons.md)
2
Text
Text
clarify text about internal module changes
be322bd9ada1579d16ab3af45328e313e0ff1a5c
<ide><path>lib/internal/readme.md <ide> # Internal Modules <ide> <ide> The modules in `lib/internal` are intended for internal use in Node.js core <del>only, and are not accessible with `require()` from user modules. These are <del>subject to change at **any** time. Reliance on these modules outside of core <add>only, and are not accessible with `require()` from user modules. These modules <add>can be changed at **any** time. Reliance on these modules outside of core <ide> is **not supported** in any way.
1
Javascript
Javascript
replace concatenation with template literals
a5352d9f1f399a1a4d4a2f445ce08fb88da66695
<ide><path>test/parallel/test-stdout-close-catch.js <ide> const child_process = require('child_process'); <ide> <ide> const testScript = path.join(common.fixturesDir, 'catch-stdout-error.js'); <ide> <del>const cmd = JSON.stringify(process.execPath) + ' ' + <del> JSON.stringify(testScript) + ' | ' + <del> JSON.stringify(process.execPath) + ' ' + <add>const cmd = `${JSON.stringify(process.execPath)} ` + <add> `${JSON.stringify(testScript)} | ` + <add> `${JSON.stringify(process.execPath)} ` + <ide> '-pe "process.stdin.on(\'data\' , () => process.exit(1))"'; <ide> <ide> const child = child_process.exec(cmd);
1
Javascript
Javascript
replace var with let in loaders.js
863402e4f236bc8097c8a408de437f0b8f082bc2
<ide><path>lib/internal/bootstrap/loaders.js <ide> const { <ide> } = internalBinding('native_module'); <ide> <ide> NativeModule.map = new Map(); <del>for (var i = 0; i < moduleIds.length; ++i) { <add>for (let i = 0; i < moduleIds.length; ++i) { <ide> const id = moduleIds[i]; <ide> const mod = new NativeModule(id); <ide> NativeModule.map.set(id, mod);
1
Python
Python
add logic for xcomarg to pull specific map indexes
8a8ad4719a182f6bcbb6f2263b9ec2a74b7bea35
<ide><path>airflow/models/xcom_arg.py <ide> if TYPE_CHECKING: <ide> from airflow.models.dag import DAG <ide> from airflow.models.operator import Operator <add> from airflow.models.taskinstance import TaskInstance <add> from airflow.utils.task_group import MappedTaskGroup, TaskGroup <ide> <ide> # Callable objects contained by MapXComArg. We only accept callables from <ide> # the user, but deserialize them into strings in a serialized XComArg for <ide> # safety (those callables are arbitrary user code). <ide> MapCallables = Sequence[Union[Callable[[Any], Any], str]] <ide> <ide> <add>def _find_common_ancestor_mapped_group(node1: Operator, node2: Operator) -> MappedTaskGroup | None: <add> """Given two operators, find their innermost common mapped task group.""" <add> if node1.dag is None or node2.dag is None or node1.dag_id != node2.dag_id: <add> return None <add> parent_group_ids = {g.group_id for g in node1.iter_mapped_task_groups()} <add> common_groups = (g for g in node2.iter_mapped_task_groups() if g.group_id in parent_group_ids) <add> return next(common_groups, None) <add> <add> <add>def _is_further_mapped_inside(operator: Operator, container: TaskGroup) -> bool: <add> """Whether given operator is *further* mapped inside a task group.""" <add> if operator.is_mapped: <add> return True <add> task_group = operator.task_group <add> while task_group is not None and task_group.group_id != container.group_id: <add> if isinstance(task_group, MappedTaskGroup): <add> return True <add> task_group = task_group.parent_group <add> return False <add> <add> <ide> class XComArg(ResolveMixin, DependencyMixin): <ide> """Reference to an XCom value pushed from another operator. <ide> <ide> def get_task_map_length(self, run_id: str, *, session: Session) -> int | None: <ide> ) <ide> return query.scalar() <ide> <add> def _get_map_indexes_to_pull( <add> self, <add> ti: TaskInstance, <add> ti_count: int | None, <add> *, <add> session: Session, <add> ) -> int | range | None: <add> """Infer the correct ``map_indexes`` to ``xcom_pull`` for resolution. <add> <add> The bulk of the logic mainly exists to solve the problem described by <add> the following example, where 'val' must resolve to different values, <add> depending on where the reference is being used:: <add> <add> @task <add> def this_task(v): # This task is ti.task. <add> return v * 2 <add> <add> @task_group <add> def tg1(inp): <add> val = referenced_task(inp) # This task is self.operator. <add> this_task(val) # When inp is 1, val here should resolve to 2. <add> return val <add> <add> # This val is the same object returned by tg1. <add> val = tg1.expand(inp=[1, 2, 3]) <add> <add> @task_group <add> def tg2(inp): <add> another_task(inp, val) # val here should resolve to [2, 4, 6]. <add> <add> tg2.expand(inp=["a", "b"]) <add> <add> The surrounding mapped task groups of ``self.operator`` and ``ti.task`` <add> are inspected to find a common "ancestor". If such an ancestor is found, <add> we need to return specific map indexes to pull a partial value from <add> upstream XCom. <add> <add> :param ti: The currently executing task instance, i.e. ``ti`` in the <add> template context. <add> :param ti_count: The total count of task instance this task was expanded <add> by the scheduler, i.e. ``expanded_ti_count`` in the template context. <add> :return: Specific map index or map indexes to pull, or ``None`` if we <add> want to "whole" return value (i.e. no mapped task groups involved). <add> """ <add> # Find the innermost common mapped task group between the current task <add> # If the current task and the referenced task does not have a common <add> # mapped task group, the two are in different task mapping contexts <add> # (like another_task above), and we should use the "whole" value. <add> common_ancestor = _find_common_ancestor_mapped_group(ti.task, self.operator) <add> if common_ancestor is None: <add> return None <add> <add> # This value should never be None since we already know the current task <add> # is in a mapped task group, and should have been expanded. The check <add> # exists mainly to satisfy Mypy. <add> if ti_count is None: <add> return None <add> <add> # At this point we know the two tasks share a mapped task group, and we <add> # should use a "partial" value. Let's break down the mapped ti count <add> # between the ancestor and further expansion happened inside it. <add> ancestor_ti_count = common_ancestor.get_mapped_ti_count(ti.run_id, session=session) <add> ancestor_map_index = ti.map_index * ancestor_ti_count // ti_count <add> <add> # If the task is NOT further expanded inside the common ancestor, we <add> # only want to reference one single ti. We must walk the actual DAG, <add> # and "ti_count == ancestor_ti_count" does not work, since the further <add> # expansion may be of length 1. <add> if not _is_further_mapped_inside(self.operator, common_ancestor): <add> return ancestor_map_index <add> <add> # Otherwise we need a partial aggregation for values from selected task <add> # instances in the ancestor's expansion context. <add> further_count = ti_count // ancestor_ti_count <add> map_index_start = ancestor_map_index * further_count <add> return range(map_index_start, map_index_start + further_count) <add> <ide> @provide_session <ide> def resolve(self, context: Context, session: Session = NEW_SESSION) -> Any: <add> ti = context["ti"] <ide> task_id = self.operator.task_id <del> result = context["ti"].xcom_pull(task_ids=task_id, key=str(self.key), default=NOTSET, session=session) <add> result = ti.xcom_pull( <add> task_ids=task_id, <add> map_indexes=self._get_map_indexes_to_pull(ti, context["expanded_ti_count"], session=session), <add> key=self.key, <add> default=NOTSET, <add> session=session, <add> ) <ide> if not isinstance(result, ArgNotSet): <ide> return result <ide> if self.key == XCOM_RETURN_KEY: <ide> return None <del> raise XComNotFound(context["ti"].dag_id, task_id, self.key) <add> raise XComNotFound(ti.dag_id, task_id, self.key) <ide> <ide> <ide> def _get_callable_name(f: Callable | str) -> str: <ide><path>tests/models/test_dagrun.py <ide> def tg(x, y): <ide> ("tg.task_2", 4, None), <ide> ("tg.task_2", 5, None), <ide> } <add> <add> <add>def test_operator_mapped_task_group_receives_value(dag_maker, session): <add> with dag_maker(session=session): <add> <add> @task <add> def t(value, *, ti=None): <add> results[(ti.task_id, ti.map_index)] = value <add> return value <add> <add> @task_group <add> def tg(va): <add> # Each expanded group has one t1 and t2 each. <add> t1 = t.override(task_id="t1")(va) <add> t2 = t.override(task_id="t2")(t1) <add> <add> with pytest.raises(NotImplementedError) as ctx: <add> t.override(task_id="t4").expand(value=va) <add> assert str(ctx.value) == "operator expansion in an expanded task group is not yet supported" <add> <add> return t2 <add> <add> # The group is mapped by 3. <add> t2 = tg.expand(va=[["a", "b"], [4], ["z"]]) <add> <add> # Aggregates results from task group. <add> t.override(task_id="t3")(t2) <add> <add> dr: DagRun = dag_maker.create_dagrun() <add> <add> results = {} <add> decision = dr.task_instance_scheduling_decisions(session=session) <add> for ti in decision.schedulable_tis: <add> ti.run() <add> assert results == {("tg.t1", 0): ["a", "b"], ("tg.t1", 1): [4], ("tg.t1", 2): ["z"]} <add> <add> results = {} <add> decision = dr.task_instance_scheduling_decisions(session=session) <add> for ti in decision.schedulable_tis: <add> ti.run() <add> assert results == {("tg.t2", 0): ["a", "b"], ("tg.t2", 1): [4], ("tg.t2", 2): ["z"]} <add> <add> results = {} <add> decision = dr.task_instance_scheduling_decisions(session=session) <add> for ti in decision.schedulable_tis: <add> ti.run() <add> assert len(results) == 1 <add> assert list(results[("t3", -1)]) == [["a", "b"], [4], ["z"]]
2
Javascript
Javascript
use ember.k for consistency
4584fafdaf2747c8fb1b92fe2f936cba1051e2c9
<ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.CoreView.extend( <ide> <ide> @event willDestroyElement <ide> */ <del> willDestroyElement: function() {}, <add> willDestroyElement: Ember.K, <ide> <ide> /** <ide> @private
1
Javascript
Javascript
add missing semicolon
2fa0ea62e7fc96be06d18fbfbf77ff14abfc6324
<ide><path>test/Compiler.test.js <ide> describe("Compiler", () => { <ide> done(); <ide> }); <ide> }); <del> }) <add> }); <ide> });
1
Javascript
Javascript
remove unnecessary comments
b50a1a520ebd8950a0c3fdb92a015a927d0d69c9
<ide><path>src/core/Box3.js <ide> <ide> THREE.Box3 = function ( min, max ) { <ide> <del> // TODO: Is this valid JavaScript to check if the parameters are specified? <ide> if( ! min && ! max ) { <ide> this.min = new THREE.Vector3(); <ide> this.max = new THREE.Vector3(); <ide><path>src/core/Plane.js <ide> THREE.Plane.prototype = { <ide> }, <ide> <ide> setFromNormalAndCoplanarPoint: function ( normal, point ) { <del> // NOTE: This function doens't support optional parameters like the constructor. <ide> <ide> this.normal = normal; <ide> this.constant = - point.dot( normal ); <ide> THREE.Plane.prototype = { <ide> }, <ide> <ide> setFromCoplanarPoints: function ( a, b, c ) { <del> // NOTE: This function doens't support optional parameters like the constructor. <ide> <ide> var normal = new THREE.Vector3().sub( b, a ).cross( <ide> new THREE.Vector3().sub( c, a ) ); <ide> THREE.Plane.prototype = { <ide> <ide> flip: function () { <ide> <del> // Note: can also be flipped by inverting constant, but I like constant to stay positive generally. <ide> this.normal.negate(); <ide> <ide> return this; <ide> THREE.Plane.prototype = { <ide> <ide> translate: function ( offset ) { <ide> <del> // TODO: test this. <ide> this.constant = - offset.dot( normal ); <ide> <ide> return this;
2
Text
Text
translate ja of scenegraph
b0778d0ce5bc2bba07c42918a50cb7680abf0f40
<ide><path>threejs/lessons/ja/threejs-scenegraph.md <add>Title: Three.jsのシーングラフ <add>Description: シーングラフとはなにか? <add>TOC: シーングラフ <add> <add>この記事はthree.jsについてのシリーズ記事の一つです。 <add>最初の記事は[Three.jsの基礎](threejs-fundamentals.html)です。 <add>まだ読んでない人は、そちらから先に読んでみるといいかもしれません。 <add> <add>Three.jsの核心は間違いなくシーングラフです。 <add>3Dエンジンのシーングラフは、各ノードがローカルな空間を表現している、グラフ内のノードの階層です。 <add> <add><img src="resources/images/scenegraph-generic.svg" align="center"> <add> <add>抽象的なので、例をいくつか挙げてみましょう。 <add> <add>例の一つは太陽系、太陽・地球・月でしょうか。 <add> <add><img src="resources/images/scenegraph-solarsystem.svg" align="center"> <add> <add>地球は太陽を回っています。月は地球を回っています。 <add>月は地球の周りを円を描いて移動しています。月から見ると、地球の"ローカルな空間"を回っていることになります。 <add>太陽との相対的な動きは、月の視点から見るとクレイジーな螺旋のような曲線に見えますが、単に地球のローカルな空間を周回していると捉える必要があります。 <add> <add>{{{diagram url="resources/moon-orbit.html" }}} <add> <add>別の考え方をしてみます。地球が地軸の周りを自転していることも、太陽の周りを公転していることも、 <add>地球に住んでいるあなたが考える必要はありません。 <add>皆さんは全くもって地球が動きも回りもしていないかのように、 <add>歩いたり、ドライブしたり、泳いだり、走ったりするだけです。 <add>地球の"ローカルな空間"で歩いたり、ドライブしたり、泳いだり、走ったり、そして生活したりしていても、みなさんは太陽と相対的に、地球の上で1,600km/hの速さで回転し、太陽の周りを107,200km/hの速度で回っています。 <add>太陽系上のみなさんの位置は、前述した月と同じようなものですが、気にする必要はありません。 <add>みなさんは地球の"ローカルな空間"で、地球との相対的な位置だけを心配していればいいのです。 <add> <add>一歩進みましょう。私たちは太陽と地球と月の図を作りたいと想像してみてください。 <add>まず、太陽から始めましょう。ただ球体を作り原点に置くだけです。 <add>シーングラフを使う方法の演習として、太陽、地球、月を使うことを、気に留めておいてください。 <add>もちろん、現実の太陽、地球、月は物理学に従いますが、演習目的なので、シーングラフで代用します。 <add> <add> <add>```js <add>// an array of objects whose rotation to update <add>const objects = []; <add> <add>// use just one sphere for everything <add>const radius = 1; <add>const widthSegments = 6; <add>const heightSegments = 6; <add>const sphereGeometry = new THREE.SphereBufferGeometry( <add> radius, widthSegments, heightSegments); <add> <add>const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00}); <add>const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial); <add>sunMesh.scale.set(5, 5, 5); // make the sun large <add>scene.add(sunMesh); <add>objects.push(sunMesh); <add>``` <add> <add>とても少ないポリゴンからできた球体を使います。緯度方向にたった6分割です。 <add>これで、回転していることが見やすくなります。 <add> <add>同じ球体を全ての球体に使いまわすつもりなので、太陽のメッシュの大きさを5倍にしておきます。 <add> <add>また、phong materialの`emissive`属性を黄色に設定します。 <add>phong materialのemissive属性は、基本的に、光が当たっていない表面に描かれる色です。 <add>光源はその色に付け加えられます。 <add> <add>次に、シーンの真ん中に1つ点光源を置きましょう。後ほど、より詳細に点光源について説明しますが、 <add>一点から発せられる明かりというのが、とりあえずの簡単な説明です。 <add> <add>```js <add>{ <add> const color = 0xFFFFFF; <add> const intensity = 3; <add> const light = new THREE.PointLight(color, intensity); <add> scene.add(light); <add>} <add>``` <add> <add>見やすくするために、直接原点を見下ろすようにカメラを置きましょう。 <add>最も簡単な方法は `lookAt`関数を使うことです。 <add>`lookAt`関数は、引数に渡した位置を「見る」ようにカメラを向けます。 <add>その前に、カメラの上部がどの方向を向いているか、もしくは、 <add>カメラにとってどの方向が"上"なのかを、カメラに伝える必要があります。 <add>ほとんどの場合、Y軸の正が上で十分ですが、 <add>今は見下ろしているので、Z軸の正が上だとカメラに伝える必要があります。 <add> <add>```js <add>const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); <add>camera.position.set(0, 50, 0); <add>camera.up.set(0, 0, 1); <add>camera.lookAt(0, 0, 0); <add>``` <add> <add>レンダリングループの中で、前の例を参考にして、以下のコードで、`objects`配列内の全てのオブジェクトを回転させています。 <add> <add>```js <add>objects.forEach((obj) => { <add> obj.rotation.y = time; <add>}); <add>``` <add> <add>`sunMesh`を`objects`配列に追加したので、回転します。 <add> <add>{{{example url="../threejs-scenegraph-sun.html" }}} <add> <add>さて、地球を追加してみましょう。 <add> <add>```js <add>const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <add>const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>earthMesh.position.x = 10; <add>scene.add(earthMesh); <add>objects.push(earthMesh); <add>``` <add> <add>青いマテリアルを作っていますが、黒背景に対して目立つよう、 <add>*emissive*に少し青色を設定します。 <add> <add>`earthMesh`を作るため、新しく作った青色の`earthMaterial`と、先と同じ`sphereGeometry`を使います。 <add>それを太陽の10ユニット左側に置き、シーンに追加します。 <add>これは`objects`配列にそれを追加されたので、同様に回転します。 <add> <add> <add>{{{example url="../threejs-scenegraph-sun-earth.html" }}} <add> <add>太陽と地球の両方が回転して見えますが、地球は太陽の周りを公転していません。 <add>地球を太陽の子要素にしてみましょう。 <add> <add>```js <add>-scene.add(earthMesh); <add>+sunMesh.add(earthMesh); <add>``` <add> <add>そして... <add> <add>{{{example url="../threejs-scenegraph-sun-earth-orbit.html" }}} <add> <add>なにが起きましたか?なぜ地球が太陽と同じ大きさで、こんなに離れているのでしょうか。 <add>地球を見るためには、実際のところ、カメラを50ユニット上から、150ユニット上に動かす必要がありました。 <add> <add>`earthMesh`を`sunMesh`の子要素としました。 <add>`sunMesh`は`sunMesh.scale.set(5, 5, 5)`によって5倍に大きさを設定しています。 <add>よって、`sunMesh`のローカルな空間は5倍大きくなりました。 <add>その空間におかれるあらゆるものは5倍されるのです。 <add>つまり、地球が5倍大きくなり、太陽からの距離も5倍(`earthMesh.position.x = 10`)になったのです。 <add> <add> シーングラフは、このようになります。 <add> <add><img src="resources/images/scenegraph-sun-earth.svg" align="center"> <add> <add>これを修正するため、シーングラフに空のノードを追加しましょう。 <add>そして、太陽と地球の両方をそのノードの子要素にしましょう。 <add> <add>```js <add>+const solarSystem = new THREE.Object3D(); <add>+scene.add(solarSystem); <add>+objects.push(solarSystem); <add> <add>const sunMaterial = new THREE.MeshPhongMaterial({emissive: 0xFFFF00}); <add>const sunMesh = new THREE.Mesh(sphereGeometry, sunMaterial); <add>sunMesh.scale.set(5, 5, 5); <add>-scene.add(sunMesh); <add>+solarSystem.add(sunMesh); <add>objects.push(sunMesh); <add> <add>const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <add>const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>earthMesh.position.x = 10; <add>-sunMesh.add(earthMesh); <add>+solarSystem.add(earthMesh); <add>objects.push(earthMesh); <add>``` <add> <add>ここで`Object3D`を作りました。`Mesh`のように、シーングラフのノードですが、`Mesh`とは異なり、マテリアルやジオメトリを持ちません。 <add>ただローカルな空間を表現するだけです。 <add> <add>新しいシーングラフは、このようになります。 <add> <add><img src="resources/images/scenegraph-sun-earth-fixed.svg" align="center"> <add> <add>`sunMesh`と`earthMesh`は共に`solarSystem`の子要素です。3つ全部が回転していますが、 <add>いま`earthMesh`は`sunMesh`の子要素ではないので、5倍に拡大されません。 <add> <add>{{{example url="../threejs-scenegraph-sun-earth-orbit-fixed.html" }}} <add> <add>とてもよくなりました。地球は太陽よりも小さく、太陽の周りを公転しつつ、自転しています。 <add> <add>続けて、同様の方法で月を追加してみましょう。 <add> <add>```js <add>+const earthOrbit = new THREE.Object3D(); <add>+earthOrbit.position.x = 10; <add>+solarSystem.add(earthOrbit); <add>+objects.push(earthOrbit); <add> <add>const earthMaterial = new THREE.MeshPhongMaterial({color: 0x2233FF, emissive: 0x112244}); <add>const earthMesh = new THREE.Mesh(sphereGeometry, earthMaterial); <add>-solarSystem.add(earthMesh); <add>+earthOrbit.add(earthMesh); <add>objects.push(earthMesh); <add> <add>+const moonOrbit = new THREE.Object3D(); <add>+moonOrbit.position.x = 2; <add>+earthOrbit.add(moonOrbit); <add> <add>+const moonMaterial = new THREE.MeshPhongMaterial({color: 0x888888, emissive: 0x222222}); <add>+const moonMesh = new THREE.Mesh(sphereGeometry, moonMaterial); <add>+moonMesh.scale.set(.5, .5, .5); <add>+moonOrbit.add(moonMesh); <add>+objects.push(moonMesh); <add>``` <add> <add>再び、描画されないシーングラフのノードを追加しました。これは、`earthOrbit`と呼ばれる`Object3D`です。 <add>そして、このノードに`earthMesh`と`moonMesh`の両方を追加しました。 <add>新しいシーングラフは、このようになります。 <add> <add><img src="resources/images/scenegraph-sun-earth-moon.svg" align="center"> <add> <add>そして、このように描画されます。 <add> <add>{{{example url="../threejs-scenegraph-sun-earth-moon.html" }}} <add> <add>記事の上部でお見せした螺旋のパターンに沿った月が見えます。 <add>しかし、手動で操作する必要はありませんでした。 <add>ただ、シーングラフを設定しただけです。 <add> <add>シーングラフのノードが分かるような、なにかを描写すると、便利なことがあります。 <add>Three.jsはこれをするために、helpfulとか、helpersとかがあります。 <add> <add>一つは`AxesHelper`です。 <add>ローカルな<span style="color:red">X</span>、<span style="color:green">Y</span>、<span style="color:blue">Z</span>軸を表す <add>3つの線を描画します。 <add>私たちが作った全てのノードに加えましょう。 <add> <add>```js <add>// add an AxesHelper to each node <add>objects.forEach((node) => { <add> const axes = new THREE.AxesHelper(); <add> axes.material.depthTest = false; <add> axes.renderOrder = 1; <add> node.add(axes); <add>}); <add>``` <add> <add>私たちの場合、たとえ球体の内部であったとしても、軸を表示させたいです。 <add>これをするために、マテリアルの`depthTest`をfalseにします。 <add>これによって、軸がなにかの内部に描画されているかどうかチェックしなくなります。 <add>全ての球体の後に描画されるように、`renderOrder`も1に設定します(デフォルト値は0です)。 <add>そうしないと、球体が軸の上に描画され、軸を覆ってしまう可能性があります。 <add> <add>{{{example url="../threejs-scenegraph-sun-earth-moon-axes.html" }}} <add> <add><span style="color:red">x (赤)</span> と<span style="color:blue">z (青)</span>の <add>軸が見えます。私たちはオブジェクトをまっすぐ見下ろしていて、オブジェクトはy軸を中心に <add>回転しているので、<span style="color:green">y (緑)</span>軸があまり見えません。 <add> <add>位置が重なった軸が2組あるので、見づらいかもしれません。 <add>`sunMesh`と`solarSystem`は同じ場所にあります。 <add>同様に、`earthMesh`と`earthOrbit`は同じ場所にあります。 <add>各ノードに対してオン/オフできるように、簡単な操作を加えてみましょう。 <add>そのついでに、`GridHelper` というヘルパー関数も追加しておきましょう。 <add>これはX,Z平面に2次元グリッドを作ります。デフォルトでは、グリッドは10x10ユニットです。 <add> <add>[dat.GUI](https://github.com/dataarts/dat.gui)も使います。 <add>これはthree.jsプロジェクトでとても一般的なUIライブラリです。 <add>dat.GUIはオブジェクトとそのオブジェクトの属性名を受け取り、 <add>属性の型に基づいて、自動的にその属性を操作するUIを作成します。 <add> <add>それぞれのノードに対して、`GridHelper`と`AxesHelper`の両方を作りたいです。 <add>それぞれのノートにラベルが必要なので、古いループを削除し、 <add>各ノードにhelperを加える関数を呼ぶ形式にします。 <add> <add>```js <add>-// add an AxesHelper to each node <add>-objects.forEach((node) => { <add>- const axes = new THREE.AxesHelper(); <add>- axes.material.depthTest = false; <add>- axes.renderOrder = 1; <add>- node.add(axes); <add>-}); <add> <add>+function makeAxisGrid(node, label, units) { <add>+ const helper = new AxisGridHelper(node, units); <add>+ gui.add(helper, 'visible').name(label); <add>+} <add>+ <add>+makeAxisGrid(solarSystem, 'solarSystem', 25); <add>+makeAxisGrid(sunMesh, 'sunMesh'); <add>+makeAxisGrid(earthOrbit, 'earthOrbit'); <add>+makeAxisGrid(earthMesh, 'earthMesh'); <add>+makeAxisGrid(moonMesh, 'moonMesh'); <add>``` <add> <add>`makeAxisGrid`は、dat.GUIをハッピーにする`AxisGridHelper`クラスを作ります。 <add>前述したように、dat.GUIは、オブジェクトの名前が付いた属性を操作するUIを自動的に生成します。 <add>属性の型に応じて異なるUIが作成されます。 <add>チェックボックスを作って欲しいので、`bool`属性を指定する必要があります。 <add>しかし、軸とグリッドの両方を一つの属性で表示/非表示にしたいので、 <add>属性のgetterとsetterを持ったクラスを作成します。 <add>この方法で、dat.GUIに一つの属性を操作するように思わせることができますが、 <add>内部的には各ノードに`AxesHelper`と`GridHelper`の両方のvisible属性を設定することができます。 <add> <add> <add>```js <add>// Turns both axes and grid visible on/off <add>// dat.GUI requires a property that returns a bool <add>// to decide to make a checkbox so we make a setter <add>// and getter for `visible` which we can tell dat.GUI <add>// to look at. <add>class AxisGridHelper { <add> constructor(node, units = 10) { <add> const axes = new THREE.AxesHelper(); <add> axes.material.depthTest = false; <add> axes.renderOrder = 2; // after the grid <add> node.add(axes); <add> <add> const grid = new THREE.GridHelper(units, units); <add> grid.material.depthTest = false; <add> grid.renderOrder = 1; <add> node.add(grid); <add> <add> this.grid = grid; <add> this.axes = axes; <add> this.visible = false; <add> } <add> get visible() { <add> return this._visible; <add> } <add> set visible(v) { <add> this._visible = v; <add> this.grid.visible = v; <add> this.axes.visible = v; <add> } <add>} <add>``` <add> <add>注意することは、`AxesHelper`の`renderOrder`を2に設定し、`GridHelper`には1を設定することです。 <add>こうすることで、軸はグリッドの後に描画されます。 <add>そうしないと、グリッドが軸を上書きしてしまうかもしれません。 <add> <add>{{{example url="../threejs-scenegraph-sun-earth-moon-axes-grids.html" }}} <add> <add>`solarSystem`のチェックをオンにすると、上で設定したように、 <add>どのように地球が中心からちょうど10ユニットにあるか分かるでしょう。 <add>地球が`solarSystem`の*ローカルな空間*にどのように存在するか分かります。 <add>同様に、もし`earthOrbit`のチェックをオンにすると、 <add>どのように月が`earthOrbit`の*ローカルな空間*の中心から、ちょうど2ユニットあるか分かるでしょう。 <add> <add>もう少しシーングラフの例を紹介します。 <add>簡単なゲームの世界の自動車は、このようなシーングラフだとしましょう。 <add> <add><img src="resources/images/scenegraph-car.svg" align="center"> <add> <add>もし車のbody全体を動かすと、それに伴ってwheelsが動くでしょう。 <add>もしbodyにwheelsとは別にバウンドして欲しいとすると、 <add>bodyとwheelsを、車のフレームを表す"frame"ノードの子要素にできます。 <add> <add>別の例はゲームの世界の人間です。 <add> <add><img src="resources/images/scenegraph-human.svg" align="center"> <add> <add>とても複雑な人間のシーングラフを見てください。 <add>実際は、上記のシーングラフは単純化されています。 <add>例えば、全ての手の指(少なくとも28ノード)、全ての足の指(さらに28ノード)、 <add>加えて顔と顎、目、そしてもっと様々な部位もカバーするように、グラフを拡張できるかもしれません。 <add> <add> <add>もう少し複雑なシーングラフを作りましょう。戦車を作ります。 <add>戦車は6つの車輪と砲塔があります。この戦車はある道筋に沿って走ります。 <add>そこら中を移動する球体があり、戦車はその球体を狙うとしましょう。 <add> <add>これがシーングラフです。メッシュは緑色、`Object3D`は青色、明かりは金色、カメラは紫色です。 <add>シーングラフに追加されていないカメラが一つあります。 <add> <add><div class="threejs_center"><img src="resources/images/scenegraph-tank.svg" style="width: 800px;"></div> <add> <add>コードを見て、これらのノードの設定を確認してください。 <add> <add>ターゲット、つまり戦車が狙っているものとして、`targetOrbit`(`Object3D`) があります。 <add>これはちょうど前述の`earthOrbit`と同じように回転します。 <add>`targetOrbit`の子要素である`targetElevation` (`Object3D`)は、 <add>`targetOrbit`からのオフセットと基準となる高さを提供します。 <add>この子要素には、`targetElevation`に対して相対的に浮き沈みする、`targetBob`と呼ばれる`Object3D`があります。 <add>最後に、`targetMesh`があります。回転させて色を変えることができる、ただの立方体です。 <add> <add> <add>```js <add>// move target <add>targetOrbit.rotation.y = time * .27; <add>targetBob.position.y = Math.sin(time * 2) * 4; <add>targetMesh.rotation.x = time * 7; <add>targetMesh.rotation.y = time * 13; <add>targetMaterial.emissive.setHSL(time * 10 % 1, 1, .25); <add>targetMaterial.color.setHSL(time * 10 % 1, 1, .25); <add>``` <add> <add>戦車には、`tank`と呼ばれる`Object3D`があります。 <add>これを使って戦車の子要素をすべて移動させることができます。 <add>コードでは`SplineCurve`を使っています。これは曲線に沿った位置を求めることができます。 <add>0.0は曲線の始点です。1.0は曲線の終点です。これにより、戦車がある現在地を求めます。 <add>次に、カーブの少し下の位置を求めて、`Object3D.lookAt`を使い、戦車をその方向に向けます。 <add> <add> <add>```js <add>const tankPosition = new THREE.Vector2(); <add>const tankTarget = new THREE.Vector2(); <add> <add>... <add> <add>// move tank <add>const tankTime = time * .05; <add>curve.getPointAt(tankTime % 1, tankPosition); <add>curve.getPointAt((tankTime + 0.01) % 1, tankTarget); <add>tank.position.set(tankPosition.x, 0, tankPosition.y); <add>tank.lookAt(tankTarget.x, 0, tankTarget.y); <add>``` <add> <add>戦車のてっぺんに付いている砲塔は、戦車の子要素なので自動的に動きます。 <add>ターゲットの方を向かせるのに、ターゲットの位置を求め、次に再び`Object3D.lookAt`を使うだけです。 <add> <add>```js <add>const targetPosition = new THREE.Vector3(); <add> <add>... <add> <add>// face turret at target <add>targetMesh.getWorldPosition(targetPosition); <add>turretPivot.lookAt(targetPosition); <add>``` <add> <add>`turretCamera`は`turretMesh`の子要素なので、砲塔と一緒に上下に動き、回転します。 <add> <add> <add>```js <add>// make the turretCamera look at target <add>turretCamera.lookAt(targetPosition); <add>``` <add> <add>`targetBob`の子要素である`targetCameraPivot`もあります。これはターゲットと一緒に浮遊します。 <add>戦車に狙いを定めましょう。`targetCamera`にターゲット自身に高さを合わせるためです。 <add>もしカメラを`targetBob`の子要素にして、カメラ自身に狙いを定めさせただけだと、 <add>カメラがターゲットの内側に入り込んでしまうでしょう。 <add> <add>```js <add>// make the targetCameraPivot look at the tank <add>tank.getWorldPosition(targetPosition); <add>targetCameraPivot.lookAt(targetPosition); <add>``` <add> <add>最後に、全ての車輪を回転させます。 <add> <add>```js <add>wheelMeshes.forEach((obj) => { <add> obj.rotation.x = time * 3; <add>}); <add>``` <add> <add>初期化時に、4つ全てのカメラの配列を設定します。 <add> <add>```js <add>const cameras = [ <add> { cam: camera, desc: 'detached camera', }, <add> { cam: turretCamera, desc: 'on turret looking at target', }, <add> { cam: targetCamera, desc: 'near target looking at tank', }, <add> { cam: tankCamera, desc: 'above back of tank', }, <add>]; <add> <add>const infoElem = document.querySelector('#info'); <add>``` <add> <add>描画時にカメラを周回させます。 <add> <add>```js <add>const camera = cameras[time * .25 % cameras.length | 0]; <add>infoElem.textContent = camera.desc; <add>``` <add> <add>{{{example url="../threejs-scenegraph-tank.html"}}} <add> <add>シーングラフの動作と、使い方のアイデアを、この例から得られればと思います。 <add>`Object3D`ノードを作り、物体をその子要素にすることは、three.jsのような3Dエンジンを上手く使うために <add>重要なステップです。 <add>思い通りになにかを動かしたり回転させたりすることは、しばしば複雑な数学が必要に見えるかもしれません。 <add>例えばシーングラフなしで、月の動きを操作したり、車の車体に対して壮太知的に車輪を置いたりすることは、 <add>とても難しいかもしれません。しかし、シーングラフを使うことで、とても簡単になるのです。 <add> <add>[次はマテリアルを説明します](threejs-materials.html)。 <ide>\ No newline at end of file
1
Go
Go
fix testapidockerapiversion on windows
8c7fdddf480b39b79c688e1d555ca7f18fc5fd70
<ide><path>integration-cli/docker_api_test.go <ide> func (s *DockerSuite) TestAPIDockerAPIVersion(c *check.C) { <ide> defer server.Close() <ide> <ide> // Test using the env var first <del> result := cli.Docker(cli.Args("-H="+server.URL[7:], "version"), cli.WithEnvironmentVariables("DOCKER_API_VERSION=xxx")) <add> result := cli.Docker(cli.Args("-H="+server.URL[7:], "version"), cli.WithEnvironmentVariables(appendBaseEnv(false, "DOCKER_API_VERSION=xxx")...)) <ide> c.Assert(result, icmd.Matches, icmd.Expected{Out: "API version: xxx", ExitCode: 1}) <ide> c.Assert(svrVersion, check.Equals, "/vxxx/version", check.Commentf("%s", result.Compare(icmd.Success))) <ide> }
1
Javascript
Javascript
destroy editors after text editor component specs
20bf7050002cc29d2d8c4e1d4df255560ce5d299
<ide><path>spec/text-editor-component-spec.js <ide> document.registerElement('text-editor-component-test-element', { <ide> }) <ide> }) <ide> <add>const editors = [] <add> <ide> describe('TextEditorComponent', () => { <ide> beforeEach(() => { <ide> jasmine.useRealClock() <ide> describe('TextEditorComponent', () => { <ide> jasmine.attachToDOM(scrollbarStyle) <ide> }) <ide> <add> afterEach(() => { <add> for (const editor of editors) { <add> editor.destroy() <add> } <add> editors.length = 0 <add> }) <add> <ide> describe('rendering', () => { <ide> it('renders lines and line numbers for the visible region', async () => { <ide> const {component, element, editor} = buildComponent({rowsPerTile: 3, autoHeight: false}) <ide> function buildEditor (params = {}) { <ide> const editor = new TextEditor(editorParams) <ide> editor.testAutoscrollRequests = [] <ide> editor.onDidRequestAutoscroll((request) => { editor.testAutoscrollRequests.push(request) }) <add> editors.push(editor) <ide> return editor <ide> } <ide>
1
Javascript
Javascript
clarify info about from and to for animate()
a31c082de6dab64394b9a4d19c1a16e37b946887
<ide><path>src/ng/animate.js <ide> var $AnimateProvider = ['$provide', function($provide) { <ide> * @kind function <ide> * <ide> * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element. <del> * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take <del> * on the provided styles. For example, if a transition animation is set for the given className then the provided from and <del> * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles <del> * will be given in as function parameters into the `animate` method (or as apart of the `options` parameter). <add> * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take <add> * on the provided styles. For example, if a transition animation is set for the given className then the provided `from` and <add> * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding <add> * style in `to`, the style in `from` is applied immediately, and no animation is run. <add> * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate` <add> * method (or as part of the `options` parameter): <add> * <add> * ```js <add> * ngModule.animation('.my-inline-animation', function() { <add> * return { <add> * animate : function(element, className, from, to, done) { <add> * //styles <add> * } <add> * } <add> * }); <add> * ``` <ide> * <ide> * @param {DOMElement} element the element which the CSS styles will be applied to <ide> * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
1
Ruby
Ruby
add missing routing tests for info controller
b5e82d99efb073eeb240f8065b2271c2a5ebccdd
<ide><path>railties/test/application/routing_test.rb <ide> def teardown <ide> assert_equal 200, last_response.status <ide> end <ide> <add> test "rails/info in development" do <add> app("development") <add> app "/rails/info" <add> assert_equal 302, last_response.status <add> end <add> <ide> test "rails/info/routes in development" do <ide> app("development") <ide> get "/rails/info/routes" <ide> def index <ide> assert_equal 404, last_response.status <ide> end <ide> <add> test "rails/info in production" do <add> app("production") <add> get "/rails/info" <add> assert_equal 404, last_response.status <add> end <add> <ide> test "rails/info/routes in production" do <ide> app("production") <ide> get "/rails/info/routes"
1
Javascript
Javascript
fix some typos in dumpreacttree.js
5fbb307e24e144614b559bac57d1dfab6f52f2f4
<ide><path>Libraries/BugReporting/dumpReactTree.js <ide> function getReactTree() { <ide> } <ide> <ide> /* <del>function dumpNode(node: Object, identation: number) { <add>function dumpNode(node: Object, indentation: number) { <ide> const data = getReactData(node); <ide> if (data.nodeType === 'Text') { <del> return indent(identation) + data.text + '\n'; <add> return indent(indentation) + data.text + '\n'; <ide> } else if (data.nodeType === 'Empty') { <ide> return ''; <ide> } <del> let output = indent(identation) + `<${data.name}`; <add> let output = indent(indentation) + `<${data.name}`; <ide> if (data.nodeType === 'Composite') { <ide> for (const propName of Object.getOwnPropertyNames(data.props || {})) { <ide> if (isNormalProp(propName)) { <ide> function dumpNode(node: Object, identation: number) { <ide> } <ide> let childOutput = ''; <ide> for (const child of data.children || []) { <del> childOutput += dumpNode(child, identation + 1); <add> childOutput += dumpNode(child, indentation + 1); <ide> } <ide> <ide> if (childOutput) { <del> output += '>\n' + childOutput + indent(identation) + `</${data.name}>\n`; <add> output += '>\n' + childOutput + indent(indentation) + `</${data.name}>\n`; <ide> } else { <ide> output += ' />\n'; <ide> }
1
Ruby
Ruby
remove useless ivar
c10630b642bc6dc77b719385d6ba6a1569a6e739
<ide><path>actionpack/lib/action_dispatch/http/request.rb <ide> def initialize(env) <ide> @original_fullpath = nil <ide> @fullpath = nil <ide> @ip = nil <del> @request_id = nil <ide> end <ide> <ide> def check_path_parameters!
1
Go
Go
move client version to the docker cli
229d3bace8fbf1c077c063047710a6857ee2aaa6
<ide><path>api/client/client.go <ide> type apiClient interface { <ide> NetworkList() ([]types.NetworkResource, error) <ide> NetworkRemove(networkID string) error <ide> RegistryLogin(auth cliconfig.AuthConfig) (types.AuthResponse, error) <del> SystemVersion() (types.VersionResponse, error) <add> ServerVersion() (types.Version, error) <ide> VolumeCreate(options types.VolumeCreateRequest) (types.Volume, error) <ide> VolumeInspect(volumeID string) (types.Volume, error) <ide> VolumeList(filter filters.Args) (types.VolumesListResponse, error) <ide><path>api/client/lib/version.go <ide> package lib <ide> <ide> import ( <ide> "encoding/json" <del> "runtime" <ide> <del> "github.com/docker/docker/api" <ide> "github.com/docker/docker/api/types" <del> "github.com/docker/docker/dockerversion" <del> "github.com/docker/docker/utils" <ide> ) <ide> <del>// SystemVersion returns information of the docker client and server host. <del>func (cli *Client) SystemVersion() (types.VersionResponse, error) { <del> client := &types.Version{ <del> Version: dockerversion.Version, <del> APIVersion: api.Version, <del> GoVersion: runtime.Version(), <del> GitCommit: dockerversion.GitCommit, <del> BuildTime: dockerversion.BuildTime, <del> Os: runtime.GOOS, <del> Arch: runtime.GOARCH, <del> Experimental: utils.ExperimentalBuild(), <del> } <del> <add>// ServerVersion returns information of the docker client and server host. <add>func (cli *Client) ServerVersion() (types.Version, error) { <ide> resp, err := cli.get("/version", nil, nil) <ide> if err != nil { <del> return types.VersionResponse{Client: client}, err <add> return types.Version{}, err <ide> } <ide> defer ensureReaderClosed(resp) <ide> <ide> var server types.Version <ide> err = json.NewDecoder(resp.body).Decode(&server) <del> if err != nil { <del> return types.VersionResponse{Client: client}, err <del> } <del> return types.VersionResponse{Client: client, Server: &server}, nil <add> return server, err <ide> } <ide><path>api/client/version.go <ide> package client <ide> <ide> import ( <add> "runtime" <ide> "text/template" <ide> "time" <ide> <add> "github.com/docker/docker/api" <add> "github.com/docker/docker/api/types" <ide> Cli "github.com/docker/docker/cli" <add> "github.com/docker/docker/dockerversion" <ide> flag "github.com/docker/docker/pkg/mflag" <add> "github.com/docker/docker/utils" <ide> ) <ide> <ide> var versionTemplate = `Client: <ide> func (cli *DockerCli) CmdVersion(args ...string) (err error) { <ide> Status: "Template parsing error: " + err.Error()} <ide> } <ide> <del> vd, err := cli.client.SystemVersion() <add> vd := types.VersionResponse{ <add> Client: &types.Version{ <add> Version: dockerversion.Version, <add> APIVersion: api.Version, <add> GoVersion: runtime.Version(), <add> GitCommit: dockerversion.GitCommit, <add> BuildTime: dockerversion.BuildTime, <add> Os: runtime.GOOS, <add> Arch: runtime.GOARCH, <add> Experimental: utils.ExperimentalBuild(), <add> }, <add> } <add> <add> serverVersion, err := cli.client.ServerVersion() <add> if err == nil { <add> vd.Server = &serverVersion <add> } <ide> <ide> // first we need to make BuildTime more human friendly <ide> t, errTime := time.Parse(time.RFC3339Nano, vd.Client.BuildTime)
3
Python
Python
add xlmroberta to auto configuration
41a13a6375817ec3836bedcec67d12ad32bf0956
<ide><path>transformers/configuration_auto.py <ide> from .configuration_albert import AlbertConfig, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP <ide> from .configuration_camembert import CamembertConfig, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP <ide> from .configuration_t5 import T5Config, T5_PRETRAINED_CONFIG_ARCHIVE_MAP <add>from .configuration_xlm_roberta import XLMRobertaConfig, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP <ide> <ide> logger = logging.getLogger(__name__) <ide> <ide> ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> T5_PRETRAINED_CONFIG_ARCHIVE_MAP, <add> XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, <ide> ] <ide> for key, value, in pretrained_map.items()) <ide> <ide> class method. <ide> - contains `distilbert`: DistilBertConfig (DistilBERT model) <ide> - contains `albert`: AlbertConfig (ALBERT model) <ide> - contains `camembert`: CamembertConfig (CamemBERT model) <add> - contains `xlm-roberta`: XLMRobertaConfig (XLM-RoBERTa model) <ide> - contains `roberta`: RobertaConfig (RoBERTa model) <ide> - contains `bert`: BertConfig (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model) <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> - contains `distilbert`: DistilBertConfig (DistilBERT model) <ide> - contains `albert`: AlbertConfig (ALBERT model) <ide> - contains `camembert`: CamembertConfig (CamemBERT model) <add> - contains `xlm-roberta`: XLMRobertaConfig (XLM-RoBERTa model) <ide> - contains `roberta`: RobertaConfig (RoBERTa model) <ide> - contains `bert`: BertConfig (Bert model) <ide> - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model) <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> return AlbertConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <ide> elif 'camembert' in pretrained_model_name_or_path: <ide> return CamembertConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <add> elif 'xlm-roberta' in pretrained_model_name_or_path: <add> return XLMRobertaConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <ide> elif 'roberta' in pretrained_model_name_or_path: <ide> return RobertaConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <ide> elif 'bert' in pretrained_model_name_or_path: <ide> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): <ide> return CTRLConfig.from_pretrained(pretrained_model_name_or_path, **kwargs) <ide> raise ValueError("Unrecognized model identifier in {}. Should contains one of " <ide> "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', " <del> "'xlm', 'roberta', 'distilbert', 'camembert', 'ctrl', 'albert'".format(pretrained_model_name_or_path)) <add> "'xlm-roberta', 'xlm', 'roberta', 'distilbert', 'camembert', 'ctrl', 'albert'".format(pretrained_model_name_or_path))
1
Java
Java
add jackson serialization inclusion to factorybean
47d40053a41466bb2728229bc4cf0c73968d0ced
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.java <ide> import java.util.LinkedHashMap; <ide> import java.util.Map; <ide> <add>import org.springframework.beans.FatalBeanException; <add>import org.springframework.beans.factory.FactoryBean; <add>import org.springframework.beans.factory.InitializingBean; <add>import org.springframework.util.Assert; <add> <add>import com.fasterxml.jackson.annotation.JsonInclude; <ide> import com.fasterxml.jackson.core.JsonGenerator; <ide> import com.fasterxml.jackson.core.JsonParser; <ide> import com.fasterxml.jackson.databind.AnnotationIntrospector; <ide> import com.fasterxml.jackson.databind.SerializationFeature; <ide> import com.fasterxml.jackson.databind.module.SimpleModule; <ide> <del>import org.springframework.beans.FatalBeanException; <del>import org.springframework.beans.factory.FactoryBean; <del>import org.springframework.beans.factory.InitializingBean; <del>import org.springframework.util.Assert; <del> <ide> /** <ide> * A {@link FactoryBean} for creating a Jackson 2.x {@link ObjectMapper} with setters <ide> * to enable or disable Jackson features from within XML configuration. <ide> public class Jackson2ObjectMapperFactoryBean implements FactoryBean<ObjectMapper <ide> <ide> private final Map<Class<?>, JsonDeserializer<?>> deserializers = new LinkedHashMap<Class<?>, JsonDeserializer<?>>(); <ide> <add> private JsonInclude.Include serializationInclusion; <add> <ide> <ide> /** <ide> * Set the ObjectMapper instance to use. If not set, the ObjectMapper will <ide> public void setFeaturesToDisable(Object... featuresToDisable) { <ide> } <ide> } <ide> <add> /** <add> * Sets the custom inclusion strategy for serialization. <add> * @see com.fasterxml.jackson.annotation.JsonInclude.Include <add> */ <add> public void setSerializationInclusion(JsonInclude.Include serializationInclusion) { <add> this.serializationInclusion = serializationInclusion; <add> } <ide> <ide> @Override <ide> public void afterPropertiesSet() { <ide> public void afterPropertiesSet() { <ide> for (Object feature : this.features.keySet()) { <ide> configureFeature(feature, this.features.get(feature)); <ide> } <add> <add> if (this.serializationInclusion != null) { <add> this.objectMapper.setSerializationInclusion(this.serializationInclusion); <add> } <ide> } <ide> <ide> @SuppressWarnings("unchecked") <ide><path>spring-web/src/test/java/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBeanTests.java <ide> <ide> package org.springframework.http.converter.json; <ide> <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertFalse; <del>import static org.junit.Assert.assertNotNull; <del>import static org.junit.Assert.assertTrue; <del> <ide> import java.text.SimpleDateFormat; <add>import java.util.Collections; <ide> import java.util.Date; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <ide> import org.junit.Before; <ide> import org.junit.Test; <del>import org.springframework.beans.DirectFieldAccessor; <ide> import org.springframework.beans.FatalBeanException; <del>import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean; <ide> <add>import com.fasterxml.jackson.annotation.JsonInclude; <ide> import com.fasterxml.jackson.core.JsonGenerator; <ide> import com.fasterxml.jackson.core.JsonParser; <ide> import com.fasterxml.jackson.databind.DeserializationFeature; <ide> import com.fasterxml.jackson.databind.JsonDeserializer; <add>import com.fasterxml.jackson.databind.JsonSerializer; <ide> import com.fasterxml.jackson.databind.MapperFeature; <ide> import com.fasterxml.jackson.databind.ObjectMapper; <ide> import com.fasterxml.jackson.databind.SerializationFeature; <ide> import com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig; <ide> import com.fasterxml.jackson.databind.cfg.SerializerFactoryConfig; <add>import com.fasterxml.jackson.databind.deser.BasicDeserializerFactory; <ide> import com.fasterxml.jackson.databind.deser.std.DateDeserializers.DateDeserializer; <ide> import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector; <add>import com.fasterxml.jackson.databind.ser.BasicSerializerFactory; <add>import com.fasterxml.jackson.databind.ser.Serializers; <add>import com.fasterxml.jackson.databind.ser.std.NumberSerializers.NumberSerializer; <ide> import com.fasterxml.jackson.databind.ser.std.StdJdkSerializers.ClassSerializer; <add>import com.fasterxml.jackson.databind.type.SimpleType; <add> <add>import static org.junit.Assert.*; <ide> <ide> /** <ide> * Test cases for {@link Jackson2ObjectMapperFactoryBean} class. <ide> public void setUp() { <ide> } <ide> <ide> @Test <del> public void testSetFeaturesToEnableEmpty() { <del> this.factory.setFeaturesToEnable(new Object[0]); <del> this.factory.setFeaturesToDisable(new Object[0]); <add> public void testSettersWithNullValues() { <add> // Should not crash: <add> factory.setSerializers((JsonSerializer<?>[]) null); <add> factory.setSerializersByType(null); <add> factory.setDeserializersByType(null); <add> factory.setFeaturesToEnable((Object[]) null); <add> factory.setFeaturesToDisable((Object[]) null); <ide> } <ide> <ide> @Test(expected = FatalBeanException.class) <ide> public void testBooleanSetters() { <ide> assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS)); <ide> assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); <ide> assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT)); <add> assertTrue(objectMapper.getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.ALWAYS); <add> } <add> <add> @Test <add> public void testSetNotNullSerializationInclusion() { <add> factory.afterPropertiesSet(); <add> assertTrue(factory.getObject().getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.ALWAYS); <add> <add> factory.setSerializationInclusion(JsonInclude.Include.NON_NULL); <add> factory.afterPropertiesSet(); <add> assertTrue(factory.getObject().getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.NON_NULL); <add> } <add> <add> @Test <add> public void testSetNotDefaultSerializationInclusion() { <add> factory.afterPropertiesSet(); <add> assertTrue(factory.getObject().getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.ALWAYS); <add> <add> factory.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); <add> factory.afterPropertiesSet(); <add> assertTrue(factory.getObject().getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.NON_DEFAULT); <add> } <add> <add> @Test <add> public void testSetNotEmptySerializationInclusion() { <add> factory.afterPropertiesSet(); <add> assertTrue(factory.getObject().getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.ALWAYS); <add> <add> factory.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); <add> factory.afterPropertiesSet(); <add> assertTrue(factory.getObject().getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.NON_EMPTY); <ide> } <ide> <ide> @Test <ide> public void testSimpleSetup() { <ide> assertEquals(ObjectMapper.class, this.factory.getObjectType()); <ide> } <ide> <del> /** <del> * TODO: Remove use of {@link DirectFieldAccessor} with getters. <del> * See <a href="https://github.com/FasterXML/jackson-databind/issues/65">issue#65</a>. <del> */ <ide> private static final SerializerFactoryConfig getSerializerFactoryConfig(ObjectMapper objectMapper) { <del> Object factoryProp = new DirectFieldAccessor(objectMapper).getPropertyValue("_serializerFactory"); <del> return (SerializerFactoryConfig) new DirectFieldAccessor(factoryProp).getPropertyValue("_factoryConfig"); <add> return ((BasicSerializerFactory) objectMapper.getSerializerFactory()).getFactoryConfig(); <ide> } <ide> <ide> private static final DeserializerFactoryConfig getDeserializerFactoryConfig(ObjectMapper objectMapper) { <del> Object contextProp = new DirectFieldAccessor(objectMapper).getPropertyValue("_deserializationContext"); <del> Object factoryProp = new DirectFieldAccessor(contextProp).getPropertyValue("_factory"); <del> return (DeserializerFactoryConfig) new DirectFieldAccessor(factoryProp).getPropertyValue("_factoryConfig"); <add> return ((BasicDeserializerFactory) objectMapper.getDeserializationContext().getFactory()).getFactoryConfig(); <ide> } <ide> <ide> @Test <ide> public void testCompleteSetup() { <ide> Map<Class<?>, JsonDeserializer<?>> deserializers = new HashMap<Class<?>, JsonDeserializer<?>>(); <ide> deserializers.put(Date.class, new DateDeserializer()); <ide> <del> this.factory.setObjectMapper(objectMapper); <del> this.factory.setSerializers(new ClassSerializer()); <del> this.factory.setDeserializersByType(deserializers); <del> this.factory.setAnnotationIntrospector(annotationIntrospector); <add> factory.setObjectMapper(objectMapper); <add> <add> JsonSerializer serializer1 = new ClassSerializer(); <add> JsonSerializer serializer2 = new NumberSerializer(); <ide> <del> this.factory.setFeaturesToEnable( <del> SerializationFeature.FAIL_ON_EMPTY_BEANS, <add> factory.setSerializers(serializer1); <add> factory.setSerializersByType(Collections.<Class<?>, JsonSerializer<?>> singletonMap(Boolean.class, serializer2)); <add> factory.setDeserializersByType(deserializers); <add> factory.setAnnotationIntrospector(annotationIntrospector); <add> <add> this.factory.setFeaturesToEnable(SerializationFeature.FAIL_ON_EMPTY_BEANS, <ide> DeserializationFeature.UNWRAP_ROOT_VALUE, <ide> JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, <ide> JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS); <ide> <del> this.factory.setFeaturesToDisable( <del> MapperFeature.AUTO_DETECT_GETTERS, <add> this.factory.setFeaturesToDisable(MapperFeature.AUTO_DETECT_GETTERS, <ide> MapperFeature.AUTO_DETECT_FIELDS, <ide> JsonParser.Feature.AUTO_CLOSE_SOURCE, <ide> JsonGenerator.Feature.QUOTE_FIELD_NAMES); <ide> <ide> assertFalse(getSerializerFactoryConfig(objectMapper).hasSerializers()); <ide> assertFalse(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); <ide> <add> this.factory.setSerializationInclusion(JsonInclude.Include.NON_NULL); <add> <ide> this.factory.afterPropertiesSet(); <ide> <ide> assertTrue(objectMapper == this.factory.getObject()); <ide> <ide> assertTrue(getSerializerFactoryConfig(objectMapper).hasSerializers()); <ide> assertTrue(getDeserializerFactoryConfig(objectMapper).hasDeserializers()); <ide> <add> Serializers serializers = getSerializerFactoryConfig(objectMapper).serializers().iterator().next(); <add> <add> assertTrue(serializers.findSerializer(null, SimpleType.construct(Class.class), null) == serializer1); <add> assertTrue(serializers.findSerializer(null, SimpleType.construct(Boolean.class), null) == serializer2); <add> assertNull(serializers.findSerializer(null, SimpleType.construct(Number.class), null)); <add> <ide> assertTrue(annotationIntrospector == objectMapper.getSerializationConfig().getAnnotationIntrospector()); <ide> assertTrue(annotationIntrospector == objectMapper.getDeserializationConfig().getAnnotationIntrospector()); <ide> <ide> assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS)); <ide> assertTrue(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); <del> assertTrue(objectMapper.getJsonFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)); <del> assertTrue(objectMapper.getJsonFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)); <add> assertTrue(objectMapper.getFactory().isEnabled(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)); <add> assertTrue(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)); <ide> <ide> assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); <ide> assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS)); <del> assertFalse(objectMapper.getJsonFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); <del> assertFalse(objectMapper.getJsonFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)); <add> assertFalse(objectMapper.getFactory().isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); <add> assertFalse(objectMapper.getFactory().isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)); <add> <add> assertTrue(objectMapper.getSerializationConfig().getSerializationInclusion() == JsonInclude.Include.NON_NULL); <ide> } <ide> }
2
Python
Python
fix a typo in ncf model
f07081474c808c1a7a56c579b5e6670d72dee3d3
<ide><path>official/recommendation/ncf_common.py <ide> def parse_flags(flags_obj): <ide> "beta2": flags_obj.beta2, <ide> "epsilon": flags_obj.epsilon, <ide> "match_mlperf": flags_obj.ml_perf, <del> "epochs_between_evals": FLAGS.epochs_between_evals, <add> "epochs_between_evals": flags_obj.epochs_between_evals, <ide> "keras_use_ctl": flags_obj.keras_use_ctl, <ide> "hr_threshold": flags_obj.hr_threshold, <ide> "stream_files": flags_obj.tpu is not None,
1
Ruby
Ruby
fix failing test
2750f2ee00771109b2b254c8d03c5669d9f5bd59
<ide><path>activesupport/lib/active_support/xml_mini.rb <ide> def rename_key(key, options = {}) <ide> def _dasherize(key) <ide> # $2 must be a non-greedy regex for this to work <ide> left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3] <del> "#{left}#{middle.tr('_', '-')}#{right}" <add> "#{left}#{middle.tr('_ ', '--')}#{right}" <ide> end <ide> <ide> # TODO: Add support for other encodings
1
Text
Text
add entity linking to menu
3195a8f170741d9eef0d3abdc017bc1567f0147d
<ide><path>website/docs/usage/linguistic-features.md <ide> menu: <ide> - ['POS Tagging', 'pos-tagging'] <ide> - ['Dependency Parse', 'dependency-parse'] <ide> - ['Named Entities', 'named-entities'] <add> - ['Entity Linking', 'entity-linking'] <ide> - ['Tokenization', 'tokenization'] <ide> - ['Merging & Splitting', 'retokenization'] <ide> - ['Sentence Segmentation', 'sbd']
1
PHP
PHP
apply suggestions from code review
ab88514fffa030cdcd2cd319a11e530e00be05a1
<ide><path>src/Database/Type/DateTimeType.php <ide> public function toDatabase($value, DriverInterface $driver): ?string <ide> */ <ide> public function setTimezone($timezone) <ide> { <del> deprecationWarning('DateTimeType::setTimezone() is deprecated. use setDatabaseTimezone() instead.'); <add> deprecationWarning('DateTimeType::setTimezone() is deprecated. Use setDatabaseTimezone() instead.'); <ide> <ide> return $this->setDatabaseTimezone($timezone); <ide> } <ide><path>src/Http/Cookie/Cookie.php <ide> public function getValue() <ide> */ <ide> public function getStringValue() <ide> { <del> deprecationWarning('Cookie::getStringValue() is deprecated. Use getStringValue() instead.'); <add> deprecationWarning('Cookie::getStringValue() is deprecated. Use getScalarValue() instead.'); <ide> <ide> return $this->getScalarValue(); <ide> }
2
Text
Text
unify periods in comments in buffer.md
35d83d519c51febb472f98eda71f4a6b82ad81f4
<ide><path>doc/api/buffer.md <ide> const arr = new Uint16Array(2); <ide> arr[0] = 5000; <ide> arr[1] = 4000; <ide> <del>// Copies the contents of `arr` <add>// Copies the contents of `arr`. <ide> const buf1 = Buffer.from(arr); <del>// Shares memory with `arr` <add>// Shares memory with `arr`. <ide> const buf2 = Buffer.from(arr.buffer); <ide> <ide> console.log(buf1); <ide> changes: <ide> Allocates a new `Buffer` using an `array` of octets. <ide> <ide> ```js <del>// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer' <add>// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. <ide> const buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); <ide> ``` <ide> <ide> const arr = new Uint16Array(2); <ide> arr[0] = 5000; <ide> arr[1] = 4000; <ide> <del>// Shares memory with `arr` <add>// Shares memory with `arr`. <ide> const buf = new Buffer(arr.buffer); <ide> <ide> console.log(buf); <ide> // Prints: <Buffer 88 13 a0 0f> <ide> <del>// Changing the original Uint16Array changes the Buffer also <add>// Changing the original Uint16Array changes the Buffer also. <ide> arr[1] = 6000; <ide> <ide> console.log(buf); <ide> initialized*. The contents of the newly created `Buffer` are unknown and <ide> const buf = Buffer.allocUnsafe(10); <ide> <ide> console.log(buf); <del>// Prints: (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32> <add>// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32> <ide> <ide> buf.fill(0); <ide> <ide> to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and <ide> then copying out the relevant bits. <ide> <ide> ```js <del>// Need to keep around a few small chunks of memory <add>// Need to keep around a few small chunks of memory. <ide> const store = []; <ide> <ide> socket.on('readable', () => { <ide> let data; <ide> while (null !== (data = readable.read())) { <del> // Allocate for retained data <add> // Allocate for retained data. <ide> const sb = Buffer.allocUnsafeSlow(10); <ide> <del> // Copy the data into the new allocation <add> // Copy the data into the new allocation. <ide> data.copy(sb, 0, 0, 10); <ide> <ide> store.push(sb); <ide> const arr = [buf1, buf2]; <ide> <ide> console.log(arr.sort(Buffer.compare)); <ide> // Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ] <del>// (This result is equal to: [buf2, buf1]) <add>// (This result is equal to: [buf2, buf1].) <ide> ``` <ide> <ide> ### Class Method: Buffer.concat(list[, totalLength]) <ide> added: v5.10.0 <ide> Allocates a new `Buffer` using an `array` of octets. <ide> <ide> ```js <del>// Creates a new Buffer containing UTF-8 bytes of the string 'buffer' <add>// Creates a new Buffer containing UTF-8 bytes of the string 'buffer'. <ide> const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); <ide> ``` <ide> <ide> const arr = new Uint16Array(2); <ide> arr[0] = 5000; <ide> arr[1] = 4000; <ide> <del>// Shares memory with `arr` <add>// Shares memory with `arr`. <ide> const buf = Buffer.from(arr.buffer); <ide> <ide> console.log(buf); <ide> // Prints: <Buffer 88 13 a0 0f> <ide> <del>// Changing the original Uint16Array changes the Buffer also <add>// Changing the original Uint16Array changes the Buffer also. <ide> arr[1] = 6000; <ide> <ide> console.log(buf); <ide> console.log(buf2.compare(buf3)); <ide> // Prints: 1 <ide> console.log([buf1, buf2, buf3].sort(Buffer.compare)); <ide> // Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ] <del>// (This result is equal to: [buf1, buf3, buf2]) <add>// (This result is equal to: [buf1, buf3, buf2].) <ide> ``` <ide> <ide> The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` <ide> const buf1 = Buffer.allocUnsafe(26); <ide> const buf2 = Buffer.allocUnsafe(26).fill('!'); <ide> <ide> for (let i = 0; i < 26; i++) { <del> // 97 is the decimal ASCII value for 'a' <add> // 97 is the decimal ASCII value for 'a'. <ide> buf1[i] = i + 97; <ide> } <ide> <del>// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2` <add>// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. <ide> buf1.copy(buf2, 8, 16, 20); <ide> <ide> console.log(buf2.toString('ascii', 0, 25)); <ide> console.log(buf2.toString('ascii', 0, 25)); <ide> const buf = Buffer.allocUnsafe(26); <ide> <ide> for (let i = 0; i < 26; i++) { <del> // 97 is the decimal ASCII value for 'a' <add> // 97 is the decimal ASCII value for 'a'. <ide> buf[i] = i + 97; <ide> } <ide> <ide> behavior matches [`String#indexOf()`]. <ide> ```js <ide> const b = Buffer.from('abcdef'); <ide> <del>// Passing a value that's a number, but not a valid byte <del>// Prints: 2, equivalent to searching for 99 or 'c' <add>// Passing a value that's a number, but not a valid byte. <add>// Prints: 2, equivalent to searching for 99 or 'c'. <ide> console.log(b.indexOf(99.9)); <ide> console.log(b.indexOf(256 + 99)); <ide> <del>// Passing a byteOffset that coerces to NaN or 0 <del>// Prints: 1, searching the whole buffer <add>// Passing a byteOffset that coerces to NaN or 0. <add>// Prints: 1, searching the whole buffer. <ide> console.log(b.indexOf('b', undefined)); <ide> console.log(b.indexOf('b', {})); <ide> console.log(b.indexOf('b', null)); <ide> This behavior matches [`String#lastIndexOf()`]. <ide> ```js <ide> const b = Buffer.from('abcdef'); <ide> <del>// Passing a value that's a number, but not a valid byte <del>// Prints: 2, equivalent to searching for 99 or 'c' <add>// Passing a value that's a number, but not a valid byte. <add>// Prints: 2, equivalent to searching for 99 or 'c'. <ide> console.log(b.lastIndexOf(99.9)); <ide> console.log(b.lastIndexOf(256 + 99)); <ide> <del>// Passing a byteOffset that coerces to NaN <del>// Prints: 1, searching the whole buffer <add>// Passing a byteOffset that coerces to NaN. <add>// Prints: 1, searching the whole buffer. <ide> console.log(b.lastIndexOf('b', undefined)); <ide> console.log(b.lastIndexOf('b', {})); <ide> <del>// Passing a byteOffset that coerces to 0 <del>// Prints: -1, equivalent to passing 0 <add>// Passing a byteOffset that coerces to 0. <add>// Prints: -1, equivalent to passing 0. <ide> console.log(b.lastIndexOf('b', null)); <ide> console.log(b.lastIndexOf('b', [])); <ide> ``` <ide> console.log(buf.readDoubleBE(0)); <ide> console.log(buf.readDoubleLE(0)); <ide> // Prints: 5.447603722011605e-270 <ide> console.log(buf.readDoubleLE(1)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.readFloatBE([offset]) <ide> console.log(buf.readFloatBE(0)); <ide> console.log(buf.readFloatLE(0)); <ide> // Prints: 1.539989614439558e-36 <ide> console.log(buf.readFloatLE(1)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.readInt8([offset]) <ide> console.log(buf.readInt8(0)); <ide> console.log(buf.readInt8(1)); <ide> // Prints: 5 <ide> console.log(buf.readInt8(2)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.readInt16BE([offset]) <ide> console.log(buf.readInt16BE(0)); <ide> console.log(buf.readInt16LE(0)); <ide> // Prints: 1280 <ide> console.log(buf.readInt16LE(1)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.readInt32BE([offset]) <ide> console.log(buf.readInt32BE(0)); <ide> console.log(buf.readInt32LE(0)); <ide> // Prints: 83886080 <ide> console.log(buf.readInt32LE(1)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.readIntBE(offset, byteLength) <ide> console.log(buf.readIntLE(0, 6).toString(16)); <ide> console.log(buf.readIntBE(0, 6).toString(16)); <ide> // Prints: 1234567890ab <ide> console.log(buf.readIntBE(1, 6).toString(16)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> console.log(buf.readIntBE(1, 0).toString(16)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.readUInt8([offset]) <ide> console.log(buf.readUInt8(0)); <ide> console.log(buf.readUInt8(1)); <ide> // Prints: 254 <ide> console.log(buf.readUInt8(2)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.readUInt16BE([offset]) <ide> console.log(buf.readUInt16BE(1).toString(16)); <ide> console.log(buf.readUInt16LE(1).toString(16)); <ide> // Prints: 5634 <ide> console.log(buf.readUInt16LE(2).toString(16)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.readUInt32BE([offset]) <ide> console.log(buf.readUInt32BE(0).toString(16)); <ide> console.log(buf.readUInt32LE(0).toString(16)); <ide> // Prints: 78563412 <ide> console.log(buf.readUInt32LE(1).toString(16)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.readUIntBE(offset, byteLength) <ide> console.log(buf.readUIntBE(0, 6).toString(16)); <ide> console.log(buf.readUIntLE(0, 6).toString(16)); <ide> // Prints: ab9078563412 <ide> console.log(buf.readUIntBE(1, 6).toString(16)); <del>// Throws ERR_OUT_OF_RANGE <add>// Throws ERR_OUT_OF_RANGE. <ide> ``` <ide> <ide> ### buf.slice([start[, end]]) <ide> because the allocated memory of the two objects overlap. <ide> const buf1 = Buffer.allocUnsafe(26); <ide> <ide> for (let i = 0; i < 26; i++) { <del> // 97 is the decimal ASCII value for 'a' <add> // 97 is the decimal ASCII value for 'a'. <ide> buf1[i] = i + 97; <ide> } <ide> <ide> const buf = Buffer.from('buffer'); <ide> <ide> console.log(buf.slice(-6, -1).toString()); <ide> // Prints: buffe <del>// (Equivalent to buf.slice(0, 5)) <add>// (Equivalent to buf.slice(0, 5).) <ide> <ide> console.log(buf.slice(-6, -2).toString()); <ide> // Prints: buff <del>// (Equivalent to buf.slice(0, 4)) <add>// (Equivalent to buf.slice(0, 4).) <ide> <ide> console.log(buf.slice(-5, -2).toString()); <ide> // Prints: uff <del>// (Equivalent to buf.slice(1, 4)) <add>// (Equivalent to buf.slice(1, 4).) <ide> ``` <ide> <ide> ### buf.swap16() <ide> console.log(buf1); <ide> const buf2 = Buffer.from([0x1, 0x2, 0x3]); <ide> <ide> buf2.swap16(); <del>// Throws ERR_INVALID_BUFFER_SIZE <add>// Throws ERR_INVALID_BUFFER_SIZE. <ide> ``` <ide> <ide> One convenient use of `buf.swap16()` is to perform a fast in-place conversion <ide> console.log(buf1); <ide> const buf2 = Buffer.from([0x1, 0x2, 0x3]); <ide> <ide> buf2.swap32(); <del>// Throws ERR_INVALID_BUFFER_SIZE <add>// Throws ERR_INVALID_BUFFER_SIZE. <ide> ``` <ide> <ide> ### buf.swap64() <ide> console.log(buf1); <ide> const buf2 = Buffer.from([0x1, 0x2, 0x3]); <ide> <ide> buf2.swap64(); <del>// Throws ERR_INVALID_BUFFER_SIZE <add>// Throws ERR_INVALID_BUFFER_SIZE. <ide> ``` <ide> <ide> Note that JavaScript cannot encode 64-bit integers. This method is intended <ide> as [`buffer.constants.MAX_STRING_LENGTH`][]. <ide> const buf1 = Buffer.allocUnsafe(26); <ide> <ide> for (let i = 0; i < 26; i++) { <del> // 97 is the decimal ASCII value for 'a' <add> // 97 is the decimal ASCII value for 'a'. <ide> buf1[i] = i + 97; <ide> } <ide> <ide> pool for an indeterminate amount of time, it may be appropriate to create an <ide> un-pooled `Buffer` instance using `SlowBuffer` then copy out the relevant bits. <ide> <ide> ```js <del>// Need to keep around a few small chunks of memory <add>// Need to keep around a few small chunks of memory. <ide> const store = []; <ide> <ide> socket.on('readable', () => { <ide> let data; <ide> while (null !== (data = readable.read())) { <del> // Allocate for retained data <add> // Allocate for retained data. <ide> const sb = SlowBuffer(10); <ide> <del> // Copy the data into the new allocation <add> // Copy the data into the new allocation. <ide> data.copy(sb, 0, 0, 10); <ide> <ide> store.push(sb);
1
Ruby
Ruby
determine virtual path from file path
bf9edcb8a3ed0914513141fb287274ec26a6cc67
<ide><path>actionview/lib/action_view/template/resolver.rb <ide> def query(path, details, formats, locals, cache:) <ide> template_paths.map do |template| <ide> unbound_template = <ide> if cache <del> @unbound_templates.compute_if_absent([template, path.virtual]) do <del> build_unbound_template(template, path.virtual) <add> @unbound_templates.compute_if_absent(template) do <add> build_unbound_template(template) <ide> end <ide> else <del> build_unbound_template(template, path.virtual) <add> build_unbound_template(template) <ide> end <ide> <ide> unbound_template.bind_locals(locals) <ide> def source_for_template(template) <ide> Template::Sources::File.new(template) <ide> end <ide> <del> def build_unbound_template(template, virtual_path) <del> details = @path_parser.parse(template) <add> def build_unbound_template(template) <add> details = @path_parser.parse(template.from(@path.size + 1)) <ide> source = source_for_template(template) <ide> <ide> UnboundTemplate.new( <ide> source, <ide> template, <ide> details.handler, <del> virtual_path: virtual_path, <add> virtual_path: details.path.virtual, <ide> locale: details.locale, <ide> format: details.format, <ide> variant: details.variant,
1
Go
Go
simplify readers field
b2b169f13f681cd0d591ccb06d6cfff97933db77
<ide><path>daemon/logger/journald/journald.go <ide> const name = "journald" <ide> type journald struct { <ide> mu sync.Mutex <ide> vars map[string]string // additional variables and values to send to the journal along with the log message <del> readers readerList <add> readers map[*logger.LogWatcher]struct{} <ide> closed bool <ide> } <ide> <del>type readerList struct { <del> readers map[*logger.LogWatcher]*logger.LogWatcher <del>} <del> <ide> func init() { <ide> if err := logger.RegisterLogDriver(name, New); err != nil { <ide> logrus.Fatal(err) <ide> func New(info logger.Info) (logger.Logger, error) { <ide> for k, v := range extraAttrs { <ide> vars[k] = v <ide> } <del> return &journald{vars: vars, readers: readerList{readers: make(map[*logger.LogWatcher]*logger.LogWatcher)}}, nil <add> return &journald{vars: vars, readers: make(map[*logger.LogWatcher]struct{})}, nil <ide> } <ide> <ide> // We don't actually accept any options, but we have to supply a callback for <ide><path>daemon/logger/journald/read.go <ide> import ( <ide> func (s *journald) Close() error { <ide> s.mu.Lock() <ide> s.closed = true <del> for reader := range s.readers.readers { <del> reader.ProducerGone() <add> for r := range s.readers { <add> r.ProducerGone() <add> delete(s.readers, r) <add> <ide> } <ide> s.mu.Unlock() <ide> return nil <ide> drain: <ide> <ide> func (s *journald) followJournal(logWatcher *logger.LogWatcher, j *C.sd_journal, pfd [2]C.int, cursor *C.char, untilUnixMicro uint64) *C.char { <ide> s.mu.Lock() <del> s.readers.readers[logWatcher] = logWatcher <add> s.readers[logWatcher] = struct{}{} <ide> if s.closed { <ide> // the journald Logger is closed, presumably because the container has been <ide> // reset. So we shouldn't follow, because we'll never be woken up. But we <ide> func (s *journald) followJournal(logWatcher *logger.LogWatcher, j *C.sd_journal, <ide> // Clean up. <ide> C.close(pfd[0]) <ide> s.mu.Lock() <del> delete(s.readers.readers, logWatcher) <add> delete(s.readers, logWatcher) <ide> s.mu.Unlock() <ide> close(logWatcher.Msg) <ide> newCursor <- cursor
2
Python
Python
move datasets to npz/json
b0500764a8a451882262328c0f1676402fb0a783
<ide><path>keras/datasets/imdb.py <ide> from __future__ import absolute_import <del>from six.moves import cPickle <del>import gzip <ide> from ..utils.data_utils import get_file <ide> from six.moves import zip <ide> import numpy as np <del>import sys <add>import json <ide> <ide> <del>def load_data(path='imdb_full.pkl', num_words=None, skip_top=0, <add>def load_data(path='imdb.npz', num_words=None, skip_top=0, <ide> maxlen=None, seed=113, <ide> start_char=1, oov_char=2, index_from=3): <ide> """Loads the IMDB dataset. <ide> def load_data(path='imdb_full.pkl', num_words=None, skip_top=0, <ide> have simply been skipped. <ide> """ <ide> path = get_file(path, <del> origin='https://s3.amazonaws.com/text-datasets/imdb_full.pkl', <del> md5_hash='d091312047c43cf9e4e38fef92437263') <del> <del> if path.endswith('.gz'): <del> f = gzip.open(path, 'rb') <del> else: <del> f = open(path, 'rb') <del> <del> (x_train, labels_train), (x_test, labels_test) = cPickle.load(f) <add> origin='https://s3.amazonaws.com/text-datasets/imdb.npz') <add> f = np.load(path) <add> x_train = f['x_train'] <add> labels_train = f['y_train'] <add> x_test = f['x_test'] <add> labels_test = f['y_test'] <ide> f.close() <ide> <ide> np.random.seed(seed) <ide> def load_data(path='imdb_full.pkl', num_words=None, skip_top=0, <ide> np.random.seed(seed * 2) <ide> np.random.shuffle(labels_test) <ide> <del> xs = x_train + x_test <del> labels = labels_train + labels_test <add> xs = np.concatenate([x_train, x_test]) <add> labels = np.concatenate([labels_train, labels_test]) <ide> <ide> if start_char is not None: <ide> xs = [[start_char] + [w + index_from for w in x] for x in xs] <ide> def load_data(path='imdb_full.pkl', num_words=None, skip_top=0, <ide> return (x_train, y_train), (x_test, y_test) <ide> <ide> <del>def get_word_index(path='imdb_word_index.pkl'): <add>def get_word_index(path='imdb_word_index.json'): <ide> """Retrieves the dictionary mapping word indices back to words. <ide> <ide> # Arguments <ide> def get_word_index(path='imdb_word_index.pkl'): <ide> The word index dictionary. <ide> """ <ide> path = get_file(path, <del> origin='https://s3.amazonaws.com/text-datasets/imdb_word_index.pkl', <del> md5_hash='72d94b01291be4ff843198d3b0e1e4d7') <del> f = open(path, 'rb') <del> <del> if sys.version_info < (3,): <del> data = cPickle.load(f) <del> else: <del> data = cPickle.load(f, encoding='latin1') <del> <add> origin='https://s3.amazonaws.com/text-datasets/imdb_word_index.json') <add> f = open(path) <add> data = json.load(f) <ide> f.close() <ide> return data <ide><path>keras/datasets/mnist.py <del>import gzip <ide> from ..utils.data_utils import get_file <del>from six.moves import cPickle <del>import sys <add>import numpy as np <ide> <ide> <del>def load_data(path='mnist.pkl.gz'): <add>def load_data(path='mnist.npz'): <ide> """Loads the MNIST dataset. <ide> <ide> # Arguments <ide> def load_data(path='mnist.pkl.gz'): <ide> # Returns <ide> Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. <ide> """ <del> path = get_file(path, origin='https://s3.amazonaws.com/img-datasets/mnist.pkl.gz') <del> <del> if path.endswith('.gz'): <del> f = gzip.open(path, 'rb') <del> else: <del> f = open(path, 'rb') <del> <del> if sys.version_info < (3,): <del> data = cPickle.load(f) <del> else: <del> data = cPickle.load(f, encoding='bytes') <del> <add> path = get_file(path, origin='https://s3.amazonaws.com/img-datasets/mnist.npz') <add> f = np.load(path) <add> x_train = f['x_train'] <add> y_train = f['y_train'] <add> x_test = f['x_test'] <add> y_test = f['y_test'] <ide> f.close() <del> return data # (x_train, y_train), (x_test, y_test) <add> return (x_train, y_train), (x_test, y_test) <ide><path>keras/datasets/reuters.py <ide> # -*- coding: utf-8 -*- <ide> from __future__ import absolute_import <ide> from ..utils.data_utils import get_file <del>from six.moves import cPickle <ide> from six.moves import zip <ide> import numpy as np <del>import sys <add>import json <ide> <ide> <del>def load_data(path='reuters.pkl', num_words=None, skip_top=0, <add>def load_data(path='reuters.npz', num_words=None, skip_top=0, <ide> maxlen=None, test_split=0.2, seed=113, <ide> start_char=1, oov_char=2, index_from=3): <ide> """Loads the Reuters newswire classification dataset. <ide> def load_data(path='reuters.pkl', num_words=None, skip_top=0, <ide> Words that were not seen in the trining set but are in the test set <ide> have simply been skipped. <ide> """ <del> <del> path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/reuters.pkl') <del> f = open(path, 'rb') <del> xs, labels = cPickle.load(f) <del> f.close() <add> path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/reuters.npz') <add> npzfile = np.load(path) <add> xs = npzfile['x'] <add> labels = npzfile['y'] <add> npzfile.close() <ide> <ide> np.random.seed(seed) <ide> np.random.shuffle(xs) <ide> def load_data(path='reuters.pkl', num_words=None, skip_top=0, <ide> new_xs.append(nx) <ide> xs = new_xs <ide> <del> x_train = xs[:int(len(xs) * (1 - test_split))] <del> y_train = labels[:int(len(xs) * (1 - test_split))] <add> x_train = np.array(xs[:int(len(xs) * (1 - test_split))]) <add> y_train = np.array(labels[:int(len(xs) * (1 - test_split))]) <ide> <del> x_test = xs[int(len(xs) * (1 - test_split)):] <del> y_test = labels[int(len(xs) * (1 - test_split)):] <add> x_test = np.array(xs[int(len(xs) * (1 - test_split)):]) <add> y_test = np.array(labels[int(len(xs) * (1 - test_split)):]) <ide> <ide> return (x_train, y_train), (x_test, y_test) <ide> <ide> <del>def get_word_index(path='reuters_word_index.pkl'): <add>def get_word_index(path='reuters_word_index.json'): <ide> """Retrieves the dictionary mapping word indices back to words. <ide> <ide> # Arguments <ide> def get_word_index(path='reuters_word_index.pkl'): <ide> # Returns <ide> The word index dictionary. <ide> """ <del> path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/reuters_word_index.pkl') <del> f = open(path, 'rb') <del> <del> if sys.version_info < (3,): <del> data = cPickle.load(f) <del> else: <del> data = cPickle.load(f, encoding='latin1') <del> <add> path = get_file(path, origin='https://s3.amazonaws.com/text-datasets/reuters_word_index.json') <add> f = open(path) <add> data = json.load(f) <ide> f.close() <ide> return data <ide><path>tests/keras/datasets/test_datasets.py <ide> import pytest <ide> import time <ide> import random <del>from keras.datasets import cifar10, cifar100, reuters, imdb, mnist <add>from keras.datasets import cifar10 <add>from keras.datasets import cifar100 <add>from keras.datasets import reuters <add>from keras.datasets import imdb <add>from keras.datasets import mnist <add>from keras.datasets import boston_housing <ide> <ide> <ide> def test_cifar(): <ide> # only run data download tests 20% of the time <ide> # to speed up frequent testing <ide> random.seed(time.time()) <ide> if random.random() > 0.8: <del> (X_train, y_train), (X_test, y_test) = cifar10.load_data() <del> (X_train, y_train), (X_test, y_test) = cifar100.load_data('fine') <del> (X_train, y_train), (X_test, y_test) = cifar100.load_data('coarse') <add> (x_train, y_train), (x_test, y_test) = cifar10.load_data() <add> assert len(x_train) == len(y_train) == 50000 <add> assert len(x_test) == len(y_test) == 10000 <add> (x_train, y_train), (x_test, y_test) = cifar100.load_data('fine') <add> assert len(x_train) == len(y_train) == 50000 <add> assert len(x_test) == len(y_test) == 10000 <add> (x_train, y_train), (x_test, y_test) = cifar100.load_data('coarse') <add> assert len(x_train) == len(y_train) == 50000 <add> assert len(x_test) == len(y_test) == 10000 <ide> <ide> <ide> def test_reuters(): <ide> # only run data download tests 20% of the time <ide> # to speed up frequent testing <ide> random.seed(time.time()) <ide> if random.random() > 0.8: <del> (X_train, y_train), (X_test, y_test) = reuters.load_data() <del> (X_train, y_train), (X_test, y_test) = reuters.load_data(maxlen=10) <add> (x_train, y_train), (x_test, y_test) = reuters.load_data() <add> assert len(x_train) == len(y_train) <add> assert len(x_test) == len(y_test) <add> assert len(x_train) + len(x_test) == 11228 <add> (x_train, y_train), (x_test, y_test) = reuters.load_data(maxlen=10) <add> assert len(x_train) == len(y_train) <add> assert len(x_test) == len(y_test) <add> word_index = reuters.get_word_index() <add> assert isinstance(word_index, dict) <ide> <ide> <ide> def test_mnist(): <ide> # only run data download tests 20% of the time <ide> # to speed up frequent testing <ide> random.seed(time.time()) <ide> if random.random() > 0.8: <del> (X_train, y_train), (X_test, y_test) = mnist.load_data() <add> (x_train, y_train), (x_test, y_test) = mnist.load_data() <add> assert len(x_train) == len(y_train) == 60000 <add> assert len(x_test) == len(y_test) == 10000 <ide> <ide> <ide> def test_imdb(): <ide> # only run data download tests 20% of the time <ide> # to speed up frequent testing <ide> random.seed(time.time()) <ide> if random.random() > 0.8: <del> (X_train, y_train), (X_test, y_test) = imdb.load_data() <del> (X_train, y_train), (X_test, y_test) = imdb.load_data(maxlen=40) <add> (x_train, y_train), (x_test, y_test) = imdb.load_data() <add> (x_train, y_train), (x_test, y_test) = imdb.load_data(maxlen=40) <add> assert len(x_train) == len(y_train) <add> assert len(x_test) == len(y_test) <add> word_index = imdb.get_word_index() <add> assert isinstance(word_index, dict) <add> <add> <add>def test_boston_housing(): <add> # only run data download tests 20% of the time <add> # to speed up frequent testing <add> random.seed(time.time()) <add> if random.random() > 0.8: <add> (x_train, y_train), (x_test, y_test) = boston_housing.load_data() <add> assert len(x_train) == len(y_train) <add> assert len(x_test) == len(y_test) <ide> <ide> <ide> if __name__ == '__main__':
4
Javascript
Javascript
fix lint error
dfe647d914a649d85479d7ddec8ccd791cd0e65b
<ide><path>src/text-editor-element.js <ide> class TextEditorElement extends HTMLElement { <ide> } <ide> <ide> updateModelFromAttributes () { <del> const props = { <del> mini: this.hasAttribute('mini'), <del> } <add> const props = {mini: this.hasAttribute('mini')} <ide> if (this.hasAttribute('placeholder-text')) props.placeholderText = this.getAttribute('placeholder-text') <ide> if (this.hasAttribute('gutter-hidden')) props.lineNumberGutterVisible = false <ide>
1
Text
Text
remove superfluous word from crypto doc
0aab8ff602d85feb8e92e80e7cddcbbd49597219
<ide><path>doc/api/crypto.md <ide> added: v0.1.94 <ide> --> <ide> - `outputEncoding` {string} <ide> - Returns: {Buffer | string} Any remaining enciphered contents. <del> If `outputEncoding` parameter is one of `'latin1'`, `'base64'` or `'hex'`, <del> a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] <del> is returned. <add> If `outputEncoding` is one of `'latin1'`, `'base64'` or `'hex'`, a string is <add> returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned. <ide> <ide> Once the `cipher.final()` method has been called, the `Cipher` object can no <ide> longer be used to encrypt data. Attempts to call `cipher.final()` more than <ide> added: v0.1.94 <ide> --> <ide> - `outputEncoding` {string} <ide> - Returns: {Buffer | string} Any remaining deciphered contents. <del> If `outputEncoding` parameter is one of `'latin1'`, `'ascii'` or `'utf8'`, <del> a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] <del> is returned. <add> If `outputEncoding` is one of `'latin1'`, `'ascii'` or `'utf8'`, a string is <add> returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned. <ide> <ide> Once the `decipher.final()` method has been called, the `Decipher` object can <ide> no longer be used to decrypt data. Attempts to call `decipher.final()` more
1
Javascript
Javascript
remove duplicate parser unset
54e112dd61a5af6622f66cabca67474ae93113eb
<ide><path>lib/_http_common.js <ide> function freeParser(parser, req, socket) { <ide> if (parser._consumed) <ide> parser.unconsume(); <ide> parser._consumed = false; <del> if (parser.socket) <del> parser.socket.parser = null; <ide> parser.socket = null; <ide> parser.incoming = null; <ide> parser.outgoing = null; <ide><path>lib/_http_server.js <ide> function onParserExecuteCommon(server, socket, parser, state, ret, d) { <ide> socket.removeListener('error', socketOnError); <ide> unconsume(parser, socket); <ide> parser.finish(); <del> freeParser(parser, req, null); <add> freeParser(parser, req, socket); <ide> parser = null; <ide> <ide> var eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade';
2
Javascript
Javascript
fix race in test-http-curl-chunk-problem
1009130495b4c52d00deed0ee2292039c3f36310
<ide><path>test/parallel/test-http-curl-chunk-problem.js <ide> var server = http.createServer(function(req, res) { <ide> res.write(data); <ide> }); <ide> <add> cat.stdout.on('end', function onStdoutEnd() { <add> res.end(); <add> }); <add> <ide> // End the response on exit (and log errors) <ide> cat.on('exit', function(code) { <ide> if (code !== 0) { <ide> console.error('subprocess exited with code ' + code); <ide> process.exit(1); <ide> } <del> res.end(); <ide> }); <ide> <ide> });
1
PHP
PHP
add space before operators
7439dbc2139f5a17b5ea49570397828bcb96c6f7
<ide><path>src/Collection/CollectionTrait.php <ide> public function unfold(callable $transformer = null) <ide> public function through(callable $handler) <ide> { <ide> $result = $handler($this); <del> return $result instanceof CollectionInterface ? $result: new Collection($result); <add> return $result instanceof CollectionInterface ? $result : new Collection($result); <ide> } <ide> <ide> /** <ide><path>src/ORM/Behavior/TreeBehavior.php <ide> protected function _sync($shift, $dir, $conditions, $mark = false) <ide> <ide> $inverse = clone $exp; <ide> $movement = $mark ? <del> $inverse->add($movement)->tieWith('*')->add('-1'): <add> $inverse->add($movement)->tieWith('*')->add('-1') : <ide> $movement; <ide> <ide> $where = clone $exp;
2
Javascript
Javascript
add a support comment for safari 8
d24275372624bac897c4131fd1507a58c09a1483
<ide><path>src/core/support.js <ide> define([ <ide> "../var/support" <ide> ], function( document, support ) { <ide> <add>// Support: Safari 8+ <add>// In Safari 8 documents created via document.implementation.createHTMLDocument <add>// collapse sibling forms: the second one becomes a child of the first one. <add>// Because of that, this security measure has to be disabled in Safari 8. <add>// https://bugs.webkit.org/show_bug.cgi?id=137337 <ide> support.createHTMLDocument = (function() { <ide> var body = document.implementation.createHTMLDocument( "" ).body; <ide> body.innerHTML = "<form></form><form></form>";
1
Javascript
Javascript
apply some feedback
b9a40bb59e0684134a7370ac0ec8455de3f6327e
<ide><path>packages/ember-testing/tests/ext/rsvp_test.js <ide> moduleFor('ember-testing RSVP', class extends AbstractTestCase { <ide> setAdapter({ <ide> asyncStart() { <ide> asyncStarted++; <del> QUnit.stop(); <ide> }, <ide> asyncEnd() { <ide> asyncEnded++; <del> QUnit.start(); <ide> } <ide> }); <ide> } <ide> moduleFor('ember-testing RSVP', class extends AbstractTestCase { <ide> } <ide> <ide> ['@test given `Ember.testing = true`, correctly informs the test suite about async steps'](assert) { <add> let done = assert.async(); <ide> assert.expect(19); <ide> <ide> assert.ok(!run.currentRunLoop, 'expect no run-loop'); <ide> moduleFor('ember-testing RSVP', class extends AbstractTestCase { <ide> assert.equal(asyncStarted, 0); <ide> assert.equal(asyncEnded, 0); <ide> <del> let user = RSVP.Promise.resolve({ <del> name: 'tomster' <del> }); <add> let user = RSVP.Promise.resolve({ name: 'tomster' }); <ide> <ide> assert.equal(asyncStarted, 0); <ide> assert.equal(asyncEnded, 0); <ide> moduleFor('ember-testing RSVP', class extends AbstractTestCase { <ide> assert.equal(asyncEnded, 1); <ide> <ide> return new RSVP.Promise(function(resolve) { <del> QUnit.stop(); // raw async, we must inform the test framework manually <ide> setTimeout(function() { <del> QUnit.start(); // raw async, we must inform the test framework manually <del> <ide> assert.equal(asyncStarted, 1); <ide> assert.equal(asyncEnded, 1); <ide> <del> resolve({ <del> name: 'async tomster' <del> }); <add> resolve({ name: 'async tomster' }); <ide> <ide> assert.equal(asyncStarted, 2); <ide> assert.equal(asyncEnded, 1); <ide> moduleFor('ember-testing RSVP', class extends AbstractTestCase { <ide> assert.equal(user.name, 'async tomster'); <ide> assert.equal(asyncStarted, 2); <ide> assert.equal(asyncEnded, 2); <add> done(); <ide> }); <ide> } <del> <ide> }); <ide> <ide>
1
Ruby
Ruby
add accessor for homebrew_cc
930cf4c768c017b25f3bee5d96cde4be384b74dc
<ide><path>Library/Homebrew/extend/ENV/shared.rb <ide> def compiler <ide> :llvm <ide> elsif ARGV.include? '--use-clang' <ide> :clang <del> elsif self['HOMEBREW_CC'] <del> cc = COMPILER_ALIASES.fetch(self['HOMEBREW_CC'], self['HOMEBREW_CC']) <add> elsif homebrew_cc <add> cc = COMPILER_ALIASES.fetch(homebrew_cc, homebrew_cc) <ide> COMPILER_SYMBOL_MAP.fetch(cc) { MacOS.default_compiler } <ide> else <ide> MacOS.default_compiler <ide> def cc= val <ide> def cxx= val <ide> self["CXX"] = self["OBJCXX"] = val.to_s <ide> end <add> <add> def homebrew_cc <add> self["HOMEBREW_CC"] <add> end <ide> end <ide><path>Library/Homebrew/extend/ENV/super.rb <ide> def setup_build_environment(formula=nil) <ide> # s - apply fix for sed's Unicode support <ide> # a - apply fix for apr-1-config path <ide> <del> warn_about_non_apple_gcc($1) if self["HOMEBREW_CC"] =~ GNU_GCC_REGEXP <add> warn_about_non_apple_gcc($1) if homebrew_cc =~ GNU_GCC_REGEXP <ide> end <ide> <ide> private <ide> def determine_path <ide> <ide> # Homebrew's apple-gcc42 will be outside the PATH in superenv, <ide> # so xcrun may not be able to find it <del> case self["HOMEBREW_CC"] <add> case homebrew_cc <ide> when "gcc-4.2" <ide> begin <ide> apple_gcc42 = Formulary.factory('apple-gcc42') <ide> def permit_arch_flags <ide> end <ide> <ide> def cxx11 <del> case self["HOMEBREW_CC"] <add> case homebrew_cc <ide> when "clang" <ide> append 'HOMEBREW_CCCFG', "x", '' <ide> append 'HOMEBREW_CCCFG', "g", '' <ide> when /gcc-4\.(8|9)/ <ide> append 'HOMEBREW_CCCFG', "x", '' <ide> else <del> raise "The selected compiler doesn't support C++11: #{self['HOMEBREW_CC']}" <add> raise "The selected compiler doesn't support C++11: #{homebrew_cc}" <ide> end <ide> end <ide>
2
Python
Python
unify reductions in fromnumeric.py
b344da928f06d867b0a4f41746c1bcb759a2fd8f
<ide><path>numpy/core/fromnumeric.py <ide> from .numeric import asarray, array, asanyarray, concatenate <ide> from . import _methods <ide> <del> <ide> _dt_ = nt.sctype2char <ide> <ide> # functions that are methods <ide> 'rank', 'ravel', 'repeat', 'reshape', 'resize', 'round_', <ide> 'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'squeeze', <ide> 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var', <del> ] <add>] <ide> <ide> _gentype = types.GeneratorType <ide> # save away Python sum <ide> def _wrapfunc(obj, method, *args, **kwds): <ide> return _wrapit(obj, method, *args, **kwds) <ide> <ide> <add>def _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs): <add> passkwargs = {} <add> for k, v in kwargs.items(): <add> if v is not np._NoValue: <add> passkwargs[k] = v <add> <add> if type(obj) is not mu.ndarray: <add> try: <add> reduction = getattr(obj, method) <add> except AttributeError: <add> pass <add> else: <add> # This branch is needed for reductions like any which don't <add> # support a dtype. <add> if dtype is not None: <add> return reduction(axis=axis, dtype=dtype, out=out, **passkwargs) <add> else: <add> return reduction(axis=axis, out=out, **passkwargs) <add> <add> return ufunc.reduce(obj, axis, dtype, out, **passkwargs) <add> <add> <ide> def take(a, indices, axis=None, out=None, mode='raise'): <ide> """ <ide> Take elements from an array along an axis. <ide> def resize(a, new_shape): <ide> n_copies = n_copies + 1 <ide> extra = Na - extra <ide> <del> a = concatenate((a,)*n_copies) <add> a = concatenate((a,) * n_copies) <ide> if extra > 0: <ide> a = a[:-extra] <ide> <ide> def sum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue): <ide> -128 <ide> <ide> """ <del> kwargs = {} <del> if keepdims is not np._NoValue: <del> kwargs['keepdims'] = keepdims <ide> if isinstance(a, _gentype): <ide> res = _sum_(a) <ide> if out is not None: <ide> out[...] = res <ide> return out <ide> return res <del> if type(a) is not mu.ndarray: <del> try: <del> sum = a.sum <del> except AttributeError: <del> pass <del> else: <del> return sum(axis=axis, dtype=dtype, out=out, **kwargs) <del> return _methods._sum(a, axis=axis, dtype=dtype, <del> out=out, **kwargs) <ide> <add> return _wrapreduction(a, np.add, 'sum', axis, dtype, out, keepdims=keepdims) <ide> <ide> <ide> def any(a, axis=None, out=None, keepdims=np._NoValue): <ide> def any(a, axis=None, out=None, keepdims=np._NoValue): <ide> (191614240, 191614240) <ide> <ide> """ <del> arr = asanyarray(a) <del> kwargs = {} <del> if keepdims is not np._NoValue: <del> kwargs['keepdims'] = keepdims <del> return arr.any(axis=axis, out=out, **kwargs) <add> return _wrapreduction(a, np.logical_or, 'any', axis, None, out, keepdims=keepdims) <ide> <ide> <ide> def all(a, axis=None, out=None, keepdims=np._NoValue): <ide> def all(a, axis=None, out=None, keepdims=np._NoValue): <ide> (28293632, 28293632, array([ True])) <ide> <ide> """ <del> arr = asanyarray(a) <del> kwargs = {} <del> if keepdims is not np._NoValue: <del> kwargs['keepdims'] = keepdims <del> return arr.all(axis=axis, out=out, **kwargs) <add> return _wrapreduction(a, np.logical_and, 'all', axis, None, out, keepdims=keepdims) <ide> <ide> <ide> def cumsum(a, axis=None, dtype=None, out=None): <ide> def amax(a, axis=None, out=None, keepdims=np._NoValue): <ide> 4.0 <ide> <ide> """ <del> kwargs = {} <del> if keepdims is not np._NoValue: <del> kwargs['keepdims'] = keepdims <del> <del> if type(a) is not mu.ndarray: <del> try: <del> amax = a.max <del> except AttributeError: <del> pass <del> else: <del> return amax(axis=axis, out=out, **kwargs) <del> <del> return _methods._amax(a, axis=axis, <del> out=out, **kwargs) <add> return _wrapreduction(a, np.maximum, 'max', axis, None, out, keepdims=keepdims) <ide> <ide> <ide> def amin(a, axis=None, out=None, keepdims=np._NoValue): <ide> def amin(a, axis=None, out=None, keepdims=np._NoValue): <ide> 0.0 <ide> <ide> """ <del> kwargs = {} <del> if keepdims is not np._NoValue: <del> kwargs['keepdims'] = keepdims <del> if type(a) is not mu.ndarray: <del> try: <del> amin = a.min <del> except AttributeError: <del> pass <del> else: <del> return amin(axis=axis, out=out, **kwargs) <del> <del> return _methods._amin(a, axis=axis, <del> out=out, **kwargs) <add> return _wrapreduction(a, np.minimum, 'min', axis, None, out, keepdims=keepdims) <ide> <ide> <ide> def alen(a): <ide> def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue): <ide> True <ide> <ide> """ <del> kwargs = {} <del> if keepdims is not np._NoValue: <del> kwargs['keepdims'] = keepdims <del> if type(a) is not mu.ndarray: <del> try: <del> prod = a.prod <del> except AttributeError: <del> pass <del> else: <del> return prod(axis=axis, dtype=dtype, out=out, **kwargs) <del> <del> return _methods._prod(a, axis=axis, dtype=dtype, <del> out=out, **kwargs) <add> return _wrapreduction(a, np.multiply, 'prod', axis, dtype, out, keepdims=keepdims) <ide> <ide> <ide> def cumprod(a, axis=None, dtype=None, out=None):
1
Ruby
Ruby
add singleton in nullmutationtracker class
c08c4681adc8bf68ed284c1f5ac8c41e8d0987df
<ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb <ide> def store_original_attributes <ide> end <ide> <ide> def previous_mutation_tracker <del> @previous_mutation_tracker ||= NullMutationTracker.new <add> @previous_mutation_tracker ||= NullMutationTracker.instance <ide> end <ide> <ide> def cache_changed_attributes <ide><path>activerecord/lib/active_record/attribute_mutation_tracker.rb <ide> def attr_names <ide> end <ide> <ide> class NullMutationTracker # :nodoc: <add> include Singleton <add> <ide> def changed_values <ide> {} <ide> end
2
Python
Python
remove extraeneous spaces
b43418ade653256a5918cbba72f9c478eb33691e
<ide><path>research/object_detection/models/faster_rcnn_resnet_v1_fpn_keras_feature_extractor.py <ide> def get_proposal_feature_extractor_model(self, name=None): <ide> self._conv_hyperparams.build_activation_layer( <ide> name=layer_name)) <ide> self._coarse_feature_layers.append(layers) <del> <add> <ide> feature_maps = [] <ide> for level in range(self._fpn_min_level, self._base_fpn_max_level + 1): <ide> feature_maps.append(fpn_features['top_down_block{}'.format(level-1)])
1
Javascript
Javascript
remove janky bypass of npm version check
67843c8ebd19f537266e44cfc6af4a923317ebbf
<ide><path>script/utils/verify-requirements.js <ide> function verifyNpm(cb) { <ide> var versionArray = npmVersion.split('.'); <ide> var npmMajorVersion = +versionArray[0] || 0; <ide> var npmMinorVersion = +versionArray[1] || 0; <del> if (npmMajorVersion === 1 && npmMinorVersion < 4 && !process.env.JANKY_SHA1) <del> cb("npm v1.4+ is required to build Atom. Version " + npmVersion + " was detected"); <add> if (npmMajorVersion === 1 && npmMinorVersion < 4) <add> cb("npm v1.4+ is required to build Atom. Version " + npmVersion + " was detected."); <ide> else <ide> cb(null, "npm: v" + npmVersion); <ide> });
1
Go
Go
move version out of server
7894a70f8b2dcb329178978066d825dc41ec6239
<ide><path>builtins/builtins.go <ide> package builtins <ide> <ide> import ( <del> api "github.com/dotcloud/docker/api/server" <add> "runtime" <add> <add> "github.com/dotcloud/docker/api" <add> apiserver "github.com/dotcloud/docker/api/server" <ide> "github.com/dotcloud/docker/daemon/networkdriver/bridge" <add> "github.com/dotcloud/docker/dockerversion" <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/registry" <ide> "github.com/dotcloud/docker/server" <add> "github.com/dotcloud/docker/utils" <ide> ) <ide> <ide> func Register(eng *engine.Engine) error { <ide> func Register(eng *engine.Engine) error { <ide> if err := remote(eng); err != nil { <ide> return err <ide> } <add> if err := eng.Register("version", dockerVersion); err != nil { <add> return err <add> } <ide> return registry.NewService().Install(eng) <ide> } <ide> <ide> // remote: a RESTful api for cross-docker communication <ide> func remote(eng *engine.Engine) error { <del> return eng.Register("serveapi", api.ServeApi) <add> return eng.Register("serveapi", apiserver.ServeApi) <ide> } <ide> <ide> // daemon: a default execution and storage backend for Docker on Linux, <ide> func daemon(eng *engine.Engine) error { <ide> } <ide> return eng.Register("init_networkdriver", bridge.InitDriver) <ide> } <add> <add>// builtins jobs independent of any subsystem <add>func dockerVersion(job *engine.Job) engine.Status { <add> v := &engine.Env{} <add> v.Set("Version", dockerversion.VERSION) <add> v.SetJson("ApiVersion", api.APIVERSION) <add> v.Set("GitCommit", dockerversion.GITCOMMIT) <add> v.Set("GoVersion", runtime.Version()) <add> v.Set("Os", runtime.GOOS) <add> v.Set("Arch", runtime.GOARCH) <add> if kernelVersion, err := utils.GetKernelVersion(); err == nil { <add> v.Set("KernelVersion", kernelVersion.String()) <add> } <add> if _, err := v.WriteTo(job.Stdout); err != nil { <add> return job.Error(err) <add> } <add> return engine.StatusOK <add>} <ide><path>server/server.go <ide> import ( <ide> "syscall" <ide> "time" <ide> <del> "github.com/dotcloud/docker/api" <ide> "github.com/dotcloud/docker/archive" <ide> "github.com/dotcloud/docker/daemon" <ide> "github.com/dotcloud/docker/daemonconfig" <ide> func InitServer(job *engine.Job) engine.Status { <ide> "logs": srv.ContainerLogs, <ide> "changes": srv.ContainerChanges, <ide> "top": srv.ContainerTop, <del> "version": srv.DockerVersion, <ide> "load": srv.ImageLoad, <ide> "build": srv.Build, <ide> "pull": srv.ImagePull, <ide> func (srv *Server) DockerInfo(job *engine.Job) engine.Status { <ide> return engine.StatusOK <ide> } <ide> <del>func (srv *Server) DockerVersion(job *engine.Job) engine.Status { <del> v := &engine.Env{} <del> v.Set("Version", dockerversion.VERSION) <del> v.SetJson("ApiVersion", api.APIVERSION) <del> v.Set("GitCommit", dockerversion.GITCOMMIT) <del> v.Set("GoVersion", runtime.Version()) <del> v.Set("Os", runtime.GOOS) <del> v.Set("Arch", runtime.GOARCH) <del> if kernelVersion, err := utils.GetKernelVersion(); err == nil { <del> v.Set("KernelVersion", kernelVersion.String()) <del> } <del> if _, err := v.WriteTo(job.Stdout); err != nil { <del> return job.Error(err) <del> } <del> return engine.StatusOK <del>} <del> <ide> func (srv *Server) ImageHistory(job *engine.Job) engine.Status { <ide> if n := len(job.Args); n != 1 { <ide> return job.Errorf("Usage: %s IMAGE", job.Name)
2
Ruby
Ruby
fix tests on 1.9.2
31906eecdf7bffc2203379c5d40f1bb77fb35858
<ide><path>actionpack/lib/action_dispatch/http/mime_type.rb <ide> def parse_data_with_trailing_star(input) <ide> # <ide> # Usage: <ide> # <del> # Mime::Type.unregister("text/x-mobile", :mobile) <del> def unregister(string, symbol) <del> EXTENSION_LOOKUP.delete(symbol.to_s) <del> LOOKUP.delete(string) <del> symbol = symbol.to_s.upcase.intern <del> Mime.module_eval { remove_const(symbol) if const_defined?(symbol) } <add> # Mime::Type.unregister(:mobile) <add> def unregister(symbol) <add> symbol = symbol.to_s.upcase <add> mime = Mime.const_get(symbol) <add> Mime.instance_eval { remove_const(symbol) } <add> <add> SET.delete_if { |v| v.eql?(mime) } <add> LOOKUP.delete_if { |k,v| v.eql?(mime) } <add> EXTENSION_LOOKUP.delete_if { |k,v| v.eql?(mime) } <ide> end <ide> end <ide> <ide><path>actionpack/test/controller/mime_responds_test.rb <ide> def setup <ide> <ide> def teardown <ide> super <del> Mime::Type.unregister('text/x-mobile', :iphone) <del> Mime::Type.unregister('text/iphone', :mobile) <add> Mime::Type.unregister(:iphone) <add> Mime::Type.unregister(:mobile) <ide> end <ide> <ide> def test_html <ide> class RespondWithControllerTest < ActionController::TestCase <ide> def setup <ide> super <ide> @request.host = "www.example.com" <add> Mime::Type.register_alias('text/html', :iphone) <add> Mime::Type.register('text/x-mobile', :mobile) <ide> end <ide> <ide> def teardown <ide> super <del> Mime::Type.unregister('text/x-mobile', :iphone) <del> Mime::Type.unregister('text/iphone', :mobile) <add> Mime::Type.unregister(:iphone) <add> Mime::Type.unregister(:mobile) <ide> end <ide> <ide> def test_using_resource <ide> def test_render_json_object_responds_to_str_still_produce_json <ide> @controller = RenderJsonRespondWithController.new <ide> @request.accept = "application/json" <ide> get :index, :format => :json <del> assert_equal %Q{{"message":"boom","error":"RenderJsonTestException"}}, @response.body <add> assert_match(/"message":"boom"/, @response.body) <add> assert_match(/"error":"RenderJsonTestException"/, @response.body) <ide> end <ide> <ide> def test_no_double_render_is_raised <ide> def setup <ide> <ide> def teardown <ide> super <del> Mime::Type.unregister('text/x-mobile', :iphone) <del> Mime::Type.unregister('text/iphone', :mobile) <add> Mime::Type.unregister(:iphone) <ide> end <ide> <ide> def test_missing_layout_renders_properly <ide><path>actionpack/test/dispatch/mime_type_test.rb <ide> class MimeTypeTest < ActiveSupport::TestCase <ide> assert_equal Mime::MOBILE, Mime::LOOKUP['text/x-mobile'] <ide> assert_equal Mime::MOBILE, Mime::EXTENSION_LOOKUP['mobile'] <ide> <del> Mime::Type.unregister("text/x-mobile", :mobile) <add> Mime::Type.unregister(:mobile) <ide> assert !defined?(Mime::MOBILE), "Mime::MOBILE should not be defined" <ide> assert !Mime::LOOKUP.has_key?('text/x-mobile'), "Mime::LOOKUP should not have key ['text/x-mobile]" <ide> assert !Mime::EXTENSION_LOOKUP.has_key?('mobile'), "Mime::EXTENSION_LOOKUP should not have key ['mobile]" <ide> class MimeTypeTest < ActiveSupport::TestCase <ide> <ide> test "parse application with trailing star" do <ide> accept = "application/*" <del> expect = [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::PDF, Mime::URL_ENCODED_FORM].sort_by(&:to_s) <add> expect = [Mime::HTML, Mime::JS, Mime::XML, Mime::RSS, Mime::ATOM, Mime::YAML, Mime::URL_ENCODED_FORM, Mime::JSON, Mime::PDF] <ide> parsed = Mime::Type.parse(accept) <del> assert_equal 9, parsed.size <del> assert_equal expect, parsed.sort_by(&:to_s) <add> assert_equal expect, parsed <ide> end <ide> <ide> test "parse without q" do <ide> class MimeTypeTest < ActiveSupport::TestCase <ide> assert_equal Mime::GIF, Mime::SET.last <ide> end <ide> ensure <del> Mime::Type.unregister('image/gif', :gif) <add> Mime::Type.unregister(:gif) <ide> end <ide> end <ide> <ide><path>actionpack/test/lib/controller/fake_models.rb <ide> def each <ide> <ide> class RenderJsonTestException < Exception <ide> def to_json(options = nil) <del> return { :error => self.class.name, :message => self.to_str }.to_json <add> return { :error => self.class.name, :message => self.to_s }.to_json <ide> end <ide> end
4
Text
Text
add example api with examples of example usage
14a796e3f9ecfd5a6db969032324d83d40883704
<ide><path>website/docs/api/example.md <ide> --- <ide> title: Example <del>teaser: A training example <add>teaser: A training instance <ide> tag: class <ide> source: spacy/gold/example.pyx <add>new: 3.0 <ide> --- <ide> <del><!-- TODO: --> <add>An `Example` holds the information for one training instance. It stores two <add>`Doc` objects: one for holding the gold-standard reference data, and one for <add>holding the predictions of the pipeline. An `Alignment` <!-- TODO: link? --> <add>object stores the alignment between these two documents, as they can differ in <add>tokenization. <ide> <ide> ## Example.\_\_init\_\_ {#init tag="method"} <add> <add>Construct an `Example` object from the `predicted` document and the `reference` <add>document. If `alignment` is `None`, it will be initialized from the words in <add>both documents. <add> <add>> #### Example <add>> <add>> ```python <add>> from spacy.tokens import Doc <add>> from spacy.gold import Example <add>> words = ["hello", "world", "!"] <add>> spaces = [True, False, False] <add>> predicted = Doc(nlp.vocab, words=words, spaces=spaces) <add>> reference = parse_gold_doc(my_data) <add>> example = Example(predicted, reference) <add>> ``` <add> <add>| Name | Type | Description | <add>| -------------- | ----------- | ------------------------------------------------------------------------------------------------ | <add>| `predicted` | `Doc` | The document containing (partial) predictions. Can not be `None`. | <add>| `reference` | `Doc` | The document containing gold-standard annotations. Can not be `None`. | <add>| _keyword-only_ | | | <add>| `alignment` | `Alignment` | An object holding the alignment between the tokens of the `predicted` and `reference` documents. | <add>| **RETURNS** | `Example` | The newly constructed object. | <add> <add>## Example.from_dict {#from_dict tag="classmethod"} <add> <add>Construct an `Example` object from the `predicted` document and the reference <add>annotations provided as a dictionary. <add> <add><!-- TODO: document formats? legacy & token_annotation stuff --> <add> <add>> #### Example <add>> <add>> ```python <add>> from spacy.tokens import Doc <add>> from spacy.gold import Example <add>> predicted = Doc(vocab, words=["Apply", "some", "sunscreen"]) <add>> token_ref = ["Apply", "some", "sun", "screen"] <add>> tags_ref = ["VERB", "DET", "NOUN", "NOUN"] <add>> example = Example.from_dict(predicted, {"words": token_ref, "tags": tags_ref}) <add>> ``` <add> <add>| Name | Type | Description | <add>| -------------- | ---------------- | ----------------------------------------------------------------- | <add>| `predicted` | `Doc` | The document containing (partial) predictions. Can not be `None`. | <add>| `example_dict` | `Dict[str, obj]` | The gold-standard annotations as a dictionary. Can not be `None`. | <add>| **RETURNS** | `Example` | The newly constructed object. | <add> <add>## Example.text {#text tag="property"} <add> <add>The text of the `predicted` document in this `Example`. <add> <add>> #### Example <add>> <add>> ```python <add>> raw_text = example.text <add>> ``` <add> <add>| Name | Type | Description | <add>| ----------- | ---- | ------------------------------------- | <add>| **RETURNS** | str | The text of the `predicted` document. | <add> <add>## Example.predicted {#predicted tag="property"} <add> <add>> #### Example <add>> <add>> ```python <add>> docs = [eg.predicted for eg in examples] <add>> predictions, _ = model.begin_update(docs) <add>> set_annotations(docs, predictions) <add>> ``` <add> <add>The `Doc` holding the predictions. Occassionally also refered to as `example.x`. <add> <add>| Name | Type | Description | <add>| ----------- | ----- | ---------------------------------------------- | <add>| **RETURNS** | `Doc` | The document containing (partial) predictions. | <add> <add>## Example.reference {#reference tag="property"} <add> <add>> #### Example <add>> <add>> ```python <add>> for i, eg in enumerate(examples): <add>> for j, label in enumerate(all_labels): <add>> gold_labels[i][j] = eg.reference.cats.get(label, 0.0) <add>> ``` <add> <add>The `Doc` holding the gold-standard annotations. Occassionally also refered to <add>as `example.y`. <add> <add>| Name | Type | Description | <add>| ----------- | ----- | -------------------------------------------------- | <add>| **RETURNS** | `Doc` | The document containing gold-standard annotations. | <add> <add>## Example.alignment {#alignment tag="property"} <add> <add>> #### Example <add>> <add>> ```python <add>> tokens_x = ["Apply", "some", "sunscreen"] <add>> x = Doc(vocab, words=tokens_x) <add>> tokens_y = ["Apply", "some", "sun", "screen"] <add>> example = Example.from_dict(x, {"words": tokens_y}) <add>> alignment = example.alignment <add>> assert list(alignment.y2x.data) == [[0], [1], [2], [2]] <add>> ``` <add> <add>The `Alignment` object mapping the tokens of the `predicted` document to those <add>of the `reference` document. <add> <add>| Name | Type | Description | <add>| ----------- | ----------- | -------------------------------------------------- | <add>| **RETURNS** | `Alignment` | The document containing gold-standard annotations. | <add> <add>## Example.get_aligned {#get_aligned tag="method"} <add> <add>> #### Example <add>> <add>> ```python <add>> predicted = Doc(vocab, words=["Apply", "some", "sunscreen"]) <add>> token_ref = ["Apply", "some", "sun", "screen"] <add>> tags_ref = ["VERB", "DET", "NOUN", "NOUN"] <add>> example = Example.from_dict(predicted, {"words": token_ref, "tags": tags_ref}) <add>> assert example.get_aligned("TAG", as_string=True) == ["VERB", "DET", "NOUN"] <add>> ``` <add> <add>Get the aligned view of a certain token attribute, denoted by its int ID or string name. <add> <add>| Name | Type | Description | Default | <add>| ----------- | -------------------------- | ------------------------------------------------------------------ | ------- | <add>| `field` | int or str | Attribute ID or string name | | <add>| `as_string` | bool | Whether or not to return the list of values as strings. | `False` | <add>| **RETURNS** | `List[int]` or `List[str]` | List of integer values, or string values if `as_string` is `True`. | | <add> <add>## Example.get_aligned_parse {#get_aligned_parse tag="method"} <add> <add>> #### Example <add>> <add>> ```python <add>> doc = nlp("He pretty quickly walks away") <add>> example = Example.from_dict(doc, {"heads": [3, 2, 3, 0, 2]}) <add>> proj_heads, proj_labels = example.get_aligned_parse(projectivize=True) <add>> assert proj_heads == [3, 2, 3, 0, 3] <add>> ``` <add> <add>Get the aligned view of the dependency parse. If `projectivize` is set to <add>`True`, non-projective dependency trees are made projective through the <add>Pseudo-Projective Dependency Parsing algorithm by Nivre and Nilsson (2005). <add> <add>| Name | Type | Description | Default | <add>| -------------- | -------------------------- | ------------------------------------------------------------------ | ------- | <add>| `projectivize` | bool | Whether or not to projectivize the dependency trees | `True` | <add>| **RETURNS** | `List[int]` or `List[str]` | List of integer values, or string values if `as_string` is `True`. | | <add> <add>## Example.get_aligned_ner {#get_aligned_ner tag="method"} <add> <add>> #### Example <add>> <add>> ```python <add>> words = ["Mrs", "Smith", "flew", "to", "New York"] <add>> doc = Doc(en_vocab, words=words) <add>> entities = [(0, len("Mrs Smith"), "PERSON"), (18, 18 + len("New York"), "LOC")] <add>> gold_words = ["Mrs Smith", "flew", "to", "New", "York"] <add>> example = Example.from_dict(doc, {"words": gold_words, "entities": entities}) <add>> ner_tags = example.get_aligned_ner() <add>> assert ner_tags == ["B-PERSON", "L-PERSON", "O", "O", "U-LOC"] <add>> ``` <add> <add>Get the aligned view of the NER <add>[BILUO](/usage/linguistic-features#accessing-ner) tags. <add> <add>| Name | Type | Description | <add>| ----------- | ----------- | ----------------------------------------------------------------------------------- | <add>| **RETURNS** | `List[str]` | List of BILUO values, denoting whether tokens are part of an NER annotation or not. | <add> <add>## Example.get_aligned_spans_y2x {#get_aligned_spans_y2x tag="method"} <add> <add>> #### Example <add>> <add>> ```python <add>> words = ["Mr and Mrs Smith", "flew", "to", "New York"] <add>> doc = Doc(en_vocab, words=words) <add>> entities = [(0, len("Mr and Mrs Smith"), "PERSON")] <add>> tokens_ref = ["Mr", "and", "Mrs", "Smith", "flew", "to", "New", "York"] <add>> example = Example.from_dict(doc, {"words": tokens_ref, "entities": entities}) <add>> ents_ref = example.reference.ents <add>> assert [(ent.start, ent.end) for ent in ents_ref] == [(0, 4)] <add>> ents_y2x = example.get_aligned_spans_y2x(ents_ref) <add>> assert [(ent.start, ent.end) for ent in ents_y2x] == [(0, 1)] <add>> ``` <add> <add>Get the aligned view of any set of [`Span`](/api/span) objects defined over <add>`example.reference`. The resulting span indices will align to the tokenization <add>in `example.predicted`. <add> <add>| Name | Type | Description | <add>| ----------- | ---------------- | --------------------------------------------------------------- | <add>| `y_spans` | `Iterable[Span]` | `Span` objects aligned to the tokenization of `self.reference`. | <add>| **RETURNS** | `Iterable[Span]` | `Span` objects aligned to the tokenization of `self.predicted`. | <add> <add>## Example.get_aligned_spans_x2y {#get_aligned_spans_x2y tag="method"} <add> <add>> #### Example <add>> <add>> ```python <add>> ruler = EntityRuler(nlp) <add>> patterns = [{"label": "PERSON", "pattern": "Mr and Mrs Smith"}] <add>> ruler.add_patterns(patterns) <add>> nlp.add_pipe(ruler) <add>> doc = nlp("Mr and Mrs Smith flew to New York") <add>> entities = [(0, len("Mr and Mrs Smith"), "PERSON")] <add>> tokens_ref = ["Mr and Mrs", "Smith", "flew", "to", "New York"] <add>> example = Example.from_dict(doc, {"words": tokens_ref, "entities": entities}) <add>> ents_pred = example.predicted.ents <add>> assert [(ent.start, ent.end) for ent in ents_pred] == [(0, 4)] <add>> ents_x2y = example.get_aligned_spans_x2y(ents_pred) <add>> assert [(ent.start, ent.end) for ent in ents_x2y] == [(0, 2)] <add>> ``` <add> <add>Get the aligned view of any set of [`Span`](/api/span) objects defined over <add>`example.predicted`. The resulting span indices will align to the tokenization <add>in `example.reference`. This method is particularly useful to assess the <add>accuracy of predicted entities against the original gold-standard annotation. <add> <add>| Name | Type | Description | <add>| ----------- | ---------------- | --------------------------------------------------------------- | <add>| `x_spans` | `Iterable[Span]` | `Span` objects aligned to the tokenization of `self.predicted`. | <add>| **RETURNS** | `Iterable[Span]` | `Span` objects aligned to the tokenization of `self.reference`. | <add> <add>## Example.to_dict {#to_dict tag="method"} <add> <add>Return a dictionary representation of the reference annotation contained in this <add>`Example`. <add> <add>> #### Example <add>> <add>> ```python <add>> eg_dict = example.to_dict() <add>> ``` <add> <add>| Name | Type | Description | <add>| ----------- | ---------------- | ------------------------------------------------------ | <add>| **RETURNS** | `Dict[str, obj]` | Dictionary representation of the reference annotation. | <add> <add>## Example.split_sents {#split_sents tag="method"} <add> <add>> #### Example <add>> <add>> ```python <add>> doc = nlp("I went yesterday had lots of fun") <add>> tokens_ref = ["I", "went", "yesterday", "had", "lots", "of", "fun"] <add>> sents_ref = [True, False, False, True, False, False, False] <add>> example = Example.from_dict(doc, {"words": tokens_ref, "sent_starts": sents_ref}) <add>> split_examples = example.split_sents() <add>> assert split_examples[0].text == "I went yesterday " <add>> assert split_examples[1].text == "had lots of fun" <add>> ``` <add> <add>Split one `Example` into multiple `Example` objects, one for each sentence. <add> <add>| Name | Type | Description | <add>| ----------- | --------------- | ---------------------------------------------------------- | <add>| **RETURNS** | `List[Example]` | List of `Example` objects, one for each original sentence. |
1
Javascript
Javascript
use correct ctor for error serialization
de9d5ff287c576c495f5c132fdf4b826f1356e5a
<ide><path>lib/internal/error-serdes.js <ide> function serializeError(error) { <ide> if (typeof error === 'object' && <ide> ObjectPrototypeToString(error) === '[object Error]') { <ide> const constructors = GetConstructors(error); <del> for (var i = constructors.length - 1; i >= 0; i--) { <add> for (var i = 0; i < constructors.length; i++) { <ide> const name = GetName(constructors[i]); <ide> if (errorConstructorNames.has(name)) { <ide> try { error.stack; } catch {} <ide><path>test/parallel/test-worker-syntax-error-file.js <ide> if (!process.env.HAS_STARTED_WORKER) { <ide> const w = new Worker(fixtures.path('syntax', 'bad_syntax.js')); <ide> w.on('message', common.mustNotCall()); <ide> w.on('error', common.mustCall((err) => { <add> assert.strictEqual(err.constructor, SyntaxError); <ide> assert(/SyntaxError/.test(err)); <ide> })); <ide> } else { <ide><path>test/parallel/test-worker-syntax-error.js <ide> if (!process.env.HAS_STARTED_WORKER) { <ide> const w = new Worker('abc)', { eval: true }); <ide> w.on('message', common.mustNotCall()); <ide> w.on('error', common.mustCall((err) => { <add> assert.strictEqual(err.constructor, SyntaxError); <ide> assert(/SyntaxError/.test(err)); <ide> })); <ide> } else {
3
Text
Text
fix typo in updating.md
b88ca51a34054f7775f95dd3e5905e9040494a1e
<ide><path>UPDATING.md <ide> dag >> dummy <ide> This is no longer supported. Instead, we recommend using the DAG as context manager: <ide> <ide> ```python <del>with DAG('my_dag): <add>with DAG('my_dag'): <ide> dummy = DummyOperator(task_id='dummy') <ide> ``` <ide>
1
Javascript
Javascript
keep iframes visible in testswarm
c0edd8dc18e02999a25768a4946093b015045f80
<ide><path>test/data/testinit.js <ide> this.testIframe = function( title, fileName, func, wrapper ) { <ide> wrapper.call( QUnit, title, function( assert ) { <ide> var done = assert.async(), <ide> $iframe = supportjQuery( "<iframe/>" ) <del> .css( { position: "absolute", width: "500px", left: "-600px" } ) <del> .attr( { id: "qunit-fixture-iframe", src: url( "./data/" + fileName ) } ); <add> .attr( { id: "qunit-fixture-iframe", src: url( "./data/" + fileName ) } ) <add> .css( { <add> position: "absolute", <add> top: "0", <add> left: "-600px", <add> height: "300px", <add> width: "500px" <add> } ); <add> <add> // Overcome TestSwarm iframe visibilty quirks <add> if ( QUnit.isSwarm ) { <add> $iframe.css( { left: "0" } ); <add> } <ide> <ide> // Test iframes are expected to invoke this via startIframeTest (cf. iframeTest.js) <ide> window.iframeCallback = function() {
1
Python
Python
fix output size in documentation
76568d24b67d50ca82192fa53e8b9ebb3dd27b42
<ide><path>src/transformers/models/segformer/modeling_segformer.py <ide> def forward( <ide> <ide> >>> inputs = feature_extractor(images=image, return_tensors="pt") <ide> >>> outputs = model(**inputs) <del> >>> logits = outputs.logits # shape (batch_size, num_labels, height, width) <add> >>> logits = outputs.logits # shape (batch_size, num_labels, height/4, width/4) <ide> >>> list(logits.shape) <ide> [1, 150, 128, 128] <ide> ```""" <ide><path>src/transformers/models/segformer/modeling_tf_segformer.py <ide> def call( <ide> <ide> >>> inputs = feature_extractor(images=image, return_tensors="tf") <ide> >>> outputs = model(**inputs, training=False) <del> >>> # logits are of shape (batch_size, num_labels, height, width) <add> >>> # logits are of shape (batch_size, num_labels, height/4, width/4) <ide> >>> logits = outputs.logits <ide> >>> list(logits.shape) <ide> [1, 150, 128, 128]
2
Javascript
Javascript
remove markup related paths
e34e8974db85e98e735a73a65f01e49b35e6f414
<ide><path>src/renderers/dom/fiber/ReactDOMFiberComponent.js <ide> function isCustomComponent(tagName, props) { <ide> return tagName.indexOf('-') >= 0 || props.is != null; <ide> } <ide> <del> <del>/** <del> * Creates markup for the open tag and all attributes. <del> * <del> * This method has side effects because events get registered. <del> * <del> * Iterating over object properties is faster than iterating over arrays. <del> * @see http://jsperf.com/obj-vs-arr-iteration <del> * <del> * @private <del> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction <del> * @param {object} props <del> * @return {string} Markup of opening tag. <del> */ <del>function createOpenTagMarkupAndPutListeners(workInProgress, transaction, props) { <del> var ret = '<' + workInProgress._currentElement.type; <del> <del> for (var propKey in props) { <del> if (!props.hasOwnProperty(propKey)) { <del> continue; <del> } <del> var propValue = props[propKey]; <del> if (propValue == null) { <del> continue; <del> } <del> if (registrationNameModules.hasOwnProperty(propKey)) { <del> if (propValue) { <del> enqueuePutListener(workInProgress, propKey, propValue, transaction); <del> } <del> } else { <del> if (propKey === STYLE) { <del> if (propValue) { <del> if (__DEV__) { <del> // See `_updateDOMProperties`. style block <del> workInProgress._previousStyle = propValue; <del> } <del> propValue = workInProgress._previousStyleCopy = Object.assign({}, props.style); <del> } <del> propValue = CSSPropertyOperations.createMarkupForStyles(propValue, workInProgress); <del> } <del> var markup = null; <del> if (workInProgress._tag != null && isCustomComponent(workInProgress._tag, props)) { <del> if (!RESERVED_PROPS.hasOwnProperty(propKey)) { <del> markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); <del> } <del> } else { <del> markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); <del> } <del> if (markup) { <del> ret += ' ' + markup; <del> } <del> } <del> } <del> <del> // For static pages, no need to put React ID and checksum. Saves lots of <del> // bytes. <del> if (transaction.renderToStaticMarkup) { <del> return ret; <del> } <del> <del> if (!workInProgress._hostParent) { <del> ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); <del> } <del> ret += ' ' + DOMPropertyOperations.createMarkupForID(workInProgress._domID); <del> return ret; <del>} <del> <del>/** <del> * Creates markup for the content between the tags. <del> * <del> * @private <del> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction <del> * @param {object} props <del> * @param {object} context <del> * @return {string} Content markup. <del> */ <del>function createContentMarkup(workInProgress, transaction, props, context) { <del> var ret = ''; <del> <del> // Intentional use of != to avoid catching zero/false. <del> var innerHTML = props.dangerouslySetInnerHTML; <del> if (innerHTML != null) { <del> if (innerHTML.__html != null) { <del> ret = innerHTML.__html; <del> } <del> } else { <del> var contentToUse = <del> CONTENT_TYPES[typeof props.children] ? props.children : null; <del> var childrenToUse = contentToUse != null ? null : props.children; <del> if (contentToUse != null) { <del> // TODO: Validate that text is allowed as a child of this node <del> ret = escapeTextContentForBrowser(contentToUse); <del> if (__DEV__) { <del> setAndValidateContentChildDev.call(workInProgress, contentToUse); <del> } <del> } else if (childrenToUse != null) { <del> var mountImages = workInProgress.mountChildren( <del> childrenToUse, <del> transaction, <del> context <del> ); <del> ret = mountImages.join(''); <del> } <del> } <del> if (newlineEatingTags[workInProgress._tag] && ret.charAt(0) === '\n') { <del> // text/html ignores the first character in these tags if it's a newline <del> // Prefer to break application/xml over text/html (for now) by adding <del> // a newline specifically to get eaten by the parser. (Alternately for <del> // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first <del> // \r is normalized out by HTMLTextAreaElement#value.) <del> // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> <del> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> <del> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> <del> // See: Parsing of "textarea" "listing" and "pre" elements <del> // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> <del> return '\n' + ret; <del> } else { <del> return ret; <del> } <del>} <del> <ide> function createInitialChildren(workInProgress, transaction, props, context, lazyTree) { <ide> // Intentional use of != to avoid catching zero/false. <ide> var innerHTML = props.dangerouslySetInnerHTML; <ide> var ReactDOMFiberComponent = { <ide> <ide> var mountImage; <ide> var type = workInProgress._currentElement.type; <del> if (transaction.useCreateElement) { <del> var ownerDocument = hostContainerInfo._ownerDocument; <del> var el; <del> if (namespaceURI === DOMNamespaces.html) { <del> if (workInProgress._tag === 'script') { <del> // Create the script via .innerHTML so its "parser-inserted" flag is <del> // set to true and it does not execute <del> var div = ownerDocument.createElement('div'); <del> div.innerHTML = `<${type}></${type}>`; <del> el = div.removeChild(div.firstChild); <del> } else if (props.is) { <del> el = ownerDocument.createElement(type, props.is); <del> } else { <del> // Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug. <del> // See discussion in https://github.com/facebook/react/pull/6896 <del> // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 <del> el = ownerDocument.createElement(type); <del> } <add> var ownerDocument = hostContainerInfo._ownerDocument; <add> var el; <add> if (namespaceURI === DOMNamespaces.html) { <add> if (workInProgress._tag === 'script') { <add> // Create the script via .innerHTML so its "parser-inserted" flag is <add> // set to true and it does not execute <add> var div = ownerDocument.createElement('div'); <add> div.innerHTML = `<${type}></${type}>`; <add> el = div.removeChild(div.firstChild); <add> } else if (props.is) { <add> el = ownerDocument.createElement(type, props.is); <ide> } else { <del> el = ownerDocument.createElementNS( <del> namespaceURI, <del> type <del> ); <del> } <del> var isCustomComponentTag = isCustomComponent(workInProgress._tag, props); <del> if (__DEV__ && isCustomComponentTag && !didWarnShadyDOM && el.shadyRoot) { <del> var owner = workInProgress._currentElement._owner; <del> var name = owner && owner.getName() || 'A component'; <del> warning( <del> false, <del> '%s is using shady DOM. Using shady DOM with React can ' + <del> 'cause things to break subtly.', <del> name <del> ); <del> didWarnShadyDOM = true; <del> } <del> ReactDOMComponentTree.precacheNode(workInProgress, el); <del> workInProgress._flags |= Flags.hasCachedChildNodes; <del> if (!workInProgress._hostParent) { <del> DOMPropertyOperations.setAttributeForRoot(el); <add> // Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug. <add> // See discussion in https://github.com/facebook/react/pull/6896 <add> // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 <add> el = ownerDocument.createElement(type); <ide> } <del> updateDOMProperties(workInProgress, null, props, transaction, isCustomComponentTag); <del> var lazyTree = DOMLazyTree(el); <del> createInitialChildren(workInProgress, transaction, props, context, lazyTree); <del> mountImage = lazyTree; <ide> } else { <del> var tagOpen = createOpenTagMarkupAndPutListeners(workInProgress, transaction, props); <del> var tagContent = createContentMarkup(workInProgress, transaction, props, context); <del> if (!tagContent && omittedCloseTags[workInProgress._tag]) { <del> mountImage = tagOpen + '/>'; <del> } else { <del> mountImage = tagOpen + '>' + tagContent + '</' + type + '>'; <del> } <add> el = ownerDocument.createElementNS( <add> namespaceURI, <add> type <add> ); <add> } <add> var isCustomComponentTag = isCustomComponent(workInProgress._tag, props); <add> if (__DEV__ && isCustomComponentTag && !didWarnShadyDOM && el.shadyRoot) { <add> var owner = workInProgress._currentElement._owner; <add> var name = owner && owner.getName() || 'A component'; <add> warning( <add> false, <add> '%s is using shady DOM. Using shady DOM with React can ' + <add> 'cause things to break subtly.', <add> name <add> ); <add> didWarnShadyDOM = true; <add> } <add> ReactDOMComponentTree.precacheNode(workInProgress, el); <add> workInProgress._flags |= Flags.hasCachedChildNodes; <add> if (!workInProgress._hostParent) { <add> DOMPropertyOperations.setAttributeForRoot(el); <ide> } <add> updateDOMProperties(workInProgress, null, props, transaction, isCustomComponentTag); <add> var lazyTree = DOMLazyTree(el); <add> createInitialChildren(workInProgress, transaction, props, context, lazyTree); <add> mountImage = lazyTree; <ide> <ide> switch (workInProgress._tag) { <ide> case 'input':
1
Ruby
Ruby
upgrade virtualenv to 16.2.0
2181ea76c6d48c10974fa9d36cf01c014dd42475
<ide><path>Library/Homebrew/language/python_virtualenv_constants.rb <ide> PYTHON_VIRTUALENV_URL = <del> "https://files.pythonhosted.org/packages/4e/8b" \ <del> "/75469c270ac544265f0020aa7c4ea925c5284b23e445cf3aa8b99f662690" \ <del> "/virtualenv-16.1.0.tar.gz".freeze <add> "https://github.com/pypa/virtualenv/archive/16.2.0.tar.gz".freeze <ide> PYTHON_VIRTUALENV_SHA256 = <del> "f899fafcd92e1150f40c8215328be38ff24b519cd95357fa6e78e006c7638208".freeze <add> "448def1220df9960e6d18fb5424107ffb1249eb566a5a311257860ab6b52b3fd".freeze
1
Text
Text
add v3.9.0-beta.5 to changelog
7255233fa5e92a8d3389a8accefd20817c132a85
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.9.0-beta.5 (March 25, 2019) <add> <add>- [#17733](https://github.com/emberjs/ember.js/pull/17733) [BUGFIX] Assert on use of reserved component names (`input` and `textarea`) <add> <ide> ### v3.9.0-beta.4 (March 11, 2019) <ide> <ide> - [#17710](https://github.com/emberjs/ember.js/pull/17710) [BUGFIX] Allow accessors in mixins
1
Javascript
Javascript
fix some issues related to rendering
03209d88fd014293e59dc40c9ebda5ae7b21ec6e
<ide><path>client/index.js <ide> const { <ide> location <ide> } = window <ide> <del>window.NEXT_PAGE_LOADER = new PageLoader(buildId) <del> <add>const pageLoader = window.NEXT_PAGE_LOADER = new PageLoader(buildId) <ide> const Component = evalScript(component).default <ide> const ErrorComponent = evalScript(errorComponent).default <ide> let lastAppProps <ide> <ide> export const router = createRouter(pathname, query, getURL(), { <add> pageLoader, <ide> Component, <ide> ErrorComponent, <ide> err <ide><path>lib/router/router.js <del>/* global NEXT_PAGE_LOADER */ <del> <ide> import { parse, format } from 'url' <ide> import mitt from 'mitt' <ide> import shallowEquals from '../shallow-equals' <ide> import { _notifyBuildIdMismatch } from './' <ide> const webpackModule = module <ide> <ide> export default class Router { <del> constructor (pathname, query, as, { Component, ErrorComponent, err } = {}) { <add> constructor (pathname, query, as, { pageLoader, Component, ErrorComponent, err } = {}) { <ide> // represents the current component key <ide> this.route = toRoute(pathname) <ide> <ide> export default class Router { <ide> // Handling Router Events <ide> this.events = mitt() <ide> <add> this.pageLoader = pageLoader <ide> this.prefetchQueue = new PQueue({ concurrency: 2 }) <ide> this.ErrorComponent = ErrorComponent <ide> this.pathname = pathname <ide> export default class Router { <ide> <ide> async reload (route) { <ide> delete this.components[route] <del> NEXT_PAGE_LOADER.clearCache(route) <add> this.pageLoader.clearCache(route) <ide> <ide> if (route !== this.route) return <ide> <ide> export default class Router { <ide> }) <ide> } <ide> <del> return await NEXT_PAGE_LOADER.loadPage(route) <add> return await this.pageLoader.loadPage(route) <ide> } <ide> <ide> abortComponentLoad (as) { <ide><path>server/build/plugins/pages-plugin.js <ide> export default class PagesPlugin { <ide> pages.forEach((chunk) => { <ide> const page = compilation.assets[chunk.name] <ide> const pageName = matchRouteName.exec(chunk.name)[1] <del> const routeName = `/${pageName.replace(/index$/, '')}` <add> const routeName = `/${pageName.replace(/[/\\]index$/, '')}` <ide> <ide> const content = page.source() <ide> const newContent = `
3
Java
Java
add websocketclient for jetty
bd09a76a1eec053bd5a7533f67ecbb65fbe2b96d
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/HandshakeInfo.java <ide> public class HandshakeInfo { <ide> <ide> private final URI uri; <ide> <del> private final HttpHeaders headers; <del> <ide> private final Mono<Principal> principalMono; <ide> <del> private final Optional<String> protocol; <add> private HttpHeaders headers; <add> <add> private Optional<String> protocol; <ide> <ide> <add> public HandshakeInfo(URI uri, Mono<Principal> principal) { <add> this(uri, new HttpHeaders(), principal, Optional.empty()); <add> } <add> <ide> public HandshakeInfo(URI uri, HttpHeaders headers, Mono<Principal> principal, <ide> Optional<String> subProtocol) { <ide> <ide> public HttpHeaders getHeaders() { <ide> return this.headers; <ide> } <ide> <add> /** <add> * Sets the handshake HTTP headers. Those are the request headers for a <add> * server session and the response headers for a client session. <add> * @param headers the handshake HTTP headers. <add> */ <add> public void setHeaders(HttpHeaders headers) { <add> this.headers = headers; <add> } <add> <ide> /** <ide> * Return the principal associated with the handshake HTTP request. <ide> */ <ide> public Optional<String> getSubProtocol() { <ide> return this.protocol; <ide> } <ide> <add> /** <add> * Sets the sub-protocol negotiated at handshake time. <add> * @param protocol the sub-protocol negotiated at handshake time. <add> */ <add> public void setSubProtocol(Optional<String> protocol) { <add> this.protocol = protocol; <add> } <add> <ide> <ide> @Override <ide> public String toString() { <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/adapter/JettyWebSocketHandlerAdapter.java <ide> import org.eclipse.jetty.websocket.common.OpCode; <ide> import org.reactivestreams.Subscriber; <ide> import org.reactivestreams.Subscription; <add>import reactor.core.publisher.MonoProcessor; <ide> <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferFactory; <ide> public class JettyWebSocketHandlerAdapter extends WebSocketHandlerAdapterSupport <ide> <ide> private JettyWebSocketSession delegateSession; <ide> <add> private final MonoProcessor<Void> completionMono; <add> <ide> <ide> public JettyWebSocketHandlerAdapter(WebSocketHandler delegate, HandshakeInfo info, <ide> DataBufferFactory bufferFactory) { <ide> <add> this(delegate, info, bufferFactory, null); <add> } <add> <add> public JettyWebSocketHandlerAdapter(WebSocketHandler delegate, HandshakeInfo info, <add> DataBufferFactory bufferFactory, MonoProcessor<Void> completionMono) { <add> <ide> super(delegate, info, bufferFactory); <add> this.completionMono = completionMono; <ide> } <ide> <ide> <ide> public void onNext(Void aVoid) { <ide> <ide> @Override <ide> public void onError(Throwable ex) { <add> if (completionMono != null) { <add> completionMono.onError(ex); <add> } <ide> if (delegateSession != null) { <ide> int code = CloseStatus.SERVER_ERROR.getCode(); <ide> delegateSession.close(new CloseStatus(code, ex.getMessage())); <ide> public void onError(Throwable ex) { <ide> <ide> @Override <ide> public void onComplete() { <add> if (completionMono != null) { <add> completionMono.onComplete(); <add> } <ide> if (delegateSession != null) { <ide> delegateSession.close(); <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/socket/client/JettyWebSocketClient.java <add>/* <add> * Copyright 2002-2016 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.reactive.socket.client; <add> <add>import java.net.URI; <add>import java.util.Optional; <add> <add>import org.eclipse.jetty.websocket.api.Session; <add>import org.eclipse.jetty.websocket.api.UpgradeResponse; <add>import org.eclipse.jetty.websocket.api.annotations.WebSocket; <add>import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; <add> <add>import reactor.core.publisher.Mono; <add>import reactor.core.publisher.MonoProcessor; <add> <add>import org.springframework.context.Lifecycle; <add>import org.springframework.core.io.buffer.DataBufferFactory; <add>import org.springframework.core.io.buffer.DefaultDataBufferFactory; <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.util.ObjectUtils; <add>import org.springframework.web.reactive.socket.HandshakeInfo; <add>import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.adapter.JettyWebSocketHandlerAdapter; <add> <add>/** <add> * A Jetty based implementation of {@link WebSocketClient}. <add> * <add> * @author Violeta Georgieva <add> * @since 5.0 <add> */ <add>public class JettyWebSocketClient extends WebSocketClientSupport implements WebSocketClient, Lifecycle { <add> <add> private final DataBufferFactory bufferFactory = new DefaultDataBufferFactory(); <add> <add> private final org.eclipse.jetty.websocket.client.WebSocketClient wsClient; <add> <add> private final Object lifecycleMonitor = new Object(); <add> <add> <add> /** <add> * Default constructor that creates an instance of <add> * {@link org.eclipse.jetty.websocket.client.WebSocketClient}. <add> */ <add> public JettyWebSocketClient() { <add> this(new org.eclipse.jetty.websocket.client.WebSocketClient()); <add> } <add> <add> /** <add> * Constructor that accepts an existing <add> * {@link org.eclipse.jetty.websocket.client.WebSocketClient} instance. <add> * @param wsClient a web socket client <add> */ <add> public JettyWebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient wsClient) { <add> this.wsClient = wsClient; <add> } <add> <add> <add> @Override <add> public Mono<Void> execute(URI url, WebSocketHandler handler) { <add> return execute(url, new HttpHeaders(), handler); <add> } <add> <add> @Override <add> public Mono<Void> execute(URI url, HttpHeaders headers, WebSocketHandler handler) { <add> return connectInternal(url, headers, handler); <add> } <add> <add> private Mono<Void> connectInternal(URI url, HttpHeaders headers, WebSocketHandler handler) { <add> MonoProcessor<Void> processor = MonoProcessor.create(); <add> return Mono.fromCallable( <add> () -> { <add> HandshakeInfo info = new HandshakeInfo(url, Mono.empty()); <add> Object adapter = new JettyClientAdapter(handler, info, this.bufferFactory, processor); <add> ClientUpgradeRequest request = createRequest(url, headers, handler); <add> return this.wsClient.connect(adapter, url, request); <add> }) <add> .then(processor); <add> } <add> <add> private ClientUpgradeRequest createRequest(URI url, HttpHeaders headers, WebSocketHandler handler) { <add> ClientUpgradeRequest request = new ClientUpgradeRequest(); <add> <add> String[] protocols = beforeHandshake(url, headers, handler); <add> if (!ObjectUtils.isEmpty(protocols)) { <add> request.setSubProtocols(protocols); <add> } <add> <add> headers.forEach((k, v) -> request.setHeader(k, v)); <add> <add> return request; <add> } <add> <add> <add> @Override <add> public void start() { <add> synchronized (this.lifecycleMonitor) { <add> if (!isRunning()) { <add> try { <add> this.wsClient.start(); <add> } <add> catch (Exception ex) { <add> throw new IllegalStateException("Failed to start Jetty WebSocketClient", ex); <add> } <add> } <add> } <add> } <add> <add> @Override <add> public void stop() { <add> synchronized (this.lifecycleMonitor) { <add> if (isRunning()) { <add> try { <add> this.wsClient.stop(); <add> } <add> catch (Exception ex) { <add> throw new IllegalStateException("Error stopping Jetty WebSocketClient", ex); <add> } <add> } <add> } <add> } <add> <add> @Override <add> public boolean isRunning() { <add> synchronized (this.lifecycleMonitor) { <add> return this.wsClient.isStarted(); <add> } <add> } <add> <add> <add> @WebSocket <add> private static final class JettyClientAdapter extends JettyWebSocketHandlerAdapter { <add> <add> public JettyClientAdapter(WebSocketHandler delegate, <add> HandshakeInfo info, DataBufferFactory bufferFactory, MonoProcessor<Void> processor) { <add> super(delegate, info, bufferFactory, processor); <add> } <add> <add> @Override <add> public void onWebSocketConnect(Session session) { <add> UpgradeResponse response = session.getUpgradeResponse(); <add> <add> getHandshakeInfo().setHeaders(getResponseHeaders(response)); <add> getHandshakeInfo().setSubProtocol( <add> Optional.ofNullable(response.getAcceptedSubProtocol())); <add> <add> super.onWebSocketConnect(session); <add> } <add> <add> private HttpHeaders getResponseHeaders(UpgradeResponse response) { <add> HttpHeaders responseHeaders = new HttpHeaders(); <add> response.getHeaders().forEach((k, v) -> responseHeaders.put(k, v)); <add> return responseHeaders; <add> } <add> <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/socket/server/WebSocketIntegrationTests.java <ide> import org.springframework.web.reactive.socket.WebSocketHandler; <ide> import org.springframework.web.reactive.socket.WebSocketMessage; <ide> import org.springframework.web.reactive.socket.WebSocketSession; <add>import org.springframework.web.reactive.socket.client.JettyWebSocketClient; <ide> import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; <ide> import org.springframework.web.reactive.socket.client.RxNettyWebSocketClient; <ide> import org.springframework.web.reactive.socket.client.WebSocketClient; <ide> public void echoRxNettyClient() throws Exception { <ide> testEcho(new RxNettyWebSocketClient()); <ide> } <ide> <add> @Test <add> public void echoJettyClient() throws Exception { <add> JettyWebSocketClient client = new JettyWebSocketClient(); <add> client.start(); <add> testEcho(client); <add> client.stop(); <add> } <add> <ide> private void testEcho(WebSocketClient client) throws URISyntaxException { <ide> int count = 100; <ide> Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index); <ide> public void subProtocolRxNettyClient() throws Exception { <ide> testSubProtocol(new RxNettyWebSocketClient()); <ide> } <ide> <add> @Test <add> public void subProtocolJettyClient() throws Exception { <add> JettyWebSocketClient client = new JettyWebSocketClient(); <add> client.start(); <add> testSubProtocol(client); <add> client.stop(); <add> } <add> <ide> private void testSubProtocol(WebSocketClient client) throws URISyntaxException { <ide> String protocol = "echo-v1"; <ide> AtomicReference<HandshakeInfo> infoRef = new AtomicReference<>();
4
Go
Go
move pull and import to a job
9dcbdbc4b1addb67c0fdcadab1c8f98f30e58b4c
<ide><path>api.go <ide> func postImagesCreate(srv *Server, version float64, w http.ResponseWriter, r *ht <ide> return err <ide> } <ide> <del> src := r.Form.Get("fromSrc") <del> image := r.Form.Get("fromImage") <del> tag := r.Form.Get("tag") <del> repo := r.Form.Get("repo") <del> <add> var ( <add> image = r.Form.Get("fromImage") <add> tag = r.Form.Get("tag") <add> job *engine.Job <add> ) <ide> authEncoded := r.Header.Get("X-Registry-Auth") <ide> authConfig := &auth.AuthConfig{} <ide> if authEncoded != "" { <ide> func postImagesCreate(srv *Server, version float64, w http.ResponseWriter, r *ht <ide> if version > 1.0 { <ide> w.Header().Set("Content-Type", "application/json") <ide> } <del> sf := utils.NewStreamFormatter(version > 1.0) <ide> if image != "" { //pull <ide> metaHeaders := map[string][]string{} <ide> for k, v := range r.Header { <ide> if strings.HasPrefix(k, "X-Meta-") { <ide> metaHeaders[k] = v <ide> } <ide> } <del> if err := srv.ImagePull(image, tag, w, sf, authConfig, metaHeaders, version > 1.3); err != nil { <del> if sf.Used() { <del> w.Write(sf.FormatError(err)) <del> return nil <del> } <del> return err <del> } <add> job = srv.Eng.Job("pull", r.Form.Get("fromImage"), tag) <add> job.SetenvBool("parallel", version > 1.3) <add> job.SetenvJson("metaHeaders", metaHeaders) <add> job.SetenvJson("authConfig", authConfig) <ide> } else { //import <del> if err := srv.ImageImport(src, repo, tag, r.Body, w, sf); err != nil { <del> if sf.Used() { <del> w.Write(sf.FormatError(err)) <del> return nil <del> } <add> job = srv.Eng.Job("import", r.Form.Get("fromSrc"), r.Form.Get("repo"), tag) <add> job.Stdin.Add(r.Body) <add> } <add> <add> job.SetenvBool("json", version > 1.0) <add> job.Stdout.Add(w) <add> if err := job.Run(); err != nil { <add> if !job.Stdout.Used() { <ide> return err <ide> } <add> sf := utils.NewStreamFormatter(version > 1.0) <add> w.Write(sf.FormatError(err)) <ide> } <add> <ide> return nil <ide> } <ide> <ide><path>buildfile.go <ide> func (b *buildFile) CmdFrom(name string) error { <ide> resolvedAuth := b.configFile.ResolveAuthConfig(endpoint) <ide> pullRegistryAuth = &resolvedAuth <ide> } <del> if err := b.srv.ImagePull(remote, tag, b.outOld, b.sf, pullRegistryAuth, nil, true); err != nil { <add> job := b.srv.Eng.Job("pull", remote, tag) <add> job.SetenvBool("json", b.sf.Json()) <add> job.SetenvBool("parallel", true) <add> job.SetenvJson("authConfig", pullRegistryAuth) <add> job.Stdout.Add(b.outOld) <add> if err := job.Run(); err != nil { <ide> return err <ide> } <ide> image, err = b.runtime.repositories.LookupImage(name) <ide><path>engine/engine.go <ide> func (eng *Engine) Job(name string, args ...string) *Job { <ide> } <ide> <ide> func (eng *Engine) Logf(format string, args ...interface{}) (n int, err error) { <del> prefixedFormat := fmt.Sprintf("[%s] %s\n", eng, strings.TrimRight(format, "\n")) <del> return fmt.Fprintf(eng.Stderr, prefixedFormat, args...) <add> if os.Getenv("TEST") == "" { <add> prefixedFormat := fmt.Sprintf("[%s] %s\n", eng, strings.TrimRight(format, "\n")) <add> return fmt.Fprintf(eng.Stderr, prefixedFormat, args...) <add> } <add> return 0, nil <ide> } <ide><path>engine/job.go <ide> package engine <ide> import ( <ide> "fmt" <ide> "io" <add> "os" <ide> "strings" <ide> "time" <ide> ) <ide> func (job *Job) Environ() map[string]string { <ide> } <ide> <ide> func (job *Job) Logf(format string, args ...interface{}) (n int, err error) { <del> prefixedFormat := fmt.Sprintf("[%s] %s\n", job, strings.TrimRight(format, "\n")) <del> return fmt.Fprintf(job.Stderr, prefixedFormat, args...) <add> if os.Getenv("TEST") == "" { <add> prefixedFormat := fmt.Sprintf("[%s] %s\n", job, strings.TrimRight(format, "\n")) <add> return fmt.Fprintf(job.Stderr, prefixedFormat, args...) <add> } <add> return 0, nil <ide> } <ide> <ide> func (job *Job) Printf(format string, args ...interface{}) (n int, err error) { <ide><path>integration/runtime_test.go <ide> func setupBaseImage() { <ide> // If the unit test is not found, try to download it. <ide> if img, err := srv.ImageInspect(unitTestImageName); err != nil || img.ID != unitTestImageID { <ide> // Retrieve the Image <del> if err := srv.ImagePull(unitTestImageName, "", os.Stdout, utils.NewStreamFormatter(false), nil, nil, true); err != nil { <add> job = eng.Job("pull", unitTestImageName) <add> job.Stdout.Add(utils.NopWriteCloser(os.Stdout)) <add> if err := job.Run(); err != nil { <ide> log.Fatalf("Unable to pull the test image: %s", err) <ide> } <ide> } <ide><path>integration/sorter_test.go <ide> package docker <ide> <ide> import ( <ide> "github.com/dotcloud/docker" <del> "github.com/dotcloud/docker/utils" <del> "io/ioutil" <ide> "testing" <ide> "time" <ide> ) <ide> func generateImage(name string, srv *docker.Server) error { <ide> if err != nil { <ide> return err <ide> } <del> return srv.ImageImport("-", "repo", name, archive, ioutil.Discard, utils.NewStreamFormatter(true)) <add> job := srv.Eng.Job("import", "-", "repo", name) <add> job.Stdin.Add(archive) <add> job.SetenvBool("json", true) <add> return job.Run() <ide> } <ide><path>server.go <ide> func jobInitApi(job *engine.Job) engine.Status { <ide> "top": srv.ContainerTop, <ide> "load": srv.ImageLoad, <ide> "build": srv.Build, <add> "pull": srv.ImagePull, <add> "import": srv.ImageImport, <ide> } { <ide> if err := job.Eng.Register(name, handler); err != nil { <ide> job.Error(err) <ide> func (srv *Server) poolRemove(kind, key string) error { <ide> return nil <ide> } <ide> <del>func (srv *Server) ImagePull(localName string, tag string, out io.Writer, sf *utils.StreamFormatter, authConfig *auth.AuthConfig, metaHeaders map[string][]string, parallel bool) error { <del> out = utils.NewWriteFlusher(out) <add>func (srv *Server) ImagePull(job *engine.Job) engine.Status { <add> if n := len(job.Args); n != 1 && n != 2 { <add> job.Errorf("Usage: %s IMAGE [TAG]", job.Name) <add> return engine.StatusErr <add> } <add> var ( <add> localName = job.Args[0] <add> tag string <add> sf = utils.NewStreamFormatter(job.GetenvBool("json")) <add> out = utils.NewWriteFlusher(job.Stdout) <add> authConfig *auth.AuthConfig <add> metaHeaders map[string][]string <add> ) <add> if len(job.Args) > 1 { <add> tag = job.Args[1] <add> } <add> <add> job.GetenvJson("authConfig", authConfig) <add> job.GetenvJson("metaHeaders", metaHeaders) <ide> <ide> c, err := srv.poolAdd("pull", localName+":"+tag) <ide> if err != nil { <ide> if c != nil { <ide> // Another pull of the same repository is already taking place; just wait for it to finish <ide> out.Write(sf.FormatStatus("", "Repository %s already being pulled by another client. Waiting.", localName)) <ide> <-c <del> return nil <add> return engine.StatusOK <ide> } <del> return err <add> job.Error(err) <add> return engine.StatusErr <ide> } <ide> defer srv.poolRemove("pull", localName+":"+tag) <ide> <ide> // Resolve the Repository name from fqn to endpoint + name <ide> endpoint, remoteName, err := registry.ResolveRepositoryName(localName) <ide> if err != nil { <del> return err <add> job.Error(err) <add> return engine.StatusErr <ide> } <ide> <ide> r, err := registry.NewRegistry(authConfig, srv.HTTPRequestFactory(metaHeaders), endpoint) <ide> if err != nil { <del> return err <add> job.Error(err) <add> return engine.StatusErr <ide> } <ide> <ide> if endpoint == auth.IndexServerAddress() { <ide> // If pull "index.docker.io/foo/bar", it's stored locally under "foo/bar" <ide> localName = remoteName <ide> } <ide> <del> if err = srv.pullRepository(r, out, localName, remoteName, tag, sf, parallel); err != nil { <del> return err <add> if err = srv.pullRepository(r, out, localName, remoteName, tag, sf, job.GetenvBool("parallel")); err != nil { <add> job.Error(err) <add> return engine.StatusErr <ide> } <ide> <del> return nil <add> return engine.StatusOK <ide> } <ide> <ide> // Retrieve the all the images to be uploaded in the correct order <ide> func (srv *Server) ImagePush(localName string, out io.Writer, sf *utils.StreamFo <ide> return nil <ide> } <ide> <del>func (srv *Server) ImageImport(src, repo, tag string, in io.Reader, out io.Writer, sf *utils.StreamFormatter) error { <del> var archive io.Reader <del> var resp *http.Response <add>func (srv *Server) ImageImport(job *engine.Job) engine.Status { <add> if n := len(job.Args); n != 2 && n != 3 { <add> job.Errorf("Usage: %s SRC REPO [TAG]", job.Name) <add> return engine.StatusErr <add> } <add> var ( <add> src = job.Args[0] <add> repo = job.Args[1] <add> tag string <add> sf = utils.NewStreamFormatter(job.GetenvBool("json")) <add> out = utils.NewWriteFlusher(job.Stdout) <add> archive io.Reader <add> resp *http.Response <add> ) <add> if len(job.Args) > 2 { <add> tag = job.Args[2] <add> } <ide> <ide> if src == "-" { <del> archive = in <add> archive = job.Stdin <ide> } else { <ide> u, err := url.Parse(src) <ide> if err != nil { <del> return err <add> job.Error(err) <add> return engine.StatusErr <ide> } <ide> if u.Scheme == "" { <ide> u.Scheme = "http" <ide> func (srv *Server) ImageImport(src, repo, tag string, in io.Reader, out io.Write <ide> // If curl is not available, fallback to http.Get() <ide> resp, err = utils.Download(u.String()) <ide> if err != nil { <del> return err <add> job.Error(err) <add> return engine.StatusErr <ide> } <ide> archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, sf, true, "", "Importing") <ide> } <ide> img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil) <ide> if err != nil { <del> return err <add> job.Error(err) <add> return engine.StatusErr <ide> } <ide> // Optionally register the image at REPO/TAG <ide> if repo != "" { <ide> if err := srv.runtime.repositories.Set(repo, tag, img.ID, true); err != nil { <del> return err <add> job.Error(err) <add> return engine.StatusErr <ide> } <ide> } <ide> out.Write(sf.FormatStatus("", img.ID)) <del> return nil <add> return engine.StatusOK <ide> } <ide> <ide> func (srv *Server) ContainerCreate(job *engine.Job) engine.Status { <ide><path>utils/streamformatter.go <ide> func (sf *StreamFormatter) FormatProgress(id, action string, progress *JSONProgr <ide> func (sf *StreamFormatter) Used() bool { <ide> return sf.used <ide> } <add> <add>func (sf *StreamFormatter) Json() bool { <add> return sf.json <add>}
8
Javascript
Javascript
detect hostname more reliably in url.parse()
1086468aa3d328d2eac00bf66058906553ecd209
<ide><path>lib/url.js <ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { <ide> // Back slashes before the query string get converted to forward slashes <ide> // See: https://code.google.com/p/chromium/issues/detail?id=25916 <ide> let hasHash = false; <add> let hasAt = false; <ide> let start = -1; <ide> let end = -1; <ide> let rest = ''; <ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { <ide> // Only convert backslashes while we haven't seen a split character <ide> if (!split) { <ide> switch (code) { <add> case CHAR_AT: <add> hasAt = true; <add> break; <ide> case CHAR_HASH: <ide> hasHash = true; <ide> // Fall through <ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { <ide> } <ide> } <ide> <del> if (!slashesDenoteHost && !hasHash) { <add> if (!slashesDenoteHost && !hasHash && !hasAt) { <ide> // Try fast path regexp <ide> const simplePath = simplePathPattern.exec(rest); <ide> if (simplePath) { <ide><path>test/parallel/test-url-parse-format.js <ide> const parseTests = { <ide> pathname: '/', <ide> path: '/', <ide> href: 'wss://www.example.com/' <del> } <add> }, <add> <add> '//fhqwhgads@example.com/everybody-to-the-limit': { <add> protocol: null, <add> slashes: true, <add> auth: 'fhqwhgads', <add> host: 'example.com', <add> port: null, <add> hostname: 'example.com', <add> hash: null, <add> search: null, <add> query: null, <add> pathname: '/everybody-to-the-limit', <add> path: '/everybody-to-the-limit', <add> href: '//fhqwhgads@example.com/everybody-to-the-limit' <add> }, <add> <add> '//fhqwhgads@example.com/everybody#to-the-limit': { <add> protocol: null, <add> slashes: true, <add> auth: 'fhqwhgads', <add> host: 'example.com', <add> port: null, <add> hostname: 'example.com', <add> hash: '#to-the-limit', <add> search: null, <add> query: null, <add> pathname: '/everybody', <add> path: '/everybody', <add> href: '//fhqwhgads@example.com/everybody#to-the-limit' <add> }, <ide> }; <ide> <ide> for (const u in parseTests) {
2
Python
Python
add train command to fabfile
dbbfc02bda7bdb784c8be475d22423d969038e0f
<ide><path>fabfile.py <ide> def test(): <ide> with virtualenv(VENV_DIR) as venv_local: <ide> with lcd(path.dirname(__file__)): <ide> venv_local('pytest -x spacy/tests') <add> <add>def train(): <add> args = environ.get('SPACY_TRAIN_ARGS', '') <add> with virtualenv(VENV_DIR) as venv_local: <add> venv_local('spacy train {args}'.format(args=args))
1
Java
Java
add more time for gc in refcounttest.publishnoleak
d9c076061c103ca457d7a9070193498a08e1c282
<ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRefCountTest.java <ide> static final class ExceptionData extends Exception { <ide> } <ide> } <ide> <add> static final int GC_SLEEP_TIME = 250; <add> <ide> @Test <ide> public void publishNoLeak() throws Exception { <del> Thread.sleep(100); <ide> System.gc(); <del> Thread.sleep(100); <del> <del> long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <add> Thread.sleep(GC_SLEEP_TIME); <ide> <ide> source = Flowable.fromCallable(new Callable<Object>() { <ide> @Override <ide> public Object call() throws Exception { <ide> .publish() <ide> .refCount(); <ide> <add> long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <add> <ide> source.subscribe(Functions.emptyConsumer(), Functions.emptyConsumer()); <ide> <del> Thread.sleep(100); <ide> System.gc(); <del> Thread.sleep(200); <add> Thread.sleep(GC_SLEEP_TIME); <ide> <ide> long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <ide> <ide> public Object call() throws Exception { <ide> @Test <ide> public void publishNoLeak2() throws Exception { <ide> System.gc(); <del> Thread.sleep(100); <add> Thread.sleep(GC_SLEEP_TIME); <ide> <ide> long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <ide> <ide> public Object call() throws Exception { <ide> d2 = null; <ide> <ide> System.gc(); <del> Thread.sleep(100); <add> Thread.sleep(GC_SLEEP_TIME); <ide> <ide> long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <ide> <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableRefCountTest.java <ide> static final class ExceptionData extends Exception { <ide> } <ide> } <ide> <add> static final int GC_SLEEP_TIME = 250; <add> <ide> @Test <ide> public void publishNoLeak() throws Exception { <ide> System.gc(); <del> Thread.sleep(100); <del> <del> long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <add> Thread.sleep(GC_SLEEP_TIME); <ide> <ide> source = Observable.fromCallable(new Callable<Object>() { <ide> @Override <ide> public Object call() throws Exception { <ide> .publish() <ide> .refCount(); <ide> <add> long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <add> <ide> source.subscribe(Functions.emptyConsumer(), Functions.emptyConsumer()); <ide> <del> System.gc(); <del> Thread.sleep(100); <add> long after = 0L; <ide> <del> long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <add> for (int i = 0; i < 10; i++) { <add> System.gc(); <add> <add> after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <add> <add> if (start + 20 * 1000 * 1000 > after) { <add> break; <add> } <add> <add> Thread.sleep(GC_SLEEP_TIME); <add> } <ide> <ide> source = null; <ide> assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after); <ide> public Object call() throws Exception { <ide> @Test <ide> public void publishNoLeak2() throws Exception { <ide> System.gc(); <del> Thread.sleep(100); <add> Thread.sleep(GC_SLEEP_TIME); <ide> <ide> long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <ide> <ide> public Object call() throws Exception { <ide> d2 = null; <ide> <ide> System.gc(); <del> Thread.sleep(100); <add> Thread.sleep(GC_SLEEP_TIME); <ide> <ide> long after = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); <ide>
2
Python
Python
fix spancat for zero suggestions
445c670a2d537598b3d562fb7f444050164a260b
<ide><path>spacy/pipeline/spancat.py <ide> def predict(self, docs: Iterable[Doc]): <ide> DOCS: https://spacy.io/api/spancategorizer#predict <ide> """ <ide> indices = self.suggester(docs, ops=self.model.ops) <del> scores = self.model.predict((docs, indices)) # type: ignore <add> if indices.lengths.sum() == 0: <add> scores = self.model.ops.alloc2f(0, 0) <add> else: <add> scores = self.model.predict((docs, indices)) # type: ignore <ide> return indices, scores <ide> <ide> def set_candidates( <ide><path>spacy/tests/pipeline/test_spancat.py <ide> def test_overfitting_IO_overlapping(): <ide> <ide> <ide> def test_zero_suggestions(): <del> # Test with a suggester that returns 0 suggestions <add> # Test with a suggester that can return 0 suggestions <ide> <del> @registry.misc("test_zero_suggester") <del> def make_zero_suggester(): <del> def zero_suggester(docs, *, ops=None): <add> @registry.misc("test_mixed_zero_suggester") <add> def make_mixed_zero_suggester(): <add> def mixed_zero_suggester(docs, *, ops=None): <ide> if ops is None: <ide> ops = get_current_ops() <del> return Ragged( <del> ops.xp.zeros((0, 0), dtype="i"), ops.xp.zeros((len(docs),), dtype="i") <del> ) <del> <del> return zero_suggester <add> spans = [] <add> lengths = [] <add> for doc in docs: <add> if len(doc) > 0 and len(doc) % 2 == 0: <add> spans.append((0, 1)) <add> lengths.append(1) <add> else: <add> lengths.append(0) <add> spans = ops.asarray2i(spans) <add> lengths_array = ops.asarray1i(lengths) <add> if len(spans) > 0: <add> output = Ragged(ops.xp.vstack(spans), lengths_array) <add> else: <add> output = Ragged(ops.xp.zeros((0, 0), dtype="i"), lengths_array) <add> return output <add> <add> return mixed_zero_suggester <ide> <ide> fix_random_seed(0) <ide> nlp = English() <ide> spancat = nlp.add_pipe( <ide> "spancat", <del> config={"suggester": {"@misc": "test_zero_suggester"}, "spans_key": SPAN_KEY}, <add> config={ <add> "suggester": {"@misc": "test_mixed_zero_suggester"}, <add> "spans_key": SPAN_KEY, <add> }, <ide> ) <ide> train_examples = make_examples(nlp) <ide> optimizer = nlp.initialize(get_examples=lambda: train_examples) <ide> assert spancat.model.get_dim("nO") == 2 <ide> assert set(spancat.labels) == {"LOC", "PERSON"} <ide> <ide> nlp.update(train_examples, sgd=optimizer) <add> # empty doc <add> nlp("") <add> # single doc with zero suggestions <add> nlp("one") <add> # single doc with one suggestion <add> nlp("two two") <add> # batch with mixed zero/one suggestions <add> list(nlp.pipe(["one", "two two", "three three three", "", "four four four four"])) <add> # batch with no suggestions <add> list(nlp.pipe(["", "one", "three three three"])) <ide> <ide> <ide> def test_set_candidates():
2
Javascript
Javascript
move shallowrenderer tests
73038840efbaf96bb45095b3fb571bda6beec8a3
<ide><path>src/renderers/dom/test/__tests__/ReactTestUtils-test.js <ide> 'use strict'; <ide> <ide> let createRenderer; <del>let PropTypes; <ide> let React; <ide> let ReactDOM; <ide> let ReactDOMServer; <ide> let ReactTestUtils; <ide> describe('ReactTestUtils', () => { <ide> beforeEach(() => { <ide> createRenderer = require('react-test-renderer/shallow').createRenderer; <del> PropTypes = require('prop-types'); <ide> React = require('react'); <ide> ReactDOM = require('react-dom'); <ide> ReactDOMServer = require('react-dom/server'); <ide> ReactTestUtils = require('react-dom/test-utils'); <ide> }); <ide> <del> it('should call all of the lifecycle hooks', () => { <del> const logs = []; <del> const logger = message => () => logs.push(message) || true; <del> <del> class SomeComponent extends React.Component { <del> componentWillMount = logger('componentWillMount'); <del> componentDidMount = logger('componentDidMount'); <del> componentWillReceiveProps = logger('componentWillReceiveProps'); <del> shouldComponentUpdate = logger('shouldComponentUpdate'); <del> componentWillUpdate = logger('componentWillUpdate'); <del> componentDidUpdate = logger('componentDidUpdate'); <del> componentWillUnmount = logger('componentWillUnmount'); <del> render() { <del> return <div />; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> shallowRenderer.render(<SomeComponent foo={1} />); <del> <del> // Calling cDU might lead to problems with host component references. <del> // Since our components aren't really mounted, refs won't be available. <del> expect(logs).toEqual(['componentWillMount']); <del> <del> logs.splice(0); <del> <del> const instance = shallowRenderer.getMountedInstance(); <del> instance.setState({}); <del> <del> // The previous shallow renderer triggered cDU for setState() calls. <del> expect(logs).toEqual([ <del> 'shouldComponentUpdate', <del> 'componentWillUpdate', <del> 'componentDidUpdate', <del> ]); <del> <del> logs.splice(0); <del> <del> shallowRenderer.render(<SomeComponent foo={2} />); <del> <del> // The previous shallow renderer did not trigger cDU for props changes. <del> expect(logs).toEqual([ <del> 'componentWillReceiveProps', <del> 'shouldComponentUpdate', <del> 'componentWillUpdate', <del> ]); <del> }); <del> <del> it('should only render 1 level deep', () => { <del> function Parent() { <del> return <div><Child /></div>; <del> } <del> function Child() { <del> throw Error('This component should not render'); <del> } <del> <del> const shallowRenderer = createRenderer(); <del> shallowRenderer.render(React.createElement(Parent)); <del> }); <del> <del> it('should have shallow rendering', () => { <del> class SomeComponent extends React.Component { <del> render() { <del> return ( <del> <div> <del> <span className="child1" /> <del> <span className="child2" /> <del> </div> <del> ); <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SomeComponent />); <del> <del> expect(result.type).toBe('div'); <del> expect(result.props.children).toEqual([ <del> <span className="child1" />, <del> <span className="child2" />, <del> ]); <del> }); <del> <del> it('should enable shouldComponentUpdate to prevent a re-render', () => { <del> let renderCounter = 0; <del> class SimpleComponent extends React.Component { <del> state = {update: false}; <del> shouldComponentUpdate(nextProps, nextState) { <del> return this.state.update !== nextState.update; <del> } <del> render() { <del> renderCounter++; <del> return <div>{`${renderCounter}`}</div>; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> shallowRenderer.render(<SimpleComponent />); <del> expect(shallowRenderer.getRenderOutput()).toEqual(<div>1</div>); <del> <del> const instance = shallowRenderer.getMountedInstance(); <del> instance.setState({update: false}); <del> expect(shallowRenderer.getRenderOutput()).toEqual(<div>1</div>); <del> <del> instance.setState({update: true}); <del> expect(shallowRenderer.getRenderOutput()).toEqual(<div>2</div>); <del> }); <del> <del> it('should shallow render a functional component', () => { <del> function SomeComponent(props, context) { <del> return ( <del> <div> <del> <div>{props.foo}</div> <del> <div>{context.bar}</div> <del> <span className="child1" /> <del> <span className="child2" /> <del> </div> <del> ); <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SomeComponent foo={'FOO'} />, { <del> bar: 'BAR', <del> }); <del> <del> expect(result.type).toBe('div'); <del> expect(result.props.children).toEqual([ <del> <div>FOO</div>, <del> <div>BAR</div>, <del> <span className="child1" />, <del> <span className="child2" />, <del> ]); <del> }); <del> <del> it('should shallow render a component returning strings directly from render', () => { <del> const Text = ({value}) => value; <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<Text value="foo" />); <del> expect(result).toEqual('foo'); <del> }); <del> <del> it('should shallow render a component returning numbers directly from render', () => { <del> const Text = ({value}) => value; <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<Text value={10} />); <del> expect(result).toEqual(10); <del> }); <del> <del> it('should shallow render a fragment', () => { <del> class SomeComponent extends React.Component { <del> render() { <del> return <div />; <del> } <del> } <del> class Fragment extends React.Component { <del> render() { <del> return [<div key="a" />, <span key="b" />, <SomeComponent />]; <del> } <del> } <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<Fragment />); <del> expect(result).toEqual([ <del> <div key="a" />, <del> <span key="b" />, <del> <SomeComponent />, <del> ]); <del> }); <del> <del> it('should throw for invalid elements', () => { <del> class SomeComponent extends React.Component { <del> render() { <del> return <div />; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> expect(() => shallowRenderer.render(SomeComponent)).toThrowError( <del> 'ReactShallowRenderer render(): Invalid component element. Instead of ' + <del> 'passing a component class, make sure to instantiate it by passing it ' + <del> 'to React.createElement.', <del> ); <del> expect(() => shallowRenderer.render(<div />)).toThrowError( <del> 'ReactShallowRenderer render(): Shallow rendering works only with ' + <del> 'custom components, not primitives (div). Instead of calling ' + <del> '`.render(el)` and inspecting the rendered output, look at `el.props` ' + <del> 'directly instead.', <del> ); <del> }); <del> <del> it('should have shallow unmounting', () => { <del> const componentWillUnmount = jest.fn(); <del> <del> class SomeComponent extends React.Component { <del> componentWillUnmount = componentWillUnmount; <del> render() { <del> return <div />; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> shallowRenderer.render(<SomeComponent />); <del> shallowRenderer.unmount(); <del> <del> expect(componentWillUnmount).toBeCalled(); <del> }); <del> <del> it('can shallow render to null', () => { <del> class SomeComponent extends React.Component { <del> render() { <del> return null; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SomeComponent />); <del> <del> expect(result).toBe(null); <del> }); <del> <del> it('can shallow render with a ref', () => { <del> class SomeComponent extends React.Component { <del> render() { <del> return <div ref="hello" />; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> // Shouldn't crash. <del> shallowRenderer.render(<SomeComponent />); <del> }); <del> <del> it('lets you update shallowly rendered components', () => { <del> class SomeComponent extends React.Component { <del> state = {clicked: false}; <del> <del> onClick = () => { <del> this.setState({clicked: true}); <del> }; <del> <del> render() { <del> const className = this.state.clicked ? 'was-clicked' : ''; <del> <del> if (this.props.aNew === 'prop') { <del> return ( <del> <a href="#" onClick={this.onClick} className={className}> <del> Test link <del> </a> <del> ); <del> } else { <del> return ( <del> <div> <del> <span className="child1" /> <del> <span className="child2" /> <del> </div> <del> ); <del> } <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SomeComponent />); <del> expect(result.type).toBe('div'); <del> expect(result.props.children).toEqual([ <del> <span className="child1" />, <del> <span className="child2" />, <del> ]); <del> <del> const updatedResult = shallowRenderer.render(<SomeComponent aNew="prop" />); <del> expect(updatedResult.type).toBe('a'); <del> <del> const mockEvent = {}; <del> updatedResult.props.onClick(mockEvent); <del> <del> const updatedResultCausedByClick = shallowRenderer.getRenderOutput(); <del> expect(updatedResultCausedByClick.type).toBe('a'); <del> expect(updatedResultCausedByClick.props.className).toBe('was-clicked'); <del> }); <del> <del> it('can access the mounted component instance', () => { <del> class SimpleComponent extends React.Component { <del> someMethod = () => { <del> return this.props.n; <del> }; <del> <del> render() { <del> return <div>{this.props.n}</div>; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> shallowRenderer.render(<SimpleComponent n={5} />); <del> expect(shallowRenderer.getMountedInstance().someMethod()).toEqual(5); <del> }); <del> <del> it('can shallowly render components with contextTypes', () => { <del> class SimpleComponent extends React.Component { <del> static contextTypes = { <del> name: PropTypes.string, <del> }; <del> <del> render() { <del> return <div />; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SimpleComponent />); <del> expect(result).toEqual(<div />); <del> }); <del> <del> it('can shallowly render components with ref as function', () => { <del> class SimpleComponent extends React.Component { <del> state = {clicked: false}; <del> <del> handleUserClick = () => { <del> this.setState({clicked: true}); <del> }; <del> <del> render() { <del> return ( <del> <div <del> ref={() => {}} <del> onClick={this.handleUserClick} <del> className={this.state.clicked ? 'clicked' : ''} <del> /> <del> ); <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> shallowRenderer.render(<SimpleComponent />); <del> let result = shallowRenderer.getRenderOutput(); <del> expect(result.type).toEqual('div'); <del> expect(result.props.className).toEqual(''); <del> result.props.onClick(); <del> <del> result = shallowRenderer.getRenderOutput(); <del> expect(result.type).toEqual('div'); <del> expect(result.props.className).toEqual('clicked'); <del> }); <del> <del> it('can setState in componentWillMount when shallow rendering', () => { <del> class SimpleComponent extends React.Component { <del> componentWillMount() { <del> this.setState({groovy: 'doovy'}); <del> } <del> <del> render() { <del> return <div>{this.state.groovy}</div>; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SimpleComponent />); <del> expect(result).toEqual(<div>doovy</div>); <del> }); <del> <del> it('can setState in componentWillReceiveProps when shallow rendering', () => { <del> class SimpleComponent extends React.Component { <del> state = {count: 0}; <del> <del> componentWillReceiveProps(nextProps) { <del> if (nextProps.updateState) { <del> this.setState({count: 1}); <del> } <del> } <del> <del> render() { <del> return <div>{this.state.count}</div>; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> let result = shallowRenderer.render( <del> <SimpleComponent updateState={false} />, <del> ); <del> expect(result.props.children).toEqual(0); <del> <del> result = shallowRenderer.render(<SimpleComponent updateState={true} />); <del> expect(result.props.children).toEqual(1); <del> }); <del> <del> it('can setState with an updater function', () => { <del> let instance; <del> <del> class SimpleComponent extends React.Component { <del> state = { <del> counter: 0, <del> }; <del> <del> render() { <del> instance = this; <del> return ( <del> <button ref="button" onClick={this.onClick}> <del> {this.state.counter} <del> </button> <del> ); <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> let result = shallowRenderer.render(<SimpleComponent defaultCount={1} />); <del> expect(result.props.children).toEqual(0); <del> <del> instance.setState((state, props) => { <del> return {counter: props.defaultCount + 1}; <del> }); <del> <del> result = shallowRenderer.getRenderOutput(); <del> expect(result.props.children).toEqual(2); <del> }); <del> <del> it('can setState with a callback', () => { <del> let instance; <del> <del> class SimpleComponent extends React.Component { <del> state = { <del> counter: 0, <del> }; <del> render() { <del> instance = this; <del> return ( <del> <p> <del> {this.state.counter} <del> </p> <del> ); <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SimpleComponent />); <del> expect(result.props.children).toBe(0); <del> <del> const callback = jest.fn(function() { <del> expect(this).toBe(instance); <del> }); <del> <del> instance.setState({counter: 1}, callback); <del> <del> const updated = shallowRenderer.getRenderOutput(); <del> expect(updated.props.children).toBe(1); <del> expect(callback).toHaveBeenCalled(); <del> }); <del> <del> it('can replaceState with a callback', () => { <del> let instance; <del> <del> class SimpleComponent extends React.Component { <del> state = { <del> counter: 0, <del> }; <del> render() { <del> instance = this; <del> return ( <del> <p> <del> {this.state.counter} <del> </p> <del> ); <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SimpleComponent />); <del> expect(result.props.children).toBe(0); <del> <del> const callback = jest.fn(function() { <del> expect(this).toBe(instance); <del> }); <del> <del> // No longer a public API, but we can test that it works internally by <del> // reaching into the updater. <del> shallowRenderer._updater.enqueueReplaceState( <del> instance, <del> {counter: 1}, <del> callback, <del> ); <del> <del> const updated = shallowRenderer.getRenderOutput(); <del> expect(updated.props.children).toBe(1); <del> expect(callback).toHaveBeenCalled(); <del> }); <del> <del> it('can forceUpdate with a callback', () => { <del> let instance; <del> <del> class SimpleComponent extends React.Component { <del> state = { <del> counter: 0, <del> }; <del> render() { <del> instance = this; <del> return ( <del> <p> <del> {this.state.counter} <del> </p> <del> ); <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SimpleComponent />); <del> expect(result.props.children).toBe(0); <del> <del> const callback = jest.fn(function() { <del> expect(this).toBe(instance); <del> }); <del> <del> instance.forceUpdate(callback); <del> <del> const updated = shallowRenderer.getRenderOutput(); <del> expect(updated.props.children).toBe(0); <del> expect(callback).toHaveBeenCalled(); <del> }); <del> <del> it('can pass context when shallowly rendering', () => { <del> class SimpleComponent extends React.Component { <del> static contextTypes = { <del> name: PropTypes.string, <del> }; <del> <del> render() { <del> return <div>{this.context.name}</div>; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> const result = shallowRenderer.render(<SimpleComponent />, { <del> name: 'foo', <del> }); <del> expect(result).toEqual(<div>foo</div>); <del> }); <del> <del> it('should track context across updates', () => { <del> class SimpleComponent extends React.Component { <del> static contextTypes = { <del> foo: PropTypes.string, <del> }; <del> <del> state = { <del> bar: 'bar', <del> }; <del> <del> render() { <del> return <div>{`${this.context.foo}:${this.state.bar}`}</div>; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> let result = shallowRenderer.render(<SimpleComponent />, { <del> foo: 'foo', <del> }); <del> expect(result).toEqual(<div>foo:bar</div>); <del> <del> const instance = shallowRenderer.getMountedInstance(); <del> instance.setState({bar: 'baz'}); <del> <del> result = shallowRenderer.getRenderOutput(); <del> expect(result).toEqual(<div>foo:baz</div>); <del> }); <del> <del> it('can fail context when shallowly rendering', () => { <del> spyOn(console, 'error'); <del> <del> class SimpleComponent extends React.Component { <del> static contextTypes = { <del> name: PropTypes.string.isRequired, <del> }; <del> <del> render() { <del> return <div>{this.context.name}</div>; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> shallowRenderer.render(<SimpleComponent />); <del> expectDev(console.error.calls.count()).toBe(1); <del> expect( <del> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'), <del> ).toBe( <del> 'Warning: Failed context type: The context `name` is marked as ' + <del> 'required in `SimpleComponent`, but its value is `undefined`.\n' + <del> ' in SimpleComponent (at **)', <del> ); <del> }); <del> <del> it('should warn about propTypes (but only once)', () => { <del> spyOn(console, 'error'); <del> <del> class SimpleComponent extends React.Component { <del> render() { <del> return React.createElement('div', null, this.props.name); <del> } <del> } <del> <del> SimpleComponent.propTypes = { <del> name: PropTypes.string.isRequired, <del> }; <del> <del> const shallowRenderer = createRenderer(); <del> shallowRenderer.render(React.createElement(SimpleComponent, {name: 123})); <del> <del> expect(console.error.calls.count()).toBe(1); <del> expect( <del> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'), <del> ).toBe( <del> 'Warning: Failed prop type: Invalid prop `name` of type `number` ' + <del> 'supplied to `SimpleComponent`, expected `string`.\n' + <del> ' in SimpleComponent', <del> ); <del> }); <del> <ide> it('can scryRenderedDOMComponentsWithClass with TextComponent', () => { <ide> class Wrapper extends React.Component { <ide> render() { <ide> describe('ReactTestUtils', () => { <ide> expect(hrs.length).toBe(2); <ide> }); <ide> <del> it('should enable rendering of cloned element', () => { <del> class SimpleComponent extends React.Component { <del> constructor(props) { <del> super(props); <del> <del> this.state = { <del> bar: 'bar', <del> }; <del> } <del> <del> render() { <del> return <div>{`${this.props.foo}:${this.state.bar}`}</div>; <del> } <del> } <del> <del> const shallowRenderer = createRenderer(); <del> let result = shallowRenderer.render(<SimpleComponent foo="foo" />); <del> expect(result).toEqual(<div>foo:bar</div>); <del> <del> const instance = shallowRenderer.getMountedInstance(); <del> const cloned = React.cloneElement(instance, {foo: 'baz'}); <del> result = shallowRenderer.render(cloned); <del> expect(result).toEqual(<div>baz:bar</div>); <del> }); <del> <ide> describe('Simulate', () => { <ide> it('should set the type of the event', () => { <ide> let event; <ide><path>src/renderers/testing/__tests__/ReactShallowRenderer-test.js <add>/** <add> * Copyright 2013-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @emails react-core <add> */ <add> <add>'use strict'; <add> <add>let createRenderer; <add>let PropTypes; <add>let React; <add> <add>describe('ReactTestUtils', () => { <add> beforeEach(() => { <add> createRenderer = require('react-test-renderer/shallow').createRenderer; <add> PropTypes = require('prop-types'); <add> React = require('react'); <add> }); <add> <add> it('should call all of the lifecycle hooks', () => { <add> const logs = []; <add> const logger = message => () => logs.push(message) || true; <add> <add> class SomeComponent extends React.Component { <add> componentWillMount = logger('componentWillMount'); <add> componentDidMount = logger('componentDidMount'); <add> componentWillReceiveProps = logger('componentWillReceiveProps'); <add> shouldComponentUpdate = logger('shouldComponentUpdate'); <add> componentWillUpdate = logger('componentWillUpdate'); <add> componentDidUpdate = logger('componentDidUpdate'); <add> componentWillUnmount = logger('componentWillUnmount'); <add> render() { <add> return <div />; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> shallowRenderer.render(<SomeComponent foo={1} />); <add> <add> // Calling cDU might lead to problems with host component references. <add> // Since our components aren't really mounted, refs won't be available. <add> expect(logs).toEqual(['componentWillMount']); <add> <add> logs.splice(0); <add> <add> const instance = shallowRenderer.getMountedInstance(); <add> instance.setState({}); <add> <add> // The previous shallow renderer triggered cDU for setState() calls. <add> expect(logs).toEqual([ <add> 'shouldComponentUpdate', <add> 'componentWillUpdate', <add> 'componentDidUpdate', <add> ]); <add> <add> logs.splice(0); <add> <add> shallowRenderer.render(<SomeComponent foo={2} />); <add> <add> // The previous shallow renderer did not trigger cDU for props changes. <add> expect(logs).toEqual([ <add> 'componentWillReceiveProps', <add> 'shouldComponentUpdate', <add> 'componentWillUpdate', <add> ]); <add> }); <add> <add> it('should only render 1 level deep', () => { <add> function Parent() { <add> return <div><Child /></div>; <add> } <add> function Child() { <add> throw Error('This component should not render'); <add> } <add> <add> const shallowRenderer = createRenderer(); <add> shallowRenderer.render(React.createElement(Parent)); <add> }); <add> <add> it('should have shallow rendering', () => { <add> class SomeComponent extends React.Component { <add> render() { <add> return ( <add> <div> <add> <span className="child1" /> <add> <span className="child2" /> <add> </div> <add> ); <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SomeComponent />); <add> <add> expect(result.type).toBe('div'); <add> expect(result.props.children).toEqual([ <add> <span className="child1" />, <add> <span className="child2" />, <add> ]); <add> }); <add> <add> it('should enable shouldComponentUpdate to prevent a re-render', () => { <add> let renderCounter = 0; <add> class SimpleComponent extends React.Component { <add> state = {update: false}; <add> shouldComponentUpdate(nextProps, nextState) { <add> return this.state.update !== nextState.update; <add> } <add> render() { <add> renderCounter++; <add> return <div>{`${renderCounter}`}</div>; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> shallowRenderer.render(<SimpleComponent />); <add> expect(shallowRenderer.getRenderOutput()).toEqual(<div>1</div>); <add> <add> const instance = shallowRenderer.getMountedInstance(); <add> instance.setState({update: false}); <add> expect(shallowRenderer.getRenderOutput()).toEqual(<div>1</div>); <add> <add> instance.setState({update: true}); <add> expect(shallowRenderer.getRenderOutput()).toEqual(<div>2</div>); <add> }); <add> <add> it('should shallow render a functional component', () => { <add> function SomeComponent(props, context) { <add> return ( <add> <div> <add> <div>{props.foo}</div> <add> <div>{context.bar}</div> <add> <span className="child1" /> <add> <span className="child2" /> <add> </div> <add> ); <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SomeComponent foo={'FOO'} />, { <add> bar: 'BAR', <add> }); <add> <add> expect(result.type).toBe('div'); <add> expect(result.props.children).toEqual([ <add> <div>FOO</div>, <add> <div>BAR</div>, <add> <span className="child1" />, <add> <span className="child2" />, <add> ]); <add> }); <add> <add> it('should shallow render a component returning strings directly from render', () => { <add> const Text = ({value}) => value; <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<Text value="foo" />); <add> expect(result).toEqual('foo'); <add> }); <add> <add> it('should shallow render a component returning numbers directly from render', () => { <add> const Text = ({value}) => value; <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<Text value={10} />); <add> expect(result).toEqual(10); <add> }); <add> <add> it('should shallow render a fragment', () => { <add> class SomeComponent extends React.Component { <add> render() { <add> return <div />; <add> } <add> } <add> class Fragment extends React.Component { <add> render() { <add> return [<div key="a" />, <span key="b" />, <SomeComponent />]; <add> } <add> } <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<Fragment />); <add> expect(result).toEqual([ <add> <div key="a" />, <add> <span key="b" />, <add> <SomeComponent />, <add> ]); <add> }); <add> <add> it('should throw for invalid elements', () => { <add> class SomeComponent extends React.Component { <add> render() { <add> return <div />; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> expect(() => shallowRenderer.render(SomeComponent)).toThrowError( <add> 'ReactShallowRenderer render(): Invalid component element. Instead of ' + <add> 'passing a component class, make sure to instantiate it by passing it ' + <add> 'to React.createElement.', <add> ); <add> expect(() => shallowRenderer.render(<div />)).toThrowError( <add> 'ReactShallowRenderer render(): Shallow rendering works only with ' + <add> 'custom components, not primitives (div). Instead of calling ' + <add> '`.render(el)` and inspecting the rendered output, look at `el.props` ' + <add> 'directly instead.', <add> ); <add> }); <add> <add> it('should have shallow unmounting', () => { <add> const componentWillUnmount = jest.fn(); <add> <add> class SomeComponent extends React.Component { <add> componentWillUnmount = componentWillUnmount; <add> render() { <add> return <div />; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> shallowRenderer.render(<SomeComponent />); <add> shallowRenderer.unmount(); <add> <add> expect(componentWillUnmount).toBeCalled(); <add> }); <add> <add> it('can shallow render to null', () => { <add> class SomeComponent extends React.Component { <add> render() { <add> return null; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SomeComponent />); <add> <add> expect(result).toBe(null); <add> }); <add> <add> it('can shallow render with a ref', () => { <add> class SomeComponent extends React.Component { <add> render() { <add> return <div ref="hello" />; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> // Shouldn't crash. <add> shallowRenderer.render(<SomeComponent />); <add> }); <add> <add> it('lets you update shallowly rendered components', () => { <add> class SomeComponent extends React.Component { <add> state = {clicked: false}; <add> <add> onClick = () => { <add> this.setState({clicked: true}); <add> }; <add> <add> render() { <add> const className = this.state.clicked ? 'was-clicked' : ''; <add> <add> if (this.props.aNew === 'prop') { <add> return ( <add> <a href="#" onClick={this.onClick} className={className}> <add> Test link <add> </a> <add> ); <add> } else { <add> return ( <add> <div> <add> <span className="child1" /> <add> <span className="child2" /> <add> </div> <add> ); <add> } <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SomeComponent />); <add> expect(result.type).toBe('div'); <add> expect(result.props.children).toEqual([ <add> <span className="child1" />, <add> <span className="child2" />, <add> ]); <add> <add> const updatedResult = shallowRenderer.render(<SomeComponent aNew="prop" />); <add> expect(updatedResult.type).toBe('a'); <add> <add> const mockEvent = {}; <add> updatedResult.props.onClick(mockEvent); <add> <add> const updatedResultCausedByClick = shallowRenderer.getRenderOutput(); <add> expect(updatedResultCausedByClick.type).toBe('a'); <add> expect(updatedResultCausedByClick.props.className).toBe('was-clicked'); <add> }); <add> <add> it('can access the mounted component instance', () => { <add> class SimpleComponent extends React.Component { <add> someMethod = () => { <add> return this.props.n; <add> }; <add> <add> render() { <add> return <div>{this.props.n}</div>; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> shallowRenderer.render(<SimpleComponent n={5} />); <add> expect(shallowRenderer.getMountedInstance().someMethod()).toEqual(5); <add> }); <add> <add> it('can shallowly render components with contextTypes', () => { <add> class SimpleComponent extends React.Component { <add> static contextTypes = { <add> name: PropTypes.string, <add> }; <add> <add> render() { <add> return <div />; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SimpleComponent />); <add> expect(result).toEqual(<div />); <add> }); <add> <add> it('can shallowly render components with ref as function', () => { <add> class SimpleComponent extends React.Component { <add> state = {clicked: false}; <add> <add> handleUserClick = () => { <add> this.setState({clicked: true}); <add> }; <add> <add> render() { <add> return ( <add> <div <add> ref={() => {}} <add> onClick={this.handleUserClick} <add> className={this.state.clicked ? 'clicked' : ''} <add> /> <add> ); <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> shallowRenderer.render(<SimpleComponent />); <add> let result = shallowRenderer.getRenderOutput(); <add> expect(result.type).toEqual('div'); <add> expect(result.props.className).toEqual(''); <add> result.props.onClick(); <add> <add> result = shallowRenderer.getRenderOutput(); <add> expect(result.type).toEqual('div'); <add> expect(result.props.className).toEqual('clicked'); <add> }); <add> <add> it('can setState in componentWillMount when shallow rendering', () => { <add> class SimpleComponent extends React.Component { <add> componentWillMount() { <add> this.setState({groovy: 'doovy'}); <add> } <add> <add> render() { <add> return <div>{this.state.groovy}</div>; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SimpleComponent />); <add> expect(result).toEqual(<div>doovy</div>); <add> }); <add> <add> it('can setState in componentWillReceiveProps when shallow rendering', () => { <add> class SimpleComponent extends React.Component { <add> state = {count: 0}; <add> <add> componentWillReceiveProps(nextProps) { <add> if (nextProps.updateState) { <add> this.setState({count: 1}); <add> } <add> } <add> <add> render() { <add> return <div>{this.state.count}</div>; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> let result = shallowRenderer.render( <add> <SimpleComponent updateState={false} />, <add> ); <add> expect(result.props.children).toEqual(0); <add> <add> result = shallowRenderer.render(<SimpleComponent updateState={true} />); <add> expect(result.props.children).toEqual(1); <add> }); <add> <add> it('can setState with an updater function', () => { <add> let instance; <add> <add> class SimpleComponent extends React.Component { <add> state = { <add> counter: 0, <add> }; <add> <add> render() { <add> instance = this; <add> return ( <add> <button ref="button" onClick={this.onClick}> <add> {this.state.counter} <add> </button> <add> ); <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> let result = shallowRenderer.render(<SimpleComponent defaultCount={1} />); <add> expect(result.props.children).toEqual(0); <add> <add> instance.setState((state, props) => { <add> return {counter: props.defaultCount + 1}; <add> }); <add> <add> result = shallowRenderer.getRenderOutput(); <add> expect(result.props.children).toEqual(2); <add> }); <add> <add> it('can setState with a callback', () => { <add> let instance; <add> <add> class SimpleComponent extends React.Component { <add> state = { <add> counter: 0, <add> }; <add> render() { <add> instance = this; <add> return ( <add> <p> <add> {this.state.counter} <add> </p> <add> ); <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SimpleComponent />); <add> expect(result.props.children).toBe(0); <add> <add> const callback = jest.fn(function() { <add> expect(this).toBe(instance); <add> }); <add> <add> instance.setState({counter: 1}, callback); <add> <add> const updated = shallowRenderer.getRenderOutput(); <add> expect(updated.props.children).toBe(1); <add> expect(callback).toHaveBeenCalled(); <add> }); <add> <add> it('can replaceState with a callback', () => { <add> let instance; <add> <add> class SimpleComponent extends React.Component { <add> state = { <add> counter: 0, <add> }; <add> render() { <add> instance = this; <add> return ( <add> <p> <add> {this.state.counter} <add> </p> <add> ); <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SimpleComponent />); <add> expect(result.props.children).toBe(0); <add> <add> const callback = jest.fn(function() { <add> expect(this).toBe(instance); <add> }); <add> <add> // No longer a public API, but we can test that it works internally by <add> // reaching into the updater. <add> shallowRenderer._updater.enqueueReplaceState( <add> instance, <add> {counter: 1}, <add> callback, <add> ); <add> <add> const updated = shallowRenderer.getRenderOutput(); <add> expect(updated.props.children).toBe(1); <add> expect(callback).toHaveBeenCalled(); <add> }); <add> <add> it('can forceUpdate with a callback', () => { <add> let instance; <add> <add> class SimpleComponent extends React.Component { <add> state = { <add> counter: 0, <add> }; <add> render() { <add> instance = this; <add> return ( <add> <p> <add> {this.state.counter} <add> </p> <add> ); <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SimpleComponent />); <add> expect(result.props.children).toBe(0); <add> <add> const callback = jest.fn(function() { <add> expect(this).toBe(instance); <add> }); <add> <add> instance.forceUpdate(callback); <add> <add> const updated = shallowRenderer.getRenderOutput(); <add> expect(updated.props.children).toBe(0); <add> expect(callback).toHaveBeenCalled(); <add> }); <add> <add> it('can pass context when shallowly rendering', () => { <add> class SimpleComponent extends React.Component { <add> static contextTypes = { <add> name: PropTypes.string, <add> }; <add> <add> render() { <add> return <div>{this.context.name}</div>; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> const result = shallowRenderer.render(<SimpleComponent />, { <add> name: 'foo', <add> }); <add> expect(result).toEqual(<div>foo</div>); <add> }); <add> <add> it('should track context across updates', () => { <add> class SimpleComponent extends React.Component { <add> static contextTypes = { <add> foo: PropTypes.string, <add> }; <add> <add> state = { <add> bar: 'bar', <add> }; <add> <add> render() { <add> return <div>{`${this.context.foo}:${this.state.bar}`}</div>; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> let result = shallowRenderer.render(<SimpleComponent />, { <add> foo: 'foo', <add> }); <add> expect(result).toEqual(<div>foo:bar</div>); <add> <add> const instance = shallowRenderer.getMountedInstance(); <add> instance.setState({bar: 'baz'}); <add> <add> result = shallowRenderer.getRenderOutput(); <add> expect(result).toEqual(<div>foo:baz</div>); <add> }); <add> <add> it('can fail context when shallowly rendering', () => { <add> spyOn(console, 'error'); <add> <add> class SimpleComponent extends React.Component { <add> static contextTypes = { <add> name: PropTypes.string.isRequired, <add> }; <add> <add> render() { <add> return <div>{this.context.name}</div>; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> shallowRenderer.render(<SimpleComponent />); <add> expectDev(console.error.calls.count()).toBe(1); <add> expect( <add> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'), <add> ).toBe( <add> 'Warning: Failed context type: The context `name` is marked as ' + <add> 'required in `SimpleComponent`, but its value is `undefined`.\n' + <add> ' in SimpleComponent (at **)', <add> ); <add> }); <add> <add> it('should warn about propTypes (but only once)', () => { <add> spyOn(console, 'error'); <add> <add> class SimpleComponent extends React.Component { <add> render() { <add> return React.createElement('div', null, this.props.name); <add> } <add> } <add> <add> SimpleComponent.propTypes = { <add> name: PropTypes.string.isRequired, <add> }; <add> <add> const shallowRenderer = createRenderer(); <add> shallowRenderer.render(React.createElement(SimpleComponent, {name: 123})); <add> <add> expect(console.error.calls.count()).toBe(1); <add> expect( <add> console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'), <add> ).toBe( <add> 'Warning: Failed prop type: Invalid prop `name` of type `number` ' + <add> 'supplied to `SimpleComponent`, expected `string`.\n' + <add> ' in SimpleComponent', <add> ); <add> }); <add> <add> it('should enable rendering of cloned element', () => { <add> class SimpleComponent extends React.Component { <add> constructor(props) { <add> super(props); <add> <add> this.state = { <add> bar: 'bar', <add> }; <add> } <add> <add> render() { <add> return <div>{`${this.props.foo}:${this.state.bar}`}</div>; <add> } <add> } <add> <add> const shallowRenderer = createRenderer(); <add> let result = shallowRenderer.render(<SimpleComponent foo="foo" />); <add> expect(result).toEqual(<div>foo:bar</div>); <add> <add> const instance = shallowRenderer.getMountedInstance(); <add> const cloned = React.cloneElement(instance, {foo: 'baz'}); <add> result = shallowRenderer.render(cloned); <add> expect(result).toEqual(<div>baz:bar</div>); <add> }); <add>});
2
PHP
PHP
dump specific key of the response
081f467ade3cea2edf7d581e20a3772c882029f5
<ide><path>src/Illuminate/Testing/TestResponse.php <ide> protected function session() <ide> /** <ide> * Dump the content from the response. <ide> * <add> * @param string|null $key <ide> * @return $this <ide> */ <del> public function dump() <add> public function dump($key = null) <ide> { <ide> $content = $this->getContent(); <ide> <ide> public function dump() <ide> $content = $json; <ide> } <ide> <del> dump($content); <add> if (! is_null($key)) { <add> dump(data_get($content, $key)); <add> } else { <add> dump($content); <add> } <ide> <ide> return $this; <ide> }
1
Ruby
Ruby
autorequire bundled libraries by default
db15e49ddf64afd982ddb52e7d0487314f7dcf97
<ide><path>railties/lib/generators/rails/app/templates/config/boot.rb <ide> # require 'rubygems' <ide> end <ide> <add># Auto-require all bundled libraries. <add>Bundler.require <add> <ide> <% unless options[:skip_activerecord] -%> <ide> require 'rails/all' <ide> <ide> require "action_mailer/railtie" <ide> require "active_resource/railtie" <ide> require "rails/test_unit/railtie" <del><% end -%> <ide>\ No newline at end of file <add><% end -%>
1
Javascript
Javascript
add sortableset as a new collection type
0eaa84748ddecf37896dee3d0aad8d38f68bbe3e
<ide><path>lib/util/SortableSet.js <add>"use strict"; <add> <add>module.exports = class SortableSet extends Set { <add> <add> constructor(initialIterable, defaultSort) { <add> super(initialIterable); <add> this._sortFn = defaultSort; <add> } <add> <add> /** <add> * @param {Function} sortFn - function to sort the set <add> * @returns {void} <add> */ <add> sortWith(sortFn) { <add> const sortedArray = Array.from(this).sort(sortFn); <add> this.clear(); <add> for(let i = 0; i < sortedArray.length; i += 1) { <add> this.add(sortedArray[i]); <add> } <add> } <add> <add> /** <add> * @returns {void} <add> */ <add> sort() { <add> this.sortWith(this._sortFn); <add> } <add>};
1
Javascript
Javascript
fix ie7 regression in jqlite which prevented
f7a9ea6a418f6201638556b0925388e67a8b1b12
<ide><path>src/Angular.js <ide> var _undefined = undefined, <ide> msie = parseInt((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1], 10), <ide> jqLite, // delay binding since jQuery could be loaded after us. <ide> jQuery, // delay binding <del> slice = Array.prototype.slice, <del> push = Array.prototype.push, <add> slice = [].slice, <add> push = [].push, <ide> error = window[$console] <ide> ? bind(window[$console], window[$console]['error'] || noop) <ide> : noop, <ide><path>src/jqLite.js <ide> function JQLiteAddNodes(root, elements) { <ide> ////////////////////////////////////////// <ide> // Functions which are declared directly. <ide> ////////////////////////////////////////// <del>var JQLitePrototype = JQLite.prototype = extend([], { <add>var JQLitePrototype = JQLite.prototype = { <ide> ready: function(fn) { <ide> var fired = false; <ide> <ide> var JQLitePrototype = JQLite.prototype = extend([], { <ide> var value = []; <ide> forEach(this, function(e){ value.push('' + e);}); <ide> return '[' + value.join(', ') + ']'; <del> } <del>}); <add> }, <add> length: 0, <add> push: push, <add> sort: [].sort, <add> splice: [].splice <add>}; <ide> <ide> ////////////////////////////////////////// <ide> // Functions iterating getter/setters.
2
Ruby
Ruby
remove unused variables
6c04ccfb3bf9d71b700ab44b32a508766b8cdcf9
<ide><path>Library/Homebrew/cmd/install.rb <ide> def install <ide> require 'cmd/tap' <ide> begin <ide> install_tap $1, $2 <del> rescue AlreadyTappedError => e <add> rescue AlreadyTappedError <ide> end <ide> end <ide> end unless ARGV.force? <ide><path>Library/Homebrew/cmd/update.rb <ide> def update <ide> tap_user, tap_repo = migration.split '/' <ide> begin <ide> install_tap tap_user, tap_repo <del> rescue AlreadyTappedError => e <add> rescue AlreadyTappedError <ide> end <ide> end if load_tap_migrations <ide>
2
Ruby
Ruby
define jruby_skip to skip test on jruby
e998edd2c02667af53dd55cff1b37a6d4661c181
<ide><path>activesupport/test/abstract_unit.rb <ide> <ide> # Show backtraces for deprecated behavior for quicker cleanup. <ide> ActiveSupport::Deprecation.debug = true <add> <add># Skips the current run on JRuby using Minitest::Assertions#skip <add>def jruby_skip(message = '') <add> skip message if RUBY_ENGINE == 'jruby' <add>end
1
Text
Text
update the react 18 documentation
ec2e107f7fefb5d13402c2888ffea33bfe78bebe
<ide><path>docs/advanced-features/react-18.md <ide> Ensure you have the `rc` npm tag of React installed: <ide> npm install next@latest react@rc react-dom@rc <ide> ``` <ide> <add>That's all! You can now start using React 18's new APIs like `startTransition` and Suspense in Next.js. <add> <ide> ### Enable SSR Streaming (Alpha) <ide> <ide> Concurrent features in React 18 include built-in support for server-side Suspense and SSR streaming support, allowing you to server-render pages using HTTP streaming.
1
Ruby
Ruby
show correct helper in description
851275e706977ddbfa05a9f23c60861904443f18
<ide><path>actionpack/lib/action_view/helpers/date_helper.rb <ide> def select_time(datetime = Time.current, options = {}, html_options = {}) <ide> # <ide> # # Generates a select field for seconds with a custom prompt. Use <tt>:prompt => true</tt> for a <ide> # # generic prompt. <del> # select_minute(14, :prompt => 'Choose seconds') <add> # select_second(14, :prompt => 'Choose seconds') <ide> # <ide> def select_second(datetime, options = {}, html_options = {}) <ide> DateTimeSelector.new(datetime, options, html_options).select_second
1
Java
Java
improve error message for json path expressions
b47d97c23a24a10305c8a82ba4acc823ce52f088
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java <ide> package org.springframework.test.util; <ide> <ide> import static org.springframework.test.util.AssertionErrors.assertEquals; <del>import static org.springframework.test.util.AssertionErrors.*; <add>import static org.springframework.test.util.AssertionErrors.assertTrue; <add>import static org.springframework.test.util.AssertionErrors.fail; <ide> import static org.springframework.test.util.MatcherAssertionErrors.assertThat; <ide> <ide> import java.text.ParseException; <ide> public void assertValue(String responseContent, Object expectedValue) throws Par <ide> } <ide> actualValue = actualValueList.get(0); <ide> } <add> else if (actualValue != null && expectedValue != null) { <add> assertEquals("For JSON path " + this.expression + " type of value", <add> expectedValue.getClass(), actualValue.getClass()); <add> } <ide> assertEquals("JSON path" + this.expression, expectedValue, actualValue); <ide> } <ide> <ide><path>spring-test-mvc/src/test/java/org/springframework/test/util/JsonPathExpectationsHelperTests.java <add>/* <add> * Copyright 2004-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.test.util; <add> <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.fail; <add> <add>import org.junit.Test; <add> <add> <add>/** <add> * Test fixture for {@link JsonPathExpectationsHelper}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class JsonPathExpectationsHelperTests { <add> <add> <add> @Test <add> public void test() throws Exception { <add> try { <add> new JsonPathExpectationsHelper("$.nr").assertValue("{ \"nr\" : 5 }", "5"); <add> fail("Expected exception"); <add> } <add> catch (AssertionError ex) { <add> assertEquals("For JSON path $.nr type of value expected:<class java.lang.String> but was:<class java.lang.Integer>", <add> ex.getMessage()); <add> } <add> } <add> <add>}
2
Javascript
Javascript
fix a typo
33cd29b3a30239f8836381f3163e5b9ff233d6b4
<ide><path>test/helpers/testabilityPatch.js <ide> afterEach(function() { <ide> // These Nodes are persisted across tests. <ide> // They used to be assigned a `$$hashKey` when animated, which we needed to clear after each test <ide> // to avoid affecting other tests. This is no longer the case, so we are just ensuring that there <del> // is indeed no `$$hachKey` on them. <add> // is indeed no `$$hashKey` on them. <ide> var doc = window.document; <ide> var html = doc.querySelector('html'); <ide> var body = doc.body;
1
Java
Java
fix javadoc for @value
80ad60e91ba2492889cd689f576b4e5902c95048
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/annotation/Value.java <ide> * for dynamic resolution of handler method parameters, e.g. in Spring MVC. <ide> * <ide> * <p>A common use case is to assign default field values using <del> * {@code #{systemProperties.myProp}} style expressions. <add> * <code>#{systemProperties.myProp}</code> style expressions. <ide> * <ide> * <p>Note that actual processing of the {@code @Value} annotation is performed <ide> * by a {@link org.springframework.beans.factory.config.BeanPostProcessor <ide> public @interface Value { <ide> <ide> /** <del> * The actual value expression: for example {@code #{systemProperties.myProp}}. <add> * The actual value expression &mdash; for example, <code>#{systemProperties.myProp}</code>. <ide> */ <ide> String value(); <ide>
1
PHP
PHP
remove special sqlite order by logic
d36c18a3188e2a0be40549731cc79b7275dbccbf
<ide><path>src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php <ide> <ide> class SQLiteGrammar extends Grammar { <ide> <del> /** <del> * Compile the "order by" portions of the query. <del> * <del> * @param \Illuminate\Database\Query\Builder $query <del> * @param array $orders <del> * @return string <del> */ <del> protected function compileOrders(Builder $query, $orders) <del> { <del> $me = $this; <del> <del> return 'order by '.implode(', ', array_map(function($order) use ($me) <del> { <del> return $me->wrap($order['column']).' collate nocase '.$order['direction']; <del> } <del> , $orders)); <del> } <del> <ide> /** <ide> * Compile an insert statement into SQL. <ide> *
1
Text
Text
add merge methods
06171568f9d3dbc87985b06b62a788c54fecd8cd
<ide><path>README.md <ide> Transform the DOM by selecting elements and joining to data. <ide> * [*selection*.select](https://github.com/d3/d3-selection#selection_select) - select a descendant element for each selected element. <ide> * [*selection*.selectAll](https://github.com/d3/d3-selection#selection_selectAll) - select multiple descendants for each selected element. <ide> * [*selection*.filter](https://github.com/d3/d3-selection#selection_filter) - filter elements based on data. <add>* [*selection*.merge](https://github.com/d3/d3-selection#selection_merge) - merge this selection with another. <ide> * [d3.matcher](https://github.com/d3/d3-selection#matcher) - test whether an element matches a selector. <ide> * [d3.selector](https://github.com/d3/d3-selection#selector) - select an element. <ide> * [d3.selectorAll](https://github.com/d3/d3-selection#selectorAll) - select elements. <ide> Animated transitions for [selections](#selections). <ide> * [*transition*.select](https://github.com/d3/d3-transition#transition_select) - <ide> * [*transition*.selectAll](https://github.com/d3/d3-transition#transition_selectAll) - <ide> * [*transition*.filter](https://github.com/d3/d3-transition#transition_filter) - <add>* [*transition*.merge](https://github.com/d3/d3-transition#transition_merge) - merge this transition with another. <ide> * [*transition*.transition](https://github.com/d3/d3-transition#transition_transition) - <ide> * [*transition*.call](https://github.com/d3/d3-transition#transition_call) - <ide> * [*transition*.nodes](https://github.com/d3/d3-transition#transition_nodes) -
1
Text
Text
add information about indexoutofrangeexception
731dda053998568390da64cbeed223a56241d0cf
<ide><path>guide/english/csharp/array/index.md <ide> You can assign a value into an element directly by using the format below: <ide> <ide> Code above will assign the value of 50 directly into element [2] <ide> <add>Note - Be careful when trying to assign/access a value to/from an array. If an invalid index isused, like `nameOfArray[-1]` you will encounter a run-time error. <ide> <ide> You can assign multiple values at once while declaring the array using the format below: <ide>
1
Text
Text
fix instructions for with-netlify-cms example
926a4e5abc67b9ef605a097a6d16e86876fe5781
<ide><path>examples/with-netlify-cms/readme.md <ide> Download the example: <ide> <ide> ```bash <ide> curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-netlify-cms <del>cd nested-components <add>cd with-netlify-cms <ide> ``` <ide> <ide> Install it and run:
1
Python
Python
make duplicated masked constants obvious
7254888b9ffe1f26ce59600ad31b7d4c9135c13d
<ide><path>numpy/ma/core.py <ide> def __str__(self): <ide> return str(masked_print_option._display) <ide> <ide> def __repr__(self): <del> return 'masked' <add> if self is masked: <add> return 'masked' <add> else: <add> # something is wrong, make it obvious <add> return object.__repr__(self) <ide> <ide> def flatten(self): <ide> return masked_array([self._data], dtype=float, mask=[True]) <ide><path>numpy/ma/tests/test_core.py <ide> def test_ctor(self): <ide> assert_(not isinstance(m, np.ma.core.MaskedConstant)) <ide> assert_(m is not np.ma.masked) <ide> <add> def test_repr(self): <add> # copies should not exist, but if they do, it should be obvious that <add> # something is wrong <add> assert_equal(repr(np.ma.masked), 'masked') <add> assert_not_equal(repr(np.ma.masked.copy()), 'masked') <add> <ide> <ide> def test_masked_array(): <ide> a = np.ma.array([0, 1, 2, 3], mask=[0, 0, 1, 0])
2
Javascript
Javascript
add bugzill reference, reducing to 1px size
1cfb099640b839aad2228bc74128a5c96c0b28d3
<ide><path>src/canvas.js <ide> var TextRenderingMode = { <ide> }; <ide> <ide> // Minimal font size that would be used during canvas fillText operations. <del>var MIN_FONT_SIZE = 2; <add>var MIN_FONT_SIZE = 1; <ide> <ide> var CanvasExtraState = (function CanvasExtraStateClosure() { <ide> function CanvasExtraState(old) { <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> var serif = fontObj.isSerifFont ? 'serif' : 'sans-serif'; <ide> var typeface = '"' + name + '", ' + serif; <ide> <add> // Some font backends cannot handle fonts below certain size. <add> // Keeping the font at minimal size and using the fontSizeScale to change <add> // the current transformation matrix before the fillText/strokeText. <add> // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 <ide> var browserFontSize = size >= MIN_FONT_SIZE ? size : MIN_FONT_SIZE; <ide> this.current.fontSizeScale = browserFontSize != MIN_FONT_SIZE ? 1.0 : <ide> size / MIN_FONT_SIZE;
1
PHP
PHP
add a provider to test checked values
3c1adc292ac14333e45708212283fa33679ab427
<ide><path>tests/TestCase/View/Widget/CheckboxTest.php <ide> public function testRenderChecked() { <ide> $this->assertTags($result, $expected); <ide> } <ide> <add>/** <add> * Data provider for checkbox values <add> * <add> * @return array <add> */ <add> public static function checkedProvider() { <add> return [ <add> ['checked'], <add> ['1'], <add> [1], <add> [true], <add> ]; <add> } <add> <ide> /** <ide> * Test rendering checked checkboxes with value. <ide> * <add> * @dataProvider checkedProvider <ide> * @return void <ide> */ <del> public function testRenderCheckedValue() { <add> public function testRenderCheckedValue($checked) { <ide> $checkbox = new Checkbox($this->templates); <ide> $data = [ <ide> 'name' => 'Comment[spam]', <ide> 'value' => 1, <del> 'checked' => 1, <add> 'checked' => $checked, <ide> ]; <ide> $result = $checkbox->render($data); <ide> $expected = [
1
Javascript
Javascript
fix memory leak in messagequeue
5d748b2eec0b5bb2dea4eced79aba2fd994eb20a
<ide><path>Libraries/Utilities/MessageQueue.js <ide> const TO_JS = 0; <ide> <ide> const TRACE_TAG_REACT_APPS = 1 << 17; <ide> <add>const DEBUG_INFO_LIMIT = 32; <add> <ide> const MethodTypes = keyMirror({ <ide> remote: null, <ide> remoteAsync: null, <ide> class MessageQueue { <ide> __nativeCall(module, method, params, onFail, onSucc) { <ide> if (onFail || onSucc) { <ide> if (__DEV__) { <del> // eventually delete old debug info <del> (this._callbackID > (1 << 5)) && <del> (this._debugInfo[this._callbackID >> 5] = null); <del> this._debugInfo[this._callbackID >> 1] = [module, method]; <add> let callId = this._callbackID >> 1; <add> this._debugInfo[callId] = [module, method]; <add> if (callId > DEBUG_INFO_LIMIT) { <add> delete this._debugInfo[callId - DEBUG_INFO_LIMIT]; <add> } <ide> } <ide> onFail && params.push(this._callbackID); <ide> this._callbacks[this._callbackID++] = onFail;
1
Javascript
Javascript
follow jmpr op only if outside of fdef and if
8b6aeee35c14fb7b162615127f391e42dd4a3510
<ide><path>src/core/fonts.js <ide> var Font = (function FontClosure() { <ide> } <ide> --ifLevel; <ide> } else if (op === 0x1C) { // JMPR <del> var offset = stack[stack.length - 1]; <del> // only jumping forward to prevent infinite loop <del> if (offset > 0) { i += offset - 1; } <add> if (!inFDEF && !inELSE) { <add> var offset = stack[stack.length - 1]; <add> // only jumping forward to prevent infinite loop <add> if (offset > 0) { i += offset - 1; } <add> } <ide> } <ide> // Adjusting stack not extactly, but just enough to get function id <ide> if (!inFDEF && !inELSE) {
1
Javascript
Javascript
remove dom functions from top-level isomorphic api
2e1fb4b52972711199d5065625251642f7d75c29
<ide><path>src/React.js <ide> var ReactDOMServer = require('ReactDOMServer'); <ide> var ReactIsomorphic = require('ReactIsomorphic'); <ide> <ide> var assign = require('Object.assign'); <del>var deprecated = require('deprecated'); <ide> <ide> // `version` will be added here by ReactIsomorphic. <ide> var React = {}; <ide> <ide> assign(React, ReactIsomorphic); <ide> <del>assign(React, { <del> // ReactDOM <del> findDOMNode: deprecated( <del> 'findDOMNode', <del> 'ReactDOM', <del> 'react-dom', <del> ReactDOM, <del> ReactDOM.findDOMNode <del> ), <del> render: deprecated( <del> 'render', <del> 'ReactDOM', <del> 'react-dom', <del> ReactDOM, <del> ReactDOM.render <del> ), <del> unmountComponentAtNode: deprecated( <del> 'unmountComponentAtNode', <del> 'ReactDOM', <del> 'react-dom', <del> ReactDOM, <del> ReactDOM.unmountComponentAtNode <del> ), <del> <del> // ReactDOMServer <del> renderToString: deprecated( <del> 'renderToString', <del> 'ReactDOMServer', <del> 'react-dom/server', <del> ReactDOMServer, <del> ReactDOMServer.renderToString <del> ), <del> renderToStaticMarkup: deprecated( <del> 'renderToStaticMarkup', <del> 'ReactDOMServer', <del> 'react-dom/server', <del> ReactDOMServer, <del> ReactDOMServer.renderToStaticMarkup <del> ), <del>}); <del> <ide> React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM; <ide> React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer; <ide>
1
Text
Text
remove legacy models in the readmes
44811ca21a63aaef9a2d90c209fe0c5a5e6eabd0
<ide><path>official/README.md <ide> In the near future, we will add: <ide> <ide> ## Models and Implementations <ide> <del>### Computer Vision <add>### [Computer Vision](vision/README.md) <ide> <ide> #### Image Classification <ide> <ide> | Model | Reference (Paper) | <ide> |-------|-------------------| <del>| [MNIST](legacy/image_classification) | A basic model to classify digits from the [MNIST dataset](http://yann.lecun.com/exdb/mnist/) | <ide> | [ResNet](vision/MODEL_GARDEN.md) | [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) | <ide> | [ResNet-RS](vision/MODEL_GARDEN.md) | [Revisiting ResNets: Improved Training and Scaling Strategies](https://arxiv.org/abs/2103.07579) | <del>| [EfficientNet](legacy/image_classification) | [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) | <add>| [EfficientNet](vision/MODEL_GARDEN.md) | [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) | <ide> | [Vision Transformer](vision/MODEL_GARDEN.md) | [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) | <ide> <ide> #### Object Detection and Segmentation <ide> In the near future, we will add: <ide> |-------|-------------------| <ide> | [RetinaNet](vision/MODEL_GARDEN.md) | [Focal Loss for Dense Object Detection](https://arxiv.org/abs/1708.02002) | <ide> | [Mask R-CNN](vision/MODEL_GARDEN.md) | [Mask R-CNN](https://arxiv.org/abs/1703.06870) | <del>| [ShapeMask](legacy/detection) | [ShapeMask: Learning to Segment Novel Objects by Refining Shape Priors](https://arxiv.org/abs/1904.03239) | <ide> | [SpineNet](vision/MODEL_GARDEN.md) | [SpineNet: Learning Scale-Permuted Backbone for Recognition and Localization](https://arxiv.org/abs/1912.05027) | <ide> | [Cascade RCNN-RS and RetinaNet-RS](vision/MODEL_GARDEN.md) | [Simple Training Strategies and Model Scaling for Object Detection](https://arxiv.org/abs/2107.00057)| <ide> <ide> In the near future, we will add: <ide> |-------|-------------------| <ide> | [Mobile Video Networks (MoViNets)](projects/movinet) | [MoViNets: Mobile Video Networks for Efficient Video Recognition](https://arxiv.org/abs/2103.11511) | <ide> <del>### Natural Language Processing <add>### [Natural Language Processing](nlp/README.md) <ide> <ide> | Model | Reference (Paper) | <ide> |-------|-------------------| <ide> | [ALBERT (A Lite BERT)](nlp/MODEL_GARDEN.md#available-model-configs) | [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942) | <ide> | [BERT (Bidirectional Encoder Representations from Transformers)](nlp/MODEL_GARDEN.md#available-model-configs) | [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) | <ide> | [NHNet (News Headline generation model)](projects/nhnet) | [Generating Representative Headlines for News Stories](https://arxiv.org/abs/2001.09386) | <ide> | [Transformer](nlp/MODEL_GARDEN.md#available-model-configs) | [Attention Is All You Need](https://arxiv.org/abs/1706.03762) | <del>| [XLNet](nlp/xlnet) | [XLNet: Generalized Autoregressive Pretraining for Language Understanding](https://arxiv.org/abs/1906.08237) | <ide> | [MobileBERT](projects/mobilebert) | [MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited Devices](https://arxiv.org/abs/2004.02984) | <ide> <ide> ### Recommendation <ide><path>official/nlp/README.md <del># TensorFlow NLP Modelling Toolkit <add># TF-NLP Model Garden <add> <add>⚠️ Disclaimer: All datasets hyperlinked from this page are not owned or <add>distributed by Google. The dataset is made available by third parties. <add>Please review the terms and conditions made available by the third parties <add>before using the data. <ide> <ide> This codebase provides a Natrual Language Processing modeling toolkit written in <ide> [TF2](https://www.tensorflow.org/guide/effective_tf2). It allows researchers and
2
Javascript
Javascript
refactor the code in test-dns-ipv6
5e781a38834c4195d96c860e643dde850e8b7e6e
<ide><path>test/internet/test-dns-ipv6.js <ide> const dns = require('dns'); <ide> const net = require('net'); <ide> const isIPv6 = net.isIPv6; <ide> <del>let expected = 0; <del>let completed = 0; <ide> let running = false; <ide> const queue = []; <ide> <ide> if (!common.hasIPv6) { <ide> <ide> function TEST(f) { <ide> function next() { <del> var f = queue.shift(); <add> const f = queue.shift(); <ide> if (f) { <ide> running = true; <ide> console.log(f.name); <ide> function TEST(f) { <ide> <ide> function done() { <ide> running = false; <del> completed++; <ide> process.nextTick(next); <ide> } <ide> <del> expected++; <ide> queue.push(f); <ide> <ide> if (!running) { <ide> function checkWrap(req) { <ide> } <ide> <ide> TEST(function test_resolve6(done) { <del> var req = dns.resolve6('ipv6.google.com', function(err, ips) { <del> if (err) throw err; <add> const req = dns.resolve6('ipv6.google.com', <add> common.mustCall((err, ips) => { <add> assert.ifError(err); <ide> <del> assert.ok(ips.length > 0); <add> assert.ok(ips.length > 0); <ide> <del> for (var i = 0; i < ips.length; i++) { <del> assert.ok(isIPv6(ips[i])); <del> } <add> for (let i = 0; i < ips.length; i++) <add> assert.ok(isIPv6(ips[i])); <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_reverse_ipv6(done) { <del> var req = dns.reverse('2001:4860:4860::8888', function(err, domains) { <del> if (err) throw err; <add> const req = dns.reverse('2001:4860:4860::8888', <add> common.mustCall((err, domains) => { <add> assert.ifError(err); <ide> <del> assert.ok(domains.length > 0); <add> assert.ok(domains.length > 0); <ide> <del> for (var i = 0; i < domains.length; i++) { <del> assert.ok(domains[i]); <del> assert.ok(typeof domains[i] === 'string'); <del> } <add> for (let i = 0; i < domains.length; i++) <add> assert.ok(typeof domains[i] === 'string'); <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv6_explicit(done) { <del> var req = dns.lookup('ipv6.google.com', 6, function(err, ip, family) { <del> if (err) throw err; <del> assert.ok(net.isIPv6(ip)); <del> assert.strictEqual(family, 6); <add> const req = dns.lookup('ipv6.google.com', 6, <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.ok(isIPv6(ip)); <add> assert.strictEqual(family, 6); <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> TEST(function test_lookup_ipv6_implicit(done) { <ide> */ <ide> <ide> TEST(function test_lookup_ipv6_explicit_object(done) { <del> var req = dns.lookup('ipv6.google.com', { <add> const req = dns.lookup('ipv6.google.com', { <ide> family: 6 <del> }, function(err, ip, family) { <del> if (err) throw err; <del> assert.ok(net.isIPv6(ip)); <add> }, common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.ok(isIPv6(ip)); <ide> assert.strictEqual(family, 6); <ide> <ide> done(); <del> }); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ipv6_hint(done) { <del> var req = dns.lookup('www.google.com', { <add> const req = dns.lookup('www.google.com', { <ide> family: 6, <ide> hints: dns.V4MAPPED <del> }, function(err, ip, family) { <add> }, common.mustCall((err, ip, family) => { <ide> if (err) { <ide> // FreeBSD does not support V4MAPPED <ide> if (common.isFreeBSD) { <ide> TEST(function test_lookup_ipv6_hint(done) { <ide> assert.ok(/getaddrinfo EAI_BADFLAGS/.test(err.message)); <ide> done(); <ide> return; <del> } else { <del> throw err; <ide> } <add> <add> assert.ifError(err); <ide> } <del> assert.ok(net.isIPv6(ip)); <add> <add> assert.ok(isIPv6(ip)); <ide> assert.strictEqual(family, 6); <ide> <ide> done(); <del> }); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_ip_ipv6(done) { <del> var req = dns.lookup('::1', function(err, ip, family) { <del> if (err) throw err; <del> assert.ok(net.isIPv6(ip)); <del> assert.strictEqual(family, 6); <add> const req = dns.lookup('::1', <add> common.mustCall((err, ip, family) => { <add> assert.ifError(err); <add> assert.ok(isIPv6(ip)); <add> assert.strictEqual(family, 6); <ide> <del> done(); <del> }); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookup_all_ipv6(done) { <del> var req = dns.lookup( <add> const req = dns.lookup( <ide> 'www.google.com', <ide> {all: true, family: 6}, <del> function(err, ips) { <del> if (err) throw err; <add> common.mustCall((err, ips) => { <add> assert.ifError(err); <ide> assert.ok(Array.isArray(ips)); <ide> assert.ok(ips.length > 0); <ide> <del> ips.forEach(function(ip) { <add> ips.forEach((ip) => { <ide> assert.ok(isIPv6(ip.address), <ide> 'Invalid IPv6: ' + ip.address.toString()); <ide> assert.strictEqual(ip.family, 6); <ide> }); <ide> <ide> done(); <ide> } <del> ); <add> )); <ide> <ide> checkWrap(req); <ide> }); <ide> <ide> TEST(function test_lookupservice_ip_ipv6(done) { <del> var req = dns.lookupService('::1', 80, function(err, host, service) { <del> if (err) { <del> // Not skipping the test, rather checking an alternative result, <del> // i.e. that ::1 may not be configured (e.g. in /etc/hosts) <del> assert.strictEqual(err.code, 'ENOTFOUND'); <del> return done(); <del> } <del> assert.equal(typeof host, 'string'); <del> assert(host); <del> assert(['http', 'www', '80'].includes(service)); <del> done(); <del> }); <add> const req = dns.lookupService('::1', 80, <add> common.mustCall((err, host, service) => { <add> if (err) { <add> // Not skipping the test, rather checking an alternative result, <add> // i.e. that ::1 may not be configured (e.g. in /etc/hosts) <add> assert.strictEqual(err.code, 'ENOTFOUND'); <add> return done(); <add> } <add> assert.strictEqual(typeof host, 'string'); <add> assert(host); <add> assert(['http', 'www', '80'].includes(service)); <add> done(); <add> })); <ide> <ide> checkWrap(req); <ide> }); <ide> TEST(function test_lookupservice_ip_ipv6(done) { <ide> <ide> checkWrap(req); <ide> }); */ <del> <del>process.on('exit', function() { <del> console.log(completed + ' tests completed'); <del> assert.equal(running, false); <del> assert.strictEqual(expected, completed); <del>});
1