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
Go
Go
change subnet key schema in ipam
390a9702d236f7e170116fe3720170c91cc7d04f
<ide><path>libnetwork/ipam/allocator.go <ide> package ipam <ide> import ( <ide> "fmt" <ide> "net" <add> "strings" <ide> "sync" <ide> <ide> "github.com/docker/libnetwork/bitseq" <ide> type Allocator struct { <ide> // The internal subnets host size <ide> internalHostSize int <ide> // Static subnet information <del> subnetsInfo map[subnetKey]*SubnetInfo <add> subnets map[subnetKey]*SubnetInfo <ide> // Allocated addresses in each address space's internal subnet <ide> addresses map[subnetKey]*bitmask <ide> // Datastore <ide> type Allocator struct { <ide> // NewAllocator returns an instance of libnetwork ipam <ide> func NewAllocator(ds datastore.DataStore) *Allocator { <ide> a := &Allocator{} <del> a.subnetsInfo = make(map[subnetKey]*SubnetInfo) <add> a.subnets = make(map[subnetKey]*SubnetInfo) <ide> a.addresses = make(map[subnetKey]*bitmask) <ide> a.internalHostSize = defaultInternalHostSize <ide> a.store = ds <ide> func NewAllocator(ds datastore.DataStore) *Allocator { <ide> type subnetKey struct { <ide> addressSpace AddressSpace <ide> subnet string <add> childSubnet string <ide> } <ide> <ide> func (s *subnetKey) String() string { <del> return fmt.Sprintf("%s/%s", s.addressSpace, s.subnet) <add> k := fmt.Sprintf("%s/%s", s.addressSpace, s.subnet) <add> if s.childSubnet != "" { <add> k = fmt.Sprintf("%s/%s", k, s.childSubnet) <add> } <add> return k <add>} <add> <add>func (s *subnetKey) FromString(str string) error { <add> if str == "" || !strings.Contains(str, "/") { <add> return fmt.Errorf("invalid string form for subnetkey: %s", str) <add> } <add> <add> p := strings.Split(str, "/") <add> if len(p) != 3 && len(p) != 5 { <add> return fmt.Errorf("invalid string form for subnetkey: %s", str) <add> } <add> s.addressSpace = AddressSpace(p[0]) <add> s.subnet = fmt.Sprintf("%s/%s", p[1], p[2]) <add> if len(p) == 5 { <add> s.childSubnet = fmt.Sprintf("%s/%s", p[1], p[2]) <add> } <add> <add> return nil <ide> } <ide> <ide> // The structs containing the address allocation bitmask for the internal subnet. <ide> func (a *Allocator) AddSubnet(addrSpace AddressSpace, subnetInfo *SubnetInfo) er <ide> } <ide> <ide> // Store the configured subnet information <del> key := subnetKey{addrSpace, subnetInfo.Subnet.String()} <add> key := subnetKey{addrSpace, subnetInfo.Subnet.String(), ""} <ide> a.Lock() <del> a.subnetsInfo[key] = subnetInfo <add> a.subnets[key] = subnetInfo <ide> a.Unlock() <ide> <ide> // Create and insert the internal subnet(s) addresses masks into the address database <ide> for _, sub := range subnetList { <ide> ones, bits := sub.Mask.Size() <ide> numAddresses := 1 << uint(bits-ones) <del> smallKey := subnetKey{addrSpace, sub.String()} <add> smallKey := subnetKey{addrSpace, key.subnet, sub.String()} <ide> <ide> // Add the new address masks <ide> a.Lock() <ide> func adjustAndCheckSubnetSize(subnet *net.IPNet) (*net.IPNet, error) { <ide> func (a *Allocator) contains(space AddressSpace, subInfo *SubnetInfo) bool { <ide> a.Lock() <ide> defer a.Unlock() <del> for k, v := range a.subnetsInfo { <add> for k, v := range a.subnets { <ide> if space == k.addressSpace { <ide> if subInfo.Subnet.Contains(v.Subnet.IP) || <ide> v.Subnet.Contains(subInfo.Subnet.IP) { <ide> func (a *Allocator) RemoveSubnet(addrSpace AddressSpace, subnet *net.IPNet) erro <ide> <ide> // Look for the respective subnet configuration data <ide> // Remove it along with the internal subnets <del> subKey := subnetKey{addrSpace, subnet.String()} <add> subKey := subnetKey{addrSpace, subnet.String(), ""} <ide> a.Lock() <del> _, ok := a.subnetsInfo[subKey] <add> _, ok := a.subnets[subKey] <ide> a.Unlock() <ide> if !ok { <ide> return ErrSubnetNotFound <ide> func (a *Allocator) RemoveSubnet(addrSpace AddressSpace, subnet *net.IPNet) erro <ide> <ide> for _, s := range subnetList { <ide> a.Lock() <del> delete(a.addresses, subnetKey{addrSpace, s.String()}) <add> delete(a.addresses, subnetKey{addrSpace, subKey.subnet, s.String()}) <ide> a.Unlock() <ide> } <ide> <ide> a.Lock() <del> delete(a.subnetsInfo, subKey) <add> delete(a.subnets, subKey) <ide> a.Unlock() <ide> <ide> return nil <ide> func (a *Allocator) request(addrSpace AddressSpace, req *AddressRequest, version <ide> // Populate response <ide> response.Address = ip <ide> a.Lock() <del> response.Subnet = *a.subnetsInfo[subnetKey{addrSpace, req.Subnet.String()}] <add> response.Subnet = *a.subnets[subnetKey{addrSpace, req.Subnet.String(), ""}] <ide> a.Unlock() <ide> } <ide> <ide> func (a *Allocator) Release(addrSpace AddressSpace, address net.IP) { <ide> address = address.To4() <ide> } <ide> for _, subKey := range a.getSubnetList(addrSpace, ver) { <del> sub := a.addresses[subKey].subnet <add> a.Lock() <add> space := a.addresses[subKey] <add> a.Unlock() <add> sub := space.subnet <ide> if sub.Contains(address) { <ide> // Retrieve correspondent ordinal in the subnet <del> space := a.addresses[subnetKey{addrSpace, sub.String()}] <del> ordinal := ipToInt(getHostPortionIP(address, space.subnet)) <add> ordinal := ipToInt(getHostPortionIP(address, sub)) <ide> // Release it <ide> space.addressMask.PushReservation(ordinal/8, ordinal%8, true) <ide> space.freeAddresses++ <ide> func (a *Allocator) reserveAddress(addrSpace AddressSpace, subnet *net.IPNet, pr <ide> return nil, nil, err <ide> } <ide> for _, s := range subnetList { <del> keyList = append(keyList, subnetKey{addrSpace, s.String()}) <add> keyList = append(keyList, subnetKey{addrSpace, subnet.String(), s.String()}) <ide> } <ide> } else { <ide> a.Lock() <ide> again: <ide> func (a *Allocator) DumpDatabase() { <ide> a.Lock() <ide> defer a.Unlock() <del> for k, config := range a.subnetsInfo { <add> for k, config := range a.subnets { <ide> fmt.Printf("\n\n%s:", config.Subnet.String()) <ide> subnetList, _ := getInternalSubnets(config.Subnet, a.internalHostSize) <ide> for _, s := range subnetList { <del> internKey := subnetKey{k.addressSpace, s.String()} <add> internKey := subnetKey{k.addressSpace, config.Subnet.String(), s.String()} <ide> bm := a.addresses[internKey] <ide> fmt.Printf("\n\t%s: %s\n\t%d", bm.subnet, bm.addressMask, bm.freeAddresses) <ide> } <ide><path>libnetwork/ipam/allocator_test.go <ide> func TestGetAddressVersion(t *testing.T) { <ide> } <ide> } <ide> <add>func TestKeyString(t *testing.T) { <add> <add> k := &subnetKey{addressSpace: "default", subnet: "172.27.0.0/16"} <add> expected := "default/172.27.0.0/16" <add> if expected != k.String() { <add> t.Fatalf("Unexpected key string: %s", k.String()) <add> } <add> <add> k2 := &subnetKey{} <add> err := k2.FromString(expected) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if k2.addressSpace != k.addressSpace || k2.subnet != k.subnet { <add> t.Fatalf("subnetKey.FromString() failed. Expected %v. Got %v", k, k2) <add> } <add> <add> expected = fmt.Sprintf("%s/%s", expected, "172.27.3.0/24") <add> k.childSubnet = "172.27.3.0/24" <add> if expected != k.String() { <add> t.Fatalf("Unexpected key string: %s", k.String()) <add> } <add> <add> err = k2.FromString(expected) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if k2.addressSpace != k.addressSpace || k2.subnet != k.subnet { <add> t.Fatalf("subnetKey.FromString() failed. Expected %v. Got %v", k, k2) <add> } <add>} <add> <ide> func TestAddSubnets(t *testing.T) { <ide> a := NewAllocator(nil) <ide> <ide> func TestRemoveSubnet(t *testing.T) { <ide> <ide> _, sub, _ := net.ParseCIDR("172.17.0.0/16") <ide> a.RemoveSubnet("default", sub) <del> if len(a.subnetsInfo) != 7 { <add> if len(a.subnets) != 7 { <ide> t.Fatalf("Failed to remove subnet info") <ide> } <ide> list := a.getSubnetList("default", v4) <ide> func TestRemoveSubnet(t *testing.T) { <ide> <ide> _, sub, _ = net.ParseCIDR("2002:1:2:3:4:5:ffff::/112") <ide> a.RemoveSubnet("default", sub) <del> if len(a.subnetsInfo) != 6 { <add> if len(a.subnets) != 6 { <ide> t.Fatalf("Failed to remove subnet info") <ide> } <ide> list = a.getSubnetList("default", v6) <ide> func TestRemoveSubnet(t *testing.T) { <ide> <ide> _, sub, _ = net.ParseCIDR("2002:1:2:3:4:5:6::/112") <ide> a.RemoveSubnet("splane", sub) <del> if len(a.subnetsInfo) != 5 { <add> if len(a.subnets) != 5 { <ide> t.Fatalf("Failed to remove subnet info") <ide> } <ide> list = a.getSubnetList("splane", v6) <ide> func TestRelease(t *testing.T) { <ide> _, sub, _ := net.ParseCIDR(subnet) <ide> a := getAllocator(sub) <ide> req = &AddressRequest{Subnet: *sub} <del> bm := a.addresses[subnetKey{"default", subnet}] <add> bm := a.addresses[subnetKey{"default", subnet, subnet}] <ide> <ide> // Allocate all addresses <ide> for err != ErrNoAvailableIPs {
2
Javascript
Javascript
fix loading gltf zip files in the editor
bdba8e2af61494aac0b3c2fae7f15248405732b3
<ide><path>editor/js/Loader.js <ide> var Loader = function ( editor ) { <ide> var scene = result.scene; <ide> <ide> editor.addAnimation( scene, result.animations ); <del> editor.execute( new AddObjectCommand( scene ) ); <add> editor.execute( new AddObjectCommand( editor, scene ) ); <ide> <ide> } ); <ide>
1
Ruby
Ruby
add assert_redirected_to test with custom message
28eb8b4818663033c808b59d7714ef1e03fb9150
<ide><path>actionpack/test/controller/action_pack_assertions_test.rb <ide> def test_assert_redirection_with_symbol <ide> } <ide> end <ide> <add> def test_assert_redirection_with_custom_message <add> error = assert_raise(ActiveSupport::TestCase::Assertion) do <add> assert_redirected_to "http://test.host/some/path", "wrong redirect" <add> end <add> <add> assert_equal("wrong redirect", error.message) <add> end <add> <ide> def test_assert_redirection_with_status <ide> process :redirect_to_path <ide> assert_redirected_to "http://test.host/some/path", status: :found
1
Javascript
Javascript
create experimental stub
819b926beb38b12a984c9cb9a1008bff5dc8559c
<ide><path>Libraries/Animated/createAnimatedComponent_EXPERIMENTAL.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow strict-local <add> * @format <add> */ <add> <add>import * as React from 'react'; <add> <add>/** <add> * Experimental implementation of `createAnimatedComponent` that is intended to <add> * be compatible with concurrent rendering. <add> */ <add>export default function createAnimatedComponent<TProps: {...}, TInstance>( <add> Component: React.AbstractComponent<TProps, TInstance>, <add>): React.AbstractComponent<TProps, TInstance> { <add> return React.forwardRef((props, ref) => { <add> throw new Error('createAnimatedComponent: Not yet implemented.'); <add> }); <add>}
1
Mixed
Javascript
allow use of filenames in exportpathmap
a79357f2a4bc8eca1bcc64ff30c411fee4842d98
<ide><path>lib/router/index.js <ide> export function _rewriteUrlForNextExport (url) { <ide> let [path, qs] = url.split('?') <ide> path = path.replace(/\/$/, '') <ide> <del> let newPath = `${path}/` <add> let newPath = path <add> // Append a trailing slash if this path does not have an extension <add> if (!/\.[^/]+\/?$/.test(path)) { <add> newPath = `${path}/` <add> } <add> <ide> if (qs) { <ide> newPath = `${newPath}?${qs}` <ide> } <ide><path>readme.md <ide> module.exports = { <ide> return { <ide> '/': { page: '/' }, <ide> '/about': { page: '/about' }, <add> '/readme.md': { page: '/readme' }, <ide> '/p/hello-nextjs': { page: '/post', query: { title: 'hello-nextjs' } }, <ide> '/p/learn-nextjs': { page: '/post', query: { title: 'learn-nextjs' } }, <ide> '/p/deploy-nextjs': { page: '/post', query: { title: 'deploy-nextjs' } } <ide> module.exports = { <ide> } <ide> ``` <ide> <add>> Note that if the path ends with a directory, it will be exported as `/dir-name/index.html`, but if it ends with an extension, it will be exported as the specified filename, e.g. `/readme.md` above. If you use a file extension other than `.html`, you may need to set the `Content-Type` header to `text/html` when serving this content. <add> <ide> In that, you specify what are the pages you need to export as static HTML. <ide> <ide> Then simply run these commands: <ide><path>server/export.js <ide> import del from 'del' <ide> import cp from 'recursive-copy' <ide> import mkdirp from 'mkdirp-then' <ide> import walk from 'walk' <del>import { resolve, join, dirname, sep } from 'path' <add>import { extname, resolve, join, dirname, sep } from 'path' <ide> import { existsSync, readFileSync, writeFileSync } from 'fs' <ide> import getConfig from './config' <ide> import { renderToHTML } from './render' <ide> export default async function (dir, options, configuration) { <ide> const req = { url: path } <ide> const res = {} <ide> <del> const htmlFilename = path === '/' ? 'index.html' : `${path}${sep}index.html` <add> let htmlFilename = `${path}${sep}index.html` <add> if (extname(path) !== '') { <add> // If the path has an extension, use that as the filename instead <add> htmlFilename = path <add> } else if (path === '/') { <add> // If the path is the root, just use index.html <add> htmlFilename = 'index.html' <add> } <ide> const baseDir = join(outDir, dirname(htmlFilename)) <ide> const htmlFilepath = join(outDir, htmlFilename) <ide> <ide><path>test/integration/static/next.config.js <ide> module.exports = { <ide> '/dynamic-imports': { page: '/dynamic-imports' }, <ide> '/dynamic': { page: '/dynamic', query: { text: 'cool dynamic text' } }, <ide> '/dynamic/one': { page: '/dynamic', query: { text: 'next export is nice' } }, <del> '/dynamic/two': { page: '/dynamic', query: { text: 'zeit is awesome' } } <add> '/dynamic/two': { page: '/dynamic', query: { text: 'zeit is awesome' } }, <add> '/file-name.md': { page: '/dynamic', query: { text: 'this file has an extension' } } <ide> } <ide> } <ide> } <ide><path>test/integration/static/pages/index.js <ide> export default () => ( <ide> > <ide> <a id='with-hash'>With Hash</a> <ide> </Link> <add> <Link <add> href='/dynamic?text=this+file+has+an+extension' <add> as='/file-name.md' <add> > <add> <a id='path-with-extension'>Path with extension</a> <add> </Link> <ide> <Link href='/level1'> <ide> <a id='level1-home-page'>Level1 home page</a> <ide> </Link> <ide><path>test/integration/static/test/ssr.js <ide> /* global describe, it, expect */ <ide> import { renderViaHTTP } from 'next-test-utils' <add>import cheerio from 'cheerio' <ide> <ide> export default function (context) { <ide> describe('Render via SSR', () => { <ide> export default function (context) { <ide> expect(html).toMatch(/This is the home page/) <ide> }) <ide> <add> it('should render links correctly', async () => { <add> const html = await renderViaHTTP(context.port, '/') <add> const $ = cheerio.load(html) <add> const dynamicLink = $('#dynamic-1').prop('href') <add> const filePathLink = $('#path-with-extension').prop('href') <add> expect(dynamicLink).toEqual('/dynamic/one/') <add> expect(filePathLink).toEqual('/file-name.md') <add> }) <add> <ide> it('should render a page with getInitialProps', async() => { <ide> const html = await renderViaHTTP(context.port, '/dynamic') <ide> expect(html).toMatch(/cool dynamic text/) <ide> export default function (context) { <ide> <ide> it('should render pages with dynamic imports', async() => { <ide> const html = await renderViaHTTP(context.port, '/dynamic-imports') <del> expect(html).toMatch(/Welcome to dynamic imports./) <add> expect(html).toMatch(/Welcome to dynamic imports/) <add> }) <add> <add> it('should render paths with extensions', async() => { <add> const html = await renderViaHTTP(context.port, '/file-name.md') <add> expect(html).toMatch(/this file has an extension/) <ide> }) <ide> <ide> it('should give empty object for query if there is no query', async() => {
6
Javascript
Javascript
unload the pdfstreamconverter on shutdown
08d3710bfc1dc76ecb66f0fab5aee4850c0ae4d3
<ide><path>extensions/firefox/bootstrap.js <ide> let Factory = { <ide> } <ide> }; <ide> <add>let pdfStreamConverterUrl = null; <add> <ide> // As of Firefox 13 bootstrapped add-ons don't support automatic registering and <ide> // unregistering of resource urls and components/contracts. Until then we do <ide> // it programatically. See ManifestDirective ManifestParser.cpp for support. <ide> function startup(aData, aReason) { <ide> resProt.setSubstitution(RESOURCE_NAME, aliasURI); <ide> <ide> // Load the component and register it. <del> Cu.import(aData.resourceURI.spec + 'components/PdfStreamConverter.js'); <add> pdfStreamConverterUrl = aData.resourceURI.spec + <add> 'components/PdfStreamConverter.js'; <add> Cu.import(pdfStreamConverterUrl); <ide> Factory.register(PdfStreamConverter); <ide> Services.prefs.setBoolPref('extensions.pdf.js.active', true); <ide> } <ide> function shutdown(aData, aReason) { <ide> resProt.setSubstitution(RESOURCE_NAME, null); <ide> // Remove the contract/component. <ide> Factory.unregister(); <add> // Unload the converter <add> if (pdfStreamConverterUrl) { <add> Cu.unload(pdfStreamConverterUrl); <add> pdfStreamConverterUrl = null; <add> } <ide> } <ide> <ide> function install(aData, aReason) {
1
Java
Java
add compositecontentyperesolver and a builder
4af99473ffa36a75fb4d6d521f736a403a4f904f
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/accept/CompositeContentTypeResolver.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>package org.springframework.web.reactive.accept; <add> <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.LinkedHashSet; <add>import java.util.List; <add>import java.util.Set; <add> <add>import org.springframework.http.MediaType; <add>import org.springframework.util.Assert; <add>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.ServerWebExchange; <add> <add>/** <add> * A {@link ContentTypeResolver} that contains and delegates to a list of other <add> * resolvers. <add> * <add> * <p>Also an implementation of {@link MappingContentTypeResolver} that delegates <add> * to those resolvers from the list that are also of type <add> * {@code MappingContentTypeResolver}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class CompositeContentTypeResolver implements MappingContentTypeResolver { <add> <add> private final List<ContentTypeResolver> resolvers = new ArrayList<>(); <add> <add> <add> public CompositeContentTypeResolver(List<ContentTypeResolver> resolvers) { <add> Assert.notEmpty(resolvers, "At least one resolver is expected."); <add> this.resolvers.addAll(resolvers); <add> } <add> <add> <add> /** <add> * Return a read-only list of the configured resolvers. <add> */ <add> public List<ContentTypeResolver> getResolvers() { <add> return Collections.unmodifiableList(this.resolvers); <add> } <add> <add> /** <add> * Return the first {@link ContentTypeResolver} of the given type. <add> * @param resolverType the resolver type <add> * @return the first matching resolver or {@code null}. <add> */ <add> @SuppressWarnings("unchecked") <add> public <T extends ContentTypeResolver> T findResolver(Class<T> resolverType) { <add> for (ContentTypeResolver resolver : this.resolvers) { <add> if (resolverType.isInstance(resolver)) { <add> return (T) resolver; <add> } <add> } <add> return null; <add> } <add> <add> <add> @Override <add> public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws HttpMediaTypeNotAcceptableException { <add> for (ContentTypeResolver resolver : this.resolvers) { <add> List<MediaType> mediaTypes = resolver.resolveMediaTypes(exchange); <add> if (mediaTypes.isEmpty() || (mediaTypes.size() == 1 && mediaTypes.contains(MediaType.ALL))) { <add> continue; <add> } <add> return mediaTypes; <add> } <add> return Collections.emptyList(); <add> } <add> <add> @Override <add> public Set<String> getKeysFor(MediaType mediaType) { <add> Set<String> result = new LinkedHashSet<>(); <add> for (ContentTypeResolver resolver : this.resolvers) { <add> if (resolver instanceof MappingContentTypeResolver) <add> result.addAll(((MappingContentTypeResolver) resolver).getKeysFor(mediaType)); <add> } <add> return result; <add> } <add> <add> @Override <add> public Set<String> getKeys() { <add> Set<String> result = new LinkedHashSet<>(); <add> for (ContentTypeResolver resolver : this.resolvers) { <add> if (resolver instanceof MappingContentTypeResolver) <add> result.addAll(((MappingContentTypeResolver) resolver).getKeys()); <add> } <add> return result; <add> } <add> <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/accept/CompositeContentTypeResolverBuilder.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>package org.springframework.web.reactive.accept; <add> <add>import java.util.ArrayList; <add>import java.util.HashMap; <add>import java.util.List; <add>import java.util.Locale; <add>import java.util.Map; <add> <add>import org.springframework.http.MediaType; <add>import org.springframework.util.Assert; <add>import org.springframework.util.CollectionUtils; <add> <add> <add>/** <add> * Builder for {@link CompositeContentTypeResolver}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class CompositeContentTypeResolverBuilder { <add> <add> private boolean favorPathExtension = true; <add> <add> private boolean favorParameter = false; <add> <add> private boolean ignoreAcceptHeader = false; <add> <add> private Map<String, MediaType> mediaTypes = new HashMap<>(); <add> <add> private boolean ignoreUnknownPathExtensions = true; <add> <add> private Boolean useJaf; <add> <add> private String parameterName = "format"; <add> <add> private ContentTypeResolver contentTypeResolver; <add> <add> <add> /** <add> * Whether the path extension in the URL path should be used to determine <add> * the requested media type. <add> * <p>By default this is set to {@code true} in which case a request <add> * for {@code /hotels.pdf} will be interpreted as a request for <add> * {@code "application/pdf"} regardless of the 'Accept' header. <add> */ <add> public CompositeContentTypeResolverBuilder favorPathExtension(boolean favorPathExtension) { <add> this.favorPathExtension = favorPathExtension; <add> return this; <add> } <add> <add> /** <add> * Add a mapping from a key, extracted from a path extension or a query <add> * parameter, to a MediaType. This is required in order for the parameter <add> * strategy to work. Any extensions explicitly registered here are also <add> * whitelisted for the purpose of Reflected File Download attack detection <add> * (see Spring Framework reference documentation for more details on RFD <add> * attack protection). <add> * <p>The path extension strategy will also try to use JAF (if present) to <add> * resolve path extensions. To change this behavior see {@link #useJaf}. <add> * @param mediaTypes media type mappings <add> */ <add> public CompositeContentTypeResolverBuilder mediaTypes(Map<String, MediaType> mediaTypes) { <add> if (!CollectionUtils.isEmpty(mediaTypes)) { <add> for (Map.Entry<String, MediaType> entry : mediaTypes.entrySet()) { <add> String extension = entry.getKey().toLowerCase(Locale.ENGLISH); <add> this.mediaTypes.put(extension, entry.getValue()); <add> } <add> } <add> return this; <add> } <add> <add> /** <add> * Alternative to {@link #mediaTypes} to add a single mapping. <add> */ <add> public CompositeContentTypeResolverBuilder mediaType(String key, MediaType mediaType) { <add> this.mediaTypes.put(key, mediaType); <add> return this; <add> } <add> <add> /** <add> * Whether to ignore requests with path extension that cannot be resolved <add> * to any media type. Setting this to {@code false} will result in an <add> * {@link org.springframework.web.HttpMediaTypeNotAcceptableException} if <add> * there is no match. <add> * <p>By default this is set to {@code true}. <add> */ <add> public CompositeContentTypeResolverBuilder ignoreUnknownPathExtensions(boolean ignore) { <add> this.ignoreUnknownPathExtensions = ignore; <add> return this; <add> } <add> <add> /** <add> * When {@link #favorPathExtension favorPathExtension} is set, this <add> * property determines whether to allow use of JAF (Java Activation Framework) <add> * to resolve a path extension to a specific MediaType. <add> * <p>By default this is not set in which case <add> * {@code PathExtensionContentNegotiationStrategy} will use JAF if available. <add> */ <add> public CompositeContentTypeResolverBuilder useJaf(boolean useJaf) { <add> this.useJaf = useJaf; <add> return this; <add> } <add> <add> /** <add> * Whether a request parameter ("format" by default) should be used to <add> * determine the requested media type. For this option to work you must <add> * register {@link #mediaTypes media type mappings}. <add> * <p>By default this is set to {@code false}. <add> * @see #parameterName <add> */ <add> public CompositeContentTypeResolverBuilder favorParameter(boolean favorParameter) { <add> this.favorParameter = favorParameter; <add> return this; <add> } <add> <add> /** <add> * Set the query parameter name to use when {@link #favorParameter} is on. <add> * <p>The default parameter name is {@code "format"}. <add> */ <add> public CompositeContentTypeResolverBuilder parameterName(String parameterName) { <add> Assert.notNull(parameterName, "parameterName is required"); <add> this.parameterName = parameterName; <add> return this; <add> } <add> <add> /** <add> * Whether to disable checking the 'Accept' request header. <add> * <p>By default this value is set to {@code false}. <add> */ <add> public CompositeContentTypeResolverBuilder ignoreAcceptHeader(boolean ignoreAcceptHeader) { <add> this.ignoreAcceptHeader = ignoreAcceptHeader; <add> return this; <add> } <add> <add> /** <add> * Set the default content type to use when no content type is requested. <add> * <p>By default this is not set. <add> * @see #defaultContentTypeResolver <add> */ <add> public CompositeContentTypeResolverBuilder defaultContentType(MediaType contentType) { <add> this.contentTypeResolver = new FixedContentTypeResolver(contentType); <add> return this; <add> } <add> <add> /** <add> * Set a custom {@link ContentTypeResolver} to use to determine <add> * the content type to use when no content type is requested. <add> * <p>By default this is not set. <add> * @see #defaultContentType <add> */ <add> public CompositeContentTypeResolverBuilder defaultContentTypeResolver(ContentTypeResolver resolver) { <add> this.contentTypeResolver = resolver; <add> return this; <add> } <add> <add> <add> public CompositeContentTypeResolver build() { <add> List<ContentTypeResolver> resolvers = new ArrayList<>(); <add> <add> if (this.favorPathExtension) { <add> PathExtensionContentTypeResolver resolver = new PathExtensionContentTypeResolver(this.mediaTypes); <add> resolver.setIgnoreUnknownExtensions(this.ignoreUnknownPathExtensions); <add> if (this.useJaf != null) { <add> resolver.setUseJaf(this.useJaf); <add> } <add> resolvers.add(resolver); <add> } <add> <add> if (this.favorParameter) { <add> ParameterContentTypeResolver resolver = new ParameterContentTypeResolver(this.mediaTypes); <add> resolver.setParameterName(this.parameterName); <add> resolvers.add(resolver); <add> } <add> <add> if (!this.ignoreAcceptHeader) { <add> resolvers.add(new HeaderContentTypeResolver()); <add> } <add> <add> if (this.contentTypeResolver != null) { <add> resolvers.add(this.contentTypeResolver); <add> } <add> <add> return new CompositeContentTypeResolver(resolvers); <add> } <add> <add>} <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/accept/FixedContentTypeResolver.java <add>/* <add> * Copyright 2002-2015 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.accept; <add> <add>import java.util.Collections; <add>import java.util.List; <add> <add>import org.springframework.http.MediaType; <add>import org.springframework.web.server.ServerWebExchange; <add> <add>/** <add> * A {@link ContentTypeResolver} that resolves to a fixed list of media types. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class FixedContentTypeResolver implements ContentTypeResolver { <add> <add> private final List<MediaType> mediaTypes; <add> <add> <add> /** <add> * Create an instance with the given content type. <add> */ <add> public FixedContentTypeResolver(MediaType mediaTypes) { <add> this.mediaTypes = Collections.singletonList(mediaTypes); <add> } <add> <add> <add> @Override <add> public List<MediaType> resolveMediaTypes(ServerWebExchange exchange) { <add> return this.mediaTypes; <add> } <add> <add>} <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/accept/CompositeContentTypeResolverBuilderTests.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>package org.springframework.web.reactive.accept; <add> <add>import java.net.URI; <add>import java.net.URISyntaxException; <add>import java.util.Collections; <add> <add>import org.junit.Test; <add> <add>import org.springframework.http.HttpMethod; <add>import org.springframework.http.MediaType; <add>import org.springframework.http.server.reactive.MockServerHttpRequest; <add>import org.springframework.http.server.reactive.MockServerHttpResponse; <add>import org.springframework.http.server.reactive.ServerHttpRequest; <add>import org.springframework.web.HttpMediaTypeNotAcceptableException; <add>import org.springframework.web.server.ServerWebExchange; <add>import org.springframework.web.server.adapter.DefaultServerWebExchange; <add>import org.springframework.web.server.session.WebSessionManager; <add> <add>import static org.junit.Assert.assertEquals; <add>import static org.mockito.Mockito.mock; <add> <add>/** <add> * Unit tests for {@link CompositeContentTypeResolverBuilder}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class CompositeContentTypeResolverBuilderTests { <add> <add> @Test <add> public void defaultSettings() throws Exception { <add> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder().build(); <add> <add> ServerWebExchange exchange = createExchange("/flower.gif"); <add> <add> assertEquals("Should be able to resolve file extensions by default", <add> Collections.singletonList(MediaType.IMAGE_GIF), resolver.resolveMediaTypes(exchange)); <add> <add> exchange = createExchange("/flower.xyz"); <add> <add> assertEquals("Should ignore unknown extensions by default", <add> Collections.<MediaType>emptyList(), resolver.resolveMediaTypes(exchange)); <add> <add> exchange = createExchange("/flower"); <add> exchange.getRequest().getQueryParams().add("format", "gif"); <add> <add> assertEquals("Should not resolve request parameters by default", <add> Collections.<MediaType>emptyList(), resolver.resolveMediaTypes(exchange)); <add> <add> exchange = createExchange("/flower"); <add> exchange.getRequest().getHeaders().setAccept(Collections.singletonList(MediaType.IMAGE_GIF)); <add> <add> assertEquals("Should resolve Accept header by default", <add> Collections.singletonList(MediaType.IMAGE_GIF), resolver.resolveMediaTypes(exchange)); <add> } <add> <add> @Test <add> public void favorPath() throws Exception { <add> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <add> .favorPathExtension(true) <add> .mediaType("foo", new MediaType("application", "foo")) <add> .mediaType("bar", new MediaType("application", "bar")) <add> .build(); <add> <add> ServerWebExchange exchange = createExchange("/flower.foo"); <add> assertEquals(Collections.singletonList(new MediaType("application", "foo")), <add> resolver.resolveMediaTypes(exchange)); <add> <add> exchange = createExchange("/flower.bar"); <add> assertEquals(Collections.singletonList(new MediaType("application", "bar")), <add> resolver.resolveMediaTypes(exchange)); <add> <add> exchange = createExchange("/flower.gif"); <add> assertEquals(Collections.singletonList(MediaType.IMAGE_GIF), resolver.resolveMediaTypes(exchange)); <add> } <add> <add> @Test <add> public void favorPathWithJafTurnedOff() throws Exception { <add> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <add> .favorPathExtension(true) <add> .useJaf(false) <add> .build(); <add> <add> ServerWebExchange exchange = createExchange("/flower.foo"); <add> assertEquals(Collections.emptyList(), resolver.resolveMediaTypes(exchange)); <add> <add> exchange = createExchange("/flower.gif"); <add> assertEquals(Collections.emptyList(), resolver.resolveMediaTypes(exchange)); <add> } <add> <add> @Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-10170 <add> public void favorPathWithIgnoreUnknownPathExtensionTurnedOff() throws Exception { <add> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <add> .favorPathExtension(true) <add> .ignoreUnknownPathExtensions(false) <add> .build(); <add> <add> ServerWebExchange exchange = createExchange("/flower.xyz"); <add> exchange.getRequest().getQueryParams().add("format", "json"); <add> <add> resolver.resolveMediaTypes(exchange); <add> } <add> <add> @Test <add> public void favorParameter() throws Exception { <add> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <add> .favorParameter(true) <add> .mediaType("json", MediaType.APPLICATION_JSON) <add> .build(); <add> <add> ServerWebExchange exchange = createExchange("/flower"); <add> exchange.getRequest().getQueryParams().add("format", "json"); <add> <add> assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), <add> resolver.resolveMediaTypes(exchange)); <add> } <add> <add> @Test(expected = HttpMediaTypeNotAcceptableException.class) // SPR-10170 <add> public void favorParameterWithUnknownMediaType() throws Exception { <add> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <add> .favorParameter(true) <add> .build(); <add> <add> ServerWebExchange exchange = createExchange("/flower"); <add> exchange.getRequest().getQueryParams().add("format", "xyz"); <add> <add> resolver.resolveMediaTypes(exchange); <add> } <add> <add> @Test <add> public void ignoreAcceptHeader() throws Exception { <add> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <add> .ignoreAcceptHeader(true) <add> .build(); <add> <add> ServerWebExchange exchange = createExchange("/flower"); <add> exchange.getRequest().getHeaders().setAccept(Collections.singletonList(MediaType.IMAGE_GIF)); <add> <add> assertEquals(Collections.<MediaType>emptyList(), resolver.resolveMediaTypes(exchange)); <add> } <add> <add> @Test // SPR-10513 <add> public void setDefaultContentType() throws Exception { <add> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <add> .defaultContentType(MediaType.APPLICATION_JSON) <add> .build(); <add> <add> ServerWebExchange exchange = createExchange("/"); <add> <add> assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), <add> resolver.resolveMediaTypes(exchange)); <add> <add> exchange.getRequest().getHeaders().setAccept(Collections.singletonList(MediaType.ALL)); <add> <add> assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), <add> resolver.resolveMediaTypes(exchange)); <add> } <add> <add> @Test // SPR-12286 <add> public void setDefaultContentTypeWithStrategy() throws Exception { <add> CompositeContentTypeResolver resolver = new CompositeContentTypeResolverBuilder() <add> .defaultContentTypeResolver(new FixedContentTypeResolver(MediaType.APPLICATION_JSON)) <add> .build(); <add> <add> ServerWebExchange exchange = createExchange("/"); <add> <add> assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), <add> resolver.resolveMediaTypes(exchange)); <add> <add> exchange.getRequest().getHeaders().setAccept(Collections.singletonList(MediaType.ALL)); <add> assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), <add> resolver.resolveMediaTypes(exchange)); <add> } <add> <add> <add> private ServerWebExchange createExchange(String path) throws URISyntaxException { <add> ServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, new URI(path)); <add> WebSessionManager sessionManager = mock(WebSessionManager.class); <add> return new DefaultServerWebExchange(request, new MockServerHttpResponse(), sessionManager); <add> } <add> <add>}
4
PHP
PHP
fix cs error
7582d4b8348d0436109ca759076546636da9f274
<ide><path>src/Network/Http/FormData.php <ide> class FormData implements Countable <ide> /** <ide> * Whether or not this formdata object has attached files. <ide> * <del> * @var boolean <add> * @var bool <ide> */ <ide> protected $_hasFile = false; <ide>
1
PHP
PHP
add deprecation warning to _unwrap()
d5b239fb6786ce10158006bc1ca6bd60cea70926
<ide><path>src/Collection/CollectionTrait.php <ide> public function unwrap() <ide> * Backwards compatible wrapper for unwrap() <ide> * <ide> * @return \Traversable <del> * @deprecated <add> * @deprecated 3.0.10 Will be removed in 4.0.0 <ide> */ <ide> // @codingStandardsIgnoreLine <ide> public function _unwrap() <ide> { <add> deprecationWarning('CollectionTrait::_unwrap() is deprecated. Use CollectionTrait::unwrap() instead.'); <ide> return $this->unwrap(); <ide> } <ide>
1
Javascript
Javascript
add spec for timepickerandroid
65b10b350e7a461f0a516a424cea6f625c6aadf3
<add><path>Libraries/Components/TimePickerAndroid/NativeTimePickerAndroid.js <del><path>Libraries/Components/TimePickerAndroid/TimePickerAndroidTypes.js <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <ide> * <add> * @flow <ide> * @format <del> * @flow strict-local <ide> */ <ide> <ide> 'use strict'; <ide> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <ide> export type TimePickerOptions = {| <ide> hour?: number, <ide> minute?: number, <ide> is24Hour?: boolean, <del> mode?: 'clock' | 'spinner' | 'default', <add> mode?: string, <ide> |}; <ide> <del>export type TimePickerResult = $ReadOnly<{| <add>export type TimePickerResult = {| <ide> action: string, <ide> hour: number, <ide> minute: number, <del>|}>; <add>|}; <add> <add>export interface Spec extends TurboModule { <add> +open: (options: TimePickerOptions) => Promise<TimePickerResult>; <add>} <add> <add>export default TurboModuleRegistry.get<Spec>('TimePickerAndroid'); <ide><path>Libraries/Components/TimePickerAndroid/TimePickerAndroid.ios.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @format <del> * @flow strict-local <del> */ <del> <del>'use strict'; <del> <del>import type { <del> TimePickerOptions, <del> TimePickerResult, <del>} from './TimePickerAndroidTypes'; <del> <del>const TimePickerAndroid = { <del> async open(options: TimePickerOptions): Promise<TimePickerResult> { <del> return Promise.reject({ <del> message: 'TimePickerAndroid is not supported on this platform.', <del> }); <del> }, <del>}; <del> <del>module.exports = TimePickerAndroid; <add><path>Libraries/Components/TimePickerAndroid/TimePickerAndroid.js <del><path>Libraries/Components/TimePickerAndroid/TimePickerAndroid.android.js <ide> <ide> 'use strict'; <ide> <del>const TimePickerModule = require('../../BatchedBridge/NativeModules') <del> .TimePickerAndroid; <del> <del>import type { <del> TimePickerOptions, <del> TimePickerResult, <del>} from './TimePickerAndroidTypes'; <add>import NativeTimePickerAndroid, { <add> type TimePickerOptions, <add> type TimePickerResult, <add>} from './NativeTimePickerAndroid'; <ide> <ide> /** <ide> * Opens the standard Android time picker dialog. <ide> class TimePickerAndroid { <ide> * still be resolved with action being `TimePickerAndroid.dismissedAction` and all the other keys <ide> * being undefined. **Always** check whether the `action` before reading the values. <ide> */ <del> static async open(options: TimePickerOptions): Promise<TimePickerResult> { <del> return TimePickerModule.open(options); <add> static async open( <add> options: TimePickerOptions, <add> ): Promise<$ReadOnly<TimePickerResult>> { <add> if (NativeTimePickerAndroid) { <add> return NativeTimePickerAndroid.open(options); <add> } else { <add> return Promise.reject({ <add> message: 'TimePickerAndroid is not supported on this platform.', <add> }); <add> } <ide> } <ide> <ide> /**
3
Text
Text
remove versions from gems listing
1af528df58ea20fecd2668fd065144a1ba573658
<ide><path>guides/source/initialization.md <ide> dependencies of the application. `config/boot.rb` sets <ide> `ENV['BUNDLE_GEMFILE']` to the location of this file. If the Gemfile <ide> exists, `bundler/setup` is then required. <ide> <del>The gems that a Rails 4 application depends on are as follows: <del> <del>TODO: change these when the Rails 4 release is near. <del> <del>* abstract (1.0.0) <del>* actionmailer (4.0.0.beta) <del>* actionpack (4.0.0.beta) <del>* activemodel (4.0.0.beta) <del>* activerecord (4.0.0.beta) <del>* activesupport (4.0.0.beta) <del>* arel (2.0.7) <del>* builder (3.0.0) <del>* bundler (1.0.6) <del>* erubis (2.6.6) <del>* i18n (0.5.0) <del>* mail (2.2.12) <del>* mime-types (1.16) <del>* polyglot (0.3.1) <del>* rack (1.2.1) <del>* rack-cache (0.5.3) <del>* rack-mount (0.6.13) <del>* rack-test (0.5.6) <del>* rails (4.0.0.beta) <del>* railties (4.0.0.beta) <del>* rake (0.8.7) <del>* sqlite3-ruby (1.3.2) <del>* thor (0.14.6) <del>* treetop (1.4.9) <del>* tzinfo (0.3.23) <add>A standard Rails application depends on several gems, specifically: <add> <add>* abstract <add>* actionmailer <add>* actionpack <add>* activemodel <add>* activerecord <add>* activesupport <add>* arel <add>* builder <add>* bundler <add>* erubis <add>* i18n <add>* mail <add>* mime-types <add>* polyglot <add>* rack <add>* rack-cache <add>* rack-mount <add>* rack-test <add>* rails <add>* railties <add>* rake <add>* sqlite3-ruby <add>* thor <add>* treetop <add>* tzinfo <ide> <ide> ### `rails/commands.rb` <ide>
1
Python
Python
add missing arguments for bertwordpiecetokenizer
90ec78b5140251f093f658ebd4d2925e8c03f5e6
<ide><path>src/transformers/tokenization_bert.py <ide> def __init__( <ide> unk_token=unk_token, <ide> sep_token=sep_token, <ide> cls_token=cls_token, <add> pad_token=pad_token, <add> mask_token=mask_token, <ide> clean_text=clean_text, <ide> handle_chinese_chars=tokenize_chinese_chars, <ide> strip_accents=strip_accents,
1
PHP
PHP
ignore non-scalar values for length
4fdd5e5d4595e9719a598bc12877709fc36a0b4e
<ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function input($fieldName, $options = array()) { <ide> } <ide> } <ide> <del> $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length'])); <add> $autoLength = ( <add> !array_key_exists('maxlength', $options) && <add> isset($fieldDef['length']) && <add> is_scalar($fieldDef['length']) <add> ); <ide> if ($autoLength && $options['type'] == 'text') { <ide> $options['maxlength'] = $fieldDef['length']; <ide> }
1
PHP
PHP
check application.ssl when setting a secure cookie
785e168f5ed15908b1d15dc2071eedc1bc16e30e
<ide><path>laravel/cookie.php <ide> public static function put($name, $value, $expiration = 0, $path = '/', $domain <ide> <ide> $value = static::hash($value).'+'.$value; <ide> <add> // If the developer has explicitly disabled SLL, then we shouldn't force <add> // this cookie over SSL. <add> $secure = $secure && Config::get('application.ssl'); <add> <ide> // If the secure option is set to true, yet the request is not over HTTPS <ide> // we'll throw an exception to let the developer know that they are <ide> // attempting to send a secure cookie over the insecure HTTP.
1
Text
Text
reduce react test flakiness
ac7388dd1b4e63b7069c2b246149db835abb810d
<ide><path>curriculum/challenges/english/03-front-end-development-libraries/react/render-conditionally-from-props.md <ide> Each time the button is clicked, the counter state should be incremented by a va <ide> })(); <ide> ``` <ide> <del>When the `GameOfChance` component is first mounted to the DOM and each time the button is clicked thereafter, a single `h1` element should be returned that randomly renders either `You Win!` or `You Lose!`. <add>When the `GameOfChance` component is first mounted to the DOM and each time the button is clicked thereafter, a single `h1` element should be returned that randomly renders either `You Win!` or `You Lose!`. Note: this can fail randomly. If that happens, please try again. <ide> <ide> ```js <ide> (() => { <ide> class GameOfChance extends React.Component { <ide> # --solutions-- <ide> <ide> ```jsx <add>// We want this to be deterministic for testing purposes. <add>const randomSequence = [true, false, false, true, true, false, false, true, true, false]; <add>let index = 0; <add>const fiftyFifty = () => randomSequence[index++ % randomSequence.length]; <add> <ide> class Results extends React.Component { <ide> constructor(props) { <ide> super(props); <ide> class GameOfChance extends React.Component { <ide> }); <ide> } <ide> render() { <del> const expression = Math.random() >= 0.5; <ide> return ( <ide> <div> <ide> <button onClick={this.handleClick}>Play Again</button> <del> <Results fiftyFifty={expression} /> <add> <Results fiftyFifty={fiftyFifty()} /> <ide> <p>{'Turn: ' + this.state.counter}</p> <ide> </div> <ide> );
1
Javascript
Javascript
fix import of linkingios on android
fb29a95e011921ac043993a852223a27d1224464
<ide><path>Libraries/LinkingIOS/LinkingIOS.js <ide> var Linking = require('Linking'); <ide> var RCTLinkingManager = require('NativeModules').LinkingManager; <ide> var invariant = require('invariant'); <ide> <del>var _initialURL = RCTLinkingManager.initialURL; <add>var _initialURL = RCTLinkingManager && RCTLinkingManager.initialURL; <ide> <ide> /** <ide> * NOTE: `LinkingIOS` is being deprecated. Use `Linking` instead.
1
Python
Python
add support for fetching logs from running pods
19ac45aacb00acc956025be4e607a0d7ea0ef6f2
<ide><path>airflow/kubernetes/pod_launcher.py <ide> def base_container_is_running(self, pod: V1Pod): <ide> wait=tenacity.wait_exponential(), <ide> reraise=True <ide> ) <del> def read_pod_logs(self, pod: V1Pod): <add> def read_pod_logs(self, pod: V1Pod, tail_lines: int = 10): <ide> """Reads log from the POD""" <ide> try: <ide> return self._client.read_namespaced_pod_log( <ide> name=pod.metadata.name, <ide> namespace=pod.metadata.namespace, <ide> container='base', <ide> follow=True, <del> tail_lines=10, <add> tail_lines=tail_lines, <ide> _preload_content=False <ide> ) <ide> except BaseHTTPError as e: <ide><path>airflow/utils/log/file_task_handler.py <ide> def _read(self, ti, try_number, metadata=None): # pylint: disable=unused-argume <ide> except Exception as e: # pylint: disable=broad-except <ide> log = "*** Failed to load local log file: {}\n".format(location) <ide> log += "*** {}\n".format(str(e)) <add> elif conf.get('core', 'executor') == 'KubernetesExecutor': <add> log += '*** Trying to get logs (last 100 lines) from worker pod {} ***\n\n'\ <add> .format(ti.hostname) <add> <add> try: <add> from airflow.kubernetes.kube_client import get_kube_client <add> <add> kube_client = get_kube_client() <add> res = kube_client.read_namespaced_pod_log( <add> name=ti.hostname, <add> namespace=conf.get('kubernetes', 'namespace'), <add> container='base', <add> follow=False, <add> tail_lines=100, <add> _preload_content=False <add> ) <add> <add> for line in res: <add> log += line.decode() <add> <add> except Exception as f: # pylint: disable=broad-except <add> log += '*** Unable to fetch logs from worker pod {} ***\n{}\n\n'.format( <add> ti.hostname, str(f) <add> ) <ide> else: <ide> url = os.path.join( <ide> "http://{ti.hostname}:{worker_log_server_port}/log", log_relative_path <ide><path>tests/kubernetes/test_pod_launcher.py <ide> def test_read_pod_logs_retries_fails(self): <ide> mock.sentinel <ide> ) <ide> <add> def test_read_pod_logs_successfully_with_tail_lines(self): <add> mock.sentinel.metadata = mock.MagicMock() <add> self.mock_kube_client.read_namespaced_pod_log.side_effect = [ <add> mock.sentinel.logs <add> ] <add> logs = self.pod_launcher.read_pod_logs(mock.sentinel, 100) <add> self.assertEqual(mock.sentinel.logs, logs) <add> self.mock_kube_client.read_namespaced_pod_log.assert_has_calls([ <add> mock.call( <add> _preload_content=False, <add> container='base', <add> follow=True, <add> name=mock.sentinel.metadata.name, <add> namespace=mock.sentinel.metadata.namespace, <add> tail_lines=100 <add> ), <add> ]) <add> <ide> def test_read_pod_events_successfully_returns_events(self): <ide> mock.sentinel.metadata = mock.MagicMock() <ide> self.mock_kube_client.list_namespaced_event.return_value = mock.sentinel.events
3
Ruby
Ruby
fix exception in exception
85c3b55e2b77975370dcd0c07b953d281a9c8d07
<ide><path>Library/Homebrew/cask/exceptions.rb <ide> def initialize(path, reason) <ide> end <ide> <ide> def to_s <del> s = "Failed to quarantine #{path}." <add> s = +"Failed to quarantine #{path}." <ide> <ide> unless reason.empty? <ide> s << " Here's the reason:\n" <ide> def to_s <ide> <ide> class CaskQuarantinePropagationError < CaskQuarantineError <ide> def to_s <del> s = "Failed to quarantine one or more files within #{path}." <add> s = +"Failed to quarantine one or more files within #{path}." <ide> <ide> unless reason.empty? <ide> s << " Here's the reason:\n" <ide> def to_s <ide> <ide> class CaskQuarantineReleaseError < CaskQuarantineError <ide> def to_s <del> s = "Failed to release #{path} from quarantine." <add> s = +"Failed to release #{path} from quarantine." <ide> <ide> unless reason.empty? <ide> s << " Here's the reason:\n"
1
Javascript
Javascript
fix assert.strictequal argument order
b4e979ff84bbd366218ddba73ce7f275415b3569
<ide><path>test/addons-napi/test_conversions/test.js <ide> const stringExpected = /string was expected/; <ide> <ide> const testSym = Symbol('test'); <ide> <del>assert.strictEqual(false, test.asBool(false)); <del>assert.strictEqual(true, test.asBool(true)); <add>assert.strictEqual(test.asBool(false), false); <add>assert.strictEqual(test.asBool(true), true); <ide> assert.throws(() => test.asBool(undefined), boolExpected); <ide> assert.throws(() => test.asBool(null), boolExpected); <ide> assert.throws(() => test.asBool(Number.NaN), boolExpected); <ide> assert.throws(() => test.asBool([]), boolExpected); <ide> assert.throws(() => test.asBool(testSym), boolExpected); <ide> <ide> [test.asInt32, test.asUInt32, test.asInt64].forEach((asInt) => { <del> assert.strictEqual(0, asInt(0)); <del> assert.strictEqual(1, asInt(1)); <del> assert.strictEqual(1, asInt(1.0)); <del> assert.strictEqual(1, asInt(1.1)); <del> assert.strictEqual(1, asInt(1.9)); <del> assert.strictEqual(0, asInt(0.9)); <del> assert.strictEqual(999, asInt(999.9)); <del> assert.strictEqual(0, asInt(Number.NaN)); <add> assert.strictEqual(asInt(0), 0); <add> assert.strictEqual(asInt(1), 1); <add> assert.strictEqual(asInt(1.0), 1); <add> assert.strictEqual(asInt(1.1), 1); <add> assert.strictEqual(asInt(1.9), 1); <add> assert.strictEqual(asInt(0.9), 0); <add> assert.strictEqual(asInt(999.9), 999); <add> assert.strictEqual(asInt(Number.NaN), 0); <ide> assert.throws(() => asInt(undefined), numberExpected); <ide> assert.throws(() => asInt(null), numberExpected); <ide> assert.throws(() => asInt(false), numberExpected); <ide> assert.throws(() => test.asBool(testSym), boolExpected); <ide> assert.throws(() => asInt(testSym), numberExpected); <ide> }); <ide> <del>assert.strictEqual(-1, test.asInt32(-1)); <del>assert.strictEqual(-1, test.asInt64(-1)); <del>assert.strictEqual(Math.pow(2, 32) - 1, test.asUInt32(-1)); <add>assert.strictEqual(test.asInt32(-1), -1); <add>assert.strictEqual(test.asInt64(-1), -1); <add>assert.strictEqual(test.asUInt32(-1), Math.pow(2, 32) - 1); <ide> <del>assert.strictEqual(0, test.asDouble(0)); <del>assert.strictEqual(1, test.asDouble(1)); <del>assert.strictEqual(1.0, test.asDouble(1.0)); <del>assert.strictEqual(1.1, test.asDouble(1.1)); <del>assert.strictEqual(1.9, test.asDouble(1.9)); <del>assert.strictEqual(0.9, test.asDouble(0.9)); <del>assert.strictEqual(999.9, test.asDouble(999.9)); <del>assert.strictEqual(-1, test.asDouble(-1)); <add>assert.strictEqual(test.asDouble(0), 0); <add>assert.strictEqual(test.asDouble(1), 1); <add>assert.strictEqual(test.asDouble(1.0), 1.0); <add>assert.strictEqual(test.asDouble(1.1), 1.1); <add>assert.strictEqual(test.asDouble(1.9), 1.9); <add>assert.strictEqual(test.asDouble(0.9), 0.9); <add>assert.strictEqual(test.asDouble(999.9), 999.9); <add>assert.strictEqual(test.asDouble(-1), -1); <ide> assert.ok(Number.isNaN(test.asDouble(Number.NaN))); <ide> assert.throws(() => test.asDouble(undefined), numberExpected); <ide> assert.throws(() => test.asDouble(null), numberExpected); <ide> assert.throws(() => test.asDouble({}), numberExpected); <ide> assert.throws(() => test.asDouble([]), numberExpected); <ide> assert.throws(() => test.asDouble(testSym), numberExpected); <ide> <del>assert.strictEqual('', test.asString('')); <del>assert.strictEqual('test', test.asString('test')); <add>assert.strictEqual(test.asString(''), ''); <add>assert.strictEqual(test.asString('test'), 'test'); <ide> assert.throws(() => test.asString(undefined), stringExpected); <ide> assert.throws(() => test.asString(null), stringExpected); <ide> assert.throws(() => test.asString(false), stringExpected); <ide> assert.throws(() => test.asString({}), stringExpected); <ide> assert.throws(() => test.asString([]), stringExpected); <ide> assert.throws(() => test.asString(testSym), stringExpected); <ide> <del>assert.strictEqual(true, test.toBool(true)); <del>assert.strictEqual(true, test.toBool(1)); <del>assert.strictEqual(true, test.toBool(-1)); <del>assert.strictEqual(true, test.toBool('true')); <del>assert.strictEqual(true, test.toBool('false')); <del>assert.strictEqual(true, test.toBool({})); <del>assert.strictEqual(true, test.toBool([])); <del>assert.strictEqual(true, test.toBool(testSym)); <del>assert.strictEqual(false, test.toBool(false)); <del>assert.strictEqual(false, test.toBool(undefined)); <del>assert.strictEqual(false, test.toBool(null)); <del>assert.strictEqual(false, test.toBool(0)); <del>assert.strictEqual(false, test.toBool(Number.NaN)); <del>assert.strictEqual(false, test.toBool('')); <add>assert.strictEqual(test.toBool(true), true); <add>assert.strictEqual(test.toBool(1), true); <add>assert.strictEqual(test.toBool(-1), true); <add>assert.strictEqual(test.toBool('true'), true); <add>assert.strictEqual(test.toBool('false'), true); <add>assert.strictEqual(test.toBool({}), true); <add>assert.strictEqual(test.toBool([]), true); <add>assert.strictEqual(test.toBool(testSym), true); <add>assert.strictEqual(test.toBool(false), false); <add>assert.strictEqual(test.toBool(undefined), false); <add>assert.strictEqual(test.toBool(null), false); <add>assert.strictEqual(test.toBool(0), false); <add>assert.strictEqual(test.toBool(Number.NaN), false); <add>assert.strictEqual(test.toBool(''), false); <ide> <del>assert.strictEqual(0, test.toNumber(0)); <del>assert.strictEqual(1, test.toNumber(1)); <del>assert.strictEqual(1.1, test.toNumber(1.1)); <del>assert.strictEqual(-1, test.toNumber(-1)); <del>assert.strictEqual(0, test.toNumber('0')); <del>assert.strictEqual(1, test.toNumber('1')); <del>assert.strictEqual(1.1, test.toNumber('1.1')); <del>assert.strictEqual(0, test.toNumber([])); <del>assert.strictEqual(0, test.toNumber(false)); <del>assert.strictEqual(0, test.toNumber(null)); <del>assert.strictEqual(0, test.toNumber('')); <add>assert.strictEqual(test.toNumber(0), 0); <add>assert.strictEqual(test.toNumber(1), 1); <add>assert.strictEqual(test.toNumber(1.1), 1.1); <add>assert.strictEqual(test.toNumber(-1), -1); <add>assert.strictEqual(test.toNumber('0'), 0); <add>assert.strictEqual(test.toNumber('1'), 1); <add>assert.strictEqual(test.toNumber('1.1'), 1.1); <add>assert.strictEqual(test.toNumber([]), 0); <add>assert.strictEqual(test.toNumber(false), 0); <add>assert.strictEqual(test.toNumber(null), 0); <add>assert.strictEqual(test.toNumber(''), 0); <ide> assert.ok(Number.isNaN(test.toNumber(Number.NaN))); <ide> assert.ok(Number.isNaN(test.toNumber({}))); <ide> assert.ok(Number.isNaN(test.toNumber(undefined))); <ide> assert.notDeepStrictEqual(test.toObject(''), ''); <ide> assert.notDeepStrictEqual(test.toObject(0), 0); <ide> assert.ok(!Number.isNaN(test.toObject(Number.NaN))); <ide> <del>assert.strictEqual('', test.toString('')); <del>assert.strictEqual('test', test.toString('test')); <del>assert.strictEqual('undefined', test.toString(undefined)); <del>assert.strictEqual('null', test.toString(null)); <del>assert.strictEqual('false', test.toString(false)); <del>assert.strictEqual('true', test.toString(true)); <del>assert.strictEqual('0', test.toString(0)); <del>assert.strictEqual('1.1', test.toString(1.1)); <del>assert.strictEqual('NaN', test.toString(Number.NaN)); <del>assert.strictEqual('[object Object]', test.toString({})); <del>assert.strictEqual('test', test.toString({ toString: () => 'test' })); <del>assert.strictEqual('', test.toString([])); <del>assert.strictEqual('1,2,3', test.toString([ 1, 2, 3 ])); <add>assert.strictEqual(test.toString(''), ''); <add>assert.strictEqual(test.toString('test'), 'test'); <add>assert.strictEqual(test.toString(undefined), 'undefined'); <add>assert.strictEqual(test.toString(null), 'null'); <add>assert.strictEqual(test.toString(false), 'false'); <add>assert.strictEqual(test.toString(true), 'true'); <add>assert.strictEqual(test.toString(0), '0'); <add>assert.strictEqual(test.toString(1.1), '1.1'); <add>assert.strictEqual(test.toString(Number.NaN), 'NaN'); <add>assert.strictEqual(test.toString({}), '[object Object]'); <add>assert.strictEqual(test.toString({ toString: () => 'test' }), 'test'); <add>assert.strictEqual(test.toString([]), ''); <add>assert.strictEqual(test.toString([ 1, 2, 3 ]), '1,2,3'); <ide> assert.throws(() => test.toString(testSym), TypeError);
1
PHP
PHP
fix coding standards
9d5b832c999ce3b4cdb85e3edd6190476b248a65
<ide><path>Cake/Controller/Component/PaginatorComponent.php <ide> <?php <ide> /** <del> * Paginator Component <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> * ### Configuring pagination <ide> * <ide> * You configure pagination when calling paginate(). See that method for more details. <add> * <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html <ide> */ <ide> class PaginatorComponent extends Component { <ide><path>Cake/Controller/Controller.php <ide> use Cake\Event\Event; <ide> use Cake\Event\EventListener; <ide> use Cake\Event\EventManager; <del>use Cake\ORM\TableRegistry; <ide> use Cake\Network\Request; <ide> use Cake\Network\Response; <add>use Cake\ORM\TableRegistry; <ide> use Cake\Routing\RequestActionTrait; <ide> use Cake\Routing\Router; <ide> use Cake\Utility\ClassRegistry; <ide><path>Cake/Test/TestCase/Controller/Component/PaginatorComponentTest.php <ide> <?php <ide> /** <del> * PaginatorComponentTest file <del> * <del> * Series of tests for paginator component. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> namespace Cake\Test\TestCase\Controller\Component; <ide> <ide> use Cake\Controller\Component\PaginatorComponent; <del>use Cake\Controller\Controller; <ide> use Cake\Controller\ComponentRegistry; <add>use Cake\Controller\Controller; <ide> use Cake\Core\Configure; <ide> use Cake\Database\ConnectionManager; <ide> use Cake\Error;
3
Javascript
Javascript
add redirects for legacy certification paths
6f8d36f4a74f1f0509585d48324801551f1e34a7
<ide><path>server/boot/certificate.js <ide> export default function certificate(app) { <ide> <ide> const superBlocks = Object.keys(superBlockCertTypeMap); <ide> <add> router.get( <add> '/:username/front-end-certification', <add> (req, res) => res.redirect( <add> `/certification/${req.params.username}/legacy-front-end` <add> ) <add> ); <add> <add> router.get( <add> '/:username/data-visualization-certification', <add> (req, res) => res.redirect( <add> `/certification/${req.params.username}/legacy-data-visualization` <add> ) <add> ); <add> <add> router.get( <add> '/:username/back-end-certification', <add> (req, res) => res.redirect( <add> `/certification/${req.params.username}/legacy-back-end` <add> ) <add> ); <add> <add> router.get( <add> '/:username/full-stack-certification', <add> (req, res) => res.redirect( <add> `/certification/${req.params.username}/legacy-full-stack` <add> ) <add> ); <add> <ide> router.post( <ide> '/certificate/verify', <ide> ifNoUser401,
1
PHP
PHP
add missing param tag
79cd455c40c5c81f835601ef115ce8c1928a341d
<ide><path>Cake/Database/Query.php <ide> protected function _stringifyExpressions(array $expressions, ValueBinder $genera <ide> * <ide> * @param string $table The table name to insert into. <ide> * @param array $columns The columns to insert into. <add> * @param array $types A map between columns & their datatypes. <ide> * @return Query <ide> */ <ide> public function insert($table, $columns, $types = []) {
1
Java
Java
remove trailing whitespace from source code
c335e99e3f720337dd2a01b4c8ea9d34718b9854
<ide><path>spring-aspects/src/test/java/org/springframework/mock/staticmock/AnnotationDrivenStaticEntityMockingControlTests.java <ide> /** <ide> * Tests for Spring's static entity mocking framework (i.e., @{@link MockStaticEntityMethods} <ide> * and {@link AnnotationDrivenStaticEntityMockingControl}). <del> * <add> * <ide> * @author Rod Johnson <ide> * @author Ramnivas Laddad <ide> * @author Sam Brannen <ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheExpressionRootObject.java <ide> <ide> /** <ide> * Class describing the root object used during the expression evaluation. <del> * <add> * <ide> * @author Costin Leau <ide> * @author Sam Brannen <ide> * @since 3.1 <ide><path>spring-context/src/test/java/org/springframework/context/annotation/Spr11202Tests.java <ide> public void testWithImporter() { <ide> context = new AnnotationConfigApplicationContext(Wrapper.class); <ide> assertEquals("foo", context.getBean("value")); <ide> } <del> <add> <ide> @Test // Passes <ide> public void testWithoutImporter() { <ide> context = new AnnotationConfigApplicationContext(Config.class); <ide> assertEquals("foo", context.getBean("value")); <ide> } <del> <add> <ide> <ide> @Configuration <ide> @Import(Selector.class) <ide> protected static class Wrapper { <ide> } <del> <add> <ide> protected static class Selector implements ImportSelector { <ide> <ide> @Override <ide><path>spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java <ide> public void testImportDifferentResourceTypes() { <ide> reader=XmlBeanDefinitionReader.class) <ide> static class SubResourceConfig extends ImportNonXmlResourceConfig { <ide> } <del> <add> <ide> @Test <ide> public void importWithPlaceHolder() throws Exception { <ide> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); <del> PropertySource<?> propertySource = new MapPropertySource("test", <add> PropertySource<?> propertySource = new MapPropertySource("test", <ide> Collections.<String, Object> singletonMap("test", "springframework")); <ide> ctx.getEnvironment().getPropertySources().addFirst(propertySource); <ide> ctx.register(ImportXmlConfig.class); <ide> public void importWithPlaceHolder() throws Exception { <ide> @ImportResource("classpath:org/${test}/context/annotation/configuration/ImportXmlConfig-context.xml") <ide> static class ImportWithPlaceHolder { <ide> } <del> <del> <add> <add> <ide> } <ide><path>spring-core/src/test/java/org/springframework/core/annotation/subpackage/NonPublicAnnotatedClass.java <ide> <ide> /** <ide> * Class annotated with a non-public (i.e., package private) custom annotation. <del> * <add> * <ide> * @author Sam Brannen <ide> * @since 4.0 <ide> */ <ide><path>spring-core/src/test/java/org/springframework/core/annotation/subpackage/NonPublicAnnotation.java <ide> <ide> /** <ide> * Non-public (i.e., package private) custom annotation. <del> * <add> * <ide> * @author Sam Brannen <ide> * @since 4.0 <ide> */ <ide><path>spring-core/src/test/java/org/springframework/core/type/CachingMetadataReaderLeakTests.java <ide> * Unit tests for checking the behaviour of {@link CachingMetadataReaderFactory} under <ide> * load. If the cache is not controlled, this test should fail with an out of memory <ide> * exception around entry 5k. <del> * <add> * <ide> * @author Costin Leau <ide> * @author Sam Brannen <ide> */ <ide><path>spring-expression/src/main/java/org/springframework/expression/ConstructorResolver.java <ide> * A constructor resolver attempts locate a constructor and returns a ConstructorExecutor <ide> * that can be used to invoke that constructor. The ConstructorExecutor will be cached but <ide> * if it 'goes stale' the resolvers will be called again. <del> * <add> * <ide> * @author Andy Clement <ide> * @since 3.0 <ide> */ <ide><path>spring-expression/src/main/java/org/springframework/expression/common/TemplateAwareExpressionParser.java <ide> /** <ide> * An expression parser that understands templates. It can be subclassed by expression <ide> * parsers that do not offer first class support for templating. <del> * <add> * <ide> * @author Keith Donald <ide> * @author Juergen Hoeller <ide> * @author Andy Clement <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/SpelParseException.java <ide> * Root exception for Spring EL related exceptions. Rather than holding a hard coded <ide> * string indicating the problem, it records a message key and the inserts for the <ide> * message. See {@link SpelMessage} for the list of all possible messages that can occur. <del> * <add> * <ide> * @author Andy Clement <ide> * @since 3.0 <ide> */ <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTests.java <ide> <ide> /** <ide> * Tests for {@link DelegatingDataSource}. <del> * <add> * <ide> * @author Phillip Webb <ide> */ <ide> public class DelegatingDataSourceTests { <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/MessageExceptionHandler.java <ide> /** <ide> * Annotation for handling exceptions thrown from message-handling methods within a <ide> * specific handler class. <del> * <add> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/SharedEntityManagerCreatorTests.java <ide> <ide> /** <ide> * Unit tests for {@link SharedEntityManagerCreator}. <del> * <add> * <ide> * @author Oliver Gierke <ide> */ <ide> public class SharedEntityManagerCreatorTests { <ide><path>spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java <ide> * The result is that three application contexts will be loaded (one for each <ide> * declaration of {@code @ContextConfiguration}, and the application context <ide> * loaded based on the configuration in {@code AbstractWebTests} will be set as <del> * the parent context for each of the contexts loaded for the concrete subclasses. <add> * the parent context for each of the contexts loaded for the concrete subclasses. <ide> * <ide> * <pre class="code"> <ide> * &#064;RunWith(SpringJUnit4ClassRunner.class) <ide> * &#064;ContextConfiguration(name = "child", locations = "/user-config.xml") <ide> * }) <ide> * public class BaseTests {} <del> * <add> * <ide> * &#064;ContextHierarchy( <ide> * &#064;ContextConfiguration(name = "child", locations = "/order-config.xml") <ide> * ) <ide> * by setting the {@link ContextConfiguration#inheritLocations} flag to {@code false}. <ide> * Consequently, the application context for {@code ExtendedTests} will be loaded <ide> * only from {@code "/test-user-config.xml"} and will have its parent set to the <del> * context loaded from {@code "/app-config.xml"}. <add> * context loaded from {@code "/app-config.xml"}. <ide> * <ide> * <pre class="code"> <ide> * &#064;RunWith(SpringJUnit4ClassRunner.class) <ide> * &#064;ContextConfiguration(name = "child", locations = "/user-config.xml") <ide> * }) <ide> * public class BaseTests {} <del> * <add> * <ide> * &#064;ContextHierarchy( <ide> * &#064;ContextConfiguration(name = "child", locations = "/test-user-config.xml", inheritLocations=false) <ide> * ) <ide><path>spring-test/src/main/java/org/springframework/test/context/MetaAnnotationUtils.java <ide> public static <T extends Annotation> AnnotationDescriptor<T> findAnnotationDescr <ide> * the specified {@code clazz} itself) which declares at least one of the <ide> * specified {@code annotationTypes}, or {@code null} if none of the <ide> * specified annotation types could be found. <del> * <add> * <ide> * <p>This method traverses the annotations and superclasses of the specified <ide> * {@code clazz} if no annotation can be found on the given class itself. <ide> * <ide><path>spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/DirtiesContextWithContextHierarchyTests.java <ide> * <ide> * <p>Note that correct method execution order is essential, thus the use of <ide> * {@link FixMethodOrder}. <del> * <add> * <ide> * @author Sam Brannen <ide> * @since 3.2.2 <ide> */ <ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/aci/annotation/InitializerWithoutConfigFilesOrClassesTests.java <ide> * Integration test that verifies support for {@link ApplicationContextInitializer <ide> * ApplicationContextInitializers} in the TestContext framework when the test class <ide> * declares neither XML configuration files nor annotated configuration classes. <del> * <add> * <ide> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <ide><path>spring-test/src/test/java/org/springframework/test/context/web/ServletContextAwareBean.java <ide> <ide> /** <ide> * Introduced to investigate claims in SPR-11145. <del> * <add> * <ide> * @author Sam Brannen <ide> * @since 4.0.2 <ide> */ <ide><path>spring-test/src/test/java/org/springframework/test/context/web/ServletContextAwareBeanWacTests.java <ide> <ide> /** <ide> * Introduced to investigate claims in SPR-11145. <del> * <add> * <ide> * <p> <ide> * Yes, this test class does in fact use JUnit to run JUnit. ;) <del> * <add> * <ide> * @author Sam Brannen <ide> * @since 4.0.2 <ide> */ <ide><path>spring-web/src/test/java/org/springframework/mock/web/test/MockHttpSession.java <ide> public boolean isInvalid() { <ide> /** <ide> * Convenience method for asserting that this session has not been <ide> * {@linkplain #invalidate() invalidated}. <del> * <add> * <ide> * @throws IllegalStateException if this session has been invalidated <ide> */ <ide> private void assertIsValid() {
20
Javascript
Javascript
pass error on legacy destroy
51beb26a5fe0b409b976271cab6bf386eff8738a
<ide><path>lib/internal/streams/destroy.js <ide> function destroyer(stream, err) { <ide> // TODO: Don't lose err? <ide> stream.close(); <ide> } else if (err) { <del> process.nextTick(emitErrorCloseLegacy, stream); <add> process.nextTick(emitErrorCloseLegacy, stream, err); <ide> } else { <ide> process.nextTick(emitCloseLegacy, stream); <ide> } <ide><path>test/parallel/test-stream-pipeline.js <ide> const tsp = require('timers/promises'); <ide> assert.strictEqual(val, null); <ide> })); <ide> } <add> <add>{ <add> // Mimics a legacy stream without the .destroy method <add> class LegacyWritable extends Stream { <add> write(chunk, encoding, callback) { <add> callback(); <add> } <add> } <add> <add> const writable = new LegacyWritable(); <add> writable.on('error', common.mustCall((err) => { <add> assert.deepStrictEqual(err, new Error('stop')); <add> })); <add> <add> pipeline( <add> Readable.from({ <add> [Symbol.asyncIterator]() { <add> return { <add> next() { <add> return Promise.reject(new Error('stop')); <add> } <add> }; <add> } <add> }), <add> writable, <add> common.mustCall((err) => { <add> assert.deepStrictEqual(err, new Error('stop')); <add> }) <add> ); <add>}
2
Go
Go
use filepath.walkdir instead of filepath.walk
3db11af44b76b6554ff37799de56a36bd22b3c6d
<ide><path>libnetwork/drivers/overlay/ov_network.go <ide> func (n *network) destroySandbox() { <ide> } <ide> <ide> func populateVNITbl() { <del> filepath.Walk(filepath.Dir(osl.GenerateKey("walk")), <add> filepath.WalkDir(filepath.Dir(osl.GenerateKey("walk")), <ide> // NOTE(cpuguy83): The linter picked up on the fact that this walk function was not using this error argument <ide> // That seems wrong... however I'm not familiar with this code or if that error matters <del> func(path string, info os.FileInfo, _ error) error { <add> func(path string, _ os.DirEntry, _ error) error { <ide> _, fname := filepath.Split(path) <ide> <ide> if len(strings.Split(fname, "-")) <= 1 { <ide> return nil <ide> } <ide> <del> ns, err := netns.GetFromPath(path) <add> n, err := netns.GetFromPath(path) <ide> if err != nil { <ide> logrus.Errorf("Could not open namespace path %s during vni population: %v", path, err) <ide> return nil <ide> } <del> defer ns.Close() <add> defer n.Close() <ide> <del> nlh, err := netlink.NewHandleAt(ns, unix.NETLINK_ROUTE) <add> nlh, err := netlink.NewHandleAt(n, unix.NETLINK_ROUTE) <ide> if err != nil { <ide> logrus.Errorf("Could not open netlink handle during vni population for ns %s: %v", path, err) <ide> return nil <ide> func (n *network) initSubnetSandbox(s *subnet, restore bool) error { <ide> } <ide> <ide> func (n *network) cleanupStaleSandboxes() { <del> filepath.Walk(filepath.Dir(osl.GenerateKey("walk")), <del> func(path string, info os.FileInfo, err error) error { <add> filepath.WalkDir(filepath.Dir(osl.GenerateKey("walk")), <add> func(path string, _ os.DirEntry, _ error) error { <ide> _, fname := filepath.Split(path) <ide> <ide> pList := strings.Split(fname, "-")
1
Python
Python
fix spangroup import
0563cd73d6b9dc9a5cc639f9a33e45691229d82a
<ide><path>spacy/tokens/__init__.py <ide> from .doc import Doc <ide> from .token import Token <ide> from .span import Span <add>from .span_group import SpanGroup <ide> from ._serialize import DocBin <ide> from .morphanalysis import MorphAnalysis <ide> <del>__all__ = ["Doc", "Token", "Span", "DocBin", "MorphAnalysis"] <add>__all__ = ["Doc", "Token", "Span", "SpanGroup", "DocBin", "MorphAnalysis"]
1
Go
Go
remove ref counting from layer store
e19499710e3728433cdc8348e985f9a825cb2336
<ide><path>layer/layer_store.go <ide> func (ls *layerStore) ReinitRWLayer(l RWLayer) error { <ide> ls.mountL.Lock() <ide> defer ls.mountL.Unlock() <ide> <del> m, ok := ls.mounts[l.Name()] <del> if !ok { <add> if _, ok := ls.mounts[l.Name()]; !ok { <ide> return ErrMountDoesNotExist <ide> } <del> <del> if err := m.incActivityCount(l); err != nil { <del> return err <del> } <del> <ide> return nil <ide> } <ide> <ide><path>layer/layer_test.go <ide> func TestStoreRestore(t *testing.T) { <ide> if err := ioutil.WriteFile(filepath.Join(path, "testfile.txt"), []byte("nothing here"), 0644); err != nil { <ide> t.Fatal(err) <ide> } <del> assertActivityCount(t, m, 1) <ide> <ide> if err := m.Unmount(); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> assertActivityCount(t, m, 0) <del> <ide> ls2, err := NewStoreFromGraphDriver(ls.(*layerStore).store, ls.(*layerStore).driver) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestStoreRestore(t *testing.T) { <ide> t.Fatalf("Unexpected path %s, expected %s", mountPath, path) <ide> } <ide> <del> assertActivityCount(t, m2, 1) <del> <ide> if mountPath, err := m2.Mount(""); err != nil { <ide> t.Fatal(err) <ide> } else if path != mountPath { <ide> t.Fatalf("Unexpected path %s, expected %s", mountPath, path) <ide> } <del> assertActivityCount(t, m2, 2) <ide> if err := m2.Unmount(); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> assertActivityCount(t, m2, 1) <del> <ide> b, err := ioutil.ReadFile(filepath.Join(path, "testfile.txt")) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestStoreRestore(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> assertActivityCount(t, m2, 0) <del> <ide> if metadata, err := ls2.ReleaseRWLayer(m2); err != nil { <ide> t.Fatal(err) <ide> } else if len(metadata) != 0 { <ide> func assertReferences(t *testing.T, references ...Layer) { <ide> } <ide> } <ide> <del>func assertActivityCount(t *testing.T, l RWLayer, expected int) { <del> rl := l.(*referencedRWLayer) <del> if rl.activityCount != expected { <del> t.Fatalf("Unexpected activity count %d, expected %d", rl.activityCount, expected) <del> } <del>} <del> <ide> func TestRegisterExistingLayer(t *testing.T) { <ide> ls, _, cleanup := newTestStore(t) <ide> defer cleanup() <ide><path>layer/migration_test.go <ide> func TestMountMigration(t *testing.T) { <ide> Kind: archive.ChangeAdd, <ide> }) <ide> <del> assertActivityCount(t, rwLayer1, 1) <del> <ide> if _, err := ls.CreateRWLayer("migration-mount", layer1.ChainID(), "", nil, nil); err == nil { <ide> t.Fatal("Expected error creating mount with same name") <ide> } else if err != ErrMountNameConflict { <ide> func TestMountMigration(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> <del> assertActivityCount(t, rwLayer2, 1) <del> assertActivityCount(t, rwLayer1, 1) <del> <ide> if _, err := rwLayer2.Mount(""); err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> assertActivityCount(t, rwLayer2, 2) <del> assertActivityCount(t, rwLayer1, 1) <del> <ide> if metadata, err := ls.Release(layer1); err != nil { <ide> t.Fatal(err) <ide> } else if len(metadata) > 0 { <ide> func TestMountMigration(t *testing.T) { <ide> if err := rwLayer1.Unmount(); err != nil { <ide> t.Fatal(err) <ide> } <del> assertActivityCount(t, rwLayer2, 2) <del> assertActivityCount(t, rwLayer1, 0) <ide> <ide> if _, err := ls.ReleaseRWLayer(rwLayer1); err != nil { <ide> t.Fatal(err) <ide> func TestMountMigration(t *testing.T) { <ide> if err := rwLayer2.Unmount(); err != nil { <ide> t.Fatal(err) <ide> } <del> if _, err := ls.ReleaseRWLayer(rwLayer2); err == nil { <del> t.Fatal("Expected error deleting active mount") <del> } <ide> if err := rwLayer2.Unmount(); err != nil { <ide> t.Fatal(err) <ide> } <ide><path>layer/mounted_layer.go <ide> package layer <ide> <ide> import ( <ide> "io" <del> "sync" <ide> <ide> "github.com/docker/docker/pkg/archive" <ide> ) <ide> func (ml *mountedLayer) hasReferences() bool { <ide> return len(ml.references) > 0 <ide> } <ide> <del>func (ml *mountedLayer) incActivityCount(ref RWLayer) error { <del> rl, ok := ml.references[ref] <del> if !ok { <del> return ErrLayerNotRetained <del> } <del> <del> if err := rl.acquire(); err != nil { <del> return err <del> } <del> return nil <del>} <del> <ide> func (ml *mountedLayer) deleteReference(ref RWLayer) error { <del> rl, ok := ml.references[ref] <del> if !ok { <add> if _, ok := ml.references[ref]; !ok { <ide> return ErrLayerNotRetained <ide> } <del> <del> if err := rl.release(); err != nil { <del> return err <del> } <ide> delete(ml.references, ref) <del> <ide> return nil <ide> } <ide> <ide> func (ml *mountedLayer) retakeReference(r RWLayer) { <ide> if ref, ok := r.(*referencedRWLayer); ok { <del> ref.activityCount = 0 <ide> ml.references[ref] = ref <ide> } <ide> } <ide> <ide> type referencedRWLayer struct { <ide> *mountedLayer <del> <del> activityL sync.Mutex <del> activityCount int <del>} <del> <del>func (rl *referencedRWLayer) acquire() error { <del> rl.activityL.Lock() <del> defer rl.activityL.Unlock() <del> <del> rl.activityCount++ <del> <del> return nil <del>} <del> <del>func (rl *referencedRWLayer) release() error { <del> rl.activityL.Lock() <del> defer rl.activityL.Unlock() <del> <del> if rl.activityCount > 0 { <del> return ErrActiveMount <del> } <del> <del> rl.activityCount = -1 <del> <del> return nil <ide> } <ide> <ide> func (rl *referencedRWLayer) Mount(mountLabel string) (string, error) { <del> rl.activityL.Lock() <del> defer rl.activityL.Unlock() <del> <del> if rl.activityCount == -1 { <del> return "", ErrLayerNotRetained <del> } <del> <del> if rl.activityCount > 0 { <del> rl.activityCount++ <del> return rl.path, nil <del> } <del> <del> m, err := rl.mountedLayer.Mount(mountLabel) <del> if err == nil { <del> rl.activityCount++ <del> rl.path = m <del> } <del> return m, err <add> return rl.mountedLayer.Mount(mountLabel) <ide> } <ide> <ide> // Unmount decrements the activity count and unmounts the underlying layer <ide> // Callers should only call `Unmount` once per call to `Mount`, even on error. <ide> func (rl *referencedRWLayer) Unmount() error { <del> rl.activityL.Lock() <del> defer rl.activityL.Unlock() <del> <del> if rl.activityCount == 0 { <del> return ErrNotMounted <del> } <del> if rl.activityCount == -1 { <del> return ErrLayerNotRetained <del> } <del> <del> rl.activityCount-- <del> if rl.activityCount > 0 { <del> return nil <del> } <del> <ide> return rl.mountedLayer.Unmount() <ide> }
4
Python
Python
remove redundant parentheses
938cf201da513ab51d9c88990124607122994c5f
<ide><path>glances/plugins/glances_system.py <ide> def update(self): <ide> else: <ide> self.stats['hr_name'] = '{0} {1}'.format( <ide> self.stats['os_name'], self.stats['os_version']) <del> self.stats['hr_name'] += ' ({0})'.format(self.stats['platform']) <add> self.stats['hr_name'] += ' {0}'.format(self.stats['platform']) <ide> <ide> elif self.input_method == 'snmp': <ide> # Update stats using SNMP
1
Text
Text
add sass gobbling info to asset pipeline docs
4990a793470a1454d1ac06ad888c872e4ec50f9b
<ide><path>guides/source/asset_pipeline.md <ide> NOTE. If you want to use multiple Sass files, you should generally use the [Sass <ide> rule](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import) instead <ide> of these Sprockets directives. Using Sprockets directives all Sass files exist <ide> within their own scope, making variables or mixins only available within the <del>document they were defined in. <add>document they were defined in. You can do file globbing as well using <add>`@import "*"`, and `@import "**/*"` to add the whole tree equivalent to how <add>`require_tree` works. Check the [sass-rails <add>documentation](https://github.com/rails/sass-rails#features) for more info and <add>important caveats. <ide> <ide> You can have as many manifest files as you need. For example, the `admin.css` <ide> and `admin.js` manifest could contain the JS and CSS files that are used for the
1
Text
Text
add punctuation. [ci skip]
65520c29f7e9fbd654446624a5c267bdc6285341
<ide><path>activerecord/CHANGELOG.md <del>* Added ActiveRecord::SecureToken in order to encapsulate generation of <del> unique tokens for attributes in a model using SecureRandom <add>* Added `ActiveRecord::SecureToken` in order to encapsulate generation of <add> unique tokens for attributes in a model using `SecureRandom`. <ide> <ide> *Roberto Miranda* <ide>
1
Javascript
Javascript
fix setproctitle on freebsd
27e9ed6e9819794220fa7bd682125116ae76d3c4
<ide><path>test/sequential/test-setproctitle.js <ide> exec('ps -p ' + process.pid + ' -o args=', function(error, stdout, stderr) { <ide> assert.equal(stderr, ''); <ide> <ide> // freebsd always add ' (procname)' to the process title <del> if (process.platform === 'freebsd') title += ' (node)'; <add> if (process.platform === 'freebsd') title += ' (iojs)'; <ide> <ide> // omitting trailing whitespace and \n <ide> assert.equal(stdout.replace(/\s+$/, ''), title);
1
PHP
PHP
add a when method to collection
3cf02fa30ff6087ad14111c6d73e917dcb2920a6
<ide><path>src/Illuminate/Support/Collection.php <ide> public function filter(callable $callback = null) <ide> return new static(array_filter($this->items)); <ide> } <ide> <add> /** <add> * Apply the callback if the value is truthy. <add> * <add> * @param bool $value <add> * @param callable $callback <add> * @return mixed <add> */ <add> public function when($value, callable $callback) <add> { <add> if ($value) { <add> return $callback($this); <add> } <add> <add> return $this; <add> } <add> <ide> /** <ide> * Filter items by the given key value pair. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testTap() <ide> $this->assertSame([1], $fromTap); <ide> $this->assertSame([1, 2, 3], $collection->toArray()); <ide> } <add> <add> public function testWhen() <add> { <add> $collection = new Collection(['michael', 'tom']); <add> <add> $collection->when(true, function ($collection) { <add> return $collection->push('adam'); <add> }); <add> <add> $this->assertSame(['michael', 'tom', 'adam'], $collection->toArray()); <add> <add> $collection = new Collection(['michael', 'tom']); <add> <add> $collection->when(false, function ($collection) { <add> return $collection->push('adam'); <add> }); <add> <add> $this->assertSame(['michael', 'tom'], $collection->toArray()); <add> } <ide> } <ide> <ide> class TestSupportCollectionHigherOrderItem
2
Ruby
Ruby
fix typos on the csrf whitelisting doc
faf27445d0f3bccdde6624ac0c7e156fdb263e5b
<ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb <ide> class InvalidAuthenticityToken < ActionControllerError #:nodoc: <ide> # Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks <ide> # by including a token in the rendered html for your application. This token is <ide> # stored as a random string in the session, to which an attacker does not have <del> # access. When a request reaches your application, Rails verifies the received <add> # access. When a request reaches your application, \Rails verifies the received <ide> # token with the token in the session. All requests are checked except GET requests <del> # as these should be idempotent. It's is important to remember that XML or JSON <del> # requests are also affected and if you're building an API you'll need <add> # as these should be idempotent. It's important to remember that XML or JSON <add> # requests are also affected and if you're building an API you'll need <ide> # something like that: <ide> # <ide> # class ApplicationController < ActionController::Base
1
Python
Python
enable auto_delete for the result queues again
a3bd35c653a66173dcc28586a7f196a1d5026e64
<ide><path>celery/backends/amqp.py <ide> class AMQResultWarning(UserWarning): <ide> <ide> <ide> class ResultPublisher(Publisher): <del> auto_delete = False <add> exchange = conf.RESULT_EXCHANGE <add> exchange_type = conf.RESULT_EXCHANGE_TYPE <add> delivery_mode = conf.RESULT_PERSISTENT and 2 or 1 <add> serializer = conf.RESULT_SERIALIZER <add> durable = conf.RESULT_PERSISTENT <add> auto_delete = True <ide> <ide> def __init__(self, connection, task_id, **kwargs): <ide> super(ResultPublisher, self).__init__(connection, <ide> def __init__(self, connection, task_id, **kwargs): <ide> <ide> class ResultConsumer(Consumer): <ide> no_ack = True <del> auto_delete = False <add> auto_delete = True <ide> <ide> def __init__(self, connection, task_id, **kwargs): <ide> routing_key = task_id.replace("-", "")
1
Java
Java
add nullable annotation to simple queue (fixes )
e5d3b0e1de992719c88766558c4b5ad21a8725ba
<ide><path>src/main/java/io/reactivex/internal/disposables/EmptyDisposable.java <ide> package io.reactivex.internal.disposables; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.internal.fuseable.QueueDisposable; <ide> <ide> /** <ide> public boolean offer(Object v1, Object v2) { <ide> throw new UnsupportedOperationException("Should not be called!"); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Object poll() throws Exception { <ide> return null; // always empty <ide><path>src/main/java/io/reactivex/internal/fuseable/SimplePlainQueue.java <ide> <ide> package io.reactivex.internal.fuseable; <ide> <add>import io.reactivex.annotations.Nullable; <add> <ide> /** <ide> * Override of the SimpleQueue interface with no throws Exception on poll. <ide> * <ide> * @param <T> the value type to enqueue and dequeue, not null <ide> */ <ide> public interface SimplePlainQueue<T> extends SimpleQueue<T> { <ide> <add> @Nullable <ide> @Override <ide> T poll(); <ide> } <ide><path>src/main/java/io/reactivex/internal/fuseable/SimpleQueue.java <ide> <ide> package io.reactivex.internal.fuseable; <ide> <add>import io.reactivex.annotations.Nullable; <add> <ide> /** <ide> * A minimalist queue interface without the method bloat of java.util.Collection and java.util.Queue. <ide> * <ide> <ide> boolean offer(T v1, T v2); <ide> <add> /** <add> * @return null to indicate an empty queue <add> */ <add> @Nullable <ide> T poll() throws Exception; <ide> <ide> boolean isEmpty(); <ide><path>src/main/java/io/reactivex/internal/observers/DeferredScalarDisposable.java <ide> package io.reactivex.internal.observers; <ide> <ide> import io.reactivex.Observer; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> /** <ide> public final void complete() { <ide> actual.onComplete(); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public final T poll() throws Exception { <ide> if (get() == FUSED_READY) { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java <ide> import java.util.Iterator; <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <ide> public int requestFusion(int requestedMode) { <ide> return m; <ide> } <ide> <add> @Nullable <ide> @SuppressWarnings("unchecked") <ide> @Override <ide> public R poll() throws Exception { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinct.java <ide> import java.util.Collection; <ide> import java.util.concurrent.Callable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.exceptions.Exceptions; <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> for (;;) { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDistinctUntilChanged.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.functions.*; <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> for (;;) { <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> for (;;) { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDoAfterNext.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.annotations.Experimental; <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = qs.poll(); <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = qs.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDoFinally.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.annotations.Experimental; <ide> public boolean isEmpty() { <ide> return qs.isEmpty(); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = qs.poll(); <ide> public boolean isEmpty() { <ide> return qs.isEmpty(); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = qs.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnEach.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.exceptions.*; <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = qs.poll(); <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = qs.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFilter.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.functions.Predicate; <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> QueueSubscription<T> qs = this.qs; <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> QueueSubscription<T> qs = this.qs; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapCompletable.java <ide> <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <ide> public void request(long n) { <ide> // ignored, no values emitted <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> return null; // always empty <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java <ide> import java.util.concurrent.Callable; <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.exceptions.*; <ide> public boolean isEmpty() { <ide> return (it != null && !it.hasNext()) || queue.isEmpty(); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public R poll() throws Exception { <ide> Iterator<? extends R> it = current; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFromArray.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.Flowable; <ide> public final int requestFusion(int mode) { <ide> return mode & SYNC; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public final T poll() { <ide> int i = index; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java <ide> <ide> import java.util.Iterator; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.Flowable; <ide> public final int requestFusion(int mode) { <ide> return mode & SYNC; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public final T poll() { <ide> if (it == null) { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.exceptions.Exceptions; <ide> public int requestFusion(int mode) { <ide> return NONE; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public GroupedFlowable<K, V> poll() { <ide> return queue.poll(); <ide> public int requestFusion(int mode) { <ide> return NONE; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() { <ide> T v = queue.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElements.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.internal.fuseable.QueueSubscription; <ide> public boolean offer(T v1, T v2) { <ide> throw new UnsupportedOperationException("Should not be called!"); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() { <ide> return null; // empty, always <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableMap.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.functions.Function; <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public U poll() throws Exception { <ide> T t = qs.poll(); <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public U poll() throws Exception { <ide> T t = qs.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java <ide> <ide> import java.util.concurrent.atomic.AtomicLong; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Scheduler; <ide> void runBackfused() { <ide> } <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = queue.poll(); <ide> void runBackfused() { <ide> } <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = queue.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java <ide> <ide> import java.util.concurrent.atomic.AtomicLong; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.exceptions.*; <ide> public int requestFusion(int mode) { <ide> return NONE; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> return queue.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableRange.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.Flowable; <ide> public final int requestFusion(int mode) { <ide> return mode & SYNC; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public final Integer poll() { <ide> int i = index; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableRangeLong.java <ide> package io.reactivex.internal.operators.flowable; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.internal.fuseable.ConditionalSubscriber; <ide> import io.reactivex.internal.subscriptions.BasicQueueSubscription; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> public final int requestFusion(int mode) { <ide> return mode & SYNC; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public final Long poll() { <ide> long i = index; <ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableFlowable.java <ide> import java.util.Iterator; <ide> import java.util.concurrent.atomic.AtomicLong; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.*; <ide> public boolean isEmpty() { <ide> return it == null; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public R poll() throws Exception { <ide> Iterator<? extends R> iter = it; <ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeFlatMapIterableObservable.java <ide> import java.util.Iterator; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> public boolean isEmpty() { <ide> return it == null; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public R poll() throws Exception { <ide> Iterator<? extends R> iter = it; <ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeMergeArray.java <ide> import java.util.concurrent.ConcurrentLinkedQueue; <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.*; <ide> public int requestFusion(int mode) { <ide> return NONE; <ide> } <ide> <add> @Nullable <ide> @SuppressWarnings("unchecked") <ide> @Override <ide> public T poll() throws Exception { <ide> void drain() { <ide> <ide> interface SimpleQueueWithConsumerIndex<T> extends SimpleQueue<T> { <ide> <add> @Nullable <ide> @Override <ide> T poll(); <ide> <ide> public boolean offer(T v1, T v2) { <ide> throw new UnsupportedOperationException(); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() { <ide> int ci = consumerIndex; <ide> public boolean offer(T e) { <ide> return super.offer(e); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() { <ide> T v = super.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDistinct.java <ide> import java.util.concurrent.Callable; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> for (;;) { <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDistinctUntilChanged.java <ide> package io.reactivex.internal.operators.observable; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.observers.BasicFuseableObserver; <ide> <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> for (;;) { <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDoAfterNext.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.annotations.Experimental; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.observers.BasicFuseableObserver; <ide> <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = qs.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDoFinally.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.annotations.Experimental; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Action; <ide> public boolean isEmpty() { <ide> return qd.isEmpty(); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> T v = qd.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableFilter.java <ide> package io.reactivex.internal.operators.observable; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.functions.Predicate; <ide> import io.reactivex.internal.observers.BasicFuseableObserver; <ide> <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> for (;;) { <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMapCompletable.java <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.disposables.*; <ide> import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> public boolean isDisposed() { <ide> return d.isDisposed(); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> return null; // always empty <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableFromArray.java <ide> package io.reactivex.internal.operators.observable; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.internal.functions.ObjectHelper; <ide> import io.reactivex.internal.observers.BasicQueueDisposable; <ide> <ide> public int requestFusion(int mode) { <ide> return NONE; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() { <ide> int i = index; <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableFromIterable.java <ide> import java.util.Iterator; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <ide> import io.reactivex.internal.functions.ObjectHelper; <ide> public int requestFusion(int mode) { <ide> return NONE; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() { <ide> if (done) { <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableMap.java <ide> package io.reactivex.internal.operators.observable; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.ObjectHelper; <ide> import io.reactivex.internal.observers.BasicFuseableObserver; <ide> public int requestFusion(int mode) { <ide> return transitiveBoundaryFusion(mode); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public U poll() throws Exception { <ide> T t = qs.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableObserveOn.java <ide> package io.reactivex.internal.operators.observable; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> public int requestFusion(int mode) { <ide> return NONE; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> return queue.poll(); <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableRange.java <ide> package io.reactivex.internal.operators.observable; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.internal.observers.BasicIntQueueDisposable; <ide> <ide> /** <ide> void run() { <ide> } <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> long i = index; <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableRangeLong.java <ide> package io.reactivex.internal.operators.observable; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.internal.observers.BasicIntQueueDisposable; <ide> <ide> public final class ObservableRangeLong extends Observable<Long> { <ide> void run() { <ide> } <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Long poll() throws Exception { <ide> long i = index; <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableScalarXMap.java <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <ide> public boolean offer(T v1, T v2) { <ide> throw new UnsupportedOperationException("Should not be called!"); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> if (get() == FUSED) { <ide><path>src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableFlowable.java <ide> import java.util.Iterator; <ide> import java.util.concurrent.atomic.AtomicLong; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.*; <ide> public boolean isEmpty() { <ide> return it == null; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public R poll() throws Exception { <ide> Iterator<? extends R> iter = it; <ide><path>src/main/java/io/reactivex/internal/operators/single/SingleFlatMapIterableObservable.java <ide> import java.util.Iterator; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> public boolean isEmpty() { <ide> return it == null; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public R poll() throws Exception { <ide> Iterator<? extends R> iter = it; <ide><path>src/main/java/io/reactivex/internal/queue/MpscLinkedQueue.java <ide> <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.internal.fuseable.SimplePlainQueue; <ide> <ide> /** <ide> public boolean offer(final T e) { <ide> * <ide> * @see java.util.Queue#poll() <ide> */ <add> @Nullable <ide> @Override <ide> public T poll() { <ide> LinkedQueueNode<T> currConsumerNode = lpConsumerNode(); // don't load twice, it's alright <ide><path>src/main/java/io/reactivex/internal/queue/SpscArrayQueue.java <ide> <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.internal.fuseable.SimplePlainQueue; <ide> import io.reactivex.internal.util.Pow2; <ide> <ide> public boolean offer(E v1, E v2) { <ide> return offer(v1) && offer(v2); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public E poll() { <ide> final long index = consumerIndex.get(); <ide><path>src/main/java/io/reactivex/internal/queue/SpscLinkedArrayQueue.java <ide> <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.internal.fuseable.SimplePlainQueue; <ide> import io.reactivex.internal.util.Pow2; <ide> <ide> private AtomicReferenceArray<Object> lvNext(AtomicReferenceArray<Object> curr) { <ide> * <p> <ide> * This implementation is correct for single consumer thread use only. <ide> */ <add> @Nullable <ide> @SuppressWarnings("unchecked") <ide> @Override <ide> public T poll() { <ide><path>src/main/java/io/reactivex/internal/subscriptions/DeferredScalarSubscription.java <ide> <ide> package io.reactivex.internal.subscriptions; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.Subscriber; <ide> <ide> /** <ide> public final int requestFusion(int mode) { <ide> return NONE; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public final T poll() { <ide> if (get() == FUSED_READY) { <ide><path>src/main/java/io/reactivex/internal/subscriptions/EmptySubscription.java <ide> <ide> package io.reactivex.internal.subscriptions; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.internal.fuseable.QueueSubscription; <ide> public static void complete(Subscriber<?> s) { <ide> s.onSubscribe(INSTANCE); <ide> s.onComplete(); <ide> } <add> @Nullable <ide> @Override <ide> public Object poll() { <ide> return null; // always empty <ide><path>src/main/java/io/reactivex/internal/subscriptions/ScalarSubscription.java <ide> <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.internal.fuseable.QueueSubscription; <ide> public boolean offer(T v1, T v2) { <ide> throw new UnsupportedOperationException("Should not be called!"); <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() { <ide> if (get() == NO_REQUEST) { <ide><path>src/main/java/io/reactivex/processors/UnicastProcessor.java <ide> import io.reactivex.annotations.CheckReturnValue; <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.internal.functions.ObjectHelper; <ide> final class UnicastQueueSubscription extends BasicIntQueueSubscription<T> { <ide> <ide> private static final long serialVersionUID = -4896760517184205454L; <ide> <add> @Nullable <ide> @Override <ide> public T poll() { <ide> return queue.poll(); <ide><path>src/main/java/io/reactivex/subjects/UnicastSubject.java <ide> <ide> package io.reactivex.subjects; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import java.util.concurrent.atomic.*; <ide> <ide> public int requestFusion(int mode) { <ide> return NONE; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public T poll() throws Exception { <ide> return queue.poll(); <ide><path>src/test/java/io/reactivex/internal/observers/BasicFuseableObserverTest.java <ide> <ide> package io.reactivex.internal.observers; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.junit.Test; <ide> <ide> import io.reactivex.disposables.Disposables; <ide> public class BasicFuseableObserverTest { <ide> public void offer() { <ide> TestObserver<Integer> to = new TestObserver<Integer>(); <ide> BasicFuseableObserver<Integer, Integer> o = new BasicFuseableObserver<Integer, Integer>(to) { <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> return null; <ide> protected boolean beforeDownstream() { <ide> @Test(expected = UnsupportedOperationException.class) <ide> public void offer2() { <ide> BasicFuseableObserver<Integer, Integer> o = new BasicFuseableObserver<Integer, Integer>(new TestObserver<Integer>()) { <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> return null; <ide><path>src/test/java/io/reactivex/internal/observers/BasicQueueDisposableTest.java <ide> <ide> package io.reactivex.internal.observers; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.junit.Test; <ide> <ide> public class BasicQueueDisposableTest { <ide> public void dispose() { <ide> <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> return null; <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java <ide> import java.util.concurrent.*; <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.junit.Test; <ide> import org.mockito.InOrder; <ide> import org.reactivestreams.*; <ide> public boolean offer(Integer v1, Integer v2) { <ide> return false; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> throw new TestException(); <ide> public boolean offer(Integer v1, Integer v2) { <ide> return false; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> throw new TestException(); <ide> public boolean offer(Integer v1, Integer v2) { <ide> return false; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> throw new TestException(); <ide> public boolean offer(Integer v1, Integer v2) { <ide> return false; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> throw new TestException(); <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableObserveOnTest.java <ide> import java.util.concurrent.*; <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.junit.Test; <ide> import org.mockito.InOrder; <ide> <ide> public boolean offer(Integer v1, Integer v2) { <ide> return false; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> throw new TestException(); <ide><path>src/test/java/io/reactivex/internal/subscribers/BasicFuseableConditionalSubscriberTest.java <ide> <ide> import static org.junit.Assert.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.junit.Test; <ide> import org.reactivestreams.Subscription; <ide> <ide> public int requestFusion(int mode) { <ide> return 0; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> return null; <ide><path>src/test/java/io/reactivex/internal/subscribers/BasicFuseableSubscriberTest.java <ide> <ide> import static org.junit.Assert.*; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.junit.Test; <ide> <ide> import io.reactivex.TestHelper; <ide> public int requestFusion(int mode) { <ide> return 0; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> return null; <ide><path>src/test/java/io/reactivex/internal/subscriptions/QueueSubscriptionTest.java <ide> <ide> package io.reactivex.internal.subscriptions; <ide> <add>import io.reactivex.annotations.Nullable; <ide> import org.junit.Test; <ide> <ide> import static org.junit.Assert.*; <ide> public int requestFusion(int mode) { <ide> return 0; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> return null; <ide> public int requestFusion(int mode) { <ide> return 0; <ide> } <ide> <add> @Nullable <ide> @Override <ide> public Integer poll() throws Exception { <ide> return null;
55
Ruby
Ruby
update hash format for render_text_test
9e9cc660773d331b04a829b4a727af70b3e23c16
<ide><path>actionpack/test/controller/new_base/render_text_test.rb <ide> class SimpleController < ActionController::Base <ide> self.view_paths = [ActionView::FixtureResolver.new] <ide> <ide> def index <del> render :text => "hello david" <add> render text: "hello david" <ide> end <ide> end <ide> <ide> class WithLayoutController < ::ApplicationController <ide> )] <ide> <ide> def index <del> render :text => "hello david" <add> render text: "hello david" <ide> end <ide> <ide> def custom_code <del> render :text => "hello world", :status => 404 <add> render text: "hello world", status: 404 <ide> end <ide> <ide> def with_custom_code_as_string <del> render :text => "hello world", :status => "404 Not Found" <add> render text: "hello world", status: "404 Not Found" <ide> end <ide> <ide> def with_nil <del> render :text => nil <add> render text: nil <ide> end <ide> <ide> def with_nil_and_status <del> render :text => nil, :status => 403 <add> render text: nil, status: 403 <ide> end <ide> <ide> def with_false <del> render :text => false <add> render text: false <ide> end <ide> <ide> def with_layout_true <del> render :text => "hello world", :layout => true <add> render text: "hello world", layout: true <ide> end <ide> <ide> def with_layout_false <del> render :text => "hello world", :layout => false <add> render text: "hello world", layout: false <ide> end <ide> <ide> def with_layout_nil <del> render :text => "hello world", :layout => nil <add> render text: "hello world", layout: nil <ide> end <ide> <ide> def with_custom_layout <del> render :text => "hello world", :layout => "greetings" <add> render text: "hello world", layout: "greetings" <ide> end <ide> <ide> def with_ivar_in_layout <ide> @ivar = "hello world" <del> render :text => "hello world", :layout => "ivar" <add> render text: "hello world", layout: "ivar" <ide> end <ide> end <ide> <ide> class RenderTextTest < Rack::TestCase <ide> <ide> test "rendering text from an action with default options renders the text with the layout" do <ide> with_routing do |set| <del> set.draw { get ':controller', :action => 'index' } <add> set.draw { get ':controller', action: 'index' } <ide> <ide> get "/render_text/simple" <ide> assert_body "hello david" <ide> class RenderTextTest < Rack::TestCase <ide> <ide> test "rendering text from an action with default options renders the text without the layout" do <ide> with_routing do |set| <del> set.draw { get ':controller', :action => 'index' } <add> set.draw { get ':controller', action: 'index' } <ide> <ide> get "/render_text/with_layout" <ide> <ide> class RenderTextTest < Rack::TestCase <ide> assert_status 200 <ide> end <ide> <del> test "rendering text with :layout => true" do <add> test "rendering text with layout: true" do <ide> get "/render_text/with_layout/with_layout_true" <ide> <ide> assert_body "hello world, I'm here!" <ide> assert_status 200 <ide> end <ide> <del> test "rendering text with :layout => 'greetings'" do <add> test "rendering text with layout: 'greetings'" do <ide> get "/render_text/with_layout/with_custom_layout" <ide> <ide> assert_body "hello world, I wish thee well." <ide> assert_status 200 <ide> end <ide> <del> test "rendering text with :layout => false" do <add> test "rendering text with layout: false" do <ide> get "/render_text/with_layout/with_layout_false" <ide> <ide> assert_body "hello world" <ide> assert_status 200 <ide> end <ide> <del> test "rendering text with :layout => nil" do <add> test "rendering text with layout: nil" do <ide> get "/render_text/with_layout/with_layout_nil" <ide> <ide> assert_body "hello world"
1
Ruby
Ruby
add test for gemspec of the generated engine
855d14dd945c6d341242a0d8fd48cb4d424af8d1
<ide><path>railties/test/generators/plugin_new_generator_test.rb <ide> def test_create_mountable_application_with_mountable_option <ide> assert_file "app/views/layouts/bukkits/application.html.erb", /<title>Bukkits<\/title>/ <ide> end <ide> <add> def test_creating_gemspec <add> assert_file "bukkits.gemspec", /s.name = "bukkits"/ <add> assert_file "bukkits.gemspec", /s.files = Dir["{app,config,lib}\/**\/*"]/ <add> assert_file "bukkits.gemspec", /s.version = "0.0.1"/ <add> end <add> <ide> def test_passing_dummy_path_as_a_parameter <ide> run_generator [destination_root, "--dummy_path", "spec/dummy"] <ide> assert_file "spec/dummy"
1
Javascript
Javascript
read debugrenderphasesideeffects from gk
dbf715c958ca43cbcf47d5e3c69e76d6123eb142
<ide><path>packages/react-native-renderer/src/ReactNativeFeatureFlags.js <add>/** <add> * Copyright (c) 2013-present, Facebook, Inc. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> */ <add> <add>import invariant from 'fbjs/lib/invariant'; <add> <add>import typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags'; <add>import typeof * as FeatureFlagsShimType from './ReactNativeFeatureFlags'; <add> <add>// Re-export dynamic flags from the fbsource version. <add>export const {debugRenderPhaseSideEffects} = require('ReactFeatureFlags'); <add> <add>// The rest of the flags are static for better dead code elimination. <add>export const enableAsyncSubtreeAPI = true; <add>export const enableAsyncSchedulingByDefaultInReactDOM = false; <add>export const enableReactFragment = false; <add>export const enableCreateRoot = false; <add>export const enableUserTimingAPI = __DEV__; <add>export const enableMutatingReconciler = true; <add>export const enableNoopReconciler = false; <add>export const enablePersistentReconciler = false; <add> <add>// Only used in www builds. <add>export function addUserTimingListener() { <add> invariant(false, 'Not implemented.'); <add>} <add> <add>// Flow magic to verify the exports of this file match the original version. <add>// eslint-disable-next-line no-unused-vars <add>type Check<_X, Y: _X, X: Y = _X> = null; <add>// eslint-disable-next-line no-unused-expressions <add>(null: Check<FeatureFlagsShimType, FeatureFlagsType>); <ide><path>scripts/rollup/bundles.js <ide> const bundles = [ <ide> 'deepFreezeAndThrowOnMutationInDev', <ide> 'flattenStyle', <ide> ], <add> featureFlags: 'react-native-renderer/src/ReactNativeFeatureFlags', <ide> }, <ide> <ide> /******* React Native RT *******/ <ide><path>scripts/rollup/shims/rollup/ReactFeatureFlags-www.js <ide> import typeof * as FeatureFlagsShimType from './ReactFeatureFlags-www'; <ide> <ide> // Re-export dynamic flags from the www version. <ide> export const { <add> debugRenderPhaseSideEffects, <ide> enableAsyncSchedulingByDefaultInReactDOM, <ide> } = require('ReactFeatureFlags'); <ide> <ide> // The rest of the flags are static for better dead code elimination. <del>export const debugRenderPhaseSideEffects = false; <ide> export const enableAsyncSubtreeAPI = true; <ide> export const enableReactFragment = false; <ide> export const enableCreateRoot = true;
3
Javascript
Javascript
move missplaced variable declaration
b5dcd1fb299c0297e9d16374fc326072ae49e509
<ide><path>examples/js/nodes/accessors/CameraNode.js <ide> THREE.CameraNode.prototype.setScope = function( scope ) { <ide> this.scope = scope; <ide> <ide> switch ( scope ) { <del> <del> var camera = this.camera <ide> <ide> case THREE.CameraNode.DEPTH: <ide> <add> var camera = this.camera <ide> this.near = new THREE.FloatNode( camera ? camera.near : 1 ); <ide> this.far = new THREE.FloatNode( camera ? camera.far : 1200 ); <ide>
1
PHP
PHP
add more doc blocks
8e874aba7289559679ac4927967cb2f5c5d9148b
<ide><path>src/View/Input/DateTime.php <ide> public function __construct($templates, $selectBox) { <ide> * - `empty` - Set to true to add an empty option at the top of the <ide> * option elements. Set to a string to define the display value of the <ide> * empty option. <add> * <add> * In addtion to the above options, the following options allow you to control <add> * which input elements are generated. By setting any option to false you can disable <add> * that input picker. In addition each picker allows you to set additional options <add> * that are set as HTML properties on the picker. <add> * <ide> * - `year` - Array of options for the year select box. <ide> * - `month` - Array of options for the month select box. <ide> * - `day` - Array of options for the day select box. <ide> public function __construct($templates, $selectBox) { <ide> * - `meridian` - Set to true to enable the meridian input. Defaults to false. <ide> * The meridian will be enabled automatically if you chose a 12 hour format. <ide> * <add> * The `year` option accepts the `start` and `end` options. These let you control <add> * the year range that is generated. It defaults to +-5 years from today. <add> * <add> * The `month` option accepts the `name` option which allows you to get month <add> * names instead of month numbers. <add> * <add> * The `hour` option allows you to set the `format` option which accepts <add> * 12 or 24, allowing you to indicate which hour format you want. <add> * <add> * The `minute` option allows you to define the following options: <add> * <add> * - `interval` The interval to round options to. <add> * - `round` Accepts `up` or `down`. Defines which direction the current value <add> * should be rounded to match the select options. <add> * <ide> * @param array $data Data to render with. <ide> * @return string A generated select box. <ide> * @throws \RuntimeException When option data is invalid.
1
Go
Go
fix some minor issues in windows implementation
37a241768d2ed0f005ca376e76fc9e1e98cafe26
<ide><path>cmd/dockerd/daemon_windows.go <ide> func setDefaultUmask() error { <ide> } <ide> <ide> func getDaemonConfDir(root string) (string, error) { <del> return filepath.Join(root, `\config`), nil <add> return filepath.Join(root, "config"), nil <ide> } <ide> <ide> // preNotifyReady sends a message to the host when the API is active, but before the daemon is <ide><path>cmd/dockerd/docker_windows.go <ide> func runDaemon(opts *daemonOptions) error { <ide> // register the service. <ide> stop, runAsService, err := initService(daemonCli) <ide> if err != nil { <del> logrus.Fatal(err) <add> return err <ide> } <ide> <ide> if stop { <ide> func runDaemon(opts *daemonOptions) error { <ide> <ide> // Windows specific settings as these are not defaulted. <ide> if opts.configFile == "" { <del> opts.configFile = filepath.Join(opts.daemonConfig.Root, `config\daemon.json`) <add> configDir, err := getDaemonConfDir(opts.daemonConfig.Root) <add> if err != nil { <add> return err <add> } <add> opts.configFile = filepath.Join(configDir, "daemon.json") <ide> } <ide> if runAsService { <ide> // If Windows SCM manages the service - no need for PID files
2
Text
Text
fix example in updating.md
d963467ddeb8df2f1be245589d8f41b409f60a67
<ide><path>UPDATING.md <ide> called `my_plugin` then your configuration looks like this <ide> <ide> ```ini <ide> [core] <del>executor = my_plguin.MyCustomExecutor <add>executor = my_plugin.MyCustomExecutor <ide> ``` <ide> And now it should look like this: <ide> ```ini
1
Text
Text
add latest item to the release notes
b2fb0deb349160016b8c3f35701654363c260139
<ide><path>docs/topics/release-notes.md <ide> You can determine your currently installed version using `pip freeze`: <ide> * AJAX browsable API. ([#3410][gh3410]) <ide> * Added JSONField. ([#3454][gh3454]) <ide> * Correctly map `to_field` when creating `ModelSerializer` relational fields. ([#3526][gh3526]) <add>* Include keyword arguments when mapping `FilePathField` to a serializer field. ([#3536][gh3536]) <ide> * Map appropriate model `error_messages` on `ModelSerializer` uniqueness constraints. ([#3435][gh3435]) <ide> * Include `max_length` constraint for `ModelSerializer` fields mapped from TextField. ([#3509][gh3509]) <ide> * Added support for Django 1.9. ([#3450][gh3450], [#3525][gh3525]) <ide> For older release notes, [please see the version 2.x documentation][old-release- <ide> [gh3525]: https://github.com/tomchristie/django-rest-framework/issues/3525 <ide> [gh3526]: https://github.com/tomchristie/django-rest-framework/issues/3526 <ide> [gh3429]: https://github.com/tomchristie/django-rest-framework/issues/3429 <add>[gh3536]: https://github.com/tomchristie/django-rest-framework/issues/3536 <ide>
1
Text
Text
fix a typo in active support's changelog [ci skip]
482b74e793301bda3e6c8282a064485a6db01c55
<ide><path>activesupport/CHANGELOG.md <ide> <ide> *Godfrey Chan* <ide> <del>* Fix bug where `URI.unscape` would fail with mixed Unicode/escaped character input: <add>* Fix bug where `URI.unescape` would fail with mixed Unicode/escaped character input: <ide> <ide> URI.unescape("\xe3\x83\x90") # => "バ" <ide> URI.unescape("%E3%83%90") # => "バ"
1
Go
Go
fix bad test comment
b02107db8b3ead7757141584523ce9b623c24c0b
<ide><path>integration-cli/docker_cli_events_test.go <ide> func (s *DockerSuite) TestEventsContainerRestart(c *check.C) { <ide> // wait until test2 is auto removed. <ide> waitTime := 10 * time.Second <ide> if daemonPlatform == "windows" { <del> // nslookup isn't present in Windows busybox. Is built-in. <add> // Windows takes longer... <ide> waitTime = 90 * time.Second <ide> } <ide>
1
Ruby
Ruby
update bundled flexmock to latest 0.4.3
7ca2b657f01b09014cd1fb0494fb13ab63dafe5c
<ide><path>activesupport/lib/active_support/vendor/flexmock.rb <ide> #!/usr/bin/env ruby <ide> <ide> #--- <del># Copyright 2003, 2004 by Jim Weirich ([email protected]). <add># Copyright 2003, 2004, 2005, 2006 by Jim Weirich ([email protected]). <ide> # All rights reserved. <ide> <ide> # Permission is granted for use, copying, modification, distribution, <ide> <ide> require 'test/unit' <ide> <add>###################################################################### <ide> # FlexMock is a flexible mock object suitable for using with Ruby's <ide> # Test::Unit unit test framework. FlexMock has a simple interface <ide> # that's easy to remember, and leaves the hard stuff to all those <ide> # other mock object implementations. <ide> # <del># Usage: See TestSamples for example usage. <del> <add># Basic Usage: <add># <add># m = FlexMock.new("name") <add># m.mock_handle(:meth) { |args| assert_stuff } <add># <add># Simplified Usage: <add># <add># m = FlexMock.new("name") <add># m.should_receive(:upcase).with("stuff"). <add># returns("STUFF") <add># m.should_receive(:downcase).with(String). <add># returns { |s| s.downcase }.once <add># <add># With Test::Unit Integration: <add># <add># class TestSomething < Test::Unit::TestCase <add># include FlexMock::TestCase <add># <add># def test_something <add># m = flexmock("name") <add># m.should_receive(:hi).and_return("Hello") <add># m.hi <add># end <add># end <add># <add># Note: When using Test::Unit integeration, don't forget to include <add># FlexMock::TestCase. Also, if you override +teardown+, make sure you <add># call +super+. <add># <ide> class FlexMock <ide> include Test::Unit::Assertions <ide> <del> # Create a FlexMock object. <del> def initialize <del> @handlers = Hash.new <del> @counts = Hash.new(0) <del> @expected_counts = Hash.new <add> class BadInterceptionError < RuntimeError; end <add> <add> attr_reader :mock_name, :mock_groups <add> attr_accessor :mock_current_order <add> <add> # Create a FlexMock object with the given name. The name is used in <add> # error messages. <add> def initialize(name="unknown") <add> @mock_name = name <add> @expectations = Hash.new <add> @allocated_order = 0 <add> @mock_current_order = 0 <add> @mock_groups = {} <add> @ignore_missing = false <add> @verified = false <ide> end <ide> <ide> # Handle all messages denoted by +sym+ by calling the given block <ide> def initialize <ide> # that by passing in the number of expected calls as a second <ide> # paramter. <ide> def mock_handle(sym, expected_count=nil, &block) <del> if block_given? <del> @handlers[sym] = block <del> else <del> @handlers[sym] = proc { } <del> end <del> @expected_counts[sym] = expected_count if expected_count <add> self.should_receive(sym).times(expected_count).returns(&block) <ide> end <ide> <ide> # Verify that each method that had an explicit expected count was <ide> # actually called that many times. <ide> def mock_verify <del> @expected_counts.keys.each do |key| <del> assert_equal @expected_counts[key], @counts[key], <del> "Expected method #{key} to be called #{@expected_counts[key]} times, " + <del> "got #{@counts[key]}" <add> return if @verified <add> @verified = true <add> mock_wrap do <add> @expectations.each do |sym, handler| <add> handler.mock_verify <add> end <ide> end <ide> end <ide> <del> # Report how many times a method was called. <del> def mock_count(sym) <del> @counts[sym] <add> # Teardown and infrastructure setup for this mock. <add> def mock_teardown <add> end <add> <add> # Allocation a new order number from the mock. <add> def mock_allocate_order <add> @auto_allocate = true <add> @allocated_order += 1 <ide> end <ide> <ide> # Ignore all undefined (missing) method calls. <del> def mock_ignore_missing <add> def should_ignore_missing <ide> @ignore_missing = true <ide> end <add> alias mock_ignore_missing should_ignore_missing <ide> <ide> # Handle missing methods by attempting to look up a handler. <ide> def method_missing(sym, *args, &block) <del> if handler = @handlers[sym] <del> @counts[sym] += 1 <del> args << block if block_given? <del> handler.call(*args) <add> mock_wrap do <add> if handler = @expectations[sym] <add> args << block if block_given? <add> handler.call(*args) <add> else <add> super(sym, *args, &block) unless @ignore_missing <add> end <add> end <add> end <add> <add> # Save the original definition of respond_to? for use a bit later. <add> alias mock_respond_to? respond_to? <add> <add> # Override the built-in respond_to? to include the mocked methods. <add> def respond_to?(sym) <add> super || (@expectations[sym] ? true : @ignore_missing) <add> end <add> <add> # Override the built-in +method+ to include the mocked methods. <add> def method(sym) <add> @expectations[sym] || super <add> rescue NameError => ex <add> if @ignore_missing <add> proc { } <ide> else <del> super(sym, *args, &block) unless @ignore_missing <add> raise ex <add> end <add> end <add> <add> # Declare that the mock object should receive a message with the <add> # given name. An expectation object for the method name is returned <add> # as the result of this method. Further expectation constraints can <add> # be added by chaining to the result. <add> # <add> # See Expectation for a list of declarators that can be used. <add> def should_receive(sym) <add> @expectations[sym] ||= ExpectationDirector.new(sym) <add> result = Expectation.new(self, sym) <add> @expectations[sym] << result <add> override_existing_method(sym) if mock_respond_to?(sym) <add> result <add> end <add> <add> # Override the existing definition of method +sym+ in the mock. <add> # Most methods depend on the method_missing trick to be invoked. <add> # However, if the method already exists, it will not call <add> # method_missing. This method defines a singleton method on the <add> # mock to explicitly invoke the method_missing logic. <add> def override_existing_method(sym) <add> sclass.class_eval "def #{sym}(*args, &block) method_missing(:#{sym}, *args, &block) end" <add> end <add> private :override_existing_method <add> <add> # Return the singleton class of the mock object. <add> def sclass <add> class << self; self; end <add> end <add> private :sclass <add> <add> # Declare that the mock object should expect methods by providing a <add> # recorder for the methods and having the user invoke the expected <add> # methods in a block. Further expectations may be applied the <add> # result of the recording call. <add> # <add> # Example Usage: <add> # <add> # mock.should_expect do |record| <add> # record.add(Integer, 4) { |a, b| <add> # a + b <add> # }.at_least.once <add> # <add> def should_expect <add> yield Recorder.new(self) <add> end <add> <add> # Return a factory object that returns this mock. This is useful in <add> # Class Interception. <add> def mock_factory <add> Factory.new(self) <add> end <add> <add> class << self <add> include Test::Unit::Assertions <add> <add> # Class method to make sure that verify is called at the end of a <add> # test. One mock object will be created for each name given to <add> # the use method. The mocks will be passed to the block as <add> # arguments. If no names are given, then a single anonymous mock <add> # object will be created. <add> # <add> # At the end of the use block, each mock object will be verified <add> # to make sure the proper number of calls have been made. <add> # <add> # Usage: <add> # <add> # FlexMock.use("name") do |mock| # Creates a mock named "name" <add> # mock.should_receive(:meth). <add> # returns(0).once <add> # end # mock is verified here <add> # <add> # NOTE: If you include FlexMock::TestCase into your test case <add> # file, you can create mocks that will be automatically verified in <add> # the test teardown by using the +flexmock+ method. <add> # <add> def use(*names) <add> names = ["unknown"] if names.empty? <add> got_excecption = false <add> mocks = names.collect { |n| new(n) } <add> yield(*mocks) <add> rescue Exception => ex <add> got_exception = true <add> raise <add> ensure <add> mocks.each do |mock| <add> mock.mock_verify unless got_exception <add> end <add> end <add> <add> # Class method to format a method name and argument list as a nice <add> # looking string. <add> def format_args(sym, args) <add> if args <add> "#{sym}(#{args.collect { |a| a.inspect }.join(', ')})" <add> else <add> "#{sym}(*args)" <add> end <add> end <add> <add> # Check will assert the block returns true. If it doesn't, an <add> # assertion failure is triggered with the given message. <add> def check(msg, &block) <add> assert_block(msg, &block) <add> end <add> end <add> <add> private <add> <add> # Wrap a block of code so the any assertion errors are wrapped so <add> # that the mock name is added to the error message . <add> def mock_wrap(&block) <add> yield <add> rescue Test::Unit::AssertionFailedError => ex <add> raise Test::Unit::AssertionFailedError, <add> "in mock '#{@mock_name}': #{ex.message}", <add> ex.backtrace <add> end <add> <add> #################################################################### <add> # A Factory object is returned from a mock_factory method call. The <add> # factory merely returns the manufactured object it is initialized <add> # with. The factory is handy to use with class interception, <add> # allowing the intercepted class to return the mock object. <add> # <add> # If the user needs more control over the mock factory, they are <add> # free to create their own. <add> # <add> # Typical Usage: <add> # intercept(Bar).in(Foo).with(a_mock.mack_factory) <add> # <add> class Factory <add> def initialize(manufactured_object) <add> @obj = manufactured_object <add> end <add> def new(*args, &block) <add> @obj <add> end <add> end <add> <add> #################################################################### <add> # The expectation director is responsible for routing calls to the <add> # correct expectations for a given argument list. <add> # <add> class ExpectationDirector <add> <add> # Create an ExpectationDirector for a mock object. <add> def initialize(sym) <add> @sym = sym <add> @expectations = [] <add> @expected_order = nil <add> end <add> <add> # Invoke the expectations for a given set of arguments. <add> # <add> # First, look for an expectation that matches the arguements and <add> # is eligible to be called. Failing that, look for a expectation <add> # that matches the arguments (at this point it will be ineligible, <add> # but at least we will get a good failure message). Finally, <add> # check for expectations that don't have any argument matching <add> # criteria. <add> def call(*args) <add> exp = @expectations.find { |e| e.match_args(args) && e.eligible? } || <add> @expectations.find { |e| e.match_args(args) } || <add> @expectations.find { |e| e.expected_args.nil? } <add> FlexMock.check("no matching handler found for " + <add> FlexMock.format_args(@sym, args)) { ! exp.nil? } <add> exp.verify_call(*args) <add> end <add> <add> # Same as call. <add> def [](*args) <add> call(*args) <add> end <add> <add> # Append an expectation to this director. <add> def <<(expectation) <add> @expectations << expectation <add> end <add> <add> # Do the post test verification for this directory. Check all the <add> # expectations. <add> def mock_verify <add> @expectations.each do |exp| <add> exp.mock_verify <add> end <add> end <add> end <add> <add> #################################################################### <add> # Match any object <add> class AnyMatcher <add> def ===(target) <add> true <add> end <add> def inspect <add> "ANY" <add> end <add> end <add> <add> #################################################################### <add> # Match only things that are equal. <add> class EqualMatcher <add> def initialize(obj) <add> @obj = obj <add> end <add> def ===(target) <add> @obj == target <add> end <add> def inspect <add> "==(#{@obj.inspect})" <add> end <add> end <add> <add> ANY = AnyMatcher.new <add> <add> #################################################################### <add> # Match only things where the block evaluates to true. <add> class ProcMatcher <add> def initialize(&block) <add> @block = block <add> end <add> def ===(target) <add> @block.call(target) <add> end <add> def inspect <add> "on{...}" <add> end <add> end <add> <add> #################################################################### <add> # Include this module in your test class if you wish to use the +eq+ <add> # and +any+ argument matching methods without a prefix. (Otherwise <add> # use <tt>FlexMock.any</tt> and <tt>FlexMock.eq(obj)</tt>. <add> # <add> module ArgumentTypes <add> # Return an argument matcher that matches any argument. <add> def any <add> ANY <add> end <add> <add> # Return an argument matcher that only matches things equal to <add> # (==) the given object. <add> def eq(obj) <add> EqualMatcher.new(obj) <add> end <add> <add> # Return an argument matcher that matches any object, that when <add> # passed to the supplied block, will cause the block to return <add> # true. <add> def on(&block) <add> ProcMatcher.new(&block) <ide> end <ide> end <add> extend ArgumentTypes <add> <add> #################################################################### <add> # Base class for all the count validators. <add> # <add> class CountValidator <add> include Test::Unit::Assertions <add> def initialize(expectation, limit) <add> @exp = expectation <add> @limit = limit <add> end <add> <add> # If the expectation has been called +n+ times, is it still <add> # eligible to be called again? The default answer compares n to <add> # the established limit. <add> def eligible?(n) <add> n < @limit <add> end <add> end <add> <add> #################################################################### <add> # Validator for exact call counts. <add> # <add> class ExactCountValidator < CountValidator <add> # Validate that the method expectation was called exactly +n+ <add> # times. <add> def validate(n) <add> assert_equal @limit, n, <add> "method '#{@exp}' called incorrect number of times" <add> end <add> end <add> <add> #################################################################### <add> # Validator for call counts greater than or equal to a limit. <add> # <add> class AtLeastCountValidator < CountValidator <add> # Validate the method expectation was called no more than +n+ <add> # times. <add> def validate(n) <add> assert n >= @limit, <add> "Method '#{@exp}' should be called at least #{@limit} times,\n" + <add> "only called #{n} times" <add> end <add> <add> # If the expectation has been called +n+ times, is it still <add> # eligible to be called again? Since this validator only <add> # establishes a lower limit, not an upper limit, then the answer <add> # is always true. <add> def eligible?(n) <add> true <add> end <add> end <add> <add> #################################################################### <add> # Validator for call counts less than or equal to a limit. <add> # <add> class AtMostCountValidator < CountValidator <add> # Validate the method expectation was called at least +n+ times. <add> def validate(n) <add> assert n <= @limit, <add> "Method '#{@exp}' should be called at most #{@limit} times,\n" + <add> "only called #{n} times" <add> end <add> end <add> <add> #################################################################### <add> # An Expectation is returned from each +should_receive+ message sent <add> # to mock object. Each expectation records how a message matching <add> # the message name (argument to +should_receive+) and the argument <add> # list (given by +with+) should behave. Mock expectations can be <add> # recorded by chaining the declaration methods defined in this <add> # class. <add> # <add> # For example: <add> # <add> # mock.should_receive(:meth).with(args).and_returns(result) <add> # <add> class Expectation <add> include Test::Unit::Assertions <add> <add> attr_reader :expected_args, :mock, :order_number <add> <add> # Create an expectation for a method named +sym+. <add> def initialize(mock, sym) <add> @mock = mock <add> @sym = sym <add> @expected_args = nil <add> @count_validators = [] <add> @count_validator_class = ExactCountValidator <add> @actual_count = 0 <add> @return_value = nil <add> @return_block = lambda { @return_value } <add> @order_number = nil <add> end <add> <add> def to_s <add> FlexMock.format_args(@sym, @expected_args) <add> end <ide> <del> # Class method to make sure that verify is called at the end of a <del> # test. <del> def self.use <del> mock = new <del> yield mock <del> ensure <del> mock.mock_verify <add> # Verify the current call with the given arguments matches the <add> # expectations recorded in this object. <add> def verify_call(*args) <add> validate_order <add> @actual_count += 1 <add> @return_block.call(*args) <add> end <add> <add> # Is this expectation eligible to be called again? It is eligible <add> # only if all of its count validators agree that it is eligible. <add> def eligible? <add> @count_validators.all? { |v| v.eligible?(@actual_count) } <add> end <add> <add> # Validate that the order <add> def validate_order <add> return if @order_number.nil? <add> FlexMock.check("method #{to_s} called out of order " + <add> "(expected order #{@order_number}, was #{@mock.mock_current_order})") { <add> @order_number >= @mock.mock_current_order <add> } <add> @mock.mock_current_order = @order_number <add> end <add> private :validate_order <add> <add> # Validate the correct number of calls have been made. Called by <add> # the teardown process. <add> def mock_verify <add> @count_validators.each do |v| <add> v.validate(@actual_count) <add> end <add> end <add> <add> # Does the argument list match this expectation's argument <add> # specification. <add> def match_args(args) <add> return false if @expected_args.nil? <add> return false if args.size != @expected_args.size <add> (0...args.size).all? { |i| match_arg(@expected_args[i], args[i]) } <add> end <add> <add> # Does the expected argument match the corresponding actual value. <add> def match_arg(expected, actual) <add> expected === actual || <add> expected == actual || <add> ( Regexp === expected && expected === actual.to_s ) <add> end <add> <add> # Declare that the method should expect the given argument list. <add> def with(*args) <add> @expected_args = args <add> self <add> end <add> <add> # Declare that the method should be called with no arguments. <add> def with_no_args <add> with <add> end <add> <add> # Declare that the method can be called with any number of <add> # arguments of any type. <add> def with_any_args <add> @expected_args = nil <add> self <add> end <add> <add> # Declare that the method returns a particular value (when the <add> # argument list is matched). <add> # <add> # * If a single value is given, it will be returned for all matching <add> # calls. <add> # * If multiple values are given, each value will be returned in turn for <add> # each successive call. If the number of matching calls is greater <add> # than the number of values, the last value will be returned for <add> # the extra matching calls. <add> # * If a block is given, it is evaluated on each call and its <add> # value is returned. <add> # <add> # For example: <add> # <add> # mock.should_receive(:f).returns(12) # returns 12 <add> # <add> # mock.should_receive(:f).with(String). # returns an <add> # returns { |str| str.upcase } # upcased string <add> # <add> # +and_return+ is an alias for +returns+. <add> # <add> def returns(*args, &block) <add> @return_block = block_given? ? <add> block : <add> lambda { args.size == 1 ? args.first : args.shift } <add> self <add> end <add> alias :and_return :returns # :nodoc: <add> <add> # Declare that the method may be called any number of times. <add> def zero_or_more_times <add> at_least.never <add> end <add> <add> # Declare that the method is called +limit+ times with the <add> # declared argument list. This may be modified by the +at_least+ <add> # and +at_most+ declarators. <add> def times(limit) <add> @count_validators << @count_validator_class.new(self, limit) unless limit.nil? <add> @count_validator_class = ExactCountValidator <add> self <add> end <add> <add> # Declare that the method is never expected to be called with the <add> # given argument list. This may be modified by the +at_least+ and <add> # +at_most+ declarators. <add> def never <add> times(0) <add> end <add> <add> # Declare that the method is expected to be called exactly once <add> # with the given argument list. This may be modified by the <add> # +at_least+ and +at_most+ declarators. <add> def once <add> times(1) <add> end <add> <add> # Declare that the method is expected to be called exactly twice <add> # with the given argument list. This may be modified by the <add> # +at_least+ and +at_most+ declarators. <add> def twice <add> times(2) <add> end <add> <add> # Modifies the next call count declarator (+times+, +never+, <add> # +once+ or +twice+) so that the declarator means the method is <add> # called at least that many times. <add> # <add> # E.g. method f must be called at least twice: <add> # <add> # mock.should_receive(:f).at_least.twice <add> # <add> def at_least <add> @count_validator_class = AtLeastCountValidator <add> self <add> end <add> <add> # Modifies the next call count declarator (+times+, +never+, <add> # +once+ or +twice+) so that the declarator means the method is <add> # called at most that many times. <add> # <add> # E.g. method f must be called no more than twice <add> # <add> # mock.should_receive(:f).at_most.twice <add> # <add> def at_most <add> @count_validator_class = AtMostCountValidator <add> self <add> end <add> <add> # Declare that the given method must be called in order. All <add> # ordered method calls must be received in the order specified by <add> # the ordering of the +should_receive+ messages. Receiving a <add> # methods out of the specified order will cause a test failure. <add> # <add> # If the user needs more fine control over ordering <add> # (e.g. specifying that a group of messages may be received in any <add> # order as long as they all come after another group of messages), <add> # a _group_ _name_ may be specified in the +ordered+ calls. All <add> # messages within the same group may be received in any order. <add> # <add> # For example, in the following, messages +flip+ and +flop+ may be <add> # received in any order (because they are in the same group), but <add> # must occur strictly after +start+ but before +end+. The message <add> # +any_time+ may be received at any time because it is not <add> # ordered. <add> # <add> # m = FlexMock.new <add> # m.should_receive(:any_time) <add> # m.should_receive(:start).ordered <add> # m.should_receive(:flip).ordered(:flip_flop_group) <add> # m.should_receive(:flop).ordered(:flip_flop_group) <add> # m.should_receive(:end).ordered <add> # <add> def ordered(group_name=nil) <add> if group_name.nil? <add> @order_number = @mock.mock_allocate_order <add> elsif (num = @mock.mock_groups[group_name]) <add> @order_number = num <add> else <add> @order_number = @mock.mock_allocate_order <add> @mock.mock_groups[group_name] = @order_number <add> end <add> self <add> end <add> end <add> <add> #################################################################### <add> # Translate arbitrary method calls into expectations on the given <add> # mock object. <add> # <add> class Recorder <add> include FlexMock::ArgumentTypes <add> <add> # Create a method recorder for the mock +mock+. <add> def initialize(mock) <add> @mock = mock <add> @strict = false <add> end <add> <add> # Place the record in strict mode. While recording expectations <add> # in strict mode, the following will be true. <add> # <add> # * All expectations will be expected in the order they were <add> # recorded. <add> # * All expectations will be expected once. <add> # * All arguments will be placed in exact match mode, <add> # including regular expressions and class objects. <add> # <add> # Strict mode is usually used when giving the recorder to a known <add> # good algorithm. Strict mode captures the exact sequence of <add> # calls and validate that the code under test performs the exact <add> # same sequence of calls. <add> # <add> # The recorder may exit strict mode via a <add> # <tt>should_be_strict(false)</tt> call. Non-strict expectations <add> # may be recorded at that point, or even explicit expectations <add> # (using +should_receieve+) can be specified. <add> # <add> def should_be_strict(is_strict=true) <add> @strict = is_strict <add> end <add> <add> # Is the recorder in strict mode? <add> def strict? <add> @strict <add> end <add> <add> # Record an expectation for receiving the method +sym+ with the <add> # given arguments. <add> def method_missing(sym, *args, &block) <add> expectation = @mock.should_receive(sym).and_return(&block) <add> if @strict <add> args = args.collect { |arg| eq(arg) } <add> expectation.with(*args).ordered.once <add> else <add> expectation.with(*args) <add> end <add> expectation <add> end <add> end <add> <add> #################################################################### <add> # Test::Unit::TestCase Integration. <add> # <add> # Include this module in any TestCase class in a Test::Unit test <add> # suite to get integration with FlexMock. When this module is <add> # included, mocks may be created with a simple call to the <add> # +flexmock+ method. Mocks created with via the method call will <add> # automatically be verified in the teardown of the test case. <add> # <add> # <b>Note:</b> If you define a +teardown+ method in the test case, <add> # <em>dont' forget to invoke the +super+ method!</em> Failure to <add> # invoke super will cause all mocks to not be verified. <add> # <add> module TestCase <add> include ArgumentTypes <add> <add> # Teardown the test case, verifying any mocks that might have been <add> # defined in this test case. <add> def teardown <add> super <add> flexmock_teardown <add> end <add> <add> # Do the flexmock specific teardown stuff. <add> def flexmock_teardown <add> @flexmock_created_mocks ||= [] <add> if passed? <add> @flexmock_created_mocks.each do |m| <add> m.mock_verify <add> end <add> end <add> ensure <add> @flexmock_created_mocks.each do |m| <add> m.mock_teardown <add> end <add> @flexmock_interceptors ||= [] <add> @flexmock_interceptors.each do |i| <add> i.restore <add> end <add> end <add> <add> # Create a FlexMock object with the given name. Mocks created <add> # with this method will be automatically verify during teardown <add> # (assuming the the flexmock teardown isn't overridden). <add> # <add> # If a block is given, then the mock object is passed to the block and <add> # may be configured in the block. <add> def flexmock(name="unknown") <add> mock = FlexMock.new(name) <add> yield(mock) if block_given? <add> flexmock_remember(mock) <add> mock <add> end <add> <add> # Stub the given object by overriding the behavior of individual methods. <add> # The stub object returned will respond to the +should_receive+ <add> # method, just like normal stubs. Singleton methods cannot be <add> # stubbed. <add> # <add> # Example: Stub out DBI to return a fake db connection. <add> # <add> # flexstub(DBI).should_receive(:connect).and_return { <add> # fake_db = flexmock("db connection") <add> # fake_db.should_receive(:select_all).and_return(...) <add> # fake_db <add> # } <add> # <add> def flexstub(obj, name=nil) <add> name ||= "flexstub(#{obj.class.to_s})" <add> obj.instance_eval { <add> @flexmock_proxy ||= StubProxy.new(obj, FlexMock.new(name)) <add> } <add> flexmock_remember(obj.instance_variable_get("@flexmock_proxy")) <add> end <add> <add> # Intercept the named class in the target class for the duration <add> # of the test. Class interception is very simple-minded and has a <add> # number of restrictions. First, the intercepted class must be <add> # reference in the tested class via a simple constant name <add> # (e.g. no scoped names using "::") that is not directly defined <add> # in the class itself. After the test, a proxy class constant <add> # will be left behind that will forward all calls to the original <add> # class. <add> # <add> # Usage: <add> # intercept(SomeClass).in(ClassBeingTested).with(MockClass) <add> # intercept(SomeClass).with(MockClass).in(ClassBeingTested) <add> # <add> def intercept(intercepted_class) <add> result = Interception.new(intercepted_class) <add> @flexmock_interceptors ||= [] <add> @flexmock_interceptors << result <add> result <add> end <add> <add> private <add> <add> def flexmock_remember(mocking_object) <add> @flexmock_created_mocks ||= [] <add> @flexmock_created_mocks << mocking_object <add> mocking_object <add> end <add> end <add> <add> #################################################################### <add> # A Class Interception defines a constant in the target class to be <add> # a proxy that points to a replacement class for the duration of a <add> # test. When an interception is restored, the proxy will point to <add> # the original intercepted class. <add> # <add> class Interception <add> # Create an interception object with the class to intercepted. <add> def initialize(intercepted_class) <add> @intercepted = nil <add> @target = nil <add> @replacement = nil <add> @proxy = nil <add> intercept(intercepted_class) <add> update <add> end <add> <add> # Intercept this class in the class to be tested. <add> def intercept(intercepted_class) <add> @intercepted = intercepted_class <add> update <add> self <add> end <add> <add> # Define the class number test that will receive the <add> # interceptioned definition. <add> def in(target_class) <add> @target = target_class <add> update <add> self <add> end <add> <add> # Define the replacement class. This is normally a proxy or a <add> # stub. <add> def with(replacement_class) <add> @replacement = replacement_class <add> update <add> self <add> end <add> <add> # Restore the original class. The proxy remains in place however. <add> def restore <add> @proxy.proxied_class = @restore_class if @proxy <add> end <add> <add> private <add> <add> # Update the interception if the definition is complete. <add> def update <add> if complete? <add> do_interception <add> end <add> end <add> <add> # Is the interception definition complete. In other words, are <add> # all three actors defined? <add> def complete? <add> @intercepted && @target && @replacement <add> end <add> <add> # Implement interception on the classes defined. <add> def do_interception <add> @target_class = coerce_class(@target, "target") <add> @replacement_class = coerce_class(@replacement, "replacement") <add> case @intercepted <add> when String, Symbol <add> @intercepted_name = @intercepted.to_s <add> when Class <add> @intercepted_name = @intercepted.name <add> end <add> @intercepted_class = coerce_class(@intercepted, "intercepted") <add> current_class = @target_class.const_get(@intercepted_name) <add> if ClassProxy === current_class <add> @proxy = current_class <add> @restore_class = @proxy.proxied_class <add> @proxy.proxied_class = @replacement_class <add> else <add> @proxy = ClassProxy.new(@replacement_class) <add> @restore_class = current_class <add> @target_class.const_set(@intercepted_name, @proxy) <add> end <add> end <add> <add> # Coerce a class object, string to symbol to be the class object. <add> def coerce_class(klass, where) <add> case klass <add> when String, Symbol <add> lookup_const(klass.to_s, where) <add> else <add> klass <add> end <add> end <add> <add> def lookup_const(name, where, target=Object) <add> begin <add> target.const_get(name) <add> rescue NameError <add> raise BadInterceptionError, "in #{where} class #{name}" <add> end <add> end <add> end <add> <add> #################################################################### <add> # Class Proxy for class interception. Forward all method calls to <add> # whatever is the proxied_class. <add> # <add> class ClassProxy <add> attr_accessor :proxied_class <add> def initialize(default_class) <add> @proxied_class = default_class <add> end <add> def method_missing(sym, *args, &block) <add> @proxied_class.__send__(sym, *args, &block) <add> end <add> end <add> <add> #################################################################### <add> # StubProxy is used to mate the mock framework to an existing <add> # object. The object is "enhanced" with a reference to a mock <add> # object (stored in <tt>@flexmock_mock</tt>). When the <add> # +should_receive+ method is sent to the proxy, it overrides the <add> # existing object's method by creating singleton method that <add> # forwards to the mock. When testing is complete, StubProxy <add> # will erase the mocking infrastructure from the object being <add> # stubbed (e.g. remove instance variables and mock singleton <add> # methods). <add> # <add> class StubProxy <add> attr_reader :mock <add> <add> def initialize(obj, mock) <add> @obj = obj <add> @mock = mock <add> @method_definitions = {} <add> @methods_proxied = [] <add> end <add> <add> # Stub out the given method in the existing object and then let the <add> # mock object handle should_receive. <add> def should_receive(method_name) <add> method_name = method_name.to_sym <add> unless @methods_proxied.include?(method_name) <add> hide_existing_method(method_name) <add> @methods_proxied << method_name <add> end <add> @mock.should_receive(method_name) <add> end <add> <add> # Verify that the mock has been properly called. After verification, <add> # detach the mocking infrastructure from the existing object. <add> def mock_verify <add> @mock.mock_verify <add> end <add> <add> # Remove all traces of the mocking framework from the existing object. <add> def mock_teardown <add> if ! detached? <add> @methods_proxied.each do |method_name| <add> remove_current_method(method_name) <add> restore_original_definition(method_name) <add> end <add> @obj.instance_variable_set("@flexmock_proxy", nil) <add> @obj = nil <add> end <add> end <add> <add> private <add> <add> # The singleton class of the object. <add> def sclass <add> class << @obj; self; end <add> end <add> <add> # Is the current method a singleton method in the object we are <add> # mocking? <add> def singleton?(method_name) <add> @obj.methods(false).include?(method_name.to_s) <add> end <add> <add> # Hide the existing method definition with a singleton defintion <add> # that proxies to our mock object. If the current definition is a <add> # singleton, we need to record the definition and remove it before <add> # creating our own singleton method. If the current definition is <add> # not a singleton, all we need to do is override it with our own <add> # singleton. <add> def hide_existing_method(method_name) <add> if singleton?(method_name) <add> @method_definitions[method_name] = @obj.method(method_name) <add> remove_current_method(method_name) <add> end <add> define_proxy_method(method_name) <add> end <add> <add> # Define a proxy method that forwards to our mock object. The <add> # proxy method is defined as a singleton method on the object <add> # being mocked. <add> def define_proxy_method(method_name) <add> sclass.class_eval %{ <add> def #{method_name}(*args, &block) <add> @flexmock_proxy.mock.#{method_name}(*args, &block) <add> end <add> } <add> end <add> <add> # Restore the original singleton defintion for method_name that <add> # was saved earlier. <add> def restore_original_definition(method_name) <add> method_def = @method_definitions[method_name] <add> if method_def <add> sclass.class_eval { <add> define_method(method_name, &method_def) <add> } <add> end <add> end <add> <add> # Remove the current method if it is a singleton method of the <add> # object being mocked. <add> def remove_current_method(method_name) <add> sclass.class_eval { remove_method(method_name) } <add> end <add> <add> # Have we been detached from the existing object? <add> def detached? <add> @obj.nil? <add> end <add> <ide> end <ide> end
1
Mixed
Text
use hash#compact and hash#compact! from ruby 2.4
69a3fa1efc979f9d65110560d9779c2f8a74d8f6
<ide><path>activesupport/CHANGELOG.md <add>* Use `Hash#compact` and `Hash#compact!` from Ruby 2.4. Old Ruby versions <add> will continue to get these methods from Active Support as before. <add> <add> *Prathamesh Sonpatki* <add> <ide> * Fix `ActiveSupport::TimeZone#strptime`. <ide> Support for timestamps in format of seconds (%s) and milliseconds (%Q). <ide> <ide> Time.zone = "US/Eastern" <ide> <ide> t = Time.zone.local(2016,11,6,1) <del> # => Sun, 06 Nov 2016 01:00:00 EDT -05:00 <add> # => Sun, 06 Nov 2016 01:00:00 EDT -05:00 <ide> <ide> t.in(1.hour) <del> # => Sun, 06 Nov 2016 01:00:00 EST -05:00 <add> # => Sun, 06 Nov 2016 01:00:00 EST -05:00 <ide> <ide> Fixes #26580. <ide> <ide><path>activesupport/lib/active_support/core_ext/hash/compact.rb <ide> class Hash <del> # Returns a hash with non +nil+ values. <del> # <del> # hash = { a: true, b: false, c: nil } <del> # hash.compact # => { a: true, b: false } <del> # hash # => { a: true, b: false, c: nil } <del> # { c: nil }.compact # => {} <del> # { c: true }.compact # => { c: true } <del> def compact <del> select { |_, value| !value.nil? } <add> unless Hash.instance_methods(false).include?(:compact) <add> # Returns a hash with non +nil+ values. <add> # <add> # hash = { a: true, b: false, c: nil } <add> # hash.compact # => { a: true, b: false } <add> # hash # => { a: true, b: false, c: nil } <add> # { c: nil }.compact # => {} <add> # { c: true }.compact # => { c: true } <add> def compact <add> select { |_, value| !value.nil? } <add> end <ide> end <ide> <del> # Replaces current hash with non +nil+ values. <del> # Returns nil if no changes were made, otherwise returns the hash. <del> # <del> # hash = { a: true, b: false, c: nil } <del> # hash.compact! # => { a: true, b: false } <del> # hash # => { a: true, b: false } <del> # { c: true }.compact! # => nil <del> def compact! <del> reject! { |_, value| value.nil? } <add> unless Hash.instance_methods(false).include?(:compact!) <add> # Replaces current hash with non +nil+ values. <add> # Returns nil if no changes were made, otherwise returns the hash. <add> # <add> # hash = { a: true, b: false, c: nil } <add> # hash.compact! # => { a: true, b: false } <add> # hash # => { a: true, b: false } <add> # { c: true }.compact! # => nil <add> def compact! <add> reject! { |_, value| value.nil? } <add> end <ide> end <ide> end
2
Text
Text
add note about node_env being set automatically
72827d25cb5990156436d5fffc4bd3ab7a4bdd38
<ide><path>readme.md <ide> Then run `now` and enjoy! <ide> <ide> Next.js can be deployed to other hosting solutions too. Please have a look at the ['Deployment'](https://github.com/zeit/next.js/wiki/Deployment) section of the wiki. <ide> <add>Note: `NODE_ENV` is properly configured by the `next` subcommands, if absent, to maximize performance. if you’re using Next.js [programmatically](#custom-server-and-routing), it’s your responsibility to set `NODE_ENV=production` manually! <add> <ide> Note: we recommend putting `.next`, or your custom dist folder (Please have a look at ['Custom Config'](https://github.com/zeit/next.js#custom-configuration). You can set a custom folder in config, `.npmignore`, or `.gitignore`. Otherwise, use `files` or `now.files` to opt-into a whitelist of files you want to deploy (and obviously exclude `.next` or your custom dist folder). <ide> <ide> ## Static HTML export
1
Javascript
Javascript
update links to html spec for stripandcollapse
e1b1b2d7fe5aff907a9accf59910bc3b7e4d1dec
<ide><path>src/core/stripAndCollapse.js <ide> define( [ <ide> "use strict"; <ide> <ide> // Strip and collapse whitespace according to HTML spec <del> // https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace <add> // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace <ide> function stripAndCollapse( value ) { <ide> var tokens = value.match( rnothtmlwhite ) || []; <ide> return tokens.join( " " ); <ide><path>src/var/rnothtmlwhite.js <ide> define( function() { <ide> <ide> // Only count HTML whitespace <ide> // Other whitespace should count in values <del> // https://html.spec.whatwg.org/multipage/infrastructure.html#space-character <add> // https://infra.spec.whatwg.org/#ascii-whitespace <ide> return ( /[^\x20\t\r\n\f]+/g ); <ide> } );
2
PHP
PHP
tap() return type
d3c8c8ea83ad82c7bc13ef37fcb99f90b9d3fdee
<ide><path>src/Illuminate/Support/Traits/Tappable.php <ide> trait Tappable <ide> * Call the given Closure with this instance then return the instance. <ide> * <ide> * @param callable|null $callback <del> * @return mixed <add> * @return $this|\Illuminate\Support\HigherOrderTapProxy <ide> */ <ide> public function tap($callback = null) <ide> {
1
Javascript
Javascript
remove unneeded lazy check
b35fcaa45da30a593b9238aaa2194fc79c85d919
<ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.CoreView.extend( <ide> // Get the current value of the property <ide> newClass = this._classStringForProperty(binding); <ide> elem = this.$(); <del> if (!elem) { <del> removeObserver(this, parsedPath.path, observer); <del> return; <del> } <ide> <ide> // If we had previously added a class to the element, remove it. <ide> if (oldClass) {
1
Javascript
Javascript
fix bug in timers_uv timeout recomputation
1037f5c11369566b33debc47dedac2a1c65dae68
<ide><path>lib/timers_uv.js <ide> function insert(item, msecs) { <ide> <ide> list.ontimeout = function() { <ide> debug('timeout callback ' + msecs); <del> // TODO - don't stop and start the watcher all the time. <del> // just set its repeat <add> <ide> var now = new Date(); <ide> debug('now: ' + now); <ide> <ide> var first; <ide> while (first = L.peek(list)) { <ide> var diff = now - first._idleStart; <ide> if (diff + 1 < msecs) { <del> list.start(diff, 0); <add> list.start(msecs - diff, 0); <ide> debug(msecs + ' list wait because diff is ' + diff); <ide> return; <ide> } else {
1
PHP
PHP
add additional test for empty
0cb86ec3c09b859bbcd6e1b3a19e062a65e90618
<ide><path>Test/TestCase/View/Input/SelectBoxTest.php <ide> public function testRenderEmptyOption() { <ide> '/select' <ide> ]; <ide> $this->assertTags($result, $expected); <add> <add> $data['value'] = false; <add> $result = $select->render($data); <add> $this->assertTags($result, $expected); <ide> } <ide> <ide> }
1
Javascript
Javascript
remove arity check from initializer
40bc56ca3c87edc9f0b9ae63772a1b706e67cfaf
<ide><path>packages/ember-application/lib/system/engine.js <ide> import { <ide> privatize as P <ide> } from 'container'; <ide> import DAG from 'dag-map'; <del>import { assert, deprecate } from 'ember-debug'; <add>import { assert } from 'ember-debug'; <ide> import { get, set } from 'ember-metal'; <ide> import DefaultResolver from './resolver'; <ide> import EngineInstance from './engine-instance'; <ide> const Engine = Namespace.extend(RegistryProxyMixin, { <ide> runInitializers() { <ide> this._runInitializer('initializers', (name, initializer) => { <ide> assert(`No application initializer named '${name}'`, !!initializer); <del> if (initializer.initialize.length === 2) { <del> deprecate(`The \`initialize\` method for Application initializer '${name}' should take only one argument - \`App\`, an instance of an \`Application\`.`, <del> false, { <del> id: 'ember-application.app-initializer-initialize-arguments', <del> until: '3.0.0', <del> url: 'https://emberjs.com/deprecations/v2.x/#toc_initializer-arity' <del> }); <del> <del> initializer.initialize(this.__registry__, this); <del> } else { <del> initializer.initialize(this); <del> } <add> initializer.initialize(this); <ide> }); <ide> }, <ide> <ide> function resolverFor(namespace) { <ide> } <ide> <ide> function buildInitializerMethod(bucketName, humanName) { <del> return function(initializer) { <add> return function (initializer) { <ide> // If this is the first initializer being added to a subclass, we are going to reopen the class <ide> // to make sure we have a new `initializers` object, which extends from the parent class' using <ide> // prototypal inheritance. Without this, attempting to add initializers to the subclass would <ide><path>packages/ember-application/tests/system/initializers_test.js <ide> moduleFor('Ember.Application initializers', class extends AutobootApplicationTes <ide> }); <ide> } <ide> <del> createSecondApplication(options, MyApplication=Application) { <add> createSecondApplication(options, MyApplication = Application) { <ide> let myOptions = assign(this.applicationOptions, { <ide> rootElement: '#two' <ide> }, options); <ide> moduleFor('Ember.Application initializers', class extends AutobootApplicationTes <ide> }); <ide> <ide> expectAssertion(() => { <del> MyApplication.initializer({ initialize() {} }); <add> MyApplication.initializer({ initialize() { } }); <ide> }); <ide> } <ide> <ide> moduleFor('Ember.Application initializers', class extends AutobootApplicationTes <ide> <ide> FirstApp.initializer({ <ide> name: 'abc', <del> initialize() {} <add> initialize() { } <ide> }); <ide> <ide> expectAssertion(() => { <ide> FirstApp.initializer({ <ide> name: 'abc', <del> initialize() {} <add> initialize() { } <ide> }); <ide> }); <ide> <ide> let SecondApp = Application.extend(); <ide> SecondApp.instanceInitializer({ <ide> name: 'abc', <del> initialize() {} <add> initialize() { } <ide> }); <ide> <ide> assert.ok(true, 'Two apps can have initializers named the same.'); <ide> moduleFor('Ember.Application initializers', class extends AutobootApplicationTes <ide> <ide> this.runTask(() => this.createApplication({}, MyApplication)); <ide> } <del> <del> [`@test initializers throw a deprecation warning when receiving a second argument`](assert) { <del> assert.expect(1); <del> <del> let MyApplication = Application.extend(); <del> <del> MyApplication.initializer({ <del> name: 'deprecated', <del> initialize(registry, application) { // eslint-disable-line no-unused-vars <del> } <del> }); <del> <del> expectDeprecation(() => { <del> this.runTask(() => this.createApplication({}, MyApplication)); <del> }, /The `initialize` method for Application initializer 'deprecated' should take only one argument - `App`, an instance of an `Application`./); <del> } <ide> });
2
Go
Go
remove use of deprecated os.seek_end
6ee536b4a048bbb9aaa0a017eabecd83d8d2a69e
<ide><path>daemon/logger/loggerutils/logfile.go <ide> func NewLogFile(logPath string, capacity int64, maxFiles int, compress bool, mar <ide> return nil, err <ide> } <ide> <del> size, err := log.Seek(0, os.SEEK_END) <add> size, err := log.Seek(0, io.SeekEnd) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func decompressfile(fileName, destFileName string, since time.Time) (*os.File, e <ide> func newSectionReader(f *os.File) (*io.SectionReader, error) { <ide> // seek to the end to get the size <ide> // we'll leave this at the end of the file since section reader does not advance the reader <del> size, err := f.Seek(0, os.SEEK_END) <add> size, err := f.Seek(0, io.SeekEnd) <ide> if err != nil { <ide> return nil, errors.Wrap(err, "error getting current file size") <ide> }
1
Javascript
Javascript
trim expression only if string
a1341223c084c8188671bb8d6ea1608490b66f9f
<ide><path>src/ng/parse.js <ide> function $ParseProvider() { <ide> $parseOptions.csp = $sniffer.csp; <ide> <ide> return function(exp, interceptorFn) { <del> var parsedExpression, oneTime, <del> cacheKey = (exp = trim(exp)); <add> var parsedExpression, oneTime, cacheKey; <ide> <ide> switch (typeof exp) { <ide> case 'string': <add> cacheKey = exp = exp.trim(); <add> <ide> if (cache.hasOwnProperty(cacheKey)) { <ide> parsedExpression = cache[cacheKey]; <ide> } else {
1
PHP
PHP
fix multiple notification recipients
7bc1103a127d26442e60e343abf34bb6f6857f99
<ide><path>src/Illuminate/Notifications/Channels/MailChannel.php <ide> protected function getRecipients($notifiable, $notification, $message) <ide> <ide> return collect($recipients)->mapWithKeys(function ($recipient, $email) { <ide> return is_numeric($email) <del> ? [(is_string($recipient) ? $recipient : $recipient->email)] <add> ? [$email => (is_string($recipient) ? $recipient : $recipient->email)] <ide> : [$email => $recipient]; <ide> })->all(); <ide> } <ide><path>tests/Integration/Notifications/SendingMailNotificationsTest.php <ide> public function test_mail_is_sent_with_subject() <ide> $user->notify($notification); <ide> } <ide> <add> public function test_mail_is_sent_to_multiple_adresses() <add> { <add> $notification = new TestMailNotificationWithSubject; <add> <add> $user = NotifiableUserWithMultipleAddreses::forceCreate([ <add> 'email' => '[email protected]', <add> ]); <add> <add> $this->markdown->shouldReceive('render')->once()->andReturn('htmlContent'); <add> $this->markdown->shouldReceive('renderText')->once()->andReturn('textContent'); <add> <add> $this->mailer->shouldReceive('send')->once()->with( <add> ['html' => 'htmlContent', 'text' => 'textContent'], <add> $notification->toMail($user)->toArray(), <add> Mockery::on(function ($closure) { <add> $message = Mockery::mock(\Illuminate\Mail\Message::class); <add> <add> $message->shouldReceive('to')->once()->with(['[email protected]', '[email protected]']); <add> <add> $message->shouldReceive('subject')->once()->with('mail custom subject'); <add> <add> $closure($message); <add> <add> return true; <add> }) <add> ); <add> <add> $user->notify($notification); <add> } <add> <ide> public function test_mail_is_sent_using_mailable() <ide> { <ide> $notification = new TestMailNotificationWithMailable; <ide> public function routeNotificationForMail($notification) <ide> } <ide> } <ide> <add>class NotifiableUserWithMultipleAddreses extends NotifiableUser <add>{ <add> public function routeNotificationForMail($notification) <add> { <add> return [ <add> 'foo_'.$this->email, <add> 'bar_'.$this->email, <add> ]; <add> } <add>} <add> <ide> class TestMailNotification extends Notification <ide> { <ide> public function via($notifiable)
2
Text
Text
add example declaration for clarity
e8b6a9e5dd2a43f1c392656acdf257bff77ff098
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.md <ide> forumTopicId: 18242 <ide> If the <code>break</code> statement is omitted from a <code>switch</code> statement's <code>case</code>, the following <code>case</code> statement(s) are executed until a <code>break</code> is encountered. If you have multiple inputs with the same output, you can represent them in a <code>switch</code> statement like this: <ide> <ide> ```js <add>var result = ""; <ide> switch(val) { <ide> case 1: <ide> case 2:
1
Go
Go
clear the containers/images upon failure
b8f66c0d14780bd8cb3b8916acc0287fcaf8cafa
<ide><path>builder.go <ide> func (builder *Builder) run(image *Image, cmd string) (*Container, error) { <ide> return container, nil <ide> } <ide> <del>func (builder *Builder) runCommit(image *Image, cmd string) (*Image, error) { <del> c, err := builder.run(image, cmd) <del> if err != nil { <del> return nil, err <add>func (builder *Builder) clearTmp(containers, images map[string]struct{}) { <add> for c := range containers { <add> tmp := builder.runtime.Get(c) <add> builder.runtime.Destroy(tmp) <add> Debugf("Removing container %s", c) <ide> } <del> if result := c.Wait(); result != 0 { <del> return nil, fmt.Errorf("!!! '%s' return non-zero exit code '%d'. Aborting.", cmd, result) <del> } <del> img, err := builder.runtime.Commit(c.Id, "", "", "", "") <del> if err != nil { <del> return nil, err <add> for i := range images { <add> builder.runtime.graph.Delete(i) <add> Debugf("Removing image %s", i) <ide> } <del> return img, nil <ide> } <ide> <ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) error { <del> var image, base *Image <add> var ( <add> image, base *Image <add> tmpContainers map[string]struct{} = make(map[string]struct{}) <add> tmpImages map[string]struct{} = make(map[string]struct{}) <add> ) <add> defer builder.clearTmp(tmpContainers, tmpImages) <ide> <ide> file := bufio.NewReader(dockerfile) <ide> for { <ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) error { <ide> if image == nil { <ide> return fmt.Errorf("Please provide a source image with `from` prior to run") <ide> } <del> base, err = builder.runCommit(image, tmp[1]) <add> <add> // Create the container and start it <add> c, err := builder.run(image, tmp[1]) <ide> if err != nil { <ide> return err <ide> } <add> tmpContainers[c.Id] = struct{}{} <add> <add> // Wait for it to finish <add> if result := c.Wait(); result != 0 { <add> return fmt.Errorf("!!! '%s' return non-zero exit code '%d'. Aborting.", tmp[1], result) <add> } <add> <add> // Commit the container <add> base, err := builder.runtime.Commit(c.Id, "", "", "", "") <add> if err != nil { <add> return err <add> } <add> tmpImages[base.Id] = struct{}{} <add> <ide> fmt.Fprintf(stdout, "===> %s\n", base.Id) <ide> break <ide> case "copy": <ide> func (builder *Builder) Build(dockerfile io.Reader, stdout io.Writer) error { <ide> } <ide> } <ide> if base != nil { <add> // The build is successful, keep the temporary containers and images <add> for i := range tmpImages { <add> delete(tmpImages, i) <add> } <add> for i := range tmpContainers { <add> delete(tmpContainers, i) <add> } <ide> fmt.Fprintf(stdout, "Build finished. image id: %s\n", base.Id) <ide> } else { <ide> fmt.Fprintf(stdout, "An error occured during the build\n")
1
Ruby
Ruby
add missing ruby2_keywords in routingassertions
e3c9d566aee43545951648b8b60b1045dc4d8c37
<ide><path>actionpack/lib/action_dispatch/testing/assertions/routing.rb <ide> def method_missing(selector, *args, &block) <ide> super <ide> end <ide> end <add> ruby2_keywords(:method_missing) <ide> <ide> private <ide> # Recognizes the route for a given path.
1
PHP
PHP
add throws doc block
4e0f4734bea5898df31f558eaf43222d09020d23
<ide><path>src/Illuminate/Container/Container.php <ide> public function factory($abstract) <ide> * @param string $abstract <ide> * @param array $parameters <ide> * @return mixed <add> * <add> * @throws \Illuminate\Contracts\Container\BindingResolutionException <ide> */ <ide> public function makeWith($abstract, array $parameters = []) <ide> {
1
Javascript
Javascript
improve empty typed array inspection
db6a24699abce1eba6760c2c3e31b390ab684410
<ide><path>lib/util.js <ide> function formatValue(ctx, value, recurseTimes) { <ide> formatter = formatMap; <ide> } else if (isTypedArray(value)) { <ide> braces = [`${getPrefix(constructor, tag)}[`, ']']; <add> if (value.length === 0 && keyLength === 0 && !ctx.showHidden) <add> return `${braces[0]}]`; <ide> formatter = formatTypedArray; <ide> } else if (isMapIterator(value)) { <ide> braces = [`[${tag}] {`, '}']; <ide><path>test/parallel/test-fs-read-empty-buffer.js <ide> assert.throws( <ide> { <ide> code: 'ERR_INVALID_ARG_VALUE', <ide> message: 'The argument \'buffer\' is empty and cannot be written. ' + <del> 'Received Uint8Array [ ]' <add> 'Received Uint8Array []' <ide> } <ide> ); <ide><path>test/parallel/test-util-inspect.js <ide> assert.strictEqual(util.inspect({ 'a': { 'b': { 'c': 2 } } }, false, 1), <ide> '{ a: { b: [Object] } }'); <ide> assert.strictEqual(util.inspect({ 'a': { 'b': ['c'] } }, false, 1), <ide> '{ a: { b: [Array] } }'); <del>assert.strictEqual(util.inspect(new Uint8Array(0)), 'Uint8Array [ ]'); <add>assert.strictEqual(util.inspect(new Uint8Array(0)), 'Uint8Array []'); <add>assert(inspect(new Uint8Array(0), { showHidden: true }).includes('[buffer]')); <ide> assert.strictEqual( <ide> util.inspect( <ide> Object.create(
3
Go
Go
remove unused help command
298a26e0b2d086a32f14ee675bf24322cc92ddd4
<ide><path>cli/cobra.go <ide> package cli // import "github.com/docker/docker/cli" <ide> <ide> import ( <ide> "fmt" <del> "strings" <ide> <ide> "github.com/docker/docker/pkg/term" <del> "github.com/pkg/errors" <ide> "github.com/spf13/cobra" <ide> ) <ide> <ide> func SetupRootCommand(rootCmd *cobra.Command) { <ide> rootCmd.SetUsageTemplate(usageTemplate) <ide> rootCmd.SetHelpTemplate(helpTemplate) <ide> rootCmd.SetFlagErrorFunc(FlagErrorFunc) <del> rootCmd.SetHelpCommand(helpCommand) <ide> rootCmd.SetVersionTemplate("Docker version {{.Version}}\n") <ide> <ide> rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage") <ide> func FlagErrorFunc(cmd *cobra.Command, err error) error { <ide> } <ide> } <ide> <del>var helpCommand = &cobra.Command{ <del> Use: "help [command]", <del> Short: "Help about the command", <del> PersistentPreRun: func(cmd *cobra.Command, args []string) {}, <del> PersistentPostRun: func(cmd *cobra.Command, args []string) {}, <del> RunE: func(c *cobra.Command, args []string) error { <del> cmd, args, e := c.Root().Find(args) <del> if cmd == nil || e != nil || len(args) > 0 { <del> return errors.Errorf("unknown help topic: %v", strings.Join(args, " ")) <del> } <del> <del> helpFunc := cmd.HelpFunc() <del> helpFunc(cmd, args) <del> return nil <del> }, <del>} <del> <ide> func hasSubCommands(cmd *cobra.Command) bool { <ide> return len(operationSubCommands(cmd)) > 0 <ide> }
1
Ruby
Ruby
remove dead code
8b9ddab287ca3fb5a39cfda82421fafbaf649eb5
<ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def build_where(opts, other = []) <ide> case opts <ide> when String, Array <ide> #TODO: Remove duplication with: /activerecord/lib/active_record/sanitization.rb:113 <del> values = Hash === other.first ? other.first.values : other <del> <ide> [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))] <ide> when Hash <ide> opts = PredicateBuilder.resolve_column_aliases(klass, opts)
1
Ruby
Ruby
make respond_to? work as expected
0306e4a20483a91d9288ac6f20e6b79db6eca7a7
<ide><path>activeresource/lib/active_resource/base.rb <ide> def load(attributes) <ide> end <ide> self <ide> end <add> <add> # For checking respond_to? without searching the attributes (which is faster). <add> alias_method :respond_to_without_attributes?, :respond_to? <add> <add> # A Person object with a name attribute can ask person.respond_to?("name"), person.respond_to?("name="), and <add> # person.respond_to?("name?") which will all return true. <add> def respond_to?(method, include_priv = false) <add> method_name = method.to_s <add> if attributes.nil? <add> return super <add> elsif attributes.has_key?(method_name) <add> return true <add> elsif ['?','='].include?(method_name.last) && attributes.has_key?(method_name.first(-1)) <add> return true <add> end <add> # super must be called at the end of the method, because the inherited respond_to? <add> # would return true for generated readers, even if the attribute wasn't present <add> super <add> end <add> <ide> <ide> protected <ide> def connection(refresh = false) <ide><path>activeresource/test/base_test.rb <ide> def test_find_by_id <ide> assert_kind_of Person, matz <ide> assert_equal "Matz", matz.name <ide> end <add> <add> def test_respond_to <add> matz = Person.find(1) <add> assert matz.respond_to?(:name) <add> assert matz.respond_to?(:name=) <add> assert matz.respond_to?(:name?) <add> assert !matz.respond_to?(:java) <add> end <ide> <ide> def test_find_by_id_with_custom_prefix <ide> addy = StreetAddress.find(1, :params => { :person_id => 1 })
2
Javascript
Javascript
remove event constants
22d16cc15df8e570b79c2825fb495c2b98b40bf5
<ide><path>packages/react-dom/src/client/ReactDOMComponent.js <ide> import { <ide> listenToNonDelegatedEvent, <ide> } from '../events/DOMPluginEventSystem'; <ide> import {getEventListenerMap} from './ReactDOMComponentTree'; <del>import { <del> TOP_LOAD, <del> TOP_ERROR, <del> TOP_TOGGLE, <del> TOP_INVALID, <del> TOP_CANCEL, <del> TOP_CLOSE, <del>} from '../events/DOMTopLevelEventTypes'; <ide> <ide> let didWarnInvalidHydration = false; <ide> let didWarnScriptTags = false; <ide> export function setInitialProperties( <ide> let props: Object; <ide> switch (tag) { <ide> case 'dialog': <del> listenToNonDelegatedEvent(TOP_CANCEL, domElement); <del> listenToNonDelegatedEvent(TOP_CLOSE, domElement); <add> listenToNonDelegatedEvent('cancel', domElement); <add> listenToNonDelegatedEvent('close', domElement); <ide> props = rawProps; <ide> break; <ide> case 'iframe': <ide> case 'object': <ide> case 'embed': <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the load event. <del> listenToNonDelegatedEvent(TOP_LOAD, domElement); <add> listenToNonDelegatedEvent('load', domElement); <ide> props = rawProps; <ide> break; <ide> case 'video': <ide> export function setInitialProperties( <ide> case 'source': <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the error event. <del> listenToNonDelegatedEvent(TOP_ERROR, domElement); <add> listenToNonDelegatedEvent('error', domElement); <ide> props = rawProps; <ide> break; <ide> case 'img': <ide> case 'image': <ide> case 'link': <ide> // We listen to these events in case to ensure emulated bubble <ide> // listeners still fire for error and load events. <del> listenToNonDelegatedEvent(TOP_ERROR, domElement); <del> listenToNonDelegatedEvent(TOP_LOAD, domElement); <add> listenToNonDelegatedEvent('error', domElement); <add> listenToNonDelegatedEvent('load', domElement); <ide> props = rawProps; <ide> break; <ide> case 'details': <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the toggle event. <del> listenToNonDelegatedEvent(TOP_TOGGLE, domElement); <add> listenToNonDelegatedEvent('toggle', domElement); <ide> props = rawProps; <ide> break; <ide> case 'input': <ide> ReactDOMInputInitWrapperState(domElement, rawProps); <ide> props = ReactDOMInputGetHostProps(domElement, rawProps); <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the invalid event. <del> listenToNonDelegatedEvent(TOP_INVALID, domElement); <add> listenToNonDelegatedEvent('invalid', domElement); <ide> // For controlled components we always need to ensure we're listening <ide> // to onChange. Even if there is no listener. <ide> ensureListeningTo(rootContainerElement, 'onChange', domElement); <ide> export function setInitialProperties( <ide> props = ReactDOMSelectGetHostProps(domElement, rawProps); <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the invalid event. <del> listenToNonDelegatedEvent(TOP_INVALID, domElement); <add> listenToNonDelegatedEvent('invalid', domElement); <ide> // For controlled components we always need to ensure we're listening <ide> // to onChange. Even if there is no listener. <ide> ensureListeningTo(rootContainerElement, 'onChange', domElement); <ide> export function setInitialProperties( <ide> props = ReactDOMTextareaGetHostProps(domElement, rawProps); <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the invalid event. <del> listenToNonDelegatedEvent(TOP_INVALID, domElement); <add> listenToNonDelegatedEvent('invalid', domElement); <ide> // For controlled components we always need to ensure we're listening <ide> // to onChange. Even if there is no listener. <ide> ensureListeningTo(rootContainerElement, 'onChange', domElement); <ide> export function diffHydratedProperties( <ide> // TODO: Make sure that we check isMounted before firing any of these events. <ide> switch (tag) { <ide> case 'dialog': <del> listenToNonDelegatedEvent(TOP_CANCEL, domElement); <del> listenToNonDelegatedEvent(TOP_CLOSE, domElement); <add> listenToNonDelegatedEvent('cancel', domElement); <add> listenToNonDelegatedEvent('close', domElement); <ide> break; <ide> case 'iframe': <ide> case 'object': <ide> case 'embed': <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the load event. <del> listenToNonDelegatedEvent(TOP_LOAD, domElement); <add> listenToNonDelegatedEvent('load', domElement); <ide> break; <ide> case 'video': <ide> case 'audio': <ide> export function diffHydratedProperties( <ide> case 'source': <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the error event. <del> listenToNonDelegatedEvent(TOP_ERROR, domElement); <add> listenToNonDelegatedEvent('error', domElement); <ide> break; <ide> case 'img': <ide> case 'image': <ide> case 'link': <ide> // We listen to these events in case to ensure emulated bubble <ide> // listeners still fire for error and load events. <del> listenToNonDelegatedEvent(TOP_ERROR, domElement); <del> listenToNonDelegatedEvent(TOP_LOAD, domElement); <add> listenToNonDelegatedEvent('error', domElement); <add> listenToNonDelegatedEvent('load', domElement); <ide> break; <ide> case 'details': <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the toggle event. <del> listenToNonDelegatedEvent(TOP_TOGGLE, domElement); <add> listenToNonDelegatedEvent('toggle', domElement); <ide> break; <ide> case 'input': <ide> ReactDOMInputInitWrapperState(domElement, rawProps); <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the invalid event. <del> listenToNonDelegatedEvent(TOP_INVALID, domElement); <add> listenToNonDelegatedEvent('invalid', domElement); <ide> // For controlled components we always need to ensure we're listening <ide> // to onChange. Even if there is no listener. <ide> ensureListeningTo(rootContainerElement, 'onChange', domElement); <ide> export function diffHydratedProperties( <ide> ReactDOMSelectInitWrapperState(domElement, rawProps); <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the invalid event. <del> listenToNonDelegatedEvent(TOP_INVALID, domElement); <add> listenToNonDelegatedEvent('invalid', domElement); <ide> // For controlled components we always need to ensure we're listening <ide> // to onChange. Even if there is no listener. <ide> ensureListeningTo(rootContainerElement, 'onChange', domElement); <ide> export function diffHydratedProperties( <ide> ReactDOMTextareaInitWrapperState(domElement, rawProps); <ide> // We listen to this event in case to ensure emulated bubble <ide> // listeners still fire for the invalid event. <del> listenToNonDelegatedEvent(TOP_INVALID, domElement); <add> listenToNonDelegatedEvent('invalid', domElement); <ide> // For controlled components we always need to ensure we're listening <ide> // to onChange. Even if there is no listener. <ide> ensureListeningTo(rootContainerElement, 'onChange', domElement); <ide><path>packages/react-dom/src/client/ReactDOMComponentTree.js <ide> import type { <ide> SuspenseInstance, <ide> Props, <ide> } from './ReactDOMHostConfig'; <del>import type {DOMTopLevelEventType} from '../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../events/DOMEventNames'; <ide> <ide> import { <ide> HostComponent, <ide> const internalEventHandlersKey = '__reactEvents$' + randomKey; <ide> const internalEventHandlerListenersKey = '__reactListeners$' + randomKey; <ide> <ide> export type ElementListenerMap = Map< <del> DOMTopLevelEventType | string, <add> DOMEventName | string, <ide> ElementListenerMapEntry | null, <ide> >; <ide> <ide><path>packages/react-dom/src/client/ReactDOMEventHandle.js <ide> * @flow <ide> */ <ide> <del>import type {DOMTopLevelEventType} from '../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../events/DOMEventNames'; <ide> import type {EventPriority, ReactScopeInstance} from 'shared/ReactTypes'; <ide> import type { <ide> ReactDOMEventHandle, <ide> function isReactScope(target: EventTarget | ReactScopeInstance): boolean { <ide> } <ide> <ide> function createEventHandleListener( <del> type: DOMTopLevelEventType, <add> type: DOMEventName, <ide> isCapturePhaseListener: boolean, <ide> callback: (SyntheticEvent<EventTarget>) => void, <ide> ): ReactDOMEventHandleListener { <ide> function createEventHandleListener( <ide> <ide> function registerEventOnNearestTargetContainer( <ide> targetFiber: Fiber, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> isPassiveListener: boolean | void, <ide> listenerPriority: EventPriority | void, <ide> isCapturePhaseListener: boolean, <ide> function registerEventOnNearestTargetContainer( <ide> targetContainer = ((targetContainer.parentNode: any): Element); <ide> } <ide> listenToNativeEvent( <del> topLevelType, <add> domEventName, <ide> isCapturePhaseListener, <ide> targetContainer, <ide> targetElement, <ide> function registerEventOnNearestTargetContainer( <ide> <ide> function registerReactDOMEvent( <ide> target: EventTarget | ReactScopeInstance, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> isPassiveListener: boolean | void, <ide> isCapturePhaseListener: boolean, <ide> listenerPriority: EventPriority | void, <ide> function registerReactDOMEvent( <ide> } <ide> registerEventOnNearestTargetContainer( <ide> targetFiber, <del> topLevelType, <add> domEventName, <ide> isPassiveListener, <ide> listenerPriority, <ide> isCapturePhaseListener, <ide> function registerReactDOMEvent( <ide> } <ide> registerEventOnNearestTargetContainer( <ide> targetFiber, <del> topLevelType, <add> domEventName, <ide> isPassiveListener, <ide> listenerPriority, <ide> isCapturePhaseListener, <ide> function registerReactDOMEvent( <ide> // These are valid event targets, but they are also <ide> // non-managed React nodes. <ide> listenToNativeEvent( <del> topLevelType, <add> domEventName, <ide> isCapturePhaseListener, <ide> eventTarget, <ide> null, <ide> export function createEventHandle( <ide> options?: EventHandleOptions, <ide> ): ReactDOMEventHandle { <ide> if (enableCreateEventHandleAPI) { <del> const topLevelType = ((type: any): DOMTopLevelEventType); <add> const domEventName = ((type: any): DOMEventName); <ide> let isCapturePhaseListener = false; <ide> let isPassiveListener = undefined; // Undefined means to use the browser default <ide> let listenerPriority; <ide> export function createEventHandle( <ide> } <ide> } <ide> if (listenerPriority === undefined) { <del> listenerPriority = getEventPriorityForListenerSystem(topLevelType); <add> listenerPriority = getEventPriorityForListenerSystem(domEventName); <ide> } <ide> <ide> const registeredReactDOMEvents = new PossiblyWeakSet(); <ide> export function createEventHandle( <ide> registeredReactDOMEvents.add(target); <ide> registerReactDOMEvent( <ide> target, <del> topLevelType, <add> domEventName, <ide> isPassiveListener, <ide> isCapturePhaseListener, <ide> listenerPriority, <ide> ); <ide> // Add the event to our known event types list. <del> addEventTypeToDispatchConfig(topLevelType); <add> addEventTypeToDispatchConfig(domEventName); <ide> } <ide> const listener = createEventHandleListener( <del> topLevelType, <add> domEventName, <ide> isCapturePhaseListener, <ide> callback, <ide> ); <ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js <ide> * @flow <ide> */ <ide> <del>import type {TopLevelType} from '../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../events/DOMEventNames'; <ide> import type {Fiber, FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; <ide> import type { <ide> BoundingRect, <ide> import { <ide> enableScopeAPI, <ide> } from 'shared/ReactFeatureFlags'; <ide> import {HostComponent, HostText} from 'react-reconciler/src/ReactWorkTags'; <del>import {TOP_BEFORE_BLUR, TOP_AFTER_BLUR} from '../events/DOMTopLevelEventTypes'; <ide> import {listenToReactEvent} from '../events/DOMPluginEventSystem'; <ide> <ide> export type Type = string; <ide> export function insertInContainerBefore( <ide> } <ide> } <ide> <del>function createEvent(type: TopLevelType, bubbles: boolean): Event { <add>function createEvent(type: DOMEventName, bubbles: boolean): Event { <ide> const event = document.createEvent('Event'); <ide> event.initEvent(((type: any): string), bubbles, false); <ide> return event; <ide> } <ide> <ide> function dispatchBeforeDetachedBlur(target: HTMLElement): void { <ide> if (enableDeprecatedFlareAPI || enableCreateEventHandleAPI) { <del> const event = createEvent(TOP_BEFORE_BLUR, true); <add> const event = createEvent('beforeblur', true); <ide> // Dispatch "beforeblur" directly on the target, <ide> // so it gets picked up by the event system and <ide> // can propagate through the React internal tree. <ide> function dispatchBeforeDetachedBlur(target: HTMLElement): void { <ide> <ide> function dispatchAfterDetachedBlur(target: HTMLElement): void { <ide> if (enableDeprecatedFlareAPI || enableCreateEventHandleAPI) { <del> const event = createEvent(TOP_AFTER_BLUR, false); <add> const event = createEvent('afterblur', false); <ide> // So we know what was detached, make the relatedTarget the <ide> // detached target on the "afterblur" event. <ide> (event: any).relatedTarget = target; <ide><path>packages/react-dom/src/events/DOMEventNames.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> */ <add> <add>import getVendorPrefixedEventName from './getVendorPrefixedEventName'; <add> <add>export type DOMEventName = <add> | 'abort' <add> | 'afterblur' // Not a real event. This is used by event experiments. <add> // These are vendor-prefixed so you should use the exported constants instead: <add> // 'animationiteration' | <add> // 'animationend | <add> // 'animationstart' | <add> | 'beforeblur' // Not a real event. This is used by event experiments. <add> | 'canplay' <add> | 'canplaythrough' <add> | 'cancel' <add> | 'change' <add> | 'click' <add> | 'close' <add> | 'compositionend' <add> | 'compositionstart' <add> | 'compositionupdate' <add> | 'contextmenu' <add> | 'copy' <add> | 'cut' <add> | 'dblclick' <add> | 'auxclick' <add> | 'drag' <add> | 'dragend' <add> | 'dragenter' <add> | 'dragexit' <add> | 'dragleave' <add> | 'dragover' <add> | 'dragstart' <add> | 'drop' <add> | 'durationchange' <add> | 'emptied' <add> | 'encrypted' <add> | 'ended' <add> | 'error' <add> | 'focusin' <add> | 'focusout' <add> | 'gotpointercapture' <add> | 'input' <add> | 'invalid' <add> | 'keydown' <add> | 'keypress' <add> | 'keyup' <add> | 'load' <add> | 'loadstart' <add> | 'loadeddata' <add> | 'loadedmetadata' <add> | 'lostpointercapture' <add> | 'mousedown' <add> | 'mousemove' <add> | 'mouseout' <add> | 'mouseover' <add> | 'mouseup' <add> | 'paste' <add> | 'pause' <add> | 'play' <add> | 'playing' <add> | 'pointercancel' <add> | 'pointerdown' <add> | 'pointerenter' <add> | 'pointerleave' <add> | 'pointermove' <add> | 'pointerout' <add> | 'pointerover' <add> | 'pointerup' <add> | 'progress' <add> | 'ratechange' <add> | 'reset' <add> | 'scroll' <add> | 'seeked' <add> | 'seeking' <add> | 'selectionchange' <add> | 'stalled' <add> | 'submit' <add> | 'suspend' <add> | 'textInput' // Intentionally camelCase. Non-standard. <add> | 'timeupdate' <add> | 'toggle' <add> | 'touchcancel' <add> | 'touchend' <add> | 'touchmove' <add> | 'touchstart' <add> // These are vendor-prefixed so you should use the exported constants instead: <add> // 'transitionend' | <add> | 'volumechange' <add> | 'waiting' <add> | 'wheel'; <add> <add>export const ANIMATION_END: DOMEventName = getVendorPrefixedEventName( <add> 'animationend', <add>); <add>export const ANIMATION_ITERATION: DOMEventName = getVendorPrefixedEventName( <add> 'animationiteration', <add>); <add>export const ANIMATION_START: DOMEventName = getVendorPrefixedEventName( <add> 'animationstart', <add>); <add>export const TRANSITION_END: DOMEventName = getVendorPrefixedEventName( <add> 'transitionend', <add>); <ide><path>packages/react-dom/src/events/DOMEventProperties.js <ide> */ <ide> <ide> import type {EventPriority} from 'shared/ReactTypes'; <del>import type { <del> TopLevelType, <del> DOMTopLevelEventType, <del>} from '../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../events/DOMEventNames'; <ide> <ide> import {registerTwoPhaseEvent} from './EventRegistry'; <del>import * as DOMTopLevelEventTypes from './DOMTopLevelEventTypes'; <add>import { <add> ANIMATION_END, <add> ANIMATION_ITERATION, <add> ANIMATION_START, <add> TRANSITION_END, <add>} from './DOMEventNames'; <ide> import { <ide> DiscreteEvent, <ide> UserBlockingEvent, <ide> import { <ide> import {enableCreateEventHandleAPI} from 'shared/ReactFeatureFlags'; <ide> <ide> export const topLevelEventsToReactNames: Map< <del> TopLevelType, <add> DOMEventName, <ide> string | null, <ide> > = new Map(); <ide> <ide> const eventPriorities = new Map(); <ide> <ide> // prettier-ignore <ide> const discreteEventPairsForSimpleEventPlugin = [ <del> DOMTopLevelEventTypes.TOP_CANCEL, 'cancel', <del> DOMTopLevelEventTypes.TOP_CLICK, 'click', <del> DOMTopLevelEventTypes.TOP_CLOSE, 'close', <del> DOMTopLevelEventTypes.TOP_CONTEXT_MENU, 'contextMenu', <del> DOMTopLevelEventTypes.TOP_COPY, 'copy', <del> DOMTopLevelEventTypes.TOP_CUT, 'cut', <del> DOMTopLevelEventTypes.TOP_AUX_CLICK, 'auxClick', <del> DOMTopLevelEventTypes.TOP_DOUBLE_CLICK, 'doubleClick', <del> DOMTopLevelEventTypes.TOP_DRAG_END, 'dragEnd', <del> DOMTopLevelEventTypes.TOP_DRAG_START, 'dragStart', <del> DOMTopLevelEventTypes.TOP_DROP, 'drop', <del> DOMTopLevelEventTypes.TOP_FOCUS_IN, 'focus', <del> DOMTopLevelEventTypes.TOP_FOCUS_OUT, 'blur', <del> DOMTopLevelEventTypes.TOP_INPUT, 'input', <del> DOMTopLevelEventTypes.TOP_INVALID, 'invalid', <del> DOMTopLevelEventTypes.TOP_KEY_DOWN, 'keyDown', <del> DOMTopLevelEventTypes.TOP_KEY_PRESS, 'keyPress', <del> DOMTopLevelEventTypes.TOP_KEY_UP, 'keyUp', <del> DOMTopLevelEventTypes.TOP_MOUSE_DOWN, 'mouseDown', <del> DOMTopLevelEventTypes.TOP_MOUSE_UP, 'mouseUp', <del> DOMTopLevelEventTypes.TOP_PASTE, 'paste', <del> DOMTopLevelEventTypes.TOP_PAUSE, 'pause', <del> DOMTopLevelEventTypes.TOP_PLAY, 'play', <del> DOMTopLevelEventTypes.TOP_POINTER_CANCEL, 'pointerCancel', <del> DOMTopLevelEventTypes.TOP_POINTER_DOWN, 'pointerDown', <del> DOMTopLevelEventTypes.TOP_POINTER_UP, 'pointerUp', <del> DOMTopLevelEventTypes.TOP_RATE_CHANGE, 'rateChange', <del> DOMTopLevelEventTypes.TOP_RESET, 'reset', <del> DOMTopLevelEventTypes.TOP_SEEKED, 'seeked', <del> DOMTopLevelEventTypes.TOP_SUBMIT, 'submit', <del> DOMTopLevelEventTypes.TOP_TOUCH_CANCEL, 'touchCancel', <del> DOMTopLevelEventTypes.TOP_TOUCH_END, 'touchEnd', <del> DOMTopLevelEventTypes.TOP_TOUCH_START, 'touchStart', <del> DOMTopLevelEventTypes.TOP_VOLUME_CHANGE, 'volumeChange', <add> ('cancel': DOMEventName), 'cancel', <add> ('click': DOMEventName), 'click', <add> ('close': DOMEventName), 'close', <add> ('contextmenu': DOMEventName), 'contextMenu', <add> ('copy': DOMEventName), 'copy', <add> ('cut': DOMEventName), 'cut', <add> ('auxclick': DOMEventName), 'auxClick', <add> ('dblclick': DOMEventName), 'doubleClick', // Careful! <add> ('dragend': DOMEventName), 'dragEnd', <add> ('dragstart': DOMEventName), 'dragStart', <add> ('drop': DOMEventName), 'drop', <add> ('focusin': DOMEventName), 'focus', // Careful! <add> ('focusout': DOMEventName), 'blur', // Careful! <add> ('input': DOMEventName), 'input', <add> ('invalid': DOMEventName), 'invalid', <add> ('keydown': DOMEventName), 'keyDown', <add> ('keypress': DOMEventName), 'keyPress', <add> ('keyup': DOMEventName), 'keyUp', <add> ('mousedown': DOMEventName), 'mouseDown', <add> ('mouseup': DOMEventName), 'mouseUp', <add> ('paste': DOMEventName), 'paste', <add> ('pause': DOMEventName), 'pause', <add> ('play': DOMEventName), 'play', <add> ('pointercancel': DOMEventName), 'pointerCancel', <add> ('pointerdown': DOMEventName), 'pointerDown', <add> ('pointerup': DOMEventName), 'pointerUp', <add> ('ratechange': DOMEventName), 'rateChange', <add> ('reset': DOMEventName), 'reset', <add> ('seeked': DOMEventName), 'seeked', <add> ('submit': DOMEventName), 'submit', <add> ('touchcancel': DOMEventName), 'touchCancel', <add> ('touchend': DOMEventName), 'touchEnd', <add> ('touchstart': DOMEventName), 'touchStart', <add> ('volumechange': DOMEventName), 'volumeChange', <ide> ]; <ide> <del>const otherDiscreteEvents = [ <del> DOMTopLevelEventTypes.TOP_CHANGE, <del> DOMTopLevelEventTypes.TOP_SELECTION_CHANGE, <del> DOMTopLevelEventTypes.TOP_TEXT_INPUT, <del> DOMTopLevelEventTypes.TOP_COMPOSITION_START, <del> DOMTopLevelEventTypes.TOP_COMPOSITION_END, <del> DOMTopLevelEventTypes.TOP_COMPOSITION_UPDATE, <add>const otherDiscreteEvents: Array<DOMEventName> = [ <add> 'change', <add> 'selectionchange', <add> 'textInput', <add> 'compositionstart', <add> 'compositionend', <add> 'compositionupdate', <ide> ]; <ide> <ide> if (enableCreateEventHandleAPI) { <del> otherDiscreteEvents.push( <del> DOMTopLevelEventTypes.TOP_BEFORE_BLUR, <del> DOMTopLevelEventTypes.TOP_AFTER_BLUR, <del> ); <add> otherDiscreteEvents.push('beforeblur', 'afterblur'); <ide> } <ide> <ide> // prettier-ignore <del>const userBlockingPairsForSimpleEventPlugin = [ <del> DOMTopLevelEventTypes.TOP_DRAG, 'drag', <del> DOMTopLevelEventTypes.TOP_DRAG_ENTER, 'dragEnter', <del> DOMTopLevelEventTypes.TOP_DRAG_EXIT, 'dragExit', <del> DOMTopLevelEventTypes.TOP_DRAG_LEAVE, 'dragLeave', <del> DOMTopLevelEventTypes.TOP_DRAG_OVER, 'dragOver', <del> DOMTopLevelEventTypes.TOP_MOUSE_MOVE, 'mouseMove', <del> DOMTopLevelEventTypes.TOP_MOUSE_OUT, 'mouseOut', <del> DOMTopLevelEventTypes.TOP_MOUSE_OVER, 'mouseOver', <del> DOMTopLevelEventTypes.TOP_POINTER_MOVE, 'pointerMove', <del> DOMTopLevelEventTypes.TOP_POINTER_OUT, 'pointerOut', <del> DOMTopLevelEventTypes.TOP_POINTER_OVER, 'pointerOver', <del> DOMTopLevelEventTypes.TOP_SCROLL, 'scroll', <del> DOMTopLevelEventTypes.TOP_TOGGLE, 'toggle', <del> DOMTopLevelEventTypes.TOP_TOUCH_MOVE, 'touchMove', <del> DOMTopLevelEventTypes.TOP_WHEEL, 'wheel', <add>const userBlockingPairsForSimpleEventPlugin: Array<string | DOMEventName> = [ <add> ('drag': DOMEventName), 'drag', <add> ('dragenter': DOMEventName), 'dragEnter', <add> ('dragexit': DOMEventName), 'dragExit', <add> ('dragleave': DOMEventName), 'dragLeave', <add> ('dragover': DOMEventName), 'dragOver', <add> ('mousemove': DOMEventName), 'mouseMove', <add> ('mouseout': DOMEventName), 'mouseOut', <add> ('mouseover': DOMEventName), 'mouseOver', <add> ('pointermove': DOMEventName), 'pointerMove', <add> ('pointerout': DOMEventName), 'pointerOut', <add> ('pointerover': DOMEventName), 'pointerOver', <add> ('scroll': DOMEventName), 'scroll', <add> ('toggle': DOMEventName), 'toggle', <add> ('touchmove': DOMEventName), 'touchMove', <add> ('wheel': DOMEventName), 'wheel', <ide> ]; <ide> <ide> // prettier-ignore <del>const continuousPairsForSimpleEventPlugin = [ <del> DOMTopLevelEventTypes.TOP_ABORT, 'abort', <del> DOMTopLevelEventTypes.TOP_ANIMATION_END, 'animationEnd', <del> DOMTopLevelEventTypes.TOP_ANIMATION_ITERATION, 'animationIteration', <del> DOMTopLevelEventTypes.TOP_ANIMATION_START, 'animationStart', <del> DOMTopLevelEventTypes.TOP_CAN_PLAY, 'canPlay', <del> DOMTopLevelEventTypes.TOP_CAN_PLAY_THROUGH, 'canPlayThrough', <del> DOMTopLevelEventTypes.TOP_DURATION_CHANGE, 'durationChange', <del> DOMTopLevelEventTypes.TOP_EMPTIED, 'emptied', <del> DOMTopLevelEventTypes.TOP_ENCRYPTED, 'encrypted', <del> DOMTopLevelEventTypes.TOP_ENDED, 'ended', <del> DOMTopLevelEventTypes.TOP_ERROR, 'error', <del> DOMTopLevelEventTypes.TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture', <del> DOMTopLevelEventTypes.TOP_LOAD, 'load', <del> DOMTopLevelEventTypes.TOP_LOADED_DATA, 'loadedData', <del> DOMTopLevelEventTypes.TOP_LOADED_METADATA, 'loadedMetadata', <del> DOMTopLevelEventTypes.TOP_LOAD_START, 'loadStart', <del> DOMTopLevelEventTypes.TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture', <del> DOMTopLevelEventTypes.TOP_PLAYING, 'playing', <del> DOMTopLevelEventTypes.TOP_PROGRESS, 'progress', <del> DOMTopLevelEventTypes.TOP_SEEKING, 'seeking', <del> DOMTopLevelEventTypes.TOP_STALLED, 'stalled', <del> DOMTopLevelEventTypes.TOP_SUSPEND, 'suspend', <del> DOMTopLevelEventTypes.TOP_TIME_UPDATE, 'timeUpdate', <del> DOMTopLevelEventTypes.TOP_TRANSITION_END, 'transitionEnd', <del> DOMTopLevelEventTypes.TOP_WAITING, 'waiting', <add>const continuousPairsForSimpleEventPlugin: Array<string | DOMEventName> = [ <add> ('abort': DOMEventName), 'abort', <add> (ANIMATION_END: DOMEventName), 'animationEnd', <add> (ANIMATION_ITERATION: DOMEventName), 'animationIteration', <add> (ANIMATION_START: DOMEventName), 'animationStart', <add> ('canplay': DOMEventName), 'canPlay', <add> ('canplaythrough': DOMEventName), 'canPlayThrough', <add> ('durationchange': DOMEventName), 'durationChange', <add> ('emptied': DOMEventName), 'emptied', <add> ('encrypted': DOMEventName), 'encrypted', <add> ('ended': DOMEventName), 'ended', <add> ('error': DOMEventName), 'error', <add> ('gotpointercapture': DOMEventName), 'gotPointerCapture', <add> ('load': DOMEventName), 'load', <add> ('loadeddata': DOMEventName), 'loadedData', <add> ('loadedmetadata': DOMEventName), 'loadedMetadata', <add> ('loadstart': DOMEventName), 'loadStart', <add> ('lostpointercapture': DOMEventName), 'lostPointerCapture', <add> ('playing': DOMEventName), 'playing', <add> ('progress': DOMEventName), 'progress', <add> ('seeking': DOMEventName), 'seeking', <add> ('stalled': DOMEventName), 'stalled', <add> ('suspend': DOMEventName), 'suspend', <add> ('timeupdate': DOMEventName), 'timeUpdate', <add> (TRANSITION_END: DOMEventName), 'transitionEnd', <add> ('waiting': DOMEventName), 'waiting', <ide> ]; <ide> <ide> /** <ide> const continuousPairsForSimpleEventPlugin = [ <ide> * into <ide> * <ide> * topLevelEventsToReactNames = new Map([ <del> * [TOP_ABORT, 'onAbort'], <add> * ['abort', 'onAbort'], <ide> * ]); <ide> * <ide> * and registers them. <ide> */ <ide> function registerSimplePluginEventsAndSetTheirPriorities( <del> eventTypes: Array<DOMTopLevelEventType | string>, <add> eventTypes: Array<DOMEventName | string>, <ide> priority: EventPriority, <ide> ): void { <ide> // As the event types are in pairs of two, we need to iterate <ide> function registerSimplePluginEventsAndSetTheirPriorities( <ide> // if we only use three arrays to process all the categories of <ide> // instead of tuples. <ide> for (let i = 0; i < eventTypes.length; i += 2) { <del> const topEvent = ((eventTypes[i]: any): DOMTopLevelEventType); <add> const topEvent = ((eventTypes[i]: any): DOMEventName); <ide> const event = ((eventTypes[i + 1]: any): string); <ide> const capitalizedEvent = event[0].toUpperCase() + event.slice(1); <ide> const reactName = 'on' + capitalizedEvent; <ide> function registerSimplePluginEventsAndSetTheirPriorities( <ide> } <ide> <ide> function setEventPriorities( <del> eventTypes: Array<DOMTopLevelEventType | string>, <add> eventTypes: Array<DOMEventName>, <ide> priority: EventPriority, <ide> ): void { <ide> for (let i = 0; i < eventTypes.length; i++) { <ide> function setEventPriorities( <ide> } <ide> <ide> export function getEventPriorityForPluginSystem( <del> topLevelType: TopLevelType, <add> domEventName: DOMEventName, <ide> ): EventPriority { <del> const priority = eventPriorities.get(topLevelType); <add> const priority = eventPriorities.get(domEventName); <ide> // Default to a ContinuousEvent. Note: we might <ide> // want to warn if we can't detect the priority <ide> // for the event. <ide> return priority === undefined ? ContinuousEvent : priority; <ide> } <ide> <ide> export function getEventPriorityForListenerSystem( <del> type: DOMTopLevelEventType, <add> type: DOMEventName, <ide> ): EventPriority { <ide> const priority = eventPriorities.get(type); <ide> if (priority !== undefined) { <ide><path>packages/react-dom/src/events/DOMPluginEventSystem.js <ide> * @flow <ide> */ <ide> <del>import type {TopLevelType, DOMTopLevelEventType} from './TopLevelEventTypes'; <add>import type {DOMEventName} from './DOMEventNames'; <ide> import { <ide> type EventSystemFlags, <ide> SHOULD_NOT_DEFER_CLICK_FOR_FB_SUPPORT_MODE, <ide> import { <ide> } from 'react-reconciler/src/ReactWorkTags'; <ide> <ide> import getEventTarget from './getEventTarget'; <del>import { <del> TOP_LOAD, <del> TOP_ABORT, <del> TOP_CANCEL, <del> TOP_INVALID, <del> TOP_SCROLL, <del> TOP_CLOSE, <del> TOP_CAN_PLAY, <del> TOP_CAN_PLAY_THROUGH, <del> TOP_DURATION_CHANGE, <del> TOP_EMPTIED, <del> TOP_ENCRYPTED, <del> TOP_ENDED, <del> TOP_ERROR, <del> TOP_WAITING, <del> TOP_VOLUME_CHANGE, <del> TOP_TIME_UPDATE, <del> TOP_SUSPEND, <del> TOP_STALLED, <del> TOP_SEEKING, <del> TOP_SEEKED, <del> TOP_PLAY, <del> TOP_PAUSE, <del> TOP_LOAD_START, <del> TOP_LOADED_DATA, <del> TOP_LOADED_METADATA, <del> TOP_RATE_CHANGE, <del> TOP_PROGRESS, <del> TOP_PLAYING, <del> TOP_CLICK, <del> TOP_SELECTION_CHANGE, <del> TOP_TOGGLE, <del> getRawEventName, <del>} from './DOMTopLevelEventTypes'; <ide> import { <ide> getClosestInstanceFromNode, <ide> getEventListenerMap, <ide> BeforeInputEventPlugin.registerEvents(); <ide> <ide> function extractEvents( <ide> dispatchQueue: DispatchQueue, <del> topLevelType: TopLevelType, <add> domEventName: DOMEventName, <ide> targetInst: null | Fiber, <ide> nativeEvent: AnyNativeEvent, <ide> nativeEventTarget: null | EventTarget, <ide> function extractEvents( <ide> // us to ship builds of React without the polyfilled plugins below. <ide> SimpleEventPlugin.extractEvents( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> function extractEvents( <ide> if (shouldProcessPolyfillPlugins) { <ide> EnterLeaveEventPlugin.extractEvents( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> function extractEvents( <ide> ); <ide> ChangeEventPlugin.extractEvents( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> function extractEvents( <ide> ); <ide> SelectEventPlugin.extractEvents( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> function extractEvents( <ide> ); <ide> BeforeInputEventPlugin.extractEvents( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> function extractEvents( <ide> } <ide> <ide> // List of events that need to be individually attached to media elements. <del>export const mediaEventTypes = [ <del> TOP_ABORT, <del> TOP_CAN_PLAY, <del> TOP_CAN_PLAY_THROUGH, <del> TOP_DURATION_CHANGE, <del> TOP_EMPTIED, <del> TOP_ENCRYPTED, <del> TOP_ENDED, <del> TOP_ERROR, <del> TOP_LOADED_DATA, <del> TOP_LOADED_METADATA, <del> TOP_LOAD_START, <del> TOP_PAUSE, <del> TOP_PLAY, <del> TOP_PLAYING, <del> TOP_PROGRESS, <del> TOP_RATE_CHANGE, <del> TOP_SEEKED, <del> TOP_SEEKING, <del> TOP_STALLED, <del> TOP_SUSPEND, <del> TOP_TIME_UPDATE, <del> TOP_VOLUME_CHANGE, <del> TOP_WAITING, <add>export const mediaEventTypes: Array<DOMEventName> = [ <add> 'abort', <add> 'canplay', <add> 'canplaythrough', <add> 'durationchange', <add> 'emptied', <add> 'encrypted', <add> 'ended', <add> 'error', <add> 'loadeddata', <add> 'loadedmetadata', <add> 'loadstart', <add> 'pause', <add> 'play', <add> 'playing', <add> 'progress', <add> 'ratechange', <add> 'seeked', <add> 'seeking', <add> 'stalled', <add> 'suspend', <add> 'timeupdate', <add> 'volumechange', <add> 'waiting', <ide> ]; <ide> <ide> // We should not delegate these events to the container, but rather <ide> // set them on the actual target element itself. This is primarily <ide> // because these events do not consistently bubble in the DOM. <del>export const nonDelegatedEvents: Set<DOMTopLevelEventType> = new Set([ <del> TOP_CANCEL, <del> TOP_CLOSE, <del> TOP_INVALID, <del> TOP_LOAD, <del> TOP_SCROLL, <del> TOP_TOGGLE, <add>export const nonDelegatedEvents: Set<DOMEventName> = new Set([ <add> 'cancel', <add> 'close', <add> 'invalid', <add> 'load', <add> 'scroll', <add> 'toggle', <ide> // In order to reduce bytes, we insert the above array of media events <ide> // into this Set. Note: the "error" event isn't an exclusive media event, <ide> // and can occur on other elements too. Rather than duplicate that event, <ide> export function processDispatchQueue( <ide> } <ide> <ide> function dispatchEventsForPlugins( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> nativeEvent: AnyNativeEvent, <ide> targetInst: null | Fiber, <ide> function dispatchEventsForPlugins( <ide> const dispatchQueue: DispatchQueue = []; <ide> extractEvents( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> function shouldUpgradeListener( <ide> } <ide> <ide> export function listenToNonDelegatedEvent( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> targetElement: Element, <ide> ): void { <ide> const isCapturePhaseListener = false; <ide> const listenerMap = getEventListenerMap(targetElement); <ide> const listenerMapKey = getListenerMapKey( <del> topLevelType, <add> domEventName, <ide> isCapturePhaseListener, <ide> ); <ide> const listenerEntry = ((listenerMap.get( <ide> export function listenToNonDelegatedEvent( <ide> if (listenerEntry === undefined) { <ide> const listener = addTrappedEventListener( <ide> targetElement, <del> topLevelType, <add> domEventName, <ide> PLUGIN_EVENT_SYSTEM | IS_NON_DELEGATED, <ide> isCapturePhaseListener, <ide> ); <ide> export function listenToNonDelegatedEvent( <ide> } <ide> <ide> export function listenToNativeEvent( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> isCapturePhaseListener: boolean, <ide> rootContainerElement: EventTarget, <ide> targetElement: Element | null, <ide> export function listenToNativeEvent( <ide> eventSystemFlags?: EventSystemFlags = PLUGIN_EVENT_SYSTEM, <ide> ): void { <ide> let target = rootContainerElement; <del> // TOP_SELECTION_CHANGE needs to be attached to the document <add> // selectionchange needs to be attached to the document <ide> // otherwise it won't capture incoming events that are only <ide> // triggered on the document directly. <del> if (topLevelType === TOP_SELECTION_CHANGE) { <add> if (domEventName === 'selectionchange') { <ide> target = (rootContainerElement: any).ownerDocument; <ide> } <ide> // If the event can be delegated (or is capture phase), we can <ide> export function listenToNativeEvent( <ide> if ( <ide> targetElement !== null && <ide> !isCapturePhaseListener && <del> nonDelegatedEvents.has(topLevelType) <add> nonDelegatedEvents.has(domEventName) <ide> ) { <ide> // For all non-delegated events, apart from scroll, we attach <ide> // their event listeners to the respective elements that their <ide> export function listenToNativeEvent( <ide> // TODO: ideally, we'd eventually apply the same logic to all <ide> // events from the nonDelegatedEvents list. Then we can remove <ide> // this special case and use the same logic for all events. <del> if (topLevelType !== TOP_SCROLL) { <add> if (domEventName !== 'scroll') { <ide> return; <ide> } <ide> eventSystemFlags |= IS_NON_DELEGATED; <ide> target = targetElement; <ide> } <ide> const listenerMap = getEventListenerMap(target); <ide> const listenerMapKey = getListenerMapKey( <del> topLevelType, <add> domEventName, <ide> isCapturePhaseListener, <ide> ); <ide> const listenerEntry = ((listenerMap.get( <ide> export function listenToNativeEvent( <ide> if (shouldUpgrade) { <ide> removeTrappedEventListener( <ide> target, <del> topLevelType, <add> domEventName, <ide> isCapturePhaseListener, <ide> ((listenerEntry: any): ElementListenerMapEntry).listener, <ide> ); <ide> export function listenToNativeEvent( <ide> } <ide> const listener = addTrappedEventListener( <ide> target, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> isCapturePhaseListener, <ide> false, <ide> export function listenToReactEvent( <ide> <ide> function addTrappedEventListener( <ide> targetContainer: EventTarget, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> isCapturePhaseListener: boolean, <ide> isDeferredListenerForLegacyFBSupport?: boolean, <ide> function addTrappedEventListener( <ide> ): any => void { <ide> let listener = createEventListenerWrapperWithPriority( <ide> targetContainer, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> listenerPriority, <ide> ); <ide> function addTrappedEventListener( <ide> ? (targetContainer: any).ownerDocument <ide> : targetContainer; <ide> <del> const rawEventName = getRawEventName(topLevelType); <del> <ide> let unsubscribeListener; <ide> // When legacyFBSupport is enabled, it's for when we <ide> // want to add a one time event listener to a container. <ide> function addTrappedEventListener( <ide> listener = function(...p) { <ide> removeEventListener( <ide> targetContainer, <del> rawEventName, <add> domEventName, <ide> unsubscribeListener, <ide> isCapturePhaseListener, <ide> ); <ide> function addTrappedEventListener( <ide> if (enableCreateEventHandleAPI && isPassiveListener !== undefined) { <ide> unsubscribeListener = addEventCaptureListenerWithPassiveFlag( <ide> targetContainer, <del> rawEventName, <add> domEventName, <ide> listener, <ide> isPassiveListener, <ide> ); <ide> } else { <ide> unsubscribeListener = addEventCaptureListener( <ide> targetContainer, <del> rawEventName, <add> domEventName, <ide> listener, <ide> ); <ide> } <ide> } else { <ide> if (enableCreateEventHandleAPI && isPassiveListener !== undefined) { <ide> unsubscribeListener = addEventBubbleListenerWithPassiveFlag( <ide> targetContainer, <del> rawEventName, <add> domEventName, <ide> listener, <ide> isPassiveListener, <ide> ); <ide> } else { <ide> unsubscribeListener = addEventBubbleListener( <ide> targetContainer, <del> rawEventName, <add> domEventName, <ide> listener, <ide> ); <ide> } <ide> function addTrappedEventListener( <ide> } <ide> <ide> function deferClickToDocumentForLegacyFBSupport( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> targetContainer: EventTarget, <ide> ): void { <ide> // We defer all click events with legacy FB support mode on. <ide> function deferClickToDocumentForLegacyFBSupport( <ide> const isDeferredListenerForLegacyFBSupport = true; <ide> addTrappedEventListener( <ide> targetContainer, <del> topLevelType, <add> domEventName, <ide> PLUGIN_EVENT_SYSTEM | IS_LEGACY_FB_SUPPORT_MODE, <ide> false, <ide> isDeferredListenerForLegacyFBSupport, <ide> function isMatchingRootContainer( <ide> } <ide> <ide> export function dispatchEventForPluginEventSystem( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> nativeEvent: AnyNativeEvent, <ide> targetInst: null | Fiber, <ide> export function dispatchEventForPluginEventSystem( <ide> // then we can defer the event to the "document", to allow <ide> // for legacy FB support, where the expected behavior was to <ide> // match React < 16 behavior of delegated clicks to the doc. <del> topLevelType === TOP_CLICK && <add> domEventName === 'click' && <ide> (eventSystemFlags & SHOULD_NOT_DEFER_CLICK_FOR_FB_SUPPORT_MODE) === 0 <ide> ) { <del> deferClickToDocumentForLegacyFBSupport(topLevelType, targetContainer); <add> deferClickToDocumentForLegacyFBSupport(domEventName, targetContainer); <ide> return; <ide> } <ide> if (targetInst !== null) { <ide> export function dispatchEventForPluginEventSystem( <ide> <ide> batchedEventUpdates(() => <ide> dispatchEventsForPlugins( <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> nativeEvent, <ide> ancestorInst, <ide> export function accumulateEventHandleNonManagedNodeListeners( <ide> const eventListeners = getEventHandlerListeners(currentTarget); <ide> if (eventListeners !== null) { <ide> const listenersArr = Array.from(eventListeners); <del> const targetType = ((event.type: any): DOMTopLevelEventType); <add> const targetType = ((event.type: any): DOMEventName); <ide> <ide> for (let i = 0; i < listenersArr.length; i++) { <ide> const listener = listenersArr[i]; <ide> export function accumulateEventHandleNonManagedNodeListeners( <ide> } <ide> } <ide> <del>export function addEventTypeToDispatchConfig(type: DOMTopLevelEventType): void { <add>export function addEventTypeToDispatchConfig(type: DOMEventName): void { <ide> const reactName = topLevelEventsToReactNames.get(type); <ide> // If we don't have a reactName, then we're dealing with <ide> // an event type that React does not know about (i.e. a custom event). <ide> export function addEventTypeToDispatchConfig(type: DOMTopLevelEventType): void { <ide> } <ide> <ide> export function getListenerMapKey( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> capture: boolean, <ide> ): string { <del> return `${getRawEventName(topLevelType)}__${capture ? 'capture' : 'bubble'}`; <add> return `${domEventName}__${capture ? 'capture' : 'bubble'}`; <ide> } <ide><path>packages/react-dom/src/events/DOMTopLevelEventTypes.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @flow <del> */ <del> <del>import type {DOMTopLevelEventType} from '../events/TopLevelEventTypes'; <del> <del>import { <del> unsafeCastStringToDOMTopLevelType, <del> unsafeCastDOMTopLevelTypeToString, <del>} from '../events/TopLevelEventTypes'; <del>import getVendorPrefixedEventName from './getVendorPrefixedEventName'; <del> <del>/** <del> * To identify top level events in ReactDOM, we use constants defined by this <del> * module. This is the only module that uses the unsafe* methods to express <del> * that the constants actually correspond to the browser event names. This lets <del> * us save some bundle size by avoiding a top level type -> event name map. <del> * The rest of ReactDOM code should import top level types from this file. <del> */ <del>export const TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort'); <del>export const TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType( <del> getVendorPrefixedEventName('animationend'), <del>); <del>export const TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType( <del> getVendorPrefixedEventName('animationiteration'), <del>); <del>export const TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType( <del> getVendorPrefixedEventName('animationstart'), <del>); <del>export const TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay'); <del>export const TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType( <del> 'canplaythrough', <del>); <del>export const TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel'); <del>export const TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change'); <del>export const TOP_CLICK = unsafeCastStringToDOMTopLevelType('click'); <del>export const TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close'); <del>export const TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType( <del> 'compositionend', <del>); <del>export const TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType( <del> 'compositionstart', <del>); <del>export const TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType( <del> 'compositionupdate', <del>); <del>export const TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType( <del> 'contextmenu', <del>); <del>export const TOP_COPY = unsafeCastStringToDOMTopLevelType('copy'); <del>export const TOP_CUT = unsafeCastStringToDOMTopLevelType('cut'); <del>export const TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick'); <del>export const TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick'); <del>export const TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag'); <del>export const TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend'); <del>export const TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter'); <del>export const TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit'); <del>export const TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave'); <del>export const TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover'); <del>export const TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart'); <del>export const TOP_DROP = unsafeCastStringToDOMTopLevelType('drop'); <del>export const TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType( <del> 'durationchange', <del>); <del>export const TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied'); <del>export const TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted'); <del>export const TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended'); <del>export const TOP_ERROR = unsafeCastStringToDOMTopLevelType('error'); <del>export const TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType( <del> 'gotpointercapture', <del>); <del>export const TOP_INPUT = unsafeCastStringToDOMTopLevelType('input'); <del>export const TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid'); <del>export const TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown'); <del>export const TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress'); <del>export const TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup'); <del>export const TOP_LOAD = unsafeCastStringToDOMTopLevelType('load'); <del>export const TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart'); <del>export const TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata'); <del>export const TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType( <del> 'loadedmetadata', <del>); <del>export const TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType( <del> 'lostpointercapture', <del>); <del>export const TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown'); <del>export const TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove'); <del>export const TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout'); <del>export const TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover'); <del>export const TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup'); <del>export const TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste'); <del>export const TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause'); <del>export const TOP_PLAY = unsafeCastStringToDOMTopLevelType('play'); <del>export const TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing'); <del>export const TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType( <del> 'pointercancel', <del>); <del>export const TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType( <del> 'pointerdown', <del>); <del>export const TOP_POINTER_ENTER = unsafeCastStringToDOMTopLevelType( <del> 'pointerenter', <del>); <del>export const TOP_POINTER_LEAVE = unsafeCastStringToDOMTopLevelType( <del> 'pointerleave', <del>); <del>export const TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType( <del> 'pointermove', <del>); <del>export const TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout'); <del>export const TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType( <del> 'pointerover', <del>); <del>export const TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup'); <del>export const TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress'); <del>export const TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange'); <del>export const TOP_RESET = unsafeCastStringToDOMTopLevelType('reset'); <del>export const TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll'); <del>export const TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked'); <del>export const TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking'); <del>export const TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType( <del> 'selectionchange', <del>); <del>export const TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled'); <del>export const TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit'); <del>export const TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend'); <del>export const TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput'); <del>export const TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate'); <del>export const TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle'); <del>export const TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType( <del> 'touchcancel', <del>); <del>export const TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend'); <del>export const TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove'); <del>export const TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart'); <del>export const TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType( <del> getVendorPrefixedEventName('transitionend'), <del>); <del>export const TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType( <del> 'volumechange', <del>); <del>export const TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting'); <del>export const TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); <del> <del>export const TOP_AFTER_BLUR = unsafeCastStringToDOMTopLevelType('afterblur'); <del>export const TOP_BEFORE_BLUR = unsafeCastStringToDOMTopLevelType('beforeblur'); <del> <del>export const TOP_FOCUS_IN = unsafeCastStringToDOMTopLevelType('focusin'); <del>export const TOP_FOCUS_OUT = unsafeCastStringToDOMTopLevelType('focusout'); <del> <del>export function getRawEventName(topLevelType: DOMTopLevelEventType): string { <del> return unsafeCastDOMTopLevelTypeToString(topLevelType); <del>} <ide><path>packages/react-dom/src/events/DeprecatedDOMEventResponderSystem.js <ide> import type { <ide> ReactDOMResponderContext, <ide> ReactDOMResponderEvent, <ide> } from '../shared/ReactDOMTypes'; <del>import type {DOMTopLevelEventType} from '../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../events/DOMEventNames'; <ide> import { <ide> batchedEventUpdates, <ide> discreteUpdates, <ide> import {getClosestInstanceFromNode} from '../client/ReactDOMComponentTree'; <ide> import {enqueueStateRestore} from './ReactDOMControlledComponent'; <ide> import {createEventListenerWrapper} from './ReactDOMEventListener'; <ide> import {passiveBrowserEventsSupported} from './checkPassiveEvents'; <del>import {getRawEventName} from './DOMTopLevelEventTypes'; <ide> import { <ide> addEventCaptureListener, <ide> addEventCaptureListenerWithPassiveFlag, <ide> export function setListenToResponderEventTypes( <ide> } <ide> <ide> const rootEventTypesToEventResponderInstances: Map< <del> DOMTopLevelEventType | string, <add> DOMEventName | string, <ide> Set<ReactDOMEventResponderInstance>, <ide> > = new Map(); <ide> <ide> function getActiveDocument(): Document { <ide> } <ide> <ide> function createDOMResponderEvent( <del> topLevelType: string, <add> domEventName: string, <ide> nativeEvent: AnyNativeEvent, <ide> nativeEventTarget: Element | Document, <ide> passive: boolean, <ide> function createDOMResponderEvent( <ide> passive, <ide> pointerType: eventPointerType, <ide> target: nativeEventTarget, <del> type: topLevelType, <add> type: domEventName, <ide> }; <ide> } <ide> <ide> function validateResponderTargetEventTypes( <ide> } <ide> <ide> function traverseAndHandleEventResponderInstances( <del> topLevelType: string, <add> domEventName: string, <ide> targetFiber: null | Fiber, <ide> nativeEvent: AnyNativeEvent, <ide> nativeEventTarget: Document | Element, <ide> function traverseAndHandleEventResponderInstances( <ide> <ide> const visitedResponders = new Set(); <ide> const responderEvent = createDOMResponderEvent( <del> topLevelType, <add> domEventName, <ide> nativeEvent, <ide> nativeEventTarget, <ide> isPassiveEvent, <ide> function traverseAndHandleEventResponderInstances( <ide> if ( <ide> !visitedResponders.has(responder) && <ide> validateResponderTargetEventTypes( <del> topLevelType, <add> domEventName, <ide> responder, <ide> isPassive, <ide> ) && <ide> function traverseAndHandleEventResponderInstances( <ide> node = node.return; <ide> } <ide> // Root phase <del> const passive = rootEventTypesToEventResponderInstances.get(topLevelType); <add> const passive = rootEventTypesToEventResponderInstances.get(domEventName); <ide> const rootEventResponderInstances = []; <ide> if (passive !== undefined) { <ide> rootEventResponderInstances.push(...Array.from(passive)); <ide> } <ide> if (!isPassive) { <ide> const active = rootEventTypesToEventResponderInstances.get( <del> topLevelType + '_active', <add> domEventName + '_active', <ide> ); <ide> if (active !== undefined) { <ide> rootEventResponderInstances.push(...Array.from(active)); <ide> function validateResponderContext(): void { <ide> } <ide> <ide> export function DEPRECATED_dispatchEventForResponderEventSystem( <del> topLevelType: string, <add> domEventName: string, <ide> targetFiber: null | Fiber, <ide> nativeEvent: AnyNativeEvent, <ide> nativeEventTarget: Document | Element, <ide> export function DEPRECATED_dispatchEventForResponderEventSystem( <ide> try { <ide> batchedEventUpdates(() => { <ide> traverseAndHandleEventResponderInstances( <del> topLevelType, <add> domEventName, <ide> targetFiber, <ide> nativeEvent, <ide> nativeEventTarget, <ide> function DEPRECATED_registerRootEventType( <ide> <ide> export function addResponderEventSystemEvent( <ide> document: Document, <del> topLevelType: string, <add> domEventName: string, <ide> passive: boolean, <ide> ): any => void { <ide> let eventFlags = RESPONDER_EVENT_SYSTEM; <ide> export function addResponderEventSystemEvent( <ide> // Check if interactive and wrap in discreteUpdates <ide> const listener = createEventListenerWrapper( <ide> document, <del> ((topLevelType: any): DOMTopLevelEventType), <add> ((domEventName: any): DOMEventName), <ide> eventFlags, <ide> ); <ide> if (passiveBrowserEventsSupported) { <ide> return addEventCaptureListenerWithPassiveFlag( <ide> document, <del> topLevelType, <add> domEventName, <ide> listener, <ide> passive, <ide> ); <ide> } else { <del> return addEventCaptureListener(document, topLevelType, listener); <add> return addEventCaptureListener(document, domEventName, listener); <ide> } <ide> } <ide> <ide> export function removeTrappedEventListener( <ide> targetContainer: EventTarget, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> capture: boolean, <ide> listener: any => void, <ide> ): void { <del> const rawEventName = getRawEventName(topLevelType); <del> removeEventListener(targetContainer, rawEventName, listener, capture); <add> removeEventListener(targetContainer, domEventName, listener, capture); <ide> } <ide><path>packages/react-dom/src/events/EventRegistry.js <ide> * @flow <ide> */ <ide> <del>import type {TopLevelType} from './TopLevelEventTypes'; <add>import type {DOMEventName} from './DOMEventNames'; <ide> <ide> /** <ide> * Mapping from registration name to event name <ide> export const possibleRegistrationNames = __DEV__ ? {} : (null: any); <ide> <ide> export function registerTwoPhaseEvent( <ide> registrationName: string, <del> dependencies: ?Array<TopLevelType>, <add> dependencies: ?Array<DOMEventName>, <ide> ): void { <ide> registerDirectEvent(registrationName, dependencies); <ide> registerDirectEvent(registrationName + 'Capture', dependencies); <ide> } <ide> <ide> export function registerDirectEvent( <ide> registrationName: string, <del> dependencies: ?Array<TopLevelType>, <add> dependencies: ?Array<DOMEventName>, <ide> ) { <ide> if (__DEV__) { <ide> if (registrationNameDependencies[registrationName]) { <ide><path>packages/react-dom/src/events/ReactDOMEventListener.js <ide> import type {AnyNativeEvent} from '../events/PluginModuleType'; <ide> import type {EventPriority} from 'shared/ReactTypes'; <ide> import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; <ide> import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig'; <del>import type {DOMTopLevelEventType} from '../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../events/DOMEventNames'; <ide> <ide> // Intentionally not named imports because Rollup would use dynamic dispatch for <ide> // CommonJS interop named imports. <ide> export function isEnabled() { <ide> <ide> export function createEventListenerWrapper( <ide> targetContainer: EventTarget, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> ): Function { <ide> return dispatchEvent.bind( <ide> null, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> ); <ide> } <ide> <ide> export function createEventListenerWrapperWithPriority( <ide> targetContainer: EventTarget, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> priority?: EventPriority, <ide> ): Function { <ide> const eventPriority = <ide> priority === undefined <del> ? getEventPriorityForPluginSystem(topLevelType) <add> ? getEventPriorityForPluginSystem(domEventName) <ide> : priority; <ide> let listenerWrapper; <ide> switch (eventPriority) { <ide> export function createEventListenerWrapperWithPriority( <ide> } <ide> return listenerWrapper.bind( <ide> null, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> ); <ide> } <ide> <ide> function dispatchDiscreteEvent( <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> container, <ide> nativeEvent, <ide> function dispatchDiscreteEvent( <ide> } <ide> discreteUpdates( <ide> dispatchEvent, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> container, <ide> nativeEvent, <ide> ); <ide> } <ide> <ide> function dispatchUserBlockingUpdate( <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> container, <ide> nativeEvent, <ide> function dispatchUserBlockingUpdate( <ide> UserBlockingPriority, <ide> dispatchEvent.bind( <ide> null, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> container, <ide> nativeEvent, <ide> function dispatchUserBlockingUpdate( <ide> } <ide> <ide> export function dispatchEvent( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> targetContainer: EventTarget, <ide> nativeEvent: AnyNativeEvent, <ide> ): void { <ide> if (!_enabled) { <ide> return; <ide> } <del> if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) { <add> if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(domEventName)) { <ide> // If we already have a queue of discrete events, and this is another discrete <ide> // event, then we can't dispatch it regardless of its target, since they <ide> // need to dispatch in order. <ide> queueDiscreteEvent( <ide> null, // Flags that we're not actually blocked on anything as far as we know. <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> nativeEvent, <ide> export function dispatchEvent( <ide> } <ide> <ide> const blockedOn = attemptToDispatchEvent( <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> nativeEvent, <ide> ); <ide> <ide> if (blockedOn === null) { <ide> // We successfully dispatched this event. <del> clearIfContinuousEvent(topLevelType, nativeEvent); <add> clearIfContinuousEvent(domEventName, nativeEvent); <ide> return; <ide> } <ide> <del> if (isReplayableDiscreteEvent(topLevelType)) { <add> if (isReplayableDiscreteEvent(domEventName)) { <ide> // This this to be replayed later once the target is available. <ide> queueDiscreteEvent( <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> nativeEvent, <ide> export function dispatchEvent( <ide> if ( <ide> queueIfContinuousEvent( <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> nativeEvent, <ide> export function dispatchEvent( <ide> <ide> // We need to clear only if we didn't queue because <ide> // queueing is accummulative. <del> clearIfContinuousEvent(topLevelType, nativeEvent); <add> clearIfContinuousEvent(domEventName, nativeEvent); <ide> <ide> // This is not replayable so we'll invoke it but without a target, <ide> // in case the event system needs to trace it. <ide> if (enableDeprecatedFlareAPI) { <ide> if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) { <ide> dispatchEventForPluginEventSystem( <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> nativeEvent, <ide> null, <ide> export function dispatchEvent( <ide> if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) { <ide> // React Flare event system <ide> DEPRECATED_dispatchEventForResponderEventSystem( <del> (topLevelType: any), <add> (domEventName: any), <ide> null, <ide> nativeEvent, <ide> getEventTarget(nativeEvent), <ide> export function dispatchEvent( <ide> } <ide> } else { <ide> dispatchEventForPluginEventSystem( <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> nativeEvent, <ide> null, <ide> export function dispatchEvent( <ide> <ide> // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked. <ide> export function attemptToDispatchEvent( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> targetContainer: EventTarget, <ide> nativeEvent: AnyNativeEvent, <ide> export function attemptToDispatchEvent( <ide> if (enableDeprecatedFlareAPI) { <ide> if (eventSystemFlags & PLUGIN_EVENT_SYSTEM) { <ide> dispatchEventForPluginEventSystem( <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> nativeEvent, <ide> targetInst, <ide> export function attemptToDispatchEvent( <ide> if (eventSystemFlags & RESPONDER_EVENT_SYSTEM) { <ide> // React Flare event system <ide> DEPRECATED_dispatchEventForResponderEventSystem( <del> (topLevelType: any), <add> (domEventName: any), <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> export function attemptToDispatchEvent( <ide> } <ide> } else { <ide> dispatchEventForPluginEventSystem( <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> nativeEvent, <ide> targetInst, <ide><path>packages/react-dom/src/events/ReactDOMEventReplaying.js <ide> <ide> import type {AnyNativeEvent} from '../events/PluginModuleType'; <ide> import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig'; <del>import type {DOMTopLevelEventType} from '../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../events/DOMEventNames'; <ide> import type {ElementListenerMap} from '../client/ReactDOMComponentTree'; <ide> import type {EventSystemFlags} from './EventSystemFlags'; <ide> import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; <ide> import { <ide> getClosestInstanceFromNode, <ide> getEventListenerMap, <ide> } from '../client/ReactDOMComponentTree'; <del>import {unsafeCastDOMTopLevelTypeToString} from '../events/TopLevelEventTypes'; <ide> import {HostRoot, SuspenseComponent} from 'react-reconciler/src/ReactWorkTags'; <ide> <ide> let attemptSynchronousHydration: (fiber: Object) => void; <ide> type PointerEvent = Event & { <ide> ... <ide> }; <ide> <del>import { <del> TOP_MOUSE_DOWN, <del> TOP_MOUSE_UP, <del> TOP_TOUCH_CANCEL, <del> TOP_TOUCH_END, <del> TOP_TOUCH_START, <del> TOP_AUX_CLICK, <del> TOP_DOUBLE_CLICK, <del> TOP_POINTER_CANCEL, <del> TOP_POINTER_DOWN, <del> TOP_POINTER_UP, <del> TOP_DRAG_END, <del> TOP_DRAG_START, <del> TOP_DROP, <del> TOP_COMPOSITION_END, <del> TOP_COMPOSITION_START, <del> TOP_KEY_DOWN, <del> TOP_KEY_PRESS, <del> TOP_KEY_UP, <del> TOP_INPUT, <del> TOP_TEXT_INPUT, <del> TOP_COPY, <del> TOP_CUT, <del> TOP_PASTE, <del> TOP_CLICK, <del> TOP_CHANGE, <del> TOP_CONTEXT_MENU, <del> TOP_RESET, <del> TOP_SUBMIT, <del> TOP_DRAG_ENTER, <del> TOP_DRAG_LEAVE, <del> TOP_MOUSE_OVER, <del> TOP_MOUSE_OUT, <del> TOP_POINTER_OVER, <del> TOP_POINTER_OUT, <del> TOP_GOT_POINTER_CAPTURE, <del> TOP_LOST_POINTER_CAPTURE, <del> TOP_FOCUS_IN, <del> TOP_FOCUS_OUT, <del>} from './DOMTopLevelEventTypes'; <ide> import {IS_REPLAYED} from './EventSystemFlags'; <ide> import {listenToNativeEvent} from './DOMPluginEventSystem'; <ide> import {addResponderEventSystemEvent} from './DeprecatedDOMEventResponderSystem'; <ide> <ide> type QueuedReplayableEvent = {| <ide> blockedOn: null | Container | SuspenseInstance, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> nativeEvent: AnyNativeEvent, <ide> targetContainers: Array<EventTarget>, <ide> export function hasQueuedContinuousEvents(): boolean { <ide> return hasAnyQueuedContinuousEvents; <ide> } <ide> <del>const discreteReplayableEvents = [ <del> TOP_MOUSE_DOWN, <del> TOP_MOUSE_UP, <del> TOP_TOUCH_CANCEL, <del> TOP_TOUCH_END, <del> TOP_TOUCH_START, <del> TOP_AUX_CLICK, <del> TOP_DOUBLE_CLICK, <del> TOP_POINTER_CANCEL, <del> TOP_POINTER_DOWN, <del> TOP_POINTER_UP, <del> TOP_DRAG_END, <del> TOP_DRAG_START, <del> TOP_DROP, <del> TOP_COMPOSITION_END, <del> TOP_COMPOSITION_START, <del> TOP_KEY_DOWN, <del> TOP_KEY_PRESS, <del> TOP_KEY_UP, <del> TOP_INPUT, <del> TOP_TEXT_INPUT, <del> TOP_COPY, <del> TOP_CUT, <del> TOP_PASTE, <del> TOP_CLICK, <del> TOP_CHANGE, <del> TOP_CONTEXT_MENU, <del> TOP_RESET, <del> TOP_SUBMIT, <add>const discreteReplayableEvents: Array<DOMEventName> = [ <add> 'mousedown', <add> 'mouseup', <add> 'touchcancel', <add> 'touchend', <add> 'touchstart', <add> 'auxclick', <add> 'dblclick', <add> 'pointercancel', <add> 'pointerdown', <add> 'pointerup', <add> 'dragend', <add> 'dragstart', <add> 'drop', <add> 'compositionend', <add> 'compositionstart', <add> 'keydown', <add> 'keypress', <add> 'keyup', <add> 'input', <add> 'textInput', // Intentionally camelCase <add> 'copy', <add> 'cut', <add> 'paste', <add> 'click', <add> 'change', <add> 'contextmenu', <add> 'reset', <add> 'submit', <ide> ]; <ide> <del>const continuousReplayableEvents = [ <del> TOP_DRAG_ENTER, <del> TOP_DRAG_LEAVE, <del> TOP_FOCUS_IN, <del> TOP_FOCUS_OUT, <del> TOP_MOUSE_OVER, <del> TOP_MOUSE_OUT, <del> TOP_POINTER_OVER, <del> TOP_POINTER_OUT, <del> TOP_GOT_POINTER_CAPTURE, <del> TOP_LOST_POINTER_CAPTURE, <add>const continuousReplayableEvents: Array<DOMEventName> = [ <add> 'dragenter', <add> 'dragleave', <add> 'focusin', <add> 'focusout', <add> 'mouseover', <add> 'mouseout', <add> 'pointerover', <add> 'pointerout', <add> 'gotpointercapture', <add> 'lostpointercapture', <ide> ]; <ide> <del>export function isReplayableDiscreteEvent( <del> eventType: DOMTopLevelEventType, <del>): boolean { <add>export function isReplayableDiscreteEvent(eventType: DOMEventName): boolean { <ide> return discreteReplayableEvents.indexOf(eventType) > -1; <ide> } <ide> <ide> function trapReplayableEventForContainer( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> container: Container, <ide> ) { <del> listenToNativeEvent(topLevelType, false, ((container: any): Element), null); <add> listenToNativeEvent(domEventName, false, ((container: any): Element), null); <ide> } <ide> <ide> function trapReplayableEventForDocument( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> document: Document, <ide> listenerMap: ElementListenerMap, <ide> ) { <ide> if (enableDeprecatedFlareAPI) { <ide> // Trap events for the responder system. <del> const topLevelTypeString = unsafeCastDOMTopLevelTypeToString(topLevelType); <ide> // TODO: Ideally we shouldn't need these to be active but <ide> // if we only have a passive listener, we at least need it <ide> // to still pretend to be active so that Flare gets those <ide> // events. <del> const activeEventKey = topLevelTypeString + '_active'; <add> const activeEventKey = domEventName + '_active'; <ide> if (!listenerMap.has(activeEventKey)) { <ide> const listener = addResponderEventSystemEvent( <ide> document, <del> topLevelTypeString, <add> domEventName, <ide> false, <ide> ); <ide> listenerMap.set(activeEventKey, {passive: false, listener}); <ide> export function eagerlyTrapReplayableEvents( <ide> ) { <ide> const listenerMapForDoc = getEventListenerMap(document); <ide> // Discrete <del> discreteReplayableEvents.forEach(topLevelType => { <del> trapReplayableEventForContainer(topLevelType, container); <del> trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc); <add> discreteReplayableEvents.forEach(domEventName => { <add> trapReplayableEventForContainer(domEventName, container); <add> trapReplayableEventForDocument(domEventName, document, listenerMapForDoc); <ide> }); <ide> // Continuous <del> continuousReplayableEvents.forEach(topLevelType => { <del> trapReplayableEventForContainer(topLevelType, container); <del> trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc); <add> continuousReplayableEvents.forEach(domEventName => { <add> trapReplayableEventForContainer(domEventName, container); <add> trapReplayableEventForDocument(domEventName, document, listenerMapForDoc); <ide> }); <ide> } <ide> <ide> function createQueuedReplayableEvent( <ide> blockedOn: null | Container | SuspenseInstance, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> targetContainer: EventTarget, <ide> nativeEvent: AnyNativeEvent, <ide> ): QueuedReplayableEvent { <ide> return { <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags: eventSystemFlags | IS_REPLAYED, <ide> nativeEvent, <ide> targetContainers: [targetContainer], <ide> function createQueuedReplayableEvent( <ide> <ide> export function queueDiscreteEvent( <ide> blockedOn: null | Container | SuspenseInstance, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> targetContainer: EventTarget, <ide> nativeEvent: AnyNativeEvent, <ide> ): void { <ide> const queuedEvent = createQueuedReplayableEvent( <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> nativeEvent, <ide> export function queueDiscreteEvent( <ide> <ide> // Resets the replaying for this type of continuous event to no event. <ide> export function clearIfContinuousEvent( <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> nativeEvent: AnyNativeEvent, <ide> ): void { <del> switch (topLevelType) { <del> case TOP_FOCUS_IN: <del> case TOP_FOCUS_OUT: <add> switch (domEventName) { <add> case 'focusin': <add> case 'focusout': <ide> queuedFocus = null; <ide> break; <del> case TOP_DRAG_ENTER: <del> case TOP_DRAG_LEAVE: <add> case 'dragenter': <add> case 'dragleave': <ide> queuedDrag = null; <ide> break; <del> case TOP_MOUSE_OVER: <del> case TOP_MOUSE_OUT: <add> case 'mouseover': <add> case 'mouseout': <ide> queuedMouse = null; <ide> break; <del> case TOP_POINTER_OVER: <del> case TOP_POINTER_OUT: { <add> case 'pointerover': <add> case 'pointerout': { <ide> const pointerId = ((nativeEvent: any): PointerEvent).pointerId; <ide> queuedPointers.delete(pointerId); <ide> break; <ide> } <del> case TOP_GOT_POINTER_CAPTURE: <del> case TOP_LOST_POINTER_CAPTURE: { <add> case 'gotpointercapture': <add> case 'lostpointercapture': { <ide> const pointerId = ((nativeEvent: any): PointerEvent).pointerId; <ide> queuedPointerCaptures.delete(pointerId); <ide> break; <ide> export function clearIfContinuousEvent( <ide> function accumulateOrCreateContinuousQueuedReplayableEvent( <ide> existingQueuedEvent: null | QueuedReplayableEvent, <ide> blockedOn: null | Container | SuspenseInstance, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> targetContainer: EventTarget, <ide> nativeEvent: AnyNativeEvent, <ide> function accumulateOrCreateContinuousQueuedReplayableEvent( <ide> ) { <ide> const queuedEvent = createQueuedReplayableEvent( <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> nativeEvent, <ide> function accumulateOrCreateContinuousQueuedReplayableEvent( <ide> <ide> export function queueIfContinuousEvent( <ide> blockedOn: null | Container | SuspenseInstance, <del> topLevelType: DOMTopLevelEventType, <add> domEventName: DOMEventName, <ide> eventSystemFlags: EventSystemFlags, <ide> targetContainer: EventTarget, <ide> nativeEvent: AnyNativeEvent, <ide> ): boolean { <ide> // These set relatedTarget to null because the replayed event will be treated as if we <ide> // moved from outside the window (no target) onto the target once it hydrates. <ide> // Instead of mutating we could clone the event. <del> switch (topLevelType) { <del> case TOP_FOCUS_IN: { <add> switch (domEventName) { <add> case 'focusin': { <ide> const focusEvent = ((nativeEvent: any): FocusEvent); <ide> queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent( <ide> queuedFocus, <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> focusEvent, <ide> ); <ide> return true; <ide> } <del> case TOP_DRAG_ENTER: { <add> case 'dragenter': { <ide> const dragEvent = ((nativeEvent: any): DragEvent); <ide> queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent( <ide> queuedDrag, <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> dragEvent, <ide> ); <ide> return true; <ide> } <del> case TOP_MOUSE_OVER: { <add> case 'mouseover': { <ide> const mouseEvent = ((nativeEvent: any): MouseEvent); <ide> queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent( <ide> queuedMouse, <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> mouseEvent, <ide> ); <ide> return true; <ide> } <del> case TOP_POINTER_OVER: { <add> case 'pointerover': { <ide> const pointerEvent = ((nativeEvent: any): PointerEvent); <ide> const pointerId = pointerEvent.pointerId; <ide> queuedPointers.set( <ide> pointerId, <ide> accumulateOrCreateContinuousQueuedReplayableEvent( <ide> queuedPointers.get(pointerId) || null, <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> pointerEvent, <ide> ), <ide> ); <ide> return true; <ide> } <del> case TOP_GOT_POINTER_CAPTURE: { <add> case 'gotpointercapture': { <ide> const pointerEvent = ((nativeEvent: any): PointerEvent); <ide> const pointerId = pointerEvent.pointerId; <ide> queuedPointerCaptures.set( <ide> pointerId, <ide> accumulateOrCreateContinuousQueuedReplayableEvent( <ide> queuedPointerCaptures.get(pointerId) || null, <ide> blockedOn, <del> topLevelType, <add> domEventName, <ide> eventSystemFlags, <ide> targetContainer, <ide> pointerEvent, <ide> function attemptReplayContinuousQueuedEvent( <ide> while (targetContainers.length > 0) { <ide> const targetContainer = targetContainers[0]; <ide> const nextBlockedOn = attemptToDispatchEvent( <del> queuedEvent.topLevelType, <add> queuedEvent.domEventName, <ide> queuedEvent.eventSystemFlags, <ide> targetContainer, <ide> queuedEvent.nativeEvent, <ide> function replayUnblockedEvents() { <ide> while (targetContainers.length > 0) { <ide> const targetContainer = targetContainers[0]; <ide> const nextBlockedOn = attemptToDispatchEvent( <del> nextDiscreteEvent.topLevelType, <add> nextDiscreteEvent.domEventName, <ide> nextDiscreteEvent.eventSystemFlags, <ide> targetContainer, <ide> nextDiscreteEvent.nativeEvent, <ide><path>packages/react-dom/src/events/ReactSyntheticEventType.js <ide> <ide> import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; <ide> import type {EventPriority} from 'shared/ReactTypes'; <del>import type {TopLevelType} from './TopLevelEventTypes'; <add>import type {DOMEventName} from './DOMEventNames'; <ide> <ide> export type DispatchConfig = {| <del> dependencies?: Array<TopLevelType>, <add> dependencies?: Array<DOMEventName>, <ide> phasedRegistrationNames: {| <ide> bubbled: null | string, <ide> captured: null | string, <ide><path>packages/react-dom/src/events/TopLevelEventTypes.js <ide> * @flow <ide> */ <ide> <del>export opaque type DOMTopLevelEventType = string; <del> <del>// Do not use the below two methods directly! <del>// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM. <del>// (It is the only module that is allowed to access these methods.) <del> <del>export function unsafeCastStringToDOMTopLevelType( <del> topLevelType: string, <del>): DOMTopLevelEventType { <del> return topLevelType; <del>} <del> <del>export function unsafeCastDOMTopLevelTypeToString( <del> topLevelType: DOMTopLevelEventType, <del>): string { <del> return topLevelType; <del>} <del> <del>export type TopLevelType = DOMTopLevelEventType; <add>export type TopLevelType = <add> | 'abort' <add> // Dynamic and vendor-prefixed at the usage site: <add> // 'animationiteration' | <add> // 'animationend | <add> // 'animationstart' | <add> | 'canplay' <add> | 'canplaythrough' <add> | 'cancel' <add> | 'change' <add> | 'click' <add> | 'close' <add> | 'compositionend' <add> | 'compositionstart' <add> | 'compositionupdate' <add> | 'contextmenu' <add> | 'copy' <add> | 'cut' <add> | 'dblclick' <add> | 'auxclick' <add> | 'drag' <add> | 'dragend' <add> | 'dragenter' <add> | 'dragexit' <add> | 'dragleave' <add> | 'dragover' <add> | 'dragstart' <add> | 'drop' <add> | 'durationchange' <add> | 'emptied' <add> | 'encrypted' <add> | 'ended' <add> | 'error' <add> | 'gotpointercapture' <add> | 'input' <add> | 'invalid' <add> | 'keydown' <add> | 'keypress' <add> | 'keyup' <add> | 'load' <add> | 'loadstart' <add> | 'loadeddata' <add> | 'loadedmetadata' <add> | 'lostpointercapture' <add> | 'mousedown' <add> | 'mousemove' <add> | 'mouseout' <add> | 'mouseover' <add> | 'mouseup' <add> | 'paste' <add> | 'pause' <add> | 'play' <add> | 'playing' <add> | 'pointercancel' <add> | 'pointerdown' <add> | 'pointerenter' <add> | 'pointerleave' <add> | 'pointermove' <add> | 'pointerout' <add> | 'pointerover' <add> | 'pointerup' <add> | 'progress' <add> | 'ratechange' <add> | 'reset' <add> | 'scroll' <add> | 'seeked' <add> | 'seeking' <add> | 'selectionchange' <add> | 'stalled' <add> | 'submit' <add> | 'suspend' <add> | 'textInput' <add> | 'timeupdate' <add> | 'toggle' <add> | 'touchcancel' <add> | 'touchend' <add> | 'touchmove' <add> | 'touchstart' <add> // Dynamic and vendor-prefixed at the usage site: <add> // 'transitionend' | <add> | 'volumechange' <add> | 'waiting' <add> | 'wheel' <add> | 'afterblur' <add> | 'beforeblur' <add> | 'focusin' <add> | 'focusout'; <ide><path>packages/react-dom/src/events/plugins/BeforeInputEventPlugin.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <ide> */ <ide> <del>import type {TopLevelType} from '../../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../../events/DOMEventNames'; <add>import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; <add>import type {AnyNativeEvent} from '../../events/PluginModuleType'; <add>import type {DispatchQueue} from '../DOMPluginEventSystem'; <add>import type {EventSystemFlags} from '../EventSystemFlags'; <ide> <ide> import {canUseDOM} from 'shared/ExecutionEnvironment'; <ide> <ide> import {registerTwoPhaseEvent} from '../EventRegistry'; <del>import { <del> TOP_FOCUS_OUT, <del> TOP_COMPOSITION_START, <del> TOP_COMPOSITION_END, <del> TOP_COMPOSITION_UPDATE, <del> TOP_KEY_DOWN, <del> TOP_KEY_PRESS, <del> TOP_KEY_UP, <del> TOP_MOUSE_DOWN, <del> TOP_TEXT_INPUT, <del> TOP_PASTE, <del>} from '../DOMTopLevelEventTypes'; <ide> import { <ide> getData as FallbackCompositionStateGetData, <ide> initialize as FallbackCompositionStateInitialize, <ide> const SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); <ide> <ide> function registerEvents() { <ide> registerTwoPhaseEvent('onBeforeInput', [ <del> TOP_COMPOSITION_END, <del> TOP_KEY_PRESS, <del> TOP_TEXT_INPUT, <del> TOP_PASTE, <add> 'compositionend', <add> 'keypress', <add> 'textInput', <add> 'paste', <ide> ]); <ide> registerTwoPhaseEvent('onCompositionEnd', [ <del> TOP_COMPOSITION_END, <del> TOP_FOCUS_OUT, <del> TOP_KEY_DOWN, <del> TOP_KEY_PRESS, <del> TOP_KEY_UP, <del> TOP_MOUSE_DOWN, <add> 'compositionend', <add> 'focusout', <add> 'keydown', <add> 'keypress', <add> 'keyup', <add> 'mousedown', <ide> ]); <ide> registerTwoPhaseEvent('onCompositionStart', [ <del> TOP_COMPOSITION_START, <del> TOP_FOCUS_OUT, <del> TOP_KEY_DOWN, <del> TOP_KEY_PRESS, <del> TOP_KEY_UP, <del> TOP_MOUSE_DOWN, <add> 'compositionstart', <add> 'focusout', <add> 'keydown', <add> 'keypress', <add> 'keyup', <add> 'mousedown', <ide> ]); <ide> registerTwoPhaseEvent('onCompositionUpdate', [ <del> TOP_COMPOSITION_UPDATE, <del> TOP_FOCUS_OUT, <del> TOP_KEY_DOWN, <del> TOP_KEY_PRESS, <del> TOP_KEY_UP, <del> TOP_MOUSE_DOWN, <add> 'compositionupdate', <add> 'focusout', <add> 'keydown', <add> 'keypress', <add> 'keyup', <add> 'mousedown', <ide> ]); <ide> } <ide> <ide> let hasSpaceKeypress = false; <ide> * This is required because Firefox fires `keypress` events for key commands <ide> * (cut, copy, select-all, etc.) even though no character is inserted. <ide> */ <del>function isKeypressCommand(nativeEvent) { <add>function isKeypressCommand(nativeEvent: any) { <ide> return ( <ide> (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && <ide> // ctrlKey && altKey is equivalent to AltGr, and is not a command. <ide> function isKeypressCommand(nativeEvent) { <ide> <ide> /** <ide> * Translate native top level events into event types. <del> * <del> * @param {string} topLevelType <del> * @return {object} <ide> */ <del>function getCompositionEventType(topLevelType) { <del> switch (topLevelType) { <del> case TOP_COMPOSITION_START: <add>function getCompositionEventType(domEventName: DOMEventName) { <add> switch (domEventName) { <add> case 'compositionstart': <ide> return 'onCompositionStart'; <del> case TOP_COMPOSITION_END: <add> case 'compositionend': <ide> return 'onCompositionEnd'; <del> case TOP_COMPOSITION_UPDATE: <add> case 'compositionupdate': <ide> return 'onCompositionUpdate'; <ide> } <ide> } <ide> <ide> /** <ide> * Does our fallback best-guess model think this event signifies that <ide> * composition has begun? <del> * <del> * @param {string} topLevelType <del> * @param {object} nativeEvent <del> * @return {boolean} <ide> */ <del>function isFallbackCompositionStart(topLevelType, nativeEvent) { <del> return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE; <add>function isFallbackCompositionStart( <add> domEventName: DOMEventName, <add> nativeEvent: any, <add>): boolean { <add> return domEventName === 'keydown' && nativeEvent.keyCode === START_KEYCODE; <ide> } <ide> <ide> /** <ide> * Does our fallback mode think that this event is the end of composition? <del> * <del> * @param {string} topLevelType <del> * @param {object} nativeEvent <del> * @return {boolean} <ide> */ <del>function isFallbackCompositionEnd(topLevelType, nativeEvent) { <del> switch (topLevelType) { <del> case TOP_KEY_UP: <add>function isFallbackCompositionEnd( <add> domEventName: DOMEventName, <add> nativeEvent: any, <add>): boolean { <add> switch (domEventName) { <add> case 'keyup': <ide> // Command keys insert or clear IME input. <ide> return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; <del> case TOP_KEY_DOWN: <add> case 'keydown': <ide> // Expect IME keyCode on each keydown. If we get any other <ide> // code we must have exited earlier. <ide> return nativeEvent.keyCode !== START_KEYCODE; <del> case TOP_KEY_PRESS: <del> case TOP_MOUSE_DOWN: <del> case TOP_FOCUS_OUT: <add> case 'keypress': <add> case 'mousedown': <add> case 'focusout': <ide> // Events are not possible without cancelling IME. <ide> return true; <ide> default: <ide> function isFallbackCompositionEnd(topLevelType, nativeEvent) { <ide> * @param {object} nativeEvent <ide> * @return {?string} <ide> */ <del>function getDataFromCustomEvent(nativeEvent) { <add>function getDataFromCustomEvent(nativeEvent: any) { <ide> const detail = nativeEvent.detail; <ide> if (typeof detail === 'object' && 'data' in detail) { <ide> return detail.data; <ide> function getDataFromCustomEvent(nativeEvent) { <ide> * @param {object} nativeEvent <ide> * @return {boolean} <ide> */ <del>function isUsingKoreanIME(nativeEvent) { <add>function isUsingKoreanIME(nativeEvent: any) { <ide> return nativeEvent.locale === 'ko'; <ide> } <ide> <ide> let isComposing = false; <ide> */ <ide> function extractCompositionEvent( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> function extractCompositionEvent( <ide> let fallbackData; <ide> <ide> if (canUseCompositionEvent) { <del> eventType = getCompositionEventType(topLevelType); <add> eventType = getCompositionEventType(domEventName); <ide> } else if (!isComposing) { <del> if (isFallbackCompositionStart(topLevelType, nativeEvent)) { <add> if (isFallbackCompositionStart(domEventName, nativeEvent)) { <ide> eventType = 'onCompositionStart'; <ide> } <del> } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { <add> } else if (isFallbackCompositionEnd(domEventName, nativeEvent)) { <ide> eventType = 'onCompositionEnd'; <ide> } <ide> <ide> function extractCompositionEvent( <ide> } <ide> } <ide> <del>/** <del> * @param {TopLevelType} topLevelType Number from `TopLevelType`. <del> * @param {object} nativeEvent Native browser event. <del> * @return {?string} The string corresponding to this `beforeInput` event. <del> */ <del>function getNativeBeforeInputChars(topLevelType: TopLevelType, nativeEvent) { <del> switch (topLevelType) { <del> case TOP_COMPOSITION_END: <add>function getNativeBeforeInputChars( <add> domEventName: DOMEventName, <add> nativeEvent: any, <add>): ?string { <add> switch (domEventName) { <add> case 'compositionend': <ide> return getDataFromCustomEvent(nativeEvent); <del> case TOP_KEY_PRESS: <add> case 'keypress': <ide> /** <ide> * If native `textInput` events are available, our goal is to make <ide> * use of them. However, there is a special case: the spacebar key. <ide> function getNativeBeforeInputChars(topLevelType: TopLevelType, nativeEvent) { <ide> hasSpaceKeypress = true; <ide> return SPACEBAR_CHAR; <ide> <del> case TOP_TEXT_INPUT: <add> case 'textInput': <ide> // Record the characters to be added to the DOM. <ide> const chars = nativeEvent.data; <ide> <ide> function getNativeBeforeInputChars(topLevelType: TopLevelType, nativeEvent) { <ide> /** <ide> * For browsers that do not provide the `textInput` event, extract the <ide> * appropriate string to use for SyntheticInputEvent. <del> * <del> * @param {number} topLevelType Number from `TopLevelEventTypes`. <del> * @param {object} nativeEvent Native browser event. <del> * @return {?string} The fallback string for this `beforeInput` event. <ide> */ <del>function getFallbackBeforeInputChars(topLevelType: TopLevelType, nativeEvent) { <add>function getFallbackBeforeInputChars( <add> domEventName: DOMEventName, <add> nativeEvent: any, <add>): ?string { <ide> // If we are currently composing (IME) and using a fallback to do so, <ide> // try to extract the composed characters from the fallback object. <ide> // If composition event is available, we extract a string only at <ide> // compositionevent, otherwise extract it at fallback events. <ide> if (isComposing) { <ide> if ( <del> topLevelType === TOP_COMPOSITION_END || <add> domEventName === 'compositionend' || <ide> (!canUseCompositionEvent && <del> isFallbackCompositionEnd(topLevelType, nativeEvent)) <add> isFallbackCompositionEnd(domEventName, nativeEvent)) <ide> ) { <ide> const chars = FallbackCompositionStateGetData(); <ide> FallbackCompositionStateReset(); <ide> function getFallbackBeforeInputChars(topLevelType: TopLevelType, nativeEvent) { <ide> return null; <ide> } <ide> <del> switch (topLevelType) { <del> case TOP_PASTE: <add> switch (domEventName) { <add> case 'paste': <ide> // If a paste event occurs after a keypress, throw out the input <ide> // chars. Paste events should not lead to BeforeInput events. <ide> return null; <del> case TOP_KEY_PRESS: <add> case 'keypress': <ide> /** <ide> * As of v27, Firefox may fire keypress events even when no character <ide> * will be inserted. A few possibilities: <ide> function getFallbackBeforeInputChars(topLevelType: TopLevelType, nativeEvent) { <ide> } <ide> } <ide> return null; <del> case TOP_COMPOSITION_END: <add> case 'compositionend': <ide> return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) <ide> ? null <ide> : nativeEvent.data; <ide> function getFallbackBeforeInputChars(topLevelType: TopLevelType, nativeEvent) { <ide> */ <ide> function extractBeforeInputEvent( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> ) { <ide> let chars; <ide> <ide> if (canUseTextInputEvent) { <del> chars = getNativeBeforeInputChars(topLevelType, nativeEvent); <add> chars = getNativeBeforeInputChars(domEventName, nativeEvent); <ide> } else { <del> chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); <add> chars = getFallbackBeforeInputChars(domEventName, nativeEvent); <ide> } <ide> <ide> // If no characters are being inserted, no BeforeInput event should <ide> function extractBeforeInputEvent( <ide> * `composition` event types. <ide> */ <ide> function extractEvents( <del> dispatchQueue, <del> topLevelType, <del> targetInst, <del> nativeEvent, <del> nativeEventTarget, <del> eventSystemFlags, <del> targetContainer, <del>) { <add> dispatchQueue: DispatchQueue, <add> domEventName: DOMEventName, <add> targetInst: null | Fiber, <add> nativeEvent: AnyNativeEvent, <add> nativeEventTarget: null | EventTarget, <add> eventSystemFlags: EventSystemFlags, <add> targetContainer: EventTarget, <add>): void { <ide> extractCompositionEvent( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide> ); <ide> extractBeforeInputEvent( <ide> dispatchQueue, <del> topLevelType, <add> domEventName, <ide> targetInst, <ide> nativeEvent, <ide> nativeEventTarget, <ide><path>packages/react-dom/src/events/plugins/ChangeEventPlugin.js <ide> * @flow <ide> */ <ide> import type {AnyNativeEvent} from '../PluginModuleType'; <del>import type {TopLevelType} from '../TopLevelEventTypes'; <add>import type {DOMEventName} from '../DOMEventNames'; <ide> import type {DispatchQueue} from '../DOMPluginEventSystem'; <ide> import type {EventSystemFlags} from '../EventSystemFlags'; <ide> <ide> import {SyntheticEvent} from '../SyntheticEvent'; <ide> import isTextInputElement from '../isTextInputElement'; <ide> import {canUseDOM} from 'shared/ExecutionEnvironment'; <ide> <del>import { <del> TOP_FOCUS_OUT, <del> TOP_CHANGE, <del> TOP_CLICK, <del> TOP_FOCUS_IN, <del> TOP_INPUT, <del> TOP_KEY_DOWN, <del> TOP_KEY_UP, <del> TOP_SELECTION_CHANGE, <del>} from '../DOMTopLevelEventTypes'; <ide> import getEventTarget from '../getEventTarget'; <ide> import isEventSupported from '../isEventSupported'; <ide> import {getNodeFromInstance} from '../../client/ReactDOMComponentTree'; <ide> import { <ide> <ide> function registerEvents() { <ide> registerTwoPhaseEvent('onChange', [ <del> TOP_CHANGE, <del> TOP_CLICK, <del> TOP_FOCUS_IN, <del> TOP_FOCUS_OUT, <del> TOP_INPUT, <del> TOP_KEY_DOWN, <del> TOP_KEY_UP, <del> TOP_SELECTION_CHANGE, <add> 'change', <add> 'click', <add> 'focusin', <add> 'focusout', <add> 'input', <add> 'keydown', <add> 'keyup', <add> 'selectionchange', <ide> ]); <ide> } <ide> <ide> function getInstIfValueChanged(targetInst: Object) { <ide> } <ide> } <ide> <del>function getTargetInstForChangeEvent(topLevelType, targetInst) { <del> if (topLevelType === TOP_CHANGE) { <add>function getTargetInstForChangeEvent(domEventName: DOMEventName, targetInst) { <add> if (domEventName === 'change') { <ide> return targetInst; <ide> } <ide> } <ide> function handlePropertyChange(nativeEvent) { <ide> } <ide> } <ide> <del>function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) { <del> if (topLevelType === TOP_FOCUS_IN) { <add>function handleEventsForInputEventPolyfill( <add> domEventName: DOMEventName, <add> target, <add> targetInst, <add>) { <add> if (domEventName === 'focusin') { <ide> // In IE9, propertychange fires for most input events but is buggy and <ide> // doesn't fire when text is deleted, but conveniently, selectionchange <ide> // appears to fire in all of the remaining cases so we catch those and <ide> function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) { <ide> // missed a blur event somehow. <ide> stopWatchingForValueChange(); <ide> startWatchingForValueChange(target, targetInst); <del> } else if (topLevelType === TOP_FOCUS_OUT) { <add> } else if (domEventName === 'focusout') { <ide> stopWatchingForValueChange(); <ide> } <ide> } <ide> <ide> // For IE8 and IE9. <del>function getTargetInstForInputEventPolyfill(topLevelType, targetInst) { <add>function getTargetInstForInputEventPolyfill( <add> domEventName: DOMEventName, <add> targetInst, <add>) { <ide> if ( <del> topLevelType === TOP_SELECTION_CHANGE || <del> topLevelType === TOP_KEY_UP || <del> topLevelType === TOP_KEY_DOWN <add> domEventName === 'selectionchange' || <add> domEventName === 'keyup' || <add> domEventName === 'keydown' <ide> ) { <ide> // On the selectionchange event, the target is just document which isn't <ide> // helpful for us so just check activeElement instead. <ide> function shouldUseClickEvent(elem) { <ide> ); <ide> } <ide> <del>function getTargetInstForClickEvent(topLevelType, targetInst) { <del> if (topLevelType === TOP_CLICK) { <add>function getTargetInstForClickEvent(domEventName: DOMEventName, targetInst) { <add> if (domEventName === 'click') { <ide> return getInstIfValueChanged(targetInst); <ide> } <ide> } <ide> <del>function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) { <del> if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) { <add>function getTargetInstForInputOrChangeEvent( <add> domEventName: DOMEventName, <add> targetInst, <add>) { <add> if (domEventName === 'input' || domEventName === 'change') { <ide> return getInstIfValueChanged(targetInst); <ide> } <ide> } <ide> function handleControlledInputBlur(node: HTMLInputElement) { <ide> */ <ide> function extractEvents( <ide> dispatchQueue: DispatchQueue, <del> topLevelType: TopLevelType, <add> domEventName: DOMEventName, <ide> targetInst: null | Fiber, <ide> nativeEvent: AnyNativeEvent, <ide> nativeEventTarget: null | EventTarget, <ide> function extractEvents( <ide> } <ide> <ide> if (getTargetInstFunc) { <del> const inst = getTargetInstFunc(topLevelType, targetInst); <add> const inst = getTargetInstFunc(domEventName, targetInst); <ide> if (inst) { <ide> createAndAccumulateChangeEvent( <ide> dispatchQueue, <ide> function extractEvents( <ide> } <ide> <ide> if (handleEventFunc) { <del> handleEventFunc(topLevelType, targetNode, targetInst); <add> handleEventFunc(domEventName, targetNode, targetInst); <ide> } <ide> <ide> // When blurring, set the value attribute for number inputs <del> if (topLevelType === TOP_FOCUS_OUT) { <add> if (domEventName === 'focusout') { <ide> handleControlledInputBlur(((targetNode: any): HTMLInputElement)); <ide> } <ide> } <ide><path>packages/react-dom/src/events/plugins/EnterLeaveEventPlugin.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <ide> */ <ide> <add>import type {AnyNativeEvent} from '../PluginModuleType'; <add>import type {DOMEventName} from '../DOMEventNames'; <add>import type {DispatchQueue} from '../DOMPluginEventSystem'; <add>import type {EventSystemFlags} from '../EventSystemFlags'; <add> <ide> import {registerDirectEvent} from '../EventRegistry'; <del>import { <del> TOP_MOUSE_OUT, <del> TOP_MOUSE_OVER, <del> TOP_POINTER_OUT, <del> TOP_POINTER_OVER, <del>} from '../DOMTopLevelEventTypes'; <ide> import {IS_REPLAYED} from 'react-dom/src/events/EventSystemFlags'; <ide> import { <ide> SyntheticEvent, <ide> import {HostComponent, HostText} from 'react-reconciler/src/ReactWorkTags'; <ide> import {getNearestMountedFiber} from 'react-reconciler/src/ReactFiberTreeReflection'; <ide> <ide> function registerEvents() { <del> registerDirectEvent('onMouseEnter', [TOP_MOUSE_OUT, TOP_MOUSE_OVER]); <del> registerDirectEvent('onMouseLeave', [TOP_MOUSE_OUT, TOP_MOUSE_OVER]); <del> registerDirectEvent('onPointerEnter', [TOP_POINTER_OUT, TOP_POINTER_OVER]); <del> registerDirectEvent('onPointerLeave', [TOP_POINTER_OUT, TOP_POINTER_OVER]); <add> registerDirectEvent('onMouseEnter', ['mouseout', 'mouseover']); <add> registerDirectEvent('onMouseLeave', ['mouseout', 'mouseover']); <add> registerDirectEvent('onPointerEnter', ['pointerout', 'pointerover']); <add> registerDirectEvent('onPointerLeave', ['pointerout', 'pointerover']); <ide> } <ide> <ide> /** <ide> function registerEvents() { <ide> * the `mouseover` top-level event. <ide> */ <ide> function extractEvents( <del> dispatchQueue, <del> topLevelType, <del> targetInst, <del> nativeEvent, <del> nativeEventTarget, <del> eventSystemFlags, <del> targetContainer, <add> dispatchQueue: DispatchQueue, <add> domEventName: DOMEventName, <add> targetInst: null | Fiber, <add> nativeEvent: AnyNativeEvent, <add> nativeEventTarget: null | EventTarget, <add> eventSystemFlags: EventSystemFlags, <add> targetContainer: EventTarget, <ide> ) { <ide> const isOverEvent = <del> topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER; <add> domEventName === 'mouseover' || domEventName === 'pointerover'; <ide> const isOutEvent = <del> topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT; <add> domEventName === 'mouseout' || domEventName === 'pointerout'; <ide> <ide> if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0) { <del> const related = nativeEvent.relatedTarget || nativeEvent.fromElement; <add> const related = <add> (nativeEvent: any).relatedTarget || (nativeEvent: any).fromElement; <ide> if (related) { <ide> // Due to the fact we don't add listeners to the document with the <ide> // modern event system and instead attach listeners to roots, we <ide> function extractEvents( <ide> } <ide> <ide> let win; <del> if (nativeEventTarget.window === nativeEventTarget) { <add> // TODO: why is this nullable in the types but we read from it? <add> if ((nativeEventTarget: any).window === nativeEventTarget) { <ide> // `nativeEventTarget` is probably a window object. <ide> win = nativeEventTarget; <ide> } else { <ide> // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. <del> const doc = nativeEventTarget.ownerDocument; <add> const doc = (nativeEventTarget: any).ownerDocument; <ide> if (doc) { <ide> win = doc.defaultView || doc.parentWindow; <ide> } else { <ide> function extractEvents( <ide> let from; <ide> let to; <ide> if (isOutEvent) { <del> const related = nativeEvent.relatedTarget || nativeEvent.toElement; <add> const related = nativeEvent.relatedTarget || (nativeEvent: any).toElement; <ide> from = targetInst; <del> to = related ? getClosestInstanceFromNode(related) : null; <add> to = related ? getClosestInstanceFromNode((related: any)) : null; <ide> if (to !== null) { <ide> const nearestMounted = getNearestMountedFiber(to); <ide> if ( <ide> function extractEvents( <ide> return; <ide> } <ide> <del> let eventInterface, leaveEventType, enterEventType, eventTypePrefix; <del> <del> if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) { <del> eventInterface = MouseEventInterface; <del> leaveEventType = 'onMouseLeave'; <del> enterEventType = 'onMouseEnter'; <del> eventTypePrefix = 'mouse'; <del> } else if ( <del> topLevelType === TOP_POINTER_OUT || <del> topLevelType === TOP_POINTER_OVER <del> ) { <add> let eventInterface = MouseEventInterface; <add> let leaveEventType = 'onMouseLeave'; <add> let enterEventType = 'onMouseEnter'; <add> let eventTypePrefix = 'mouse'; <add> if (domEventName === 'pointerout' || domEventName === 'pointerover') { <ide> eventInterface = PointerEventInterface; <ide> leaveEventType = 'onPointerLeave'; <ide> enterEventType = 'onPointerEnter'; <ide> function extractEvents( <ide> // If we are not processing the first ancestor, then we <ide> // should not process the same nativeEvent again, as we <ide> // will have already processed it in the first ancestor. <del> const nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget); <add> const nativeTargetInst = getClosestInstanceFromNode((nativeEventTarget: any)); <ide> if (nativeTargetInst !== targetInst) { <ide> enter = null; <ide> } <ide><path>packages/react-dom/src/events/plugins/SelectEventPlugin.js <ide> * <ide> * This source code is licensed under the MIT license found in the <ide> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <ide> */ <ide> <add>import type {AnyNativeEvent} from '../PluginModuleType'; <add>import type {DOMEventName} from '../DOMEventNames'; <add>import type {DispatchQueue} from '../DOMPluginEventSystem'; <add>import type {EventSystemFlags} from '../EventSystemFlags'; <add> <ide> import {canUseDOM} from 'shared/ExecutionEnvironment'; <ide> import {SyntheticEvent} from '../../events/SyntheticEvent'; <ide> import isTextInputElement from '../isTextInputElement'; <ide> import shallowEqual from 'shared/shallowEqual'; <ide> <ide> import {registerTwoPhaseEvent} from '../EventRegistry'; <del>import { <del> TOP_FOCUS_OUT, <del> TOP_CONTEXT_MENU, <del> TOP_DRAG_END, <del> TOP_FOCUS_IN, <del> TOP_KEY_DOWN, <del> TOP_KEY_UP, <del> TOP_MOUSE_DOWN, <del> TOP_MOUSE_UP, <del> TOP_SELECTION_CHANGE, <del>} from '../DOMTopLevelEventTypes'; <ide> import getActiveElement from '../../client/getActiveElement'; <ide> import { <ide> getNodeFromInstance, <ide> import {accumulateTwoPhaseListeners} from '../DOMPluginEventSystem'; <ide> const skipSelectionChangeEvent = <ide> canUseDOM && 'documentMode' in document && document.documentMode <= 11; <ide> <del>const rootTargetDependencies = [ <del> TOP_FOCUS_OUT, <del> TOP_CONTEXT_MENU, <del> TOP_DRAG_END, <del> TOP_FOCUS_IN, <del> TOP_KEY_DOWN, <del> TOP_KEY_UP, <del> TOP_MOUSE_DOWN, <del> TOP_MOUSE_UP, <del>]; <del> <ide> function registerEvents() { <ide> registerTwoPhaseEvent('onSelect', [ <del> ...rootTargetDependencies, <del> TOP_SELECTION_CHANGE, <add> 'focusout', <add> 'contextmenu', <add> 'dragend', <add> 'focusin', <add> 'keydown', <add> 'keyup', <add> 'mousedown', <add> 'mouseup', <add> 'selectionchange', <ide> ]); <ide> } <ide> <ide> let mouseDown = false; <ide> * <ide> * The return value will not be consistent across nodes or browsers, but <ide> * two identical selections on the same node will return identical objects. <del> * <del> * @param {DOMElement} node <del> * @return {object} <ide> */ <del>function getSelection(node) { <add>function getSelection(node: any) { <ide> if ('selectionStart' in node && hasSelectionCapabilities(node)) { <ide> return { <ide> start: node.selectionStart, <ide> function getSelection(node) { <ide> <ide> /** <ide> * Get document associated with the event target. <del> * <del> * @param {object} nativeEventTarget <del> * @return {Document} <ide> */ <del>function getEventTargetDocument(eventTarget) { <add>function getEventTargetDocument(eventTarget: any) { <ide> return eventTarget.window === eventTarget <ide> ? eventTarget.document <ide> : eventTarget.nodeType === DOCUMENT_NODE <ide> function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) { <ide> * - Fires after user input. <ide> */ <ide> function extractEvents( <del> dispatchQueue, <del> topLevelType, <del> targetInst, <del> nativeEvent, <del> nativeEventTarget, <del> eventSystemFlags, <del> targetContainer, <add> dispatchQueue: DispatchQueue, <add> domEventName: DOMEventName, <add> targetInst: null | Fiber, <add> nativeEvent: AnyNativeEvent, <add> nativeEventTarget: null | EventTarget, <add> eventSystemFlags: EventSystemFlags, <add> targetContainer: EventTarget, <ide> ) { <ide> const eventListenerMap = getEventListenerMap(targetContainer); <ide> // Track whether all listeners exists for this plugin. If none exist, we do <ide> // not extract events. See #3639. <ide> if ( <del> // If we are handling TOP_SELECTION_CHANGE, then we don't need to <del> // check for the other dependencies, as TOP_SELECTION_CHANGE is only <add> // If we are handling selectionchange, then we don't need to <add> // check for the other dependencies, as selectionchange is only <ide> // event attached from the onChange plugin and we don't expose an <ide> // onSelectionChange event from React. <del> topLevelType !== TOP_SELECTION_CHANGE && <add> domEventName !== 'selectionchange' && <ide> !eventListenerMap.has('onSelect') && <ide> !eventListenerMap.has('onSelectCapture') <ide> ) { <ide> function extractEvents( <ide> <ide> const targetNode = targetInst ? getNodeFromInstance(targetInst) : window; <ide> <del> switch (topLevelType) { <add> switch (domEventName) { <ide> // Track the input node that has focus. <del> case TOP_FOCUS_IN: <add> case 'focusin': <ide> if ( <del> isTextInputElement(targetNode) || <add> isTextInputElement((targetNode: any)) || <ide> targetNode.contentEditable === 'true' <ide> ) { <ide> activeElement = targetNode; <ide> activeElementInst = targetInst; <ide> lastSelection = null; <ide> } <ide> break; <del> case TOP_FOCUS_OUT: <add> case 'focusout': <ide> activeElement = null; <ide> activeElementInst = null; <ide> lastSelection = null; <ide> break; <ide> // Don't fire the event while the user is dragging. This matches the <ide> // semantics of the native select event. <del> case TOP_MOUSE_DOWN: <add> case 'mousedown': <ide> mouseDown = true; <ide> break; <del> case TOP_CONTEXT_MENU: <del> case TOP_MOUSE_UP: <del> case TOP_DRAG_END: <add> case 'contextmenu': <add> case 'mouseup': <add> case 'dragend': <ide> mouseDown = false; <ide> constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); <ide> break; <ide> function extractEvents( <ide> // keyup, but we check on keydown as well in the case of holding down a <ide> // key, when multiple keydown events are fired but only one keyup is. <ide> // This is also our approach for IE handling, for the reason above. <del> case TOP_SELECTION_CHANGE: <add> case 'selectionchange': <ide> if (skipSelectionChangeEvent) { <ide> break; <ide> } <ide> // falls through <del> case TOP_KEY_DOWN: <del> case TOP_KEY_UP: <add> case 'keydown': <add> case 'keyup': <ide> constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); <ide> } <ide> <ide><path>packages/react-dom/src/events/plugins/SimpleEventPlugin.js <ide> * @flow <ide> */ <ide> <del>import type {TopLevelType} from '../../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../../events/DOMEventNames'; <ide> import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; <ide> import type {AnyNativeEvent} from '../../events/PluginModuleType'; <ide> import type {DispatchQueue} from '../DOMPluginEventSystem'; <ide> import { <ide> WheelEventInterface, <ide> } from '../../events/SyntheticEvent'; <ide> <del>import * as DOMTopLevelEventTypes from '../DOMTopLevelEventTypes'; <add>import { <add> ANIMATION_END, <add> ANIMATION_ITERATION, <add> ANIMATION_START, <add> TRANSITION_END, <add>} from '../DOMEventNames'; <ide> import { <ide> topLevelEventsToReactNames, <ide> registerSimpleEvents, <ide> import { <ide> <ide> function extractEvents( <ide> dispatchQueue: DispatchQueue, <del> topLevelType: TopLevelType, <add> domEventName: DOMEventName, <ide> targetInst: null | Fiber, <ide> nativeEvent: AnyNativeEvent, <ide> nativeEventTarget: null | EventTarget, <ide> eventSystemFlags: EventSystemFlags, <ide> targetContainer: EventTarget, <ide> ): void { <del> const reactName = topLevelEventsToReactNames.get(topLevelType); <add> const reactName = topLevelEventsToReactNames.get(domEventName); <ide> if (reactName === undefined) { <ide> return; <ide> } <ide> let EventInterface; <del> switch (topLevelType) { <del> case DOMTopLevelEventTypes.TOP_KEY_PRESS: <add> switch (domEventName) { <add> case 'keypress': <ide> // Firefox creates a keypress event for function keys too. This removes <ide> // the unwanted keypress events. Enter is however both printable and <ide> // non-printable. One would expect Tab to be as well (but it isn't). <ide> if (getEventCharCode(((nativeEvent: any): KeyboardEvent)) === 0) { <ide> return; <ide> } <ide> /* falls through */ <del> case DOMTopLevelEventTypes.TOP_KEY_DOWN: <del> case DOMTopLevelEventTypes.TOP_KEY_UP: <add> case 'keydown': <add> case 'keyup': <ide> EventInterface = KeyboardEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_FOCUS_IN: <del> case DOMTopLevelEventTypes.TOP_FOCUS_OUT: <del> case DOMTopLevelEventTypes.TOP_BEFORE_BLUR: <del> case DOMTopLevelEventTypes.TOP_AFTER_BLUR: <add> case 'focusin': <add> case 'focusout': <add> case 'beforeblur': <add> case 'afterblur': <ide> EventInterface = FocusEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_CLICK: <add> case 'click': <ide> // Firefox creates a click event on right mouse clicks. This removes the <ide> // unwanted click events. <ide> if (nativeEvent.button === 2) { <ide> return; <ide> } <ide> /* falls through */ <del> case DOMTopLevelEventTypes.TOP_AUX_CLICK: <del> case DOMTopLevelEventTypes.TOP_DOUBLE_CLICK: <del> case DOMTopLevelEventTypes.TOP_MOUSE_DOWN: <del> case DOMTopLevelEventTypes.TOP_MOUSE_MOVE: <del> case DOMTopLevelEventTypes.TOP_MOUSE_UP: <add> case 'auxclick': <add> case 'dblclick': <add> case 'mousedown': <add> case 'mousemove': <add> case 'mouseup': <ide> // TODO: Disabled elements should not respond to mouse events <ide> /* falls through */ <del> case DOMTopLevelEventTypes.TOP_MOUSE_OUT: <del> case DOMTopLevelEventTypes.TOP_MOUSE_OVER: <del> case DOMTopLevelEventTypes.TOP_CONTEXT_MENU: <add> case 'mouseout': <add> case 'mouseover': <add> case 'contextmenu': <ide> EventInterface = MouseEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_DRAG: <del> case DOMTopLevelEventTypes.TOP_DRAG_END: <del> case DOMTopLevelEventTypes.TOP_DRAG_ENTER: <del> case DOMTopLevelEventTypes.TOP_DRAG_EXIT: <del> case DOMTopLevelEventTypes.TOP_DRAG_LEAVE: <del> case DOMTopLevelEventTypes.TOP_DRAG_OVER: <del> case DOMTopLevelEventTypes.TOP_DRAG_START: <del> case DOMTopLevelEventTypes.TOP_DROP: <add> case 'drag': <add> case 'dragend': <add> case 'dragenter': <add> case 'dragexit': <add> case 'dragleave': <add> case 'dragover': <add> case 'dragstart': <add> case 'drop': <ide> EventInterface = DragEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_TOUCH_CANCEL: <del> case DOMTopLevelEventTypes.TOP_TOUCH_END: <del> case DOMTopLevelEventTypes.TOP_TOUCH_MOVE: <del> case DOMTopLevelEventTypes.TOP_TOUCH_START: <add> case 'touchcancel': <add> case 'touchend': <add> case 'touchmove': <add> case 'touchstart': <ide> EventInterface = TouchEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_ANIMATION_END: <del> case DOMTopLevelEventTypes.TOP_ANIMATION_ITERATION: <del> case DOMTopLevelEventTypes.TOP_ANIMATION_START: <add> case ANIMATION_END: <add> case ANIMATION_ITERATION: <add> case ANIMATION_START: <ide> EventInterface = AnimationEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_TRANSITION_END: <add> case TRANSITION_END: <ide> EventInterface = TransitionEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_SCROLL: <add> case 'scroll': <ide> EventInterface = UIEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_WHEEL: <add> case 'wheel': <ide> EventInterface = WheelEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_COPY: <del> case DOMTopLevelEventTypes.TOP_CUT: <del> case DOMTopLevelEventTypes.TOP_PASTE: <add> case 'copy': <add> case 'cut': <add> case 'paste': <ide> EventInterface = ClipboardEventInterface; <ide> break; <del> case DOMTopLevelEventTypes.TOP_GOT_POINTER_CAPTURE: <del> case DOMTopLevelEventTypes.TOP_LOST_POINTER_CAPTURE: <del> case DOMTopLevelEventTypes.TOP_POINTER_CANCEL: <del> case DOMTopLevelEventTypes.TOP_POINTER_DOWN: <del> case DOMTopLevelEventTypes.TOP_POINTER_MOVE: <del> case DOMTopLevelEventTypes.TOP_POINTER_OUT: <del> case DOMTopLevelEventTypes.TOP_POINTER_OVER: <del> case DOMTopLevelEventTypes.TOP_POINTER_UP: <add> case 'gotpointercapture': <add> case 'lostpointercapture': <add> case 'pointercancel': <add> case 'pointerdown': <add> case 'pointermove': <add> case 'pointerout': <add> case 'pointerover': <add> case 'pointerup': <ide> EventInterface = PointerEventInterface; <ide> break; <ide> default: <ide> function extractEvents( <ide> // TODO: ideally, we'd eventually add all events from <ide> // nonDelegatedEvents list in DOMPluginEventSystem. <ide> // Then we can remove this special list. <del> topLevelType === DOMTopLevelEventTypes.TOP_SCROLL; <add> domEventName === 'scroll'; <ide> } <ide> <ide> accumulateSinglePhaseListeners( <ide><path>packages/react-dom/src/shared/ReactDOMTypes.js <ide> import type { <ide> EventPriority, <ide> ReactScopeInstance, <ide> } from 'shared/ReactTypes'; <del>import type {DOMTopLevelEventType} from '../events/TopLevelEventTypes'; <add>import type {DOMEventName} from '../events/DOMEventNames'; <ide> <ide> type AnyNativeEvent = Event | KeyboardEvent | MouseEvent | Touch; <ide> <ide> export type ReactDOMEventHandle = ( <ide> export type ReactDOMEventHandleListener = {| <ide> callback: (SyntheticEvent<EventTarget>) => void, <ide> capture: boolean, <del> type: DOMTopLevelEventType, <add> type: DOMEventName, <ide> |};
20
Python
Python
remove unusued import
315ff1c03463a27f815d0d1000d974a44905ba0a
<ide><path>numpy/core/tests/test_multiarray.py <del>from cgi import test <ide> import collections.abc <ide> import tempfile <ide> import sys
1
Ruby
Ruby
add initial doc for core in aj [ci skip]
785cb9fe751901a42d07a05bc7e8696660bce11c
<ide><path>activejob/lib/active_job/core.rb <ide> module ActiveJob <add> # Provides general behavior that will be included into every Active Job <add> # object that inherits from ActiveJob::Base. <ide> module Core <ide> extend ActiveSupport::Concern <ide>
1
Text
Text
add pageextensions usage note in api routes
3bd42b4d0bc3e967894f9bcf715d1c062f9a1c19
<ide><path>docs/api-routes/introduction.md <ide> export default function handler(req, res) { <ide> } <ide> ``` <ide> <add>> **Note**: API Routes will be affected by [`pageExtensions` configuration](/docs/api-reference/next.config.js/custom-page-extensions.md) in `next.config.js`. <add> <ide> For an API route to work, you need to export a function as default (a.k.a **request handler**), which then receives the following parameters: <ide> <ide> - `req`: An instance of [http.IncomingMessage](https://nodejs.org/api/http.html#class-httpincomingmessage), plus some [pre-built middlewares](/docs/api-routes/api-middlewares.md)
1
Python
Python
allow shaped dtypes
a2bf56aaf98ea150079ee5d05da21b18de68252a
<ide><path>numpy/lib/io.py <ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, <ide> def flatten_dtype(dt): <ide> """Unpack a structured data-type.""" <ide> if dt.names is None: <del> return [dt] <add> # If the dtype is flattened, return. <add> # If the dtype has a shape, the dtype occurs <add> # in the list more than once. <add> return [dt.base] * int(np.prod(dt.shape)) <ide> else: <ide> types = [] <ide> for field in dt.names: <ide><path>numpy/lib/tests/test_io.py <ide> def test_fancy_dtype(self): <ide> a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dt) <ide> assert_array_equal(x, a) <ide> <add> def test_shaped_dtype(self): <add> c = StringIO.StringIO("aaaa 1.0 8.0 1 2 3 4 5 6") <add> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), <add> ('block', int, (2, 3))]) <add> x = np.loadtxt(c, dtype=dt) <add> a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])], <add> dtype=dt) <add> assert_array_equal(x, a) <add> <ide> def test_empty_file(self): <ide> c = StringIO.StringIO() <ide> assert_raises(IOError, np.loadtxt, c)
2
Ruby
Ruby
add counter cache test for class_name
e64875ffde5787eee24a96070f3cf51727347304
<ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb <ide> def test_self_referential_belongs_to_with_counter_cache_assigning_nil <ide> assert_equal 0, comments(:greetings).reload.children_count <ide> end <ide> <add> def test_belongs_to_with_id_assigning <add> post = posts(:welcome) <add> comment = Comment.create! body: "foo", post: post <add> parent = comments(:greetings) <add> assert_equal 0, parent.reload.children_count <add> comment.parent_id = parent.id <add> <add> comment.save! <add> assert_equal 1, parent.reload.children_count <add> end <add> <ide> def test_polymorphic_with_custom_primary_key <ide> toy = Toy.create! <ide> sponsor = Sponsor.create!(:sponsorable => toy)
1
Java
Java
log timespan of attach_measured_root_views
d353b75c120787670e7086e71e4255a7ad819495
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> import com.facebook.systrace.SystraceMessage; <ide> <ide> import static com.facebook.infer.annotation.ThreadConfined.UI; <add>import static com.facebook.react.bridge.ReactMarkerConstants.ATTACH_MEASURED_ROOT_VIEWS_END; <add>import static com.facebook.react.bridge.ReactMarkerConstants.ATTACH_MEASURED_ROOT_VIEWS_START; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_END; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_START; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_END; <ide> private void setupReactContext(ReactApplicationContext reactContext) { <ide> mMemoryPressureRouter.addMemoryPressureListener(catalystInstance); <ide> moveReactContextToCurrentLifecycleState(); <ide> <add> ReactMarker.logMarker(ATTACH_MEASURED_ROOT_VIEWS_START); <ide> synchronized (mAttachedRootViews) { <ide> for (ReactRootView rootView : mAttachedRootViews) { <ide> attachMeasuredRootViewToInstance(rootView, catalystInstance); <ide> } <ide> } <add> ReactMarker.logMarker(ATTACH_MEASURED_ROOT_VIEWS_END); <ide> <ide> ReactInstanceEventListener[] listeners = <ide> new ReactInstanceEventListener[mReactInstanceEventListeners.size()]; <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReactMarkerConstants.java <ide> public enum ReactMarkerConstants { <ide> PRE_SETUP_REACT_CONTEXT_START, <ide> PRE_SETUP_REACT_CONTEXT_END, <ide> PRE_RUN_JS_BUNDLE_START, <add> ATTACH_MEASURED_ROOT_VIEWS_START, <add> ATTACH_MEASURED_ROOT_VIEWS_END, <ide> }
2
Go
Go
use remote daemon in proxy test
029ca9829df1d42a67289e0318db416cdbcfaf35
<ide><path>integration-cli/docker_cli_proxy_test.go <ide> import ( <ide> <ide> func TestCliProxyDisableProxyUnixSock(t *testing.T) { <ide> cmd := exec.Command(dockerBinary, "info") <del> cmd.Env = []string{"HTTP_PROXY=http://127.0.0.1:9999"} <add> cmd.Env = appendDockerHostEnv([]string{"HTTP_PROXY=http://127.0.0.1:9999"}) <ide> <ide> if out, _, err := runCommandWithOutput(cmd); err != nil { <ide> t.Fatal(err, out)
1
Python
Python
add push to hub to feature extractor
52d2e6f6e904ef9b75c78716ce77b98196ed837a
<ide><path>src/transformers/feature_extraction_utils.py <ide> from .file_utils import ( <ide> FEATURE_EXTRACTOR_NAME, <ide> EntryNotFoundError, <add> PushToHubMixin, <ide> RepositoryNotFoundError, <ide> RevisionNotFoundError, <ide> TensorType, <ide> _is_jax, <ide> _is_numpy, <ide> _is_torch_device, <ide> cached_path, <add> copy_func, <ide> hf_bucket_url, <ide> is_flax_available, <ide> is_offline_mode, <ide> def to(self, device: Union[str, "torch.device"]) -> "BatchFeature": <ide> return self <ide> <ide> <del>class FeatureExtractionMixin: <add>class FeatureExtractionMixin(PushToHubMixin): <ide> """ <ide> This is a feature extraction mixin used to provide saving/loading functionality for sequential and image feature <ide> extractors. <ide> def from_pretrained( <ide> <ide> return cls.from_dict(feature_extractor_dict, **kwargs) <ide> <del> def save_pretrained(self, save_directory: Union[str, os.PathLike]): <add> def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs): <ide> """ <ide> Save a feature_extractor object to the directory `save_directory`, so that it can be re-loaded using the <ide> [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] class method. <ide> <ide> Args: <ide> save_directory (`str` or `os.PathLike`): <ide> Directory where the feature extractor JSON file will be saved (will be created if it does not exist). <add> push_to_hub (`bool`, *optional*, defaults to `False`): <add> Whether or not to push your feature extractor to the Hugging Face model hub after saving it. <add> <add> <Tip warning={true}> <add> <add> Using `push_to_hub=True` will synchronize the repository you are pushing to with `save_directory`, <add> which requires `save_directory` to be a local clone of the repo you are pushing to if it's an existing <add> folder. Pass along `temp_dir=True` to use a temporary directory instead. <add> <add> </Tip> <add> <add> kwargs: <add> Additional key word arguments passed along to the [`~file_utils.PushToHubMixin.push_to_hub`] method. <ide> """ <ide> if os.path.isfile(save_directory): <ide> raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") <ide> <add> if push_to_hub: <add> commit_message = kwargs.pop("commit_message", None) <add> repo = self._create_or_get_repo(save_directory, **kwargs) <add> <ide> # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be <ide> # loaded from the Hub. <ide> if self._auto_class is not None: <ide> def save_pretrained(self, save_directory: Union[str, os.PathLike]): <ide> output_feature_extractor_file = os.path.join(save_directory, FEATURE_EXTRACTOR_NAME) <ide> <ide> self.to_json_file(output_feature_extractor_file) <del> logger.info(f"Configuration saved in {output_feature_extractor_file}") <add> logger.info(f"Feature extractor saved in {output_feature_extractor_file}") <add> <add> if push_to_hub: <add> url = self._push_to_hub(repo, commit_message=commit_message) <add> logger.info(f"Feature extractor pushed to the hub in this commit: {url}") <ide> <ide> @classmethod <ide> def get_feature_extractor_dict( <ide> def register_for_auto_class(cls, auto_class="AutoFeatureExtractor"): <ide> raise ValueError(f"{auto_class} is not a valid auto class.") <ide> <ide> cls._auto_class = auto_class <add> <add> <add>FeatureExtractionMixin.push_to_hub = copy_func(FeatureExtractionMixin.push_to_hub) <add>FeatureExtractionMixin.push_to_hub.__doc__ = FeatureExtractionMixin.push_to_hub.__doc__.format( <add> object="feature extractor", object_class="AutoFeatureExtractor", object_files="feature extractor file" <add>) <ide><path>tests/test_feature_extraction_common.py <ide> <ide> from huggingface_hub import Repository, delete_repo, login <ide> from requests.exceptions import HTTPError <del>from transformers import AutoFeatureExtractor <add>from transformers import AutoFeatureExtractor, Wav2Vec2FeatureExtractor <ide> from transformers.file_utils import is_torch_available, is_vision_available <ide> from transformers.testing_utils import PASS, USER, is_staging_test <ide> <ide> if is_vision_available(): <ide> from PIL import Image <ide> <del> <ide> SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures") <ide> <ide> <ide> def setUpClass(cls): <ide> <ide> @classmethod <ide> def tearDownClass(cls): <add> try: <add> delete_repo(token=cls._token, name="test-feature-extractor") <add> except HTTPError: <add> pass <add> <add> try: <add> delete_repo(token=cls._token, name="test-feature-extractor-org", organization="valid_org") <add> except HTTPError: <add> pass <add> <ide> try: <ide> delete_repo(token=cls._token, name="test-dynamic-feature-extractor") <ide> except HTTPError: <ide> pass <ide> <add> def test_push_to_hub(self): <add> feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) <add> with tempfile.TemporaryDirectory() as tmp_dir: <add> feature_extractor.save_pretrained( <add> os.path.join(tmp_dir, "test-feature-extractor"), push_to_hub=True, use_auth_token=self._token <add> ) <add> <add> new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor") <add> for k, v in feature_extractor.__dict__.items(): <add> self.assertEqual(v, getattr(new_feature_extractor, k)) <add> <add> def test_push_to_hub_in_organization(self): <add> feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) <add> <add> with tempfile.TemporaryDirectory() as tmp_dir: <add> feature_extractor.save_pretrained( <add> os.path.join(tmp_dir, "test-feature-extractor-org"), <add> push_to_hub=True, <add> use_auth_token=self._token, <add> organization="valid_org", <add> ) <add> <add> new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org") <add> for k, v in feature_extractor.__dict__.items(): <add> self.assertEqual(v, getattr(new_feature_extractor, k)) <add> <ide> def test_push_to_hub_dynamic_feature_extractor(self): <ide> CustomFeatureExtractor.register_for_auto_class() <ide> feature_extractor = CustomFeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR)
2
Text
Text
fix typo in guides/source/engines.md
0a89d4db1e06d06026bc73726a47d2ef20748070
<ide><path>guides/source/engines.md <ide> Now people will only need to go to the root of the engine to see all the posts, <ide> <ide> ### Generating a comments resource <ide> <del>Now that the engine can to create new blog posts, it only makes sense to add commenting functionality as well. To do get this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones. <add>Now that the engine can create new blog posts, it only makes sense to add commenting functionality as well. To do get this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones. <ide> <ide> Run the model generator and tell it to generate a `Comment` model, with the related table having two columns: a `post_id` integer and `text` text column. <ide>
1
Text
Text
fix anchor link for displayname
4d3c5ea23c38462c1156fe5b97748b89be2a6589
<ide><path>docs/docs/reference-react-component.md <ide> Each component also provides some other APIs: <ide> ### Class Properties <ide> <ide> - [`defaultProps`](#defaultprops) <del> - [`displayName`](#displayName) <add> - [`displayName`](#displayname) <ide> - [`propTypes`](#proptypes) <ide> <ide> ### Instance Properties
1
Go
Go
expose the enableipv6 setting
01d2ad412f33647d2ac0b3e33f7d3260438713d8
<ide><path>libnetwork/network.go <ide> type NetworkInfo interface { <ide> IpamInfo() ([]*IpamInfo, []*IpamInfo) <ide> DriverOptions() map[string]string <ide> Scope() string <add> IPv6Enabled() bool <ide> Internal() bool <ide> } <ide> <ide> func (n *network) Internal() bool { <ide> <ide> return n.internal <ide> } <add> <add>func (n *network) IPv6Enabled() bool { <add> n.Lock() <add> defer n.Unlock() <add> <add> return n.enableIPv6 <add>}
1
Javascript
Javascript
remove wrong addition of padding
b4b3bf60b81e898fac41afc716b5885e928caebc
<ide><path>src/scales/scale.linear.js <ide> // Bottom - top since pixels increase downard on a screen <ide> var innerHeight = this.height - (this.paddingTop + this.paddingBottom); <ide> pixel = (this.bottom - this.paddingBottom) - (innerHeight / range * (value - this.start)); <del> pixel += this.paddingTop; <ide> } <ide> <ide> return pixel;
1
PHP
PHP
boot the application on test refresh
99522e5c38cd62883ae2b040bc74554824a3a053
<ide><path>src/Illuminate/Foundation/Testing/TestCase.php <ide> abstract class TestCase extends \PHPUnit_Framework_TestCase { <ide> */ <ide> public function setUp() <ide> { <del> if ( ! $this->app) $this->refreshApplication(); <add> if ( ! $this->app) <add> { <add> $this->refreshApplication(); <add> <add> $this->app->boot(); <add> } <ide> } <ide> <ide> /** <ide> public function assertSessionHasAll(array $bindings) <ide> <ide> /** <ide> * Assert that the session has errors bound. <del> * <add> * <ide> * @param string|array $bindings <ide> * @param mixed $format <ide> * @return void
1
Ruby
Ruby
use each_key instead of keys.each
4a52bf1c3186b75551cb37cbf721da185291c384
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_for_linked_keg_only_brews <ide> You may wish to `brew unlink` these brews: <ide> <ide> EOS <del> warnings.keys.each{ |f| s << " #{f}\n" } <add> warnings.each_key { |f| s << " #{f}\n" } <ide> s <ide> end <ide> end
1
Text
Text
improve intro "tradeoffs" paragraphs and wording
96342f444ef7c0b6b29a8b8048b4f332ef9f0eb5
<ide><path>docs/recipes/UsageWithTypescript.md <ide> hide_title: true <ide> 2. Easy refactoring of typed code <ide> 3. A superior developer experience in a team environment <ide> <del>[**We strongly recommend using TypeScript in Redux applications**](../style-guide/style-guide.md#use-static-typing). However, like all tools, TypeScript has tradeoffs. It adds complexity in terms of writing additional code, understanding TS syntax, and building the application. At the same time, it provides value by catching errors early, enabling correct refactoring, and acting as documentation for existing source code. We believe that **[pragmatic use of Typescript](https://blog.isquaredsoftware.com/2019/11/blogged-answers-learning-and-using-typescript/#pragmatism-is-vital) provides more than enough value and benefit to justify the added overhead**, especially in larger codebases, but you should take time to **evaluate the tradeoffs and decide whether it's worth using TS in your own application**. <add>[**We strongly recommend using TypeScript in Redux applications**](../style-guide/style-guide.md#use-static-typing). However, like all tools, TypeScript has tradeoffs. It adds complexity in terms of writing additional code, understanding TS syntax, and building the application. At the same time, it provides value by catching errors early, enabling correct refactoring, and acting as documentation for existing source code. <ide> <del>There are multiple possible approaches to type checking Redux code. This page demonstrates some of the common and recommended approaches to keep things simple, and is not an exhaustive guide. <add>We believe that **[pragmatic use of Typescript](https://blog.isquaredsoftware.com/2019/11/blogged-answers-learning-and-using-typescript/#pragmatism-is-vital) provides more than enough value and benefit to justify the added overhead**, especially in larger codebases, but you should take time to **evaluate the tradeoffs and decide whether it's worth using TS in your own application**. <add> <add>There are multiple possible approaches to type checking Redux code. **This page shows our standard recommended patterns for using Redux and TypeScript together**, and is not an exhaustive guide. Following these patterns should result in a good TS usage experience, with **the best tradeoffs between type safety and amount of type declarations you have to add to your codebase**. <ide> <ide> ## Standard Redux Toolkit Project Setup with TypeScript <ide> <ide> Note that this assumes that there is no meaningful return value from the thunk. <ide> <ide> :::caution <ide> <del>Don't forget that **the default `useDispatch` hook does not know about thunks**, and so dispatching a thunk will cause a type error. Be sure to [use an updated form of `Dispatch` that recognizes thunks](#define-root-state-and-dispatch-types) in your components. <add>Don't forget that **the default `useDispatch` hook does not know about thunks**, and so dispatching a thunk will cause a type error. Be sure to [use an updated form of `Dispatch` in your components that recognizes thunks as an acceptable type to dispatch](#define-root-state-and-dispatch-types). <ide> <ide> ::: <ide>
1
Javascript
Javascript
update imports for elements
7cd77e779d4131cce3f2ba4c758fff7ad5a1b96b
<ide><path>src/elements/element.point.js <ide> <ide> import defaults from '../core/core.defaults'; <ide> import Element from '../core/core.element'; <del>import helpers from '../helpers'; <add>import {_isPointInArea, drawPoint} from '../helpers/helpers.canvas'; <ide> <ide> const defaultColor = defaults.color; <ide> <ide> class Point extends Element { <ide> } <ide> <ide> // Clipping for Points. <del> if (chartArea === undefined || helpers.canvas._isPointInArea(me, chartArea)) { <add> if (chartArea === undefined || _isPointInArea(me, chartArea)) { <ide> ctx.strokeStyle = options.borderColor; <ide> ctx.lineWidth = options.borderWidth; <ide> ctx.fillStyle = options.backgroundColor; <del> helpers.canvas.drawPoint(ctx, options, me.x, me.y); <add> drawPoint(ctx, options, me.x, me.y); <ide> } <ide> } <ide> <ide><path>src/elements/element.rectangle.js <ide> <ide> import defaults from '../core/core.defaults'; <ide> import Element from '../core/core.element'; <del>import helpers from '../helpers'; <add>import {isObject} from '../helpers/helpers.core'; <ide> <ide> const defaultColor = defaults.color; <ide> <ide> function parseBorderWidth(bar, maxW, maxH) { <ide> var skip = parseBorderSkipped(bar); <ide> var t, r, b, l; <ide> <del> if (helpers.isObject(value)) { <add> if (isObject(value)) { <ide> t = +value.top || 0; <ide> r = +value.right || 0; <ide> b = +value.bottom || 0;
2
Ruby
Ruby
implement pinning of taps
1a82b2133eed0599df2375b870bfe4cbf28a02aa
<ide><path>Library/Homebrew/cmd/tap-pin.rb <add>require "cmd/tap" <add> <add>module Homebrew <add> def tap_pin <add> taps = ARGV.named.map do |name| <add> Tap.new(*tap_args(name)) <add> end <add> taps.each do |tap| <add> tap.pin <add> ohai "Pinned #{tap.name}" <add> end <add> end <add>end <ide><path>Library/Homebrew/cmd/tap-unpin.rb <add>require "cmd/tap" <add> <add>module Homebrew <add> def tap_unpin <add> taps = ARGV.named.map do |name| <add> Tap.new(*tap_args(name)) <add> end <add> taps.each do |tap| <add> tap.unpin <add> ohai "Unpinned #{tap.name}" <add> end <add> end <add>end <ide><path>Library/Homebrew/cmd/untap.rb <ide> def untap <ide> raise TapUnavailableError, tap.name unless tap.installed? <ide> puts "Untapping #{tap}... (#{tap.path.abv})" <ide> <add> tap.unpin if tap.pinned? <add> <ide> formula_count = tap.formula_files.size <ide> tap.path.rmtree <ide> tap.path.dirname.rmdir_if_possible <ide><path>Library/Homebrew/exceptions.rb <ide> def initialize(name) <ide> end <ide> end <ide> <add>class TapPinStatusError < RuntimeError <add> attr_reader :name, :pinned <add> <add> def initialize name, pinned <add> @name = name <add> @pinned = pinned <add> <add> super pinned ? "#{name} is already pinned." : "#{name} is already unpinned." <add> end <add>end <add> <ide> class OperationInProgressError < RuntimeError <ide> def initialize(name) <ide> message = <<-EOS.undent <ide><path>Library/Homebrew/tap.rb <ide> def command_files <ide> Pathname.glob("#{path}/cmd/brew-*").select(&:executable?) <ide> end <ide> <add> def pinned_symlink_path <add> HOMEBREW_LIBRARY/"PinnedTaps/#{@name}" <add> end <add> <add> def pinned? <add> @pinned ||= pinned_symlink_path.directory? <add> end <add> <add> def pin <add> raise TapUnavailableError, name unless installed? <add> raise TapPinStatusError.new(name, true) if pinned? <add> pinned_symlink_path.make_relative_symlink(@path) <add> end <add> <add> def unpin <add> raise TapUnavailableError, name unless installed? <add> raise TapPinStatusError.new(name, false) unless pinned? <add> pinned_symlink_path.delete <add> pinned_symlink_path.dirname.rmdir_if_possible <add> end <add> <ide> def to_hash <ide> { <ide> "name" => @name, <ide> def to_hash <ide> "custom_remote" => custom_remote?, <ide> "formula_names" => formula_names, <ide> "formula_files" => formula_files.map(&:to_s), <del> "command_files" => command_files.map(&:to_s) <add> "command_files" => command_files.map(&:to_s), <add> "pinned" => pinned? <ide> } <ide> end <ide>
5
PHP
PHP
change delete() to remove()
89884ae9b0bdffe9441c3c806152d1d69c9f4d3d
<ide><path>src/ORM/TableRegistry.php <ide> public static function genericInstances() { <ide> } <ide> <ide> /** <del> * Deletes an instance from the registry. <add> * Removes an instance from the registry. <ide> * <ide> * Plugin name will be trimmed off of aliases as instances <ide> * stored in the registry will be without the plugin name as well. <ide> * <del> * @param string $alias The alias to delete. <add> * @param string $alias The alias to remove. <ide> * @return void <ide> */ <del> public static function delete($alias) { <add> public static function remove($alias) { <ide> list(, $alias) = pluginSplit($alias); <ide> <ide> if (isset(static::$_instances[$alias])) {
1
Text
Text
add documentation for docker stats --format
9c7b3040cc97dae0a4fc20f999ca51adce353944
<ide><path>docs/admin/formatting.md <ide> list of elements they support in their templates: <ide> - [Docker Log Tag formatting](logging/log_tags.md) <ide> - [Docker Network Inspect formatting](../reference/commandline/network_inspect.md) <ide> - [Docker PS formatting](../reference/commandline/ps.md#formatting) <add>- [Docker Stats formatting](../reference/commandline/stats.md#formatting) <ide> - [Docker Volume Inspect formatting](../reference/commandline/volume_inspect.md) <ide> - [Docker Version formatting](../reference/commandline/version.md#examples) <ide> <ide><path>docs/reference/commandline/stats.md <ide> Options: <ide> <ide> The `docker stats` command returns a live data stream for running containers. To limit data to one or more specific containers, specify a list of container names or ids separated by a space. You can specify a stopped container but stopped containers do not return any data. <ide> <del>If you want more detailed information about a container's resource usage, use the `/containers/(id)/stats` API endpoint. <add>If you want more detailed information about a container's resource usage, use the `/containers/(id)/stats` API endpoint. <ide> <ide> ## Examples <ide> <ide> Running `docker stats` on all running containers against a Linux daemon. <ide> Running `docker stats` on multiple containers by name and id against a Linux daemon. <ide> <ide> $ docker stats fervent_panini 5acfcb1b4fd1 <del> CONTAINER CPU % MEM USAGE/LIMIT MEM % NET I/O <add> CONTAINER CPU % MEM USAGE/LIMIT MEM % NET I/O <ide> 5acfcb1b4fd1 0.00% 115.2 MiB/1.045 GiB 11.03% 1.422 kB/648 B <ide> fervent_panini 0.02% 11.08 MiB/1.045 GiB 1.06% 648 B/648 B <ide> <ide> Running `docker stats` on multiple containers by name and id against a Windows d <ide> 3f214c61ad1d nanoserver "cmd" 2 minutes ago Up 2 minutes big_minsky <ide> 9db7aa4d986d windowsservercore "cmd" 2 minutes ago Up 2 minutes mad_wilson <ide> 09d3bb5b1604 windowsservercore "cmd" 2 minutes ago Up 2 minutes affectionate_easley <del> <add> <ide> PS E:\> docker stats 3f214c61ad1d mad_wilson <ide> CONTAINER CPU % PRIV WORKING SET NET I/O BLOCK I/O <ide> 3f214c61ad1d 0.00% 46.25 MiB 76.3 kB / 7.92 kB 10.3 MB / 14.7 MB <del> mad_wilson 9.59% 40.09 MiB 27.6 kB / 8.81 kB 17 MB / 20.1 MB <ide>\ No newline at end of file <add> mad_wilson 9.59% 40.09 MiB 27.6 kB / 8.81 kB 17 MB / 20.1 MB <add> <add>## Formatting <add> <add>The formatting option (`--format`) pretty prints container output <add>using a Go template. <add> <add>Valid placeholders for the Go template are listed below: <add> <add>Placeholder | Description <add>------------ | -------------------------------------------- <add>`.Container` | Container name or ID <add>`.CPUPerc` | CPU percentage <add>`.MemUsage` | Memory usage <add>`.NetIO` | Network IO <add>`.BlockIO` | Block IO <add>`.MemPerc` | Memory percentage (Not available on Windows) <add>`.PIDs` | Number of PIDs (Not available on Windows) <add> <add> <add>When using the `--format` option, the `stats` command either <add>outputs the data exactly as the template declares or, when using the <add>`table` directive, includes column headers as well. <add> <add>The following example uses a template without headers and outputs the <add>`Container` and `CPUPerc` entries separated by a colon for all images: <add> <add>```bash <add>$ docker stats --format "{{.Container}}: {{.CPUPerc}}" <add> <add>09d3bb5b1604: 6.61% <add>9db7aa4d986d: 9.19% <add>3f214c61ad1d: 0.00% <add>``` <add> <add>To list all containers statistics with their name, CPU percentage and memory <add>usage in a table format you can use: <add> <add>```bash <add>$ docker stats --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}" <add> <add>CONTAINER CPU % PRIV WORKING SET <add>1285939c1fd3 0.07% 796 KiB / 64 MiB <add>9c76f7834ae2 0.07% 2.746 MiB / 64 MiB <add>d1ea048f04e4 0.03% 4.583 MiB / 64 MiB <add>``` <ide><path>man/docker-stats.1.md <ide> docker-stats - Display a live stream of one or more containers' resource usage s <ide> [**-a**|**--all**] <ide> [**--help**] <ide> [**--no-stream**] <add>[**--format[="*TEMPLATE*"]**] <ide> [CONTAINER...] <ide> <ide> # DESCRIPTION <ide> Display a live stream of one or more containers' resource usage statistics <ide> **--no-stream**=*true*|*false* <ide> Disable streaming stats and only pull the first result, default setting is false. <ide> <add>**--format**="*TEMPLATE*" <add> Pretty-print containers statistics using a Go template. <add> Valid placeholders: <add> .Container - Container name or ID. <add> .CPUPerc - CPU percentage. <add> .MemUsage - Memory usage. <add> .NetIO - Network IO. <add> .BlockIO - Block IO. <add> .MemPerc - Memory percentage (Not available on Windows). <add> .PIDs - Number of PIDs (Not available on Windows). <add> <ide> # EXAMPLES <ide> <ide> Running `docker stats` on all running containers
3
Java
Java
use elementclass and elementtyperef consistently
08a5196c3ab34d8f8f7cc0f20383d6ba0a114832
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequester.java <ide> public ResponseSpec data(Object data) { <ide> } <ide> <ide> @Override <del> public ResponseSpec data(Object producer, Class<?> elementType) { <add> public ResponseSpec data(Object producer, Class<?> elementClass) { <ide> Assert.notNull(producer, "'producer' must not be null"); <del> Assert.notNull(elementType, "'dataType' must not be null"); <add> Assert.notNull(elementClass, "'elementClass' must not be null"); <ide> ReactiveAdapter adapter = strategies.reactiveAdapterRegistry().getAdapter(producer.getClass()); <ide> Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry"); <del> return toResponseSpec(adapter.toPublisher(producer), ResolvableType.forClass(elementType)); <add> return toResponseSpec(adapter.toPublisher(producer), ResolvableType.forClass(elementClass)); <ide> } <ide> <ide> @Override <del> public ResponseSpec data(Object producer, ParameterizedTypeReference<?> dataTypeRef) { <add> public ResponseSpec data(Object producer, ParameterizedTypeReference<?> elementTypeRef) { <ide> Assert.notNull(producer, "'producer' must not be null"); <del> Assert.notNull(dataTypeRef, "'dataTypeRef' must not be null"); <add> Assert.notNull(elementTypeRef, "'elementTypeRef' must not be null"); <ide> ReactiveAdapter adapter = strategies.reactiveAdapterRegistry().getAdapter(producer.getClass()); <ide> Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry"); <del> return toResponseSpec(adapter.toPublisher(producer), ResolvableType.forType(dataTypeRef)); <add> return toResponseSpec(adapter.toPublisher(producer), ResolvableType.forType(elementTypeRef)); <ide> } <ide> <del> private ResponseSpec toResponseSpec(Object input, ResolvableType dataType) { <add> private ResponseSpec toResponseSpec(Object input, ResolvableType elementType) { <ide> ReactiveAdapter adapter = strategies.reactiveAdapterRegistry().getAdapter(input.getClass()); <ide> Publisher<?> publisher; <ide> if (input instanceof Publisher) { <ide> else if (adapter != null) { <ide> return new DefaultResponseSpec(payloadMono); <ide> } <ide> <del> if (isVoid(dataType) || (adapter != null && adapter.isNoValue())) { <add> if (isVoid(elementType) || (adapter != null && adapter.isNoValue())) { <ide> Mono<Payload> payloadMono = Mono.when(publisher).then(emptyPayload()); <ide> return new DefaultResponseSpec(payloadMono); <ide> } <ide> <del> Encoder<?> encoder = dataType != ResolvableType.NONE && !Object.class.equals(dataType.resolve()) ? <del> strategies.encoder(dataType, dataMimeType) : null; <add> Encoder<?> encoder = elementType != ResolvableType.NONE && !Object.class.equals(elementType.resolve()) ? <add> strategies.encoder(elementType, dataMimeType) : null; <ide> <ide> if (adapter != null && !adapter.isMultiValue()) { <ide> Mono<Payload> payloadMono = Mono.from(publisher) <del> .map(value -> encodeData(value, dataType, encoder)) <add> .map(value -> encodeData(value, elementType, encoder)) <ide> .map(this::firstPayload) <ide> .switchIfEmpty(emptyPayload()); <ide> return new DefaultResponseSpec(payloadMono); <ide> } <ide> <ide> Flux<Payload> payloadFlux = Flux.from(publisher) <del> .map(value -> encodeData(value, dataType, encoder)) <add> .map(value -> encodeData(value, elementType, encoder)) <ide> .switchOnFirst((signal, inner) -> { <ide> DataBuffer data = signal.get(); <ide> if (data != null) { <ide> else if (adapter != null) { <ide> } <ide> <ide> @SuppressWarnings("unchecked") <del> private <T> DataBuffer encodeData(T value, ResolvableType valueType, @Nullable Encoder<?> encoder) { <add> private <T> DataBuffer encodeData(T value, ResolvableType elementType, @Nullable Encoder<?> encoder) { <ide> if (value instanceof DataBuffer) { <ide> return (DataBuffer) value; <ide> } <ide> if (encoder == null) { <del> valueType = ResolvableType.forInstance(value); <del> encoder = strategies.encoder(valueType, dataMimeType); <add> elementType = ResolvableType.forInstance(value); <add> encoder = strategies.encoder(elementType, dataMimeType); <ide> } <ide> return ((Encoder<T>) encoder).encodeValue( <del> value, bufferFactory(), valueType, dataMimeType, EMPTY_HINTS); <add> value, bufferFactory(), elementType, dataMimeType, EMPTY_HINTS); <ide> } <ide> <ide> private Payload firstPayload(DataBuffer data) { <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketRequester.java <ide> interface RequestSpec { <ide> * @param producer the source of payload data value(s). This must be a <ide> * {@link Publisher} or another producer adaptable to a <ide> * {@code Publisher} via {@link ReactiveAdapterRegistry} <del> * @param elementType the type of values to be produced <add> * @param elementClass the type of values to be produced <ide> * @return spec for declaring the expected response <ide> */ <del> ResponseSpec data(Object producer, Class<?> elementType); <add> ResponseSpec data(Object producer, Class<?> elementClass); <ide> <ide> /** <ide> * Alternative of {@link #data(Object, Class)} but with a <ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClient.java <ide> public RequestHeadersSpec<?> body(Object producer, Class<?> elementClass) { <ide> } <ide> <ide> @Override <del> public RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementType) { <del> this.bodySpec.body(producer, elementType); <add> public RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementTypeRef) { <add> this.bodySpec.body(producer, elementTypeRef); <ide> return this; <ide> } <ide> <ide> public <T, S extends Publisher<T>> RequestHeadersSpec<?> body(S publisher, Class <ide> } <ide> <ide> @Override <del> public <T, S extends Publisher<T>> RequestHeadersSpec<?> body(S publisher, ParameterizedTypeReference<T> elementType) { <del> this.bodySpec.body(publisher, elementType); <add> public <T, S extends Publisher<T>> RequestHeadersSpec<?> body(S publisher, ParameterizedTypeReference<T> elementTypeRef) { <add> this.bodySpec.body(publisher, elementTypeRef); <ide> return this; <ide> } <ide> <ide> public BodyContentSpec expectBody() { <ide> } <ide> <ide> @Override <del> public <T> FluxExchangeResult<T> returnResult(Class<T> elementType) { <del> Flux<T> body = this.response.bodyToFlux(elementType); <add> public <T> FluxExchangeResult<T> returnResult(Class<T> elementClass) { <add> Flux<T> body = this.response.bodyToFlux(elementClass); <ide> return new FluxExchangeResult<>(this.exchangeResult, body); <ide> } <ide> <ide> @Override <del> public <T> FluxExchangeResult<T> returnResult(ParameterizedTypeReference<T> elementType) { <del> Flux<T> body = this.response.bodyToFlux(elementType); <add> public <T> FluxExchangeResult<T> returnResult(ParameterizedTypeReference<T> elementTypeRef) { <add> Flux<T> body = this.response.bodyToFlux(elementTypeRef); <ide> return new FluxExchangeResult<>(this.exchangeResult, body); <ide> } <ide> } <ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/WebTestClient.java <ide> interface RequestBodySpec extends RequestHeadersSpec<RequestBodySpec> { <ide> * @param producer the producer to write to the request. This must be a <ide> * {@link Publisher} or another producer adaptable to a <ide> * {@code Publisher} via {@link ReactiveAdapterRegistry} <del> * @param elementType the type reference of elements contained in the producer <add> * @param elementTypeRef the type reference of elements contained in the producer <ide> * @return spec for decoding the response <ide> * @since 5.2 <ide> */ <del> RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementType); <add> RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementTypeRef); <ide> <ide> /** <ide> * Set the body of the request to the given asynchronous {@code Publisher}. <ide> interface RequestBodySpec extends RequestHeadersSpec<RequestBodySpec> { <ide> /** <ide> * Set the body of the request to the given asynchronous {@code Publisher}. <ide> * @param publisher the request body data <del> * @param elementType the type reference of elements contained in the publisher <add> * @param elementTypeRef the type reference of elements contained in the publisher <ide> * @param <T> the type of the elements contained in the publisher <ide> * @param <S> the type of the {@code Publisher} <ide> * @return spec for decoding the response <ide> * @since 5.2 <ide> */ <del> <T, S extends Publisher<T>> RequestHeadersSpec<?> body(S publisher, ParameterizedTypeReference<T> elementType); <add> <T, S extends Publisher<T>> RequestHeadersSpec<?> body(S publisher, ParameterizedTypeReference<T> elementTypeRef); <ide> <ide> /** <ide> * Set the body of the request to the given {@code BodyInserter}. <ide> interface ResponseSpec { <ide> * {@code expectBody(Void.class)} which ensures that resources are <ide> * released regardless of whether the response has content or not. <ide> */ <del> <T> FluxExchangeResult<T> returnResult(Class<T> elementType); <add> <T> FluxExchangeResult<T> returnResult(Class<T> elementClass); <ide> <ide> /** <ide> * Alternative to {@link #returnResult(Class)} that accepts information <ide> * about a target type with generics. <ide> */ <del> <T> FluxExchangeResult<T> returnResult(ParameterizedTypeReference<T> elementType); <add> <T> FluxExchangeResult<T> returnResult(ParameterizedTypeReference<T> elementTypeRef); <ide> } <ide> <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyExtractors.java <ide> public static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(Class< <ide> <ide> /** <ide> * Variant of {@link #toMono(Class)} for type information with generics. <del> * @param typeRef the type reference for the type to decode to <add> * @param elementTypeRef the type reference for the type to decode to <ide> * @param <T> the element type to decode to <ide> * @return {@code BodyExtractor} for {@code Mono<T>} <ide> */ <del> public static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(ParameterizedTypeReference<T> typeRef) { <del> return toMono(ResolvableType.forType(typeRef.getType())); <add> public static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(ParameterizedTypeReference<T> elementTypeRef) { <add> return toMono(ResolvableType.forType(elementTypeRef.getType())); <ide> } <ide> <ide> private static <T> BodyExtractor<Mono<T>, ReactiveHttpInputMessage> toMono(ResolvableType elementType) { <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java <ide> public static <T> BodyInserter<T, ReactiveHttpOutputMessage> empty() { <ide> * @see #fromProducer(Object, Class) <ide> */ <ide> public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromObject(T body) { <del> Assert.notNull(body, "Body must not be null"); <add> Assert.notNull(body, "'body' must not be null"); <ide> Assert.isNull(registry.getAdapter(body.getClass()), "'body' should be an object, for reactive types use a variant specifying a publisher/producer and its related element type"); <ide> return (message, context) -> <ide> writeWithMessageWriters(message, context, Mono.just(body), ResolvableType.forInstance(body), null); <ide> public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromObject(T body) <ide> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse}. <ide> * @param <T> the type of the body <ide> * @param producer the source of body value(s). <del> * @param elementClass the type of values to be produced <add> * @param elementClass the class of values to be produced <ide> * @return the inserter to write a producer <ide> * @since 5.2 <ide> */ <ide> public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromProducer(T prod <ide> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse}. <ide> * @param <T> the type of the body <ide> * @param producer the source of body value(s). <del> * @param elementType the type of values to be produced <add> * @param elementTypeRef the type of values to be produced <ide> * @return the inserter to write a producer <ide> * @since 5.2 <ide> */ <del> public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromProducer(T producer, ParameterizedTypeReference<?> elementType) { <add> public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromProducer(T producer, <add> ParameterizedTypeReference<?> elementTypeRef) { <ide> Assert.notNull(producer, "'producer' must not be null"); <del> Assert.notNull(elementType, "'elementType' must not be null"); <add> Assert.notNull(elementTypeRef, "'elementTypeRef' must not be null"); <ide> ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(producer.getClass()); <ide> Assert.notNull(adapter, "'producer' type is unknown to ReactiveAdapterRegistry"); <ide> return (message, context) -> <del> writeWithMessageWriters(message, context, producer, ResolvableType.forType(elementType), adapter); <add> writeWithMessageWriters(message, context, producer, ResolvableType.forType(elementTypeRef), adapter); <ide> } <ide> <ide> /** <ide> public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromProducer(T prod <ide> * {@link org.springframework.web.reactive.function.client.WebClient WebClient} and <ide> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse}. <ide> * @param publisher the publisher to write with <del> * @param elementClass the type of elements in the publisher <add> * @param elementClass the class of elements in the publisher <ide> * @param <T> the type of the elements contained in the publisher <ide> * @param <P> the {@code Publisher} type <ide> * @return the inserter to write a {@code Publisher} <ide> */ <ide> public static <T, P extends Publisher<T>> BodyInserter<P, ReactiveHttpOutputMessage> fromPublisher( <ide> P publisher, Class<T> elementClass) { <ide> <del> Assert.notNull(publisher, "Publisher must not be null"); <del> Assert.notNull(elementClass, "Element Class must not be null"); <add> Assert.notNull(publisher, "'publisher' must not be null"); <add> Assert.notNull(elementClass, "'elementClass' must not be null"); <ide> return (message, context) -> <ide> writeWithMessageWriters(message, context, publisher, ResolvableType.forClass(elementClass), null); <ide> } <ide> public static <T, P extends Publisher<T>> BodyInserter<P, ReactiveHttpOutputMess <ide> * {@link org.springframework.web.reactive.function.client.WebClient WebClient} and <ide> * {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse}. <ide> * @param publisher the publisher to write with <del> * @param typeReference the type of elements contained in the publisher <add> * @param elementTypeRef the type of elements contained in the publisher <ide> * @param <T> the type of the elements contained in the publisher <ide> * @param <P> the {@code Publisher} type <ide> * @return the inserter to write a {@code Publisher} <ide> */ <ide> public static <T, P extends Publisher<T>> BodyInserter<P, ReactiveHttpOutputMessage> fromPublisher( <del> P publisher, ParameterizedTypeReference<T> typeReference) { <add> P publisher, ParameterizedTypeReference<T> elementTypeRef) { <ide> <del> Assert.notNull(publisher, "Publisher must not be null"); <del> Assert.notNull(typeReference, "ParameterizedTypeReference must not be null"); <add> Assert.notNull(publisher, "'publisher' must not be null"); <add> Assert.notNull(elementTypeRef, "'elementTypeRef' must not be null"); <ide> return (message, context) -> <del> writeWithMessageWriters(message, context, publisher, ResolvableType.forType(typeReference.getType()), null); <add> writeWithMessageWriters(message, context, publisher, ResolvableType.forType(elementTypeRef.getType()), null); <ide> } <ide> <ide> /** <ide> public static <T, P extends Publisher<T>> BodyInserter<P, ReactiveHttpOutputMess <ide> * @return the inserter to write a {@code Publisher} <ide> */ <ide> public static <T extends Resource> BodyInserter<T, ReactiveHttpOutputMessage> fromResource(T resource) { <del> Assert.notNull(resource, "Resource must not be null"); <add> Assert.notNull(resource, "'resource' must not be null"); <ide> return (outputMessage, context) -> { <ide> ResolvableType elementType = RESOURCE_TYPE; <ide> HttpMessageWriter<Resource> writer = findWriter(context, elementType, null); <ide> public static <T extends Resource> BodyInserter<T, ReactiveHttpOutputMessage> fr <ide> public static <T, S extends Publisher<ServerSentEvent<T>>> BodyInserter<S, ServerHttpResponse> fromServerSentEvents( <ide> S eventsPublisher) { <ide> <del> Assert.notNull(eventsPublisher, "Publisher must not be null"); <add> Assert.notNull(eventsPublisher, "'eventsPublisher' must not be null"); <ide> return (serverResponse, context) -> { <ide> ResolvableType elementType = SSE_TYPE; <ide> MediaType mediaType = MediaType.TEXT_EVENT_STREAM; <ide> public static <T, P extends Publisher<T>> MultipartInserter fromMultipartAsyncDa <ide> public static <T extends Publisher<DataBuffer>> BodyInserter<T, ReactiveHttpOutputMessage> fromDataBuffers( <ide> T publisher) { <ide> <del> Assert.notNull(publisher, "Publisher must not be null"); <add> Assert.notNull(publisher, "'publisher' must not be null"); <ide> return (outputMessage, context) -> outputMessage.writeWith(publisher); <ide> } <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientResponse.java <ide> public interface ClientResponse { <ide> <ide> /** <ide> * Extract the body to a {@code Mono}. <del> * @param typeReference a type reference describing the expected response body type <add> * @param elementTypeRef the type reference of element in the {@code Mono} <ide> * @param <T> the element type <ide> * @return a mono containing the body of the given type {@code T} <ide> */ <del> <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> typeReference); <add> <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> elementTypeRef); <ide> <ide> /** <ide> * Extract the body to a {@code Flux}. <del> * @param elementClass the class of element in the {@code Flux} <add> * @param elementClass the class of elements in the {@code Flux} <ide> * @param <T> the element type <ide> * @return a flux containing the body of the given type {@code T} <ide> */ <ide> <T> Flux<T> bodyToFlux(Class<? extends T> elementClass); <ide> <ide> /** <ide> * Extract the body to a {@code Flux}. <del> * @param typeReference a type reference describing the expected response body type <add> * @param elementTypeRef the type reference of elements in the {@code Flux} <ide> * @param <T> the element type <ide> * @return a flux containing the body of the given type {@code T} <ide> */ <del> <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> typeReference); <add> <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> elementTypeRef); <ide> <ide> /** <ide> * Return this response as a delayed {@code ResponseEntity}. <del> * @param bodyType the expected response body type <add> * @param bodyClass the expected response body type <ide> * @param <T> response body type <ide> * @return {@code Mono} with the {@code ResponseEntity} <ide> */ <del> <T> Mono<ResponseEntity<T>> toEntity(Class<T> bodyType); <add> <T> Mono<ResponseEntity<T>> toEntity(Class<T> bodyClass); <ide> <ide> /** <ide> * Return this response as a delayed {@code ResponseEntity}. <del> * @param typeReference a type reference describing the expected response body type <add> * @param bodyTypeReference a type reference describing the expected response body type <ide> * @param <T> response body type <ide> * @return {@code Mono} with the {@code ResponseEntity} <ide> */ <del> <T> Mono<ResponseEntity<T>> toEntity(ParameterizedTypeReference<T> typeReference); <add> <T> Mono<ResponseEntity<T>> toEntity(ParameterizedTypeReference<T> bodyTypeReference); <ide> <ide> /** <ide> * Return this response as a delayed list of {@code ResponseEntity}s. <del> * @param elementType the expected response body list element type <add> * @param elementClass the expected response body list element class <ide> * @param <T> the type of elements in the list <ide> * @return {@code Mono} with the list of {@code ResponseEntity}s <ide> */ <del> <T> Mono<ResponseEntity<List<T>>> toEntityList(Class<T> elementType); <add> <T> Mono<ResponseEntity<List<T>>> toEntityList(Class<T> elementClass); <ide> <ide> /** <ide> * Return this response as a delayed list of {@code ResponseEntity}s. <del> * @param typeReference a type reference describing the expected response body type <add> * @param elementTypeRef the expected response body list element reference type <ide> * @param <T> the type of elements in the list <ide> * @return {@code Mono} with the list of {@code ResponseEntity}s <ide> */ <del> <T> Mono<ResponseEntity<List<T>>> toEntityList(ParameterizedTypeReference<T> typeReference); <add> <T> Mono<ResponseEntity<List<T>>> toEntityList(ParameterizedTypeReference<T> elementTypeRef); <ide> <ide> <ide> // Static builder methods <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponse.java <ide> public <T> Mono<T> bodyToMono(Class<? extends T> elementClass) { <ide> } <ide> <ide> @Override <del> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> typeReference) { <del> return body(BodyExtractors.toMono(typeReference)); <add> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> elementTypeRef) { <add> return body(BodyExtractors.toMono(elementTypeRef)); <ide> } <ide> <ide> @Override <ide> public <T> Flux<T> bodyToFlux(Class<? extends T> elementClass) { <ide> } <ide> <ide> @Override <del> public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> typeReference) { <del> return body(BodyExtractors.toFlux(typeReference)); <add> public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> elementTypeRef) { <add> return body(BodyExtractors.toFlux(elementTypeRef)); <ide> } <ide> <ide> @Override <ide> public <T> Mono<ResponseEntity<T>> toEntity(Class<T> bodyType) { <ide> } <ide> <ide> @Override <del> public <T> Mono<ResponseEntity<T>> toEntity(ParameterizedTypeReference<T> typeReference) { <del> return toEntityInternal(bodyToMono(typeReference)); <add> public <T> Mono<ResponseEntity<T>> toEntity(ParameterizedTypeReference<T> bodyTypeReference) { <add> return toEntityInternal(bodyToMono(bodyTypeReference)); <ide> } <ide> <ide> private <T> Mono<ResponseEntity<T>> toEntityInternal(Mono<T> bodyMono) { <ide> private <T> Mono<ResponseEntity<T>> toEntityInternal(Mono<T> bodyMono) { <ide> } <ide> <ide> @Override <del> public <T> Mono<ResponseEntity<List<T>>> toEntityList(Class<T> responseType) { <del> return toEntityListInternal(bodyToFlux(responseType)); <add> public <T> Mono<ResponseEntity<List<T>>> toEntityList(Class<T> elementClass) { <add> return toEntityListInternal(bodyToFlux(elementClass)); <ide> } <ide> <ide> @Override <del> public <T> Mono<ResponseEntity<List<T>>> toEntityList(ParameterizedTypeReference<T> typeReference) { <del> return toEntityListInternal(bodyToFlux(typeReference)); <add> public <T> Mono<ResponseEntity<List<T>>> toEntityList(ParameterizedTypeReference<T> elementTypeRef) { <add> return toEntityListInternal(bodyToFlux(elementTypeRef)); <ide> } <ide> <ide> private <T> Mono<ResponseEntity<List<T>>> toEntityListInternal(Flux<T> bodyFlux) { <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClient.java <ide> public RequestHeadersSpec<?> body(Object producer, Class<?> elementClass) { <ide> } <ide> <ide> @Override <del> public RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementType) { <del> this.inserter = BodyInserters.fromProducer(producer, elementType); <add> public RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementTypeRef) { <add> this.inserter = BodyInserters.fromProducer(producer, elementTypeRef); <ide> return this; <ide> } <ide> <ide> @Override <ide> public <T, P extends Publisher<T>> RequestHeadersSpec<?> body( <del> P publisher, ParameterizedTypeReference<T> elementType) { <del> this.inserter = BodyInserters.fromPublisher(publisher, elementType); <add> P publisher, ParameterizedTypeReference<T> elementTypeRef) { <add> this.inserter = BodyInserters.fromPublisher(publisher, elementTypeRef); <ide> return this; <ide> } <ide> <ide> public ResponseSpec onStatus(Predicate<HttpStatus> statusPredicate, <ide> } <ide> <ide> @Override <del> public <T> Mono<T> bodyToMono(Class<T> bodyType) { <add> public <T> Mono<T> bodyToMono(Class<T> elementClass) { <ide> return this.responseMono.flatMap(response -> handleBody(response, <del> response.bodyToMono(bodyType), mono -> mono.flatMap(Mono::error))); <add> response.bodyToMono(elementClass), mono -> mono.flatMap(Mono::error))); <ide> } <ide> <ide> @Override <del> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> bodyType) { <add> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> elementTypeRef) { <ide> return this.responseMono.flatMap(response -> <del> handleBody(response, response.bodyToMono(bodyType), mono -> mono.flatMap(Mono::error))); <add> handleBody(response, response.bodyToMono(elementTypeRef), mono -> mono.flatMap(Mono::error))); <ide> } <ide> <ide> @Override <del> public <T> Flux<T> bodyToFlux(Class<T> elementType) { <add> public <T> Flux<T> bodyToFlux(Class<T> elementClass) { <ide> return this.responseMono.flatMapMany(response -> <del> handleBody(response, response.bodyToFlux(elementType), mono -> mono.handle((t, sink) -> sink.error(t)))); <add> handleBody(response, response.bodyToFlux(elementClass), mono -> mono.handle((t, sink) -> sink.error(t)))); <ide> } <ide> <ide> @Override <del> public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> elementType) { <add> public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> elementTypeRef) { <ide> return this.responseMono.flatMapMany(response -> <del> handleBody(response, response.bodyToFlux(elementType), mono -> mono.handle((t, sink) -> sink.error(t)))); <add> handleBody(response, response.bodyToFlux(elementTypeRef), mono -> mono.handle((t, sink) -> sink.error(t)))); <ide> } <ide> <ide> private <T extends Publisher<?>> T handleBody(ClientResponse response, <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClient.java <ide> interface RequestBodySpec extends RequestHeadersSpec<RequestBodySpec> { <ide> * @param producer the producer to write to the request. This must be a <ide> * {@link Publisher} or another producer adaptable to a <ide> * {@code Publisher} via {@link ReactiveAdapterRegistry} <del> * @param elementType the type reference of elements contained in the producer <add> * @param elementTypeRef the type reference of elements contained in the producer <ide> * @return this builder <ide> * @since 5.2 <ide> */ <del> RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementType); <add> RequestHeadersSpec<?> body(Object producer, ParameterizedTypeReference<?> elementTypeRef); <ide> <ide> /** <ide> * A shortcut for {@link #body(BodyInserter)} with a <ide> interface RequestBodySpec extends RequestHeadersSpec<RequestBodySpec> { <ide> * element type information that includes generics via a <ide> * {@link ParameterizedTypeReference}. <ide> * @param publisher the {@code Publisher} to write to the request <del> * @param elementType the type reference of elements contained in the publisher <add> * @param elementTypeRef the type reference of elements contained in the publisher <ide> * @param <T> the type of the elements contained in the publisher <ide> * @param <P> the type of the {@code Publisher} <ide> * @return this builder <ide> */ <ide> <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher, <del> ParameterizedTypeReference<T> elementType); <add> ParameterizedTypeReference<T> elementTypeRef); <ide> <ide> /** <ide> * Set the body of the request using the given body inserter. <ide> ResponseSpec onStatus(Predicate<HttpStatus> statusPredicate, <ide> * Extract the body to a {@code Mono}. By default, if the response has status code 4xx or <ide> * 5xx, the {@code Mono} will contain a {@link WebClientException}. This can be overridden <ide> * with {@link #onStatus(Predicate, Function)}. <del> * @param bodyType the expected response body type <add> * @param elementClass the expected response body element class <ide> * @param <T> response body type <ide> * @return a mono containing the body, or a {@link WebClientResponseException} if the <ide> * status code is 4xx or 5xx <ide> */ <del> <T> Mono<T> bodyToMono(Class<T> bodyType); <add> <T> Mono<T> bodyToMono(Class<T> elementClass); <ide> <ide> /** <ide> * Extract the body to a {@code Mono}. By default, if the response has status code 4xx or <ide> * 5xx, the {@code Mono} will contain a {@link WebClientException}. This can be overridden <ide> * with {@link #onStatus(Predicate, Function)}. <del> * @param typeReference a type reference describing the expected response body type <add> * @param elementTypeRef a type reference describing the expected response body element type <ide> * @param <T> response body type <ide> * @return a mono containing the body, or a {@link WebClientResponseException} if the <ide> * status code is 4xx or 5xx <ide> */ <del> <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> typeReference); <add> <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> elementTypeRef); <ide> <ide> /** <ide> * Extract the body to a {@code Flux}. By default, if the response has status code 4xx or <ide> * 5xx, the {@code Flux} will contain a {@link WebClientException}. This can be overridden <ide> * with {@link #onStatus(Predicate, Function)}. <del> * @param elementType the type of element in the response <add> * @param elementClass the class of elements in the response <ide> * @param <T> the type of elements in the response <ide> * @return a flux containing the body, or a {@link WebClientResponseException} if the <ide> * status code is 4xx or 5xx <ide> */ <del> <T> Flux<T> bodyToFlux(Class<T> elementType); <add> <T> Flux<T> bodyToFlux(Class<T> elementClass); <ide> <ide> /** <ide> * Extract the body to a {@code Flux}. By default, if the response has status code 4xx or <ide> * 5xx, the {@code Flux} will contain a {@link WebClientException}. This can be overridden <ide> * with {@link #onStatus(Predicate, Function)}. <del> * @param typeReference a type reference describing the expected response body type <add> * @param elementTypeRef a type reference describing the expected response body element type <ide> * @param <T> the type of elements in the response <ide> * @return a flux containing the body, or a {@link WebClientResponseException} if the <ide> * status code is 4xx or 5xx <ide> */ <del> <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> typeReference); <add> <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> elementTypeRef); <ide> <ide> } <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/support/ClientResponseWrapper.java <ide> public <T> Mono<T> bodyToMono(Class<? extends T> elementClass) { <ide> } <ide> <ide> @Override <del> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> typeReference) { <del> return this.delegate.bodyToMono(typeReference); <add> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> elementTypeRef) { <add> return this.delegate.bodyToMono(elementTypeRef); <ide> } <ide> <ide> @Override <ide> public <T> Flux<T> bodyToFlux(Class<? extends T> elementClass) { <ide> } <ide> <ide> @Override <del> public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> typeReference) { <del> return this.delegate.bodyToFlux(typeReference); <add> public <T> Flux<T> bodyToFlux(ParameterizedTypeReference<T> elementTypeRef) { <add> return this.delegate.bodyToFlux(elementTypeRef); <ide> } <ide> <ide> @Override <ide> public <T> Mono<ResponseEntity<T>> toEntity(Class<T> bodyType) { <ide> } <ide> <ide> @Override <del> public <T> Mono<ResponseEntity<T>> toEntity(ParameterizedTypeReference<T> typeReference) { <del> return this.delegate.toEntity(typeReference); <add> public <T> Mono<ResponseEntity<T>> toEntity(ParameterizedTypeReference<T> bodyTypeReference) { <add> return this.delegate.toEntity(bodyTypeReference); <ide> } <ide> <ide> @Override <del> public <T> Mono<ResponseEntity<List<T>>> toEntityList(Class<T> elementType) { <del> return this.delegate.toEntityList(elementType); <add> public <T> Mono<ResponseEntity<List<T>>> toEntityList(Class<T> elementClass) { <add> return this.delegate.toEntityList(elementClass); <ide> } <ide> <ide> @Override <del> public <T> Mono<ResponseEntity<List<T>>> toEntityList(ParameterizedTypeReference<T> typeReference) { <del> return this.delegate.toEntityList(typeReference); <add> public <T> Mono<ResponseEntity<List<T>>> toEntityList(ParameterizedTypeReference<T> elementTypeRef) { <add> return this.delegate.toEntityList(elementTypeRef); <ide> } <ide> <ide> /** <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultServerResponseBuilder.java <ide> public Mono<ServerResponse> body(Object producer, Class<?> elementClass) { <ide> } <ide> <ide> @Override <del> public Mono<ServerResponse> body(Object producer, ParameterizedTypeReference<?> elementType) { <add> public Mono<ServerResponse> body(Object producer, ParameterizedTypeReference<?> elementTypeRef) { <ide> return new DefaultEntityResponseBuilder<>(producer, <del> BodyInserters.fromProducer(producer, elementType)) <add> BodyInserters.fromProducer(producer, elementTypeRef)) <ide> .status(this.statusCode) <ide> .headers(this.headers) <ide> .cookies(cookies -> cookies.addAll(this.cookies)) <ide> public <T, P extends Publisher<T>> Mono<ServerResponse> body(P publisher, Class< <ide> <ide> @Override <ide> public <T, P extends Publisher<T>> Mono<ServerResponse> body(P publisher, <del> ParameterizedTypeReference<T> elementType) { <add> ParameterizedTypeReference<T> elementTypeRef) { <ide> return new DefaultEntityResponseBuilder<>(publisher, <del> BodyInserters.fromPublisher(publisher, elementType)) <add> BodyInserters.fromPublisher(publisher, elementTypeRef)) <ide> .status(this.statusCode) <ide> .headers(this.headers) <ide> .cookies(cookies -> cookies.addAll(this.cookies)) <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ServerResponse.java <ide> interface BodyBuilder extends HeadersBuilder<BodyBuilder> { <ide> * @param producer the producer to write to the response. This must be a <ide> * {@link Publisher} or another producer adaptable to a <ide> * {@code Publisher} via {@link ReactiveAdapterRegistry} <del> * @param typeReference a type reference describing the elements contained in the producer <add> * @param elementTypeRef a type reference describing the elements contained in the producer <ide> * @return the built response <ide> * @since 5.2 <ide> */ <del> Mono<ServerResponse> body(Object producer, ParameterizedTypeReference<?> typeReference); <add> Mono<ServerResponse> body(Object producer, ParameterizedTypeReference<?> elementTypeRef); <ide> <ide> /** <ide> * Set the body of the response to the given asynchronous {@code Publisher} and return it. <ide> interface BodyBuilder extends HeadersBuilder<BodyBuilder> { <ide> * This convenience method combines {@link #body(BodyInserter)} and <ide> * {@link BodyInserters#fromPublisher(Publisher, ParameterizedTypeReference)}. <ide> * @param publisher the {@code Publisher} to write to the response <del> * @param typeReference a type reference describing the elements contained in the publisher <add> * @param elementTypeRef a type reference describing the elements contained in the publisher <ide> * @param <T> the type of the elements contained in the publisher <ide> * @param <P> the type of the {@code Publisher} <ide> * @return the built response <ide> */ <ide> <T, P extends Publisher<T>> Mono<ServerResponse> body(P publisher, <del> ParameterizedTypeReference<T> typeReference); <add> ParameterizedTypeReference<T> elementTypeRef); <ide> <ide> /** <ide> * Set the body of the response to the given {@code BodyInserter} and return it.
13
Javascript
Javascript
add a resolver setter to local lookup test case
5d01bb0de2b0457995f348861c455bc7638e4b3f
<ide><path>packages/ember-glimmer/tests/integration/components/local-lookup-test.js <ide> if (EMBER_MODULE_UNIFICATION) { <ide> get resolver() { <ide> return this.owner.__registry__.fallback.resolver; <ide> } <add> set resolver(resolver) { <add> // `resolver` needs a setter because RenderingTestCase sets `resolver` in <add> // its constructor <add> } <ide> <ide> getResolver() { <ide> return new LocalLookupTestResolver();
1
Javascript
Javascript
convert `stattimer` to an es6 class
50b72dec6e3f0a959927f6ac1fcf69b7c76c7caf
<ide><path>src/display/dom_utils.js <ide> function isExternalLinkTargetSet() { <ide> } <ide> } <ide> <del>var StatTimer = (function StatTimerClosure() { <del> function rpad(str, pad, length) { <del> while (str.length < length) { <del> str += pad; <del> } <del> return str; <del> } <del> function StatTimer() { <add>class StatTimer { <add> constructor(enable = true) { <ide> this.started = Object.create(null); <ide> this.times = []; <del> this.enabled = true; <add> this.enabled = !!enable; <ide> } <del> StatTimer.prototype = { <del> time: function StatTimer_time(name) { <del> if (!this.enabled) { <del> return; <del> } <del> if (name in this.started) { <del> warn('Timer is already running for ' + name); <del> } <del> this.started[name] = Date.now(); <del> }, <del> timeEnd: function StatTimer_timeEnd(name) { <del> if (!this.enabled) { <del> return; <del> } <del> if (!(name in this.started)) { <del> warn('Timer has not been started for ' + name); <del> } <del> this.times.push({ <del> 'name': name, <del> 'start': this.started[name], <del> 'end': Date.now(), <del> }); <del> // Remove timer from started so it can be called again. <del> delete this.started[name]; <del> }, <del> toString: function StatTimer_toString() { <del> var i, ii; <del> var times = this.times; <del> var out = ''; <del> // Find the longest name for padding purposes. <del> var longest = 0; <del> for (i = 0, ii = times.length; i < ii; ++i) { <del> var name = times[i]['name']; <del> if (name.length > longest) { <del> longest = name.length; <del> } <del> } <del> for (i = 0, ii = times.length; i < ii; ++i) { <del> var span = times[i]; <del> var duration = span.end - span.start; <del> out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; <add> <add> time(name) { <add> if (!this.enabled) { <add> return; <add> } <add> if (name in this.started) { <add> warn('Timer is already running for ' + name); <add> } <add> this.started[name] = Date.now(); <add> } <add> <add> timeEnd(name) { <add> if (!this.enabled) { <add> return; <add> } <add> if (!(name in this.started)) { <add> warn('Timer has not been started for ' + name); <add> } <add> this.times.push({ <add> 'name': name, <add> 'start': this.started[name], <add> 'end': Date.now(), <add> }); <add> // Remove timer from started so it can be called again. <add> delete this.started[name]; <add> } <add> <add> toString() { <add> let times = this.times; <add> // Find the longest name for padding purposes. <add> let out = '', longest = 0; <add> for (let i = 0, ii = times.length; i < ii; ++i) { <add> let name = times[i]['name']; <add> if (name.length > longest) { <add> longest = name.length; <ide> } <del> return out; <del> }, <del> }; <del> return StatTimer; <del>})(); <add> } <add> for (let i = 0, ii = times.length; i < ii; ++i) { <add> let span = times[i]; <add> let duration = span.end - span.start; <add> out += `${span['name'].padEnd(longest)} ${duration}ms\n`; <add> } <add> return out; <add> } <add>} <ide> <ide> export { <ide> CustomStyle,
1
Text
Text
use the right function name for combinereducers
9da19b91357bb440b04c541e0df4bbaddcab54e9
<ide><path>docs/api/combineReducers.md <ide> Any reducer passed to `combineReducers` must satisfy these rules: <ide> <ide> * If the `state` given to it is `undefined`, it must return the initial state for this specific reducer. According to the previous rule, the initial state must not be `undefined` either. It is handy to specify it with ES6 optional arguments syntax, but you can also explicitly check the first argument for being `undefined`. <ide> <del>While `combineReducers` attempts to check that your reducers conform to some of these rules, you should remember them, and do your best to follow them. `combineReducers` will check your reducers by passing `undefined` to them; this is done even if you specify initial state to `Redux.createStore(combinedReducers(...), initialState)`. Therefore, you **must** ensure your reducers work properly when receiving `undefined` as state, even if you never intend for them to actually receive `undefined` in your own code. <add>While `combineReducers` attempts to check that your reducers conform to some of these rules, you should remember them, and do your best to follow them. `combineReducers` will check your reducers by passing `undefined` to them; this is done even if you specify initial state to `Redux.createStore(combineReducers(...), initialState)`. Therefore, you **must** ensure your reducers work properly when receiving `undefined` as state, even if you never intend for them to actually receive `undefined` in your own code. <ide> <ide> #### Example <ide>
1
Ruby
Ruby
use libexec method in install test
b34fa6cfd870e23c3876394509ed0a5be6c70b1e
<ide><path>Library/Homebrew/test/test_formula_install.rb <ide> def test_a_basic_install <ide> assert_predicate f.bin, :directory? <ide> assert_equal 3, f.bin.children.length <ide> <del> libexec = f.prefix+'libexec' <del> assert_predicate libexec, :directory? <del> assert_equal 1, libexec.children.length <add> assert_predicate f.libexec, :directory? <add> assert_equal 1, f.libexec.children.length <ide> <ide> refute_predicate f.prefix+'main.c', :exist? <ide> assert_predicate f, :installed?
1
Python
Python
move guardian imports out of compat
9b8af04e7fe532d0bd373d0d1875cf1748bdadf5
<ide><path>rest_framework/compat.py <ide> def distinct(queryset, base): <ide> requests = None <ide> <ide> <del># Django-guardian is optional. Import only if guardian is in INSTALLED_APPS <del># Fixes (#1712). We keep the try/except for the test suite. <del>guardian = None <del>try: <del> if 'guardian' in settings.INSTALLED_APPS: <del> import guardian # noqa <del>except ImportError: <del> pass <add>def is_guardian_installed(): <add> """ <add> django-guardian is optional and only imported if in INSTALLED_APPS. <add> """ <add> return 'guardian' in settings.INSTALLED_APPS <ide> <ide> <ide> # PATCH method is not implemented by Django <ide><path>rest_framework/filters.py <ide> from django.utils.encoding import force_text <ide> from django.utils.translation import ugettext_lazy as _ <ide> <del>from rest_framework.compat import coreapi, coreschema, distinct, guardian <add>from rest_framework.compat import ( <add> coreapi, coreschema, distinct, is_guardian_installed <add>) <ide> from rest_framework.settings import api_settings <ide> <ide> <ide> class DjangoObjectPermissionsFilter(BaseFilterBackend): <ide> has read object level permissions. <ide> """ <ide> def __init__(self): <del> assert guardian, 'Using DjangoObjectPermissionsFilter, but django-guardian is not installed' <add> assert is_guardian_installed(), 'Using DjangoObjectPermissionsFilter, but django-guardian is not installed' <ide> <ide> perm_format = '%(app_label)s.view_%(model_name)s' <ide> <ide> def filter_queryset(self, request, queryset, view): <ide> # We want to defer this import until run-time, rather than import-time. <ide> # See https://github.com/encode/django-rest-framework/issues/4608 <ide> # (Also see #1624 for why we need to make this import explicitly) <add> from guardian import VERSION as guardian_version <ide> from guardian.shortcuts import get_objects_for_user <ide> <ide> extra = {} <ide> def filter_queryset(self, request, queryset, view): <ide> 'model_name': model_cls._meta.model_name <ide> } <ide> permission = self.perm_format % kwargs <del> if tuple(guardian.VERSION) >= (1, 3): <add> if tuple(guardian_version) >= (1, 3): <ide> # Maintain behavior compatibility with versions prior to 1.3 <ide> extra = {'accept_global_perms': False} <ide> else: <ide><path>tests/test_permissions.py <ide> HTTP_HEADER_ENCODING, authentication, generics, permissions, serializers, <ide> status, views <ide> ) <del>from rest_framework.compat import guardian <add>from rest_framework.compat import is_guardian_installed <ide> from rest_framework.filters import DjangoObjectPermissionsFilter <ide> from rest_framework.routers import DefaultRouter <ide> from rest_framework.test import APIRequestFactory <ide> def get_queryset(self): <ide> get_queryset_object_permissions_view = GetQuerysetObjectPermissionInstanceView.as_view() <ide> <ide> <del>@unittest.skipUnless(guardian, 'django-guardian not installed') <add>@unittest.skipUnless(is_guardian_installed(), 'django-guardian not installed') <ide> class ObjectPermissionsIntegrationTests(TestCase): <ide> """ <ide> Integration tests for the object level permissions API.
3
Mixed
Ruby
improve security of untyped bound values
1dc69cab761fbfd46142f70d8ea58a41c6a12c12
<ide><path>activerecord/CHANGELOG.md <add>* The MySQL adapter now cast numbers and booleans bind parameters to to string for safety reasons. <add> <add> When comparing a string and a number in a query, MySQL convert the string to a number. So for <add> instance `"foo" = 0`, will implicitly cast `"foo"` to `0` and will evaluate to `TRUE` which can <add> lead to security vulnerabilities. <add> <add> Active Record already protect against that vulnerability when it knows the type of the column <add> being compared, however until now it was still vulnerable when using bind parameters: <add> <add> ```ruby <add> User.where("login_token = ?", 0).first <add> ``` <add> <add> Would perform: <add> <add> ```sql <add> SELECT * FROM `users` WHERE `login_token` = 0 LIMIT 1; <add> ``` <add> <add> Now it will perform: <add> <add> ```sql <add> SELECT * FROM `users` WHERE `login_token` = '0' LIMIT 1; <add> ``` <add> <add> *Jean Boussier* <add> <ide> * Fixture configurations (`_fixture`) are now strictly validated. <ide> <ide> If an error will be raised if that entry contains unknown keys while previously it <ide><path>activerecord/lib/active_record/connection_adapters/abstract/quoting.rb <ide> def type_cast(value, column = nil) <ide> _type_cast(value) <ide> end <ide> <add> # Quote a value to be used as a bound parameter of unknown type. For example, <add> # MySQL might perform dangerous castings when comparing a string to a number, <add> # so this method will cast numbers to string. <add> def quote_bound_value(value) <add> _quote(value) <add> end <add> <ide> # If you are having to call this function, you are likely doing something <ide> # wrong. The column does not have sufficient type information if the user <ide> # provided a custom type on the class level either explicitly (via <ide><path>activerecord/lib/active_record/connection_adapters/mysql/quoting.rb <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> module MySQL <ide> module Quoting # :nodoc: <add> def quote_bound_value(value) <add> case value <add> when Numeric <add> _quote(value.to_s) <add> when BigDecimal <add> _quote(value.to_s("F")) <add> when true <add> "'1'" <add> when false <add> "'0'" <add> else <add> _quote(value) <add> end <add> end <add> <ide> def quote_column_name(name) <ide> self.class.quoted_column_names[name] ||= "`#{super.gsub('`', '``')}`" <ide> end <ide><path>activerecord/lib/active_record/sanitization.rb <ide> def quote_bound_value(value, c = connection) <ide> if value.respond_to?(:map) && !value.acts_like?(:string) <ide> values = value.map { |v| v.respond_to?(:id_for_database) ? v.id_for_database : v } <ide> if values.empty? <del> c.quote(nil) <add> c.quote_bound_value(nil) <ide> else <del> values.map! { |v| c.quote(v) }.join(",") <add> values.map! { |v| c.quote_bound_value(v) }.join(",") <ide> end <ide> else <ide> value = value.id_for_database if value.respond_to?(:id_for_database) <del> c.quote(value) <add> c.quote_bound_value(value) <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/adapters/mysql2/quoting_test.rb <add># frozen_string_literal: true <add> <add>require "cases/helper" <add> <add>class Mysql2QuotingTest < ActiveRecord::Mysql2TestCase <add> def setup <add> super <add> @conn = ActiveRecord::Base.connection <add> end <add> <add> def test_quote_bound_integer <add> assert_equal "'42'", @conn.quote_bound_value(42) <add> end <add> <add> def test_quote_bound_big_decimal <add> assert_equal "'4.2'", @conn.quote_bound_value(BigDecimal("4.2")) <add> end <add> <add> def test_quote_bound_true <add> assert_equal "'1'", @conn.quote_bound_value(true) <add> end <add> <add> def test_quote_bound_false <add> assert_equal "'0'", @conn.quote_bound_value(false) <add> end <add>end <ide><path>activerecord/test/cases/insert_all_test.rb <ide> def test_upsert_all_has_many_through <ide> def test_upsert_all_updates_using_provided_sql <ide> skip unless supports_insert_on_duplicate_update? <ide> <del> operator = sqlite? ? "MAX" : "GREATEST" <add> operator = current_adapter?(:SQLite3Adapter) ? "MAX" : "GREATEST" <ide> <ide> Book.upsert_all( <ide> [{ id: 1, status: 1 }, { id: 2, status: 1 }], <ide> def capture_log_output <ide> ActiveRecord::Base.logger = old_logger <ide> end <ide> end <del> <del> def sqlite? <del> ActiveRecord::Base.connection.adapter_name.match?(/sqlite/i) <del> end <ide> end <ide><path>activerecord/test/cases/relation/merging_test.rb <ide> def test_merge_doesnt_duplicate_same_clauses <ide> <ide> only_david = Author.where("#{author_id} IN (?)", david) <ide> <del> assert_sql(/WHERE \(#{Regexp.escape(author_id)} IN \(1\)\)\z/) do <del> assert_equal [david], only_david.merge(only_david) <del> end <add> if current_adapter?(:Mysql2Adapter) <add> assert_sql(/WHERE \(#{Regexp.escape(author_id)} IN \('1'\)\)\z/) do <add> assert_equal [david], only_david.merge(only_david) <add> end <add> <add> assert_sql(/WHERE \(#{Regexp.escape(author_id)} IN \('1'\)\)\z/) do <add> assert_equal [david], only_david.merge(only_david, rewhere: true) <add> end <add> else <add> assert_sql(/WHERE \(#{Regexp.escape(author_id)} IN \(1\)\)\z/) do <add> assert_equal [david], only_david.merge(only_david) <add> end <ide> <del> assert_sql(/WHERE \(#{Regexp.escape(author_id)} IN \(1\)\)\z/) do <del> assert_equal [david], only_david.merge(only_david, rewhere: true) <add> assert_sql(/WHERE \(#{Regexp.escape(author_id)} IN \(1\)\)\z/) do <add> assert_equal [david], only_david.merge(only_david, rewhere: true) <add> end <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_finding_with_complex_order <ide> <ide> def test_finding_with_sanitized_order <ide> query = Tag.order([Arel.sql("field(id, ?)"), [1, 3, 2]]).to_sql <del> assert_match(/field\(id, 1,3,2\)/, query) <add> if current_adapter?(:Mysql2Adapter) <add> assert_match(/field\(id, '1','3','2'\)/, query) <add> else <add> assert_match(/field\(id, 1,3,2\)/, query) <add> end <ide> <ide> query = Tag.order([Arel.sql("field(id, ?)"), []]).to_sql <ide> assert_match(/field\(id, NULL\)/, query) <ide><path>activerecord/test/cases/sanitize_test.rb <ide> def test_sanitize_sql_array_handles_bind_variables <ide> def test_sanitize_sql_array_handles_named_bind_variables <ide> quoted_bambi = ActiveRecord::Base.connection.quote("Bambi") <ide> assert_equal "name=#{quoted_bambi}", Binary.sanitize_sql_array(["name=:name", name: "Bambi"]) <del> assert_equal "name=#{quoted_bambi} AND id=1", Binary.sanitize_sql_array(["name=:name AND id=:id", name: "Bambi", id: 1]) <add> if current_adapter?(:Mysql2Adapter) <add> assert_equal "name=#{quoted_bambi} AND id='1'", Binary.sanitize_sql_array(["name=:name AND id=:id", name: "Bambi", id: 1]) <add> else <add> assert_equal "name=#{quoted_bambi} AND id=1", Binary.sanitize_sql_array(["name=:name AND id=:id", name: "Bambi", id: 1]) <add> end <ide> <ide> quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper") <ide> assert_equal "name=#{quoted_bambi_and_thumper}", Binary.sanitize_sql_array(["name=:name", name: "Bambi\nand\nThumper"]) <ide> def test_bind_arity <ide> end <ide> <ide> def test_named_bind_variables <del> assert_equal "1", bind(":a", a: 1) # ' ruby-mode <del> assert_equal "1 1", bind(":a :a", a: 1) # ' ruby-mode <add> if current_adapter?(:Mysql2Adapter) <add> assert_equal "'1'", bind(":a", a: 1) # ' ruby-mode <add> assert_equal "'1' '1'", bind(":a :a", a: 1) # ' ruby-mode <add> else <add> assert_equal "1", bind(":a", a: 1) # ' ruby-mode <add> assert_equal "1 1", bind(":a :a", a: 1) # ' ruby-mode <add> end <ide> <ide> assert_nothing_raised { bind("'+00:00'", foo: "bar") } <ide> end <ide> def each(&b) <ide> def test_bind_enumerable <ide> quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')}) <ide> <del> assert_equal "1,2,3", bind("?", [1, 2, 3]) <add> if current_adapter?(:Mysql2Adapter) <add> assert_equal "'1','2','3'", bind("?", [1, 2, 3]) <add> else <add> assert_equal "1,2,3", bind("?", [1, 2, 3]) <add> end <ide> assert_equal quoted_abc, bind("?", %w(a b c)) <ide> <del> assert_equal "1,2,3", bind(":a", a: [1, 2, 3]) <add> if current_adapter?(:Mysql2Adapter) <add> assert_equal "'1','2','3'", bind(":a", a: [1, 2, 3]) <add> else <add> assert_equal "1,2,3", bind(":a", a: [1, 2, 3]) <add> end <ide> assert_equal quoted_abc, bind(":a", a: %w(a b c)) # ' <ide> <del> assert_equal "1,2,3", bind("?", SimpleEnumerable.new([1, 2, 3])) <add> if current_adapter?(:Mysql2Adapter) <add> assert_equal "'1','2','3'", bind("?", SimpleEnumerable.new([1, 2, 3])) <add> else <add> assert_equal "1,2,3", bind("?", SimpleEnumerable.new([1, 2, 3])) <add> end <ide> assert_equal quoted_abc, bind("?", SimpleEnumerable.new(%w(a b c))) <ide> <del> assert_equal "1,2,3", bind(":a", a: SimpleEnumerable.new([1, 2, 3])) <add> if current_adapter?(:Mysql2Adapter) <add> assert_equal "'1','2','3'", bind(":a", a: SimpleEnumerable.new([1, 2, 3])) <add> else <add> assert_equal "1,2,3", bind(":a", a: SimpleEnumerable.new([1, 2, 3])) <add> end <ide> assert_equal quoted_abc, bind(":a", a: SimpleEnumerable.new(%w(a b c))) # ' <ide> end <ide> <ide> def test_bind_empty_enumerable <ide> <ide> def test_bind_range <ide> quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')}) <del> assert_equal "0", bind("?", 0..0) <del> assert_equal "1,2,3", bind("?", 1..3) <add> if current_adapter?(:Mysql2Adapter) <add> assert_equal "'0'", bind("?", 0..0) <add> assert_equal "'1','2','3'", bind("?", 1..3) <add> else <add> assert_equal "0", bind("?", 0..0) <add> assert_equal "1,2,3", bind("?", 1..3) <add> end <ide> assert_equal quoted_abc, bind("?", "a"..."d") <ide> end <ide>
9
Text
Text
fix 404 in getting started
d542621155fff0ef5d59a4e5bb373ff7e7754d3b
<ide><path>docs/docs/getting-started.md <ide> In the root directory of the starter kit, create a `helloworld.html` with the fo <ide> </html> <ide> ``` <ide> <del>The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](syntax.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser. <add>The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](jsx-in-depth.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser. <ide> <ide> ### Separate File <ide>
1
Ruby
Ruby
add another singleton for environment filtering
8654f8c5e9d50c8410376241e7ddc0a869929e4a
<ide><path>actionpack/lib/action_dispatch/http/filter_parameters.rb <ide> module Http <ide> module FilterParameters <ide> @@parameter_filter_for = {} <ide> <del> NULL_FILTER = ParameterFilter.new # :nodoc: <add> ENV_MATCH = [/RAW_POST_DATA/, "rack.request.form_vars"] # :nodoc: <add> NULL_PARAM_FILTER = ParameterFilter.new # :nodoc: <add> NULL_ENV_FILTER = ParameterFilter.new ENV_MATCH # :nodoc: <ide> <ide> def initialize(env) <ide> super <ide> def filtered_path <ide> <ide> def parameter_filter <ide> parameter_filter_for @env.fetch("action_dispatch.parameter_filter") { <del> return NULL_FILTER <add> return NULL_PARAM_FILTER <ide> } <ide> end <ide> <ide> def env_filter <del> parameter_filter_for(Array(@env["action_dispatch.parameter_filter"]) + [/RAW_POST_DATA/, "rack.request.form_vars"]) <add> user_key = @env.fetch("action_dispatch.parameter_filter") { <add> return NULL_ENV_FILTER <add> } <add> parameter_filter_for(Array(user_key) + ENV_MATCH) <ide> end <ide> <ide> def parameter_filter_for(filters)
1
Text
Text
remove duplicated commands
2ed0720b6e32c825b5df52f2638fe908e2d69d66
<ide><path>docs/how-to-work-on-the-docs-theme.md <ide> Clone freeCodeCamp: <ide> <ide> ```console <ide> git clone https://github.com/freeCodeCamp/freeCodeCamp.git <del>docsify serve docs <ide> ``` <ide> <ide> Install `docsify`:
1
Mixed
Javascript
remove unnecessary method argument
8bc250f63a039f5507582840b06f965f816dcca2
<ide><path>docs/getting-started/v3-migration.md <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> * `Chart.Animation.animationObject` was renamed to `Chart.Animation` <ide> * `Chart.Animation.chartInstance` was renamed to `Chart.Animation.chart` <del>* `DatasetController.updateElement` was renamed to `DatasetController.updateElements` <ide> * `helpers._decimalPlaces` was renamed to `helpers.math._decimalPlaces` <ide> * `helpers.almostEquals` was renamed to `helpers.math.almostEquals` <ide> * `helpers.almostWhole` was renamed to `helpers.math.almostWhole` <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> <ide> ##### Dataset Controllers <ide> <add>* `updateElement` was replaced with `updateElements` now taking the elements to update, the `start` index, and `mode` <ide> * `setHoverStyle` and `removeHoverStyle` now additionally take the `datasetIndex` and `index` <ide> <ide> #### Interactions <ide><path>src/controllers/controller.bar.js <ide> module.exports = DatasetController.extend({ <ide> const me = this; <ide> const rects = me._cachedMeta.data; <ide> <del> me.updateElements(rects, 0, rects.length, mode); <add> me.updateElements(rects, 0, mode); <ide> }, <ide> <del> updateElements: function(rectangles, start, count, mode) { <add> updateElements: function(rectangles, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const vscale = me._cachedMeta.vScale; <ide> module.exports = DatasetController.extend({ <ide> <ide> let i; <ide> <del> for (i = 0; i < start + count; i++) { <del> const options = me._resolveDataElementOptions(i, mode); <del> const vpixels = me.calculateBarValuePixels(i, options); <del> const ipixels = me.calculateBarIndexPixels(i, ruler, options); <add> for (i = 0; i < rectangles.length; i++) { <add> const index = start + i; <add> const options = me._resolveDataElementOptions(index, mode); <add> const vpixels = me.calculateBarValuePixels(index, options); <add> const ipixels = me.calculateBarIndexPixels(index, ruler, options); <ide> <ide> const properties = { <ide> horizontal, <ide> module.exports = DatasetController.extend({ <ide> if (includeOptions) { <ide> properties.options = options; <ide> } <del> me._updateElement(rectangles[i], i, properties, mode); <add> me._updateElement(rectangles[i], index, properties, mode); <ide> } <ide> <ide> me._updateSharedOptions(sharedOptions, mode); <ide><path>src/controllers/controller.bubble.js <ide> module.exports = DatasetController.extend({ <ide> const points = me._cachedMeta.data; <ide> <ide> // Update Points <del> me.updateElements(points, 0, points.length, mode); <add> me.updateElements(points, 0, mode); <ide> }, <ide> <ide> /** <ide> * @protected <ide> */ <del> updateElements: function(points, start, count, mode) { <add> updateElements: function(points, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const {xScale, yScale} = me._cachedMeta; <ide> module.exports = DatasetController.extend({ <ide> const includeOptions = me._includeOptions(mode, sharedOptions); <ide> let i; <ide> <del> for (i = start; i < start + count; i++) { <add> for (i = 0; i < points.length; i++) { <ide> const point = points[i]; <del> const parsed = !reset && me._getParsed(i); <add> const index = start + i; <add> const parsed = !reset && me._getParsed(index); <ide> const x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(parsed[xScale.id]); <ide> const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(parsed[yScale.id]); <ide> const properties = { <ide> module.exports = DatasetController.extend({ <ide> }; <ide> <ide> if (includeOptions) { <del> properties.options = i === start ? firstOpts <add> properties.options = i === 0 ? firstOpts <ide> : me._resolveDataElementOptions(i, mode); <ide> <ide> if (reset) { <ide> properties.options.radius = 0; <ide> } <ide> } <ide> <del> me._updateElement(point, i, properties, mode); <add> me._updateElement(point, index, properties, mode); <ide> } <ide> <ide> me._updateSharedOptions(sharedOptions, mode); <ide><path>src/controllers/controller.doughnut.js <ide> module.exports = DatasetController.extend({ <ide> me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index); <ide> me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0); <ide> <del> me.updateElements(arcs, 0, arcs.length, mode); <add> me.updateElements(arcs, 0, mode); <ide> }, <ide> <del> updateElements: function(arcs, start, count, mode) { <add> /** <add> * @private <add> */ <add> _circumference: function(i, reset) { <add> const me = this; <add> const opts = me.chart.options; <add> const meta = me._cachedMeta; <add> return reset && opts.animation.animateRotate ? 0 : meta.data[i].hidden ? 0 : me.calculateCircumference(meta._parsed[i] * opts.circumference / DOUBLE_PI); <add> }, <add> <add> updateElements: function(arcs, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const chart = me.chart; <ide> module.exports = DatasetController.extend({ <ide> const animationOpts = opts.animation; <ide> const centerX = (chartArea.left + chartArea.right) / 2; <ide> const centerY = (chartArea.top + chartArea.bottom) / 2; <del> const meta = me.getMeta(); <ide> const innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius; <ide> const outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius; <ide> let startAngle = opts.rotation; <ide> let i; <ide> <del> for (i = 0; i < start + count; ++i) { <add> for (i = 0; i < start; ++i) { <add> startAngle += me._circumference(i, reset); <add> } <add> <add> for (i = 0; i < arcs.length; ++i) { <add> const index = start + i; <add> const circumference = me._circumference(index, reset); <ide> const arc = arcs[i]; <del> const circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(meta._parsed[i] * opts.circumference / DOUBLE_PI); <ide> const options = arc._options || {}; <del> if (i < start) { <del> startAngle += circumference; <del> continue; <del> } <ide> const properties = { <ide> x: centerX + chart.offsetX, <ide> y: centerY + chart.offsetY, <ide> module.exports = DatasetController.extend({ <ide> }; <ide> startAngle += circumference; <ide> <del> me._updateElement(arc, i, properties, mode); <add> me._updateElement(arc, index, properties, mode); <ide> } <ide> }, <ide> <ide><path>src/controllers/controller.line.js <ide> module.exports = DatasetController.extend({ <ide> <ide> // Update Points <ide> if (meta.visible) { <del> me.updateElements(points, 0, points.length, mode); <add> me.updateElements(points, 0, mode); <ide> } <ide> }, <ide> <del> updateElements: function(points, start, count, mode) { <add> updateElements: function(points, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const {xScale, yScale, _stacked} = me._cachedMeta; <ide> module.exports = DatasetController.extend({ <ide> const includeOptions = me._includeOptions(mode, sharedOptions); <ide> let i; <ide> <del> for (i = start; i < start + count; ++i) { <add> for (i = 0; i < points.length; ++i) { <add> const index = start + i; <ide> const point = points[i]; <del> const parsed = me._getParsed(i); <add> const parsed = me._getParsed(index); <ide> const x = xScale.getPixelForValue(parsed[xScale.id]); <ide> const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(_stacked ? me._applyStack(yScale, parsed) : parsed[yScale.id]); <ide> const properties = { <ide> module.exports = DatasetController.extend({ <ide> }; <ide> <ide> if (includeOptions) { <del> properties.options = i === start ? firstOpts <del> : me._resolveDataElementOptions(i, mode); <add> properties.options = i === 0 ? firstOpts <add> : me._resolveDataElementOptions(index, mode); <ide> } <ide> <del> me._updateElement(point, i, properties, mode); <add> me._updateElement(point, index, properties, mode); <ide> } <ide> <ide> me._updateSharedOptions(sharedOptions, mode); <ide><path>src/controllers/controller.polarArea.js <ide> module.exports = DatasetController.extend({ <ide> <ide> me._updateRadius(); <ide> <del> me.updateElements(arcs, 0, arcs.length, mode); <add> me.updateElements(arcs, 0, mode); <ide> }, <ide> <ide> /** <ide> module.exports = DatasetController.extend({ <ide> me.innerRadius = me.outerRadius - chart.radiusLength; <ide> }, <ide> <del> updateElements: function(arcs, start, count, mode) { <add> updateElements: function(arcs, start, mode) { <ide> const me = this; <ide> const reset = mode === 'reset'; <ide> const chart = me.chart; <ide> module.exports = DatasetController.extend({ <ide> for (i = 0; i < start; ++i) { <ide> angle += me._computeAngle(i); <ide> } <del> for (; i < start + count; i++) { <add> for (i = 0; i < arcs.length; i++) { <ide> const arc = arcs[i]; <add> const index = start + i; <ide> let startAngle = angle; <del> let endAngle = angle + me._computeAngle(i); <del> let outerRadius = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[i]); <add> let endAngle = angle + me._computeAngle(index); <add> let outerRadius = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); <ide> angle = endAngle; <ide> <ide> if (reset) { <ide> module.exports = DatasetController.extend({ <ide> outerRadius, <ide> startAngle, <ide> endAngle, <del> options: me._resolveDataElementOptions(i) <add> options: me._resolveDataElementOptions(index) <ide> }; <ide> <del> me._updateElement(arc, i, properties, mode); <add> me._updateElement(arc, index, properties, mode); <ide> } <ide> }, <ide> <ide><path>src/controllers/controller.radar.js <ide> module.exports = DatasetController.extend({ <ide> }, <ide> <ide> update: function(mode) { <del> var me = this; <del> var meta = me._cachedMeta; <del> var line = meta.dataset; <del> var points = meta.data || []; <add> const me = this; <add> const meta = me._cachedMeta; <add> const line = meta.dataset; <add> const points = meta.data || []; <ide> <ide> const properties = { <ide> _children: points, <ide> module.exports = DatasetController.extend({ <ide> me._updateElement(line, undefined, properties, mode); <ide> <ide> // Update Points <del> me.updateElements(points, 0, points.length, mode); <add> me.updateElements(points, 0, mode); <ide> <ide> line.updateControlPoints(me.chart.chartArea); <ide> }, <ide> <del> updateElements: function(points, start, count, mode) { <add> updateElements: function(points, start, mode) { <ide> const me = this; <ide> const dataset = me.getDataset(); <ide> const scale = me.chart.scales.r; <ide> const reset = mode === 'reset'; <del> var i; <add> let i; <ide> <del> for (i = start; i < start + count; i++) { <add> for (i = 0; i < points.length; i++) { <ide> const point = points[i]; <del> const options = me._resolveDataElementOptions(i); <del> const pointPosition = scale.getPointPositionForValue(i, dataset.data[i]); <add> const index = start + i; <add> const options = me._resolveDataElementOptions(index); <add> const pointPosition = scale.getPointPositionForValue(index, dataset.data[index]); <ide> <ide> const x = reset ? scale.xCenter : pointPosition.x; <ide> const y = reset ? scale.yCenter : pointPosition.y; <ide> module.exports = DatasetController.extend({ <ide> options, <ide> }; <ide> <del> me._updateElement(point, i, properties, mode); <add> me._updateElement(point, index, properties, mode); <ide> } <ide> }, <ide> <ide> /** <ide> * @private <ide> */ <ide> _resolveDatasetElementOptions: function() { <del> var me = this; <del> var config = me._config; <del> var options = me.chart.options; <del> var values = DatasetController.prototype._resolveDatasetElementOptions.apply(me, arguments); <add> const me = this; <add> const config = me._config; <add> const options = me.chart.options; <add> const values = DatasetController.prototype._resolveDatasetElementOptions.apply(me, arguments); <ide> <ide> values.spanGaps = valueOrDefault(config.spanGaps, options.spanGaps); <ide> values.tension = valueOrDefault(config.lineTension, options.elements.line.tension); <ide><path>src/core/core.datasetController.js <ide> helpers.extend(DatasetController.prototype, { <ide> } <ide> me._parse(start, count); <ide> <del> me.updateElements(data, start, count, 'reset'); <add> me.updateElements(elements, start, 'reset'); <ide> }, <ide> <ide> /**
8
PHP
PHP
fix backwards compatibility breakage
0f837273c686461fe2dd924255966a47602d3df1
<ide><path>src/Cache/Cache.php <ide> public static function delete($key, $config = 'default') <ide> * <ide> * @param array $keys Array of cache keys to be deleted <ide> * @param string $config name of the configuration to use. Defaults to 'default' <del> * @return bool True if the items were successfully removed. False if there was an error. <add> * @return array of boolean values that are true if the value was successfully deleted, <add> * false if it didn't exist or couldn't be removed. <ide> */ <ide> public static function deleteMany($keys, $config = 'default') <ide> { <ide> $backend = static::pool($config); <ide> <del> return $backend->deleteMultiple($keys); <add> $return = []; <add> foreach ($keys as $key) { <add> $return[$key] = $backend->delete($key); <add> } <add> <add> return $return; <ide> } <ide> <ide> /**
1
Go
Go
cleanup the structure of the cli package
33c9edaf6c5401fc1891713d1ad8d861e6cea51f
<ide><path>api/client/cli.go <ide> import ( <ide> "runtime" <ide> <ide> "github.com/docker/docker/api" <del> "github.com/docker/docker/cli" <add> cliflags "github.com/docker/docker/cli/flags" <ide> "github.com/docker/docker/cliconfig" <ide> "github.com/docker/docker/cliconfig/credentials" <ide> "github.com/docker/docker/dockerversion" <ide> func (cli *DockerCli) restoreTerminal(in io.Closer) error { <ide> // The key file, protocol (i.e. unix) and address are passed in as strings, along with the tls.Config. If the tls.Config <ide> // is set the client scheme will be set to https. <ide> // The client will be given a 32-second timeout (see https://github.com/docker/docker/pull/8035). <del>func NewDockerCli(in io.ReadCloser, out, err io.Writer, clientFlags *cli.ClientFlags) *DockerCli { <add>func NewDockerCli(in io.ReadCloser, out, err io.Writer, clientFlags *cliflags.ClientFlags) *DockerCli { <ide> cli := &DockerCli{ <ide> in: in, <ide> out: out, <add><path>cli/flags/client.go <del><path>cli/client.go <del>package cli <add>package flags <ide> <ide> import flag "github.com/docker/docker/pkg/mflag" <ide> <ide><path>cli/flags/common.go <ide> import ( <ide> "path/filepath" <ide> <ide> "github.com/Sirupsen/logrus" <del> "github.com/docker/docker/cli" <ide> "github.com/docker/docker/cliconfig" <ide> "github.com/docker/docker/opts" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> var ( <ide> dockerTLSVerify = os.Getenv("DOCKER_TLS_VERIFY") != "" <ide> ) <ide> <add>// CommonFlags are flags common to both the client and the daemon. <add>type CommonFlags struct { <add> FlagSet *flag.FlagSet <add> PostParse func() <add> <add> Debug bool <add> Hosts []string <add> LogLevel string <add> TLS bool <add> TLSVerify bool <add> TLSOptions *tlsconfig.Options <add> TrustKey string <add>} <add> <ide> // InitCommonFlags initializes flags common to both client and daemon <del>func InitCommonFlags() *cli.CommonFlags { <del> var commonFlags = &cli.CommonFlags{FlagSet: new(flag.FlagSet)} <add>func InitCommonFlags() *CommonFlags { <add> var commonFlags = &CommonFlags{FlagSet: new(flag.FlagSet)} <ide> <ide> if dockerCertPath == "" { <ide> dockerCertPath = cliconfig.ConfigDir() <ide> func InitCommonFlags() *cli.CommonFlags { <ide> return commonFlags <ide> } <ide> <del>func postParseCommon(commonFlags *cli.CommonFlags) { <add>func postParseCommon(commonFlags *CommonFlags) { <ide> cmd := commonFlags.FlagSet <ide> <ide> SetDaemonLogLevel(commonFlags.LogLevel) <add><path>cli/usage.go <del><path>cli/common.go <ide> package cli <ide> <del>import ( <del> flag "github.com/docker/docker/pkg/mflag" <del> "github.com/docker/go-connections/tlsconfig" <del>) <del> <del>// CommonFlags represents flags that are common to both the client and the daemon. <del>type CommonFlags struct { <del> FlagSet *flag.FlagSet <del> PostParse func() <del> <del> Debug bool <del> Hosts []string <del> LogLevel string <del> TLS bool <del> TLSVerify bool <del> TLSOptions *tlsconfig.Options <del> TrustKey string <del>} <del> <ide> // Command is the struct containing the command name and description <ide> type Command struct { <ide> Name string <ide><path>cmd/docker/client.go <ide> package main <ide> import ( <ide> "path/filepath" <ide> <del> "github.com/docker/docker/cli" <ide> cliflags "github.com/docker/docker/cli/flags" <ide> "github.com/docker/docker/cliconfig" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> import ( <ide> <ide> var ( <ide> commonFlags = cliflags.InitCommonFlags() <del> clientFlags = &cli.ClientFlags{FlagSet: new(flag.FlagSet), Common: commonFlags} <add> clientFlags = &cliflags.ClientFlags{FlagSet: new(flag.FlagSet), Common: commonFlags} <ide> ) <ide> <ide> func init() { <ide><path>cmd/dockerd/daemon.go <ide> import ( <ide> systemrouter "github.com/docker/docker/api/server/router/system" <ide> "github.com/docker/docker/api/server/router/volume" <ide> "github.com/docker/docker/builder/dockerfile" <del> "github.com/docker/docker/cli" <ide> cliflags "github.com/docker/docker/cli/flags" <ide> "github.com/docker/docker/cliconfig" <ide> "github.com/docker/docker/daemon" <ide> const ( <ide> // DaemonCli represents the daemon CLI. <ide> type DaemonCli struct { <ide> *daemon.Config <del> commonFlags *cli.CommonFlags <add> commonFlags *cliflags.CommonFlags <ide> configFile *string <ide> } <ide> <ide> func shutdownDaemon(d *daemon.Daemon, timeout time.Duration) { <ide> } <ide> } <ide> <del>func loadDaemonCliConfig(config *daemon.Config, flags *flag.FlagSet, commonConfig *cli.CommonFlags, configFile string) (*daemon.Config, error) { <add>func loadDaemonCliConfig(config *daemon.Config, flags *flag.FlagSet, commonConfig *cliflags.CommonFlags, configFile string) (*daemon.Config, error) { <ide> config.Debug = commonConfig.Debug <ide> config.Hosts = commonConfig.Hosts <ide> config.LogLevel = commonConfig.LogLevel <ide><path>cmd/dockerd/daemon_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/Sirupsen/logrus" <del> "github.com/docker/docker/cli" <add> cliflags "github.com/docker/docker/cli/flags" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/mflag" <ide> import ( <ide> <ide> func TestLoadDaemonCliConfigWithoutOverriding(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{ <add> common := &cliflags.CommonFlags{ <ide> Debug: true, <ide> } <ide> <ide> func TestLoadDaemonCliConfigWithoutOverriding(t *testing.T) { <ide> <ide> func TestLoadDaemonCliConfigWithTLS(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{ <add> common := &cliflags.CommonFlags{ <ide> TLS: true, <ide> TLSOptions: &tlsconfig.Options{ <ide> CAFile: "/tmp/ca.pem", <ide> func TestLoadDaemonCliConfigWithTLS(t *testing.T) { <ide> <ide> func TestLoadDaemonCliConfigWithConflicts(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{} <add> common := &cliflags.CommonFlags{} <ide> f, err := ioutil.TempFile("", "docker-config-") <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestLoadDaemonCliConfigWithConflicts(t *testing.T) { <ide> <ide> func TestLoadDaemonCliConfigWithTLSVerify(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{ <add> common := &cliflags.CommonFlags{ <ide> TLSOptions: &tlsconfig.Options{ <ide> CAFile: "/tmp/ca.pem", <ide> }, <ide> func TestLoadDaemonCliConfigWithTLSVerify(t *testing.T) { <ide> <ide> func TestLoadDaemonCliConfigWithExplicitTLSVerifyFalse(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{ <add> common := &cliflags.CommonFlags{ <ide> TLSOptions: &tlsconfig.Options{ <ide> CAFile: "/tmp/ca.pem", <ide> }, <ide> func TestLoadDaemonCliConfigWithExplicitTLSVerifyFalse(t *testing.T) { <ide> <ide> func TestLoadDaemonCliConfigWithoutTLSVerify(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{ <add> common := &cliflags.CommonFlags{ <ide> TLSOptions: &tlsconfig.Options{ <ide> CAFile: "/tmp/ca.pem", <ide> }, <ide> func TestLoadDaemonCliConfigWithoutTLSVerify(t *testing.T) { <ide> <ide> func TestLoadDaemonCliConfigWithLogLevel(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{} <add> common := &cliflags.CommonFlags{} <ide> <ide> f, err := ioutil.TempFile("", "docker-config-") <ide> if err != nil { <ide> func TestLoadDaemonCliConfigWithLogLevel(t *testing.T) { <ide> <ide> func TestLoadDaemonConfigWithEmbeddedOptions(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{} <add> common := &cliflags.CommonFlags{} <ide> <ide> flags := mflag.NewFlagSet("test", mflag.ContinueOnError) <ide> flags.String([]string{"-tlscacert"}, "", "") <ide> func TestLoadDaemonConfigWithEmbeddedOptions(t *testing.T) { <ide> <ide> func TestLoadDaemonConfigWithRegistryOptions(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{} <add> common := &cliflags.CommonFlags{} <ide> flags := mflag.NewFlagSet("test", mflag.ContinueOnError) <ide> c.ServiceOptions.InstallCliFlags(flags, absentFromHelp) <ide> <ide><path>cmd/dockerd/daemon_unix_test.go <ide> import ( <ide> "io/ioutil" <ide> "testing" <ide> <del> "github.com/docker/docker/cli" <add> cliflags "github.com/docker/docker/cli/flags" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/mflag" <ide> ) <ide> <ide> func TestLoadDaemonCliConfigWithDaemonFlags(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{ <add> common := &cliflags.CommonFlags{ <ide> Debug: true, <ide> LogLevel: "info", <ide> } <ide> func TestLoadDaemonCliConfigWithDaemonFlags(t *testing.T) { <ide> <ide> func TestLoadDaemonConfigWithNetwork(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{} <add> common := &cliflags.CommonFlags{} <ide> flags := mflag.NewFlagSet("test", mflag.ContinueOnError) <ide> flags.String([]string{"-bip"}, "", "") <ide> flags.String([]string{"-ip"}, "", "") <ide> func TestLoadDaemonConfigWithNetwork(t *testing.T) { <ide> <ide> func TestLoadDaemonConfigWithMapOptions(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{} <add> common := &cliflags.CommonFlags{} <ide> flags := mflag.NewFlagSet("test", mflag.ContinueOnError) <ide> <ide> flags.Var(opts.NewNamedMapOpts("cluster-store-opts", c.ClusterOpts, nil), []string{"-cluster-store-opt"}, "") <ide> func TestLoadDaemonConfigWithMapOptions(t *testing.T) { <ide> <ide> func TestLoadDaemonConfigWithTrueDefaultValues(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{} <add> common := &cliflags.CommonFlags{} <ide> flags := mflag.NewFlagSet("test", mflag.ContinueOnError) <ide> flags.BoolVar(&c.EnableUserlandProxy, []string{"-userland-proxy"}, true, "") <ide> <ide> func TestLoadDaemonConfigWithTrueDefaultValues(t *testing.T) { <ide> <ide> func TestLoadDaemonConfigWithTrueDefaultValuesLeaveDefaults(t *testing.T) { <ide> c := &daemon.Config{} <del> common := &cli.CommonFlags{} <add> common := &cliflags.CommonFlags{} <ide> flags := mflag.NewFlagSet("test", mflag.ContinueOnError) <ide> flags.BoolVar(&c.EnableUserlandProxy, []string{"-userland-proxy"}, true, "") <ide>
8
Javascript
Javascript
add note on negation
49455a75dc01b6b57304f14fafd476de6c2b29be
<ide><path>src/ng/filter/filter.js <ide> * which have property `name` containing "M" and property `phone` containing "1". A special <ide> * property name `$` can be used (as in `{$:"text"}`) to accept a match against any <ide> * property of the object. That's equivalent to the simple substring match with a `string` <del> * as described above. <add> * as described above. The predicate can be negated by prefixing the string with `!`. <add> * For Example `{name: "!M"}` predicate will return an array of items which have property `name` <add> * not containing "M". <ide> * <ide> * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The <ide> * function is called for each element of `array`. The final result is an array of those
1
Javascript
Javascript
update minify task to work with grunt-cli 0.1.6
9576710b2f20c142e0277a0342d967a21f1da17a
<ide><path>Gruntfile.js <ide> module.exports = function(grunt) { <ide> var done = this.async(); <ide> var exec = require('child_process').exec; <ide> <del> var externs = this.files[0].externs || []; <del> var dest = this.files[0].dest; <del> var files = []; <add> var externs = this.data.externs || []; <add> var dest = this.data.dest; <add> var filePatterns = []; <ide> <ide> // Make sure deeper directories exist for compiler <ide> grunt.file.write(dest, ''); <ide> <del> if (this.files[0].sourcelist) { <del> files = files.concat(grunt.file.read(this.files[0].sourcelist).split(',')); <add> if (this.data.sourcelist) { <add> filePatterns = filePatterns.concat(grunt.file.read(this.data.sourcelist).split(',')); <ide> } <del> if (this.files[0].src) { <del> files = files.concat(this.files[0].src); <add> if (this.data.src) { <add> filePatterns = filePatterns.concat(this.data.src); <ide> } <ide> <ide> var command = 'java -jar build/compiler/compiler.jar' <ide> module.exports = function(grunt) { <ide> + ' --jscomp_warning=checkTypes --warning_level=VERBOSE' <ide> + ' --output_wrapper "(function() {%output%})();//@ sourceMappingURL=video.js.map"'; <ide> <del> files.forEach(function(file){ <add> grunt.file.expand(filePatterns).forEach(function(file){ <ide> command += ' --js='+file; <ide> }); <ide>
1