content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
remove spaces from array brackets
eba5d1365c106261a85c806bd8a93b22bd8dafac
<ide><path>src/classic/element/__tests__/ReactElementValidator-test.js <ide> describe('ReactElementValidator', function() { <ide> spyOn(console, 'warn'); <ide> var Component = React.createFactory(ComponentClass); <ide> <del> Component(null, [ Component(), Component() ]); <add> Component(null, [Component(), Component()]); <ide> <ide> expect(console.warn.argsForCall.length).toBe(1); <ide> expect(console.warn.argsForCall[0][0]).toContain( <ide> describe('ReactElementValidator', function() { <ide> var ComponentWrapper = React.createClass({ <ide> displayName: 'ComponentWrapper', <ide> render: function() { <del> return InnerComponent({childSet: [ Component(), Component() ] }); <add> return InnerComponent({childSet: [Component(), Component()] }); <ide> } <ide> }); <ide> <ide> describe('ReactElementValidator', function() { <ide> spyOn(console, 'warn'); <ide> var Component = React.createFactory(ComponentClass); <ide> <del> Component(null, [ Component({key: '#1'}), Component({key: '#2'}) ]); <add> Component(null, [Component({key: '#1'}), Component({key: '#2'})]); <ide> <ide> expect(console.warn.argsForCall.length).toBe(0); <ide> }); <ide><path>src/core/__tests__/ReactComponentLifeCycle-test.js <ide> describe('ReactComponentLifeCycle', function() { <ide> spyOn(console, 'warn'); <ide> var Component = React.createClass({ <ide> getInitialState: function() { <del> return { isMounted: false }; <add> return {isMounted: false}; <ide> }, <ide> componentDidMount: function() { <del> this.setState({ isMounted: true }); <add> this.setState({isMounted: true}); <ide> }, <ide> render: function() { <ide> if (this.state.isMounted) { <ide><path>src/core/__tests__/ReactCompositeComponentNestedState-test.js <ide> describe('ReactCompositeComponentNestedState-state', function() { <ide> ); <ide> <ide> expect(logger.mock.calls).toEqual([ <del> [ 'parent-render', 'blue' ], <del> [ 'getInitialState', 'blue' ], <del> [ 'render', 'dark blue', 'blue' ], <del> [ 'handleHue', 'dark blue', 'blue' ], <del> [ 'parent-handleColor', 'blue' ], <del> [ 'parent-render', 'green' ], <del> [ 'setState-this', 'dark blue', 'blue' ], <del> [ 'setState-args', 'dark blue', 'green' ], <del> [ 'render', 'light green', 'green' ], <del> [ 'parent-after-setState', 'green' ], <del> [ 'after-setState', 'light green', 'green' ] <add> ['parent-render', 'blue'], <add> ['getInitialState', 'blue'], <add> ['render', 'dark blue', 'blue'], <add> ['handleHue', 'dark blue', 'blue'], <add> ['parent-handleColor', 'blue'], <add> ['parent-render', 'green'], <add> ['setState-this', 'dark blue', 'blue'], <add> ['setState-args', 'dark blue', 'green'], <add> ['render', 'light green', 'green'], <add> ['parent-after-setState', 'green'], <add> ['after-setState', 'light green', 'green'] <ide> ]); <ide> }); <ide> }); <ide><path>src/core/__tests__/ReactCompositeComponentState-test.js <ide> describe('ReactCompositeComponent-state', function() { <ide> <ide> expect(stateListener.mock.calls).toEqual([ <ide> // there is no state when getInitialState() is called <del> [ 'getInitialState', null ], <del> [ 'componentWillMount-start', 'red' ], <add> ['getInitialState', null], <add> ['componentWillMount-start', 'red'], <ide> // setState()'s only enqueue pending states. <del> [ 'componentWillMount-after-sunrise', 'red' ], <del> [ 'componentWillMount-end', 'red' ], <add> ['componentWillMount-after-sunrise', 'red'], <add> ['componentWillMount-end', 'red'], <ide> // pending state queue is processed <del> [ 'before-setState-sunrise', 'red' ], <del> [ 'after-setState-sunrise', 'sunrise' ], <del> [ 'after-setState-orange', 'orange' ], <add> ['before-setState-sunrise', 'red'], <add> ['after-setState-sunrise', 'sunrise'], <add> ['after-setState-orange', 'orange'], <ide> // pending state has been applied <del> [ 'render', 'orange' ], <del> [ 'componentDidMount-start', 'orange' ], <add> ['render', 'orange'], <add> ['componentDidMount-start', 'orange'], <ide> // setState-sunrise and setState-orange should be called here, <ide> // after the bug in #1740 <ide> // componentDidMount() called setState({color:'yellow'}), which is async. <ide> // The update doesn't happen until the next flush. <del> [ 'componentDidMount-end', 'orange' ], <del> [ 'shouldComponentUpdate-currentState', 'orange' ], <del> [ 'shouldComponentUpdate-nextState', 'yellow' ], <del> [ 'componentWillUpdate-currentState', 'orange' ], <del> [ 'componentWillUpdate-nextState', 'yellow' ], <del> [ 'render', 'yellow' ], <del> [ 'componentDidUpdate-currentState', 'yellow' ], <del> [ 'componentDidUpdate-prevState', 'orange' ], <del> [ 'setState-yellow', 'yellow' ], <del> [ 'initial-callback', 'yellow' ], <del> [ 'componentWillReceiveProps-start', 'yellow' ], <add> ['componentDidMount-end', 'orange'], <add> ['shouldComponentUpdate-currentState', 'orange'], <add> ['shouldComponentUpdate-nextState', 'yellow'], <add> ['componentWillUpdate-currentState', 'orange'], <add> ['componentWillUpdate-nextState', 'yellow'], <add> ['render', 'yellow'], <add> ['componentDidUpdate-currentState', 'yellow'], <add> ['componentDidUpdate-prevState', 'orange'], <add> ['setState-yellow', 'yellow'], <add> ['initial-callback', 'yellow'], <add> ['componentWillReceiveProps-start', 'yellow'], <ide> // setState({color:'green'}) only enqueues a pending state. <del> [ 'componentWillReceiveProps-end', 'yellow' ], <add> ['componentWillReceiveProps-end', 'yellow'], <ide> // pending state queue is processed <ide> // before-setState-receiveProps never called, due to replaceState. <del> [ 'before-setState-again-receiveProps', undefined ], <del> [ 'after-setState-receiveProps', 'green' ], <del> [ 'shouldComponentUpdate-currentState', 'yellow' ], <del> [ 'shouldComponentUpdate-nextState', 'green' ], <del> [ 'componentWillUpdate-currentState', 'yellow' ], <del> [ 'componentWillUpdate-nextState', 'green' ], <del> [ 'render', 'green' ], <del> [ 'componentDidUpdate-currentState', 'green' ], <del> [ 'componentDidUpdate-prevState', 'yellow' ], <del> [ 'setState-receiveProps', 'green' ], <del> [ 'setProps', 'green' ], <add> ['before-setState-again-receiveProps', undefined], <add> ['after-setState-receiveProps', 'green'], <add> ['shouldComponentUpdate-currentState', 'yellow'], <add> ['shouldComponentUpdate-nextState', 'green'], <add> ['componentWillUpdate-currentState', 'yellow'], <add> ['componentWillUpdate-nextState', 'green'], <add> ['render', 'green'], <add> ['componentDidUpdate-currentState', 'green'], <add> ['componentDidUpdate-prevState', 'yellow'], <add> ['setState-receiveProps', 'green'], <add> ['setProps', 'green'], <ide> // setFavoriteColor('blue') <del> [ 'shouldComponentUpdate-currentState', 'green' ], <del> [ 'shouldComponentUpdate-nextState', 'blue' ], <del> [ 'componentWillUpdate-currentState', 'green' ], <del> [ 'componentWillUpdate-nextState', 'blue' ], <del> [ 'render', 'blue' ], <del> [ 'componentDidUpdate-currentState', 'blue' ], <del> [ 'componentDidUpdate-prevState', 'green' ], <del> [ 'setFavoriteColor', 'blue' ], <add> ['shouldComponentUpdate-currentState', 'green'], <add> ['shouldComponentUpdate-nextState', 'blue'], <add> ['componentWillUpdate-currentState', 'green'], <add> ['componentWillUpdate-nextState', 'blue'], <add> ['render', 'blue'], <add> ['componentDidUpdate-currentState', 'blue'], <add> ['componentDidUpdate-prevState', 'green'], <add> ['setFavoriteColor', 'blue'], <ide> // forceUpdate() <del> [ 'componentWillUpdate-currentState', 'blue' ], <del> [ 'componentWillUpdate-nextState', 'blue' ], <del> [ 'render', 'blue' ], <del> [ 'componentDidUpdate-currentState', 'blue' ], <del> [ 'componentDidUpdate-prevState', 'blue' ], <del> [ 'forceUpdate', 'blue' ], <add> ['componentWillUpdate-currentState', 'blue'], <add> ['componentWillUpdate-nextState', 'blue'], <add> ['render', 'blue'], <add> ['componentDidUpdate-currentState', 'blue'], <add> ['componentDidUpdate-prevState', 'blue'], <add> ['forceUpdate', 'blue'], <ide> // unmountComponent() <ide> // state is available within `componentWillUnmount()` <del> [ 'componentWillUnmount', 'blue' ] <add> ['componentWillUnmount', 'blue'] <ide> ]); <ide> }); <ide> }); <ide><path>src/modern/element/__tests__/ReactJSXElementValidator-test.js <ide> describe('ReactJSXElementValidator', function() { <ide> render() { <ide> return ( <ide> <InnerComponent <del> childSet={[ <Component />, <Component /> ]} <add> childSet={[<Component />, <Component />]} <ide> /> <ide> ); <ide> } <ide> describe('ReactJSXElementValidator', function() { <ide> it('does not warns for arrays of elements with keys', function() { <ide> spyOn(console, 'warn'); <ide> <del> <Component>{[ <Component key="#1" />, <Component key="#2" /> ]}</Component>; <add> <Component>{[<Component key="#1" />, <Component key="#2" />]}</Component>; <ide> <ide> expect(console.warn.argsForCall.length).toBe(0); <ide> }); <ide><path>src/utils/__tests__/ReactChildren-test.js <ide> describe('ReactChildren', function() { <ide> it('should warn if a fragment is accessed', function() { <ide> spyOn(console, 'warn'); <ide> var child = React.createElement('span'); <del> var frag = ReactChildren.map([ child, child ], function(c) { <add> var frag = ReactChildren.map([child, child], function(c) { <ide> return c; <ide> }); <ide> for (var key in frag) { <ide> describe('ReactChildren', function() { <ide> expect(console.warn.calls.length).toBe(1); <ide> expect(console.warn.calls[0].args[0]).toContain('is an opaque type'); <ide> <del> var frag2 = ReactChildren.map([ child, child ], function(c) { <add> var frag2 = ReactChildren.map([child, child], function(c) { <ide> return c; <ide> }); <ide> for (var key in frag2) {
6
Go
Go
pass taroptions via cli arg
9c01bc249dc628280f3fc019d5f0e0ace71be248
<ide><path>builder/internals.go <ide> func (b *Builder) readContext(context io.Reader) error { <ide> return err <ide> } <ide> <del> os.MkdirAll(tmpdirPath, 0700) <ide> if err := chrootarchive.Untar(b.context, tmpdirPath, nil); err != nil { <ide> return err <ide> } <ide><path>graph/load.go <ide> import ( <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/archive" <add> "github.com/docker/docker/pkg/chrootarchive" <ide> ) <ide> <ide> // Loads a set of images into the repository. This is the complementary of ImageExport. <ide> func (s *TagStore) CmdLoad(job *engine.Job) engine.Status { <ide> excludes[i] = k <ide> i++ <ide> } <del> if err := archive.Untar(repoFile, repoDir, &archive.TarOptions{Excludes: excludes}); err != nil { <add> if err := chrootarchive.Untar(repoFile, repoDir, &archive.TarOptions{Excludes: excludes}); err != nil { <ide> return job.Error(err) <ide> } <ide> <ide><path>pkg/chrootarchive/archive.go <ide> package chrootarchive <ide> <ide> import ( <add> "bytes" <add> "encoding/json" <ide> "flag" <ide> "fmt" <ide> "io" <ide> "os" <ide> "runtime" <add> "strings" <ide> "syscall" <ide> <ide> "github.com/docker/docker/pkg/archive" <ide> func untar() { <ide> if err := syscall.Chdir("/"); err != nil { <ide> fatal(err) <ide> } <del> if err := archive.Untar(os.Stdin, "/", nil); err != nil { <add> options := new(archive.TarOptions) <add> dec := json.NewDecoder(strings.NewReader(flag.Arg(1))) <add> if err := dec.Decode(options); err != nil { <add> fatal(err) <add> } <add> if err := archive.Untar(os.Stdin, "/", options); err != nil { <ide> fatal(err) <ide> } <ide> os.Exit(0) <ide> var ( <ide> ) <ide> <ide> func Untar(archive io.Reader, dest string, options *archive.TarOptions) error { <add> var buf bytes.Buffer <add> enc := json.NewEncoder(&buf) <add> if err := enc.Encode(options); err != nil { <add> return fmt.Errorf("Untar json encode: %v", err) <add> } <ide> if _, err := os.Stat(dest); os.IsNotExist(err) { <ide> if err := os.MkdirAll(dest, 0777); err != nil { <ide> return err <ide> } <ide> } <del> cmd := reexec.Command("docker-untar", dest) <add> <add> cmd := reexec.Command("docker-untar", dest, buf.String()) <ide> cmd.Stdin = archive <ide> out, err := cmd.CombinedOutput() <ide> if err != nil { <ide><path>pkg/chrootarchive/archive_test.go <add>package chrootarchive <add> <add>import ( <add> "io/ioutil" <add> "os" <add> "path/filepath" <add> "testing" <add> <add> "github.com/docker/docker/pkg/archive" <add>) <add> <add>func TestChrootTarUntar(t *testing.T) { <add> tmpdir, err := ioutil.TempDir("", "docker-TestChrootTarUntar") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(tmpdir) <add> src := filepath.Join(tmpdir, "src") <add> if err := os.MkdirAll(src, 0700); err != nil { <add> t.Fatal(err) <add> } <add> if err := ioutil.WriteFile(filepath.Join(src, "toto"), []byte("hello toto"), 0644); err != nil { <add> t.Fatal(err) <add> } <add> if err := ioutil.WriteFile(filepath.Join(src, "lolo"), []byte("hello lolo"), 0644); err != nil { <add> t.Fatal(err) <add> } <add> stream, err := archive.Tar(src, archive.Uncompressed) <add> if err != nil { <add> t.Fatal(err) <add> } <add> dest := filepath.Join(tmpdir, "src") <add> if err := os.MkdirAll(dest, 0700); err != nil { <add> t.Fatal(err) <add> } <add> if err := Untar(stream, dest, &archive.TarOptions{Excludes: []string{"lolo"}}); err != nil { <add> t.Fatal(err) <add> } <add>} <ide><path>pkg/chrootarchive/init.go <ide> import ( <ide> func init() { <ide> reexec.Register("docker-untar", untar) <ide> reexec.Register("docker-applyLayer", applyLayer) <add> reexec.Init() <ide> } <ide> <ide> func fatal(err error) {
5
Javascript
Javascript
fix varynode build in vertex shader
ad7d8036ceb251c574f48becafe2cc0826f26b62
<ide><path>examples/jsm/renderers/nodes/core/NodeVary.js <ide> class NodeVary { <ide> <del> constructor( name, type, value ) { <add> constructor( name, type, snippet = '' ) { <ide> <ide> this.name = name; <ide> this.type = type; <del> this.value = value; <add> this.snippet = snippet; <ide> <ide> Object.defineProperty( this, 'isNodeVary', { value: true } ); <ide> <ide><path>examples/jsm/renderers/nodes/core/VaryNode.js <ide> import Node from './Node.js'; <add>import { NodeShaderStage } from './constants.js'; <ide> <ide> class VaryNode extends Node { <ide> <ide> class VaryNode extends Node { <ide> <ide> const type = this.getType( builder ); <ide> <del> const value = this.value.build( builder, type ); <add> // force nodeVary.snippet work in vertex stage <add> const snippet = this.value.buildStage( builder, NodeShaderStage.Vertex, type ); <add> <add> const nodeVary = builder.getVaryFromNode( this, type ); <add> nodeVary.snippet = snippet; <ide> <del> const nodeVary = builder.getVaryFromNode( this, type, value ); <ide> const propertyName = builder.getPropertyName( nodeVary ); <ide> <ide> return builder.format( propertyName, type, output ); <ide><path>examples/jsm/renderers/nodes/core/constants.js <add>export const NodeShaderStage = { <add> Vertex: 'vertex', <add> Fragment: 'fragment' <add>}; <add> <ide> export const NodeUpdateType = { <ide> None: 'none', <ide> Frame: 'frame', <ide><path>examples/jsm/renderers/webgpu/nodes/WebGPUNodeBuilder.js <ide> class WebGPUNodeBuilder extends NodeBuilder { <ide> <ide> for ( const vary of this.varys ) { <ide> <del> snippet += `${vary.name} = ${vary.value};`; <add> snippet += `${vary.name} = ${vary.snippet};`; <ide> <ide> } <ide>
4
Java
Java
fix failing tests
02949fc4a7248c0e329f688c3ae2a1a8eb048e6e
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/handler/AnnotationMethodMessageHandler.java <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <add>import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.ReflectionUtils.MethodFilter; <ide> <ide> <ide> private void handleMessageInternal(final Message<?> message, Map<MappingInfo, Ha <ide> } <ide> <ide> private boolean checkDestinationPrefix(String destination) { <del> if ((destination != null) && (this.destinationPrefixes != null)) { <del> for (String prefix : this.destinationPrefixes) { <del> if (destination.startsWith(prefix)) { <del> return true; <del> } <add> if ((destination == null) || CollectionUtils.isEmpty(this.destinationPrefixes)) { <add> return true; <add> } <add> for (String prefix : this.destinationPrefixes) { <add> if (destination.startsWith(prefix)) { <add> return true; <ide> } <ide> } <ide> return false; <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/handler/SimpleBrokerMessageHandler.java <ide> import org.springframework.messaging.simp.SimpMessageType; <ide> import org.springframework.messaging.support.MessageBuilder; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.MultiValueMap; <ide> <ide> <ide> else if (SimpMessageType.DISCONNECT.equals(messageType)) { <ide> } <ide> <ide> private boolean checkDestinationPrefix(String destination) { <del> if ((destination != null) && (this.destinationPrefixes != null)) { <del> for (String prefix : this.destinationPrefixes) { <del> if (destination.startsWith(prefix)) { <del> return true; <del> } <add> if ((destination == null) || CollectionUtils.isEmpty(this.destinationPrefixes)) { <add> return true; <add> } <add> for (String prefix : this.destinationPrefixes) { <add> if (destination.startsWith(prefix)) { <add> return true; <ide> } <ide> } <ide> return false; <add><path>spring-messaging/src/test/java/org/springframework/messaging/simp/handler/SimpleBrokerMessageHandlerTests.java <del><path>spring-messaging/src/test/java/org/springframework/messaging/simp/handler/SimpleBrokerWebMessageHandlerTests.java <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class SimpleBrokerWebMessageHandlerTests { <add>public class SimpleBrokerMessageHandlerTests { <ide> <ide> private SimpleBrokerMessageHandler messageHandler; <ide>
3
Text
Text
remove unnecessary partial sentence
a417e78b8098e9c842039652ee2c0666381eb4f5
<ide><path>docs/00-Getting-Started.md <ide> img.onload = function() { <ide> } <ide> <ide> ``` <del> <del>It is common to spec <ide>\ No newline at end of file
1
Javascript
Javascript
remove fix for
f66c33d751879d139465417291f8da2ff266631a
<ide><path>src/manipulation.js <ide> jQuery.extend({ <ide> srcElements = getAll( elem ); <ide> <ide> for ( i = 0; ( node = srcElements[ i ] ) != null; ++i ) { <del> // Ensure that the destination node is not null; Fixes #9587 <del> if ( destElements[ i ] ) { <del> fixCloneNodeIssues( node, destElements[ i ] ); <del> } <add> fixCloneNodeIssues( node, destElements[ i ] ); <ide> } <ide> } <ide>
1
Text
Text
update rntester documentation for mac m1
4ec2d6cf0ba367f2ef5ae2e2250ac12fe1202ffe
<ide><path>packages/rn-tester/README.md <ide> rm Podfile.lock <ide> If you are still having a problem after doing the clean up (which can happen if you have built RNTester with older React Native versions where files were generated inside the react-native folder.), the best way might be to clean-install react-native (e.g. remove node_modules and yarn install). <ide> <ide> Both macOS and Xcode are required. <del>- `cd packages/rn-tester` <del>- Install [Bundler](https://bundler.io/): `gem install bundler`. We use bundler to install the right version of [CocoaPods](https://cocoapods.org/) locally. <del>- Install Bundler and CocoaPods dependencies: `bundle install && bundle exec pod install`. In order to use Hermes engine instead of JSC, run: `USE_HERMES=1 bundle exec pod install` instead. <del>- Open the generated `RNTesterPods.xcworkspace`. This is not checked in, as it is generated by CocoaPods. Do not open `RNTesterPods.xcodeproj` directly. <add>1. `cd packages/rn-tester` <add>1. Install [Bundler](https://bundler.io/): `gem install bundler`. We use bundler to install the right version of [CocoaPods](https://cocoapods.org/) locally. <add>1. Install Bundler and CocoaPods dependencies: `bundle install && bundle exec pod install`. In order to use Hermes engine instead of JSC, run: `USE_HERMES=1 bundle exec pod install` instead. <add>1. Open the generated `RNTesterPods.xcworkspace`. This is not checked in, as it is generated by CocoaPods. Do not open `RNTesterPods.xcodeproj` directly. <add> <add>#### Note for M1 users <add>If you own a Mac M1 laptop, you need to run some different commands to install and run cocoapods. <add> <add>- `sudo arch -x86_64 gem install ffi`: this installs the `ffi` package to load dynamically-linked libraries. <add>- `arch -x86_64 pod install`: this run `pod install` with the right architecture. <ide> <ide> ### Running on Android <ide>
1
Ruby
Ruby
use regexp#match? rather than regexp#===
48cc754a1070cfc4fefdd49475aea3fc9c1a5e2f
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def update_table_definition(table_name, base) #:nodoc: <ide> end <ide> <ide> def add_index_options(table_name, column_name, comment: nil, **options) # :nodoc: <del> if column_name.is_a?(String) && /\W/ === column_name <add> if column_name.is_a?(String) && /\W/.match?(column_name) <ide> column_names = column_name <ide> else <ide> column_names = Array(column_name) <ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def initialize_type_map(m) # :nodoc: <ide> <ide> def register_integer_type(mapping, key, options) # :nodoc: <ide> mapping.register_type(key) do |sql_type| <del> if /\bunsigned\z/ === sql_type <add> if /\bunsigned\z/.match?(sql_type) <ide> Type::UnsignedInteger.new(options) <ide> else <ide> Type::Integer.new(options) <ide> def register_integer_type(mapping, key, options) # :nodoc: <ide> end <ide> <ide> def extract_precision(sql_type) <del> if /time/ === sql_type <add> if /time/.match?(sql_type) <ide> super || 0 <ide> else <ide> super <ide><path>activerecord/lib/active_record/connection_adapters/column.rb <ide> def has_default? <ide> end <ide> <ide> def bigint? <del> /\Abigint\b/ === sql_type <add> /\Abigint\b/.match?(sql_type) <ide> end <ide> <ide> # Returns the human name of the column name. <ide><path>activerecord/lib/active_record/connection_adapters/mysql/column.rb <ide> class Column < ConnectionAdapters::Column # :nodoc: <ide> delegate :extra, to: :sql_type_metadata, allow_nil: true <ide> <ide> def unsigned? <del> /\bunsigned\z/ === sql_type <add> /\bunsigned\z/.match?(sql_type) <ide> end <ide> <ide> def case_sensitive? <del> collation && collation !~ /_ci\z/ <add> collation && !/_ci\z/.match?(collation) <ide> end <ide> <ide> def auto_increment? <ide><path>activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb <ide> def schema_type(column) <ide> end <ide> <ide> def schema_precision(column) <del> super unless /time/ === column.sql_type && column.precision == 0 <add> super unless /time/.match?(column.sql_type) && column.precision == 0 <ide> end <ide> <ide> def schema_collation(column) <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/bit.rb <ide> def to_s <ide> end <ide> <ide> def binary? <del> /\A[01]*\Z/ === value <add> /\A[01]*\Z/.match?(value) <ide> end <ide> <ide> def hex? <del> /\A[0-9A-F]*\Z/i === value <add> /\A[0-9A-F]*\Z/i.match?(value) <ide> end <ide> <ide> protected <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/type_metadata.rb <ide> def initialize(type_metadata, oid: nil, fmod: nil) <ide> @type_metadata = type_metadata <ide> @oid = oid <ide> @fmod = fmod <del> @array = /\[\]$/ === type_metadata.sql_type <add> @array = /\[\]$/.match?(type_metadata.sql_type) <ide> end <ide> <ide> def sql_type <ide><path>activerecord/lib/active_record/tasks/mysql_database_tasks.rb <ide> def create <ide> connection.create_database configuration["database"], creation_options <ide> establish_connection configuration <ide> rescue ActiveRecord::StatementInvalid => error <del> if /database exists/ === error.message <add> if error.message.include?("database exists") <ide> raise DatabaseAlreadyExists <ide> else <ide> raise <ide><path>activerecord/lib/active_record/tasks/postgresql_database_tasks.rb <ide> def create(master_established = false) <ide> configuration.merge("encoding" => encoding) <ide> establish_connection configuration <ide> rescue ActiveRecord::StatementInvalid => error <del> if /database .* already exists/ === error.message <add> if /database .* already exists/.match?(error.message) <ide> raise DatabaseAlreadyExists <ide> else <ide> raise <ide><path>activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb <ide> class UnsignedType < ActiveRecord::Base <ide> t.unsigned_decimal :unsigned_decimal_t, precision: 10, scale: 2 <ide> end <ide> <del> @connection.columns("unsigned_types").select { |c| /^unsigned_/ === c.name }.each do |column| <add> @connection.columns("unsigned_types").select { |c| /^unsigned_/.match?(c.name) }.each do |column| <ide> assert column.unsigned? <ide> end <ide> end
10
Javascript
Javascript
use arrayqueue for flagdependencyusageplugin
b6ce40adedbd6763ab923e6196a4b643997eb512
<ide><path>lib/FlagDependencyUsagePlugin.js <ide> const Dependency = require("./Dependency"); <ide> const { UsageState } = require("./ExportsInfo"); <ide> const ModuleGraphConnection = require("./ModuleGraphConnection"); <ide> const { STAGE_DEFAULT } = require("./OptimizationStages"); <add>const ArrayQueue = require("./util/ArrayQueue"); <ide> const TupleQueue = require("./util/TupleQueue"); <ide> const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime"); <ide> <ide> class FlagDependencyUsagePlugin { <ide> /** @type {Map<Module, (string[] | ReferencedExport)[] | Map<string, string[] | ReferencedExport>>} */ <ide> const map = new Map(); <ide> <del> /** @type {DependenciesBlock[]} */ <del> const queue = [module]; <del> for (const block of queue) { <add> /** @type {ArrayQueue<DependenciesBlock>} */ <add> const queue = new ArrayQueue(); <add> queue.enqueue(module); <add> for (;;) { <add> const block = queue.dequeue(); <add> if (block === undefined) break; <ide> for (const b of block.blocks) { <ide> if ( <ide> !this.global && <ide> class FlagDependencyUsagePlugin { <ide> ) { <ide> processModule(b, b.groupOptions.entryOptions.runtime); <ide> } else { <del> queue.push(b); <add> queue.enqueue(b); <ide> } <ide> } <ide> for (const dep of block.dependencies) {
1
Text
Text
add changelog entry for [ci skip]
a9ebfc0f6a1b7a54a425887b9d1a37b08633666b
<ide><path>activerecord/CHANGELOG.md <add>* Restrict deletion of record when using `delete_all` with `uniq`, `group`, `having` <add> or `offset`. <add> <add> I these cases the generated query ignores them and that causes unintended <add> records to be deleted. <add> <add> *Leandro Facchinetti* <add> <ide> * Floats with limit >= 25 that get turned into doubles in MySQL no longer have <ide> their limit dropped from the schema. <ide>
1
Text
Text
update copyright year in license and readme
608dc83ecdec5df674cc29c0d4fcf5f983a4cc91
<ide><path>LICENSE.md <ide> BSD 3-Clause License <ide> <del>Copyright (c) 2021, freeCodeCamp. <add>Copyright (c) 2022, freeCodeCamp. <ide> All rights reserved. <ide> <ide> Redistribution and use in source and binary forms, with or without <ide><path>README.md <ide> The general platform status for all our applications is available at [`status.fr <ide> <ide> ### License <ide> <del>Copyright © 2021 freeCodeCamp.org <add>Copyright © 2022 freeCodeCamp.org <ide> <ide> The content of this repository is bound by the following licenses: <ide>
2
Text
Text
return response in code example
a590c4e7f3f515f15a577b4f2c5f57f09eddc3c0
<ide><path>errors/middleware-upgrade-guide.md <ide> export function middleware() { <ide> <ide> // clear all cookies means mark all of them as expired <ide> response.cookies.clear() <add> <add> return response <ide> } <ide> ``` <ide>
1
Text
Text
fix typo in console.md
6a7f874825a153634d5a70009cab810d6a95b6ae
<ide><path>doc/api/console.md <ide> added: v0.1.104 <ide> changes: <ide> - version: v13.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/29251 <del> description: The elapsed time is diplayed with a suitable time unit. <add> description: The elapsed time is displayed with a suitable time unit. <ide> - version: v6.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/5901 <ide> description: This method no longer supports multiple calls that don’t map
1
Javascript
Javascript
fix error on worker disconnect/destroy
73324cf76a1898d45d887a44145e7ab12236c076
<ide><path>lib/internal/cluster/child.js <ide> function _disconnect(masterInitiated) { <ide> <ide> // Extend generic Worker with methods specific to worker processes. <ide> Worker.prototype.disconnect = function() { <del> _disconnect.call(this); <add> if (![ 'disconnecting', 'destroying' ].includes(this.state)) { <add> this.state = 'disconnecting'; <add> _disconnect.call(this); <add> } <add> <ide> return this; <ide> }; <ide> <ide> Worker.prototype.destroy = function() { <del> this.exitedAfterDisconnect = true; <add> if (this.state === 'destroying') <add> return; <ide> <add> this.exitedAfterDisconnect = true; <ide> if (!this.isConnected()) { <ide> process.exit(0); <ide> } else { <add> this.state = 'destroying'; <ide> send({ act: 'exitedAfterDisconnect' }, () => process.disconnect()); <ide> process.once('disconnect', () => process.exit(0)); <ide> } <ide><path>test/parallel/test-cluster-concurrent-disconnect.js <add>'use strict'; <add> <add>// Ref: https://github.com/nodejs/node/issues/32106 <add> <add>const common = require('../common'); <add> <add>const assert = require('assert'); <add>const cluster = require('cluster'); <add>const os = require('os'); <add> <add>if (cluster.isMaster) { <add> const workers = []; <add> const numCPUs = os.cpus().length; <add> let waitOnline = numCPUs; <add> for (let i = 0; i < numCPUs; i++) { <add> const worker = cluster.fork(); <add> workers[i] = worker; <add> worker.once('online', common.mustCall(() => { <add> if (--waitOnline === 0) <add> for (const worker of workers) <add> if (worker.isConnected()) <add> worker.send(i % 2 ? 'disconnect' : 'destroy'); <add> })); <add> <add> // These errors can occur due to the nature of the test, we might be trying <add> // to send messages when the worker is disconnecting. <add> worker.on('error', (err) => { <add> assert.strictEqual(err.syscall, 'write'); <add> assert.strictEqual(err.code, 'EPIPE'); <add> }); <add> <add> worker.once('disconnect', common.mustCall(() => { <add> for (const worker of workers) <add> if (worker.isConnected()) <add> worker.send('disconnect'); <add> })); <add> <add> worker.once('exit', common.mustCall((code, signal) => { <add> assert.strictEqual(code, 0); <add> assert.strictEqual(signal, null); <add> })); <add> } <add>} else { <add> process.on('message', (msg) => { <add> if (cluster.worker.isConnected()) <add> cluster.worker[msg](); <add> }); <add>}
2
Text
Text
move thefourtheye to emeritus
1ed90e2c0c14a42dc5a269f9f6c706b5456a3701
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Stewart X Addison** &lt;sxa@uk.ibm.com&gt; <ide> * [targos](https://github.com/targos) - <ide> **Michaël Zasso** &lt;targos@protonmail.com&gt; (he/him) <del>* [thefourtheye](https://github.com/thefourtheye) - <del>**Sakthipriyan Vairamani** &lt;thechargingvolcano@gmail.com&gt; (he/him) <ide> * [TimothyGu](https://github.com/TimothyGu) - <ide> **Tiancheng "Timothy" Gu** &lt;timothygu99@gmail.com&gt; (he/him) <ide> * [tniessen](https://github.com/tniessen) - <ide> For information about the governance of the Node.js project, see <ide> **Stefan Budeanu** &lt;stefan@budeanu.com&gt; <ide> * [tellnes](https://github.com/tellnes) - <ide> **Christian Tellnes** &lt;christian@tellnes.no&gt; <add>* [thefourtheye](https://github.com/thefourtheye) - <add>**Sakthipriyan Vairamani** &lt;thechargingvolcano@gmail.com&gt; (he/him) <ide> * [thlorenz](https://github.com/thlorenz) - <ide> **Thorsten Lorenz** &lt;thlorenz@gmx.de&gt; <ide> * [trevnorris](https://github.com/trevnorris) -
1
PHP
PHP
add returntypewillchange to splfileinfo usage
a31b48afc92668ac02c29ed322734bf25e49f9d3
<ide><path>src/Illuminate/Http/Testing/File.php <ide> public function size($kilobytes) <ide> * <ide> * @return int <ide> */ <add> #[\ReturnTypeWillChange] <ide> public function getSize() <ide> { <ide> return $this->sizeToReport ?: parent::getSize();
1
Javascript
Javascript
use anchor tag for parsing urls
b091fdbafac33123cba329e6bb48b9281323ca38
<ide><path>src/ajax.js <ide> var <ide> rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, <ide> rnoContent = /^(?:GET|HEAD)$/, <ide> rprotocol = /^\/\//, <del> rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, <ide> <ide> /* Prefilters <ide> * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) <ide> var <ide> // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression <ide> allTypes = "*/".concat( "*" ), <ide> <del> // Document location <del> ajaxLocation = location.href, <del> <del> // Segment location into parts <del> ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; <add> // Anchor tag for parsing the document origin <add> originAnchor = document.createElement( "a" ); <add> originAnchor.href = location.href; <ide> <ide> // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport <ide> function addToPrefiltersOrTransports( structure ) { <ide> jQuery.extend({ <ide> etag: {}, <ide> <ide> ajaxSettings: { <del> url: ajaxLocation, <add> url: location.href, <ide> type: "GET", <del> isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), <add> isLocal: rlocalProtocol.test( location.protocol ), <ide> global: true, <ide> processData: true, <ide> async: true, <ide> jQuery.extend({ <ide> responseHeaders, <ide> // timeout handle <ide> timeoutTimer, <del> // Cross-domain detection vars <del> parts, <add> // Url cleanup var <add> urlAnchor, <ide> // To know if global events are to be dispatched <ide> fireGlobals, <ide> // Loop variable <ide> jQuery.extend({ <ide> // Add protocol if not provided (prefilters might expect it) <ide> // Handle falsy url in the settings object (#10093: consistency with old signature) <ide> // We also use the url parameter if available <del> s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) <del> .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); <add> s.url = ( ( url || s.url || location.href ) + "" ).replace( rhash, "" ) <add> .replace( rprotocol, location.protocol + "//" ); <ide> <ide> // Alias method option to type as per ticket #12004 <ide> s.type = options.method || options.type || s.method || s.type; <ide> <ide> // Extract dataTypes list <ide> s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; <ide> <del> // A cross-domain request is in order when we have a protocol:host:port mismatch <add> // A cross-domain request is in order when the origin doesn't match the current origin. <ide> if ( s.crossDomain == null ) { <del> parts = rurl.exec( s.url.toLowerCase() ); <del> s.crossDomain = !!( parts && <del> ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || <del> ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== <del> ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) <del> ); <add> urlAnchor = document.createElement( "a" ); <add> <add> // Support: IE8-11+ <add> // IE throws exception if url is malformed, e.g. http://example.com:80x/ <add> try { <add> urlAnchor.href = s.url; <add> // Support: IE8-11+ <add> // Anchor's host property isn't correctly set when s.url is relative <add> urlAnchor.href = urlAnchor.href; <add> s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== <add> urlAnchor.protocol + "//" + urlAnchor.host; <add> } catch ( e ) { <add> // If there is an error parsing the URL, assume it is crossDomain, <add> // it can be rejected by the transport if it is invalid <add> s.crossDomain = true; <add> } <ide> } <ide> <ide> // Convert data if not already a string <ide><path>test/unit/ajax.js <ide> module( "ajax", { <ide> } <ide> ]); <ide> <del> ajaxTest( "jQuery.ajax() - cross-domain detection", 7, function() { <add> ajaxTest( "jQuery.ajax() - cross-domain detection", 8, function() { <ide> function request( url, title, crossDomainOrOptions ) { <ide> return jQuery.extend( { <ide> dataType: "jsonp", <ide> module( "ajax", { <ide> { <ide> crossDomain: true <ide> } <add> ), <add> request( <add> " http://otherdomain.com", <add> "Cross-domain url with leading space is detected as cross-domain" <ide> ) <ide> ]; <ide> });
2
Ruby
Ruby
add yield to with_delivery_job test helper
ebf484a64018cbf84e6d6c39f4a22f2f2bfc9d51
<ide><path>actionmailer/test/parameterized_test.rb <ide> class DummyDeliveryJob < ActionMailer::DeliveryJob <ide> def with_delivery_job(job) <ide> old_delivery_job = ParamsMailer.delivery_job <ide> ParamsMailer.delivery_job = job <add> yield <ide> ensure <ide> ParamsMailer.delivery_job = old_delivery_job <ide> end
1
Javascript
Javascript
add repairshopr to showcase
c0654cfc9662e3199c301d3125e06a35061a167d
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://itunes.apple.com/us/app/reactto36/id989009293?mt=8', <ide> author: 'Jonathan Solichin', <ide> }, <add> { <add> name: 'RepairShopr', <add> icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/fa/96/ee/fa96ee57-c5f0-0c6f-1a34-64c9d3266b86/icon175x175.jpeg', <add> link: 'https://itunes.apple.com/us/app/repairshopr-payments-lite/id1023262888?mt=8', <add> author: 'Jed Tiotuico', <add> }, <ide> { <ide> name: 'RN Playground', <ide> icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple1/v4/20/ec/8e/20ec8eb8-9e12-6686-cd16-7ac9e3ef1d52/mzl.ngvuoybx.png',
1
Javascript
Javascript
remove recursion from unmounting portals (#1)
024e2a02591578dcf91ac68920b1ea0ff82f3949
<ide><path>src/renderers/shared/fiber/ReactFiberCommitWork.js <ide> module.exports = function<T, P, I, TI, C>( <ide> // node from the tree. <ide> removeChild(parent, node.stateNode); <ide> } else if (node.tag === Portal) { <del> // If this is a portal, then the parent is actually the portal itself. <del> // We need to keep track of which parent we're removing from. <del> // TODO: This uses a recursive call. We can get rid of that by mutating <del> // the parent binding and restoring it by searching for the host parent <del> // again when we pop past a portal. <del> const portalParent = node.stateNode.containerInfo; <del> let child = node.child; <del> while (child) { <del> unmountHostComponents(portalParent, child); <del> child = child.sibling; <del> } <add> // When we go into a portal, it becomes the parent to remove from. <add> // We will reassign it back when we pop the portal on the way up. <add> parent = node.stateNode.containerInfo; <add> node = node.child; <add> continue; <ide> } else { <ide> commitUnmount(node); <ide> if (node.child) { <ide> module.exports = function<T, P, I, TI, C>( <ide> return; <ide> } <ide> node = node.return; <add> if (node.tag === Portal) { <add> // When we go out of the portal, we need to restore the parent. <add> // Since we don't keep a stack of them, we will search for it. <add> parent = getHostParent(node); <add> } <ide> } <ide> node.sibling.return = node.return; <ide> node = node.sibling;
1
Text
Text
add .atom/bundles directory
d9f130352328fd003c36f831f190a2b805a31a09
<ide><path>.atom/bundles/Readme.md <add>Put TextMate bundles in this directory
1
Javascript
Javascript
add failing test for appendto while rendering
4e0a23ab93815b704ac762c793aa324039dfe2b6
<ide><path>packages/ember-glimmer/tests/integration/components/append-test.js <ide> moduleFor('appendTo: an element', class extends AbstractAppendTest { <ide> <ide> }); <ide> <add>moduleFor('appendTo: with multiple components', class extends AbstractAppendTest { <add> <add> append(component) { <add> this.runTask(() => component.appendTo('#qunit-fixture')); <add> this.didAppend(component); <add> return jQuery('#qunit-fixture')[0]; <add> } <add> <add> ['@test can appendTo while rendering'](assert) { <add> assert.expect(0); <add> <add> let owner = this.owner; <add> <add> this.registerComponent('first-component', { <add> ComponentClass: Component.extend({ <add> layoutName: 'components/component-one', <add> <add> didInsertElement() { <add> let SecondComponent = owner._lookupFactory('component:second-component'); <add> SecondComponent.create().appendTo('#qunit-fixture'); <add> } <add> }) <add> }); <add> <add> this.registerComponent('second-component', { <add> ComponentClass: Component.extend() <add> }); <add> <add> let FirstComponent = this.owner._lookupFactory('component:first-component'); <add> <add> this.append(FirstComponent.create()); <add> } <add> <add>}); <add> <ide> moduleFor('renderToElement: no arguments (defaults to a body context)', class extends AbstractAppendTest { <ide> <ide> append(component) {
1
Python
Python
run classifier processor for sst-2
0f96d4b1f76a7e2278a8964aceae6b89da8623de
<ide><path>examples/run_classifier.py <ide> def _create_examples(self, lines, set_type): <ide> return examples <ide> <ide> <add>class Sst2Processor(DataProcessor): <add> """Processor for the SST-2 data set (GLUE version).""" <add> <add> def get_train_examples(self, data_dir): <add> """See base class.""" <add> return self._create_examples( <add> self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") <add> <add> def get_dev_examples(self, data_dir): <add> """See base class.""" <add> return self._create_examples( <add> self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") <add> <add> def get_labels(self): <add> """See base class.""" <add> return ["0", "1"] <add> <add> def _create_examples(self, lines, set_type): <add> """Creates examples for the training and dev sets.""" <add> examples = [] <add> for (i, line) in enumerate(lines): <add> if i == 0: <add> continue <add> guid = "%s-%s" % (set_type, i) <add> text_a = line[0] <add> label = line[1] <add> examples.append( <add> InputExample(guid=guid, text_a=text_a, text_b=None, label=label)) <add> return examples <add> <add> <ide> def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): <ide> """Loads a data file into a list of `InputBatch`s.""" <ide> <ide> def main(): <ide> "cola": ColaProcessor, <ide> "mnli": MnliProcessor, <ide> "mrpc": MrpcProcessor, <add> "sst-2": Sst2Processor, <ide> } <ide> <ide> num_labels_task = { <ide> "cola": 2, <add> "sst-2": 2, <ide> "mnli": 3, <ide> "mrpc": 2, <ide> } <ide> def main(): <ide> model.eval() <ide> eval_loss, eval_accuracy = 0, 0 <ide> nb_eval_steps, nb_eval_examples = 0, 0 <del> <add> <ide> for input_ids, input_mask, segment_ids, label_ids in tqdm(eval_dataloader, desc="Evaluating"): <ide> input_ids = input_ids.to(device) <ide> input_mask = input_mask.to(device)
1
PHP
PHP
remove helpers that depend on illuminate/html
e1426baacf0c344f2ed241f0a30d49a09cc0abe8
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function info($message, $context = array()) <ide> } <ide> } <ide> <del>if ( ! function_exists('link_to')) <del>{ <del> /** <del> * Generate a HTML link. <del> * <del> * @param string $url <del> * @param string $title <del> * @param array $attributes <del> * @param bool $secure <del> * @return string <del> */ <del> function link_to($url, $title = null, $attributes = array(), $secure = null) <del> { <del> return app('html')->link($url, $title, $attributes, $secure); <del> } <del>} <del> <del>if ( ! function_exists('link_to_asset')) <del>{ <del> /** <del> * Generate a HTML link to an asset. <del> * <del> * @param string $url <del> * @param string $title <del> * @param array $attributes <del> * @param bool $secure <del> * @return string <del> */ <del> function link_to_asset($url, $title = null, $attributes = array(), $secure = null) <del> { <del> return app('html')->linkAsset($url, $title, $attributes, $secure); <del> } <del>} <del> <del>if ( ! function_exists('link_to_route')) <del>{ <del> /** <del> * Generate a HTML link to a named route. <del> * <del> * @param string $name <del> * @param string $title <del> * @param array $parameters <del> * @param array $attributes <del> * @return string <del> */ <del> function link_to_route($name, $title = null, $parameters = array(), $attributes = array()) <del> { <del> return app('html')->linkRoute($name, $title, $parameters, $attributes); <del> } <del>} <del> <del>if ( ! function_exists('link_to_action')) <del>{ <del> /** <del> * Generate a HTML link to a controller action. <del> * <del> * @param string $action <del> * @param string $title <del> * @param array $parameters <del> * @param array $attributes <del> * @return string <del> */ <del> function link_to_action($action, $title = null, $parameters = array(), $attributes = array()) <del> { <del> return app('html')->linkAction($action, $title, $parameters, $attributes); <del> } <del>} <del> <ide> if ( ! function_exists('patch')) <ide> { <ide> /**
1
Python
Python
fix conftest for website tests
be48a7b4f3d79b02e466ef34c0ccd287fec7ccb0
<ide><path>spacy/tests/website/conftest.py <ide> def nlp(): <ide> if os.environ.get('SPACY_DATA'): <ide> data_dir = os.environ.get('SPACY_DATA') <ide> else: <del> data_dir = None <add> data_dir = True <ide> return English(path=data_dir) <ide> <ide>
1
Javascript
Javascript
add messageport benchmark
ab9e89439e8f8699efe6c7786d5a3ba9be2a16a6
<ide><path>benchmark/worker/messageport.js <add>'use strict'; <add> <add>const common = require('../common.js'); <add>const { MessageChannel } = require('worker_threads'); <add>const bench = common.createBenchmark(main, { <add> payload: ['string', 'object'], <add> n: [1e6] <add>}); <add> <add>function main(conf) { <add> const n = conf.n; <add> let payload; <add> <add> switch (conf.payload) { <add> case 'string': <add> payload = 'hello world!'; <add> break; <add> case 'object': <add> payload = { action: 'pewpewpew', powerLevel: 9001 }; <add> break; <add> default: <add> throw new Error('Unsupported payload type'); <add> } <add> <add> const { port1, port2 } = new MessageChannel(); <add> <add> let messages = 0; <add> port2.onmessage = () => { <add> if (messages++ === n) { <add> bench.end(n); <add> port1.close(); <add> } else { <add> write(); <add> } <add> }; <add> bench.start(); <add> write(); <add> <add> function write() { <add> port1.postMessage(payload); <add> } <add>}
1
Mixed
Javascript
fix rntester typos
c2b699abc565c43e5289341a8b7f2694fe1229f0
<ide><path>packages/rn-tester/js/examples/Alert/AlertExample.js <ide> export default ({ <ide> category: 'UI', <ide> documentationURL: 'https://reactnative.dev/docs/alert', <ide> description: <del> 'Alerts display a concise and informative messageand prompt the user to make a decision.', <add> 'Alerts display a concise and informative message and prompt the user to make a decision.', <ide> showIndividualExamples: true, <ide> examples, <ide> }: RNTesterModule); <ide><path>packages/rn-tester/js/examples/Experimental/PlatformTest/README.md <ide> function ExampleTestCase ({ harness }) { /* ... */ } <ide> ``` <ide> <ide> <del>As of writting this README there are 2 different types of tests that the `harness` prop provides: <add>As of writing this README there are 2 different types of tests that the `harness` prop provides: <ide> <ide> ### `test(testcase: (TestContext) => void, testName: string, options?: TestOptions)` <ide> <del>This is a method to create "regular" test reminicent of other frameworks such as Jest. These are meant to be run imperatively, and while that means that they technically could work in a `useEffect` hook as a way to run the test "on mount" — it is instead recommended to try and keep these tests in callbacks instead. A good alternative to running the test on mount would be to instead put the test in a callback and render a "Start Test" button which executes the callback. <add>This is a method to create "regular" test reminiscent of other frameworks such as Jest. These are meant to be run imperatively, and while that means that they technically could work in a `useEffect` hook as a way to run the test "on mount" — it is instead recommended to try and keep these tests in callbacks instead. A good alternative to running the test on mount would be to instead put the test in a callback and render a "Start Test" button which executes the callback. <ide> <ide> The first argument is the closure in which you will run your test and make assertions. The assertions are contained in the `TestContext` object which is provided in the test closure's first argument and contains the following assertions: <ide> <ide> Here's what a basic example would look like for verifying that `pointermove` eve <ide> <ide> ```js <ide> function BasicPointerMoveTestCase({harness}) { <del> const testPointerMove = harness.useAsyncTest('pointermove event recieved'); <add> const testPointerMove = harness.useAsyncTest('pointermove event received'); <ide> <ide> return ( <ide> <View <ide><path>packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestEventRecorder.js <ide> class RNTesterPlatformTestEventRecorder { <ide> allRecords: Array<EventRecord> = []; <ide> relevantEvents: Array<string> = []; <ide> rawOrder: number = 1; <del> eventsInScope: Array<EventRecord> = []; // Tracks syncronous event dispatches <add> eventsInScope: Array<EventRecord> = []; // Tracks synchronous event dispatches <ide> recording: boolean = true; <ide> <ide> mergeTypesTruthMap: {[string]: boolean} = {}; <ide><path>packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js <ide> function FilterModalButton(props: FilterModalProps) { <ide> transparent={true}> <ide> <SafeAreaView style={styles.filterModalRoot}> <ide> <KeyboardAvoidingView <del> style={styles.filterModalKeboardAvoidingRoot} <add> style={styles.filterModalKeyboardAvoidingRoot} <ide> behavior={Platform.OS === 'ios' ? 'padding' : 'height'}> <ide> <View style={styles.filterModalContainer}> <ide> <View style={styles.filterModalContentContainer}> <ide> const styles = StyleSheet.create({ <ide> borderColor: 'rgb(171, 171, 171)', <ide> borderRadius: 8, <ide> }, <del> filterModalKeboardAvoidingRoot: { <add> filterModalKeyboardAvoidingRoot: { <ide> flex: 1, <ide> alignItems: 'center', <ide> justifyContent: 'center', <ide><path>packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestTypes.js <ide> export type PlatformTestResult = $ReadOnly<{| <ide> name: string, <ide> status: PlatformTestResultStatus, <ide> assertions: $ReadOnlyArray<PlatformTestAssertionResult>, <del> error: mixed | null, // null is technically unecessary but is kept to ensure the error is described as nullable <add> error: mixed | null, // null is technically unnecessary but is kept to ensure the error is described as nullable <ide> |}>; <ide> <ide> export type PlatformTestContext = $ReadOnly<{ <ide><path>packages/rn-tester/js/examples/Experimental/PlatformTest/usePlatformTestHarness.js <ide> export default function usePlatformTestHarness(): PlatformTestHarnessHookResult <ide> $ReadOnlyArray<PlatformTestResult>, <ide> >([]); <ide> <del> // Since updaing the test results array can get expensive at larger sizes <add> // Since updating the test results array can get expensive at larger sizes <ide> // we use a basic debouncing logic to minimize the number of re-renders <ide> // caused by adding test results <ide> const resultQueueRef = useRef<Array<PlatformTestResult>>([]); <ide> export default function usePlatformTestHarness(): PlatformTestHarnessHookResult <ide> [scheduleResultsCommit], <ide> ); <ide> <del> // When reseting the test results we should also re-mount the <add> // When resetting the test results we should also re-mount the <ide> // so we apply a key to that component which we can increment <ide> // to ensure it re-mounts <ide> const [testElementKey, setTestElementKey] = useState<number>(0); <ide> export default function usePlatformTestHarness(): PlatformTestHarnessHookResult <ide> 'assert_true', <ide> cond, <ide> desc, <del> "expected 'true' but recieved 'false'", <add> "expected 'true' but received 'false'", <ide> ), <ide> assert_equals: (a: any, b: any, desc: string) => <ide> baseAssert( <ide><path>packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventPointerMove.js <ide> * @flow <ide> */ <ide> <del>// adapated from https://github.com/web-platform-tests/wpt/blob/master/pointerevents/pointerevent_pointermove.html <add>// adapted from https://github.com/web-platform-tests/wpt/blob/master/pointerevents/pointerevent_pointermove.html <ide> <ide> import type {PlatformTestComponentBaseProps} from '../PlatformTest/RNTesterPlatformTestTypes'; <ide> import type {PointerEvent} from 'react-native/Libraries/Types/CoreEventTypes'; <ide> function PointerEventPointerMoveTestCase( <ide> const {harness} = props; <ide> <ide> const detectedPointerTypesRef = useRef({}); <del> const testPointerMove = harness.useAsyncTest('pointermove event recieved'); <add> const testPointerMove = harness.useAsyncTest('pointermove event received'); <ide> <ide> const handlers = useTestEventHandler( <ide> ['pointerMove'], <ide><path>packages/rn-tester/js/examples/FlatList/BaseFlatListExample.js <ide> const styles = StyleSheet.create({ <ide> separator: { <ide> height: 12, <ide> }, <del> separtorText: { <add> separatorText: { <ide> fontSize: 10, <ide> }, <ide> list: { <ide><path>packages/rn-tester/js/examples/FlatList/FlatList-withSeparators.js <ide> const Separator = <ide> styles.separator, <ide> {backgroundColor: highlighted ? highlightColor : defaultColor}, <ide> ]}> <del> <Text style={styles.separtorText}>{text}</Text> <add> <Text style={styles.separatorText}>{text}</Text> <ide> </View> <ide> ); <ide> }; <ide> const styles = StyleSheet.create({ <ide> separator: { <ide> height: 12, <ide> }, <del> separtorText: { <add> separatorText: { <ide> fontSize: 10, <ide> }, <ide> }); <ide><path>packages/rn-tester/js/examples/Keyboard/KeyboardExample.js <ide> import * as React from 'react'; <ide> import {useEffect, useState} from 'react'; <ide> import {Keyboard, StyleSheet, Text, View} from 'react-native'; <ide> <del>type KeybpardEventViewerProps = { <add>type KeyboardEventViewerProps = { <ide> showEvent: 'keyboardWillShow' | 'keyboardDidShow', <ide> hideEvent: 'keyboardWillHide' | 'keyboardDidHide', <ide> }; <ide> <del>const KeyboardEventViewer = (props: KeybpardEventViewerProps): React.Node => { <add>const KeyboardEventViewer = (props: KeyboardEventViewerProps): React.Node => { <ide> const {showEvent, hideEvent} = props; <ide> const [isShown, setIsShown] = useState(false); <ide> const [lastEvent, setLastEvent] = useState<?KeyboardEvent>(); <ide><path>packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js <ide> const ScrollIndicatorExample = () => { <ide> const [scrollIndicatorInsets, setScrollIndicatorInsets] = useState(null); <ide> const [showsHorizontalScrollIndic, setShowsHorizontalScrollIndic] = <ide> useState(true); <del> const [showsVerticallScrollIndic, setShowsVerticalScrollIndic] = <add> const [showsVerticalScrollIndic, setShowsVerticalScrollIndic] = <ide> useState(true); <ide> return ( <ide> <View> <ide> const ScrollIndicatorExample = () => { <ide> contentInset={{top: 10, bottom: 10, left: 10, right: 10}} <ide> scrollIndicatorInsets={scrollIndicatorInsets} <ide> showsHorizontalScrollIndicator={showsHorizontalScrollIndic} <del> showsVerticalScrollIndicator={showsVerticallScrollIndic} <add> showsVerticalScrollIndicator={showsVerticalScrollIndic} <ide> nestedScrollEnabled> <ide> {ITEMS.map(createItemRow)} <ide> </ScrollView> <ide> const ScrollIndicatorExample = () => { <ide> /> <ide> <Button <ide> label={ <del> 'showsVerticalScrollIndicator: ' + <del> showsVerticallScrollIndic.toString() <add> 'showsVerticalScrollIndicator: ' + showsVerticalScrollIndic.toString() <ide> } <del> onPress={() => setShowsVerticalScrollIndic(!showsVerticallScrollIndic)} <add> onPress={() => setShowsVerticalScrollIndic(!showsVerticalScrollIndic)} <ide> /> <ide> </View> <ide> ); <ide><path>packages/rn-tester/js/examples/SectionList/SectionList-withSeparators.js <ide> const Separator = <ide> styles.separator, <ide> {backgroundColor: highlighted ? highlightColor : defaultColor}, <ide> ]}> <del> <Text style={styles.separtorText}>{text}</Text> <add> <Text style={styles.separatorText}>{text}</Text> <ide> </View> <ide> ); <ide> }; <ide> const styles = StyleSheet.create({ <ide> separator: { <ide> height: 12, <ide> }, <del> separtorText: { <add> separatorText: { <ide> fontSize: 10, <ide> }, <ide> }); <ide><path>packages/rn-tester/js/examples/Transform/TransformExample.js <ide> import {Animated, StyleSheet, Text, View} from 'react-native'; <ide> <ide> import type {Node, Element} from 'react'; <ide> <del>function AnimateTansformSingleProp() { <add>function AnimateTransformSingleProp() { <ide> const [theta] = useState(new Animated.Value(45)); <ide> const animate = () => { <ide> theta.setValue(0); <ide> exports.examples = [ <ide> }, <ide> }, <ide> { <del> title: 'Amimate Translate single prop', <add> title: 'Animate Translate single prop', <ide> description: "rotate: '360deg'", <ide> render(): Node { <del> return <AnimateTansformSingleProp />; <add> return <AnimateTransformSingleProp />; <ide> }, <ide> }, <ide> ]; <ide><path>packages/rn-tester/js/utils/testerStateUtils.js <ide> export const getExamplesListWithBookmarksAndRecentlyUsed = ({ <ide> })); <ide> <ide> const recentlyUsedAPIs = recentlyUsed.apis <del> .map(recentAPIKey => apis.find(apiEample => apiEample.key === recentAPIKey)) <add> .map(recentAPIKey => <add> apis.find(apiExample => apiExample.key === recentAPIKey), <add> ) <ide> .filter(Boolean); <ide> <del> const bookmarkedAPIs = apis.filter(apiEample => apiEample.isBookmarked); <add> const bookmarkedAPIs = apis.filter(apiExample => apiExample.isBookmarked); <ide> <ide> const examplesList: ExamplesList = { <ide> [Screens.COMPONENTS]: [
14
Python
Python
add test of polyder return type
dd9d99c7fec0f7eedc1ad6ba4e557810f7a8954b
<ide><path>numpy/lib/tests/test_regression.py <ide> def test_include_dirs(self): <ide> assert isinstance(path, (str, unicode)) <ide> assert path != '' <ide> <add> def test_polyder_return_type(self): <add> """Ticket #1249""" <add> assert_(isinstance(np.polyder(np.poly1d([1]), 0), np.poly1d)) <add> assert_(isinstance(np.polyder([1], 0), np.ndarray)) <add> assert_(isinstance(np.polyder(np.poly1d([1]), 1), np.poly1d)) <add> assert_(isinstance(np.polyder([1], 1), np.ndarray)) <add> <add> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Javascript
Javascript
improve setup script
7e02eea553212740c141bd57e5c0ec7e6715777d
<ide><path>setup/setup.js <ide> const fs = require("fs"); <ide> const path = require("path"); <ide> const root = process.cwd(); <ide> const node_modulesFolder = path.resolve(root, "node_modules"); <add>const huskyFolder = path.resolve(root, ".husky", "_"); <ide> const webpackDependencyFolder = path.resolve(root, "node_modules/webpack"); <ide> <ide> function setup() { <del> return checkSymlinkExistsAsync() <del> .then(hasSymlink => { <add> return Promise.all([ <add> checkGitHooksInstalledAsync().then(async hasGitHooks => { <add> if (!hasGitHooks) { <add> await runSetupGitHooksAsync(); <add> if (!(await checkGitHooksInstalledAsync())) { <add> throw new Error("Git hooks were not successfully installed"); <add> } <add> } <add> }), <add> checkSymlinkExistsAsync().then(async hasSymlink => { <ide> if (!hasSymlink) { <del> return ensureYarnInstalledAsync().then(() => { <del> return runSetupAsync().then(() => { <del> return checkSymlinkExistsAsync(); <del> }); <del> }); <add> await ensureYarnInstalledAsync(); <add> await runSetupSymlinkAsync(); <add> if (!(await checkSymlinkExistsAsync())) { <add> throw new Error("windows symlink was not successfully created"); <add> } <ide> } <ide> }) <add> ]) <ide> .then(() => { <ide> process.exitCode = 0; <ide> }) <ide> function setup() { <ide> }); <ide> } <ide> <del>function runSetupAsync() { <del> return exec("yarn", ["install"], "Install dependencies") <del> .then(() => exec("yarn", ["link"], "Create webpack symlink")) <del> .then(() => exec("yarn", ["link", "webpack"], "Link webpack into itself")) <del> .then(() => exec("yarn", ["run", "husky", "install"], "Enable Git hooks")); <add>async function runSetupSymlinkAsync() { <add> await exec("yarn", ["install"], "Install dependencies"); <add> await exec("yarn", ["link"], "Create webpack symlink"); <add> await exec("yarn", ["link", "webpack"], "Link webpack into itself"); <add>} <add> <add>async function runSetupGitHooksAsync() { <add> await exec("yarn", ["run", "husky", "install"], "Enable Git hooks"); <ide> } <ide> <ide> function checkSymlinkExistsAsync() { <ide> function checkSymlinkExistsAsync() { <ide> }); <ide> } <ide> <del>function ensureYarnInstalledAsync() { <add>function checkGitHooksInstalledAsync() { <add> return new Promise((resolve, reject) => { <add> if (fs.existsSync(huskyFolder)) { <add> resolve(true); <add> } else { <add> resolve(false); <add> } <add> }); <add>} <add> <add>async function ensureYarnInstalledAsync() { <ide> const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/; <del> return execGetOutput("yarn", ["-v"], "Check yarn version") <del> .then( <del> stdout => semverPattern.test(stdout), <del> () => false <del> ) <del> .then(hasYarn => hasYarn || installYarnAsync()); <add> let hasYarn = false; <add> try { <add> const stdout = await execGetOutput("yarn", ["-v"], "Check yarn version"); <add> hasYarn = semverPattern.test(stdout); <add> } catch (e) { <add> hasYarn = false; <add> } <add> if (!hasYarn) await installYarnAsync(); <ide> } <ide> <ide> function installYarnAsync() {
1
Python
Python
use the same json loading as everywhere else
6eb6657ce4c356d7c00f601ef2a061c2395ce95a
<ide><path>libcloud/drivers/gogrid.py <ide> import time <ide> import urllib <ide> import md5, hashlib <del>try: <del> import simplejson as json <del>except: <del> import json <add> <add># JSON is included in the standard library starting with Python 2.6. For 2.5 <add># and 2.4, there's a simplejson egg at: http://pypi.python.org/pypi/simplejson <add>try: import json <add>except: import simplejson as json <ide> <ide> HOST = 'api.gogrid.com' <ide> PORTS_BY_SECURITY = { True: 443, False: 80 }
1
Text
Text
fix broken link to upgrading ruby on rails guide
746ab3c45625f70524a772b41812599f6ea98f4d
<ide><path>guides/source/4_2_release_notes.md <ide> coverage before going in. You should also first upgrade to Rails 4.1 in case you <ide> haven't and make sure your application still runs as expected before attempting <ide> an update to Rails 4.2. A list of things to watch out for when upgrading is <ide> available in the <del>[Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-1-to-rails-4-2) <add>[Upgrading Ruby on Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4.1-to-rails-4.2) <ide> guide. <ide> <ide>
1
PHP
PHP
refactor the database connector
3d30f9f8552c4c2110d5db48a2d0239a817ab023
<ide><path>system/db/connection.php <ide> public function query($sql, $bindings = array()) <ide> { <ide> return $query->rowCount(); <ide> } <del> else <del> { <del> return $result; <del> } <add> <add> return $result; <ide> } <ide> <ide> /**
1
PHP
PHP
remove unnecessary strict type check
4afcf7cea8d66b6e96e7dd8b352783cf9f2b42b2
<ide><path>src/Command/RoutesCommand.php <ide> public function execute(Arguments $args, ConsoleIo $io): ?int <ide> $output[] = $item; <ide> } <ide> <del> if ($args->getOption('sort') === true) { <add> if ($args->getOption('sort')) { <ide> usort($output, function ($a, $b) { <ide> return strcasecmp($a[0], $b[0]); <ide> });
1
Javascript
Javascript
remove webpack replacer for debug module
86380c59ddaca18c0d8336fa4c275329926e3120
<ide><path>webpack.config.js <ide> module.exports = { <ide> }, <ide> __DEVTOOLS__: !__DEV__ <ide> }), <del> // Use browser version of visionmedia-debug <del> new webpack.NormalModuleReplacementPlugin( <del> /debug\/node/, <del> 'debug' <del> ), <ide> new webpack.optimize.DedupePlugin(), <ide> new webpack.optimize.OccurenceOrderPlugin(true) <ide> ]
1
Javascript
Javascript
escape unsafe characters in request path
38149bb048d9833cc3cf9a13cbff5300fbed36ef
<ide><path>lib/http.js <ide> ClientRequest.prototype.clearTimeout = function(cb) { <ide> exports.request = function(options, cb) { <ide> if (typeof options === 'string') { <ide> options = url.parse(options); <add> } else if (options && options.path) { <add> options = util._extend({}, options); <add> options.path = encodeURI(options.path); <add> // encodeURI() doesn't escape quotes while url.parse() does. Fix up. <add> options.path = options.path.replace(/'/g, '%27'); <ide> } <ide> <ide> if (options.protocol && options.protocol !== 'http:') { <ide><path>test/simple/test-http-client-escape-path.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <add> <add>first(); <add> <add>function first() { <add> test('/~username/', '/~username/', second); <add>} <add>function second() { <add> test('/\'foo bar\'', '/%27foo%20bar%27', third); <add>} <add>function third() { <add> var expected = '/%3C%3E%22%60%20%0D%0A%09%7B%7D%7C%5C%5E~%60%27'; <add> test('/<>"` \r\n\t{}|\\^~`\'', expected); <add>} <add> <add>function test(path, expected, next) { <add> var server = http.createServer(function(req, res) { <add> assert.equal(req.url, expected); <add> res.end('OK'); <add> server.close(function() { <add> if (next) next(); <add> }); <add> }); <add> server.on('clientError', function(err) { <add> throw err; <add> }); <add> var options = { <add> host: '127.0.0.1', <add> port: common.PORT, <add> path: path <add> }; <add> server.listen(options.port, options.host, function() { <add> http.get(options); <add> }); <add>}
2
Python
Python
fix matcher import
686735b94e0a79c4111e5783ec108bd1bdc71238
<ide><path>spacy/tests/regression/test_issue1855.py <ide> from __future__ import unicode_literals <ide> import re <ide> <del>from ..matcher import Matcher <add>from ...matcher import Matcher <ide> <ide> import pytest <ide>
1
Javascript
Javascript
remove unneeded array
dabbfa7c4e8f38b9cea8f4e964a47d03b4719a08
<ide><path>lib/optimize/ModuleConcatenationPlugin.js <ide> class ModuleConcatenationPlugin { <ide> } <ide> <ide> getImports(module) { <del> return Array.from( <del> new Set( <del> module.dependencies <del> <del> // Only harmony Dependencies <del> .filter(dep => dep instanceof HarmonyImportDependency) <del> <del> // Get reference info for this dependency <del> .map(dep => dep.getReference()) <del> <del> // Reference is valid and has a module <del> .filter(ref => ref && ref.module) <del> <del> // Dependencies are simple enough to concat them <del> .filter( <del> ref => <del> Array.isArray(ref.importedNames) || <del> Array.isArray(ref.module.buildMeta.providedExports) <del> ) <del> <del> // Take the imported module <del> .map(ref => ref.module) <del> ) <add> return new Set( <add> module.dependencies <add> <add> // Get reference info only for harmony Dependencies <add> .map( <add> dep => <add> dep instanceof HarmonyImportDependency ? dep.getReference() : null <add> ) <add> <add> // Reference is valid and has a module <add> // Dependencies are simple enough to concat them <add> .filter( <add> ref => <add> ref && <add> ref.module && <add> (Array.isArray(ref.importedNames) || <add> Array.isArray(ref.module.buildMeta.providedExports)) <add> ) <add> <add> // Take the imported module <add> .map(ref => ref.module) <ide> ); <ide> } <ide>
1
Go
Go
add output to example
3d73d32499cb13c08db45354cbe1a6bc97541c5b
<ide><path>api/types/filters/example_test.go <ide> package filters // import "github.com/docker/docker/api/types/filters" <add>import "fmt" <ide> <ide> func ExampleArgs_MatchKVList() { <ide> args := NewArgs( <ide> Arg("label", "image=foo"), <ide> Arg("label", "state=running")) <ide> <ide> // returns true because there are no values for bogus <del> args.MatchKVList("bogus", nil) <add> b := args.MatchKVList("bogus", nil) <add> fmt.Println(b) <ide> <ide> // returns false because there are no sources <del> args.MatchKVList("label", nil) <add> b = args.MatchKVList("label", nil) <add> fmt.Println(b) <ide> <ide> // returns true because all sources are matched <del> args.MatchKVList("label", map[string]string{ <add> b = args.MatchKVList("label", map[string]string{ <ide> "image": "foo", <ide> "state": "running", <ide> }) <add> fmt.Println(b) <ide> <ide> // returns false because the values do not match <del> args.MatchKVList("label", map[string]string{ <add> b = args.MatchKVList("label", map[string]string{ <ide> "image": "other", <ide> }) <add> fmt.Println(b) <add> <add> // Output: <add> // true <add> // false <add> // true <add> // false <ide> }
1
Ruby
Ruby
require json lib when serialization is loaded
fffb1da3f22852c722dbc4436ec7c924435d29a5
<ide><path>activerecord/lib/active_record/serialization.rb <add>require 'active_support/json' <add> <ide> module ActiveRecord #:nodoc: <ide> module Serialization <ide> class Serializer #:nodoc: <ide><path>activesupport/lib/active_support.rb <ide> <ide> module ActiveSupport <ide> def self.load_all! <del> [Dependencies, Deprecation, Gzip, JSON, MessageVerifier, Multibyte, SecureRandom, TimeWithZone] <add> [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom, TimeWithZone] <ide> end <ide> <ide> autoload :BacktraceCleaner, 'active_support/backtrace_cleaner'
2
Text
Text
add kernelmemory to api changelog
f988a9ce5e5926b211c7e762b67cff8e9dbac380
<ide><path>docs/reference/api/docker_remote_api.md <ide> This section lists each version from latest to oldest. Each listing includes a <ide> * `GET /info` now lists engine version information and return the information of `CPUShares` and `Cpuset`. <ide> * `GET /containers/json` will return `ImageID` of the image used by container. <ide> * `POST /exec/(name)/start` will now return an HTTP 409 when the container is either stopped or paused. <add>* `POST /containers/create` now takes `KernelMemory` in HostConfig to specify kernel memory limit. <ide> * `GET /containers/(name)/json` now accepts a `size` parameter. Setting this parameter to '1' returns container size information in the `SizeRw` and `SizeRootFs` fields. <ide> * `GET /containers/(name)/json` now returns a `NetworkSettings.Networks` field, <ide> detailing network settings per network. This field deprecates the
1
Javascript
Javascript
use mustcall() for simple flow tracking
04b4d15b396a7befea31dbfec89f69ff71dc71ca
<ide><path>test/addons/async-hello-world/test.js <ide> 'use strict'; <del>require('../../common'); <add>const common = require('../../common'); <ide> var assert = require('assert'); <ide> var binding = require('./build/Release/binding'); <del>var called = false; <ide> <del>process.on('exit', function() { <del> assert(called); <del>}); <del> <del>binding(5, function(err, val) { <add>binding(5, common.mustCall(function(err, val) { <ide> assert.equal(null, err); <ide> assert.equal(10, val); <del> process.nextTick(function() { <del> called = true; <del> }); <del>}); <add> process.nextTick(common.mustCall(function() {})); <add>})); <ide><path>test/internet/test-http-dns-fail.js <ide> * should trigger the error event after each attempt. <ide> */ <ide> <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <del>var resDespiteError = false; <ide> var hadError = 0; <ide> <ide> function httpreq(count) { <ide> function httpreq(count) { <ide> port: 80, <ide> path: '/', <ide> method: 'GET' <del> }, function(res) { <del> resDespiteError = true; <del> }); <add> }, common.fail); <ide> <ide> req.on('error', function(e) { <ide> console.log(e.message); <ide> httpreq(0); <ide> <ide> <ide> process.on('exit', function() { <del> assert.equal(false, resDespiteError); <ide> assert.equal(2, hadError); <ide> }); <ide><path>test/internet/test-http-https-default-ports.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> if (!common.hasCrypto) { <ide> var https = require('https'); <ide> <ide> var http = require('http'); <del>var gotHttpsResp = false; <del>var gotHttpResp = false; <ide> <del>process.on('exit', function() { <del> assert(gotHttpsResp); <del> assert(gotHttpResp); <del> console.log('ok'); <del>}); <del> <del>https.get('https://www.google.com/', function(res) { <del> gotHttpsResp = true; <add>https.get('https://www.google.com/', common.mustCall(function(res) { <ide> res.resume(); <del>}); <add>})); <ide> <del>http.get('http://www.google.com/', function(res) { <del> gotHttpResp = true; <add>http.get('http://www.google.com/', common.mustCall(function(res) { <ide> res.resume(); <del>}); <add>})); <ide><path>test/internet/test-net-connect-timeout.js <ide> // https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8 <ide> // https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw <ide> <del>require('../common'); <add>const common = require('../common'); <ide> var net = require('net'); <ide> var assert = require('assert'); <ide> <ide> var start = new Date(); <ide> <del>var gotTimeout = false; <del> <del>var gotConnect = false; <del> <ide> var T = 100; <ide> <ide> // 192.0.2.1 is part of subnet assigned as "TEST-NET" in RFC 5737. <ide> var socket = net.createConnection(9999, '192.0.2.1'); <ide> <ide> socket.setTimeout(T); <ide> <del>socket.on('timeout', function() { <add>socket.on('timeout', common.mustCall(function() { <ide> console.error('timeout'); <del> gotTimeout = true; <ide> var now = new Date(); <ide> assert.ok(now - start < T + 500); <ide> socket.destroy(); <del>}); <del> <del>socket.on('connect', function() { <del> console.error('connect'); <del> gotConnect = true; <del> socket.destroy(); <del>}); <del> <add>})); <ide> <del>process.on('exit', function() { <del> assert.ok(gotTimeout); <del> assert.ok(!gotConnect); <del>}); <add>socket.on('connect', common.fail); <ide><path>test/internet/test-net-connect-unref.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var net = require('net'); <ide> <del>var client, killed = false, ended = false; <add>var client; <ide> var TIMEOUT = 10 * 1000; <ide> <ide> client = net.createConnection(53, '8.8.8.8', function() { <ide> client.unref(); <ide> }); <ide> <del>client.on('close', function() { <del> ended = true; <del>}); <del> <del>setTimeout(function() { <del> killed = true; <del> client.end(); <del>}, TIMEOUT).unref(); <add>client.on('close', common.fail); <ide> <del>process.on('exit', function() { <del> assert.strictEqual(killed, false, 'A client should have connected'); <del> assert.strictEqual(ended, false, 'A client should stay connected'); <del>}); <add>setTimeout(common.fail, TIMEOUT).unref(); <ide><path>test/parallel/test-child-process-buffering.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> <del>var pwd_called = false; <del>var childClosed = false; <del>var childExited = false; <del> <ide> function pwd(callback) { <ide> var output = ''; <ide> var child = common.spawnPwd(); <ide> function pwd(callback) { <ide> output += s; <ide> }); <ide> <del> child.on('exit', function(c) { <add> child.on('exit', common.mustCall(function(c) { <ide> console.log('exit: ' + c); <ide> assert.equal(0, c); <del> childExited = true; <del> }); <add> })); <ide> <del> child.on('close', function() { <add> child.on('close', common.mustCall(function() { <ide> callback(output); <del> pwd_called = true; <del> childClosed = true; <del> }); <add> })); <ide> } <ide> <ide> <ide> pwd(function(result) { <ide> assert.equal(true, result.length > 1); <ide> assert.equal('\n', result[result.length - 1]); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(true, pwd_called); <del> assert.equal(true, childExited); <del> assert.equal(true, childClosed); <del>}); <ide><path>test/parallel/test-child-process-disconnect.js <ide> if (process.argv[2] === 'child') { <ide> var child = fork(process.argv[1], ['child']); <ide> <ide> var childFlag = false; <del> var childSelfTerminate = false; <del> var parentEmit = false; <ide> var parentFlag = false; <ide> <ide> // when calling .disconnect the event should emit <ide> // and the disconnected flag should be true. <del> child.on('disconnect', function() { <del> parentEmit = true; <add> child.on('disconnect', common.mustCall(function() { <ide> parentFlag = child.connected; <del> }); <add> })); <ide> <ide> // the process should also self terminate without using signals <del> child.on('exit', function() { <del> childSelfTerminate = true; <del> }); <add> child.on('exit', common.mustCall(function() {})); <ide> <ide> // when child is listening <ide> child.on('message', function(obj) { <ide> if (process.argv[2] === 'child') { <ide> process.on('exit', function() { <ide> assert.equal(childFlag, false); <ide> assert.equal(parentFlag, false); <del> <del> assert.ok(childSelfTerminate); <del> assert.ok(parentEmit); <ide> }); <ide> } <ide><path>test/parallel/test-child-process-exec-buffer.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var exec = require('child_process').exec; <ide> var os = require('os'); <del> <del>var success_count = 0; <del> <ide> var str = 'hello'; <ide> <ide> // default encoding <del>exec('echo ' + str, function(err, stdout, stderr) { <add>exec('echo ' + str, common.mustCall(function(err, stdout, stderr) { <ide> assert.ok('string', typeof stdout, 'Expected stdout to be a string'); <ide> assert.ok('string', typeof stderr, 'Expected stderr to be a string'); <ide> assert.equal(str + os.EOL, stdout); <del> <del> success_count++; <del>}); <add>})); <ide> <ide> // no encoding (Buffers expected) <ide> exec('echo ' + str, { <ide> encoding: null <del>}, function(err, stdout, stderr) { <add>}, common.mustCall(function(err, stdout, stderr) { <ide> assert.ok(stdout instanceof Buffer, 'Expected stdout to be a Buffer'); <ide> assert.ok(stderr instanceof Buffer, 'Expected stderr to be a Buffer'); <ide> assert.equal(str + os.EOL, stdout.toString()); <del> <del> success_count++; <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(2, success_count); <del>}); <add>})); <ide><path>test/parallel/test-child-process-exec-cwd.js <ide> const common = require('../common'); <ide> var assert = require('assert'); <ide> var exec = require('child_process').exec; <ide> <del>var success_count = 0; <del>var error_count = 0; <del> <ide> var pwdcommand, dir; <ide> <ide> if (common.isWindows) { <ide> if (common.isWindows) { <ide> dir = '/dev'; <ide> } <ide> <del>exec(pwdcommand, {cwd: dir}, function(err, stdout, stderr) { <del> if (err) { <del> error_count++; <del> console.log('error!: ' + err.code); <del> console.log('stdout: ' + JSON.stringify(stdout)); <del> console.log('stderr: ' + JSON.stringify(stderr)); <del> assert.equal(false, err.killed); <del> } else { <del> success_count++; <del> console.log(stdout); <del> assert.ok(stdout.indexOf(dir) == 0); <del> } <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(1, success_count); <del> assert.equal(0, error_count); <del>}); <add>exec(pwdcommand, {cwd: dir}, common.mustCall(function(err, stdout, stderr) { <add> assert.ifError(err); <add> assert.ok(stdout.indexOf(dir) == 0); <add>})); <ide><path>test/parallel/test-child-process-exec-error.js <ide> var assert = require('assert'); <ide> var child_process = require('child_process'); <ide> <ide> function test(fun, code) { <del> var errors = 0; <del> <del> fun('does-not-exist', function(err) { <add> fun('does-not-exist', common.mustCall(function(err) { <ide> assert.equal(err.code, code); <ide> assert(/does\-not\-exist/.test(err.cmd)); <del> errors++; <del> }); <del> <del> process.on('exit', function() { <del> assert.equal(errors, 1); <del> }); <add> })); <ide> } <ide> <ide> if (common.isWindows) { <ide><path>test/parallel/test-child-process-exit-code.js <ide> var assert = require('assert'); <ide> var spawn = require('child_process').spawn; <ide> var path = require('path'); <ide> <del>var exits = 0; <del> <ide> var exitScript = path.join(common.fixturesDir, 'exit.js'); <ide> var exitChild = spawn(process.argv[0], [exitScript, 23]); <del>exitChild.on('exit', function(code, signal) { <add>exitChild.on('exit', common.mustCall(function(code, signal) { <ide> assert.strictEqual(code, 23); <ide> assert.strictEqual(signal, null); <del> <del> exits++; <del>}); <add>})); <ide> <ide> <ide> var errorScript = path.join(common.fixturesDir, <ide> 'child_process_should_emit_error.js'); <ide> var errorChild = spawn(process.argv[0], [errorScript]); <del>errorChild.on('exit', function(code, signal) { <add>errorChild.on('exit', common.mustCall(function(code, signal) { <ide> assert.ok(code !== 0); <ide> assert.strictEqual(signal, null); <del> <del> exits++; <del>}); <del> <del> <del>process.on('exit', function() { <del> assert.equal(2, exits); <del>}); <add>})); <ide><path>test/parallel/test-child-process-fork-and-spawn.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var spawn = require('child_process').spawn; <ide> var fork = require('child_process').fork; <ide> <ide> // Fork, then spawn. The spawned process should not hang. <ide> switch (process.argv[2] || '') { <ide> case '': <del> fork(__filename, ['fork']).on('exit', checkExit); <del> process.on('exit', haveExit); <add> fork(__filename, ['fork']).on('exit', common.mustCall(checkExit)); <ide> break; <ide> case 'fork': <del> spawn(process.execPath, [__filename, 'spawn']).on('exit', checkExit); <del> process.on('exit', haveExit); <add> spawn(process.execPath, [__filename, 'spawn']) <add> .on('exit', common.mustCall(checkExit)); <ide> break; <ide> case 'spawn': <ide> break; <ide> default: <ide> assert(0); <ide> } <ide> <del>var seenExit = false; <del> <ide> function checkExit(statusCode) { <del> seenExit = true; <ide> assert.equal(statusCode, 0); <ide> process.nextTick(process.exit); <ide> } <del> <del>function haveExit() { <del> assert.equal(seenExit, true); <del>} <ide><path>test/parallel/test-child-process-fork-close.js <ide> let gotMessage = false; <ide> let gotExit = false; <ide> let gotClose = false; <ide> <del>cp.on('message', function(message) { <add>cp.on('message', common.mustCall(function(message) { <ide> assert(!gotMessage); <ide> assert(!gotClose); <ide> assert.strictEqual(message, 'hello'); <ide> gotMessage = true; <del>}); <add>})); <ide> <del>cp.on('exit', function() { <add>cp.on('exit', common.mustCall(function() { <ide> assert(!gotExit); <ide> assert(!gotClose); <ide> gotExit = true; <del>}); <add>})); <ide> <del>cp.on('close', function() { <add>cp.on('close', common.mustCall(function() { <ide> assert(gotMessage); <ide> assert(gotExit); <ide> assert(!gotClose); <ide> gotClose = true; <del>}); <del> <del>process.on('exit', function() { <del> assert(gotMessage); <del> assert(gotExit); <del> assert(gotClose); <del>}); <add>})); <ide><path>test/parallel/test-child-process-fork.js <ide> 'use strict'; <add>const common = require('../common'); <ide> var assert = require('assert'); <del>var common = require('../common'); <ide> var fork = require('child_process').fork; <ide> var args = ['foo', 'bar']; <ide> <ide> assert.throws(function() { n.send(); }, TypeError); <ide> <ide> n.send({ hello: 'world' }); <ide> <del>var childExitCode = -1; <del>n.on('exit', function(c) { <del> childExitCode = c; <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(childExitCode == 0); <del>}); <add>n.on('exit', common.mustCall(function(c) { <add> assert.strictEqual(c, 0); <add>})); <ide><path>test/parallel/test-child-process-internal.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> //messages <ide> if (process.argv[2] === 'child') { <ide> var fork = require('child_process').fork; <ide> var child = fork(process.argv[1], ['child']); <ide> <del> var gotNormal; <del> child.once('message', function(data) { <del> gotNormal = data; <del> }); <add> child.once('message', common.mustCall(function(data) { <add> assert.deepStrictEqual(data, normal); <add> })); <ide> <del> var gotInternal; <del> child.once('internalMessage', function(data) { <del> gotInternal = data; <del> }); <del> <del> process.on('exit', function() { <del> assert.deepStrictEqual(gotNormal, normal); <del> assert.deepStrictEqual(gotInternal, internal); <del> }); <add> child.once('internalMessage', common.mustCall(function(data) { <add> assert.deepStrictEqual(data, internal); <add> })); <ide> } <ide><path>test/parallel/test-child-process-kill.js <ide> 'use strict'; <ide> var common = require('../common'); <ide> var assert = require('assert'); <del> <ide> var spawn = require('child_process').spawn; <del> <del>var exitCode; <del>var termSignal; <del>var gotStdoutEOF = false; <del>var gotStderrEOF = false; <del> <ide> var cat = spawn(common.isWindows ? 'cmd' : 'cat'); <ide> <add>cat.stdout.on('end', common.mustCall(function() {})); <add>cat.stderr.on('data', common.fail); <add>cat.stderr.on('end', common.mustCall(function() {})); <ide> <del>cat.stdout.on('end', function() { <del> gotStdoutEOF = true; <del>}); <del> <del>cat.stderr.on('data', function(chunk) { <del> assert.ok(false); <del>}); <del> <del>cat.stderr.on('end', function() { <del> gotStderrEOF = true; <del>}); <del> <del>cat.on('exit', function(code, signal) { <del> exitCode = code; <del> termSignal = signal; <del>}); <add>cat.on('exit', common.mustCall(function(code, signal) { <add> assert.strictEqual(code, null); <add> assert.strictEqual(signal, 'SIGTERM'); <add>})); <ide> <ide> assert.equal(cat.killed, false); <ide> cat.kill(); <ide> assert.equal(cat.killed, true); <del> <del>process.on('exit', function() { <del> assert.strictEqual(exitCode, null); <del> assert.strictEqual(termSignal, 'SIGTERM'); <del> assert.ok(gotStdoutEOF); <del> assert.ok(gotStderrEOF); <del>}); <ide><path>test/parallel/test-child-process-set-blocking.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var ch = require('child_process'); <ide> <ide> var SIZE = 100000; <del>var childGone = false; <ide> <ide> var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { <ide> stdio: 'inherit' <ide> }); <ide> <del>cp.on('exit', function(code) { <del> childGone = true; <add>cp.on('exit', common.mustCall(function(code) { <ide> assert.equal(0, code); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(childGone); <del>}); <add>})); <ide><path>test/parallel/test-child-process-spawn-error.js <ide> var common = require('../common'); <ide> var spawn = require('child_process').spawn; <ide> var assert = require('assert'); <ide> <del>var errors = 0; <del> <ide> var enoentPath = 'foo123'; <ide> var spawnargs = ['bar']; <ide> assert.equal(common.fileExists(enoentPath), false); <ide> <ide> var enoentChild = spawn(enoentPath, spawnargs); <del>enoentChild.on('error', function(err) { <add>enoentChild.on('error', common.mustCall(function(err) { <ide> assert.equal(err.code, 'ENOENT'); <ide> assert.equal(err.errno, 'ENOENT'); <ide> assert.equal(err.syscall, 'spawn ' + enoentPath); <ide> assert.equal(err.path, enoentPath); <ide> assert.deepStrictEqual(err.spawnargs, spawnargs); <del> errors++; <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(1, errors); <del>}); <add>})); <ide><path>test/parallel/test-child-process-stdin-ipc.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var spawn = require('child_process').spawn; <ide> var proc = spawn(process.execPath, [__filename, 'child'], { <ide> stdio: ['ipc', 'inherit', 'inherit'] <ide> }); <ide> <del>var childCode = -1; <del>proc.on('exit', function(code) { <del> childCode = code; <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(childCode, 0); <del>}); <add>proc.on('exit', common.mustCall(function(code) { <add> assert.strictEqual(code, 0); <add>})); <ide><path>test/parallel/test-child-process-stdin.js <ide> assert.ok(!cat.stdin.readable); <ide> cat.stdin.end(); <ide> <ide> var response = ''; <del>var exitStatus = -1; <del>var closed = false; <ide> <ide> cat.stdout.setEncoding('utf8'); <ide> cat.stdout.on('data', function(chunk) { <ide> cat.stdout.on('data', function(chunk) { <ide> <ide> cat.stdout.on('end', common.mustCall(function() {})); <ide> <del>cat.stderr.on('data', function(chunk) { <del> // shouldn't get any stderr output <del> assert.ok(false); <del>}); <add>cat.stderr.on('data', common.fail); <ide> <ide> cat.stderr.on('end', common.mustCall(function() {})); <ide> <del>cat.on('exit', function(status) { <del> console.log('exit event'); <del> exitStatus = status; <del>}); <del> <del>cat.on('close', function() { <del> closed = true; <del> if (common.isWindows) { <del> assert.equal('hello world\r\n', response); <del> } else { <del> assert.equal('hello world', response); <del> } <del>}); <add>cat.on('exit', common.mustCall(function(status) { <add> assert.strictEqual(0, status); <add>})); <ide> <del>process.on('exit', function() { <del> assert.equal(0, exitStatus); <del> assert(closed); <add>cat.on('close', common.mustCall(function() { <ide> if (common.isWindows) { <ide> assert.equal('hello world\r\n', response); <ide> } else { <ide> assert.equal('hello world', response); <ide> } <del>}); <add>})); <ide><path>test/parallel/test-cluster-http-pipe.js <ide> if (common.isWindows) { <ide> <ide> if (cluster.isMaster) { <ide> common.refreshTmpDir(); <del> var ok = false; <ide> var worker = cluster.fork(); <del> worker.on('message', function(msg) { <add> worker.on('message', common.mustCall(function(msg) { <ide> assert.equal(msg, 'DONE'); <del> ok = true; <del> }); <add> })); <ide> worker.on('exit', function() { <ide> process.exit(); <ide> }); <del> process.on('exit', function() { <del> assert(ok); <del> }); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-cluster-listening-port.js <ide> var cluster = require('cluster'); <ide> var net = require('net'); <ide> <ide> if (cluster.isMaster) { <del> var port = null; <ide> cluster.fork(); <del> cluster.on('listening', function(worker, address) { <del> port = address.port; <add> cluster.on('listening', common.mustCall(function(worker, address) { <add> const port = address.port; <ide> // ensure that the port is not 0 or null <ide> assert(port); <ide> // ensure that the port is numerical <ide> assert.strictEqual(typeof port, 'number'); <ide> worker.kill(); <del> }); <del> process.on('exit', function() { <del> // ensure that the 'listening' handler has been called <del> assert(port); <del> }); <add> })); <ide> } else { <ide> net.createServer(common.fail).listen(0); <ide> } <ide><path>test/parallel/test-cluster-net-listen.js <ide> var net = require('net'); <ide> <ide> if (cluster.isMaster) { <ide> // ensure that the worker exits peacefully <del> var worker = cluster.fork(); <del> worker.on('exit', function(statusCode) { <add> cluster.fork().on('exit', common.mustCall(function(statusCode) { <ide> assert.equal(statusCode, 0); <del> worker = null; <del> }); <del> process.on('exit', function() { <del> assert.equal(worker, null); <del> }); <add> })); <ide> } else { <ide> // listen() without port should not trigger a libuv assert <ide> net.createServer(common.fail).listen(process.exit); <ide><path>test/parallel/test-cluster-setup-master-emit.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var cluster = require('cluster'); <ide> <ide> assert(cluster.isMaster); <ide> <del>var assertsRun = 0; <del> <ide> function emitAndCatch(next) { <del> cluster.once('setup', function(settings) { <add> cluster.once('setup', common.mustCall(function(settings) { <ide> assert.strictEqual(settings.exec, 'new-exec'); <del> console.log('ok "setup" emitted with options set'); <del> assertsRun += 1; <ide> setImmediate(next); <del> }); <add> })); <ide> cluster.setupMaster({ exec: 'new-exec' }); <ide> } <ide> <ide> function emitAndCatch2(next) { <del> cluster.once('setup', function(settings) { <add> cluster.once('setup', common.mustCall(function(settings) { <ide> assert('exec' in settings); <del> console.log('ok "setup" emitted without options set'); <del> assertsRun += 1; <ide> setImmediate(next); <del> }); <add> })); <ide> cluster.setupMaster(); <ide> } <ide> <del>process.on('exit', function() { <del> assert.strictEqual(assertsRun, 2); <del> console.log('ok correct number of assertions'); <del>}); <del> <del>emitAndCatch(function() { <del> emitAndCatch2(function() { <del> console.log('ok emitted and caught'); <del> }); <del>}); <add>emitAndCatch(common.mustCall(function() { <add> emitAndCatch2(common.mustCall(function() {})); <add>})); <ide><path>test/parallel/test-cluster-uncaught-exception.js <ide> // one that the cluster module installs. <ide> // https://github.com/joyent/node/issues/2556 <ide> <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var cluster = require('cluster'); <ide> var fork = require('child_process').fork; <ide> var MAGIC_EXIT_CODE = 42; <ide> var isTestRunner = process.argv[2] != 'child'; <ide> <ide> if (isTestRunner) { <del> var exitCode = -1; <del> <del> process.on('exit', function() { <del> assert.equal(exitCode, MAGIC_EXIT_CODE); <del> }); <del> <ide> var master = fork(__filename, ['child']); <del> master.on('exit', function(code) { <del> exitCode = code; <del> }); <add> master.on('exit', common.mustCall(function(code) { <add> assert.strictEqual(code, MAGIC_EXIT_CODE); <add> })); <ide> } else if (cluster.isMaster) { <ide> process.on('uncaughtException', function() { <ide> process.nextTick(function() { <ide><path>test/parallel/test-cluster-worker-death.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var cluster = require('cluster'); <ide> <ide> if (!cluster.isMaster) { <ide> process.exit(42); <ide> } else { <del> var seenExit = 0; <del> var seenDeath = 0; <ide> var worker = cluster.fork(); <del> worker.on('exit', function(exitCode, signalCode) { <add> worker.on('exit', common.mustCall(function(exitCode, signalCode) { <ide> assert.equal(exitCode, 42); <ide> assert.equal(signalCode, null); <del> seenExit++; <del> }); <del> cluster.on('exit', function(worker_) { <add> })); <add> cluster.on('exit', common.mustCall(function(worker_) { <ide> assert.equal(worker_, worker); <del> seenDeath++; <del> }); <del> process.on('exit', function() { <del> assert.equal(seenExit, 1); <del> assert.equal(seenDeath, 1); <del> }); <add> })); <ide> } <ide><path>test/parallel/test-cluster-worker-destroy.js <ide> * both code paths. <ide> */ <ide> <del>require('../common'); <add>const common = require('../common'); <ide> var cluster = require('cluster'); <del>var assert = require('assert'); <del> <del>var worker1, worker2, workerExited, workerDisconnected; <add>var worker1, worker2; <ide> <ide> if (cluster.isMaster) { <ide> worker1 = cluster.fork(); <ide> worker2 = cluster.fork(); <ide> <del> workerExited = 0; <del> workerDisconnected = 0; <del> <ide> [worker1, worker2].forEach(function(worker) { <del> worker.on('disconnect', ondisconnect); <del> worker.on('exit', onexit); <add> worker.on('disconnect', common.mustCall(function() {})); <add> worker.on('exit', common.mustCall(function() {})); <ide> }); <del> <del> process.on('exit', onProcessExit); <del> <ide> } else { <ide> if (cluster.worker.id === 1) { <ide> // Call destroy when worker is disconnected <ide> if (cluster.isMaster) { <ide> cluster.worker.destroy(); <ide> } <ide> } <del> <del>function onProcessExit() { <del> assert.equal(workerExited, <del> 2, <del> 'When master exits, all workers should have exited too'); <del> assert.equal(workerDisconnected, <del> 2, <del> 'When master exits, all workers should have disconnected'); <del>} <del> <del>function ondisconnect() { <del> ++workerDisconnected; <del>} <del> <del>function onexit() { <del> ++workerExited; <del>} <ide><path>test/parallel/test-cluster-worker-forced-exit.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var cluster = require('cluster'); <ide> <ide> if (cluster.isWorker) { <ide> return; <ide> } <ide> <del>var unforcedOk; <del>var forcedOk; <del> <del>process.on('exit', function() { <del> assert(forcedOk); <del> assert(unforcedOk); <del>}); <del> <ide> checkUnforced(); <ide> checkForced(); <ide> <ide> function checkUnforced() { <ide> .on('online', function() { <ide> this.disconnect(); <ide> }) <del> .on('exit', function(status) { <add> .on('exit', common.mustCall(function(status) { <ide> assert.equal(status, SENTINEL); <del> unforcedOk = true; <del> }); <add> })); <ide> } <ide> <ide> function checkForced() { <ide> cluster.fork() <ide> .on('online', function() { <ide> this.process.disconnect(); <ide> }) <del> .on('exit', function(status) { <add> .on('exit', common.mustCall(function(status) { <ide> assert.equal(status, 0); <del> forcedOk = true; <del> }); <add> })); <ide> } <ide><path>test/parallel/test-crypto-domains.js <ide> var domain = require('domain'); <ide> var assert = require('assert'); <ide> var d = domain.create(); <ide> var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; <del>var errors = 0; <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> return; <ide> } <ide> var crypto = require('crypto'); <ide> <del>process.on('exit', function() { <del> assert.equal(errors, 3); <del>}); <del> <del>d.on('error', function(e) { <add>d.on('error', common.mustCall(function(e) { <ide> assert.equal(e.message, expect.shift()); <del> errors += 1; <del>}); <add>}, 3)); <ide> <ide> d.run(function() { <ide> one(); <ide><path>test/parallel/test-crypto-hash-stream-pipe.js <ide> var stream = require('stream'); <ide> var s = new stream.PassThrough(); <ide> var h = crypto.createHash('sha1'); <ide> var expect = '15987e60950cf22655b9323bc1e281f9c4aff47e'; <del>var gotData = false; <ide> <del>process.on('exit', function() { <del> assert(gotData); <del> console.log('ok'); <del>}); <del> <del>s.pipe(h).on('data', function(c) { <add>s.pipe(h).on('data', common.mustCall(function(c) { <ide> assert.equal(c, expect); <del> gotData = true; <del>}).setEncoding('hex'); <add>})).setEncoding('hex'); <ide> <ide> s.end('aoeu'); <ide><path>test/parallel/test-delayed-require.js <ide> var common = require('../common'); <ide> var path = require('path'); <ide> var assert = require('assert'); <ide> <del>var a; <del>setTimeout(function() { <del> a = require(path.join(common.fixturesDir, 'a')); <del>}, 50); <del> <del>process.on('exit', function() { <del> assert.equal(true, 'A' in a); <del> assert.equal('A', a.A()); <del> assert.equal('D', a.D()); <del>}); <add>setTimeout(common.mustCall(function() { <add> const a = require(path.join(common.fixturesDir, 'a')); <add> assert.strictEqual(true, 'A' in a); <add> assert.strictEqual('A', a.A()); <add> assert.strictEqual('D', a.D()); <add>}), 50); <ide><path>test/parallel/test-dgram-close-is-not-callback.js <ide> 'use strict'; <del>var assert = require('assert'); <ide> var common = require('../common'); <ide> var dgram = require('dgram'); <ide> <ide> var buf = Buffer.alloc(1024, 42); <ide> <ide> var socket = dgram.createSocket('udp4'); <del>var closeEvents = 0; <add> <ide> socket.send(buf, 0, buf.length, common.PORT, 'localhost'); <ide> <ide> // if close callback is not function, ignore the argument. <ide> socket.close('bad argument'); <ide> <del>socket.on('close', function() { <del> ++closeEvents; <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(closeEvents, 1); <del>}); <add>socket.on('close', common.mustCall(function() {})); <ide><path>test/parallel/test-dgram-close.js <ide> // Ensure that if a dgram socket is closed before the DNS lookup completes, it <ide> // won't crash. <ide> <del>const assert = require('assert'); <ide> const common = require('../common'); <add>const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> <ide> var buf = Buffer.alloc(1024, 42); <ide> <ide> var socket = dgram.createSocket('udp4'); <ide> var handle = socket._handle; <del>var closeEvents = 0; <del>var closeCallbacks = 0; <add> <ide> socket.send(buf, 0, buf.length, common.PORT, 'localhost'); <del>assert.strictEqual(socket.close(function() { <del> ++closeCallbacks; <del>}), socket); <del>socket.on('close', function() { <del> assert.equal(closeCallbacks, 1); <del> ++closeEvents; <del>}); <add>assert.strictEqual(socket.close(common.mustCall(function() {})), socket); <add>socket.on('close', common.mustCall(function() {})); <ide> socket = null; <ide> <ide> // Verify that accessing handle after closure doesn't throw <ide> setImmediate(function() { <ide> console.log('Handle fd is: ', handle.fd); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(closeEvents, 1); <del> assert.equal(closeCallbacks, 1); <del>}); <ide><path>test/parallel/test-dgram-implicit-bind.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var dgram = require('dgram'); <ide> <ide> var source = dgram.createSocket('udp4'); <ide> var target = dgram.createSocket('udp4'); <ide> var messages = 0; <ide> <del>process.on('exit', function() { <del> assert.equal(messages, 2); <del>}); <del> <del>target.on('message', function(buf) { <add>target.on('message', common.mustCall(function(buf) { <ide> if (buf.toString() === 'abc') ++messages; <ide> if (buf.toString() === 'def') ++messages; <ide> if (messages === 2) { <ide> source.close(); <ide> target.close(); <ide> } <del>}); <add>}, 2)); <ide> <ide> target.on('listening', function() { <ide> // Second .send() call should not throw a bind error. <ide><path>test/parallel/test-dgram-unref.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <del> <add>const common = require('../common'); <ide> var dgram = require('dgram'); <del>var closed = false; <ide> <ide> var s = dgram.createSocket('udp4'); <ide> s.bind(); <ide> s.unref(); <ide> <del>setTimeout(function() { <del> closed = true; <del> s.close(); <del>}, 1000).unref(); <del> <del>process.on('exit', function() { <del> assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); <del>}); <add>setTimeout(common.fail, 1000).unref(); <ide><path>test/parallel/test-domain-implicit-fs.js <ide> 'use strict'; <ide> // Simple tests of most basic domain functionality. <ide> <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var domain = require('domain'); <del>var caught = 0; <del>var expectCaught = 1; <ide> <ide> var d = new domain.Domain(); <ide> <del>d.on('error', function(er) { <add>d.on('error', common.mustCall(function(er) { <ide> console.error('caught', er); <ide> <ide> assert.strictEqual(er.domain, d); <ide> d.on('error', function(er) { <ide> assert.strictEqual(er.code, 'ENOENT'); <ide> assert.ok(/\bthis file does not exist\b/i.test(er.path)); <ide> assert.strictEqual(typeof er.errno, 'number'); <del> <del> caught++; <del>}); <del> <del>process.on('exit', function() { <del> console.error('exit'); <del> assert.equal(caught, expectCaught); <del> console.log('ok'); <del>}); <add>})); <ide> <ide> <ide> // implicit handling of thrown errors while in a domain, via the <ide><path>test/parallel/test-domain-timers.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var domain = require('domain'); <ide> var assert = require('assert'); <ide> <del>var timeout_err, timeout, immediate_err; <add>var timeout; <ide> <ide> var timeoutd = domain.create(); <ide> <del>timeoutd.on('error', function(e) { <del> timeout_err = e; <add>timeoutd.on('error', common.mustCall(function(e) { <add> assert.equal(e.message, 'Timeout UNREFd', 'Domain should catch timer error'); <ide> clearTimeout(timeout); <del>}); <add>})); <ide> <ide> timeoutd.run(function() { <ide> setTimeout(function() { <ide> timeoutd.run(function() { <ide> <ide> var immediated = domain.create(); <ide> <del>immediated.on('error', function(e) { <del> immediate_err = e; <del>}); <add>immediated.on('error', common.mustCall(function(e) { <add> assert.equal(e.message, 'Immediate Error', <add> 'Domain should catch immediate error'); <add>})); <ide> <ide> immediated.run(function() { <ide> setImmediate(function() { <ide> immediated.run(function() { <ide> }); <ide> <ide> timeout = setTimeout(function() {}, 10 * 1000); <del> <del>process.on('exit', function() { <del> assert.equal(timeout_err.message, 'Timeout UNREFd', <del> 'Domain should catch timer error'); <del> assert.equal(immediate_err.message, 'Immediate Error', <del> 'Domain should catch immediate error'); <del>}); <ide><path>test/parallel/test-error-reporting.js <ide> var assert = require('assert'); <ide> var exec = require('child_process').exec; <ide> var path = require('path'); <ide> <del>var exits = 0; <del> <ide> function errExec(script, callback) { <ide> var cmd = '"' + process.argv[0] + '" "' + <ide> path.join(common.fixturesDir, script) + '"'; <ide> function errExec(script, callback) { <ide> <ide> // Proxy the args for more tests. <ide> callback(err, stdout, stderr); <del> <del> // Count the tests <del> exits++; <ide> }); <ide> } <ide> <ide> <ide> // Simple throw error <del>errExec('throws_error.js', function(err, stdout, stderr) { <add>errExec('throws_error.js', common.mustCall(function(err, stdout, stderr) { <ide> assert.ok(/blah/.test(stderr)); <del>}); <add>})); <ide> <ide> <ide> // Trying to JSON.parse(undefined) <del>errExec('throws_error2.js', function(err, stdout, stderr) { <add>errExec('throws_error2.js', common.mustCall(function(err, stdout, stderr) { <ide> assert.ok(/SyntaxError/.test(stderr)); <del>}); <add>})); <ide> <ide> <ide> // Trying to JSON.parse(undefined) in nextTick <del>errExec('throws_error3.js', function(err, stdout, stderr) { <add>errExec('throws_error3.js', common.mustCall(function(err, stdout, stderr) { <ide> assert.ok(/SyntaxError/.test(stderr)); <del>}); <add>})); <ide> <ide> <ide> // throw ILLEGAL error <del>errExec('throws_error4.js', function(err, stdout, stderr) { <add>errExec('throws_error4.js', common.mustCall(function(err, stdout, stderr) { <ide> assert.ok(/\/\*\*/.test(stderr)); <ide> assert.ok(/SyntaxError/.test(stderr)); <del>}); <add>})); <ide> <ide> // Specific long exception line doesn't result in stack overflow <del>errExec('throws_error5.js', function(err, stdout, stderr) { <add>errExec('throws_error5.js', common.mustCall(function(err, stdout, stderr) { <ide> assert.ok(/SyntaxError/.test(stderr)); <del>}); <add>})); <ide> <ide> // Long exception line with length > errorBuffer doesn't result in assertion <del>errExec('throws_error6.js', function(err, stdout, stderr) { <add>errExec('throws_error6.js', common.mustCall(function(err, stdout, stderr) { <ide> assert.ok(/SyntaxError/.test(stderr)); <del>}); <add>})); <ide> <ide> // Object that throws in toString() doesn't print garbage <del>errExec('throws_error7.js', function(err, stdout, stderr) { <add>errExec('throws_error7.js', common.mustCall(function(err, stdout, stderr) { <ide> assert.ok(/<toString\(\) threw exception/.test(stderr)); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(7, exits); <del>}); <add>})); <ide><path>test/parallel/test-eval.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var util = require('util'); <ide> var assert = require('assert'); <ide> var exec = require('child_process').exec; <ide> <del>var success_count = 0; <del>var error_count = 0; <del> <ide> var cmd = ['"' + process.execPath + '"', '-e', '"console.error(process.argv)"', <ide> 'foo', 'bar'].join(' '); <ide> var expected = util.format([process.execPath, 'foo', 'bar']) + '\n'; <del>exec(cmd, function(err, stdout, stderr) { <del> if (err) { <del> console.log(err.toString()); <del> ++error_count; <del> return; <del> } <add>exec(cmd, common.mustCall(function(err, stdout, stderr) { <add> assert.ifError(err); <ide> assert.equal(stderr, expected); <del> ++success_count; <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(1, success_count); <del> assert.equal(0, error_count); <del>}); <del> <add>})); <ide><path>test/parallel/test-event-emitter-max-listeners.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var events = require('events'); <del> <del>var gotEvent = false; <del> <del>process.on('exit', function() { <del> assert(gotEvent); <del>}); <del> <ide> var e = new events.EventEmitter(); <ide> <del>e.on('maxListeners', function() { <del> gotEvent = true; <del>}); <add>e.on('maxListeners', common.mustCall(function() {})); <ide> <ide> // Should not corrupt the 'maxListeners' queue. <ide> e.setMaxListeners(42); <ide><path>test/parallel/test-event-emitter-no-error-provided-to-error-event.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var events = require('events'); <ide> var domain = require('domain'); <del> <del>var errorCatched = false; <del> <ide> var e = new events.EventEmitter(); <ide> <ide> var d = domain.create(); <ide> d.add(e); <del>d.on('error', function(er) { <add>d.on('error', common.mustCall(function(er) { <ide> assert(er instanceof Error, 'error created'); <del> errorCatched = true; <del>}); <add>})); <ide> <ide> e.emit('error'); <del> <del>process.on('exit', function() { <del> assert(errorCatched, 'error got caught'); <del>}); <ide><path>test/parallel/test-event-emitter-once.js <ide> 'use strict'; <ide> const common = require('../common'); <del>var assert = require('assert'); <ide> var events = require('events'); <ide> <ide> var e = new events.EventEmitter(); <del>var times_hello_emited = 0; <ide> <del>e.once('hello', function(a, b) { <del> times_hello_emited++; <del>}); <add>e.once('hello', common.mustCall(function(a, b) {})); <ide> <ide> e.emit('hello', 'a', 'b'); <ide> e.emit('hello', 'a', 'b'); <ide> e.once('foo', remove); <ide> e.removeListener('foo', remove); <ide> e.emit('foo'); <ide> <del>process.on('exit', function() { <del> assert.equal(1, times_hello_emited); <del>}); <del> <del>var times_recurse_emitted = 0; <del> <del>e.once('e', function() { <add>e.once('e', common.mustCall(function() { <ide> e.emit('e'); <del> times_recurse_emitted++; <del>}); <add>})); <ide> <del>e.once('e', function() { <del> times_recurse_emitted++; <del>}); <add>e.once('e', common.mustCall(function() {})); <ide> <ide> e.emit('e'); <del> <del>process.on('exit', function() { <del> assert.equal(2, times_recurse_emitted); <del>}); <ide><path>test/parallel/test-event-emitter-subclass.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var EventEmitter = require('events').EventEmitter; <ide> var util = require('util'); <ide> function MyEE(cb) { <ide> EventEmitter.call(this); <ide> } <ide> <del>var called = false; <del>var myee = new MyEE(function() { <del> called = true; <del>}); <add>var myee = new MyEE(common.mustCall(function() {})); <ide> <ide> <ide> util.inherits(ErrorEE, EventEmitter); <ide> assert.throws(function() { <ide> }, /blerg/); <ide> <ide> process.on('exit', function() { <del> assert(called); <ide> assert(!(myee._events instanceof Object)); <ide> assert.deepStrictEqual(Object.keys(myee._events), []); <ide> console.log('ok'); <ide><path>test/parallel/test-exception-handler.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var MESSAGE = 'catch me if you can'; <del>var caughtException = false; <ide> <del>process.on('uncaughtException', function(e) { <add>process.on('uncaughtException', common.mustCall(function(e) { <ide> console.log('uncaught exception! 1'); <ide> assert.equal(MESSAGE, e.message); <del> caughtException = true; <del>}); <add>})); <ide> <del>process.on('uncaughtException', function(e) { <add>process.on('uncaughtException', common.mustCall(function(e) { <ide> console.log('uncaught exception! 2'); <ide> assert.equal(MESSAGE, e.message); <del> caughtException = true; <del>}); <add>})); <ide> <ide> setTimeout(function() { <ide> throw new Error(MESSAGE); <ide> }, 10); <del> <del>process.on('exit', function() { <del> console.log('exit'); <del> assert.equal(true, caughtException); <del>}); <ide><path>test/parallel/test-file-read-noexist.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var path = require('path'); <ide> var fs = require('fs'); <del>var got_error = false; <ide> <ide> var filename = path.join(common.fixturesDir, 'does_not_exist.txt'); <del>fs.readFile(filename, 'latin1', function(err, content) { <del> if (err) { <del> got_error = true; <del> } else { <del> console.error('cat returned some content: ' + content); <del> console.error('this shouldn\'t happen as the file doesn\'t exist...'); <del> assert.equal(true, false); <del> } <del>}); <del> <del>process.on('exit', function() { <del> console.log('done'); <del> assert.equal(true, got_error); <del>}); <add>fs.readFile(filename, 'latin1', common.mustCall(function(err, content) { <add> assert.ok(err); <add>})); <ide><path>test/parallel/test-fs-exists.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var fs = require('fs'); <ide> var f = __filename; <del>var exists; <del>var doesNotExist; <ide> <del>fs.exists(f, function(y) { <del> exists = y; <del>}); <add>fs.exists(f, common.mustCall(function(y) { <add> assert.strictEqual(y, true); <add>})); <ide> <del>fs.exists(f + '-NO', function(y) { <del> doesNotExist = y; <del>}); <add>fs.exists(f + '-NO', common.mustCall(function(y) { <add> assert.strictEqual(y, false); <add>})); <ide> <ide> assert(fs.existsSync(f)); <ide> assert(!fs.existsSync(f + '-NO')); <del> <del>process.on('exit', function() { <del> assert.strictEqual(exists, true); <del> assert.strictEqual(doesNotExist, false); <del>}); <ide><path>test/parallel/test-fs-long-path.js <ide> var common = require('../common'); <ide> var fs = require('fs'); <ide> var path = require('path'); <del>var assert = require('assert'); <ide> <ide> if (!common.isWindows) { <ide> common.skip('this test is Windows-specific.'); <ide> return; <ide> } <ide> <del>var successes = 0; <del> <ide> // make a path that will be at least 260 chars long. <ide> var fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); <ide> var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); <ide> console.log({ <ide> fullPathLength: fullPath.length <ide> }); <ide> <del>fs.writeFile(fullPath, 'ok', function(err) { <add>fs.writeFile(fullPath, 'ok', common.mustCall(function(err) { <ide> if (err) throw err; <del> successes++; <ide> <del> fs.stat(fullPath, function(err, stats) { <add> fs.stat(fullPath, common.mustCall(function(err, stats) { <ide> if (err) throw err; <del> successes++; <del> }); <del>}); <add> })); <add>})); <ide> <ide> process.on('exit', function() { <ide> fs.unlinkSync(fullPath); <del> assert.equal(2, successes); <ide> }); <ide><path>test/parallel/test-fs-open.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var fs = require('fs'); <ide> <ide> try { <ide> } <ide> assert.ok(caughtException); <ide> <del>var openFd; <del>fs.open(__filename, 'r', function(err, fd) { <add>fs.open(__filename, 'r', common.mustCall(function(err, fd) { <ide> if (err) { <ide> throw err; <ide> } <del> openFd = fd; <del>}); <add>})); <ide> <del>var openFd2; <del>fs.open(__filename, 'rs', function(err, fd) { <add>fs.open(__filename, 'rs', common.mustCall(function(err, fd) { <ide> if (err) { <ide> throw err; <ide> } <del> openFd2 = fd; <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(openFd); <del> assert.ok(openFd2); <del>}); <del> <add>})); <ide><path>test/parallel/test-fs-read-buffer.js <ide> const fd = fs.openSync(filepath, 'r'); <ide> const expected = 'xyz\n'; <ide> const bufferAsync = Buffer.allocUnsafe(expected.length); <ide> const bufferSync = Buffer.allocUnsafe(expected.length); <del>let readCalled = 0; <ide> <del>fs.read(fd, bufferAsync, 0, expected.length, 0, function(err, bytesRead) { <del> readCalled++; <del> <del> assert.equal(bytesRead, expected.length); <del> assert.deepStrictEqual(bufferAsync, Buffer.from(expected)); <del>}); <add>fs.read(fd, <add> bufferAsync, <add> 0, <add> expected.length, <add> 0, <add> common.mustCall(function(err, bytesRead) { <add> assert.equal(bytesRead, expected.length); <add> assert.deepStrictEqual(bufferAsync, Buffer.from(expected)); <add> })); <ide> <ide> var r = fs.readSync(fd, bufferSync, 0, expected.length, 0); <ide> assert.deepStrictEqual(bufferSync, Buffer.from(expected)); <ide> assert.equal(r, expected.length); <del> <del>process.on('exit', function() { <del> assert.equal(readCalled, 1); <del>}); <ide><path>test/parallel/test-fs-read.js <ide> const fs = require('fs'); <ide> const filepath = path.join(common.fixturesDir, 'x.txt'); <ide> const fd = fs.openSync(filepath, 'r'); <ide> const expected = 'xyz\n'; <del>let readCalled = 0; <ide> <del>fs.read(fd, expected.length, 0, 'utf-8', function(err, str, bytesRead) { <del> readCalled++; <del> <del> assert.ok(!err); <del> assert.equal(str, expected); <del> assert.equal(bytesRead, expected.length); <del>}); <add>fs.read(fd, <add> expected.length, <add> 0, <add> 'utf-8', <add> common.mustCall(function(err, str, bytesRead) { <add> assert.ok(!err); <add> assert.equal(str, expected); <add> assert.equal(bytesRead, expected.length); <add> })); <ide> <ide> var r = fs.readSync(fd, expected.length, 0, 'utf-8'); <ide> assert.equal(r[0], expected); <ide> assert.equal(r[1], expected.length); <del> <del>process.on('exit', function() { <del> assert.equal(readCalled, 1); <del>}); <ide><path>test/parallel/test-fs-readfile-error.js <ide> if (process.platform === 'freebsd') { <ide> return; <ide> } <ide> <del>var callbacks = 0; <del> <ide> function test(env, cb) { <ide> var filename = path.join(common.fixturesDir, 'test-fs-readfile-error.js'); <ide> var execPath = '"' + process.execPath + '" "' + filename + '"'; <ide> function test(env, cb) { <ide> }); <ide> } <ide> <del>test({ NODE_DEBUG: '' }, function(data) { <add>test({ NODE_DEBUG: '' }, common.mustCall(function(data) { <ide> assert(/EISDIR/.test(data)); <ide> assert(!/test-fs-readfile-error/.test(data)); <del> callbacks++; <del>}); <add>})); <ide> <del>test({ NODE_DEBUG: 'fs' }, function(data) { <add>test({ NODE_DEBUG: 'fs' }, common.mustCall(function(data) { <ide> assert(/EISDIR/.test(data)); <ide> assert(/test-fs-readfile-error/.test(data)); <del> callbacks++; <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(callbacks, 2); <del>}); <add>})); <ide><path>test/parallel/test-fs-readfile-zero-byte-liar.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var fs = require('fs'); <ide> <ide> fs.fstatSync = function(fd) { <ide> var d = fs.readFileSync(__filename, 'utf8'); <ide> assert.equal(d, dataExpected); <ide> <del>var called = false; <del>fs.readFile(__filename, 'utf8', function(er, d) { <add>fs.readFile(__filename, 'utf8', common.mustCall(function(er, d) { <ide> assert.equal(d, dataExpected); <del> called = true; <del>}); <del> <del>process.on('exit', function() { <del> assert(called); <del> console.log('ok'); <del>}); <add>})); <ide><path>test/parallel/test-fs-realpath.js <ide> function asynctest(testBlock, args, callback, assertBlock) { <ide> <ide> // sub-tests: <ide> function test_simple_error_callback(cb) { <del> var ncalls = 0; <del> <del> fs.realpath('/this/path/does/not/exist', function(err, s) { <add> fs.realpath('/this/path/does/not/exist', common.mustCall(function(err, s) { <ide> assert(err); <ide> assert(!s); <del> ncalls++; <ide> cb(); <del> }); <del> <del> process.on('exit', function() { <del> assert.equal(ncalls, 1); <del> }); <add> })); <ide> } <ide> <ide> function test_simple_relative_symlink(callback) { <ide><path>test/parallel/test-fs-stat.js <ide> /* eslint-disable strict */ <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var fs = require('fs'); <del>var got_error = false; <del>var success_count = 0; <ide> <del>fs.stat('.', function(err, stats) { <del> if (err) { <del> got_error = true; <del> } else { <del> console.dir(stats); <del> assert.ok(stats.mtime instanceof Date); <del> success_count++; <del> } <add>fs.stat('.', common.mustCall(function(err, stats) { <add> assert.ifError(err); <add> assert.ok(stats.mtime instanceof Date); <ide> assert(this === global); <del>}); <add>})); <ide> <del>fs.stat('.', function(err, stats) { <add>fs.stat('.', common.mustCall(function(err, stats) { <ide> assert.ok(stats.hasOwnProperty('blksize')); <ide> assert.ok(stats.hasOwnProperty('blocks')); <del>}); <add>})); <ide> <del>fs.lstat('.', function(err, stats) { <del> if (err) { <del> got_error = true; <del> } else { <del> console.dir(stats); <del> assert.ok(stats.mtime instanceof Date); <del> success_count++; <del> } <add>fs.lstat('.', common.mustCall(function(err, stats) { <add> assert.ifError(err); <add> assert.ok(stats.mtime instanceof Date); <ide> assert(this === global); <del>}); <add>})); <ide> <ide> // fstat <del>fs.open('.', 'r', undefined, function(err, fd) { <add>fs.open('.', 'r', undefined, common.mustCall(function(err, fd) { <ide> assert.ok(!err); <ide> assert.ok(fd); <ide> <del> fs.fstat(fd, function(err, stats) { <del> if (err) { <del> got_error = true; <del> } else { <del> console.dir(stats); <del> assert.ok(stats.mtime instanceof Date); <del> success_count++; <del> fs.close(fd); <del> } <add> fs.fstat(fd, common.mustCall(function(err, stats) { <add> assert.ifError(err); <add> assert.ok(stats.mtime instanceof Date); <add> fs.close(fd); <ide> assert(this === global); <del> }); <add> })); <ide> <ide> assert(this === global); <del>}); <add>})); <ide> <ide> // fstatSync <del>fs.open('.', 'r', undefined, function(err, fd) { <add>fs.open('.', 'r', undefined, common.mustCall(function(err, fd) { <ide> var stats; <ide> try { <ide> stats = fs.fstatSync(fd); <ide> } catch (err) { <del> got_error = true; <add> common.fail(err); <ide> } <ide> if (stats) { <ide> console.dir(stats); <ide> assert.ok(stats.mtime instanceof Date); <del> success_count++; <ide> } <ide> fs.close(fd); <del>}); <add>})); <ide> <ide> console.log(`stating: ${__filename}`); <del>fs.stat(__filename, function(err, s) { <del> if (err) { <del> got_error = true; <del> } else { <del> console.dir(s); <del> success_count++; <add>fs.stat(__filename, common.mustCall(function(err, s) { <add> assert.ifError(err); <ide> <del> console.log('isDirectory: ' + JSON.stringify(s.isDirectory())); <del> assert.equal(false, s.isDirectory()); <add> console.dir(s); <ide> <del> console.log('isFile: ' + JSON.stringify(s.isFile())); <del> assert.equal(true, s.isFile()); <add> console.log('isDirectory: ' + JSON.stringify(s.isDirectory())); <add> assert.equal(false, s.isDirectory()); <ide> <del> console.log('isSocket: ' + JSON.stringify(s.isSocket())); <del> assert.equal(false, s.isSocket()); <add> console.log('isFile: ' + JSON.stringify(s.isFile())); <add> assert.equal(true, s.isFile()); <ide> <del> console.log('isBlockDevice: ' + JSON.stringify(s.isBlockDevice())); <del> assert.equal(false, s.isBlockDevice()); <add> console.log('isSocket: ' + JSON.stringify(s.isSocket())); <add> assert.equal(false, s.isSocket()); <ide> <del> console.log('isCharacterDevice: ' + JSON.stringify(s.isCharacterDevice())); <del> assert.equal(false, s.isCharacterDevice()); <add> console.log('isBlockDevice: ' + JSON.stringify(s.isBlockDevice())); <add> assert.equal(false, s.isBlockDevice()); <ide> <del> console.log('isFIFO: ' + JSON.stringify(s.isFIFO())); <del> assert.equal(false, s.isFIFO()); <add> console.log('isCharacterDevice: ' + JSON.stringify(s.isCharacterDevice())); <add> assert.equal(false, s.isCharacterDevice()); <ide> <del> console.log('isSymbolicLink: ' + JSON.stringify(s.isSymbolicLink())); <del> assert.equal(false, s.isSymbolicLink()); <del> <del> assert.ok(s.mtime instanceof Date); <del> } <del>}); <add> console.log('isFIFO: ' + JSON.stringify(s.isFIFO())); <add> assert.equal(false, s.isFIFO()); <ide> <del>process.on('exit', function() { <del> assert.equal(5, success_count); <del> assert.equal(false, got_error); <del>}); <add> console.log('isSymbolicLink: ' + JSON.stringify(s.isSymbolicLink())); <add> assert.equal(false, s.isSymbolicLink()); <ide> <add> assert.ok(s.mtime instanceof Date); <add>})); <ide><path>test/parallel/test-fs-stream-double-close.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> var fs = require('fs'); <ide> <ide> common.refreshTmpDir(); <ide> function test1(stream) { <ide> <ide> function test2(stream) { <ide> stream.destroy(); <del> stream.on('open', function(fd) { <add> stream.on('open', common.mustCall(function(fd) { <ide> stream.destroy(); <del> open_cb_called++; <del> }); <del> process.on('exit', function() { <del> assert.equal(open_cb_called, 1); <del> }); <del> var open_cb_called = 0; <add> })); <ide> } <ide> <ide> function test3(stream) { <del> stream.on('open', function(fd) { <add> stream.on('open', common.mustCall(function(fd) { <ide> stream.destroy(); <ide> stream.destroy(); <del> open_cb_called++; <del> }); <del> process.on('exit', function() { <del> assert.equal(open_cb_called, 1); <del> }); <del> var open_cb_called = 0; <add> })); <ide> } <ide><path>test/parallel/test-fs-symlink-dir-junction-relative.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var path = require('path'); <ide> var fs = require('fs'); <del>var completed = 0; <del>var expected_tests = 2; <ide> <ide> var linkPath1 = path.join(common.tmpDir, 'junction1'); <ide> var linkPath2 = path.join(common.tmpDir, 'junction2'); <ide> var linkData = path.join(common.fixturesDir); <ide> common.refreshTmpDir(); <ide> <ide> // Test fs.symlink() <del>fs.symlink(linkData, linkPath1, 'junction', function(err) { <add>fs.symlink(linkData, linkPath1, 'junction', common.mustCall(function(err) { <ide> if (err) throw err; <ide> verifyLink(linkPath1); <del>}); <add>})); <ide> <ide> // Test fs.symlinkSync() <ide> fs.symlinkSync(linkData, linkPath2, 'junction'); <ide> function verifyLink(linkPath) { <ide> <ide> // Clean up. <ide> fs.unlinkSync(linkPath); <del> <del> completed++; <ide> } <del> <del>process.on('exit', function() { <del> assert.equal(completed, expected_tests); <del>}); <ide><path>test/parallel/test-fs-symlink-dir-junction.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var path = require('path'); <ide> var fs = require('fs'); <del>var completed = 0; <del>var expected_tests = 4; <ide> <ide> // test creating and reading symbolic link <ide> var linkData = path.join(common.fixturesDir, 'cycles/'); <ide> common.refreshTmpDir(); <ide> console.log('linkData: ' + linkData); <ide> console.log('linkPath: ' + linkPath); <ide> <del>fs.symlink(linkData, linkPath, 'junction', function(err) { <add>fs.symlink(linkData, linkPath, 'junction', common.mustCall(function(err) { <ide> if (err) throw err; <del> completed++; <ide> <del> fs.lstat(linkPath, function(err, stats) { <add> fs.lstat(linkPath, common.mustCall(function(err, stats) { <ide> if (err) throw err; <ide> assert.ok(stats.isSymbolicLink()); <del> completed++; <ide> <del> fs.readlink(linkPath, function(err, destination) { <add> fs.readlink(linkPath, common.mustCall(function(err, destination) { <ide> if (err) throw err; <ide> assert.equal(destination, linkData); <del> completed++; <ide> <del> fs.unlink(linkPath, function(err) { <add> fs.unlink(linkPath, common.mustCall(function(err) { <ide> if (err) throw err; <ide> assert(!common.fileExists(linkPath)); <ide> assert(common.fileExists(linkData)); <del> completed++; <del> }); <del> }); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(completed, expected_tests); <del>}); <del> <add> })); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-fs-truncate-fd.js <ide> var tmp = common.tmpDir; <ide> common.refreshTmpDir(); <ide> var filename = path.resolve(tmp, 'truncate-file.txt'); <ide> <del>var success = 0; <del> <ide> fs.writeFileSync(filename, 'hello world', 'utf8'); <ide> var fd = fs.openSync(filename, 'r+'); <del>fs.truncate(fd, 5, function(err) { <add>fs.truncate(fd, 5, common.mustCall(function(err) { <ide> assert.ok(!err); <ide> assert.equal(fs.readFileSync(filename, 'utf8'), 'hello'); <del> success++; <del>}); <add>})); <ide> <ide> process.on('exit', function() { <ide> fs.closeSync(fd); <ide> fs.unlinkSync(filename); <del> assert.equal(success, 1); <ide> console.log('ok'); <ide> }); <ide><path>test/parallel/test-fs-truncate.js <ide> assert.equal(stat.size, 0); <ide> fs.closeSync(fd); <ide> <ide> // async tests <del>var success = 0; <del>testTruncate(function(er) { <add>testTruncate(common.mustCall(function(er) { <ide> if (er) throw er; <del> success++; <del> testFtruncate(function(er) { <add> testFtruncate(common.mustCall(function(er) { <ide> if (er) throw er; <del> success++; <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(success, 2); <del> console.log('ok'); <del>}); <add> })); <add>})); <ide> <ide> function testTruncate(cb) { <ide> fs.writeFile(filename, data, function(er) { <ide><path>test/parallel/test-fs-write-buffer.js <ide> const Buffer = require('buffer').Buffer; <ide> const fs = require('fs'); <ide> const filename = path.join(common.tmpDir, 'write.txt'); <ide> const expected = Buffer.from('hello'); <del>let openCalled = 0; <del>let writeCalled = 0; <del> <ide> <ide> common.refreshTmpDir(); <ide> <del>fs.open(filename, 'w', 0o644, function(err, fd) { <del> openCalled++; <add>fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) { <ide> if (err) throw err; <ide> <del> fs.write(fd, expected, 0, expected.length, null, function(err, written) { <del> writeCalled++; <del> if (err) throw err; <del> <del> assert.equal(expected.length, written); <del> fs.closeSync(fd); <add> fs.write(fd, <add> expected, <add> 0, <add> expected.length, <add> null, <add> common.mustCall(function(err, written) { <add> if (err) throw err; <ide> <del> var found = fs.readFileSync(filename, 'utf8'); <del> assert.deepStrictEqual(expected.toString(), found); <del> fs.unlinkSync(filename); <del> }); <del>}); <add> assert.equal(expected.length, written); <add> fs.closeSync(fd); <ide> <del>process.on('exit', function() { <del> assert.equal(1, openCalled); <del> assert.equal(1, writeCalled); <del>}); <add> var found = fs.readFileSync(filename, 'utf8'); <add> assert.deepStrictEqual(expected.toString(), found); <add> fs.unlinkSync(filename); <add> })); <add>})); <ide><path>test/parallel/test-fs-write-file.js <ide> var s = '南越国是前203年至前111年存在于岭南地区的一个国家 <ide> '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + <ide> '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; <ide> <del>var ncallbacks = 0; <del> <del>fs.writeFile(filename, s, function(e) { <add>fs.writeFile(filename, s, common.mustCall(function(e) { <ide> if (e) throw e; <ide> <del> ncallbacks++; <del> <del> fs.readFile(filename, function(e, buffer) { <add> fs.readFile(filename, common.mustCall(function(e, buffer) { <ide> if (e) throw e; <del> ncallbacks++; <ide> assert.equal(Buffer.byteLength(s), buffer.length); <del> }); <del>}); <add> })); <add>})); <ide> <ide> // test that writeFile accepts buffers <ide> var filename2 = join(common.tmpDir, 'test2.txt'); <ide> var buf = Buffer.from(s, 'utf8'); <ide> <del>fs.writeFile(filename2, buf, function(e) { <add>fs.writeFile(filename2, buf, common.mustCall(function(e) { <ide> if (e) throw e; <ide> <del> ncallbacks++; <del> <del> fs.readFile(filename2, function(e, buffer) { <add> fs.readFile(filename2, common.mustCall(function(e, buffer) { <ide> if (e) throw e; <del> ncallbacks++; <add> <ide> assert.equal(buf.length, buffer.length); <del> }); <del>}); <add> })); <add>})); <ide> <ide> // test that writeFile accepts numbers. <ide> var filename3 = join(common.tmpDir, 'test3.txt'); <ide> <ide> var m = 0o600; <del>fs.writeFile(filename3, n, { mode: m }, function(e) { <add>fs.writeFile(filename3, n, { mode: m }, common.mustCall(function(e) { <ide> if (e) throw e; <ide> <ide> // windows permissions aren't unix <ide> fs.writeFile(filename3, n, { mode: m }, function(e) { <ide> assert.equal(st.mode & 0o700, m); <ide> } <ide> <del> ncallbacks++; <del> <del> fs.readFile(filename3, function(e, buffer) { <add> fs.readFile(filename3, common.mustCall(function(e, buffer) { <ide> if (e) throw e; <del> ncallbacks++; <add> <ide> assert.equal(Buffer.byteLength('' + n), buffer.length); <del> }); <del>}); <add> })); <add>})); <ide> <ide> // test that writeFile accepts file descriptors <ide> var filename4 = join(common.tmpDir, 'test4.txt'); <ide> <del>fs.open(filename4, 'w+', function(e, fd) { <add>fs.open(filename4, 'w+', common.mustCall(function(e, fd) { <ide> if (e) throw e; <ide> <del> ncallbacks++; <del> <del> fs.writeFile(fd, s, function(e) { <add> fs.writeFile(fd, s, common.mustCall(function(e) { <ide> if (e) throw e; <ide> <del> ncallbacks++; <del> <del> fs.close(fd, function(e) { <add> fs.close(fd, common.mustCall(function(e) { <ide> if (e) throw e; <ide> <del> ncallbacks++; <del> <del> fs.readFile(filename4, function(e, buffer) { <add> fs.readFile(filename4, common.mustCall(function(e, buffer) { <ide> if (e) throw e; <ide> <del> ncallbacks++; <ide> assert.equal(Buffer.byteLength(s), buffer.length); <del> }); <del> }); <del> }); <del>}); <add> })); <add> })); <add> })); <add>})); <ide> <ide> process.on('exit', function() { <del> assert.equal(10, ncallbacks); <del> <ide> fs.unlinkSync(filename); <ide> fs.unlinkSync(filename2); <ide> fs.unlinkSync(filename3); <ide><path>test/parallel/test-fs-write-string-coerce.js <ide> common.refreshTmpDir(); <ide> var fn = path.join(common.tmpDir, 'write-string-coerce.txt'); <ide> var data = true; <ide> var expected = data + ''; <del>var found; <ide> <del>fs.open(fn, 'w', 0o644, function(err, fd) { <add>fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { <ide> if (err) throw err; <ide> console.log('open done'); <del> fs.write(fd, data, 0, 'utf8', function(err, written) { <add> fs.write(fd, data, 0, 'utf8', common.mustCall(function(err, written) { <ide> console.log('write done'); <ide> if (err) throw err; <ide> assert.equal(Buffer.byteLength(expected), written); <ide> fs.closeSync(fd); <del> found = fs.readFileSync(fn, 'utf8'); <add> const found = fs.readFileSync(fn, 'utf8'); <ide> console.log('expected: "%s"', expected); <ide> console.log('found: "%s"', found); <ide> fs.unlinkSync(fn); <del> }); <del>}); <del> <del> <del>process.on('exit', function() { <del> assert.equal(expected, found); <del>}); <add> assert.strictEqual(expected, found); <add> })); <add>})); <ide><path>test/parallel/test-fs-write.js <ide> var fn = path.join(common.tmpDir, 'write.txt'); <ide> var fn2 = path.join(common.tmpDir, 'write2.txt'); <ide> var expected = 'ümlaut.'; <ide> var constants = fs.constants; <del>var found, found2; <ide> <ide> common.refreshTmpDir(); <ide> <del>fs.open(fn, 'w', 0o644, function(err, fd) { <add>fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { <ide> if (err) throw err; <ide> console.log('open done'); <ide> fs.write(fd, '', 0, 'utf8', function(err, written) { <ide> assert.equal(0, written); <ide> }); <del> fs.write(fd, expected, 0, 'utf8', function(err, written) { <add> fs.write(fd, expected, 0, 'utf8', common.mustCall(function(err, written) { <ide> console.log('write done'); <ide> if (err) throw err; <ide> assert.equal(Buffer.byteLength(expected), written); <ide> fs.closeSync(fd); <del> found = fs.readFileSync(fn, 'utf8'); <add> const found = fs.readFileSync(fn, 'utf8'); <ide> console.log('expected: "%s"', expected); <ide> console.log('found: "%s"', found); <ide> fs.unlinkSync(fn); <del> }); <del>}); <add> assert.strictEqual(expected, found); <add> })); <add>})); <ide> <ide> <ide> fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0o644, <del> function(err, fd) { <add> common.mustCall(function(err, fd) { <ide> if (err) throw err; <ide> console.log('open done'); <ide> fs.write(fd, '', 0, 'utf8', function(err, written) { <ide> assert.equal(0, written); <ide> }); <del> fs.write(fd, expected, 0, 'utf8', function(err, written) { <add> fs.write(fd, expected, 0, 'utf8', common.mustCall(function(err, written) { <ide> console.log('write done'); <ide> if (err) throw err; <ide> assert.equal(Buffer.byteLength(expected), written); <ide> fs.closeSync(fd); <del> found2 = fs.readFileSync(fn2, 'utf8'); <add> const found = fs.readFileSync(fn2, 'utf8'); <ide> console.log('expected: "%s"', expected); <del> console.log('found: "%s"', found2); <add> console.log('found: "%s"', found); <ide> fs.unlinkSync(fn2); <del> }); <del> }); <del> <del> <del>process.on('exit', function() { <del> assert.equal(expected, found); <del> assert.equal(expected, found2); <del>}); <add> assert.strictEqual(expected, found); <add> })); <add> })); <ide><path>test/parallel/test-http-abort-before-end.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var http = require('http'); <ide> var assert = require('assert'); <ide> <del>var server = http.createServer(function(req, res) { <del> assert(false); // should not be called <del>}); <add>var server = http.createServer(common.fail); <ide> <ide> server.listen(0, function() { <ide> var req = http.request({ <ide><path>test/parallel/test-http-abort-client.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var http = require('http'); <del>var assert = require('assert'); <ide> <ide> var server = http.Server(function(req, res) { <ide> console.log('Server accepted request.'); <ide> var server = http.Server(function(req, res) { <ide> res.destroy(); <ide> }); <ide> <del>var responseClose = false; <del> <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> http.get({ <ide> port: this.address().port, <ide> headers: { connection: 'keep-alive' } <del> }, function(res) { <add> }, common.mustCall(function(res) { <ide> server.close(); <ide> <ide> console.log('Got res: ' + res.statusCode); <ide> server.listen(0, function() { <ide> }); <ide> <ide> // it would be nice if this worked: <del> res.on('close', function() { <del> console.log('Response aborted'); <del> responseClose = true; <del> }); <del> }); <del>}); <del> <del> <del>process.on('exit', function() { <del> assert.ok(responseClose); <del>}); <add> res.on('close', common.mustCall(function() {})); <add> })); <add>})); <ide><path>test/parallel/test-http-agent-no-protocol.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> <del>var request = 0; <del>var response = 0; <del>process.on('exit', function() { <del> assert.equal(1, request, 'http server "request" callback was not called'); <del> assert.equal(1, response, 'http client "response" callback was not called'); <del>}); <del> <del>var server = http.createServer(function(req, res) { <add>var server = http.createServer(common.mustCall(function(req, res) { <ide> res.end(); <del> request++; <del>}).listen(0, '127.0.0.1', function() { <add>})).listen(0, '127.0.0.1', common.mustCall(function() { <ide> var opts = url.parse(`http://127.0.0.1:${this.address().port}/`); <ide> <ide> // remove the `protocol` field… the `http` module should fall back <ide> // to "http:", as defined by the global, default `http.Agent` instance. <ide> opts.agent = new http.Agent(); <ide> opts.agent.protocol = null; <ide> <del> http.get(opts, function(res) { <del> response++; <add> http.get(opts, common.mustCall(function(res) { <ide> res.resume(); <ide> server.close(); <del> }); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-http-agent-null.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var http = require('http'); <ide> <del>var request = 0; <del>var response = 0; <del>process.on('exit', function() { <del> assert.equal(request, 1, 'http server "request" callback was not called'); <del> assert.equal(response, 1, 'http request "response" callback was not called'); <del>}); <del> <del>var server = http.createServer(function(req, res) { <del> request++; <add>var server = http.createServer(common.mustCall(function(req, res) { <ide> res.end(); <del>}).listen(0, function() { <add>})).listen(0, common.mustCall(function() { <ide> var options = { <ide> agent: null, <ide> port: this.address().port <ide> }; <del> http.get(options, function(res) { <del> response++; <add> http.get(options, common.mustCall(function(res) { <ide> res.resume(); <ide> server.close(); <del> }); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-http-bind-twice.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <del>var gotError = false; <add>var server1 = http.createServer(common.fail); <add>server1.listen(0, '127.0.0.1', common.mustCall(function() { <add> var server2 = http.createServer(common.fail); <add> server2.listen(this.address().port, '127.0.0.1', common.fail); <ide> <del>process.on('exit', function() { <del> assert(gotError); <del>}); <del> <del>function dontCall() { <del> assert(false); <del>} <del> <del>var server1 = http.createServer(dontCall); <del>server1.listen(0, '127.0.0.1', function() { <del> var server2 = http.createServer(dontCall); <del> server2.listen(this.address().port, '127.0.0.1', dontCall); <del> <del> server2.on('error', function(e) { <add> server2.on('error', common.mustCall(function(e) { <ide> assert.equal(e.code, 'EADDRINUSE'); <ide> server1.close(); <del> gotError = true; <del> }); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-http-blank-header.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> <del>var gotReq = false; <del> <del>var server = http.createServer(function(req, res) { <del> gotReq = true; <add>var server = http.createServer(common.mustCall(function(req, res) { <ide> assert.equal('GET', req.method); <ide> assert.equal('/blah', req.url); <ide> assert.deepStrictEqual({ <ide> host: 'mapdevel.trolologames.ru:443', <ide> origin: 'http://mapdevel.trolologames.ru', <ide> cookie: '' <ide> }, req.headers); <del>}); <add>})); <ide> <ide> <ide> server.listen(0, function() { <ide> server.listen(0, function() { <ide> server.close(); <ide> }); <ide> }); <del> <del> <del>process.on('exit', function() { <del> assert.ok(gotReq); <del>}); <ide><path>test/parallel/test-http-buffer-sanity.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var web = http.Server(function(req, res) { <ide> }); <ide> }); <ide> <del>var gotThanks = false; <del> <del>web.listen(0, function() { <add>web.listen(0, common.mustCall(function() { <ide> console.log('Making request'); <ide> <ide> var req = http.request({ <ide> port: this.address().port, <ide> method: 'GET', <ide> path: '/', <ide> headers: { 'content-length': buffer.length } <del> }, function(res) { <add> }, common.mustCall(function(res) { <ide> console.log('Got response'); <ide> res.setEncoding('utf8'); <del> res.on('data', function(string) { <add> res.on('data', common.mustCall(function(string) { <ide> assert.equal('thanks', string); <del> gotThanks = true; <del> }); <del> }); <add> })); <add> })); <ide> req.end(buffer); <del>}); <add>})); <ide> <ide> <ide> process.on('exit', function() { <ide> assert.equal(bufferSize, measuredSize); <del> assert.ok(gotThanks); <ide> }); <ide><path>test/parallel/test-http-byteswritten.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var body = 'hello world\n'; <ide> <del>var sawFinish = false; <del>process.on('exit', function() { <del> assert(sawFinish); <del> console.log('ok'); <del>}); <del> <del>var httpServer = http.createServer(function(req, res) { <add>var httpServer = http.createServer(common.mustCall(function(req, res) { <ide> httpServer.close(); <ide> <del> res.on('finish', function() { <del> sawFinish = true; <add> res.on('finish', common.mustCall(function() { <ide> assert(typeof req.connection.bytesWritten === 'number'); <ide> assert(req.connection.bytesWritten > 0); <del> }); <add> })); <ide> res.writeHead(200, { 'Content-Type': 'text/plain' }); <ide> <ide> // Write 1.5mb to cause some requests to buffer <ide> var httpServer = http.createServer(function(req, res) { <ide> assert(res.connection.bytesWritten > 0); <ide> <ide> res.end(body); <del>}); <add>})); <ide> <ide> httpServer.listen(0, function() { <ide> http.get({ port: this.address().port }); <ide><path>test/parallel/test-http-client-abort-event.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var http = require('http'); <ide> var server = http.createServer(function(req, res) { <ide> res.end(); <ide> }); <del>var count = 0; <del>server.listen(0, function() { <add> <add>server.listen(0, common.mustCall(function() { <ide> var req = http.request({ <ide> port: this.address().port <del> }, function() { <del> assert(false, 'should not receive data'); <del> }); <add> }, common.fail); <ide> <del> req.on('abort', function() { <del> // should only be emitted once <del> count++; <add> req.on('abort', common.mustCall(function() { <ide> server.close(); <del> }); <add> })); <ide> <ide> req.end(); <ide> req.abort(); <ide> req.abort(); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(count, 1); <del>}); <add>})); <ide><path>test/parallel/test-http-client-get-url.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <del>var seen_req = false; <del> <del>var server = http.createServer(function(req, res) { <add>var server = http.createServer(common.mustCall(function(req, res) { <ide> assert.equal('GET', req.method); <ide> assert.equal('/foo?bar', req.url); <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.write('hello\n'); <ide> res.end(); <ide> server.close(); <del> seen_req = true; <del>}); <add>})); <ide> <ide> server.listen(0, function() { <ide> http.get(`http://127.0.0.1:${this.address().port}/foo?bar`); <ide> }); <del> <del>process.on('exit', function() { <del> assert(seen_req); <del>}); <ide><path>test/parallel/test-http-client-readable.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var util = require('util'); <ide> FakeAgent.prototype.createConnection = function createConnection() { <ide> }; <ide> <ide> var received = ''; <del>var ended = 0; <ide> <ide> var req = http.request({ <ide> agent: new FakeAgent() <del>}, function(res) { <add>}, common.mustCall(function(res) { <ide> res.on('data', function(chunk) { <ide> received += chunk; <ide> }); <ide> <del> res.on('end', function() { <del> ended++; <del> }); <del>}); <add> res.on('end', common.mustCall(function() {})); <add>})); <ide> req.end(); <ide> <ide> process.on('exit', function() { <ide> assert.equal(received, 'hello world'); <del> assert.equal(ended, 1); <ide> }); <ide><path>test/parallel/test-http-client-response-domain.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const domain = require('domain'); <ide> <del>var gotDomainError = false; <ide> var d; <ide> <del>process.on('exit', function() { <del> assert(gotDomainError); <del>}); <del> <ide> common.refreshTmpDir(); <ide> <ide> // first fire up a simple HTTP server <ide> var server = http.createServer(function(req, res) { <ide> server.listen(common.PIPE, function() { <ide> // create a domain <ide> d = domain.create(); <del> d.run(test); <add> d.run(common.mustCall(test)); <ide> }); <ide> <ide> function test() { <ide> <del> d.on('error', function(err) { <del> gotDomainError = true; <add> d.on('error', common.mustCall(function(err) { <ide> assert.equal('should be caught by domain', err.message); <del> }); <add> })); <ide> <ide> var req = http.get({ <ide> socketPath: common.PIPE, <ide><path>test/parallel/test-http-client-upload-buf.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var N = 1024; <del>var bytesReceived = 0; <del>var server_req_complete = false; <del>var client_res_complete = false; <ide> <del>var server = http.createServer(function(req, res) { <add>var server = http.createServer(common.mustCall(function(req, res) { <ide> assert.equal('POST', req.method); <ide> <add> var bytesReceived = 0; <add> <ide> req.on('data', function(chunk) { <ide> bytesReceived += chunk.length; <ide> }); <ide> <del> req.on('end', function() { <del> server_req_complete = true; <add> req.on('end', common.mustCall(function() { <add> assert.strictEqual(N, bytesReceived); <ide> console.log('request complete from server'); <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.write('hello\n'); <ide> res.end(); <del> }); <del>}); <add> })); <add>})); <ide> server.listen(0); <ide> <del>server.on('listening', function() { <add>server.on('listening', common.mustCall(function() { <ide> var req = http.request({ <ide> port: this.address().port, <ide> method: 'POST', <ide> path: '/' <del> }, function(res) { <add> }, common.mustCall(function(res) { <ide> res.setEncoding('utf8'); <ide> res.on('data', function(chunk) { <ide> console.log(chunk); <ide> }); <del> res.on('end', function() { <del> client_res_complete = true; <add> res.on('end', common.mustCall(function() { <ide> server.close(); <del> }); <del> }); <add> })); <add> })); <ide> <ide> req.write(Buffer.allocUnsafe(N)); <ide> req.end(); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(N, bytesReceived); <del> assert.equal(true, server_req_complete); <del> assert.equal(true, client_res_complete); <del>}); <add>})); <ide><path>test/parallel/test-http-client-upload.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <del>var sent_body = ''; <del>var server_req_complete = false; <del>var client_res_complete = false; <del> <del>var server = http.createServer(function(req, res) { <add>var server = http.createServer(common.mustCall(function(req, res) { <ide> assert.equal('POST', req.method); <ide> req.setEncoding('utf8'); <ide> <add> var sent_body = ''; <add> <ide> req.on('data', function(chunk) { <ide> console.log('server got: ' + JSON.stringify(chunk)); <ide> sent_body += chunk; <ide> }); <ide> <del> req.on('end', function() { <del> server_req_complete = true; <add> req.on('end', common.mustCall(function() { <add> assert.strictEqual('1\n2\n3\n', sent_body); <ide> console.log('request complete from server'); <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.write('hello\n'); <ide> res.end(); <del> }); <del>}); <add> })); <add>})); <ide> server.listen(0); <ide> <del>server.on('listening', function() { <add>server.on('listening', common.mustCall(function() { <ide> var req = http.request({ <ide> port: this.address().port, <ide> method: 'POST', <ide> path: '/' <del> }, function(res) { <add> }, common.mustCall(function(res) { <ide> res.setEncoding('utf8'); <ide> res.on('data', function(chunk) { <ide> console.log(chunk); <ide> }); <del> res.on('end', function() { <del> client_res_complete = true; <add> res.on('end', common.mustCall(function() { <ide> server.close(); <del> }); <del> }); <add> })); <add> })); <ide> <ide> req.write('1\n'); <ide> req.write('2\n'); <ide> req.write('3\n'); <ide> req.end(); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal('1\n2\n3\n', sent_body); <del> assert.equal(true, server_req_complete); <del> assert.equal(true, client_res_complete); <del>}); <add>})); <ide><path>test/parallel/test-http-conn-reset.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> <del>var caughtError = false; <del> <ide> var options = { <ide> host: '127.0.0.1', <ide> port: undefined <ide> var server = net.createServer(function(client) { <ide> client.destroy(); <ide> server.close(); <ide> }); <del>server.listen(0, options.host, onListen); <add>server.listen(0, options.host, common.mustCall(onListen)); <ide> <ide> // do a GET request, expect it to fail <ide> function onListen() { <ide> options.port = this.address().port; <ide> var req = http.request(options, function(res) { <ide> assert.ok(false, 'this should never run'); <ide> }); <del> req.on('error', function(err) { <add> req.on('error', common.mustCall(function(err) { <ide> assert.equal(err.code, 'ECONNRESET'); <del> caughtError = true; <del> }); <add> })); <ide> req.end(); <ide> } <del> <del>process.on('exit', function() { <del> assert.equal(caughtError, true); <del>}); <del> <ide><path>test/parallel/test-http-connect-req-res.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>const server = http.createServer(function(req, res) { <del> assert(false); <del>}); <add>const server = http.createServer(common.fail); <ide> server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) { <ide> assert.equal(req.method, 'CONNECT'); <ide> assert.equal(req.url, 'example.com:443'); <ide> server.listen(0, common.mustCall(function() { <ide> port: this.address().port, <ide> method: 'CONNECT', <ide> path: 'example.com:443' <del> }, function(res) { <del> assert(false); <del> }); <add> }, common.fail); <ide> <ide> req.on('close', common.mustCall(function() { })); <ide> <ide><path>test/parallel/test-http-connect.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var serverGotConnect = false; <ide> var clientGotConnect = false; <ide> <del>var server = http.createServer(function(req, res) { <del> assert(false); <del>}); <add>var server = http.createServer(common.fail); <ide> server.on('connect', function(req, socket, firstBodyChunk) { <ide> assert.equal(req.method, 'CONNECT'); <ide> assert.equal(req.url, 'google.com:443'); <ide> server.listen(0, function() { <ide> port: this.address().port, <ide> method: 'CONNECT', <ide> path: 'google.com:443' <del> }, function(res) { <del> assert(false); <del> }); <add> }, common.fail); <ide> <ide> var clientRequestClosed = false; <ide> req.on('close', function() { <ide><path>test/parallel/test-http-end-throw-socket-handling.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> <ide> // Make sure that throwing in 'end' handler doesn't lock <ide> // up the socket forever. <ide> server.listen(0, common.mustCall(() => { <ide> } <ide> })); <ide> <del>let errors = 0; <del>process.on('uncaughtException', () => { <del> errors++; <del>}); <del> <del>process.on('exit', () => { <del> assert.equal(errors, 10); <del>}); <add>process.on('uncaughtException', common.mustCall(() => {}, 10)); <ide><path>test/parallel/test-http-extra-response.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> var fullResponse = <ide> '\r\n' + <ide> body; <ide> <del>var gotResponse = false; <del> <del> <ide> var server = net.createServer(function(socket) { <ide> var postBody = ''; <ide> <ide> var server = net.createServer(function(socket) { <ide> }); <ide> <ide> <del>server.listen(0, function() { <del> http.get({ port: this.address().port }, function(res) { <add>server.listen(0, common.mustCall(function() { <add> http.get({ port: this.address().port }, common.mustCall(function(res) { <ide> var buffer = ''; <ide> console.log('Got res code: ' + res.statusCode); <ide> <ide> server.listen(0, function() { <ide> buffer += chunk; <ide> }); <ide> <del> res.on('end', function() { <add> res.on('end', common.mustCall(function() { <ide> console.log('Response ended, read ' + buffer.length + ' bytes'); <ide> assert.equal(body, buffer); <ide> server.close(); <del> gotResponse = true; <del> }); <del> }); <del>}); <del> <del> <del>process.on('exit', function() { <del> assert.ok(gotResponse); <del>}); <del> <add> })); <add> })); <add>})); <ide><path>test/parallel/test-http-full-response.js <ide> var server = http.createServer(function(req, res) { <ide> res.end(body); <ide> }); <ide> <del>var runs = 0; <del> <ide> function runAb(opts, callback) { <ide> var command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; <ide> exec(command, function(err, stdout, stderr) { <ide> function runAb(opts, callback) { <ide> assert.equal(bodyLength, documentLength); <ide> assert.equal(completeRequests * documentLength, htmlTransfered); <ide> <del> runs++; <del> <ide> if (callback) callback(); <ide> }); <ide> } <ide> <del>server.listen(0, function() { <del> runAb('-c 1 -n 10', function() { <add>server.listen(0, common.mustCall(function() { <add> runAb('-c 1 -n 10', common.mustCall(function() { <ide> console.log('-c 1 -n 10 okay'); <ide> <del> runAb('-c 1 -n 100', function() { <add> runAb('-c 1 -n 100', common.mustCall(function() { <ide> console.log('-c 1 -n 100 okay'); <ide> <del> runAb('-c 1 -n 1000', function() { <add> runAb('-c 1 -n 1000', common.mustCall(function() { <ide> console.log('-c 1 -n 1000 okay'); <ide> server.close(); <del> }); <del> }); <del> }); <del> <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(3, runs); <del>}); <add> })); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-http-head-request.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var http = require('http'); <ide> <ide> var body = 'hello world\n'; <ide> function test(headers) { <ide> server.close(); <ide> }); <ide> <del> var gotEnd = false; <del> <del> server.listen(0, function() { <add> server.listen(0, common.mustCall(function() { <ide> var request = http.request({ <ide> port: this.address().port, <ide> method: 'HEAD', <ide> path: '/' <del> }, function(response) { <add> }, common.mustCall(function(response) { <ide> console.error('response start'); <del> response.on('end', function() { <add> response.on('end', common.mustCall(function() { <ide> console.error('response end'); <del> gotEnd = true; <del> }); <add> })); <ide> response.resume(); <del> }); <add> })); <ide> request.end(); <del> }); <del> <del> process.on('exit', function() { <del> assert.ok(gotEnd); <del> }); <add> })); <ide> } <ide> <ide> test({ <ide><path>test/parallel/test-http-head-response-has-no-body-end.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <del> <add>const common = require('../common'); <ide> var http = require('http'); <ide> <ide> // This test is to make sure that when the HTTP server <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> server.listen(0); <ide> <del>var responseComplete = false; <del> <del>server.on('listening', function() { <add>server.on('listening', common.mustCall(function() { <ide> var req = http.request({ <ide> port: this.address().port, <ide> method: 'HEAD', <ide> path: '/' <del> }, function(res) { <del> res.on('end', function() { <add> }, common.mustCall(function(res) { <add> res.on('end', common.mustCall(function() { <ide> server.close(); <del> responseComplete = true; <del> }); <add> })); <ide> res.resume(); <del> }); <add> })); <ide> req.end(); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(responseComplete); <del>}); <add>})); <ide><path>test/parallel/test-http-head-response-has-no-body.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <del> <add>const common = require('../common'); <ide> var http = require('http'); <ide> <ide> // This test is to make sure that when the HTTP server <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> server.listen(0); <ide> <del>var responseComplete = false; <del> <del>server.on('listening', function() { <add>server.on('listening', common.mustCall(function() { <ide> var req = http.request({ <ide> port: this.address().port, <ide> method: 'HEAD', <ide> path: '/' <del> }, function(res) { <del> res.on('end', function() { <add> }, common.mustCall(function(res) { <add> res.on('end', common.mustCall(function() { <ide> server.close(); <del> responseComplete = true; <del> }); <add> })); <ide> res.resume(); <del> }); <add> })); <ide> req.end(); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(responseComplete); <del>}); <add>})); <ide><path>test/parallel/test-http-hex-write.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> <ide> var expect = 'hex\nutf8\n'; <del>var data = ''; <del>var ended = false; <del> <del>process.on('exit', function() { <del> assert(ended); <del> assert.equal(data, expect); <del> console.log('ok'); <del>}); <ide> <ide> http.createServer(function(q, s) { <ide> s.setHeader('content-length', expect.length); <ide> s.write('6865780a', 'hex'); <ide> s.write('utf8\n'); <ide> s.end(); <ide> this.close(); <del>}).listen(0, function() { <del> http.request({ port: this.address().port }).on('response', function(res) { <del> res.setEncoding('ascii'); <del> res.on('data', function(c) { <del> data += c; <del> }); <del> res.on('end', function() { <del> ended = true; <del> }); <del> }).end(); <del>}); <add>}).listen(0, common.mustCall(function() { <add> http.request({ port: this.address().port }) <add> .on('response', common.mustCall(function(res) { <add> var data = ''; <add> <add> res.setEncoding('ascii'); <add> res.on('data', function(c) { <add> data += c; <add> }); <add> res.on('end', common.mustCall(function() { <add> assert.strictEqual(data, expect); <add> })); <add> })).end(); <add>})); <ide><path>test/parallel/test-http-legacy.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var url = require('url'); <ide> <ide> var responses_sent = 0; <del>var responses_recvd = 0; <ide> var body0 = ''; <ide> var body1 = ''; <ide> <ide> var server = http.createServer(function(req, res) { <ide> req.resume(); <ide> }); <ide> <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var client = http.createClient(this.address().port); <ide> var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'}); <ide> setTimeout(function() { <ide> req.end(); <ide> }, 100); <del> req.on('response', function(res) { <add> req.on('response', common.mustCall(function(res) { <ide> assert.equal(200, res.statusCode); <del> responses_recvd += 1; <ide> res.setEncoding('utf8'); <ide> res.on('data', function(chunk) { body0 += chunk; }); <ide> console.error('Got /hello response'); <del> }); <add> })); <ide> <del> setTimeout(function() { <add> setTimeout(common.mustCall(function() { <ide> var req = client.request('POST', '/world'); <ide> req.end(); <del> req.on('response', function(res) { <add> req.on('response', common.mustCall(function(res) { <ide> assert.equal(200, res.statusCode); <del> responses_recvd += 1; <ide> res.setEncoding('utf8'); <ide> res.on('data', function(chunk) { body1 += chunk; }); <ide> console.error('Got /world response'); <del> }); <del> }, 1); <del>}); <add> })); <add> }), 1); <add>})); <ide> <ide> process.on('exit', function() { <del> console.error('responses_recvd: ' + responses_recvd); <del> assert.equal(2, responses_recvd); <del> <ide> console.error('responses_sent: ' + responses_sent); <ide> assert.equal(2, responses_sent); <ide> <ide><path>test/parallel/test-http-localaddress-bind-error.js <ide> 'use strict'; <ide> const common = require('../common'); <del>var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var invalidLocalAddress = '1.2.3.4'; <del>var gotError = false; <ide> <ide> var server = http.createServer(function(req, res) { <ide> console.log('Connect from: ' + req.connection.remoteAddress); <ide> var server = http.createServer(function(req, res) { <ide> req.resume(); <ide> }); <ide> <del>server.listen(0, '127.0.0.1', function() { <add>server.listen(0, '127.0.0.1', common.mustCall(function() { <ide> http.request({ <ide> host: 'localhost', <ide> port: this.address().port, <ide> server.listen(0, '127.0.0.1', function() { <ide> localAddress: invalidLocalAddress <ide> }, function(res) { <ide> common.fail('unexpectedly got response from server'); <del> }).on('error', function(e) { <add> }).on('error', common.mustCall(function(e) { <ide> console.log('client got error: ' + e.message); <del> gotError = true; <ide> server.close(); <del> }).end(); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(gotError); <del>}); <add> })).end(); <add>})); <ide><path>test/parallel/test-http-multi-line-headers.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var net = require('net'); <ide> <del>var gotResponse = false; <del> <ide> var server = net.createServer(function(conn) { <ide> var body = 'Yet another node.js server.'; <ide> <ide> var server = net.createServer(function(conn) { <ide> server.close(); <ide> }); <ide> <del>server.listen(0, function() { <del> http.get({host: '127.0.0.1', port: this.address().port}, function(res) { <add>server.listen(0, common.mustCall(function() { <add> http.get({ <add> host: '127.0.0.1', <add> port: this.address().port <add> }, common.mustCall(function(res) { <ide> assert.equal(res.headers['content-type'], <ide> 'text/plain; x-unix-mode=0600; name="hello.txt"'); <del> gotResponse = true; <ide> res.destroy(); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(gotResponse); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-http-no-content-length.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> <del>var body = ''; <del> <ide> var server = net.createServer(function(socket) { <ide> // Neither Content-Length nor Connection <ide> socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); <del>}).listen(0, function() { <del> http.get({port: this.address().port}, function(res) { <add>}).listen(0, common.mustCall(function() { <add> http.get({port: this.address().port}, common.mustCall(function(res) { <add> var body = ''; <add> <ide> res.setEncoding('utf8'); <ide> res.on('data', function(chunk) { <ide> body += chunk; <ide> }); <del> res.on('end', function() { <add> res.on('end', common.mustCall(function() { <add> assert.strictEqual(body, 'Hello'); <ide> server.close(); <del> }); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(body, 'Hello'); <del>}); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-http-pause-resume-one-end.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var http = require('http'); <ide> <ide> var server = http.Server(function(req, res) { <ide> var server = http.Server(function(req, res) { <ide> server.close(); <ide> }); <ide> <del> <del>var dataCount = 0, endCount = 0; <del> <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var opts = { <ide> port: this.address().port, <ide> headers: { connection: 'close' } <ide> }; <ide> <del> http.get(opts, function(res) { <del> res.on('data', function(chunk) { <del> dataCount++; <add> http.get(opts, common.mustCall(function(res) { <add> res.on('data', common.mustCall(function(chunk) { <ide> res.pause(); <ide> setTimeout(function() { <ide> res.resume(); <ide> }); <del> }); <del> <del> res.on('end', function() { <del> endCount++; <del> }); <del> }); <del>}); <del> <add> })); <ide> <del>process.on('exit', function() { <del> assert.equal(1, dataCount); <del> assert.equal(1, endCount); <del>}); <add> res.on('end', common.mustCall(function() {})); <add> })); <add>})); <ide><path>test/parallel/test-http-pipe-fs.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> var http = require('http'); <ide> var fs = require('fs'); <ide> var path = require('path'); <ide> <ide> common.refreshTmpDir(); <ide> <ide> var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); <del>var requests = 0; <ide> <del>var server = http.createServer(function(req, res) { <del> ++requests; <add>var server = http.createServer(common.mustCall(function(req, res) { <ide> var stream = fs.createWriteStream(file); <ide> req.pipe(stream); <ide> stream.on('close', function() { <ide> res.writeHead(200); <ide> res.end(); <ide> }); <del>}).listen(0, function() { <add>}, 2)).listen(0, function() { <ide> http.globalAgent.maxSockets = 1; <ide> <ide> for (var i = 0; i < 2; ++i) { <ide> var server = http.createServer(function(req, res) { <ide> }(i + 1)); <ide> } <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(requests, 2); <del>}); <ide><path>test/parallel/test-http-pipeline-flood.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> <ide> // Here we are testing the HTTP server module's flood prevention mechanism. <ide> // When writeable.write returns false (ie the underlying send() indicated the <ide> switch (process.argv[2]) { <ide> function parent() { <ide> const http = require('http'); <ide> const bigResponse = Buffer.alloc(10240, 'x'); <del> var connections = 0; <ide> var backloggedReqs = 0; <ide> <ide> const server = http.createServer(function(req, res) { <ide> function parent() { <ide> res.end(); <ide> }); <ide> <del> server.on('connection', function(conn) { <del> connections++; <del> }); <add> server.on('connection', common.mustCall(function(conn) {})); <ide> <ide> server.listen(0, function() { <ide> const spawn = require('child_process').spawn; <ide> function parent() { <ide> child.kill(); <ide> })); <ide> }); <del> <del> process.on('exit', function() { <del> assert.equal(connections, 1); <del> }); <ide> } <ide> <ide> function child() { <ide><path>test/parallel/test-http-request-end.js <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var expected = 'Post Body For Test'; <del>var result = ''; <ide> <ide> var server = http.Server(function(req, res) { <add> var result = ''; <add> <ide> req.setEncoding('utf8'); <ide> req.on('data', function(chunk) { <ide> result += chunk; <ide> }); <ide> <ide> req.on('end', function() { <add> assert.strictEqual(expected, result); <ide> server.close(); <ide> res.writeHead(200); <ide> res.end('hello world\n'); <ide> server.listen(0, function() { <ide> process.exit(1); <ide> }).end(expected); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(expected, result); <del>}); <ide><path>test/parallel/test-http-request-methods.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> <ide> // Test that the DELETE, PATCH and PURGE verbs get passed through correctly <ide> <ide> ['DELETE', 'PATCH', 'PURGE'].forEach(function(method, index) { <del> var server_response = ''; <del> var received_method = null; <del> <del> var server = http.createServer(function(req, res) { <del> received_method = req.method; <add> var server = http.createServer(common.mustCall(function(req, res) { <add> assert.strictEqual(req.method, method); <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.write('hello '); <ide> res.write('world\n'); <ide> res.end(); <del> }); <add> })); <ide> server.listen(0); <ide> <del> server.on('listening', function() { <add> server.on('listening', common.mustCall(function() { <ide> var c = net.createConnection(this.address().port); <add> var server_response = ''; <ide> <ide> c.setEncoding('utf8'); <ide> <ide> var http = require('http'); <ide> server_response += chunk; <ide> }); <ide> <del> c.on('end', function() { <add> c.on('end', common.mustCall(function() { <add> const m = server_response.split('\r\n\r\n'); <add> assert.strictEqual(m[1], 'hello world\n'); <ide> c.end(); <del> }); <add> })); <ide> <ide> c.on('close', function() { <ide> server.close(); <ide> }); <del> }); <del> <del> process.on('exit', function() { <del> var m = server_response.split('\r\n\r\n'); <del> assert.equal(m[1], 'hello world\n'); <del> assert.equal(received_method, method); <del> }); <add> })); <ide> }); <ide><path>test/parallel/test-http-res-write-after-end.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <del>var responseError; <del> <del>var server = http.Server(function(req, res) { <del> res.on('error', function onResError(err) { <del> responseError = err; <del> }); <add>var server = http.Server(common.mustCall(function(req, res) { <add> res.on('error', common.mustCall(function onResError(err) { <add> assert.strictEqual(err.message, 'write after end'); <add> })); <ide> <ide> res.write('This should write.'); <ide> res.end(); <ide> <ide> var r = res.write('This should raise an error.'); <ide> assert.equal(r, true, 'write after end should return true'); <del>}); <add>})); <ide> <ide> server.listen(0, function() { <ide> http.get({port: this.address().port}, function(res) { <ide> server.close(); <ide> }); <ide> }); <del> <del>process.on('exit', function onProcessExit(code) { <del> assert(responseError, 'response should have emitted error'); <del> assert.equal(responseError.message, 'write after end'); <del>}); <ide><path>test/parallel/test-http-response-close.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var http = require('http'); <ide> <del>var requestGotEnd = false; <del>var responseGotEnd = false; <del> <del>var server = http.createServer(function(req, res) { <add>var server = http.createServer(common.mustCall(function(req, res) { <ide> res.writeHead(200); <ide> res.write('a'); <ide> <del> req.on('close', function() { <add> req.on('close', common.mustCall(function() { <ide> console.error('request aborted'); <del> requestGotEnd = true; <del> }); <del> res.on('close', function() { <add> })); <add> res.on('close', common.mustCall(function() { <ide> console.error('response aborted'); <del> responseGotEnd = true; <del> }); <del>}); <add> })); <add>})); <ide> server.listen(0); <ide> <ide> server.on('listening', function() { <ide> server.on('listening', function() { <ide> }); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.ok(requestGotEnd); <del> assert.ok(responseGotEnd); <del>}); <ide><path>test/parallel/test-http-response-no-headers.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> var expected = { <ide> '1.1': '' <ide> }; <ide> <del>var gotExpected = false; <del> <ide> function test(httpVersion, callback) { <del> process.on('exit', function() { <del> assert(gotExpected); <del> }); <del> <ide> var server = net.createServer(function(conn) { <ide> var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + <ide> expected[httpVersion]; <ide> <ide> conn.end(reply); <ide> }); <ide> <del> server.listen(0, '127.0.0.1', function() { <add> server.listen(0, '127.0.0.1', common.mustCall(function() { <ide> var options = { <ide> host: '127.0.0.1', <ide> port: this.address().port <ide> }; <ide> <del> var req = http.get(options, function(res) { <add> var req = http.get(options, common.mustCall(function(res) { <ide> var body = ''; <ide> <ide> res.on('data', function(data) { <ide> body += data; <ide> }); <ide> <del> res.on('end', function() { <add> res.on('end', common.mustCall(function() { <ide> assert.equal(body, expected[httpVersion]); <del> gotExpected = true; <ide> server.close(); <ide> if (callback) process.nextTick(callback); <del> }); <del> }); <add> })); <add> })); <ide> <ide> req.on('error', function(err) { <ide> throw err; <ide> }); <del> }); <add> })); <ide> } <ide> <ide> test('0.9', function() { <ide><path>test/parallel/test-http-unix-socket.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <del>var status_ok = false; // status code == 200? <del>var headers_ok = false; <del>var body_ok = false; <del> <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, { <ide> 'Content-Type': 'text/plain', <ide> var server = http.createServer(function(req, res) { <ide> <ide> common.refreshTmpDir(); <ide> <del>server.listen(common.PIPE, function() { <add>server.listen(common.PIPE, common.mustCall(function() { <ide> <ide> var options = { <ide> socketPath: common.PIPE, <ide> path: '/' <ide> }; <ide> <del> var req = http.get(options, function(res) { <add> var req = http.get(options, common.mustCall(function(res) { <ide> assert.equal(res.statusCode, 200); <del> status_ok = true; <del> <ide> assert.equal(res.headers['content-type'], 'text/plain'); <del> headers_ok = true; <ide> <ide> res.body = ''; <ide> res.setEncoding('utf8'); <ide> server.listen(common.PIPE, function() { <ide> res.body += chunk; <ide> }); <ide> <del> res.on('end', function() { <add> res.on('end', common.mustCall(function() { <ide> assert.equal(res.body, 'hello world\n'); <del> body_ok = true; <ide> server.close(function(error) { <ide> assert.equal(error, undefined); <ide> server.close(function(error) { <ide> assert.equal(error && error.message, 'Not running'); <ide> }); <ide> }); <del> }); <del> }); <add> })); <add> })); <ide> <ide> req.on('error', function(e) { <ide> console.log(e.stack); <ide> server.listen(common.PIPE, function() { <ide> <ide> req.end(); <ide> <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(status_ok); <del> assert.ok(headers_ok); <del> assert.ok(body_ok); <del>}); <add>})); <ide><path>test/parallel/test-http-upgrade-agent.js <ide> var srv = net.createServer(function(c) { <ide> }); <ide> }); <ide> <del>var gotUpgrade = false; <del> <del>srv.listen(0, '127.0.0.1', function() { <add>srv.listen(0, '127.0.0.1', common.mustCall(function() { <ide> <ide> var options = { <ide> port: this.address().port, <ide> srv.listen(0, '127.0.0.1', function() { <ide> var req = http.request(options); <ide> req.end(); <ide> <del> req.on('upgrade', function(res, socket, upgradeHead) { <add> req.on('upgrade', common.mustCall(function(res, socket, upgradeHead) { <ide> var recvData = upgradeHead; <ide> socket.on('data', function(d) { <ide> recvData += d; <ide> srv.listen(0, '127.0.0.1', function() { <ide> // Make sure this request got removed from the pool. <ide> assert(!http.globalAgent.sockets.hasOwnProperty(name)); <ide> <del> req.on('close', function() { <add> req.on('close', common.mustCall(function() { <ide> socket.end(); <ide> srv.close(); <del> <del> gotUpgrade = true; <del> }); <del> }); <del> <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(gotUpgrade); <del>}); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-http-upgrade-client.js <ide> var srv = net.createServer(function(c) { <ide> }); <ide> }); <ide> <del>var gotUpgrade = false; <del> <del>srv.listen(0, '127.0.0.1', function() { <add>srv.listen(0, '127.0.0.1', common.mustCall(function() { <ide> <ide> var req = http.get({ <ide> port: this.address().port, <ide> srv.listen(0, '127.0.0.1', function() { <ide> upgrade: 'websocket' <ide> } <ide> }); <del> req.on('upgrade', function(res, socket, upgradeHead) { <add> req.on('upgrade', common.mustCall(function(res, socket, upgradeHead) { <ide> var recvData = upgradeHead; <ide> socket.on('data', function(d) { <ide> recvData += d; <ide> srv.listen(0, '127.0.0.1', function() { <ide> <ide> socket.end(); <ide> srv.close(); <del> <del> gotUpgrade = true; <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(gotUpgrade); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-http-upgrade-client2.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var http = require('http'); <ide> <ide> var CRLF = '\r\n'; <ide> server.on('upgrade', function(req, socket, head) { <ide> }); <ide> }); <ide> <del>var successCount = 0; <del> <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> <ide> function upgradeRequest(fn) { <ide> console.log('req'); <ide> server.listen(0, function() { <ide> <ide> } <ide> <del> upgradeRequest(function() { <del> successCount++; <del> upgradeRequest(function() { <del> successCount++; <add> upgradeRequest(common.mustCall(function() { <add> upgradeRequest(common.mustCall(function() { <ide> // Test pass <ide> console.log('Pass!'); <ide> server.close(); <del> }); <del> }); <del> <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(2, successCount); <del>}); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-http-upgrade-server2.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <ide> server.on('upgrade', function(req, socket, upgradeHead) { <ide> throw new Error('upgrade error'); <ide> }); <ide> <del>var gotError = false; <del> <del>process.on('uncaughtException', function(e) { <add>process.on('uncaughtException', common.mustCall(function(e) { <ide> assert.equal('upgrade error', e.message); <del> gotError = true; <ide> process.exit(0); <del>}); <add>})); <ide> <ide> <ide> server.listen(0, function() { <ide> server.listen(0, function() { <ide> server.close(); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.ok(gotError); <del>}); <ide><path>test/parallel/test-http-wget.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> var http = require('http'); <ide> var http = require('http'); <ide> // content-length is not provided, that the connection is in fact <ide> // closed. <ide> <del>var server_response = ''; <del>var client_got_eof = false; <del>var connection_was_closed = false; <del> <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.write('hello '); <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> server.listen(0); <ide> <del>server.on('listening', function() { <add>server.on('listening', common.mustCall(function() { <ide> var c = net.createConnection(this.address().port); <add> var server_response = ''; <ide> <ide> c.setEncoding('utf8'); <ide> <ide> server.on('listening', function() { <ide> server_response += chunk; <ide> }); <ide> <del> c.on('end', function() { <del> client_got_eof = true; <add> c.on('end', common.mustCall(function() { <add> const m = server_response.split('\r\n\r\n'); <add> assert.strictEqual(m[1], 'hello world\n'); <ide> console.log('got end'); <ide> c.end(); <del> }); <add> })); <ide> <del> c.on('close', function() { <del> connection_was_closed = true; <add> c.on('close', common.mustCall(function() { <ide> console.log('got close'); <ide> server.close(); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> var m = server_response.split('\r\n\r\n'); <del> assert.equal(m[1], 'hello world\n'); <del> assert.ok(client_got_eof); <del> assert.ok(connection_was_closed); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-http-write-empty-string.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var server = http.createServer(function(request, response) { <ide> this.close(); <ide> }); <ide> <del>var response = ''; <add>server.listen(0, common.mustCall(function() { <add> http.get({ port: this.address().port }, common.mustCall(function(res) { <add> var response = ''; <ide> <del>process.on('exit', function() { <del> assert.equal('1\n2\n3\n', response); <del>}); <del> <del> <del>server.listen(0, function() { <del> http.get({ port: this.address().port }, function(res) { <ide> assert.equal(200, res.statusCode); <ide> res.setEncoding('ascii'); <ide> res.on('data', function(chunk) { <ide> response += chunk; <ide> }); <del> }); <del>}); <del> <add> res.on('end', common.mustCall(function() { <add> assert.strictEqual('1\n2\n3\n', response); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-https-agent-session-eviction.js <ide> function third(server) { <ide> assert(!req.socket.isSessionReused()); <ide> server.close(); <ide> }); <del> req.on('error', function(err) { <del> // never called <del> assert(false); <del> }); <add> req.on('error', common.fail); <ide> req.end(); <ide> } <ide><path>test/parallel/test-https-client-checkServerIdentity.js <ide> var options = { <ide> cert: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent3-cert.pem')) <ide> }; <ide> <del>var reqCount = 0; <del> <del>var server = https.createServer(options, function(req, res) { <del> ++reqCount; <add>var server = https.createServer(options, common.mustCall(function(req, res) { <ide> res.writeHead(200); <ide> res.end(); <ide> req.resume(); <del>}).listen(0, function() { <add>})).listen(0, function() { <ide> authorized(); <ide> }); <ide> <ide> function authorized() { <ide> port: server.address().port, <ide> rejectUnauthorized: true, <ide> ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))] <del> }, function(res) { <del> assert(false); <del> }); <add> }, common.fail); <ide> req.on('error', function(err) { <ide> override(); <ide> }); <ide> function override() { <ide> }); <ide> req.end(); <ide> } <del> <del>process.on('exit', function() { <del> assert.equal(reqCount, 1); <del>}); <ide><path>test/parallel/test-https-client-get-url.js <ide> var https = require('https'); <ide> <ide> var fs = require('fs'); <ide> <del>var seen_req = false; <del> <ide> var options = { <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }; <ide> <del>var server = https.createServer(options, function(req, res) { <add>var server = https.createServer(options, common.mustCall(function(req, res) { <ide> assert.equal('GET', req.method); <ide> assert.equal('/foo?bar', req.url); <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.write('hello\n'); <ide> res.end(); <ide> server.close(); <del> seen_req = true; <del>}); <add>})); <ide> <ide> server.listen(0, function() { <ide> https.get(`https://127.0.0.1:${this.address().port}/foo?bar`); <ide> }); <del> <del>process.on('exit', function() { <del> assert(seen_req); <del>}); <ide><path>test/parallel/test-https-client-reject.js <ide> var options = { <ide> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) <ide> }; <ide> <del>var reqCount = 0; <del> <del>var server = https.createServer(options, function(req, res) { <del> ++reqCount; <add>var server = https.createServer(options, common.mustCall(function(req, res) { <ide> res.writeHead(200); <ide> res.end(); <ide> req.resume(); <del>}).listen(0, function() { <add>}, 2)).listen(0, function() { <ide> unauthorized(); <ide> }); <ide> <ide> function rejectUnauthorized() { <ide> port: server.address().port <ide> }; <ide> options.agent = new https.Agent(options); <del> var req = https.request(options, function(res) { <del> assert(false); <del> }); <add> var req = https.request(options, common.fail); <ide> req.on('error', function(err) { <ide> authorized(); <ide> }); <ide> function authorized() { <ide> assert(req.socket.authorized); <ide> server.close(); <ide> }); <del> req.on('error', function(err) { <del> assert(false); <del> }); <add> req.on('error', common.fail); <ide> req.end(); <ide> } <del> <del>process.on('exit', function() { <del> assert.equal(reqCount, 2); <del>}); <ide><path>test/parallel/test-https-client-resume.js <ide> var options = { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') <ide> }; <ide> <del>var connections = 0; <del> <ide> // create server <del>var server = https.createServer(options, function(req, res) { <add>var server = https.createServer(options, common.mustCall(function(req, res) { <ide> res.end('Goodbye'); <del> connections++; <del>}); <add>}, 2)); <ide> <ide> // start listening <ide> server.listen(0, function() { <ide> server.listen(0, function() { <ide> }); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(2, connections); <del>}); <ide><path>test/parallel/test-https-connecting-to-http.js <ide> // This tests the situation where you try to connect a https client <ide> // to an http server. You should get an error and exit. <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> if (!common.hasCrypto) { <ide> if (!common.hasCrypto) { <ide> } <ide> var https = require('https'); <ide> <del>var reqCount = 0; <del>var resCount = 0; <del>var reqErrorCount = 0; <del>var body = 'hello world\n'; <add>var server = http.createServer(common.fail); <ide> <add>server.listen(0, common.mustCall(function() { <add> var req = https.get({ port: this.address().port }, common.fail); <ide> <del>var server = http.createServer(function(req, res) { <del> reqCount++; <del> console.log('got request'); <del> res.writeHead(200, { 'content-type': 'text/plain' }); <del> res.end(body); <del>}); <del> <del> <del>server.listen(0, function() { <del> var req = https.get({ port: this.address().port }, function(res) { <del> resCount++; <del> }); <del> <del> req.on('error', function(e) { <add> req.on('error', common.mustCall(function(e) { <ide> console.log('Got expected error: ', e.message); <ide> server.close(); <del> reqErrorCount++; <del> }); <del>}); <del> <del> <del>process.on('exit', function() { <del> assert.equal(0, reqCount); <del> assert.equal(0, resCount); <del> assert.equal(1, reqErrorCount); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-https-eof-for-eom.js <ide> var server = tls.Server(options, function(socket) { <ide> }, 100); <ide> }); <ide> <del> <del>var gotHeaders = false; <del>var gotEnd = false; <del>var bodyBuffer = ''; <del> <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> console.log('1) Making Request'); <ide> https.get({ <ide> port: this.address().port, <ide> rejectUnauthorized: false <del> }, function(res) { <add> }, common.mustCall(function(res) { <add> var bodyBuffer = ''; <add> <ide> server.close(); <ide> console.log('3) Client got response headers.'); <ide> <ide> assert.equal('gws', res.headers.server); <del> gotHeaders = true; <ide> <ide> res.setEncoding('utf8'); <ide> res.on('data', function(s) { <ide> bodyBuffer += s; <ide> }); <ide> <del> res.on('end', function() { <add> res.on('end', common.mustCall(function() { <ide> console.log('5) Client got "end" event.'); <del> gotEnd = true; <del> }); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(gotHeaders); <del> assert.ok(gotEnd); <del> assert.equal('hello world\nhello world\n', bodyBuffer); <del>}); <add> assert.strictEqual('hello world\nhello world\n', bodyBuffer); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-https-foafssl.js <ide> var options = { <ide> requestCert: true <ide> }; <ide> <add>const modulus = 'A6F44A9C25791431214F5C87AF9E040177A8BB89AC803F7E09BBC3A5519F' + <add> '349CD9B9C40BE436D0AA823A94147E26C89248ADA2BE3DD4D34E8C289646' + <add> '94B2047D217B4F1299371EA93A83C89AB9440724131E65F2B0161DE9560C' + <add> 'DE9C13455552B2F49CF0FB00D8D77532324913F6F80FF29D0A131D29DB06' + <add> 'AFF8BE191B7920DC2DAE1C26EA82A47847A10391EF3BF6AABB3CC40FF821' + <add> '00B03A4F0FF1809278E4DDFDA7DE954ED56DC7AD9A47EEBC37D771A366FC' + <add> '60A5BCB72373BEC180649B3EFA0E9092707210B41B90032BB18BC91F2046' + <add> 'EBDAF1191F4A4E26D71879C4C7867B62FCD508E8CE66E82D128A71E91580' + <add> '9FCF44E8DE774067F1DE5D70B9C03687'; <add> <ide> var CRLF = '\r\n'; <ide> var body = 'hello world\n'; <ide> var cert; <del>var subjectaltname; <del>var modulus; <del>var exponent; <ide> <del>var server = https.createServer(options, function(req, res) { <add>var server = https.createServer(options, common.mustCall(function(req, res) { <ide> console.log('got request'); <ide> <ide> cert = req.connection.getPeerCertificate(); <ide> <del> subjectaltname = cert.subjectaltname; <del> modulus = cert.modulus; <del> exponent = cert.exponent; <del> <add> assert.strictEqual(cert.subjectaltname, 'URI:http://example.com/#me'); <add> assert.strictEqual(cert.exponent, '0x10001'); <add> assert.strictEqual(cert.modulus, modulus); <ide> res.writeHead(200, { 'content-type': 'text/plain' }); <ide> res.end(body); <del>}); <add>})); <ide> <ide> server.listen(0, function() { <ide> var args = ['s_client', <ide> server.listen(0, function() { <ide> throw error; <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(subjectaltname, 'URI:http://example.com/#me'); <del> assert.equal(modulus, 'A6F44A9C25791431214F5C87AF9E040177A8BB89AC803F7E09' + <del> 'BBC3A5519F349CD9B9C40BE436D0AA823A94147E26C89248ADA2BE3DD4D34E8C2896' + <del> '4694B2047D217B4F1299371EA93A83C89AB9440724131E65F2B0161DE9560CDE9C13' + <del> '455552B2F49CF0FB00D8D77532324913F6F80FF29D0A131D29DB06AFF8BE191B7920' + <del> 'DC2DAE1C26EA82A47847A10391EF3BF6AABB3CC40FF82100B03A4F0FF1809278E4DD' + <del> 'FDA7DE954ED56DC7AD9A47EEBC37D771A366FC60A5BCB72373BEC180649B3EFA0E90' + <del> '92707210B41B90032BB18BC91F2046EBDAF1191F4A4E26D71879C4C7867B62FCD508' + <del> 'E8CE66E82D128A71E915809FCF44E8DE774067F1DE5D70B9C03687'); <del> assert.equal(exponent, '0x10001'); <del>}); <ide><path>test/parallel/test-https-localaddress-bind-error.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> var fs = require('fs'); <ide> <ide> if (!common.hasCrypto) { <ide> var options = { <ide> }; <ide> <ide> var invalidLocalAddress = '1.2.3.4'; <del>var gotError = false; <ide> <ide> var server = https.createServer(options, function(req, res) { <ide> console.log('Connect from: ' + req.connection.remoteAddress); <ide> var server = https.createServer(options, function(req, res) { <ide> req.resume(); <ide> }); <ide> <del>server.listen(0, '127.0.0.1', function() { <add>server.listen(0, '127.0.0.1', common.mustCall(function() { <ide> https.request({ <ide> host: 'localhost', <ide> port: this.address().port, <ide> server.listen(0, '127.0.0.1', function() { <ide> localAddress: invalidLocalAddress <ide> }, function(res) { <ide> common.fail('unexpectedly got response from server'); <del> }).on('error', function(e) { <add> }).on('error', common.mustCall(function(e) { <ide> console.log('client got error: ' + e.message); <del> gotError = true; <ide> server.close(); <del> }).end(); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(gotError); <del>}); <add> })).end(); <add>})); <ide><path>test/parallel/test-https-pfx.js <ide> var server = https.createServer(options, function(req, res) { <ide> res.end('OK'); <ide> }); <ide> <del>server.listen(0, options.host, function() { <add>server.listen(0, options.host, common.mustCall(function() { <ide> options.port = this.address().port; <del> var data = ''; <ide> <del> https.get(options, function(res) { <del> res.on('data', function(data_) { data += data_; }); <del> res.on('end', function() { server.close(); }); <del> }); <add> https.get(options, common.mustCall(function(res) { <add> var data = ''; <ide> <del> process.on('exit', function() { <del> assert.equal(data, 'OK'); <del> }); <del>}); <add> res.on('data', function(data_) { data += data_; }); <add> res.on('end', common.mustCall(function() { <add> assert.strictEqual(data, 'OK'); <add> server.close(); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-https-req-split.js <ide> process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; <ide> <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> var https = require('https'); <ide> var tls = require('tls'); <ide> var fs = require('fs'); <ide> <del>var seen_req = false; <del> <ide> var options = { <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> var options = { <ide> tls.SLAB_BUFFER_SIZE = 1; <ide> <ide> var server = https.createServer(options); <del>server.on('upgrade', function(req, socket, upgrade) { <add>server.on('upgrade', common.mustCall(function(req, socket, upgrade) { <ide> socket.on('data', function(data) { <ide> throw new Error('Unexpected data: ' + data); <ide> }); <ide> socket.end('HTTP/1.1 200 Ok\r\n\r\n'); <del> seen_req = true; <del>}); <add>})); <ide> <ide> server.listen(0, function() { <ide> var req = https.request({ <ide> server.listen(0, function() { <ide> <ide> req.end(); <ide> }); <del> <del>process.on('exit', function() { <del> assert(seen_req); <del> console.log('ok'); <del>}); <ide><path>test/parallel/test-https-set-timeout-server.js <ide> function run() { <ide> } <ide> <ide> test(function serverTimeout(cb) { <del> var caughtTimeout = false; <del> process.on('exit', function() { <del> assert(caughtTimeout); <del> }); <ide> var server = https.createServer(serverOptions, function(req, res) { <ide> // just do nothing, we should get a timeout event. <ide> }); <del> server.listen(0, function() { <del> var s = server.setTimeout(50, function(socket) { <del> caughtTimeout = true; <add> server.listen(0, common.mustCall(function() { <add> var s = server.setTimeout(50, common.mustCall(function(socket) { <ide> socket.destroy(); <ide> server.close(); <ide> cb(); <del> }); <add> })); <ide> assert.ok(s instanceof https.Server); <ide> https.get({ <ide> port: this.address().port, <ide> rejectUnauthorized: false <ide> }).on('error', function() {}); <del> }); <add> })); <ide> }); <ide> <ide> test(function serverRequestTimeout(cb) { <del> var caughtTimeout = false; <del> process.on('exit', function() { <del> assert(caughtTimeout); <del> }); <del> var server = https.createServer(serverOptions, function(req, res) { <add> function handler(req, res) { <ide> // just do nothing, we should get a timeout event. <del> req.setTimeout(50, function() { <del> caughtTimeout = true; <add> req.setTimeout(50, common.mustCall(function() { <ide> req.socket.destroy(); <ide> server.close(); <ide> cb(); <del> }); <del> }); <add> })); <add> } <add> <add> var server = https.createServer(serverOptions, common.mustCall(handler)); <ide> server.listen(0, function() { <ide> var req = https.request({ <ide> port: this.address().port, <ide> test(function serverRequestTimeout(cb) { <ide> }); <ide> <ide> test(function serverResponseTimeout(cb) { <del> var caughtTimeout = false; <del> process.on('exit', function() { <del> assert(caughtTimeout); <del> }); <del> var server = https.createServer(serverOptions, function(req, res) { <add> function handler(req, res) { <ide> // just do nothing, we should get a timeout event. <del> res.setTimeout(50, function() { <del> caughtTimeout = true; <add> res.setTimeout(50, common.mustCall(function() { <ide> res.socket.destroy(); <ide> server.close(); <ide> cb(); <del> }); <del> }); <add> })); <add> } <add> <add> var server = https.createServer(serverOptions, common.mustCall(handler)); <ide> server.listen(0, function() { <ide> https.get({ <ide> port: this.address().port, <ide> test(function serverResponseTimeout(cb) { <ide> }); <ide> <ide> test(function serverRequestNotTimeoutAfterEnd(cb) { <del> var caughtTimeoutOnRequest = false; <del> var caughtTimeoutOnResponse = false; <del> process.on('exit', function() { <del> assert(!caughtTimeoutOnRequest); <del> assert(caughtTimeoutOnResponse); <del> }); <del> var server = https.createServer(serverOptions, function(req, res) { <add> function handler(req, res) { <ide> // just do nothing, we should get a timeout event. <del> req.setTimeout(50, function(socket) { <del> caughtTimeoutOnRequest = true; <del> }); <del> res.on('timeout', function(socket) { <del> caughtTimeoutOnResponse = true; <del> }); <del> }); <add> req.setTimeout(50, common.fail); <add> res.on('timeout', common.mustCall(function(socket) {})); <add> } <add> var server = https.createServer(serverOptions, common.mustCall(handler)); <ide> server.on('timeout', function(socket) { <ide> socket.destroy(); <ide> server.close(); <ide> test(function serverResponseTimeoutWithPipeline(cb) { <ide> }); <ide> <ide> test(function idleTimeout(cb) { <del> var caughtTimeoutOnRequest = false; <del> var caughtTimeoutOnResponse = false; <del> var caughtTimeoutOnServer = false; <del> process.on('exit', function() { <del> assert(!caughtTimeoutOnRequest); <del> assert(!caughtTimeoutOnResponse); <del> assert(caughtTimeoutOnServer); <del> }); <del> var server = https.createServer(serverOptions, function(req, res) { <del> req.on('timeout', function(socket) { <del> caughtTimeoutOnRequest = true; <del> }); <del> res.on('timeout', function(socket) { <del> caughtTimeoutOnResponse = true; <del> }); <del> res.end(); <del> }); <del> server.setTimeout(50, function(socket) { <del> caughtTimeoutOnServer = true; <add> var server = https.createServer(serverOptions, <add> common.mustCall(function(req, res) { <add> req.on('timeout', common.fail); <add> res.on('timeout', common.fail); <add> res.end(); <add> })); <add> server.setTimeout(50, common.mustCall(function(socket) { <ide> socket.destroy(); <ide> server.close(); <ide> cb(); <del> }); <add> })); <ide> server.listen(0, function() { <ide> var options = { <ide> port: this.address().port, <ide><path>test/parallel/test-https-timeout-server.js <ide> var https = require('https'); <ide> var net = require('net'); <ide> var fs = require('fs'); <ide> <del>var clientErrors = 0; <del> <del>process.on('exit', function() { <del> assert.equal(clientErrors, 1); <del>}); <del> <ide> var options = { <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), <ide> var options = { <ide> <ide> var server = https.createServer(options, common.fail); <ide> <del>server.on('clientError', function(err, conn) { <add>server.on('clientError', common.mustCall(function(err, conn) { <ide> // Don't hesitate to update the asserts if the internal structure of <ide> // the cleartext object ever changes. We're checking that the https.Server <ide> // has closed the client connection. <ide> assert.equal(conn._secureEstablished, false); <ide> server.close(); <del> clientErrors++; <ide> conn.destroy(); <del>}); <add>})); <ide> <ide> server.listen(0, function() { <ide> net.connect({ host: '127.0.0.1', port: this.address().port }); <ide><path>test/parallel/test-listen-fd-ebadf.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <del>var gotError = 0; <del> <del>process.on('exit', function() { <del> assert.equal(gotError, 2); <del>}); <del> <del>net.createServer(common.fail).listen({fd: 2}).on('error', onError); <del>net.createServer(common.fail).listen({fd: 42}).on('error', onError); <add>net.createServer(common.fail).listen({fd: 2}) <add> .on('error', common.mustCall(onError)); <add>net.createServer(common.fail).listen({fd: 42}) <add> .on('error', common.mustCall(onError)); <ide> <ide> function onError(ex) { <ide> assert.equal(ex.code, 'EINVAL'); <del> gotError++; <ide> } <ide><path>test/parallel/test-net-after-close.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <del>var closed = false; <ide> <ide> var server = net.createServer(function(s) { <ide> console.error('SERVER: got connection'); <ide> s.end(); <ide> }); <ide> <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var c = net.createConnection(this.address().port); <del> c.on('close', function() { <add> c.on('close', common.mustCall(function() { <ide> console.error('connection closed'); <ide> assert.strictEqual(c._handle, null); <del> closed = true; <ide> assert.doesNotThrow(function() { <ide> c.setNoDelay(); <ide> c.setKeepAlive(); <ide> server.listen(0, function() { <ide> c.remotePort; <ide> }); <ide> server.close(); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert(closed); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-net-bind-twice.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <del>var gotError = false; <add>var server1 = net.createServer(common.fail); <add>server1.listen(0, '127.0.0.1', common.mustCall(function() { <add> var server2 = net.createServer(common.fail); <add> server2.listen(this.address().port, '127.0.0.1', common.fail); <ide> <del>process.on('exit', function() { <del> assert(gotError); <del>}); <del> <del>function dontCall() { <del> assert(false); <del>} <del> <del>var server1 = net.createServer(dontCall); <del>server1.listen(0, '127.0.0.1', function() { <del> var server2 = net.createServer(dontCall); <del> server2.listen(this.address().port, '127.0.0.1', dontCall); <del> <del> server2.on('error', function(e) { <add> server2.on('error', common.mustCall(function(e) { <ide> assert.equal(e.code, 'EADDRINUSE'); <ide> server1.close(); <del> gotError = true; <del> }); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-net-can-reset-timeout.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var net = require('net'); <del>var assert = require('assert'); <ide> <del>var timeoutCount = 0; <del> <del>var server = net.createServer(function(stream) { <add>var server = net.createServer(common.mustCall(function(stream) { <ide> stream.setTimeout(100); <ide> <ide> stream.resume(); <ide> <del> stream.on('timeout', function() { <add> stream.on('timeout', common.mustCall(function() { <ide> console.log('timeout'); <ide> // try to reset the timeout. <ide> stream.write('WHAT.'); <del> // don't worry, the socket didn't *really* time out, we're just thinking <del> // it did. <del> timeoutCount += 1; <del> }); <add> })); <ide> <ide> stream.on('end', function() { <ide> console.log('server side end'); <ide> stream.end(); <ide> }); <del>}); <add>})); <ide> <ide> server.listen(0, function() { <ide> var c = net.createConnection(this.address().port); <ide> server.listen(0, function() { <ide> server.close(); <ide> }); <ide> }); <del> <del> <del>process.on('exit', function() { <del> assert.equal(1, timeoutCount); <del>}); <ide><path>test/parallel/test-net-connect-handle-econnrefused.js <ide> c.on('connect', function() { <ide> assert.ok(false); <ide> }); <ide> <del>var gotError = false; <del>c.on('error', function(e) { <add>c.on('error', common.mustCall(function(e) { <ide> console.error('couldn\'t connect.'); <del> gotError = true; <ide> assert.equal('ECONNREFUSED', e.code); <del>}); <del> <del> <del>process.on('exit', function() { <del> assert.ok(gotError); <del>}); <add>})); <ide><path>test/parallel/test-net-connect-options.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <del>var serverGotEnd = false; <del>var clientGotEnd = false; <del> <del>var server = net.createServer({allowHalfOpen: true}, function(socket) { <add>var server = net.createServer({ <add> allowHalfOpen: true <add>}, common.mustCall(function(socket) { <ide> socket.resume(); <del> socket.on('end', function() { <del> serverGotEnd = true; <del> }); <add> socket.on('end', common.mustCall(function() {})); <ide> socket.end(); <del>}); <add>})); <ide> <ide> server.listen(0, function() { <ide> var client = net.connect({ <ide> host: '127.0.0.1', <ide> port: this.address().port, <ide> allowHalfOpen: true <del> }, function() { <add> }, common.mustCall(function() { <ide> console.error('client connect cb'); <ide> client.resume(); <del> client.on('end', function() { <del> clientGotEnd = true; <add> client.on('end', common.mustCall(function() { <ide> setTimeout(function() { <ide> assert(client.writable); <ide> client.end(); <ide> }, 10); <del> }); <add> })); <ide> client.on('close', function() { <ide> server.close(); <ide> }); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> console.error('exit', serverGotEnd, clientGotEnd); <del> assert(serverGotEnd); <del> assert(clientGotEnd); <add> })); <ide> }); <ide><path>test/parallel/test-net-dns-custom-lookup.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <del>var ok = false; <ide> <ide> function check(addressType, cb) { <ide> var server = net.createServer(function(client) { <ide> function check(addressType, cb) { <ide> }); <ide> <ide> var address = addressType === 4 ? common.localhostIPv4 : '::1'; <del> server.listen(0, address, function() { <add> server.listen(0, address, common.mustCall(function() { <ide> net.connect({ <ide> port: this.address().port, <ide> host: 'localhost', <ide> family: addressType, <ide> lookup: lookup <del> }).on('lookup', function(err, ip, type) { <add> }).on('lookup', common.mustCall(function(err, ip, type) { <ide> assert.equal(err, null); <ide> assert.equal(address, ip); <ide> assert.equal(type, addressType); <del> ok = true; <del> }); <del> }); <add> })); <add> })); <ide> <ide> function lookup(host, dnsopts, cb) { <ide> dnsopts.family = addressType; <ide> function check(addressType, cb) { <ide> check(4, function() { <ide> common.hasIPv6 && check(6); <ide> }); <del> <del>process.on('exit', function() { <del> assert.ok(ok); <del>}); <ide><path>test/parallel/test-net-dns-error.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var net = require('net'); <ide> <del>var expected_bad_connections = 1; <del>var actual_bad_connections = 0; <del> <ide> var host = '*'.repeat(256); <ide> <ide> function do_not_call() { <ide> throw new Error('This function should not have been called.'); <ide> } <ide> <ide> var socket = net.connect(42, host, do_not_call); <del>socket.on('error', function(err) { <add>socket.on('error', common.mustCall(function(err) { <ide> assert.equal(err.code, 'ENOTFOUND'); <del> actual_bad_connections++; <del>}); <add>})); <ide> socket.on('lookup', function(err, ip, type) { <ide> assert(err instanceof Error); <ide> assert.equal(err.code, 'ENOTFOUND'); <ide> assert.equal(ip, undefined); <ide> assert.equal(type, undefined); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(actual_bad_connections, expected_bad_connections); <del>}); <ide><path>test/parallel/test-net-dns-lookup.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <del>var ok = false; <ide> <ide> var server = net.createServer(function(client) { <ide> client.end(); <ide> server.close(); <ide> }); <ide> <del>server.listen(0, '127.0.0.1', function() { <add>server.listen(0, '127.0.0.1', common.mustCall(function() { <ide> net.connect(this.address().port, 'localhost') <del> .on('lookup', function(err, ip, type, host) { <add> .on('lookup', common.mustCall(function(err, ip, type, host) { <ide> assert.equal(err, null); <ide> assert.equal(ip, '127.0.0.1'); <ide> assert.equal(type, '4'); <ide> assert.equal(host, 'localhost'); <del> ok = true; <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert(ok); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-net-during-close.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <del>var accessedProperties = false; <ide> <ide> var server = net.createServer(function(socket) { <ide> socket.end(); <ide> }); <ide> <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var client = net.createConnection(this.address().port); <ide> server.close(); <ide> // server connection event has not yet fired <ide> server.listen(0, function() { <ide> client.remoteFamily; <ide> client.remotePort; <ide> }); <del> accessedProperties = true; <ide> // exit now, do not wait for the client error event <ide> process.exit(0); <del>}); <del> <del>process.on('exit', function() { <del> assert(accessedProperties); <del>}); <add>})); <ide><path>test/parallel/test-net-large-string.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var kPoolSize = 40 * 1024; <ide> var data = 'あ'.repeat(kPoolSize); <del>var receivedSize = 0; <ide> var encoding = 'UTF-8'; <ide> <del>var server = net.createServer(function(socket) { <add>var server = net.createServer(common.mustCall(function(socket) { <add> var receivedSize = 0; <add> <ide> socket.setEncoding(encoding); <ide> socket.on('data', function(data) { <ide> receivedSize += data.length; <ide> }); <del> socket.on('end', function() { <add> socket.on('end', common.mustCall(function() { <add> assert.strictEqual(receivedSize, kPoolSize); <ide> socket.end(); <del> }); <del>}); <add> })); <add>})); <ide> <ide> server.listen(0, function() { <ide> var client = net.createConnection(this.address().port); <ide> server.listen(0, function() { <ide> client.write(data, encoding); <ide> client.end(); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(receivedSize, kPoolSize); <del>}); <ide><path>test/parallel/test-net-listen-close-server-callback-is-not-function.js <ide> 'use strict'; <ide> const common = require('../common'); <del>var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer(common.fail); <del>var closeEvents = 0; <ide> <del>server.on('close', function() { <del> ++closeEvents; <del>}); <add>server.on('close', common.mustCall(function() {})); <ide> <ide> server.listen(0, common.fail); <ide> <ide> server.close('bad argument'); <del> <del>process.on('exit', function() { <del> assert.equal(closeEvents, 1); <del>}); <ide><path>test/parallel/test-net-listen-close-server.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var net = require('net'); <ide> <ide> var server = net.createServer(function(socket) { <ide> }); <del>server.listen(0, function() { <del> assert(false); <del>}); <del>server.on('error', function(error) { <del> console.error(error); <del> assert(false); <del>}); <add>server.listen(0, common.fail); <add>server.on('error', common.fail); <ide> server.close(); <ide><path>test/parallel/test-net-listen-error.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var net = require('net'); <del>var gotError = false; <ide> <ide> var server = net.createServer(function(socket) { <ide> }); <del>server.listen(1, '1.1.1.1', function() { // EACCESS or EADDRNOTAVAIL <del> assert(false); <del>}); <del>server.on('error', function(error) { <del> console.error(error); <del> gotError = true; <del>}); <del> <del>process.on('exit', function() { <del> assert(gotError); <del>}); <add>server.listen(1, '1.1.1.1', common.fail); // EACCESS or EADDRNOTAVAIL <add>server.on('error', common.mustCall(function(error) {})); <ide><path>test/parallel/test-net-local-address-port.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <del>var conns = 0; <del> <del>var server = net.createServer(function(socket) { <del> conns++; <add>var server = net.createServer(common.mustCall(function(socket) { <ide> assert.equal(socket.localAddress, common.localhostIPv4); <ide> assert.equal(socket.localPort, this.address().port); <ide> socket.on('end', function() { <ide> server.close(); <ide> }); <ide> socket.resume(); <del>}); <add>})); <ide> <ide> server.listen(0, common.localhostIPv4, function() { <ide> var client = net.createConnection(this.address().port, common.localhostIPv4); <ide> client.on('connect', function() { <ide> client.end(); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(1, conns); <del>}); <ide><path>test/parallel/test-net-pause-resume-connecting.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <ide> server.listen(0, function() { <ide> // Client 3 <ide> conn = require('net').createConnection(this.address().port, 'localhost'); <ide> conn.pause(); <del> conn.on('data', onDataError); <add> conn.on('data', common.fail); <ide> scheduleTearDown(conn); <ide> <ide> <ide> server.listen(0, function() { <ide> conn.resume(); <ide> conn.resume(); <ide> conn.pause(); <del> conn.on('data', onDataError); <add> conn.on('data', common.fail); <ide> scheduleTearDown(conn); <ide> <del> <del> // Client helper functions <del> function onDataError() { <del> assert(false); <del> } <del> <ide> function onDataOk() { <ide> dataEvents++; <ide> } <ide><path>test/parallel/test-net-pipe-connect-errors.js <ide> 'use strict'; <add>var common = require('../common'); <ide> var fs = require('fs'); <ide> var net = require('net'); <ide> var path = require('path'); <ide> var assert = require('assert'); <del>var common = require('../common'); <ide> <del>var notSocketErrorFired = false; <del>var noEntErrorFired = false; <ide> var accessErrorFired = false; <ide> <ide> // Test if ENOTSOCK is fired when trying to connect to a file which is not <ide> var notSocketClient = net.createConnection(emptyTxt, function() { <ide> assert.ok(false); <ide> }); <ide> <del>notSocketClient.on('error', function(err) { <add>notSocketClient.on('error', common.mustCall(function(err) { <ide> assert(err.code === 'ENOTSOCK' || err.code === 'ECONNREFUSED', <ide> `received ${err.code} instead of ENOTSOCK or ECONNREFUSED`); <del> notSocketErrorFired = true; <del>}); <add>})); <ide> <ide> <ide> // Trying to connect to not-existing socket should result in ENOENT error <ide> var noEntSocketClient = net.createConnection('no-ent-file', function() { <ide> assert.ok(false); <ide> }); <ide> <del>noEntSocketClient.on('error', function(err) { <add>noEntSocketClient.on('error', common.mustCall(function(err) { <ide> assert.equal(err.code, 'ENOENT'); <del> noEntErrorFired = true; <del>}); <add>})); <ide> <ide> <ide> // On Windows or when running as root, a chmod has no effect on named pipes <ide> if (!common.isWindows && process.getuid() !== 0) { <ide> <ide> // Assert that all error events were fired <ide> process.on('exit', function() { <del> assert.ok(notSocketErrorFired); <del> assert.ok(noEntErrorFired); <ide> if (!common.isWindows && process.getuid() !== 0) { <ide> assert.ok(accessErrorFired); <ide> } <ide> }); <del> <ide><path>test/parallel/test-net-remote-address-port.js <ide> var assert = require('assert'); <ide> <ide> var net = require('net'); <ide> <del>var conns = 0, conns_closed = 0; <add>var conns_closed = 0; <ide> <ide> var remoteAddrCandidates = [ common.localhostIPv4 ]; <ide> if (common.hasIPv6) remoteAddrCandidates.push('::ffff:127.0.0.1'); <ide> <ide> var remoteFamilyCandidates = ['IPv4']; <ide> if (common.hasIPv6) remoteFamilyCandidates.push('IPv6'); <ide> <del>var server = net.createServer(function(socket) { <del> conns++; <add>var server = net.createServer(common.mustCall(function(socket) { <ide> assert.notEqual(-1, remoteAddrCandidates.indexOf(socket.remoteAddress)); <ide> assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); <ide> assert.ok(socket.remotePort); <ide> var server = net.createServer(function(socket) { <ide> assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); <ide> }); <ide> socket.resume(); <del>}); <add>}, 2)); <ide> <ide> server.listen(0, 'localhost', function() { <ide> var client = net.createConnection(this.address().port, 'localhost'); <ide> server.listen(0, 'localhost', function() { <ide> assert.notEqual(-1, remoteFamilyCandidates.indexOf(client2.remoteFamily)); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(2, conns); <del>}); <ide><path>test/parallel/test-net-server-unref-persistent.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var net = require('net'); <del>var closed = false; <ide> var server = net.createServer(); <ide> <ide> // unref before listening <ide> server.listen(); <ide> <ide> // If the timeout fires, that means the server held the event loop open <ide> // and the unref() was not persistent. Close the server and fail the test. <del>setTimeout(function() { <del> closed = true; <del> server.close(); <del>}, 1000).unref(); <del> <del>process.on('exit', function() { <del> assert.strictEqual(closed, false, 'server should not hold loop open'); <del>}); <add>setTimeout(common.fail, 1000).unref(); <ide><path>test/parallel/test-net-server-unref.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <del> <add>const common = require('../common'); <ide> var net = require('net'); <del>var closed = false; <ide> <ide> var s = net.createServer(); <ide> s.listen(0); <ide> s.unref(); <ide> <del>setTimeout(function() { <del> closed = true; <del> s.close(); <del>}, 1000).unref(); <del> <del>process.on('exit', function() { <del> assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); <del>}); <add>setTimeout(common.fail, 1000).unref(); <ide><path>test/parallel/test-net-socket-destroy-twice.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> var net = require('net'); <ide> <del>var nerrors = 0; <del>var ncloses = 0; <del> <del>process.on('exit', function() { <del> assert.equal(nerrors, 1); <del> assert.equal(ncloses, 1); <del>}); <del> <ide> var conn = net.createConnection(common.PORT); <ide> <del>conn.on('error', function() { <del> nerrors++; <add>conn.on('error', common.mustCall(function() { <ide> conn.destroy(); <del>}); <add>})); <ide> <del>conn.on('close', function() { <del> ncloses++; <del>}); <add>conn.on('close', common.mustCall(function() {})); <ide><path>test/parallel/test-net-socket-timeout.js <ide> for (let i = 0; i < validDelays.length; i++) { <ide> }); <ide> } <ide> <del>var timedout = false; <del> <ide> var server = net.Server(); <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var socket = net.createConnection(this.address().port); <del> socket.setTimeout(100, function() { <del> timedout = true; <add> socket.setTimeout(100, common.mustCall(function() { <ide> socket.destroy(); <ide> server.close(); <ide> clearTimeout(timer); <del> }); <add> })); <ide> var timer = setTimeout(function() { <ide> process.exit(1); <ide> }, common.platformTimeout(200)); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(timedout); <del>}); <add>})); <ide><path>test/parallel/test-net-write-after-close.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var net = require('net'); <ide> <del>var gotError = false; <del>var gotWriteCB = false; <del> <del>process.on('exit', function() { <del> assert(gotError); <del> assert(gotWriteCB); <del>}); <del> <del>var server = net.createServer(function(socket) { <add>var server = net.createServer(common.mustCall(function(socket) { <ide> socket.resume(); <ide> <del> socket.on('error', function(error) { <add> socket.on('error', common.mustCall(function(error) { <ide> console.error('got error, closing server', error); <ide> server.close(); <del> gotError = true; <del> }); <add> })); <ide> <del> setTimeout(function() { <add> setTimeout(common.mustCall(function() { <ide> console.error('about to try to write'); <del> socket.write('test', function(e) { <del> gotWriteCB = true; <del> }); <del> }, 250); <del>}); <add> socket.write('test', common.mustCall(function(e) {})); <add> }), 250); <add>})); <ide> <ide> server.listen(0, function() { <ide> var client = net.connect(this.address().port, function() { <ide><path>test/parallel/test-net-write-connect-write.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <del>var received = ''; <del> <ide> var server = net.createServer(function(socket) { <ide> socket.pipe(socket); <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var conn = net.connect(this.address().port); <add> var received = ''; <add> <ide> conn.setEncoding('utf8'); <ide> conn.write('before'); <ide> conn.on('connect', function() { <ide> var server = net.createServer(function(socket) { <ide> received += buf; <ide> conn.end(); <ide> }); <del> conn.on('end', function() { <add> conn.on('end', common.mustCall(function() { <ide> server.close(); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(received, 'before' + 'after'); <del>}); <add> assert.strictEqual(received, 'before' + 'after'); <add> })); <add>})); <ide><path>test/parallel/test-net-write-slow.js <ide> var server = net.createServer(function(socket) { <ide> } <ide> socket.end(); <ide> <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var conn = net.connect(this.address().port); <ide> conn.on('data', function(buf) { <ide> received += buf.length; <ide> var server = net.createServer(function(socket) { <ide> conn.resume(); <ide> }, 20); <ide> }); <del> conn.on('end', function() { <add> conn.on('end', common.mustCall(function() { <ide> server.close(); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(received, SIZE * N); <del>}); <add> assert.strictEqual(received, SIZE * N); <add> })); <add>})); <ide><path>test/parallel/test-next-tick.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <del>var complete = 0; <add>process.nextTick(common.mustCall(function() { <add> process.nextTick(common.mustCall(function() { <add> process.nextTick(common.mustCall(function() {})); <add> })); <add>})); <ide> <del>process.nextTick(function() { <del> complete++; <del> process.nextTick(function() { <del> complete++; <del> process.nextTick(function() { <del> complete++; <del> }); <del> }); <del>}); <del> <del>setTimeout(function() { <del> process.nextTick(function() { <del> complete++; <del> }); <del>}, 50); <add>setTimeout(common.mustCall(function() { <add> process.nextTick(common.mustCall(function() {})); <add>}), 50); <ide> <del>process.nextTick(function() { <del> complete++; <del>}); <add>process.nextTick(common.mustCall(function() {})); <ide> <ide> var obj = {}; <ide> <ide> process.nextTick(function(a, b) { <ide> }, 42, obj); <ide> <ide> process.on('exit', function() { <del> assert.equal(5, complete); <del> process.nextTick(function() { <del> throw new Error('this should not occur'); <del> }); <add> process.nextTick(common.fail); <ide> }); <ide><path>test/parallel/test-pipe-address.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <del> <del>var address = null; <del> <del>var server = net.createServer(function() { <del> assert(false); // should not be called <del>}); <add>var server = net.createServer(common.fail); <ide> <ide> common.refreshTmpDir(); <ide> <del>server.listen(common.PIPE, function() { <del> address = server.address(); <add>server.listen(common.PIPE, common.mustCall(function() { <add> assert.strictEqual(server.address(), common.PIPE); <ide> server.close(); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(address, common.PIPE); <del>}); <add>})); <ide><path>test/parallel/test-pipe-head.js <ide> var script = join(common.fixturesDir, 'print-10-lines.js'); <ide> <ide> var cmd = '"' + nodePath + '" "' + script + '" | head -2'; <ide> <del>var finished = false; <del> <del>exec(cmd, function(err, stdout, stderr) { <add>exec(cmd, common.mustCall(function(err, stdout, stderr) { <ide> if (err) throw err; <ide> var lines = stdout.split('\n'); <ide> assert.equal(3, lines.length); <del> finished = true; <del>}); <del> <del> <del>process.on('exit', function() { <del> assert.ok(finished); <del>}); <add>})); <ide><path>test/parallel/test-pipe-unref.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <del> <ide> var net = require('net'); <del>var closed = false; <ide> <ide> common.refreshTmpDir(); <ide> <ide> var s = net.Server(); <ide> s.listen(common.PIPE); <ide> s.unref(); <ide> <del>setTimeout(function() { <del> closed = true; <del> s.close(); <del>}, 1000).unref(); <del> <del>process.on('exit', function() { <del> assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); <del>}); <add>setTimeout(common.fail, 1000).unref(); <ide><path>test/parallel/test-process-next-tick.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var N = 2; <del>var tickCount = 0; <del>var exceptionCount = 0; <ide> <ide> function cb() { <del> ++tickCount; <ide> throw new Error(); <ide> } <ide> <ide> for (var i = 0; i < N; ++i) { <del> process.nextTick(cb); <add> process.nextTick(common.mustCall(cb)); <ide> } <ide> <del>process.on('uncaughtException', function() { <del> ++exceptionCount; <del>}); <add>process.on('uncaughtException', common.mustCall(function() {}, N)); <ide> <ide> process.on('exit', function() { <ide> process.removeAllListeners('uncaughtException'); <del> assert.equal(tickCount, N); <del> assert.equal(exceptionCount, N); <ide> }); <ide><path>test/parallel/test-process-remove-all-signal-listeners.js <ide> 'use strict'; <ide> <add>const common = require('../common'); <ide> const assert = require('assert'); <ide> const spawn = require('child_process').spawn; <del>const common = require('../common'); <ide> <ide> if (common.isWindows) { <ide> common.skip('Win32 doesn\'t have signals, just a kind of ' + <ide> 'emulation, insufficient for this test to apply.'); <ide> return; <ide> } <ide> <del>var ok; <del> <ide> if (process.argv[2] !== '--do-test') { <ide> // We are the master, fork a child so we can verify it exits with correct <ide> // status. <ide> process.env.DOTEST = 'y'; <ide> var child = spawn(process.execPath, [__filename, '--do-test']); <ide> <del> child.once('exit', function(code, signal) { <add> child.once('exit', common.mustCall(function(code, signal) { <ide> assert.equal(signal, 'SIGINT'); <del> ok = true; <del> }); <del> <del> process.on('exit', function() { <del> assert(ok); <del> }); <add> })); <ide> <ide> return; <ide> } <ide><path>test/parallel/test-regress-GH-1531.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> var options = { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }; <ide> <del>var gotCallback = false; <del> <ide> var server = https.createServer(options, function(req, res) { <ide> res.writeHead(200); <ide> res.end('hello world\n'); <ide> }); <ide> <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> console.error('listening'); <ide> https.get({ <ide> agent: false, <ide> path: '/', <ide> port: this.address().port, <ide> rejectUnauthorized: false <del> }, function(res) { <add> }, common.mustCall(function(res) { <ide> console.error(res.statusCode, res.headers); <del> gotCallback = true; <ide> res.resume(); <ide> server.close(); <del> }).on('error', function(e) { <add> })).on('error', function(e) { <ide> console.error(e.stack); <ide> process.exit(1); <ide> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(gotCallback); <del> console.log('ok'); <del>}); <add>})); <ide><path>test/parallel/test-regress-GH-3542.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const path = require('path'); <del>let succeeded = 0; <ide> <ide> // This test is only relevant on Windows. <ide> if (!common.isWindows) { <ide> function test(p) { <ide> var result = fs.realpathSync(p); <ide> assert.strictEqual(result.toLowerCase(), path.resolve(p).toLowerCase()); <ide> <del> fs.realpath(p, function(err, result) { <add> fs.realpath(p, common.mustCall(function(err, result) { <ide> assert.ok(!err); <ide> assert.strictEqual(result.toLowerCase(), path.resolve(p).toLowerCase()); <del> succeeded++; <del> }); <add> })); <ide> } <ide> <ide> test('//localhost/c$/Windows/System32'); <ide> test('\\\\localhost\\c$\\'); <ide> test('C:\\'); <ide> test('C:'); <ide> test(process.env.windir); <del> <del>process.on('exit', function() { <del> assert.strictEqual(succeeded, 7); <del>}); <ide><path>test/parallel/test-regress-GH-746.js <ide> // Just test that destroying stdin doesn't mess up listening on a server. <ide> // This is a regression test for GH-746. <ide> <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var net = require('net'); <ide> <ide> process.stdin.destroy(); <ide> <del>var accepted = null; <del>var server = net.createServer(function(socket) { <add>var server = net.createServer(common.mustCall(function(socket) { <ide> console.log('accepted'); <del> accepted = socket; <ide> socket.end(); <ide> server.close(); <del>}); <add>})); <ide> <ide> <ide> server.listen(0, function() { <ide> console.log('listening...'); <ide> <ide> net.createConnection(this.address().port); <ide> }); <del> <del> <del>process.on('exit', function() { <del> assert.ok(accepted); <del>}); <del> <ide><path>test/parallel/test-sigint-infinite-loop.js <ide> // This test is to assert that we can SIGINT a script which loops forever. <ide> // Ref(http): <ide> // groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var spawn = require('child_process').spawn; <ide> <ide> console.log('start'); <ide> var c = spawn(process.execPath, ['-e', 'while(true) { console.log("hi"); }']); <ide> <ide> var sentKill = false; <del>var gotChildExit = true; <ide> <ide> c.stdout.on('data', function(s) { <ide> // Prevent race condition: <ide> c.stdout.on('data', function(s) { <ide> } <ide> }); <ide> <del>c.on('exit', function(code) { <add>c.on('exit', common.mustCall(function(code) { <ide> assert.ok(code !== 0); <ide> console.log('killed infinite-loop.js'); <del> gotChildExit = true; <del>}); <add>})); <ide> <ide> process.on('exit', function() { <ide> assert.ok(sentKill); <del> assert.ok(gotChildExit); <ide> }); <del> <ide><path>test/parallel/test-signal-handler.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> <ide> if (common.isWindows) { <ide> common.skip('SIGUSR1 and SIGHUP signals are not supported'); <ide> if (common.isWindows) { <ide> <ide> console.log('process.pid: ' + process.pid); <ide> <del>let first = 0; <del>let second = 0; <add>process.on('SIGUSR1', common.mustCall(function() {})); <ide> <del>var sighup = false; <del> <del>process.on('SIGUSR1', function() { <del> console.log('Interrupted by SIGUSR1'); <del> first += 1; <del>}); <del> <del>process.on('SIGUSR1', function() { <del> second += 1; <add>process.on('SIGUSR1', common.mustCall(function() { <ide> setTimeout(function() { <ide> console.log('End.'); <ide> process.exit(0); <ide> }, 5); <del>}); <add>})); <ide> <ide> var i = 0; <ide> setInterval(function() { <ide> setInterval(function() { <ide> // has been previously registered, and `process.listeners(SIGNAL).length === 1` <ide> process.on('SIGHUP', function() {}); <ide> process.removeAllListeners('SIGHUP'); <del>process.on('SIGHUP', function() { sighup = true; }); <add>process.on('SIGHUP', common.mustCall(function() {})); <ide> process.kill(process.pid, 'SIGHUP'); <del> <del>process.on('exit', function() { <del> assert.equal(1, first); <del> assert.equal(1, second); <del> assert.equal(true, sighup); <del>}); <ide><path>test/parallel/test-socket-write-after-fin.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <del>var serverData = ''; <del>var gotServerEnd = false; <del>var clientData = ''; <del>var gotClientEnd = false; <add>const expected = 'hello1hello2hello3\nTHUNDERMUSCLE!'; <add> <add>var server = net.createServer({ <add> allowHalfOpen: true <add>}, common.mustCall(function(sock) { <add> var serverData = ''; <ide> <del>var server = net.createServer({ allowHalfOpen: true }, function(sock) { <ide> sock.setEncoding('utf8'); <ide> sock.on('data', function(c) { <ide> serverData += c; <ide> }); <del> sock.on('end', function() { <del> gotServerEnd = true; <add> sock.on('end', common.mustCall(function() { <add> assert.strictEqual(serverData, expected); <ide> sock.end(serverData); <ide> server.close(); <del> }); <del>}); <del>server.listen(0, function() { <add> })); <add>})); <add>server.listen(0, common.mustCall(function() { <ide> var sock = net.connect(this.address().port); <add> var clientData = ''; <add> <ide> sock.setEncoding('utf8'); <ide> sock.on('data', function(c) { <ide> clientData += c; <ide> }); <ide> <del> sock.on('end', function() { <del> gotClientEnd = true; <del> }); <del> <del> process.on('exit', function() { <del> assert.equal(serverData, clientData); <del> assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); <del> assert(gotClientEnd); <del> assert(gotServerEnd); <del> console.log('ok'); <del> }); <add> sock.on('end', common.mustCall(function() { <add> assert.strictEqual(clientData, expected); <add> })); <ide> <ide> sock.write('hello1'); <ide> sock.write('hello2'); <ide> sock.write('hello3\n'); <ide> sock.end('THUNDERMUSCLE!'); <del>}); <add>})); <ide><path>test/parallel/test-stdout-close-unref.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const spawn = require('child_process').spawn; <ide> <ide> if (process.argv[2] === 'child') { <del> var errs = 0; <del> <ide> process.stdin.resume(); <ide> process.stdin._handle.close(); <ide> process.stdin._handle.unref(); // Should not segfault. <del> process.stdin.on('error', function(err) { <del> errs++; <del> }); <del> <del> process.on('exit', function() { <del> assert.strictEqual(errs, 1); <del> }); <add> process.stdin.on('error', common.mustCall(function(err) {})); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-stdout-stderr-reading.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> // verify that stdout is never read from. <ide> else <ide> function parent() { <ide> var spawn = require('child_process').spawn; <ide> var node = process.execPath; <del> var closes = 0; <ide> <ide> var c1 = spawn(node, [__filename, 'child']); <ide> var c1out = ''; <ide> function parent() { <ide> c1.stderr.on('data', function(chunk) { <ide> console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); <ide> }); <del> c1.on('close', function(code, signal) { <del> closes++; <add> c1.on('close', common.mustCall(function(code, signal) { <ide> assert(!code); <ide> assert(!signal); <ide> assert.equal(c1out, 'ok\n'); <ide> console.log('ok'); <del> }); <add> })); <ide> <ide> var c2 = spawn(node, ['-e', 'console.log("ok")']); <ide> var c2out = ''; <ide> function parent() { <ide> c1.stderr.on('data', function(chunk) { <ide> console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); <ide> }); <del> c2.on('close', function(code, signal) { <del> closes++; <add> c2.on('close', common.mustCall(function(code, signal) { <ide> assert(!code); <ide> assert(!signal); <ide> assert.equal(c2out, 'ok\n'); <ide> console.log('ok'); <del> }); <del> <del> process.on('exit', function() { <del> assert.equal(closes, 2, 'saw both closes'); <del> }); <add> })); <ide> } <ide> <ide> function child() { <ide><path>test/parallel/test-stdout-to-file.js <ide> function test(size, useBuffer, cb) { <ide> }); <ide> } <ide> <del>var finished = false; <del>test(1024 * 1024, false, function() { <add>test(1024 * 1024, false, common.mustCall(function() { <ide> console.log('Done printing with string'); <del> test(1024 * 1024, true, function() { <add> test(1024 * 1024, true, common.mustCall(function() { <ide> console.log('Done printing with buffer'); <del> finished = true; <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(finished); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-stream-end-paused.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <del>var gotEnd = false; <ide> <ide> // Make sure we don't miss the end event for paused 0-length streams <ide> <ide> stream.on('data', function() { <ide> }); <ide> stream.pause(); <ide> <del>setTimeout(function() { <del> stream.on('end', function() { <del> gotEnd = true; <del> }); <add>setTimeout(common.mustCall(function() { <add> stream.on('end', common.mustCall(function() {})); <ide> stream.resume(); <del>}); <add>})); <ide> <ide> process.on('exit', function() { <del> assert(gotEnd); <ide> assert(calledRead); <ide> console.log('ok'); <ide> }); <ide><path>test/parallel/test-stream-pipe-error-handling.js <ide> const Stream = require('stream').Stream; <ide> const w = new W(); <ide> let removed = false; <ide> <del> r._read = function() { <add> r._read = common.mustCall(function() { <ide> setTimeout(common.mustCall(function() { <ide> assert(removed); <ide> assert.throws(function() { <ide> w.emit('error', new Error('fail')); <ide> }); <ide> })); <del> }; <add> }); <ide> <ide> w.on('error', myOnError); <ide> r.pipe(w); <ide> const Stream = require('stream').Stream; <ide> const w = new W(); <ide> let removed = false; <ide> <del> r._read = function() { <add> r._read = common.mustCall(function() { <ide> setTimeout(common.mustCall(function() { <ide> assert(removed); <ide> w.emit('error', new Error('fail')); <ide> })); <del> }; <add> }); <ide> <ide> w.on('error', common.mustCall(function(er) {})); <ide> w._write = function() {}; <ide><path>test/parallel/test-stream-wrap.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> const assert = require('assert'); <ide> <ide> const StreamWrap = require('_stream_wrap'); <ide> const Duplex = require('stream').Duplex; <ide> const ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; <ide> <del>var done = false; <del> <ide> function testShutdown(callback) { <ide> var stream = new Duplex({ <ide> read: function() { <ide> function testShutdown(callback) { <ide> req.handle.shutdown(req); <ide> } <ide> <del>testShutdown(function() { <del> done = true; <del>}); <del> <del>process.on('exit', function() { <del> assert(done); <del>}); <add>testShutdown(common.mustCall(function() {})); <ide><path>test/parallel/test-stream2-httpclient-response-end.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var msg = 'Hello'; <del>var readable_event = false; <del>var end_event = false; <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.end(msg); <ide> }).listen(0, function() { <ide> http.get({port: this.address().port}, function(res) { <ide> var data = ''; <del> res.on('readable', function() { <add> res.on('readable', common.mustCall(function() { <ide> console.log('readable event'); <del> readable_event = true; <ide> data += res.read(); <del> }); <del> res.on('end', function() { <add> })); <add> res.on('end', common.mustCall(function() { <ide> console.log('end event'); <del> end_event = true; <ide> assert.strictEqual(msg, data); <ide> server.close(); <del> }); <add> })); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert(readable_event); <del> assert(end_event); <del>}); <del> <ide><path>test/parallel/test-stream2-large-read-stall.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> // If everything aligns so that you do a read(n) of exactly the <ide> r.on('readable', function() { <ide> rs.length); <ide> }); <ide> <del>var endEmitted = false; <del>r.on('end', function() { <del> endEmitted = true; <del> console.error('end'); <del>}); <add>r.on('end', common.mustCall(function() {})); <ide> <ide> var pushes = 0; <ide> function push() { <ide> function push() { <ide> <ide> process.on('exit', function() { <ide> assert.equal(pushes, PUSHCOUNT + 1); <del> assert(endEmitted); <ide> }); <ide><path>test/parallel/test-stream2-read-sync-stack.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var Readable = require('stream').Readable; <ide> var r = new Readable(); <ide> var N = 256 * 1024; <ide> r.on('readable', function onReadable() { <ide> r.read(N * 2); <ide> }); <ide> <del>var ended = false; <del>r.on('end', function onEnd() { <del> ended = true; <del>}); <add>r.on('end', common.mustCall(function() {})); <ide> <ide> r.read(0); <del> <del>process.on('exit', function() { <del> assert(ended); <del> console.log('ok'); <del>}); <ide><path>test/parallel/test-stream2-readable-legacy-drain.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var Stream = require('stream'); <ide> r._read = function(n) { <ide> return r.push(++reads === N ? null : Buffer.allocUnsafe(1)); <ide> }; <ide> <del>var rended = false; <del>r.on('end', function() { <del> rended = true; <del>}); <add>r.on('end', common.mustCall(function() {})); <ide> <ide> var w = new Stream(); <ide> w.writable = true; <ide> function drain() { <ide> w.emit('drain'); <ide> } <ide> <del> <del>var wended = false; <del>w.end = function() { <del> wended = true; <del>}; <add>w.end = common.mustCall(function() {}); <ide> <ide> // Just for kicks, let's mess with the drain count. <ide> // This verifies that even if it gets negative in the <ide> r.on('readable', function() { <ide> }); <ide> <ide> r.pipe(w); <del>process.on('exit', function() { <del> assert(rended); <del> assert(wended); <del> console.error('ok'); <del>}); <ide><path>test/parallel/test-stream2-readable-non-empty-end.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var Readable = require('_stream_readable'); <ide> <ide> test.read(0); <ide> function next() { <ide> // now let's make 'end' happen <ide> test.removeListener('end', thrower); <del> <del> var endEmitted = false; <del> process.on('exit', function() { <del> assert(endEmitted, 'end should be emitted by now'); <del> }); <del> test.on('end', function() { <del> endEmitted = true; <del> }); <add> test.on('end', common.mustCall(function() {})); <ide> <ide> // one to get the last byte <ide> var r = test.read(); <ide><path>test/parallel/test-stream2-readable-wrap-empty.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> <ide> var Readable = require('_stream_readable'); <ide> var EE = require('events').EventEmitter; <ide> oldStream.resume = function() {}; <ide> <ide> var newStream = new Readable().wrap(oldStream); <ide> <del>var ended = false; <ide> newStream <ide> .on('readable', function() {}) <del> .on('end', function() { ended = true; }); <add> .on('end', common.mustCall(function() {})); <ide> <ide> oldStream.emit('end'); <del> <del>process.on('exit', function() { <del> assert.ok(ended); <del>}); <ide><path>test/parallel/test-tls-0-dns-altname.js <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <ide> <del>var requests = 0; <del> <ide> var server = tls.createServer({ <ide> key: fs.readFileSync(common.fixturesDir + '/keys/0-dns-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/0-dns-cert.pem') <ide> var server = tls.createServer({ <ide> c.destroy(); <ide> server.close(); <ide> }); <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var c = tls.connect(this.address().port, { <ide> rejectUnauthorized: false <del> }, function() { <del> requests++; <add> }, common.mustCall(function() { <ide> var cert = c.getPeerCertificate(); <ide> assert.equal(cert.subjectaltname, <ide> 'DNS:google.com\0.evil.com, ' + <ide> var server = tls.createServer({ <ide> 'IP Address:8.8.4.4, ' + <ide> 'DNS:last.com'); <ide> c.write('ok'); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(requests, 1); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-tls-cert-regression.js <ide> 'use strict'; <del>var assert = require('assert'); <ide> var common = require('../common'); <ide> <ide> if (!common.hasCrypto) { <ide> function test(cert, key, cb) { <ide> }); <ide> } <ide> <del>var completed = false; <del>test(cert, key, function() { <del> test(Buffer.from(cert), Buffer.from(key), function() { <del> completed = true; <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert(completed); <del>}); <add>test(cert, key, common.mustCall(function() { <add> test(Buffer.from(cert), Buffer.from(key), common.mustCall(function() {})); <add>})); <ide><path>test/parallel/test-tls-client-abort2.js <ide> if (!common.hasCrypto) { <ide> } <ide> var tls = require('tls'); <ide> <del>var errors = 0; <del> <del>var conn = tls.connect(common.PORT, function() { <del> assert(false); // callback should never be executed <del>}); <del>conn.on('error', function() { <del> ++errors; <add>var conn = tls.connect(common.PORT, common.fail); <add>conn.on('error', common.mustCall(function() { <ide> assert.doesNotThrow(function() { <ide> conn.destroy(); <ide> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(errors, 1); <del>}); <add>})); <ide><path>test/parallel/test-tls-client-destroy-soon.js <ide> var options = { <ide> }; <ide> <ide> var big = Buffer.alloc(2 * 1024 * 1024, 'Y'); <del>var connections = 0; <del>var bytesRead = 0; <ide> <ide> // create server <del>var server = tls.createServer(options, function(socket) { <add>var server = tls.createServer(options, common.mustCall(function(socket) { <ide> socket.end(big); <ide> socket.destroySoon(); <del> connections++; <del>}); <add>})); <ide> <ide> // start listening <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var client = tls.connect({ <ide> port: this.address().port, <ide> rejectUnauthorized: false <del> }, function() { <add> }, common.mustCall(function() { <add> var bytesRead = 0; <add> <ide> client.on('readable', function() { <ide> var d = client.read(); <ide> if (d) <ide> bytesRead += d.length; <ide> }); <ide> <del> client.on('end', function() { <add> client.on('end', common.mustCall(function() { <ide> server.close(); <del> }); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(1, connections); <del> assert.equal(big.length, bytesRead); <del>}); <add> assert.strictEqual(big.length, bytesRead); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-tls-client-reject.js <ide> var options = { <ide> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) <ide> }; <ide> <del>var connectCount = 0; <del> <del>var server = tls.createServer(options, function(socket) { <del> ++connectCount; <add>var server = tls.createServer(options, common.mustCall(function(socket) { <ide> socket.on('data', function(data) { <ide> console.error(data.toString()); <ide> assert.equal(data, 'ok'); <ide> }); <del>}).listen(0, function() { <add>}, 3)).listen(0, function() { <ide> unauthorized(); <ide> }); <ide> <ide> function unauthorized() { <ide> socket.end(); <ide> rejectUnauthorized(); <ide> }); <del> socket.on('error', function(err) { <del> assert(false); <del> }); <add> socket.on('error', common.fail); <ide> socket.write('ok'); <ide> } <ide> <ide> function rejectUnauthorized() { <ide> var socket = tls.connect(server.address().port, { <ide> servername: 'localhost' <del> }, function() { <del> assert(false); <del> }); <add> }, common.fail); <ide> socket.on('error', function(err) { <ide> console.error(err); <ide> authorized(); <ide> function authorized() { <ide> socket.end(); <ide> server.close(); <ide> }); <del> socket.on('error', function(err) { <del> assert(false); <del> }); <add> socket.on('error', common.fail); <ide> socket.write('ok'); <ide> } <del> <del>process.on('exit', function() { <del> assert.equal(connectCount, 3); <del>}); <ide><path>test/parallel/test-tls-client-resume.js <ide> var options = { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') <ide> }; <ide> <del>var connections = 0; <del> <ide> // create server <del>var server = tls.Server(options, function(socket) { <add>var server = tls.Server(options, common.mustCall(function(socket) { <ide> socket.end('Goodbye'); <del> connections++; <del>}); <add>}, 2)); <ide> <ide> // start listening <ide> server.listen(0, function() { <ide> server.listen(0, function() { <ide> }); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(2, connections); <del>}); <ide><path>test/parallel/test-tls-close-error.js <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <ide> <del>var errorCount = 0; <del>var closeCount = 0; <del> <ide> var server = tls.createServer({ <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }, function(c) { <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var c = tls.connect(this.address().port, function() { <ide> assert(false, 'should not be called'); <ide> }); <ide> <del> c.on('error', function(err) { <del> errorCount++; <del> }); <del> <del> c.on('close', function(err) { <del> if (err) <del> closeCount++; <add> c.on('error', common.mustCall(function(err) {})); <ide> <add> c.on('close', common.mustCall(function(err) { <add> assert.ok(err); <ide> server.close(); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(errorCount, 1); <del> assert.equal(closeCount, 1); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-tls-close-notify.js <ide> 'use strict'; <del>var assert = require('assert'); <ide> var common = require('../common'); <ide> <ide> if (!common.hasCrypto) { <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <ide> <del>var ended = 0; <del> <ide> var server = tls.createServer({ <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }, function(c) { <ide> // Send close-notify without shutting down TCP socket <ide> if (c._handle.shutdownSSL() !== 1) <ide> c._handle.shutdownSSL(); <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var c = tls.connect(this.address().port, { <ide> rejectUnauthorized: false <del> }, function() { <add> }, common.mustCall(function() { <ide> // Ensure that we receive 'end' event anyway <del> c.on('end', function() { <del> ended++; <add> c.on('end', common.mustCall(function() { <ide> c.destroy(); <ide> server.close(); <del> }); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(ended, 1); <del>}); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-tls-connect-pipe.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <ide> <del>var clientConnected = 0; <del>var serverConnected = 0; <del> <ide> var options = { <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }; <ide> <ide> common.refreshTmpDir(); <ide> <del>var server = tls.Server(options, function(socket) { <del> ++serverConnected; <add>var server = tls.Server(options, common.mustCall(function(socket) { <ide> server.close(); <del>}); <del>server.listen(common.PIPE, function() { <add>})); <add>server.listen(common.PIPE, common.mustCall(function() { <ide> var options = { rejectUnauthorized: false }; <del> var client = tls.connect(common.PIPE, options, function() { <del> ++clientConnected; <add> var client = tls.connect(common.PIPE, options, common.mustCall(function() { <ide> client.end(); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(clientConnected, 1); <del> assert.equal(serverConnected, 1); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-tls-connect.js <ide> var path = require('path'); <ide> const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); <ide> const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); <ide> <del> let errorEmitted = false; <del> <del> process.on('exit', function() { <del> assert.ok(errorEmitted); <del> }); <del> <ide> const options = {cert: cert, key: key, port: common.PORT}; <del> const conn = tls.connect(options, function() { <del> assert.ok(false); // callback should never be executed <del> }); <add> const conn = tls.connect(options, common.fail); <ide> <del> conn.on('error', function() { <del> errorEmitted = true; <del> }); <add> conn.on('error', common.mustCall(function() {})); <ide> } <ide> <ide> // SSL_accept/SSL_connect error handling <ide> { <ide> const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); <ide> const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); <ide> <del> let errorEmitted = false; <del> <del> process.on('exit', function() { <del> assert.ok(errorEmitted); <del> }); <del> <ide> const conn = tls.connect({ <ide> cert: cert, <ide> key: key, <ide> var path = require('path'); <ide> assert.ok(false); // callback should never be executed <ide> }); <ide> <del> conn.on('error', function() { <del> errorEmitted = true; <del> }); <add> conn.on('error', common.mustCall(function() {})); <ide> } <ide><path>test/parallel/test-tls-delayed-attach-error.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> var net = require('net'); <ide> <ide> var bonkers = Buffer.alloc(1024, 42); <ide> <del>var receivedError = false; <ide> var options = { <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }; <ide> <del>var server = net.createServer(function(c) { <del> setTimeout(function() { <add>var server = net.createServer(common.mustCall(function(c) { <add> setTimeout(common.mustCall(function() { <ide> var s = new tls.TLSSocket(c, { <ide> isServer: true, <ide> secureContext: tls.createSecureContext(options) <ide> }); <ide> <del> s.on('_tlsError', function() { <del> receivedError = true; <del> }); <add> s.on('_tlsError', common.mustCall(function() {})); <ide> <ide> s.on('close', function() { <ide> server.close(); <ide> s.destroy(); <ide> }); <del> }, 200); <del>}).listen(0, function() { <add> }), 200); <add>})).listen(0, function() { <ide> var c = net.connect({port: this.address().port}, function() { <ide> c.write(bonkers); <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.ok(receivedError); <del>}); <ide><path>test/parallel/test-tls-ecdh-disable.js <ide> var options = { <ide> ecdhCurve: false <ide> }; <ide> <del>var nconns = 0; <del> <del>process.on('exit', function() { <del> assert.equal(nconns, 0); <del>}); <del> <del>var server = tls.createServer(options, function(conn) { <del> conn.end(); <del> nconns++; <del>}); <add>var server = tls.createServer(options, common.fail); <ide> <ide> server.listen(0, '127.0.0.1', function() { <ide> var cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + <ide><path>test/parallel/test-tls-ecdh.js <ide> var options = { <ide> }; <ide> <ide> var reply = 'I AM THE WALRUS'; // something recognizable <del>var nconns = 0; <del>var response = ''; <ide> <del>process.on('exit', function() { <del> assert.equal(nconns, 1); <del> assert.notEqual(response.indexOf(reply), -1); <del>}); <del> <del>var server = tls.createServer(options, function(conn) { <add>var server = tls.createServer(options, common.mustCall(function(conn) { <ide> conn.end(reply); <del> nconns++; <del>}); <add>})); <ide> <del>server.listen(0, '127.0.0.1', function() { <add>server.listen(0, '127.0.0.1', common.mustCall(function() { <ide> var cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + <ide> ` -connect 127.0.0.1:${this.address().port}`; <ide> <ide> // for the performance and stability issue in s_client on Windows <ide> if (common.isWindows) <ide> cmd += ' -no_rand_screen'; <ide> <del> exec(cmd, function(err, stdout, stderr) { <add> exec(cmd, common.mustCall(function(err, stdout, stderr) { <ide> if (err) throw err; <del> response = stdout; <add> assert.notEqual(stdout.indexOf(reply), -1); <ide> server.close(); <del> }); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-tls-getcipher.js <ide> var options = { <ide> honorCipherOrder: true <ide> }; <ide> <del>var nconns = 0; <del> <del>process.on('exit', function() { <del> assert.equal(nconns, 1); <del>}); <del> <del>var server = tls.createServer(options, function(cleartextStream) { <del> nconns++; <del>}); <add>var server = tls.createServer(options, <add> common.mustCall(function(cleartextStream) {})); <ide> <ide> server.listen(0, '127.0.0.1', function() { <ide> var client = tls.connect({ <ide><path>test/parallel/test-tls-handshake-error.js <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <ide> <del>var errorCount = 0; <del>var closeCount = 0; <del> <ide> var server = tls.createServer({ <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), <ide> rejectUnauthorized: true <ide> }, function(c) { <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var c = tls.connect({ <ide> port: this.address().port, <ide> ciphers: 'RC4' <ide> }, function() { <ide> assert(false, 'should not be called'); <ide> }); <ide> <del> c.on('error', function(err) { <del> errorCount++; <add> c.on('error', common.mustCall(function(err) { <ide> assert.notEqual(err.code, 'ECONNRESET'); <del> }); <add> })); <ide> <del> c.on('close', function(err) { <del> if (err) <del> closeCount++; <add> c.on('close', common.mustCall(function(err) { <add> assert.ok(err); <ide> server.close(); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(errorCount, 1); <del> assert.equal(closeCount, 1); <del>}); <add> })); <add>})); <ide><path>test/parallel/test-tls-invoke-queued.js <ide> var fs = require('fs'); <ide> <ide> <ide> var received = ''; <del>var ended = 0; <ide> <ide> var server = tls.createServer({ <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> var server = tls.createServer({ <ide> }); <ide> <ide> server.close(); <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var c = tls.connect(this.address().port, { <ide> rejectUnauthorized: false <del> }, function() { <add> }, common.mustCall(function() { <ide> c.on('data', function(chunk) { <ide> received += chunk; <ide> }); <del> c.on('end', function() { <del> ended++; <del> }); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(ended, 1); <del> assert.equal(received, 'hello world! gosh'); <del>}); <add> c.on('end', common.mustCall(function() { <add> assert.strictEqual(received, 'hello world! gosh'); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-tls-legacy-onselect.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> if (!common.hasCrypto) { <ide> var tls = require('tls'); <ide> var net = require('net'); <ide> <del>var success = false; <del> <del>var server = net.Server(function(raw) { <add>var server = net.Server(common.mustCall(function(raw) { <ide> var pair = tls.createSecurePair(null, true, false, false); <ide> pair.on('error', function() {}); <del> pair.ssl.setSNICallback(function() { <add> pair.ssl.setSNICallback(common.mustCall(function() { <ide> raw.destroy(); <ide> server.close(); <del> success = true; <del> }); <add> })); <ide> require('_tls_legacy').pipe(pair, raw); <del>}).listen(0, function() { <add>})).listen(0, function() { <ide> tls.connect({ <ide> port: this.address().port, <ide> rejectUnauthorized: false, <ide> var server = net.Server(function(raw) { <ide> // Just ignore <ide> }); <ide> }); <del>process.on('exit', function() { <del> assert(success); <del>}); <ide><path>test/parallel/test-tls-max-send-fragment.js <ide> var fs = require('fs'); <ide> <ide> var buf = Buffer.allocUnsafe(10000); <ide> var received = 0; <del>var ended = 0; <ide> var maxChunk = 768; <ide> <ide> var server = tls.createServer({ <ide> var server = tls.createServer({ <ide> assert(c.setMaxSendFragment(maxChunk)); <ide> <ide> c.end(buf); <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var c = tls.connect(this.address().port, { <ide> rejectUnauthorized: false <del> }, function() { <add> }, common.mustCall(function() { <ide> c.on('data', function(chunk) { <ide> assert(chunk.length <= maxChunk); <ide> received += chunk.length; <ide> }); <ide> <ide> // Ensure that we receive 'end' event anyway <del> c.on('end', function() { <del> ended++; <add> c.on('end', common.mustCall(function() { <ide> c.destroy(); <ide> server.close(); <del> }); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(ended, 1); <del> assert.equal(received, buf.length); <del>}); <add> assert.strictEqual(received, buf.length); <add> })); <add> })); <add>})); <ide><path>test/parallel/test-tls-no-rsa-key.js <ide> var options = { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/ec-cert.pem') <ide> }; <ide> <del>var cert = null; <del> <ide> var server = tls.createServer(options, function(conn) { <ide> conn.end('ok'); <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var c = tls.connect(this.address().port, { <ide> rejectUnauthorized: false <del> }, function() { <add> }, common.mustCall(function() { <ide> c.on('end', common.mustCall(function() { <ide> c.end(); <ide> server.close(); <ide> var server = tls.createServer(options, function(conn) { <ide> assert.equal(data, 'ok'); <ide> }); <ide> <del> cert = c.getPeerCertificate(); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert(cert); <del> assert.equal(cert.subject.C, 'US'); <del>}); <add> const cert = c.getPeerCertificate(); <add> assert.strictEqual(cert.subject.C, 'US'); <add> })); <add>})); <ide><path>test/parallel/test-tls-passphrase.js <ide> var server = tls.Server({ <ide> s.end(); <ide> }); <ide> <del>var connectCount = 0; <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var c = tls.connect({ <ide> port: this.address().port, <ide> key: key, <ide> passphrase: 'passphrase', <ide> cert: cert, <ide> rejectUnauthorized: false <del> }, function() { <del> ++connectCount; <del> }); <add> }, common.mustCall(function() {})); <ide> c.on('end', function() { <ide> server.close(); <ide> }); <del>}); <add>})); <ide> <ide> assert.throws(function() { <ide> tls.connect({ <ide> assert.throws(function() { <ide> rejectUnauthorized: false <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.equal(connectCount, 1); <del>}); <ide><path>test/parallel/test-tls-peer-certificate-encoding.js <ide> var options = { <ide> cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-cert.pem')), <ide> ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca2-cert.pem')) ] <ide> }; <del>var verified = false; <ide> <ide> var server = tls.createServer(options, function(cleartext) { <ide> cleartext.end('World'); <ide> }); <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var socket = tls.connect({ <ide> port: this.address().port, <ide> rejectUnauthorized: false <del> }, function() { <add> }, common.mustCall(function() { <ide> var peerCert = socket.getPeerCertificate(); <ide> <ide> console.error(util.inspect(peerCert)); <ide> assert.equal(peerCert.subject.CN, 'Ádám Lippai'); <del> verified = true; <ide> server.close(); <del> }); <add> })); <ide> socket.end('Hello'); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(verified); <del>}); <add>})); <ide><path>test/parallel/test-tls-peer-certificate-multi-keys.js <ide> var options = { <ide> key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), <ide> cert: fs.readFileSync(join(common.fixturesDir, 'multi-alice.crt')) <ide> }; <del>var verified = false; <ide> <ide> var server = tls.createServer(options, function(cleartext) { <ide> cleartext.end('World'); <ide> }); <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var socket = tls.connect({ <ide> port: this.address().port, <ide> rejectUnauthorized: false <del> }, function() { <add> }, common.mustCall(function() { <ide> var peerCert = socket.getPeerCertificate(); <ide> console.error(util.inspect(peerCert)); <ide> assert.deepStrictEqual( <ide> peerCert.subject.OU, <ide> ['Information Technology', 'Engineering', 'Marketing'] <ide> ); <del> verified = true; <ide> server.close(); <del> }); <add> })); <ide> socket.end('Hello'); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(verified); <del>}); <add>})); <ide><path>test/parallel/test-tls-peer-certificate.js <ide> var options = { <ide> cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-cert.pem')), <ide> ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca1-cert.pem')) ] <ide> }; <del>var verified = false; <ide> <ide> var server = tls.createServer(options, function(cleartext) { <ide> cleartext.end('World'); <ide> }); <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> var socket = tls.connect({ <ide> port: this.address().port, <ide> rejectUnauthorized: false <del> }, function() { <add> }, common.mustCall(function() { <ide> var peerCert = socket.getPeerCertificate(); <ide> assert.ok(!peerCert.issuerCertificate); <ide> <ide> server.listen(0, function() { <ide> var issuer = peerCert.issuerCertificate; <ide> assert.ok(issuer.issuerCertificate === issuer); <ide> assert.equal(issuer.serialNumber, '8DF21C01468AF393'); <del> verified = true; <ide> server.close(); <del> }); <add> })); <ide> socket.end('Hello'); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(verified); <del>}); <add>})); <ide><path>test/parallel/test-tls-request-timeout.js <ide> var tls = require('tls'); <ide> <ide> var fs = require('fs'); <ide> <del>var hadTimeout = false; <del> <ide> var options = { <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }; <ide> <del>var server = tls.Server(options, function(socket) { <add>var server = tls.Server(options, common.mustCall(function(socket) { <ide> var s = socket.setTimeout(100); <ide> assert.ok(s instanceof tls.TLSSocket); <ide> <del> socket.on('timeout', function(err) { <del> hadTimeout = true; <add> socket.on('timeout', common.mustCall(function(err) { <ide> socket.end(); <ide> server.close(); <del> }); <del>}); <add> })); <add>})); <ide> <ide> server.listen(0, function() { <ide> tls.connect({ <ide> port: this.address().port, <ide> rejectUnauthorized: false <ide> }); <ide> }); <del> <del>process.on('exit', function() { <del> assert.ok(hadTimeout); <del>}); <ide><path>test/parallel/test-tls-securepair-server.js <ide> var net = require('net'); <ide> var fs = require('fs'); <ide> var spawn = require('child_process').spawn; <ide> <del>var connections = 0; <ide> var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); <ide> var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); <ide> <ide> function log(a) { <ide> console.error('***server*** ' + a); <ide> } <ide> <del>var server = net.createServer(function(socket) { <del> connections++; <add>var server = net.createServer(common.mustCall(function(socket) { <ide> log('connection fd=' + socket.fd); <ide> var sslcontext = tls.createSecureContext({key: key, cert: cert}); <ide> sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); <ide> var server = net.createServer(function(socket) { <ide> log(err.stack); <ide> socket.destroy(); <ide> }); <del>}); <add>})); <ide> <ide> var gotHello = false; <ide> var sentWorld = false; <ide> var gotWorld = false; <del>var opensslExitCode = -1; <ide> <del>server.listen(0, function() { <add>server.listen(0, common.mustCall(function() { <ide> // To test use: openssl s_client -connect localhost:8000 <ide> <ide> var args = ['s_client', '-connect', `127.0.0.1:${this.address().port}`]; <ide> server.listen(0, function() { <ide> <ide> client.stdout.pipe(process.stdout, { end: false }); <ide> <del> client.on('exit', function(code) { <del> opensslExitCode = code; <add> client.on('exit', common.mustCall(function(code) { <add> assert.strictEqual(0, code); <ide> server.close(); <del> }); <del>}); <add> })); <add>})); <ide> <ide> process.on('exit', function() { <del> assert.equal(1, connections); <ide> assert.ok(gotHello); <ide> assert.ok(sentWorld); <ide> assert.ok(gotWorld); <del> assert.equal(0, opensslExitCode); <ide> }); <ide><path>test/parallel/test-tls-set-ciphers.js <ide> var options = { <ide> }; <ide> <ide> var reply = 'I AM THE WALRUS'; // something recognizable <del>var nconns = 0; <ide> var response = ''; <ide> <ide> process.on('exit', function() { <del> assert.equal(nconns, 1); <ide> assert.notEqual(response.indexOf(reply), -1); <ide> }); <ide> <del>var server = tls.createServer(options, function(conn) { <add>var server = tls.createServer(options, common.mustCall(function(conn) { <ide> conn.end(reply); <del> nconns++; <del>}); <add>})); <ide> <ide> server.listen(0, '127.0.0.1', function() { <ide> var cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + <ide><path>test/parallel/test-tls-set-encoding.js <ide> var options = { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') <ide> }; <ide> <del>var connections = 0; <ide> var message = 'hello world\n'; <ide> <ide> <del>var server = tls.Server(options, function(socket) { <add>var server = tls.Server(options, common.mustCall(function(socket) { <ide> socket.end(message); <del> connections++; <del>}); <add>})); <ide> <ide> <ide> server.listen(0, function() { <ide> server.listen(0, function() { <ide> server.close(); <ide> }); <ide> }); <del> <del> <del>process.on('exit', function() { <del> assert.equal(1, connections); <del>}); <ide><path>test/parallel/test-tls-timeout-server.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> var tls = require('tls'); <ide> var net = require('net'); <ide> var fs = require('fs'); <ide> <del>var clientErrors = 0; <del> <del>process.on('exit', function() { <del> assert.equal(clientErrors, 1); <del>}); <del> <ide> var options = { <ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), <ide> var options = { <ide> <ide> var server = tls.createServer(options, common.fail); <ide> <del>server.on('tlsClientError', function(err, conn) { <add>server.on('tlsClientError', common.mustCall(function(err, conn) { <ide> conn.destroy(); <ide> server.close(); <del> clientErrors++; <del>}); <add>})); <ide> <ide> server.listen(0, function() { <ide> net.connect({ host: '127.0.0.1', port: this.address().port }); <ide><path>test/parallel/test-tls-zero-clear-in.js <ide> 'use strict'; <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide> var path = require('path'); <ide> var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); <ide> var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); <ide> <del>var errorEmitted = false; <del> <ide> var server = tls.createServer({ <ide> cert: cert, <ide> key: key <ide> var server = tls.createServer({ <ide> c.end(); <ide> server.close(); <ide> }, 20); <del>}).listen(0, function() { <add>}).listen(0, common.mustCall(function() { <ide> var conn = tls.connect({ <ide> cert: cert, <ide> key: key, <ide> var server = tls.createServer({ <ide> // treated as error. <ide> conn.end(''); <ide> <del> conn.on('error', function(err) { <del> console.log(err); <del> errorEmitted = true; <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(!errorEmitted); <del>}); <add> conn.on('error', common.fail); <add>})); <ide><path>test/parallel/test-zerolengthbufferbug.js <ide> 'use strict'; <ide> // Serving up a zero-length buffer should work. <ide> <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <ide> var server = http.createServer(function(req, res) { <ide> res.end(buffer); <ide> }); <ide> <del>var gotResponse = false; <del>var resBodySize = 0; <add>server.listen(0, common.mustCall(function() { <add> http.get({ port: this.address().port }, common.mustCall(function(res) { <ide> <del>server.listen(0, function() { <del> http.get({ port: this.address().port }, function(res) { <del> gotResponse = true; <del> <del> res.on('data', function(d) { <del> resBodySize += d.length; <del> }); <add> res.on('data', common.fail); <ide> <ide> res.on('end', function(d) { <ide> server.close(); <ide> }); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.ok(gotResponse); <del> assert.equal(0, resBodySize); <del>}); <del> <add> })); <add>})); <ide><path>test/parallel/test-zlib-close-after-write.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> var zlib = require('zlib'); <ide> <del>var closed = false; <del> <del>zlib.gzip('hello', function(err, out) { <add>zlib.gzip('hello', common.mustCall(function(err, out) { <ide> var unzip = zlib.createGunzip(); <ide> unzip.write(out); <del> unzip.close(function() { <del> closed = true; <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert(closed); <del>}); <add> unzip.close(common.mustCall(function() {})); <add>})); <ide><path>test/parallel/test-zlib-random-byte-pipes.js <ide> out.on('data', function(c) { <ide> console.error('out data', c.length); <ide> }); <ide> <del>var didSomething = false; <del>out.on('data', function(c) { <del> didSomething = true; <add>out.on('data', common.mustCall(function(c) { <ide> console.error('hash=%s', c); <ide> assert.equal(c, inp._hash, 'hashes should match'); <del>}); <del> <del>process.on('exit', function() { <del> assert(didSomething, 'should have done something'); <del>}); <add>})); <ide><path>test/parallel/test-zlib-write-after-close.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> var zlib = require('zlib'); <ide> <del>var closed = false; <del> <del>zlib.gzip('hello', function(err, out) { <add>zlib.gzip('hello', common.mustCall(function(err, out) { <ide> var unzip = zlib.createGunzip(); <del> unzip.close(function() { <del> closed = true; <del> }); <add> unzip.close(common.mustCall(function() {})); <ide> assert.throws(function() { <ide> unzip.write(out); <ide> }); <del>}); <del> <del>process.on('exit', function() { <del> assert(closed); <del>}); <add>})); <ide><path>test/parallel/test-zlib-zero-byte.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var zlib = require('zlib'); <ide> var received = 0; <ide> gz.on('data', function(c) { <ide> received += c.length; <ide> }); <del>var ended = false; <del>gz.on('end', function() { <del> ended = true; <del>}); <del>var finished = false; <del>gz.on('finish', function() { <del> finished = true; <del>}); <add> <add>gz.on('end', common.mustCall(function() { <add> assert.strictEqual(received, 20); <add>})); <add>gz.on('finish', common.mustCall(function() {})); <ide> gz.write(emptyBuffer); <ide> gz.end(); <del> <del>process.on('exit', function() { <del> assert.equal(received, 20); <del> assert(ended); <del> assert(finished); <del> console.log('ok'); <del>}); <ide><path>test/pummel/test-http-client-reconnect-bug.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const net = require('net'); <ide> const http = require('http'); <ide> <del>var errorCount = 0; <del>var eofCount = 0; <del> <ide> var server = net.createServer(function(socket) { <ide> socket.end(); <ide> }); <ide> <del>server.on('listening', function() { <add>server.on('listening', common.mustCall(function() { <ide> var client = http.createClient(common.PORT); <ide> <del> client.on('error', function(err) { <del> // We should receive one error <del> console.log('ERROR! ' + err.message); <del> errorCount++; <del> }); <del> <del> client.on('end', function() { <del> // When we remove the old Client interface this will most likely have to be <del> // changed. <del> console.log('EOF!'); <del> eofCount++; <del> }); <add> client.on('error', common.mustCall(function(err) {})); <add> client.on('end', common.mustCall(function() {})); <ide> <ide> var request = client.request('GET', '/', {'host': 'localhost'}); <ide> request.end(); <ide> request.on('response', function(response) { <ide> console.log('STATUS: ' + response.statusCode); <ide> }); <del>}); <add>})); <ide> <ide> server.listen(common.PORT); <ide> <ide> setTimeout(function() { <ide> server.close(); <ide> }, 500); <del> <del> <del>process.on('exit', function() { <del> assert.equal(1, errorCount); <del> assert.equal(1, eofCount); <del>}); <ide><path>test/pummel/test-https-large-response.js <ide> var options = { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') <ide> }; <ide> <del>var reqCount = 0; <del> <ide> process.stdout.write('build body...'); <ide> var body = 'hello world\n'.repeat(1024 * 1024); <ide> process.stdout.write('done\n'); <ide> <del>var server = https.createServer(options, function(req, res) { <del> reqCount++; <add>var server = https.createServer(options, common.mustCall(function(req, res) { <ide> console.log('got request'); <ide> res.writeHead(200, { 'content-type': 'text/plain' }); <ide> res.end(body); <del>}); <del> <del>var count = 0; <del>var gotResEnd = false; <add>})); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(common.PORT, common.mustCall(function() { <ide> https.get({ <ide> port: common.PORT, <ide> rejectUnauthorized: false <del> }, function(res) { <add> }, common.mustCall(function(res) { <ide> console.log('response!'); <ide> <add> var count = 0; <add> <ide> res.on('data', function(d) { <ide> process.stdout.write('.'); <ide> count += d.length; <ide> server.listen(common.PORT, function() { <ide> }); <ide> }); <ide> <del> res.on('end', function(d) { <add> res.on('end', common.mustCall(function(d) { <ide> process.stdout.write('\n'); <ide> console.log('expected: ', body.length); <ide> console.log(' got: ', count); <ide> server.close(); <del> gotResEnd = true; <del> }); <del> }); <del>}); <del> <del> <del>process.on('exit', function() { <del> assert.equal(1, reqCount); <del> assert.equal(body.length, count); <del> assert.ok(gotResEnd); <del>}); <add> assert.strictEqual(count, body.length); <add> })); <add> })); <add>})); <ide><path>test/pummel/test-net-pingpong-delay.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var net = require('net'); <ide> <del> <del>var tests_run = 0; <del> <ide> function pingPongTest(port, host, on_complete) { <ide> var N = 100; <ide> var DELAY = 1; <ide> function pingPongTest(port, host, on_complete) { <ide> }); <ide> }); <ide> <del> server.listen(port, host, function() { <add> server.listen(port, host, common.mustCall(function() { <ide> var client = net.createConnection(port, host); <ide> <ide> client.setEncoding('utf8'); <ide> function pingPongTest(port, host, on_complete) { <ide> assert.equal(false, true); <ide> }); <ide> <del> client.on('close', function() { <add> client.on('close', common.mustCall(function() { <ide> console.log('client.end'); <ide> assert.equal(N + 1, count); <ide> assert.ok(client_ended); <ide> if (on_complete) on_complete(); <del> tests_run += 1; <del> }); <del> }); <add> })); <add> })); <ide> } <ide> <ide> pingPongTest(common.PORT); <del> <del>process.on('exit', function() { <del> assert.equal(1, tests_run); <del>}); <ide><path>test/pummel/test-net-timeout2.js <ide> // https://github.com/joyent/node/issues/2002 <ide> <ide> var common = require('../common'); <del>var assert = require('assert'); <ide> var net = require('net'); <ide> <ide> var seconds = 5; <del>var gotTimeout = false; <ide> var counter = 0; <ide> <ide> var server = net.createServer(function(socket) { <del> socket.setTimeout((seconds / 2) * 1000, function() { <del> gotTimeout = true; <del> console.log('timeout!!'); <del> socket.destroy(); <del> process.exit(1); <del> }); <add> socket.setTimeout((seconds / 2) * 1000, common.fail); <ide> <ide> var interval = setInterval(function() { <ide> counter++; <ide> server.listen(common.PORT, function() { <ide> var s = net.connect(common.PORT); <ide> s.pipe(process.stdout); <ide> }); <del> <del> <del>process.on('exit', function() { <del> assert.equal(false, gotTimeout); <del>}); <ide><path>test/pummel/test-timer-wrap.js <ide> 'use strict'; <del>require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <ide> <del>var timeouts = 0; <ide> var Timer = process.binding('timer_wrap').Timer; <ide> var kOnTimeout = Timer.kOnTimeout; <ide> <ide> var t = new Timer(); <ide> <ide> t.start(1000, 0); <ide> <del>t[kOnTimeout] = function() { <del> timeouts++; <add>t[kOnTimeout] = common.mustCall(function() { <ide> console.log('timeout'); <ide> t.close(); <del>}; <del> <del>process.on('exit', function() { <del> assert.equal(1, timeouts); <ide> }); <ide><path>test/pummel/test-timers.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> var WINDOW = 200; // why is does this need to be so big? <ide> <ide> var interval_count = 0; <del>var setTimeout_called = false; <ide> <ide> // check that these don't blow up. <ide> clearTimeout(null); <ide> clearInterval(null); <ide> <ide> assert.equal(true, setTimeout instanceof Function); <ide> var starttime = new Date(); <del>setTimeout(function() { <add>setTimeout(common.mustCall(function() { <ide> var endtime = new Date(); <ide> <ide> var diff = endtime - starttime; <ide> assert.ok(diff > 0); <ide> console.error('diff: ' + diff); <ide> <ide> assert.equal(true, 1000 - WINDOW < diff && diff < 1000 + WINDOW); <del> setTimeout_called = true; <del>}, 1000); <add>}), 1000); <ide> <ide> // this timer shouldn't execute <ide> var id = setTimeout(function() { assert.equal(true, false); }, 500); <ide> clearTimeout(y); <ide> <ide> <ide> process.on('exit', function() { <del> assert.equal(true, setTimeout_called); <ide> assert.equal(3, interval_count); <ide> assert.equal(11, count4); <ide> assert.equal(0, expectedTimeouts, 'clearTimeout cleared too many timeouts'); <ide><path>test/pummel/test-tls-server-large-request.js <ide> var fs = require('fs'); <ide> var stream = require('stream'); <ide> var util = require('util'); <ide> <del>var clientConnected = 0; <del>var serverConnected = 0; <ide> var request = Buffer.from(new Array(1024 * 256).join('ABCD')); // 1mb <ide> <ide> var options = { <ide> Mediator.prototype._write = function write(data, enc, cb) { <ide> <ide> var mediator = new Mediator(); <ide> <del>var server = tls.Server(options, function(socket) { <add>var server = tls.Server(options, common.mustCall(function(socket) { <ide> socket.pipe(mediator); <del> serverConnected++; <del>}); <add>})); <ide> <del>server.listen(common.PORT, function() { <add>server.listen(common.PORT, common.mustCall(function() { <ide> var client1 = tls.connect({ <ide> port: common.PORT, <ide> rejectUnauthorized: false <del> }, function() { <del> ++clientConnected; <add> }, common.mustCall(function() { <ide> client1.end(request); <del> }); <del>}); <del> <del>process.on('exit', function() { <del> assert.equal(clientConnected, 1); <del> assert.equal(serverConnected, 1); <del>}); <add> })); <add>})); <ide><path>test/pummel/test-tls-throttle.js <ide> var options = { <ide> cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') <ide> }; <ide> <del>var connections = 0; <del> <del> <del>var server = tls.Server(options, function(socket) { <add>var server = tls.Server(options, common.mustCall(function(socket) { <ide> socket.end(body); <del> connections++; <del>}); <add>})); <ide> <ide> var recvCount = 0; <ide> <ide> var timeout = setTimeout(displayCounts, 10 * 1000); <ide> <ide> process.on('exit', function() { <ide> displayCounts(); <del> assert.equal(1, connections); <ide> assert.equal(body.length, recvCount); <ide> }); <ide><path>test/sequential/test-net-GH-5504.js <ide> function client() { <ide> function parent() { <ide> var spawn = require('child_process').spawn; <ide> var node = process.execPath; <del> var assert = require('assert'); <del> var serverExited = false; <del> var clientExited = false; <del> var serverListened = false; <del> <del> process.on('exit', function() { <del> assert(serverExited); <del> assert(clientExited); <del> assert(serverListened); <del> console.log('ok'); <del> }); <ide> <ide> setTimeout(function() { <ide> if (s) s.kill(); <ide> function parent() { <ide> <ide> wrap(s.stderr, process.stderr, 'SERVER 2>'); <ide> wrap(s.stdout, process.stdout, 'SERVER 1>'); <del> s.on('exit', function(c) { <del> console.error('server exited', c); <del> serverExited = true; <del> }); <add> s.on('exit', common.mustCall(function(c) {})); <ide> <del> s.stdout.once('data', function() { <del> serverListened = true; <add> s.stdout.once('data', common.mustCall(function() { <ide> c = spawn(node, [__filename, 'client']); <ide> wrap(c.stderr, process.stderr, 'CLIENT 2>'); <ide> wrap(c.stdout, process.stdout, 'CLIENT 1>'); <del> c.on('exit', function(c) { <del> console.error('client exited', c); <del> clientExited = true; <del> }); <del> }); <add> c.on('exit', common.mustCall(function(c) {})); <add> })); <ide> <ide> function wrap(inp, out, w) { <ide> inp.setEncoding('utf8'); <ide><path>test/sequential/test-regress-GH-4027.js <ide> var filename = path.join(common.tmpDir, 'watched'); <ide> fs.writeFileSync(filename, 'quis custodiet ipsos custodes'); <ide> setTimeout(fs.unlinkSync, 100, filename); <ide> <del>var seenEvent = 0; <del>process.on('exit', function() { <del> assert.equal(seenEvent, 1); <del>}); <del> <del>fs.watchFile(filename, { interval: 50 }, function(curr, prev) { <add>fs.watchFile(filename, { interval: 50 }, common.mustCall(function(curr, prev) { <ide> assert.equal(prev.nlink, 1); <ide> assert.equal(curr.nlink, 0); <ide> fs.unwatchFile(filename); <del> seenEvent++; <del>}); <add>})); <ide><path>test/sequential/test-util-debug.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> var assert = require('assert'); <ide> <ide> if (process.argv[2] === 'child') <ide> function test(environ, shouldWrite) { <ide> 'TUD %PID%: number=1234 string=asdf obj={"foo":"bar"}\n'; <ide> } <ide> var expectOut = 'ok\n'; <del> var didTest = false; <ide> <ide> var spawn = require('child_process').spawn; <ide> var child = spawn(process.execPath, [__filename, 'child'], { <ide> function test(environ, shouldWrite) { <ide> out += c; <ide> }); <ide> <del> child.on('close', function(c) { <add> child.on('close', common.mustCall(function(c) { <ide> assert(!c); <ide> assert.equal(err, expectErr); <ide> assert.equal(out, expectOut); <del> didTest = true; <ide> console.log('ok %j %j', environ, shouldWrite); <del> }); <del> <del> process.on('exit', function() { <del> assert(didTest); <del> }); <add> })); <ide> } <ide> <ide>
213
Go
Go
remove engine.table from more daemon side stuff
650bc2ffe545f874adeb3c1d6f54e9158a7d647e
<ide><path>api/server/server_unit_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/api" <add> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/pkg/version" <ide> ) <ide> func TestGetImagesJSON(t *testing.T) { <ide> eng.Register("images", func(job *engine.Job) error { <ide> called = true <ide> v := createEnvFromGetImagesJSONStruct(sampleImage) <del> if _, err := v.WriteTo(job.Stdout); err != nil { <add> if err := json.NewEncoder(job.Stdout).Encode(v); err != nil { <ide> return err <ide> } <ide> return nil <ide> func TestGetImagesJSONLegacyFormat(t *testing.T) { <ide> var called bool <ide> eng.Register("images", func(job *engine.Job) error { <ide> called = true <del> outsLegacy := engine.NewTable("Created", 0) <del> outsLegacy.Add(createEnvFromGetImagesJSONStruct(sampleImage)) <del> if _, err := outsLegacy.WriteListTo(job.Stdout); err != nil { <add> images := []types.Image{ <add> createEnvFromGetImagesJSONStruct(sampleImage), <add> } <add> if err := json.NewEncoder(job.Stdout).Encode(images); err != nil { <ide> return err <ide> } <ide> return nil <ide> func assertHttpNotError(r *httptest.ResponseRecorder, t *testing.T) { <ide> } <ide> } <ide> <del>func createEnvFromGetImagesJSONStruct(data getImagesJSONStruct) *engine.Env { <del> v := &engine.Env{} <del> v.SetList("RepoTags", data.RepoTags) <del> v.Set("Id", data.Id) <del> v.SetInt64("Created", data.Created) <del> v.SetInt64("Size", data.Size) <del> v.SetInt64("VirtualSize", data.VirtualSize) <del> return v <add>func createEnvFromGetImagesJSONStruct(data getImagesJSONStruct) types.Image { <add> return types.Image{ <add> RepoTags: data.RepoTags, <add> ID: data.Id, <add> Created: int(data.Created), <add> Size: int(data.Size), <add> VirtualSize: int(data.VirtualSize), <add> } <ide> } <ide> <ide> type getImagesJSONStruct struct { <ide><path>daemon/network_settings.go <ide> package daemon <ide> <ide> import ( <del> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/nat" <ide> ) <ide> <ide> type NetworkSettings struct { <ide> PortMapping map[string]PortMapping // Deprecated <ide> Ports nat.PortMap <ide> } <del> <del>func (settings *NetworkSettings) PortMappingAPI() *engine.Table { <del> var outs = engine.NewTable("", 0) <del> for port, bindings := range settings.Ports { <del> p, _ := nat.ParsePort(port.Port()) <del> if len(bindings) == 0 { <del> out := &engine.Env{} <del> out.SetInt("PrivatePort", p) <del> out.Set("Type", port.Proto()) <del> outs.Add(out) <del> continue <del> } <del> for _, binding := range bindings { <del> out := &engine.Env{} <del> h, _ := nat.ParsePort(binding.HostPort) <del> out.SetInt("PrivatePort", p) <del> out.SetInt("PublicPort", h) <del> out.Set("Type", port.Proto()) <del> out.Set("IP", binding.HostIp) <del> outs.Add(out) <del> } <del> } <del> return outs <del>} <ide><path>integration/api_test.go <ide> import ( <ide> <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/api/server" <add> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/runconfig" <ide> func TestDeleteImages(t *testing.T) { <ide> t.Fatalf("%d OK expected, received %d\n", http.StatusOK, r.Code) <ide> } <ide> <del> outs := engine.NewTable("Created", 0) <del> if _, err := outs.ReadListFrom(r2.Body.Bytes()); err != nil { <add> delImages := []types.ImageDelete{} <add> err = json.Unmarshal(r2.Body.Bytes(), &delImages) <add> if err != nil { <ide> t.Fatal(err) <ide> } <del> if len(outs.Data) != 1 { <del> t.Fatalf("Expected %d event (untagged), got %d", 1, len(outs.Data)) <add> <add> if len(delImages) != 1 { <add> t.Fatalf("Expected %d event (untagged), got %d", 1, len(delImages)) <ide> } <ide> images = getImages(eng, t, false, "") <ide> <ide><path>integration/utils_test.go <ide> func fakeTar() (io.ReadCloser, error) { <ide> return ioutil.NopCloser(buf), nil <ide> } <ide> <del>func getAllImages(eng *engine.Engine, t *testing.T) *engine.Table { <del> return getImages(eng, t, true, "") <del>} <del> <ide> func getImages(eng *engine.Engine, t *testing.T, all bool, filter string) *engine.Table { <ide> job := eng.Job("images") <ide> job.SetenvBool("all", all)
4
Python
Python
fix rare failures in chord error test
8304c0fca3c3ee3cfb295d6655eca8ad00fb28f6
<ide><path>t/integration/test_canvas.py <ide> def assert_parentids_chord(self, res, expected_root_id): <ide> def test_chord_on_error(self, manager): <ide> from celery import states <ide> from .tasks import ExpectedException <del> import time <ide> <ide> if not manager.app.conf.result_backend.startswith('redis'): <ide> raise pytest.skip('Requires redis result backend.') <ide> def test_chord_on_error(self, manager): <ide> res.get(propagate=True) <ide> <ide> # Got to wait for children to populate. <del> while not res.children: <del> time.sleep(0.1) <add> check = ( <add> lambda: res.children, <add> lambda: res.children[0].children, <add> lambda: res.children[0].children[0].result, <add> ) <add> while not all(f() for f in check): <add> pass <ide> <ide> # Extract the results of the successful tasks from the chord. <ide> #
1
Javascript
Javascript
handle modifications to fs.open
c75f71dd721d04e03204ffcc290bb3a370275cce
<ide><path>lib/fs.js <ide> var WriteStream = fs.WriteStream = function(path, options) { <ide> this._queue = []; <ide> <ide> if (this.fd === null) { <del> this._queue.push([fs.open, this.path, this.flags, this.mode, undefined]); <add> this._open = fs.open; <add> this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); <ide> this.flush(); <ide> } <ide> }; <ide> WriteStream.prototype.flush = function() { <ide> cb(null, arguments[1]); <ide> } <ide> <del> } else if (method === fs.open) { <add> } else if (method === self._open) { <ide> // save reference for file pointer <ide> self.fd = arguments[1]; <ide> self.emit('open', self.fd); <ide> WriteStream.prototype.flush = function() { <ide> }); <ide> <ide> // Inject the file pointer <del> if (method !== fs.open) { <add> if (method !== self._open) { <ide> args.unshift(this.fd); <ide> } <ide> <ide><path>test/simple/test-fs-write-stream-change-open.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>var path = require('path'), <add> fs = require('fs'); <add> <add>var file = path.join(common.tmpDir, 'write.txt'); <add> <add>var stream = fs.WriteStream(file), <add> _fs_close = fs.close, <add> _fs_open = fs.open; <add> <add>// change the fs.open with an identical function after the WriteStream <add>// has pushed it onto its internal action queue, but before it's <add>// returned. This simulates AOP-style extension of the fs lib. <add>fs.open = function() { <add> return _fs_open.apply(fs, arguments); <add>}; <add> <add>fs.close = function(fd) { <add> assert.ok(fd, 'fs.close must not be called with an undefined fd.'); <add> fs.close = _fs_close; <add> fs.open = _fs_open; <add>} <add> <add>stream.write('foo'); <add>stream.end(); <add> <add>process.on('exit', function() { <add> assert.equal(fs.open, _fs_open); <add>});
2
Text
Text
add thefourtheye as a collaborator
c019d9a2391be5d7257029ec01794f0bdf5753d6
<ide><path>README.md <ide> information about the governance of the io.js project, see <ide> * **Domenic Denicola** &lt;d@domenic.me&gt; ([@domenic](https://github.com/domenic)) <ide> * **Rich Trott** &lt;rtrott@gmail.com&gt; ([@Trott](https://github.com/Trott)) <ide> * **Сковорода Никита Андреевич** &lt;chalkerx@gmail.com&gt; ([@ChALkeR](https://github.com/ChALkeR)) <add>* **Sakthipriyan Vairamani** &lt;thechargingvolcano@gmail.com&gt; ([@thefourtheye](https://github.com/thefourtheye)) <ide> <ide> Collaborators & TSC members follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in <ide> maintaining the io.js project.
1
Javascript
Javascript
throw typeerror if kill pid not a number
832ec1cd507ed344badd2ed97d3da92975650a95
<ide><path>src/node.js <ide> process.kill = function(pid, sig) { <ide> var err; <ide> <add> if (typeof pid !== 'number' || !isFinite(pid)) { <add> throw new TypeError('pid must be a number'); <add> } <add> <ide> // preserve null signal <ide> if (0 === sig) { <ide> err = process._kill(pid, 0); <ide><path>test/simple/test-process-kill-pid.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>var pass; <add>var wait = setInterval(function(){}, 1000); <add> <add>process.on('exit', function(code) { <add> if (code === 0) { <add> assert.ok(pass); <add> } <add>}); <add> <add>// test variants of pid <add>// <add>// null: TypeError <add>// undefined: TypeError <add>// <add>// 'SIGTERM': TypeError <add>// <add>// String(process.pid): TypeError <add>// <add>// Nan, Infinity, -Infinity: TypeError <add>// <add>// 0, process.pid: ourself <add> <add>assert.throws(function() { process.kill('SIGTERM'); }, TypeError); <add>assert.throws(function() { process.kill(String(process.pid)); }, TypeError); <add>assert.throws(function() { process.kill(null); }, TypeError); <add>assert.throws(function() { process.kill(undefined); }, TypeError); <add>assert.throws(function() { process.kill(+'not a number'); }, TypeError); <add>assert.throws(function() { process.kill(1/0); }, TypeError); <add>assert.throws(function() { process.kill(-1/0); }, TypeError); <add> <add>process.once('SIGHUP', function() { <add> process.once('SIGHUP', function() { <add> pass = true; <add> clearInterval(wait); <add> }); <add> process.kill(process.pid, 'SIGHUP'); <add>}); <add> <add>process.kill(0, 'SIGHUP');
2
Javascript
Javascript
improve validation performance
a54972c195f708afbd985d981b804834817da92b
<ide><path>lib/_http_common.js <ide> exports.httpSocketSetup = httpSocketSetup; <ide> * so take care when making changes to the implementation so that the source <ide> * code size does not exceed v8's default max_inlined_source_size setting. <ide> **/ <del>function isValidTokenChar(ch) { <del> if (ch >= 94 && ch <= 122) <del> return true; <del> if (ch >= 65 && ch <= 90) <del> return true; <del> if (ch === 45) <del> return true; <del> if (ch >= 48 && ch <= 57) <del> return true; <del> if (ch === 34 || ch === 40 || ch === 41 || ch === 44) <add>var validTokens = [ <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 <add> 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 <add> 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, // 112 - 127 <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128 ... <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // ... 255 <add>]; <add>function checkIsHttpToken(val) { <add> if (typeof val !== 'string' || val.length === 0) <add> return false; <add> if (!validTokens[val.charCodeAt(0)]) <ide> return false; <del> if (ch >= 33 && ch <= 46) <add> if (val.length < 2) <ide> return true; <del> if (ch === 124 || ch === 126) <add> if (!validTokens[val.charCodeAt(1)]) <add> return false; <add> if (val.length < 3) <ide> return true; <del> return false; <del>} <del>function checkIsHttpToken(val) { <del> if (typeof val !== 'string' || val.length === 0) <add> if (!validTokens[val.charCodeAt(2)]) <ide> return false; <del> if (!isValidTokenChar(val.charCodeAt(0))) <add> if (val.length < 4) <add> return true; <add> if (!validTokens[val.charCodeAt(3)]) <ide> return false; <del> const len = val.length; <del> if (len > 1) { <del> if (!isValidTokenChar(val.charCodeAt(1))) <add> for (var i = 4; i < val.length; ++i) { <add> if (!validTokens[val.charCodeAt(i)]) <ide> return false; <del> if (len > 2) { <del> if (!isValidTokenChar(val.charCodeAt(2))) <del> return false; <del> if (len > 3) { <del> if (!isValidTokenChar(val.charCodeAt(3))) <del> return false; <del> for (var i = 4; i < len; i++) { <del> if (!isValidTokenChar(val.charCodeAt(i))) <del> return false; <del> } <del> } <del> } <ide> } <ide> return true; <ide> } <ide> exports._checkIsHttpToken = checkIsHttpToken; <ide> * so take care when making changes to the implementation so that the source <ide> * code size does not exceed v8's default max_inlined_source_size setting. <ide> **/ <add>var validHdrChars = [ <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, // 0 - 15 <add> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 32 - 47 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 48 - 63 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 95 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 112 - 127 <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 128 ... <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, <add> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // ... 255 <add>]; <ide> function checkInvalidHeaderChar(val) { <ide> val += ''; <ide> if (val.length < 1) <ide> return false; <del> var c = val.charCodeAt(0); <del> if ((c <= 31 && c !== 9) || c > 255 || c === 127) <add> if (!validHdrChars[val.charCodeAt(0)]) <ide> return true; <ide> if (val.length < 2) <ide> return false; <del> c = val.charCodeAt(1); <del> if ((c <= 31 && c !== 9) || c > 255 || c === 127) <add> if (!validHdrChars[val.charCodeAt(1)]) <ide> return true; <ide> if (val.length < 3) <ide> return false; <del> c = val.charCodeAt(2); <del> if ((c <= 31 && c !== 9) || c > 255 || c === 127) <add> if (!validHdrChars[val.charCodeAt(2)]) <add> return true; <add> if (val.length < 4) <add> return false; <add> if (!validHdrChars[val.charCodeAt(3)]) <ide> return true; <del> for (var i = 3; i < val.length; ++i) { <del> c = val.charCodeAt(i); <del> if ((c <= 31 && c !== 9) || c > 255 || c === 127) <add> for (var i = 4; i < val.length; ++i) { <add> if (!validHdrChars[val.charCodeAt(i)]) <ide> return true; <ide> } <ide> return false;
1
Javascript
Javascript
add support for events
08d09ecbaa07564bf3cf6a62e0be4c41b355d23b
<ide><path>docs/spec/ngdocSpec.js <ide> describe('ngdoc', function(){ <ide> var methodB = new Doc({name: 'methodB', methodOf: 'angular.service.abc'}); <ide> var propA = new Doc({name: 'propA', propertyOf: 'angular.service.abc'}); <ide> var propB = new Doc({name: 'propB', propertyOf: 'angular.service.abc'}); <del> var docs = [methodB, methodA, propB, propA, parent]; // keep wrong order; <add> var eventA = new Doc({name: 'eventA', eventOf: 'angular.service.abc'}); <add> var eventB = new Doc({name: 'eventB', eventOf: 'angular.service.abc'}); <add> var docs = [methodB, methodA, eventB, eventA, propA, propB, parent]; // keep wrong order; <ide> ngdoc.merge(docs); <ide> expect(docs.length).toEqual(1); <ide> expect(docs[0].id).toEqual('angular.service.abc'); <ide> expect(docs[0].methods).toEqual([methodA, methodB]); <add> expect(docs[0].events).toEqual([eventA, eventB]); <ide> expect(docs[0].properties).toEqual([propA, propB]); <ide> }); <ide> <ide><path>docs/src/ngdoc.js <ide> function Doc(text, file, line) { <ide> this.param = this.param || []; <ide> this.properties = this.properties || []; <ide> this.methods = this.methods || []; <add> this.events = this.events || []; <ide> this.links = this.links || []; <ide> } <ide> Doc.METADATA_IGNORE = (function(){ <ide> Doc.prototype = { <ide> description: self.markdown(text.replace(match[0], match[4])) <ide> }; <ide> self.properties.push(property); <add> } else if(atName == 'eventType') { <add> var match = text.match(/^([^\s]*)\s+on\s+([\S\s]*)/); <add> self.type = match[1]; <add> self.source = match[2]; <ide> } else { <ide> self[atName] = text; <ide> } <ide> Doc.prototype = { <ide> dom.h('Example', property.example, dom.html); <ide> }); <ide> }); <add> dom.h('Events', this.events, function(event){ <add> var signature = (event.param || []).map(property('name')); <add> dom.h(event.type + ' ' + <add> event.shortName + '(' + signature.join(', ') + ') on ' + <add> event.source, event, function(){ <add> dom.html(event.description); <add> event.html_usage_parameters(dom); <add> self.html_usage_this(dom); <add> <add> dom.h('Example', event.example, dom.html); <add> }); <add> }); <ide> }, <ide> <ide> parameters: function(dom, separator, skipFirst, prefix) { <ide> function merge(docs){ <ide> }); <ide> <ide> // merge into parents <del> if (findParent(doc, 'method') || findParent(doc, 'property')) { <add> if (findParent(doc, 'method') || findParent(doc, 'property') || findParent(doc, 'event')) { <ide> docs.splice(i, 1); <ide> } else { <ide> i++;
2
Javascript
Javascript
expand error message
b07aa9264e6fc7ad0fb4c4b5e15e6e5f9a604706
<ide><path>test/parallel/test-cluster-worker-isdead.js <ide> const assert = require('assert'); <ide> <ide> if (cluster.isMaster) { <ide> const worker = cluster.fork(); <del> assert.ok( <del> !worker.isDead(), <del> 'isDead() should return false right after the worker has been created.'); <add> let workerDead = worker.isDead(); <add> assert.ok(!workerDead, <add> `isDead() returned ${workerDead}. isDead() should return ` + <add> 'false right after the worker has been created.'); <ide> <ide> worker.on('exit', function() { <del> assert.ok(worker.isDead(), <del> 'After an event has been emitted, isDead should return true'); <add> workerDead = worker.isDead(); <add> assert.ok(workerDead, <add> `isDead() returned ${workerDead}. After an event has been ` + <add> 'emitted, isDead should return true'); <ide> }); <ide> <ide> worker.on('message', function(msg) { <ide> if (cluster.isMaster) { <ide> }); <ide> <ide> } else if (cluster.isWorker) { <del> assert.ok(!cluster.worker.isDead(), <del> 'isDead() should return false when called from within a worker'); <add> const workerDead = cluster.worker.isDead(); <add> assert.ok(!workerDead, <add> `isDead() returned ${workerDead}. isDead() should return ` + <add> 'false when called from within a worker'); <ide> process.send('readyToDie'); <ide> }
1
PHP
PHP
compile more files
b6d1e7ecb0ad5375a7d8b0e99ce4ead16af8afc6
<ide><path>src/Illuminate/Foundation/Console/Optimize/config.php <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Cookie/QueueingFactory.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Encryption/Encrypter.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Queue/QueueableEntity.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/HttpKernel.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Routing/Registrar.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Routing/ResponseFactory.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Routing/UrlGenerator.php', <ide> $basePath.'/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/TerminableInterface.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Application.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/EnvironmentDetector.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/ConfigureLogging.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterFacades.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterProviders.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/BootProviders.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/DetectEnvironment.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Http/Request.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Http/FrameGuard.php', <ide> $basePath.'/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Request.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/ServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/AggregateServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/RoutingServiceProvider.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/ControllerServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Events/EventServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Validation/ValidationServiceProvider.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FoundationServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Providers/EventServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FormRequestServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/RouteServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Pagination/PaginationServiceProvider.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Pagination/Paginator.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Pagination/AbstractPaginator.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Pagination/Paginator.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/Traits/MacroableTrait.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/Arr.php', <ide> $basePath.'/vendor/symfony/routing/Symfony/Component/Routing/Route.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/Controller.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/ControllerInspector.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/Stack.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/Matching/ValidatorInterface.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/Matching/HostValidator.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/Matching/MethodValidator.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Database/ConnectionResolverInterface.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Session/SessionInterface.php', <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Session/Middleware/Reader.php', <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Session/Middleware/Writer.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Session/Middleware/ReadSession.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Session/Middleware/WriteSession.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Session/Middleware/MiddlewareTrait.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Session/Store.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Session/SessionManager.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/Manager.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/Collection.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Cookie/CookieJar.php', <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/Guard.php', <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/Queue.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToRequest.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/Facades/Log.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Log/LogServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Log/Writer.php', <add> $basePath.'/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php', <ide> $basePath.'/vendor/monolog/monolog/src/Monolog/Logger.php', <ide> $basePath.'/vendor/psr/log/Psr/Log/LoggerInterface.php', <ide> $basePath.'/vendor/monolog/monolog/src/Monolog/Handler/AbstractHandler.php',
1
Javascript
Javascript
convert `namespacesassert` to es6 class
2f57dafa4934fd9097b262f7f986de84584deac3
<ide><path>packages/internal-test-helpers/lib/ember-dev/namespaces.js <ide> import { run } from '@ember/runloop'; <ide> import { NAMESPACES, NAMESPACES_BY_ID } from '@ember/-internals/metal'; <ide> <del>function NamespacesAssert(env) { <del> this.env = env; <del>} <add>export default class NamespacesAssert { <add> constructor(env) { <add> this.env = env; <add> } <add> <add> reset() {} <ide> <del>NamespacesAssert.prototype = { <del> reset: function() {}, <del> inject: function() {}, <del> assert: function() { <add> inject() {} <add> <add> assert() { <ide> let { assert } = QUnit.config.current; <ide> <ide> if (NAMESPACES.length > 0) { <ide> NamespacesAssert.prototype = { <ide> delete NAMESPACES_BY_ID[keys[i]]; <ide> } <ide> } <del> }, <del> restore: function() {}, <del>}; <add> } <ide> <del>export default NamespacesAssert; <add> restore() {} <add>}
1
Go
Go
add image graph output (dot/graphviz)
f4de9d919d7ad6cf677c8157eabf82cf65aa4396
<ide><path>commands.go <ide> func (srv *Server) CmdImages(stdin io.ReadCloser, stdout io.Writer, args ...stri <ide> //limit := cmd.Int("l", 0, "Only show the N most recent versions of each image") <ide> quiet := cmd.Bool("q", false, "only show numeric IDs") <ide> flAll := cmd.Bool("a", false, "show all images") <add> flViz := cmd.Bool("viz", false, "output graph in graphviz format") <ide> if err := cmd.Parse(args); err != nil { <ide> return nil <ide> } <del> if cmd.NArg() > 1 { <del> cmd.Usage() <del> return nil <del> } <del> var nameFilter string <del> if cmd.NArg() == 1 { <del> nameFilter = cmd.Arg(0) <del> } <del> w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0) <del> if !*quiet { <del> fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED") <del> } <del> var allImages map[string]*Image <del> var err error <del> if *flAll { <del> allImages, err = srv.runtime.graph.Map() <del> } else { <del> allImages, err = srv.runtime.graph.Heads() <del> } <del> if err != nil { <del> return err <del> } <del> for name, repository := range srv.runtime.repositories.Repositories { <del> if nameFilter != "" && name != nameFilter { <del> continue <add> <add> if *flViz { <add> images, _ := srv.runtime.graph.All() <add> if images == nil { <add> return nil <ide> } <del> for tag, id := range repository { <del> image, err := srv.runtime.graph.Get(id) <add> <add> fmt.Fprintf(stdout, "digraph G {\n") <add> <add> var parentImage *Image <add> var err error <add> for _, image := range images { <add> parentImage, err = image.GetParent() <ide> if err != nil { <del> log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err) <add> fmt.Errorf("Error while getting parent image: %v", err) <add> return nil <add> } <add> if parentImage != nil { <add> fmt.Fprintf(stdout, " \"%s\" -> \"%s\"\n", parentImage.ShortId(), image.ShortId()) <add> } else { <add> fmt.Fprintf(stdout, " base -> \"%s\" [style=invis]\n", image.ShortId()) <add> } <add> } <add> <add> reporefs := make(map[string][]string) <add> <add> for name, repository := range srv.runtime.repositories.Repositories { <add> for tag, id := range repository { <add> reporefs[TruncateId(id)] = append(reporefs[TruncateId(id)], fmt.Sprintf("%s:%s", name, tag)) <add> } <add> } <add> <add> for id, repos := range reporefs { <add> fmt.Fprintf(stdout, " \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n", id, id, strings.Join(repos, "\\n")) <add> } <add> <add> fmt.Fprintf(stdout, " base [style=invisible]\n") <add> fmt.Fprintf(stdout, "}\n") <add> } else { <add> if cmd.NArg() > 1 { <add> cmd.Usage() <add> return nil <add> } <add> var nameFilter string <add> if cmd.NArg() == 1 { <add> nameFilter = cmd.Arg(0) <add> } <add> w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0) <add> if !*quiet { <add> fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED") <add> } <add> var allImages map[string]*Image <add> var err error <add> if *flAll { <add> allImages, err = srv.runtime.graph.Map() <add> } else { <add> allImages, err = srv.runtime.graph.Heads() <add> } <add> if err != nil { <add> return err <add> } <add> for name, repository := range srv.runtime.repositories.Repositories { <add> if nameFilter != "" && name != nameFilter { <ide> continue <ide> } <del> delete(allImages, id) <del> if !*quiet { <del> for idx, field := range []string{ <del> /* REPOSITORY */ name, <del> /* TAG */ tag, <del> /* ID */ TruncateId(id), <del> /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago", <del> } { <del> if idx == 0 { <del> w.Write([]byte(field)) <del> } else { <del> w.Write([]byte("\t" + field)) <add> for tag, id := range repository { <add> image, err := srv.runtime.graph.Get(id) <add> if err != nil { <add> log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err) <add> continue <add> } <add> delete(allImages, id) <add> if !*quiet { <add> for idx, field := range []string{ <add> /* REPOSITORY */ name, <add> /* TAG */ tag, <add> /* ID */ TruncateId(id), <add> /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago", <add> } { <add> if idx == 0 { <add> w.Write([]byte(field)) <add> } else { <add> w.Write([]byte("\t" + field)) <add> } <ide> } <add> w.Write([]byte{'\n'}) <add> } else { <add> stdout.Write([]byte(image.ShortId() + "\n")) <ide> } <del> w.Write([]byte{'\n'}) <del> } else { <del> stdout.Write([]byte(image.ShortId() + "\n")) <ide> } <ide> } <del> } <del> // Display images which aren't part of a <del> if nameFilter == "" { <del> for id, image := range allImages { <del> if !*quiet { <del> for idx, field := range []string{ <del> /* REPOSITORY */ "<none>", <del> /* TAG */ "<none>", <del> /* ID */ TruncateId(id), <del> /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago", <del> } { <del> if idx == 0 { <del> w.Write([]byte(field)) <del> } else { <del> w.Write([]byte("\t" + field)) <add> // Display images which aren't part of a <add> if nameFilter == "" { <add> for id, image := range allImages { <add> if !*quiet { <add> for idx, field := range []string{ <add> /* REPOSITORY */ "<none>", <add> /* TAG */ "<none>", <add> /* ID */ TruncateId(id), <add> /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago", <add> } { <add> if idx == 0 { <add> w.Write([]byte(field)) <add> } else { <add> w.Write([]byte("\t" + field)) <add> } <ide> } <add> w.Write([]byte{'\n'}) <add> } else { <add> stdout.Write([]byte(image.ShortId() + "\n")) <ide> } <del> w.Write([]byte{'\n'}) <del> } else { <del> stdout.Write([]byte(image.ShortId() + "\n")) <ide> } <ide> } <del> } <del> if !*quiet { <del> w.Flush() <add> if !*quiet { <add> w.Flush() <add> } <ide> } <ide> return nil <ide> }
1
Java
Java
relax servletcontext check for resource handling
436486b8a1cab5a37a415c7560ee6dea8014bf9b
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <del>import javax.servlet.ServletContext; <ide> import javax.servlet.ServletException; <ide> import javax.servlet.ServletResponse; <ide> import javax.servlet.http.HttpServletRequest; <ide> import org.apache.commons.logging.LogFactory; <ide> <ide> import org.springframework.beans.factory.InitializingBean; <add>import org.springframework.beans.factory.SmartInitializingSingleton; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.core.io.support.ResourceRegion; <ide> import org.springframework.http.HttpHeaders; <ide> * @since 3.0.4 <ide> */ <ide> public class ResourceHttpRequestHandler extends WebContentGenerator <del> implements HttpRequestHandler, InitializingBean, CorsConfigurationSource { <add> implements HttpRequestHandler, InitializingBean, SmartInitializingSingleton, CorsConfigurationSource { <ide> <ide> // Servlet 3.1 setContentLengthLong(long) available? <ide> private static final boolean contentLengthLongAvailable = <ide> public class ResourceHttpRequestHandler extends WebContentGenerator <ide> <ide> private ContentNegotiationManager contentNegotiationManager; <ide> <del> private ServletPathExtensionContentNegotiationStrategy pathExtensionStrategy; <del> <del> private ServletContext servletContext; <add> private PathExtensionContentNegotiationStrategy pathExtensionStrategy; <ide> <ide> private CorsConfiguration corsConfiguration; <ide> <ide> public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { <ide> return this.corsConfiguration; <ide> } <ide> <del> @Override <del> protected void initServletContext(ServletContext servletContext) { <del> this.servletContext = servletContext; <del> } <del> <ide> <ide> @Override <ide> public void afterPropertiesSet() throws Exception { <ide> public void afterPropertiesSet() throws Exception { <ide> if (this.resourceRegionHttpMessageConverter == null) { <ide> this.resourceRegionHttpMessageConverter = new ResourceRegionHttpMessageConverter(); <ide> } <del> this.pathExtensionStrategy = initPathExtensionStrategy(); <ide> } <ide> <ide> /** <ide> protected void initAllowedLocations() { <ide> } <ide> } <ide> <del> protected ServletPathExtensionContentNegotiationStrategy initPathExtensionStrategy() { <add> @Override <add> public void afterSingletonsInstantiated() { <add> this.pathExtensionStrategy = initContentNegotiationStrategy(); <add> } <add> <add> protected PathExtensionContentNegotiationStrategy initContentNegotiationStrategy() { <ide> Map<String, MediaType> mediaTypes = null; <ide> if (getContentNegotiationManager() != null) { <ide> PathExtensionContentNegotiationStrategy strategy = <ide> protected ServletPathExtensionContentNegotiationStrategy initPathExtensionStrate <ide> mediaTypes = new HashMap<>(strategy.getMediaTypes()); <ide> } <ide> } <del> return new ServletPathExtensionContentNegotiationStrategy(this.servletContext, mediaTypes); <add> return (getServletContext() != null) ? <add> new ServletPathExtensionContentNegotiationStrategy(getServletContext(), mediaTypes) : <add> new PathExtensionContentNegotiationStrategy(mediaTypes); <ide> } <ide> <ide> <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java <ide> public void mapPathToLocation() throws Exception { <ide> request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/testStylesheet.css"); <ide> <ide> ResourceHttpRequestHandler handler = getHandler("/resources/**"); <add> handler.afterPropertiesSet(); <add> handler.afterSingletonsInstantiated(); <ide> handler.handleRequest(request, this.response); <ide> <ide> assertEquals("test stylesheet content", this.response.getContentAsString()); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java <ide> public void setUp() throws Exception { <ide> this.handler.setCacheSeconds(3600); <ide> this.handler.setServletContext(new TestServletContext()); <ide> this.handler.afterPropertiesSet(); <add> this.handler.afterSingletonsInstantiated(); <ide> <ide> this.request = new MockHttpServletRequest("GET", ""); <ide> this.response = new MockHttpServletResponse(); <ide> public void getVersionedResource() throws Exception { <ide> .addFixedVersionStrategy("versionString", "/**"); <ide> this.handler.setResourceResolvers(Arrays.asList(versionResolver, new PathResourceResolver())); <ide> this.handler.afterPropertiesSet(); <add> this.handler.afterSingletonsInstantiated(); <ide> <ide> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "versionString/foo.css"); <ide> this.handler.handleRequest(this.request, this.response); <ide> public void getResourceWithRegisteredMediaType() throws Exception { <ide> handler.setLocations(paths); <ide> handler.setContentNegotiationManager(manager); <ide> handler.afterPropertiesSet(); <add> handler.afterSingletonsInstantiated(); <ide> <ide> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); <ide> handler.handleRequest(this.request, this.response); <ide> public void getMediaTypeWithFavorPathExtensionOff() throws Exception { <ide> handler.setLocations(paths); <ide> handler.setContentNegotiationManager(manager); <ide> handler.afterPropertiesSet(); <add> handler.afterSingletonsInstantiated(); <ide> <ide> this.request.addHeader("Accept", "application/json,text/plain,*/*"); <ide> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html"); <ide> public String getVirtualServerName() { <ide> handler.setServletContext(servletContext); <ide> handler.setLocations(paths); <ide> handler.afterPropertiesSet(); <add> handler.afterSingletonsInstantiated(); <ide> <ide> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); <ide> handler.handleRequest(this.request, this.response); <ide> public void initAllowedLocationsWithExplicitConfiguration() throws Exception { <ide> handler.setServletContext(new MockServletContext()); <ide> handler.setLocations(Arrays.asList(location1, location2)); <ide> handler.afterPropertiesSet(); <add> handler.afterSingletonsInstantiated(); <ide> <ide> Resource[] locations = pathResolver.getAllowedLocations(); <ide> assertEquals(1, locations.length);
3
Ruby
Ruby
fix a couple of formatting issues [ci skip]
f1cc45e56a4fc6e80bb4be4434dbf49d41adfd83
<ide><path>actionpack/lib/action_view/helpers/text_helper.rb <ide> def truncate(text, options = {}) <ide> <ide> # Highlights one or more +phrases+ everywhere in +text+ by inserting it into <ide> # a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt> <del> # as a single-quoted string with \1 where the phrase is to be inserted (defaults to <add> # as a single-quoted string with <tt>\1</tt> where the phrase is to be inserted (defaults to <ide> # '<mark>\1</mark>') <ide> # <ide> # ==== Examples <ide> def truncate(text, options = {}) <ide> # <ide> # You can still use <tt>highlight</tt> with the old API that accepts the <ide> # +highlighter+ as its optional third parameter: <del> # highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') # => You searched for: <a href="search?q=rails">rails</a> <add> # <add> # highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') <add> # # => You searched for: <a href="search?q=rails">rails</a> <ide> def highlight(text, phrases, *args) <ide> options = args.extract_options! <ide> unless args.empty?
1
PHP
PHP
apply fixes from styleci
4f5c5cc1ef773d8bac72fc9bd2ae178ce3991f9f
<ide><path>src/Illuminate/Foundation/Console/ComponentMakeCommand.php <ide> public function handle() <ide> <ide> return; <ide> } <del> <add> <ide> if (parent::handle() === false && ! $this->option('force')) { <ide> return false; <ide> } <ide> public function handle() <ide> /** <ide> * Write the view for the component. <ide> * <del> * @param callable|null $onSuccess <add> * @param callable|null $onSuccess <ide> * @return void <ide> */ <ide> protected function writeView($onSuccess = null)
1
Javascript
Javascript
add support for chrome 75
0f1732bdcc5bc72b808eb9cbeab3305819ab5a56
<ide><path>examples/js/vr/HelioWebXRPolyfill.js <ide> <ide> if ( /(Helio)/g.test( navigator.userAgent ) && "xr" in navigator ) { <ide> <del> console.log( "Helio WebXR Polyfill (Lumin 0.96.0)" ); <add> console.log( "Helio WebXR Polyfill (Lumin 0.97.0)" ); <add> const isHelio96 = navigator.userAgent.includes("Chrome/73"); <ide> <ide> // WebXRManager - XR.supportSession() Polyfill - WebVR.js line 147 <ide> <ide> if ( /(Helio)/g.test( navigator.userAgent ) && "xr" in navigator ) { <ide> navigator.xr.requestSession = function ( sessionType ) { <ide> <ide> return new Promise( function ( resolve, reject ) { <del> <del> tempRequestSession( { <add> const sessionType = (isHelio96 ? { <ide> mode: 'immersive-ar' // Force using immersive-ar <del> } ) <add> } : 'immersive-ar'); <add> <add> tempRequestSession( sessionType ) <ide> .then( function ( session ) { <ide> <ide> // WebXRManager - xrFrame.getPose() Polyfill - line 279 <ide> if ( /(Helio)/g.test( navigator.userAgent ) && "xr" in navigator ) { <ide> <ide> // WebXRManager - xrFrame.getPose() Polyfill - line 259 <ide> <add> const tempGetPose = frame.getPose.bind( frame ); <add> <ide> frame.getPose = function ( targetRaySpace, referenceSpace ) { <ide> <del> const inputPose = frame.getInputPose( <del> targetRaySpace, <del> referenceSpace <del> ); <add> if (isHelio96) { <ide> <del> inputPose.transform = { <del> matrix: inputPose.targetRay.transformMatrix <del> }; <add> const inputPose = frame.getInputPose( <add> targetRaySpace, <add> referenceSpace <add> ); <ide> <del> return inputPose; <add> inputPose.transform = { <add> matrix: inputPose.targetRay.transformMatrix <add> }; <add> <add> return inputPose; <add> <add> } else { <add> return tempGetPose(targetRaySpace.gripSpace, referenceSpace); <add> } <ide> <ide> }; <ide> <ide> if ( /(Helio)/g.test( navigator.userAgent ) && "xr" in navigator ) { <ide> <ide> // WebXRManager - xrSession.updateRenderState() Polyfill Line 129 <ide> <del> session.updateRenderState = function ( { baseLayer } ) { <add> if (isHelio96) { <add> <add> session.updateRenderState = function ( { baseLayer } ) { <ide> <del> session.baseLayer = baseLayer; <add> session.baseLayer = baseLayer; <ide> <del> // WebXRManager - xrSession.renderState.baseLayer Polyfill Line 219 <add> // WebXRManager - xrSession.renderState.baseLayer Polyfill Line 219 <add> <add> session.renderState = { <add> baseLayer: baseLayer <add> }; <ide> <del> session.renderState = { <del> baseLayer: baseLayer <ide> }; <ide> <del> }; <add> } <ide> <ide> // WebXRManager - xrSession.requestReferenceSpace() Polyfill Line 130 <ide>
1
PHP
PHP
list as json
2d14798f6115d5a4f7ee50359c43e4b8c6180d0f
<ide><path>src/Illuminate/Foundation/Console/RouteListCommand.php <ide> protected function pluckColumns(array $routes) <ide> */ <ide> protected function displayRoutes(array $routes) <ide> { <add> if ($this->option('json')) { <add> $this->line(json_encode(array_values($routes))); <add> <add> return; <add> } <add> <ide> $this->table($this->getHeaders(), $routes); <ide> } <ide> <ide> protected function getOptions() <ide> ['path', null, InputOption::VALUE_OPTIONAL, 'Filter the routes by path'], <ide> ['reverse', 'r', InputOption::VALUE_NONE, 'Reverse the ordering of the routes'], <ide> ['sort', null, InputOption::VALUE_OPTIONAL, 'The column (domain, method, uri, name, action, middleware) to sort by', 'uri'], <add> ['json', null, InputOption::VALUE_NONE, 'Output the route list as JSON'], <ide> ]; <ide> } <ide> }
1
Javascript
Javascript
use custom elements on text editor element spec
fc5286fdcac757b9c6a20014039898bcfc94bd91
<ide><path>spec/text-editor-element-spec.js <ide> describe('TextEditorElement', () => { <ide> }); <ide> <ide> describe('when focused while a parent node is being attached to the DOM', () => { <del> class ElementThatFocusesChild extends HTMLDivElement { <del> attachedCallback() { <add> class ElementThatFocusesChild extends HTMLElement { <add> connectedCallback() { <ide> this.firstChild.focus(); <ide> } <ide> } <ide> <del> document.registerElement('element-that-focuses-child', { <del> prototype: ElementThatFocusesChild.prototype <del> }); <add> window.customElements.define( <add> 'element-that-focuses-child', <add> ElementThatFocusesChild <add> ); <ide> <ide> it('proxies the focus event to the hidden input', () => { <ide> const element = buildTextEditorElement();
1
Python
Python
remove a duplicate test. closes gh-8447
bed40e207a26064bf83568efaeeec8079a99dc74
<ide><path>numpy/random/tests/test_random.py <ide> def test_logistic(self): <ide> [-0.21682183359214885, 2.63373365386060332]]) <ide> assert_array_almost_equal(actual, desired, decimal=15) <ide> <del> def test_laplace_0(self): <del> assert_(np.random.laplace(scale=0) in [0, 1]) <del> assert_raises(ValueError, np.random.laplace, scale=-0.) <del> <ide> def test_lognormal(self): <ide> np.random.seed(self.seed) <ide> actual = np.random.lognormal(mean=.123456789, sigma=2.0, size=(3, 2))
1
PHP
PHP
remove html from default formatting in messagebag
77024b6d23eceb58f47e9a2039ed33de516224f5
<ide><path>src/Illuminate/Support/MessageBag.php <ide> class MessageBag implements ArrayableInterface, Countable, JsonableInterface, Me <ide> * <ide> * @var string <ide> */ <del> protected $format = '<span class="help-inline">:message</span>'; <add> protected $format = ':message'; <ide> <ide> /** <ide> * Create a new message bag instance.
1
Text
Text
add the missing module name
1ca1583513372422bd301fc0fef7bbb5a760fd87
<ide><path>docs/api-guide/serializers.md <ide> A mapping of Django model fields to REST framework serializer fields. You can ov <ide> <ide> This property should be the serializer field class, that is used for relational fields by default. <ide> <del>For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`. <add>For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`. <ide> <ide> For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`. <ide>
1
Python
Python
fix broken tests after url restructure pr
f91f1ca9773fce258f02a6bc3c11d16ac029467b
<ide><path>airflow/utils/helpers.py <ide> Tuple, <ide> TypeVar, <ide> ) <del>from urllib import parse <ide> <ide> from airflow.configuration import conf <ide> from airflow.exceptions import AirflowException <ide> def build_airflow_url_with_query(query: Dict[str, Any]) -> str: <ide> import flask <ide> <ide> view = conf.get('webserver', 'dag_default_view').lower() <del> url = flask.url_for(f"Airflow.{view}") <del> return f"{url}?{parse.urlencode(query)}" <add> return flask.url_for(f"Airflow.{view}", **query) <ide> <ide> <ide> # The 'template' argument is typed as Any because the jinja2.Template is too <ide><path>tests/utils/test_helpers.py <ide> def test_build_airflow_url_with_query(self): <ide> Test query generated with dag_id and params <ide> """ <ide> query = {"dag_id": "test_dag", "param": "key/to.encode"} <del> expected_url = "/graph?dag_id=test_dag&param=key%2Fto.encode" <add> expected_url = "/dags/test_dag/graph?param=key%2Fto.encode" <ide> <ide> from airflow.www.app import cached_app <ide>
2
Go
Go
add journald tag as syslog_identifier
ae557f9d85f41e009229d1a33844f06f7ad1fb99
<ide><path>daemon/logger/journald/journald.go <ide> func New(info logger.Info) (logger.Logger, error) { <ide> "CONTAINER_ID_FULL": info.ContainerID, <ide> "CONTAINER_NAME": info.Name(), <ide> "CONTAINER_TAG": tag, <add> "SYSLOG_IDENTIFIER": tag, <ide> } <ide> extraAttrs, err := info.ExtraAttributes(sanitizeKeyMod) <ide> if err != nil {
1
PHP
PHP
fix regression in save(touch) option
6c3ecdc5cf02c19ae28218201152ef34cd1ff9b5
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function save(array $options = []) <ide> // clause to only update this model. Otherwise, we'll just insert them. <ide> if ($this->exists) { <ide> $saved = $this->isDirty() ? <del> $this->performUpdate($query) : true; <add> $this->performUpdate($query, $options) : true; <ide> } <ide> <ide> // If the model is brand new, we'll insert it into our database and set the <ide> protected function finishSave(array $options) <ide> * Perform a model update operation. <ide> * <ide> * @param \Illuminate\Database\Eloquent\Builder $query <add> * @param array $options <ide> * @return bool <ide> */ <del> protected function performUpdate(Builder $query) <add> protected function performUpdate(Builder $query, array $options = []) <ide> { <ide> // If the updating event returns false, we will cancel the update operation so <ide> // developers can hook Validation systems into their models and cancel this <ide> protected function performUpdate(Builder $query) <ide> // First we need to create a fresh query instance and touch the creation and <ide> // update timestamp on the model which are maintained by us for developer <ide> // convenience. Then we will just continue saving the model instances. <del> if ($this->timestamps) { <add> if ($this->timestamps && Arr::get($options, 'touch', true)) { <ide> $this->updateTimestamps(); <ide> } <ide> <ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testUpdateProcessDoesntOverrideTimestamps() <ide> $this->assertTrue($model->save()); <ide> } <ide> <add> public function testSaveDoesntUpateTimestampsIfTouchOptionDisabled() <add> { <add> $model = $this->getMockBuilder('EloquentModelStub')->setMethods(['newQueryWithoutScopes', 'updateTimestamps', 'fireModelEvent'])->getMock(); <add> $query = m::mock('Illuminate\Database\Eloquent\Builder'); <add> $query->shouldReceive('where')->once()->with('id', '=', 1); <add> $query->shouldReceive('update')->once()->with(['name' => 'taylor'])->andReturn(1); <add> $model->expects($this->once())->method('newQueryWithoutScopes')->will($this->returnValue($query)); <add> $model->expects($this->never())->method('updateTimestamps'); <add> $model->expects($this->any())->method('fireModelEvent')->will($this->returnValue(true)); <add> <add> $model->id = 1; <add> $model->syncOriginal(); <add> $model->name = 'taylor'; <add> $model->exists = true; <add> $this->assertTrue($model->save(['touch' => false])); <add> } <add> <ide> public function testSaveIsCancelledIfSavingEventReturnsFalse() <ide> { <ide> $model = $this->getMockBuilder('EloquentModelStub')->setMethods(['newQueryWithoutScopes'])->getMock();
2
Javascript
Javascript
update morphanimmesh to work with the new mixer
4985ed03dbfa59fb722af18fa66f4c347d034ae9
<ide><path>examples/js/MD2Character.js <ide> THREE.MD2Character = function () { <ide> scope.root.add( mesh ); <ide> <ide> scope.meshBody = mesh; <del> scope.activeAnimationClipName = geo.firstAnimationClip.name; <add> scope.activeAnimationClipName = mesh.firstAnimationClip.name; <ide> <ide> checkLoadingComplete(); <ide> <ide><path>src/animation/PropertyBinding.js <ide> THREE.PropertyBinding = function ( rootNode, trackName ) { <ide> this.propertyName = parseResults.propertyName; <ide> this.propertyIndex = parseResults.propertyIndex; <ide> <del> this.node = THREE.PropertyBinding.findNode( rootNode, this.nodeName ); <del> <add> this.node = THREE.PropertyBinding.findNode( rootNode, this.nodeName ) || rootNode; <add> <ide> this.cumulativeValue = null; <ide> this.cumulativeWeight = 0; <ide> }; <ide> THREE.PropertyBinding.parseTrackName = function( trackName ) { <ide> // TODO: Cache this at some point <ide> THREE.PropertyBinding.findNode = function( root, nodeName ) { <ide> <del> //console.log( 'AnimationUtils.findNode( ' + root.name + ', nodeName: ' + nodeName + ')'); <add> //console.log( 'AnimationUtils.findNode( ' + root.name + ', nodeName: ' + nodeName + ')', root ); <ide> <ide> if( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) { <ide> <ide><path>src/objects/MorphAnimMesh.js <ide> THREE.MorphAnimMesh.prototype.parseAnimations = function () { <ide> <ide> }; <ide> <del>THREE.MorphAnimMesh.prototype.playAnimation = function ( label ) { <add>THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) { <ide> <ide> this.mixer.removeAllActions(); <ide> <ide> THREE.MorphAnimMesh.prototype.playAnimation = function ( label ) { <ide> <ide> if ( clip ) { <ide> <del> this.mixer.addAction( new THREE.AnimationAction( clip, 0, 1, 1, true ) ); <add> var action = new THREE.AnimationAction( clip, 0, 1, 1, true ); <add> action.timeScale = ( clip.tracks.length * fps ) / clip.duration; <add> this.mixer.addAction( action ); <ide> <ide> } else { <ide>
3
PHP
PHP
previous()
e38cf45df8ec077134de79987c2b9d566fceb257
<ide><path>tests/Routing/RoutingUrlGeneratorTest.php <ide> public function testForceRootUrl() <ide> $this->assertEquals('https://www.bar.com/foo', $url->route('plain')); <ide> } <ide> <add> <add> public function testPrevious() <add> { <add> $url = new UrlGenerator( <add> $routes = new Illuminate\Routing\RouteCollection, <add> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> ); <add> <add> $url->getRequest()->headers->set('referer', 'http://www.bar.com/'); <add> $this->assertEquals('http://www.bar.com/', $url->previous()); <add> <add> $url->getRequest()->headers->remove('referer'); <add> $this->assertEquals($url->to('/'), $url->previous()); <add> } <add> <ide> }
1
PHP
PHP
apply suggestions from @staudenmeir
c1984c9715e980e7f545fe70db0f997c87a70bd7
<ide><path>src/Illuminate/Http/Resources/ConditionallyLoadsAttributes.php <ide> protected function removeMissingValues($data) <ide> $value->resource instanceof PotentiallyMissing && <ide> $value->isMissing())) { <ide> unset($data[$key]); <add> } else { <add> $numericKeys = $numericKeys && is_numeric($key); <ide> } <del> $numericKeys = $numericKeys && is_numeric($key); <ide> } <ide> <ide> if (property_exists($this, 'preserveKeys') && $this->preserveKeys === true) { <del> $values = array_values($data); <del> <del> return $values === $data ? $values : $data; <add> return $data; <ide> } <ide> <ide> return $numericKeys ? array_values($data) : $data; <ide><path>tests/Integration/Http/ResourceTest.php <ide> public function test_the_resource_can_be_an_array() <ide> ]); <ide> } <ide> <add> public function test_it_will_return_as_an_array_when_string_keys_are_stripped() <add> { <add> $this->assertJsonResourceResponse([ <add> 1 => 'John', <add> 2 => 'Hank', <add> 'foo' => new MissingValue, <add> ], ['data' => ['John', 'Hank']]); <add> <add> $this->assertJsonResourceResponse([ <add> 1 => 'John', <add> 'foo' => new MissingValue, <add> 3 => 'Hank', <add> ], ['data' => ['John', 'Hank']]); <add> <add> $this->assertJsonResourceResponse([ <add> 'foo' => new MissingValue, <add> 2 => 'John', <add> 3 => 'Hank', <add> ], ['data' => ['John', 'Hank']]); <add> } <add> <ide> public function test_it_strips_numeric_keys() <ide> { <ide> $this->assertJsonResourceResponse([
2
Javascript
Javascript
add tests for codegennativecomponent
2e8ecab583a3c66491cbc31202a0f1b6e23c912e
<ide><path>Libraries/Utilities/__tests__/codegenNativeComponent-test.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @format <add> * @emails oncall+react_native <add> */ <add> <add>'use strict'; <add> <add>const codegenNativeComponent = require('../codegenNativeComponent').default; <add>const {UIManager} = require('react-native'); <add> <add>// We need to unmock requireNativeComponent since it's under test. <add>// Instead, we mock the function it calls, createReactNativeComponentClass, <add>// so that we don't run into issues populating the registry with the same <add>// component names. <add>jest.unmock('../../ReactNative/requireNativeComponent'); <add>jest.mock( <add> '../../Renderer/shims/createReactNativeComponentClass', <add> () => componentName => componentName, <add>); <add>jest <add> .spyOn(UIManager, 'getViewManagerConfig') <add> .mockImplementation(componentName => <add> componentName.includes('ComponentNameDoesNotExist') ? false : true, <add> ); <add> <add>describe('codegenNativeComponent', () => { <add> it('should require component as is ', () => { <add> const component = codegenNativeComponent('ComponentName'); <add> expect(component).toBe('ComponentName'); <add> }); <add> <add> it('should require paperComponentName', () => { <add> const component = codegenNativeComponent('ComponentName', { <add> paperComponentName: 'PaperComponentName', <add> }); <add> expect(component).toBe('PaperComponentName'); <add> }); <add> <add> it('should fall back to requiring the deprecated paper component name', () => { <add> const component = codegenNativeComponent('ComponentNameDoesNotExist', { <add> paperComponentNameDeprecated: 'ComponentName', <add> }); <add> expect(component).toBe('ComponentName'); <add> }); <add> <add> it('should require the new component name', () => { <add> const component = codegenNativeComponent('ComponentName', { <add> paperComponentNameDeprecated: 'ComponentNameDoesNotExist', <add> }); <add> expect(component).toBe('ComponentName'); <add> }); <add> <add> it('should throw if neither component names exist', () => { <add> expect(() => <add> codegenNativeComponent('ComponentNameDoesNotExistOne', { <add> paperComponentNameDeprecated: 'ComponentNameDoesNotExistTwo', <add> }), <add> ).toThrow( <add> 'Failed to find native component for either ComponentNameDoesNotExistOne or ComponentNameDoesNotExistTwo', <add> ); <add> }); <add>});
1
Python
Python
remove mutable arguments in assert_routes_to_queue
d537be48e41cec1336e8e35f6db271b5f635adb7
<ide><path>t/unit/app/test_routes.py <ide> def mytask(*args, **kwargs): <ide> self.mytask = mytask <ide> <ide> def assert_routes_to_queue(self, queue, router, name, <del> args=[], kwargs={}, options={}): <add> args=None, kwargs=None, options=None): <add> if options is None: <add> options = {} <add> if kwargs is None: <add> kwargs = {} <add> if args is None: <add> args = [] <ide> assert router.route(options, name, args, kwargs)['queue'].name == queue <ide> <ide> def assert_routes_to_default_queue(self, router, name, *args, **kwargs):
1
Javascript
Javascript
remove common.port in test tls ticket cluster
dac9f42a7e1fbe7128e3c39d565b0ac1040231ec
<ide><path>test/parallel/test-tls-ticket-cluster.js <ide> if (cluster.isMaster) { <ide> let reqCount = 0; <ide> let lastSession = null; <ide> let shootOnce = false; <add> let workerPort = null; <ide> <ide> function shoot() { <del> console.error('[master] connecting'); <del> const c = tls.connect(common.PORT, { <add> console.error('[master] connecting', workerPort); <add> const c = tls.connect(workerPort, { <ide> session: lastSession, <ide> rejectUnauthorized: false <ide> }, function() { <ide> if (cluster.isMaster) { <ide> <ide> function fork() { <ide> const worker = cluster.fork(); <del> worker.on('message', function(msg) { <add> worker.on('message', function({ msg, port }) { <ide> console.error('[master] got %j', msg); <ide> if (msg === 'reused') { <ide> ++reusedCount; <ide> } else if (msg === 'listening' && !shootOnce) { <add> workerPort = port || workerPort; <ide> shootOnce = true; <ide> shoot(); <ide> } <ide> const options = { <ide> <ide> const server = tls.createServer(options, function(c) { <ide> if (c.isSessionReused()) { <del> process.send('reused'); <add> process.send({ msg: 'reused' }); <ide> } else { <del> process.send('not-reused'); <add> process.send({ msg: 'not-reused' }); <ide> } <ide> c.end(); <ide> }); <ide> <del>server.listen(common.PORT, function() { <del> process.send('listening'); <add>server.listen(0, function() { <add> const { port } = server.address(); <add> process.send({ <add> msg: 'listening', <add> port, <add> }); <ide> }); <ide> <ide> process.on('message', function listener(msg) {
1
Text
Text
add release key for danielle adams
6b6bbfe7d043e9170895c8dfdb61fec28b2a368c
<ide><path>README.md <ide> Primary GPG keys for Node.js Releasers (some Releasers sign with subkeys): <ide> `4ED778F539E3634C779C87C6D7062848A1AB005C` <ide> * **Colin Ihrig** &lt;cjihrig@gmail.com&gt; <ide> `94AE36675C464D64BAFA68DD7434390BDBE9B9C5` <add>* **Danielle Adams** &lt;adamzdanielle@gmail.com&gt; <add>`1C050899334244A8AF75E53792EF661D867B9DFA` <ide> * **James M Snell** &lt;jasnell@keybase.io&gt; <ide> `71DCFD284A79C3B38668286BC97EC7A07EDE3FC1` <ide> * **Michaël Zasso** &lt;targos@protonmail.com&gt; <ide> To import the full set of trusted release keys: <ide> ```bash <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 4ED778F539E3634C779C87C6D7062848A1AB005C <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 94AE36675C464D64BAFA68DD7434390BDBE9B9C5 <add>gpg --keyserver pool.sks-keyservers.net --recv-keys 1C050899334244A8AF75E53792EF661D867B9DFA <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600 <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8
1
Javascript
Javascript
use specific method names in error messages
ebe51284896981142af5b8b1509df17419f2b644
<ide><path>src/isomorphic/classic/class/ReactClass.js <ide> var ReactClassMixin = { <ide> replaceState: function(newState, callback) { <ide> this.updater.enqueueReplaceState(this, newState); <ide> if (callback) { <del> this.updater.enqueueCallback(this, callback); <add> this.updater.enqueueCallback(this, callback, 'replaceState'); <ide> } <ide> }, <ide> <ide><path>src/isomorphic/modern/class/ReactComponent.js <ide> ReactComponent.prototype.setState = function(partialState, callback) { <ide> } <ide> this.updater.enqueueSetState(this, partialState); <ide> if (callback) { <del> this.updater.enqueueCallback(this, callback); <add> this.updater.enqueueCallback(this, callback, 'setState'); <ide> } <ide> }; <ide> <ide> ReactComponent.prototype.setState = function(partialState, callback) { <ide> ReactComponent.prototype.forceUpdate = function(callback) { <ide> this.updater.enqueueForceUpdate(this); <ide> if (callback) { <del> this.updater.enqueueCallback(this, callback); <add> this.updater.enqueueCallback(this, callback, 'forceUpdate'); <ide> } <ide> }; <ide> <ide><path>src/renderers/shared/reconciler/ReactUpdateQueue.js <ide> var ReactUpdateQueue = { <ide> * <ide> * @param {ReactClass} publicInstance The instance to use as `this` context. <ide> * @param {?function} callback Called after state is updated. <add> * @param {string} callerName Name of the calling function in the public API. <ide> * @internal <ide> */ <del> enqueueCallback: function(publicInstance, callback) { <add> enqueueCallback: function(publicInstance, callback, callerName) { <ide> invariant( <ide> typeof callback === 'function', <del> 'enqueueCallback(...): You called `setState`, `replaceState`, or ' + <del> '`forceUpdate` with the last argument of type %s. When specified, ' + <del> 'their last `callback` argument is expected to be a function.', <add> 'enqueueCallback(...): You called `%s` with the last argument of type ' + <add> '%s. When specified, its last `callback` argument must be a function.', <add> callerName, <ide> formatUnexpectedArgument(callback) <ide> ); <ide> var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); <ide><path>src/renderers/shared/reconciler/__tests__/ReactUpdates-test.js <ide> describe('ReactUpdates', function() { <ide> } <ide> }); <ide> <del> it('throws when the update callback is not a function', function() { <add> it('throws in setState if the update callback is not a function', function() { <ide> function Foo() { <ide> this.a = 1; <ide> this.b = 2; <ide> describe('ReactUpdates', function() { <ide> }); <ide> var component = ReactTestUtils.renderIntoDocument(<A />); <ide> <del> var stringMessage = <del> 'enqueueCallback(...): You called `setState`, `replaceState`, or '+ <del> '`forceUpdate` with the last argument of type string. When specified, ' + <del> 'their last `callback` argument is expected to be a function.'; <del> expect(() => component.setState({}, 'no')).toThrow(stringMessage); <del> expect(() => component.replaceState({}, 'no')).toThrow(stringMessage); <del> expect(() => component.forceUpdate('no')).toThrow(stringMessage); <del> <del> var objectMessage = <del> 'enqueueCallback(...): You called `setState`, `replaceState`, or '+ <del> '`forceUpdate` with the last argument of type Object. When specified, ' + <del> 'their last `callback` argument is expected to be a function.'; <del> expect(() => component.setState({}, {})).toThrow(objectMessage); <del> expect(() => component.replaceState({}, {})).toThrow(objectMessage); <del> expect(() => component.forceUpdate({})).toThrow(objectMessage); <del> <del> var fooMessage = <del> 'enqueueCallback(...): You called `setState`, `replaceState`, or '+ <del> '`forceUpdate` with the last argument of type Foo (keys: a, b). When ' + <del> 'specified, their last `callback` argument is expected to be a function.'; <del> expect(() => component.setState({}, new Foo())).toThrow(fooMessage); <del> expect(() => component.replaceState({}, new Foo())).toThrow(fooMessage); <del> expect(() => component.forceUpdate(new Foo())).toThrow(fooMessage); <add> expect(() => component.setState({}, 'no')).toThrow( <add> 'enqueueCallback(...): You called `setState` with the last argument of ' + <add> 'type string. When specified, its last `callback` argument must be a ' + <add> 'function.' <add> ); <add> expect(() => component.setState({}, {})).toThrow( <add> 'enqueueCallback(...): You called `setState` with the last argument of ' + <add> 'type Object. When specified, its last `callback` argument must be a ' + <add> 'function.' <add> ); <add> expect(() => component.setState({}, new Foo())).toThrow( <add> 'enqueueCallback(...): You called `setState` with the last argument of ' + <add> 'type Foo (keys: a, b). When specified, its last `callback` argument ' + <add> 'must be a function.' <add> ); <add> }); <add> <add> it('throws in replaceState if the update callback is not a function', function() { <add> function Foo() { <add> this.a = 1; <add> this.b = 2; <add> } <add> var A = React.createClass({ <add> getInitialState: function() { <add> return {}; <add> }, <add> render: function() { <add> return <div />; <add> }, <add> }); <add> var component = ReactTestUtils.renderIntoDocument(<A />); <add> <add> expect(() => component.replaceState({}, 'no')).toThrow( <add> 'enqueueCallback(...): You called `replaceState` with the last ' + <add> 'argument of type string. When specified, its last `callback` argument ' + <add> 'must be a function.' <add> ); <add> expect(() => component.replaceState({}, {})).toThrow( <add> 'enqueueCallback(...): You called `replaceState` with the last ' + <add> 'argument of type Object. When specified, its last `callback` argument ' + <add> 'must be a function.' <add> ); <add> expect(() => component.replaceState({}, new Foo())).toThrow( <add> 'enqueueCallback(...): You called `replaceState` with the last ' + <add> 'argument of type Foo (keys: a, b). When specified, its last ' + <add> '`callback` argument must be a function.' <add> ); <add> }); <add> <add> it('throws in forceUpdate if the update callback is not a function', function() { <add> function Foo() { <add> this.a = 1; <add> this.b = 2; <add> } <add> var A = React.createClass({ <add> getInitialState: function() { <add> return {}; <add> }, <add> render: function() { <add> return <div />; <add> }, <add> }); <add> var component = ReactTestUtils.renderIntoDocument(<A />); <add> <add> expect(() => component.forceUpdate('no')).toThrow( <add> 'enqueueCallback(...): You called `forceUpdate` with the last ' + <add> 'argument of type string. When specified, its last `callback` argument ' + <add> 'must be a function.' <add> ); <add> expect(() => component.forceUpdate({})).toThrow( <add> 'enqueueCallback(...): You called `forceUpdate` with the last ' + <add> 'argument of type Object. When specified, its last `callback` argument ' + <add> 'must be a function.' <add> ); <add> expect(() => component.forceUpdate(new Foo())).toThrow( <add> 'enqueueCallback(...): You called `forceUpdate` with the last ' + <add> 'argument of type Foo (keys: a, b). When specified, its last ' + <add> '`callback` argument must be a function.' <add> ); <ide> }); <ide> });
4
Java
Java
avoid hamcrest 2.x deprecation warnings
19ed439e4bab269400a1dd585bcb947e61cda45e
<ide><path>spring-test/src/test/java/org/springframework/test/web/client/samples/matchers/JsonPathRequestMatchersIntegrationTests.java <ide> import static org.hamcrest.Matchers.endsWith; <ide> import static org.hamcrest.Matchers.equalTo; <ide> import static org.hamcrest.Matchers.hasItem; <del>import static org.hamcrest.Matchers.isIn; <add>import static org.hamcrest.Matchers.in; <add>import static org.hamcrest.Matchers.is; <ide> import static org.hamcrest.Matchers.startsWith; <ide> import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; <ide> import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; <ide> public void hamcrestMatchers() throws Exception { <ide> .andExpect(jsonPath("$.composers[0].name", startsWith("Johann"))) <ide> .andExpect(jsonPath("$.performers[0].name", endsWith("Ashkenazy"))) <ide> .andExpect(jsonPath("$.performers[1].name", containsString("di Me"))) <del> .andExpect(jsonPath("$.composers[1].name", isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms")))) <add> .andExpect(jsonPath("$.composers[1].name", is(in(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))) <ide> .andExpect(jsonPath("$.composers[:3].name", hasItem("Johannes Brahms"))) <ide> .andRespond(withSuccess()); <ide> <ide> public void hamcrestMatchersWithParameterizedJsonPaths() throws Exception { <ide> .andExpect(jsonPath(composerName, 0).value(startsWith("Johann"))) <ide> .andExpect(jsonPath(performerName, 0).value(endsWith("Ashkenazy"))) <ide> .andExpect(jsonPath(performerName, 1).value(containsString("di Me"))) <del> .andExpect(jsonPath(composerName, 1).value(isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms")))) <add> .andExpect(jsonPath(composerName, 1).value(is(in(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))) <ide> .andRespond(withSuccess()); <ide> <ide> executeAndVerify(); <ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/JsonPathAssertionTests.java <ide> import static org.hamcrest.Matchers.containsString; <ide> import static org.hamcrest.Matchers.endsWith; <ide> import static org.hamcrest.Matchers.equalTo; <del>import static org.hamcrest.Matchers.isIn; <add>import static org.hamcrest.Matchers.in; <add>import static org.hamcrest.Matchers.is; <ide> import static org.hamcrest.Matchers.startsWith; <ide> import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; <ide> import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; <ide> public void hamcrestMatcher() throws Exception { <ide> .andExpect(jsonPath("$.composers[0].name", startsWith("Johann"))) <ide> .andExpect(jsonPath("$.performers[0].name", endsWith("Ashkenazy"))) <ide> .andExpect(jsonPath("$.performers[1].name", containsString("di Me"))) <del> .andExpect(jsonPath("$.composers[1].name", isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms")))); <add> .andExpect(jsonPath("$.composers[1].name", is(in(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))); <ide> } <ide> <ide> @Test <ide> public void hamcrestMatcherWithParameterizedJsonPath() throws Exception { <ide> .andExpect(jsonPath(composerName, 0).value(startsWith("Johann"))) <ide> .andExpect(jsonPath(performerName, 0).value(endsWith("Ashkenazy"))) <ide> .andExpect(jsonPath(performerName, 1).value(containsString("di Me"))) <del> .andExpect(jsonPath(composerName, 1).value(isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms")))); <add> .andExpect(jsonPath(composerName, 1).value(is(in(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))); <ide> } <ide> <ide>
2
Javascript
Javascript
simplify simd setup
5f2994723048f6d433cece23af0e11bdd97e0896
<ide><path>lib/util.js <ide> if (typeof global.SIMD === 'object' && global.SIMD !== null) { <ide> <ide> const SIMD = global.SIMD; // Pacify eslint. <ide> <del> if (typeof SIMD.Bool16x8 === 'function') <del> simdFormatters.set(SIMD.Bool16x8, make(SIMD.Bool16x8.extractLane, 8)); <del> <del> if (typeof SIMD.Bool32x4 === 'function') <del> simdFormatters.set(SIMD.Bool32x4, make(SIMD.Bool32x4.extractLane, 4)); <del> <del> if (typeof SIMD.Bool8x16 === 'function') <del> simdFormatters.set(SIMD.Bool8x16, make(SIMD.Bool8x16.extractLane, 16)); <del> <del> if (typeof SIMD.Float32x4 === 'function') <del> simdFormatters.set(SIMD.Float32x4, make(SIMD.Float32x4.extractLane, 4)); <del> <del> if (typeof SIMD.Int16x8 === 'function') <del> simdFormatters.set(SIMD.Int16x8, make(SIMD.Int16x8.extractLane, 8)); <del> <del> if (typeof SIMD.Int32x4 === 'function') <del> simdFormatters.set(SIMD.Int32x4, make(SIMD.Int32x4.extractLane, 4)); <del> <del> if (typeof SIMD.Int8x16 === 'function') <del> simdFormatters.set(SIMD.Int8x16, make(SIMD.Int8x16.extractLane, 16)); <del> <del> if (typeof SIMD.Uint16x8 === 'function') <del> simdFormatters.set(SIMD.Uint16x8, make(SIMD.Uint16x8.extractLane, 8)); <del> <del> if (typeof SIMD.Uint32x4 === 'function') <del> simdFormatters.set(SIMD.Uint32x4, make(SIMD.Uint32x4.extractLane, 4)); <add> const countPerType = { <add> Bool16x8: 8, <add> Bool32x4: 4, <add> Bool8x16: 16, <add> Float32x4: 4, <add> Int16x8: 8, <add> Int32x4: 4, <add> Int8x16: 16, <add> Uint16x8: 8, <add> Uint32x4: 4, <add> Uint8x16: 16 <add> }; <ide> <del> if (typeof SIMD.Uint8x16 === 'function') <del> simdFormatters.set(SIMD.Uint8x16, make(SIMD.Uint8x16.extractLane, 16)); <add> for (const key in countPerType) { <add> const type = SIMD[key]; <add> simdFormatters.set(type, make(type.extractLane, countPerType[key])); <add> } <ide> } <ide> <ide> function tryStringify(arg) {
1
PHP
PHP
add coverage for warnings being generated
920f8af4d98968686cac813bc4161614692633ea
<ide><path>tests/TestCase/Controller/ControllerTest.php <ide> use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <add>use PHPUnit\Framework\Error\Warning; <ide> use TestApp\Controller\Admin\PostsController; <ide> use TestPlugin\Controller\TestPluginController; <ide> <ide> public function testComponents() <ide> $this->assertSame($result, $controller->components()); <ide> } <ide> <add> /** <add> * Test the components property errors <add> * <add> * @return void <add> */ <add> public function testComponentsPropertyError() <add> { <add> $this->expectException(Warning::class); <add> $request = new ServerRequest(['url' => '/']); <add> $response = new Response(); <add> <add> $controller = new TestController($request, $response); <add> $controller->components = ['Flash']; <add> } <add> <add> /** <add> * Test the helpers property errors <add> * <add> * @return void <add> */ <add> public function testHelpersPropertyError() <add> { <add> $this->expectException(Warning::class); <add> $request = new ServerRequest(['url' => '/']); <add> $response = new Response(); <add> <add> $controller = new TestController($request, $response); <add> $controller->helpers = ['Flash']; <add> } <add> <ide> /** <ide> * Test the components() method with the custom ObjectRegistry. <ide> *
1
Python
Python
fix obvious typos in flax decoder impl
e86faecfd43b8a8e296f14b4dbe21a68f3e2a4ed
<ide><path>src/transformers/models/bart/modeling_flax_bart.py <ide> def setup(self) -> None: <ide> ) <ide> self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05) <ide> self.fc1 = nn.Dense( <del> self.config.encoder_ffn_dim, <add> self.config.decoder_ffn_dim, <ide> dtype=self.dtype, <ide> kernel_init=jax.nn.initializers.normal(self.config.init_std), <ide> ) <ide><path>src/transformers/models/blenderbot/modeling_flax_blenderbot.py <ide> def setup(self) -> None: <ide> ) <ide> self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05) <ide> self.fc1 = nn.Dense( <del> self.config.encoder_ffn_dim, <add> self.config.decoder_ffn_dim, <ide> dtype=self.dtype, <ide> kernel_init=jax.nn.initializers.normal(self.config.init_std), <ide> ) <ide><path>src/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py <ide> def setup(self) -> None: <ide> ) <ide> self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05) <ide> self.fc1 = nn.Dense( <del> self.config.encoder_ffn_dim, <add> self.config.decoder_ffn_dim, <ide> dtype=self.dtype, <ide> kernel_init=jax.nn.initializers.normal(self.config.init_std), <ide> ) <ide><path>src/transformers/models/marian/modeling_flax_marian.py <ide> def setup(self) -> None: <ide> ) <ide> self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05) <ide> self.fc1 = nn.Dense( <del> self.config.encoder_ffn_dim, <add> self.config.decoder_ffn_dim, <ide> dtype=self.dtype, <ide> kernel_init=jax.nn.initializers.normal(self.config.init_std), <ide> ) <ide><path>src/transformers/models/mbart/modeling_flax_mbart.py <ide> def setup(self) -> None: <ide> ) <ide> self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05) <ide> self.fc1 = nn.Dense( <del> self.config.encoder_ffn_dim, <add> self.config.decoder_ffn_dim, <ide> dtype=self.dtype, <ide> kernel_init=jax.nn.initializers.normal(self.config.init_std), <ide> ) <ide><path>src/transformers/models/pegasus/modeling_flax_pegasus.py <ide> def setup(self) -> None: <ide> ) <ide> self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05) <ide> self.fc1 = nn.Dense( <del> self.config.encoder_ffn_dim, <add> self.config.decoder_ffn_dim, <ide> dtype=self.dtype, <ide> kernel_init=jax.nn.initializers.normal(self.config.init_std), <ide> ) <ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_flax_{{cookiecutter.lowercase_modelname}}.py <ide> def setup(self) -> None: <ide> ) <ide> self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype) <ide> self.fc1 = nn.Dense( <del> self.config.encoder_ffn_dim, <add> self.config.decoder_ffn_dim, <ide> dtype=self.dtype, <ide> kernel_init=jax.nn.initializers.normal(self.config.init_std), <ide> ) <ide> def update_inputs_for_generation(self, model_outputs, model_kwargs): <ide> ```python <ide> >>> import jax <ide> >>> from transformers import {{cookiecutter.camelcase_modelname}}Tokenizer, Flax{{cookiecutter.camelcase_modelname}}ForConditionalGeneration <del> <add> <ide> >>> model = Flax{{cookiecutter.camelcase_modelname}}ForConditionalGeneration.from_pretrained('{{cookiecutter.checkpoint_identifier}}') <ide> >>> tokenizer = {{cookiecutter.camelcase_modelname}}Tokenizer.from_pretrained('{{cookiecutter.checkpoint_identifier}}') <del> <add> <ide> >>> TXT = "My friends are <mask> but they eat too many carbs." <ide> >>> input_ids = tokenizer([TXT], return_tensors='np')['input_ids'] <ide>
7
Javascript
Javascript
fix lint issues
66bb2d95cd834b97d13bc6c5cd8c4d7e116d0ac3
<ide><path>src/lib/locale/locales.js <ide> function chooseLocale(names) { <ide> function loadLocale(name) { <ide> var oldLocale = null; <ide> // TODO: Find a better way to register and load all the locales in Node <del> if (!locales[name] && (typeof module !== "undefined") && <add> if (!locales[name] && (typeof module !== 'undefined') && <ide> module && module.exports) { <ide> try { <ide> oldLocale = globalLocale._abbr; <ide><path>src/lib/utils/deprecate.js <ide> import isUndefined from './is-undefined'; <ide> <ide> function warn(msg) { <ide> if (hooks.suppressDeprecationWarnings === false && <del> (typeof console !== "undefined") && console.warn) { <add> (typeof console !== 'undefined') && console.warn) { <ide> console.warn('Deprecation warning: ' + msg); <ide> } <ide> }
2
Javascript
Javascript
remove observables from requestupdateemail method
9cf1d67e024f9993fd8d7b2aec46af0111bf8b5a
<ide><path>common/models/user.js <ide> module.exports = function(User) { <ide> <ide> User.prototype.requestUpdateEmail = function requestUpdateEmail(newEmail) { <ide> const currentEmail = this.email; <del> return Observable.defer(() => { <del> const isOwnEmail = isTheSame(newEmail, currentEmail); <del> const sameUpdate = isTheSame(newEmail, this.newEmail); <del> const messageOrNull = getWaitMessage(this.emailVerifyTTL); <del> if (isOwnEmail) { <del> if (this.emailVerified) { <del> // email is already associated and verified with this account <del> throw wrapHandledError( <del> new Error('email is already verified'), <del> { <del> type: 'info', <del> message: `${newEmail} is already associated with this account.` <del> } <del> ); <del> } else if (!this.emailVerified && messageOrNull) { <del> // email is associated but unverified and <del> // email is within time limit <del> throw wrapHandledError( <del> new Error(), <del> { <del> type: 'info', <del> message: messageOrNull <del> } <del> ); <del> } <del> } <del> if (sameUpdate && messageOrNull) { <del> // trying to update with the same newEmail and <del> // confirmation email is still valid <add> const isOwnEmail = isTheSame(newEmail, currentEmail); <add> const sameUpdate = isTheSame(newEmail, this.newEmail); <add> const messageOrNull = getWaitMessage(this.emailVerifyTTL); <add> if (isOwnEmail) { <add> if (this.emailVerified) { <add> // email is already associated and verified with this account <ide> throw wrapHandledError( <del> new Error(), <add> new Error('email is already verified'), <ide> { <ide> type: 'info', <del> message: dedent` <del> We have already sent an email confirmation request to ${newEmail}. <del> Please check your inbox.` <add> message: `${newEmail} is already associated with this account.` <ide> } <ide> ); <del> } <del> if (!isEmail('' + newEmail)) { <del> throw createEmailError(); <del> } <del> // newEmail is not associated with this user, and <del> // this attempt to change email is the first or <del> // previous attempts have expired <del> return Observable.if( <del> () => isOwnEmail || (sameUpdate && messageOrNull), <del> Observable.empty(), <del> // defer prevents the promise from firing prematurely (before subscribe) <del> Observable.defer(() => User.doesExist(null, newEmail)) <del> ) <del> .do(exists => { <del> if (exists) { <del> // newEmail is not associated with this account, <del> // but is associated with different account <add> } else if (!this.emailVerified && messageOrNull) { <add> // email is associated but unverified and <add> // email is within time limit <ide> throw wrapHandledError( <del> new Error('email already in use'), <add> new Error(), <ide> { <ide> type: 'info', <del> message: <del> `${newEmail} is already associated with another account.` <add> message: messageOrNull <ide> } <ide> ); <ide> } <add> } <add> if (sameUpdate && messageOrNull) { <add> // trying to update with the same newEmail and <add> // confirmation email is still valid <add> throw wrapHandledError( <add> new Error(), <add> { <add> type: 'info', <add> message: dedent` <add> We have already sent an email confirmation request to ${newEmail}. <add> Please check your inbox.` <add> } <add> ); <add> } <add> if (!isEmail('' + newEmail)) { <add> throw createEmailError(); <add> } <add> // newEmail is not associated with this user, and <add> // this attempt to change email is the first or <add> // previous attempts have expired <add> <add> if (isOwnEmail || (sameUpdate && !messageOrNull)) { <add> const update = { <add> newEmail, <add> emailVerified: false, <add> emailVerifyTTL: new Date() <add> }; <add> return this.update$(update).toPromise() <add> .then(() => { <add> Object.assign(this, update); <add> return; <ide> }) <del> .flatMap(() => { <del> const update = { <del> newEmail, <del> emailVerified: false, <del> emailVerifyTTL: new Date() <del> }; <del> return this.update$(update) <del> .do(() => Object.assign(this, update)) <del> .flatMap(() => this.requestAuthEmail(false, newEmail)); <del> }); <del> }); <add> .then(() => this.requestAuthEmail(false, newEmail).toPromise()); <add> } else { <add> return 'Something unexpected happened whilst updating your email.'; <add> } <ide> }; <ide> <ide> function requestCompletedChallenges() { <ide><path>server/boot/authentication.js <ide> module.exports = function enableAuthentication(app) { <ide> ifUserRedirect, <ide> (req, res) => res.redirect(301, '/auth/auth0')); <ide> <add> router.get( <add> '/update-email', <add> ifNoUserRedirectHome, <add> (req, res) => res.render('account/update-email', { <add> title: 'Update your email' <add> }) <add> ); <add> <ide> router.get('/signout', (req, res) => { <ide> req.logout(); <ide> req.session.destroy( (err) => { <ide><path>server/boot/settings.js <ide> export default function settingsController(app) { <ide> .withMessage('Email format is invalid.') <ide> ]; <ide> <del> function updateMyEmail(req, res, next) { <add> function updateMyEmail(req, res) { <ide> const { user, body: { email } } = req; <del> return user.requestUpdateEmail(email) <del> .subscribe( <del> message => res.json({ message }), <del> next <del> ); <add> return res.json({ message: user.requestUpdateEmail(email) } ); <ide> } <ide> <ide> const updateMyCurrentChallengeValidators = [ <ide><path>server/middlewares/email-not-verified-notice.js <ide> const ALLOWED_METHODS = ['GET']; <ide> const EXCLUDED_PATHS = [ <ide> '/api/flyers/findOne', <ide> '/signout', <del> '/settings/update-email' <add> '/update-email', <add> '/passwordless-change' <ide> ]; <ide> <ide> export default function emailNotVerifiedNotice() { <ide> export default function emailNotVerifiedNotice() { <ide> confirm. <ide> ` <ide> ); <del> res.redirect('/settings/update-email'); <add> res.redirect('/update-email'); <ide> return next; <ide> } <ide> }
4
Text
Text
describe the available pypi packages
b8565dcab1292944b96328d92ad81ec1adaa481e
<ide><path>official/README.md <ide> don't recommend earlier versions. <ide> ### Installation <ide> <ide> Please check [here](https://github.com/tensorflow/models#Installation) for the <del>instructions <add>instructions. <add> <add>Available pypi packages: <add> <add>* [tf-models-official](https://pypi.org/project/tf-models-official/) <add>* [tf-models-nightly](https://pypi.org/project/tf-models-nightly/): nightly <add>release with the latest changes. <add>* [tf-models-no-deps](https://pypi.org/project/tf-models-no-deps/): without <add>`tensorflow` and `tensorflow-text` in the `install_requires` list. <ide> <ide> ## Contributions <ide>
1
Java
Java
avoid deprecation warnings on jdk 9 in spring-test
c88f11f9583bf5123d7f51d81fe4c1bbe40d6e51
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/SpringExtensionTestCase.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> void autowiredFields() { <ide> assertEquals(2, this.cats.size(), "Number of cats in context"); <ide> <ide> assertNotNull(this.enigma, "Enigma should have been injected via @Value by Spring"); <del> assertEquals(new Integer(42), this.enigma, "enigma"); <add> assertEquals(Integer.valueOf(42), this.enigma, "enigma"); <ide> } <ide> <ide> @Test <ide> void valueParameterWithPrimitiveType(@Value("99") int num) { <ide> @Test <ide> void valueParameterFromPropertyPlaceholder(@Value("${enigma}") Integer enigmaParam) { <ide> assertNotNull(enigmaParam, "Enigma should have been injected via @Value by Spring"); <del> assertEquals(new Integer(42), enigmaParam, "enigma"); <add> assertEquals(Integer.valueOf(42), enigmaParam, "enigma"); <ide> } <ide> <ide> @Test <ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/SpringJUnitJupiterAutowiredConstructorInjectionTestCase.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> void beansInjected() { <ide> @Test <ide> void propertyPlaceholderInjected() { <ide> assertNotNull(this.enigma, "Enigma should have been injected via @Value by Spring"); <del> assertEquals(new Integer(42), this.enigma, "enigma"); <add> assertEquals(Integer.valueOf(42), this.enigma, "enigma"); <ide> } <ide> <ide> } <ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/SpringJUnitJupiterConstructorInjectionTestCase.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> void beansInjected() { <ide> @Test <ide> void propertyPlaceholderInjected() { <ide> assertNotNull(this.enigma, "Enigma should have been injected via @Value by Spring"); <del> assertEquals(new Integer(42), this.enigma, "enigma"); <add> assertEquals(Integer.valueOf(42), this.enigma, "enigma"); <ide> } <ide> <ide> @Test <ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/orm/HibernateSessionFlushingTests.java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void findSam() { <ide> assertNotNull("Should be able to find Sam", sam); <ide> DriversLicense driversLicense = sam.getDriversLicense(); <ide> assertNotNull("Sam's driver's license should not be null", driversLicense); <del> assertEquals("Verifying Sam's driver's license number", new Long(1234), driversLicense.getNumber()); <add> assertEquals("Verifying Sam's driver's license number", Long.valueOf(1234), driversLicense.getNumber()); <ide> } <ide> <ide> @Test <ide><path>spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.junit.rules.ExpectedException; <ide> <ide> import org.mockito.BDDMockito; <del> <add>import org.springframework.beans.BeanUtils; <ide> import org.springframework.core.annotation.AliasFor; <ide> import org.springframework.test.annotation.Commit; <ide> import org.springframework.test.annotation.Rollback; <ide> private void assertBeforeTestMethodWithTransactionalTestMethod(Class<? extends I <ide> private void assertBeforeTestMethodWithTransactionalTestMethod(Class<? extends Invocable> clazz, boolean invokedInTx) <ide> throws Exception { <ide> BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); <del> Invocable instance = clazz.newInstance(); <add> Invocable instance = BeanUtils.instantiateClass(clazz); <ide> given(testContext.getTestInstance()).willReturn(instance); <ide> given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest")); <ide> <ide> private void assertBeforeTestMethodWithTransactionalTestMethod(Class<? extends I <ide> private void assertBeforeTestMethodWithNonTransactionalTestMethod(Class<? extends Invocable> clazz) <ide> throws Exception { <ide> BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); <del> Invocable instance = clazz.newInstance(); <add> Invocable instance = BeanUtils.instantiateClass(clazz); <ide> given(testContext.getTestInstance()).willReturn(instance); <ide> given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("nonTransactionalTest")); <ide> <ide> private void assertAfterTestMethod(Class<? extends Invocable> clazz) throws Exce <ide> <ide> private void assertAfterTestMethodWithTransactionalTestMethod(Class<? extends Invocable> clazz) throws Exception { <ide> BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); <del> Invocable instance = clazz.newInstance(); <add> Invocable instance = BeanUtils.instantiateClass(clazz); <ide> given(testContext.getTestInstance()).willReturn(instance); <ide> given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest")); <ide> <ide> private void assertAfterTestMethodWithTransactionalTestMethod(Class<? extends In <ide> <ide> private void assertAfterTestMethodWithNonTransactionalTestMethod(Class<? extends Invocable> clazz) throws Exception { <ide> BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); <del> Invocable instance = clazz.newInstance(); <add> Invocable instance = BeanUtils.instantiateClass(clazz); <ide> given(testContext.getTestInstance()).willReturn(instance); <ide> given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("nonTransactionalTest")); <ide> <ide> protected PlatformTransactionManager getTransactionManager(TestContext testConte <ide> Class<? extends Invocable> clazz = TransactionalDeclaredOnClassLocallyTestCase.class; <ide> <ide> BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz); <del> Invocable instance = clazz.newInstance(); <add> Invocable instance = BeanUtils.instantiateClass(clazz); <ide> given(testContext.getTestInstance()).willReturn(instance); <ide> given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest")); <ide> <ide><path>spring-test/src/test/java/org/springframework/test/util/ReflectionTestUtilsTests.java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> */ <ide> public class ReflectionTestUtilsTests { <ide> <del> private static final Float PI = new Float((float) 22 / 7); <add> private static final Float PI = Float.valueOf((float) 22 / 7); <ide> <ide> private final Person person = new PersonEntity(); <ide> <ide> public void resetStaticFields() { <ide> public void setFieldWithNullTargetObject() throws Exception { <ide> exception.expect(IllegalArgumentException.class); <ide> exception.expectMessage(startsWith("Either targetObject or targetClass")); <del> setField((Object) null, "id", new Long(99)); <add> setField((Object) null, "id", Long.valueOf(99)); <ide> } <ide> <ide> @Test <ide> public void getFieldWithNullTargetObject() throws Exception { <ide> public void setFieldWithNullTargetClass() throws Exception { <ide> exception.expect(IllegalArgumentException.class); <ide> exception.expectMessage(startsWith("Either targetObject or targetClass")); <del> setField((Class<?>) null, "id", new Long(99)); <add> setField((Class<?>) null, "id", Long.valueOf(99)); <ide> } <ide> <ide> @Test <ide> public void getFieldWithNullTargetClass() throws Exception { <ide> public void setFieldWithNullNameAndNullType() throws Exception { <ide> exception.expect(IllegalArgumentException.class); <ide> exception.expectMessage(startsWith("Either name or type")); <del> setField(person, null, new Long(99), null); <add> setField(person, null, Long.valueOf(99), null); <ide> } <ide> <ide> @Test <ide> public void setFieldWithBogusName() throws Exception { <ide> exception.expect(IllegalArgumentException.class); <ide> exception.expectMessage(startsWith("Could not find field 'bogus'")); <del> setField(person, "bogus", new Long(99), long.class); <add> setField(person, "bogus", Long.valueOf(99), long.class); <ide> } <ide> <ide> @Test <ide> public void setFieldWithWrongType() throws Exception { <ide> exception.expect(IllegalArgumentException.class); <ide> exception.expectMessage(startsWith("Could not find field")); <del> setField(person, "id", new Long(99), String.class); <add> setField(person, "id", Long.valueOf(99), String.class); <ide> } <ide> <ide> @Test <ide> public void setFieldAndGetFieldViaCglibProxy() throws Exception { <ide> <ide> private static void assertSetFieldAndGetFieldBehavior(Person person) { <ide> // Set reflectively <del> setField(person, "id", new Long(99), long.class); <add> setField(person, "id", Long.valueOf(99), long.class); <ide> setField(person, "name", "Tom"); <del> setField(person, "age", new Integer(42)); <add> setField(person, "age", Integer.valueOf(42)); <ide> setField(person, "eyeColor", "blue", String.class); <ide> setField(person, "likesPets", Boolean.TRUE); <ide> setField(person, "favoriteNumber", PI, Number.class); <ide> <ide> // Get reflectively <del> assertEquals(new Long(99), getField(person, "id")); <add> assertEquals(Long.valueOf(99), getField(person, "id")); <ide> assertEquals("Tom", getField(person, "name")); <del> assertEquals(new Integer(42), getField(person, "age")); <add> assertEquals(Integer.valueOf(42), getField(person, "age")); <ide> assertEquals("blue", getField(person, "eyeColor")); <ide> assertEquals(Boolean.TRUE, getField(person, "likesPets")); <ide> assertEquals(PI, getField(person, "favoriteNumber")); <ide> public void getStaticFieldViaInstance() throws Exception { <ide> <ide> @Test <ide> public void invokeSetterMethodAndInvokeGetterMethodWithExplicitMethodNames() throws Exception { <del> invokeSetterMethod(person, "setId", new Long(1), long.class); <add> invokeSetterMethod(person, "setId", Long.valueOf(1), long.class); <ide> invokeSetterMethod(person, "setName", "Jerry", String.class); <del> invokeSetterMethod(person, "setAge", new Integer(33), int.class); <add> invokeSetterMethod(person, "setAge", Integer.valueOf(33), int.class); <ide> invokeSetterMethod(person, "setEyeColor", "green", String.class); <ide> invokeSetterMethod(person, "setLikesPets", Boolean.FALSE, boolean.class); <del> invokeSetterMethod(person, "setFavoriteNumber", new Integer(42), Number.class); <add> invokeSetterMethod(person, "setFavoriteNumber", Integer.valueOf(42), Number.class); <ide> <ide> assertEquals("ID (protected method in a superclass)", 1, person.getId()); <ide> assertEquals("name (private method)", "Jerry", person.getName()); <ide> assertEquals("age (protected method)", 33, person.getAge()); <ide> assertEquals("eye color (package private method)", "green", person.getEyeColor()); <ide> assertEquals("'likes pets' flag (protected method for a boolean)", false, person.likesPets()); <del> assertEquals("'favorite number' (protected method for a Number)", new Integer(42), person.getFavoriteNumber()); <add> assertEquals("'favorite number' (protected method for a Number)", Integer.valueOf(42), person.getFavoriteNumber()); <ide> <del> assertEquals(new Long(1), invokeGetterMethod(person, "getId")); <add> assertEquals(Long.valueOf(1), invokeGetterMethod(person, "getId")); <ide> assertEquals("Jerry", invokeGetterMethod(person, "getName")); <del> assertEquals(new Integer(33), invokeGetterMethod(person, "getAge")); <add> assertEquals(Integer.valueOf(33), invokeGetterMethod(person, "getAge")); <ide> assertEquals("green", invokeGetterMethod(person, "getEyeColor")); <ide> assertEquals(Boolean.FALSE, invokeGetterMethod(person, "likesPets")); <del> assertEquals(new Integer(42), invokeGetterMethod(person, "getFavoriteNumber")); <add> assertEquals(Integer.valueOf(42), invokeGetterMethod(person, "getFavoriteNumber")); <ide> } <ide> <ide> @Test <ide> public void invokeSetterMethodAndInvokeGetterMethodWithJavaBeanPropertyNames() throws Exception { <del> invokeSetterMethod(person, "id", new Long(99), long.class); <add> invokeSetterMethod(person, "id", Long.valueOf(99), long.class); <ide> invokeSetterMethod(person, "name", "Tom"); <del> invokeSetterMethod(person, "age", new Integer(42)); <add> invokeSetterMethod(person, "age", Integer.valueOf(42)); <ide> invokeSetterMethod(person, "eyeColor", "blue", String.class); <ide> invokeSetterMethod(person, "likesPets", Boolean.TRUE); <ide> invokeSetterMethod(person, "favoriteNumber", PI, Number.class); <ide> public void invokeSetterMethodAndInvokeGetterMethodWithJavaBeanPropertyNames() t <ide> assertEquals("'likes pets' flag (protected method for a boolean)", true, person.likesPets()); <ide> assertEquals("'favorite number' (protected method for a Number)", PI, person.getFavoriteNumber()); <ide> <del> assertEquals(new Long(99), invokeGetterMethod(person, "id")); <add> assertEquals(Long.valueOf(99), invokeGetterMethod(person, "id")); <ide> assertEquals("Tom", invokeGetterMethod(person, "name")); <del> assertEquals(new Integer(42), invokeGetterMethod(person, "age")); <add> assertEquals(Integer.valueOf(42), invokeGetterMethod(person, "age")); <ide> assertEquals("blue", invokeGetterMethod(person, "eyeColor")); <ide> assertEquals(Boolean.TRUE, invokeGetterMethod(person, "likesPets")); <ide> assertEquals(PI, invokeGetterMethod(person, "favoriteNumber")); <ide> public void invokeMethodSimulatingLifecycleEvents() { <ide> assertNull("text", component.getText()); <ide> <ide> // Simulate autowiring a configuration method <del> invokeMethod(component, "configure", new Integer(42), "enigma"); <del> assertEquals("number should have been configured", new Integer(42), component.getNumber()); <add> invokeMethod(component, "configure", Integer.valueOf(42), "enigma"); <add> assertEquals("number should have been configured", Integer.valueOf(42), component.getNumber()); <ide> assertEquals("text should have been configured", "enigma", component.getText()); <ide> <ide> // Simulate @PostConstruct life-cycle event <ide> public void invokeMethodWithIncompatibleArgumentTypes() { <ide> public void invokeMethodWithTooFewArguments() { <ide> exception.expect(IllegalStateException.class); <ide> exception.expectMessage(startsWith("Method not found")); <del> invokeMethod(component, "configure", new Integer(42)); <add> invokeMethod(component, "configure", Integer.valueOf(42)); <ide> } <ide> <ide> @Test <ide> public void invokeMethodWithTooManyArguments() { <ide> exception.expect(IllegalStateException.class); <ide> exception.expectMessage(startsWith("Method not found")); <del> invokeMethod(component, "configure", new Integer(42), "enigma", "baz", "quux"); <add> invokeMethod(component, "configure", Integer.valueOf(42), "enigma", "baz", "quux"); <ide> } <ide> <ide> @Test // SPR-14363 <ide> public void setFieldOnLegacyEntityWithSideEffectsInToString() { <ide> <ide> @Test // SPR-14363 <ide> public void invokeMethodOnLegacyEntityWithSideEffectsInToString() { <del> invokeMethod(entity, "configure", new Integer(42), "enigma"); <del> assertEquals("number should have been configured", new Integer(42), entity.getNumber()); <add> invokeMethod(entity, "configure", Integer.valueOf(42), "enigma"); <add> assertEquals("number should have been configured", Integer.valueOf(42), entity.getNumber()); <ide> assertEquals("text should have been configured", "enigma", entity.getText()); <ide> } <ide>
6
Ruby
Ruby
remove unused method expand_deps
596d26f8b430bfbe2250a7de90009c5f949997fd
<ide><path>Library/Homebrew/brew.h.rb <ide> def clean f <ide> end <ide> <ide> <del>def expand_deps ff <del> deps = [] <del> ff.deps.collect do |f| <del> deps += expand_deps(Formula.factory(f)) <del> end <del> deps << ff <del>end <del> <del> <ide> def prune <ide> $n=0 <ide> $d=0
1
Javascript
Javascript
add tests for stream3 buffering using cork
9d0b7d85b55c13fd49948094732c2bb55d0e92a1
<ide><path>test/parallel/test-stream3-cork-end.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add>const stream = require('stream'); <add>const Writable = stream.Writable; <add> <add>// Test the buffering behaviour of Writable streams. <add>// <add>// The call to cork() triggers storing chunks which are flushed <add>// on calling end() and the stream subsequently ended. <add>// <add>// node version target: 0.12 <add> <add>const expectedChunks = ['please', 'buffer', 'me', 'kindly']; <add>var inputChunks = expectedChunks.slice(0); <add>var seenChunks = []; <add>var seenEnd = false; <add> <add>var w = new Writable(); <add>// lets arrange to store the chunks <add>w._write = function(chunk, encoding, cb) { <add> // stream end event is not seen before the last write <add> assert.ok(!seenEnd); <add> // default encoding given none was specified <add> assert.equal(encoding, 'buffer'); <add> <add> seenChunks.push(chunk); <add> cb(); <add>}; <add>// lets record the stream end event <add>w.on('finish', () => { <add> seenEnd = true; <add>}); <add> <add>function writeChunks(remainingChunks, callback) { <add> var writeChunk = remainingChunks.shift(); <add> var writeState; <add> <add> if (writeChunk) { <add> setImmediate(() => { <add> writeState = w.write(writeChunk); <add> // we were not told to stop writing <add> assert.ok(writeState); <add> <add> writeChunks(remainingChunks, callback); <add> }); <add> } else { <add> callback(); <add> } <add>} <add> <add>// do an initial write <add>w.write('stuff'); <add>// the write was immediate <add>assert.equal(seenChunks.length, 1); <add>// reset the seen chunks <add>seenChunks = []; <add> <add>// trigger stream buffering <add>w.cork(); <add> <add>// write the bufferedChunks <add>writeChunks(inputChunks, () => { <add> // should not have seen anything yet <add> assert.equal(seenChunks.length, 0); <add> <add> // trigger flush and ending the stream <add> w.end(); <add> <add> // stream should not ended in current tick <add> assert.ok(!seenEnd); <add> <add> // buffered bytes should be seen in current tick <add> assert.equal(seenChunks.length, 4); <add> <add> // did the chunks match <add> for (var i = 0, l = expectedChunks.length; i < l; i++) { <add> var seen = seenChunks[i]; <add> // there was a chunk <add> assert.ok(seen); <add> <add> var expected = new Buffer(expectedChunks[i]); <add> // it was what we expected <add> assert.ok(seen.equals(expected)); <add> } <add> <add> setImmediate(() => { <add> // stream should have ended in next tick <add> assert.ok(seenEnd); <add> }); <add>}); <ide><path>test/parallel/test-stream3-cork-uncork.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add>const stream = require('stream'); <add>const Writable = stream.Writable; <add> <add>// Test the buffering behaviour of Writable streams. <add>// <add>// The call to cork() triggers storing chunks which are flushed <add>// on calling uncork() in the same tick. <add>// <add>// node version target: 0.12 <add> <add>const expectedChunks = ['please', 'buffer', 'me', 'kindly']; <add>var inputChunks = expectedChunks.slice(0); <add>var seenChunks = []; <add>var seenEnd = false; <add> <add>var w = new Writable(); <add>// lets arrange to store the chunks <add>w._write = function(chunk, encoding, cb) { <add> // default encoding given none was specified <add> assert.equal(encoding, 'buffer'); <add> <add> seenChunks.push(chunk); <add> cb(); <add>}; <add>// lets record the stream end event <add>w.on('finish', () => { <add> seenEnd = true; <add>}); <add> <add>function writeChunks(remainingChunks, callback) { <add> var writeChunk = remainingChunks.shift(); <add> var writeState; <add> <add> if (writeChunk) { <add> setImmediate(() => { <add> writeState = w.write(writeChunk); <add> // we were not told to stop writing <add> assert.ok(writeState); <add> <add> writeChunks(remainingChunks, callback); <add> }); <add> } else { <add> callback(); <add> } <add>} <add> <add>// do an initial write <add>w.write('stuff'); <add>// the write was immediate <add>assert.equal(seenChunks.length, 1); <add>// reset the chunks seen so far <add>seenChunks = []; <add> <add>// trigger stream buffering <add>w.cork(); <add> <add>// write the bufferedChunks <add>writeChunks(inputChunks, () => { <add> // should not have seen anything yet <add> assert.equal(seenChunks.length, 0); <add> <add> // trigger writing out the buffer <add> w.uncork(); <add> <add> // buffered bytes shoud be seen in current tick <add> assert.equal(seenChunks.length, 4); <add> <add> // did the chunks match <add> for (var i = 0, l = expectedChunks.length; i < l; i++) { <add> var seen = seenChunks[i]; <add> // there was a chunk <add> assert.ok(seen); <add> <add> var expected = new Buffer(expectedChunks[i]); <add> // it was what we expected <add> assert.ok(seen.equals(expected)); <add> } <add> <add> setImmediate(() => { <add> // the stream should not have been ended <add> assert.ok(!seenEnd); <add> }); <add>});
2
Javascript
Javascript
add known helpers to precompilation
7f1e74b95820d5698a1e9564e40bdbc394f89aca
<ide><path>packages/ember-handlebars/lib/ext.js <ide> Ember.Handlebars.Compiler.prototype.mustache = function(mustache) { <ide> */ <ide> Ember.Handlebars.precompile = function(string) { <ide> var ast = Handlebars.parse(string); <del> var options = { data: true, stringParams: true }; <add> <add> var options = { <add> knownHelpers: { <add> action: true, <add> unbound: true, <add> bindAttr: true, <add> template: true, <add> view: true <add> }, <add> data: true, <add> stringParams: true <add> }; <add> <ide> var environment = new Ember.Handlebars.Compiler().compile(ast, options); <ide> return new Ember.Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true); <ide> };
1
Javascript
Javascript
use strict in tests
92fdc1562df54f486a7927c37768c26870b320de
<ide><path>src/core/__tests__/ReactMultiChild-test.js <ide> * @jsx React.DOM <ide> * @emails react-core <ide> */ <add>"use strict"; <ide> <ide> var mocks = require('mocks'); <ide> <ide><path>src/dom/__tests__/Danger-test.js <ide> * @jsx React.DOM <ide> * @emails react-core <ide> */ <add>"use strict"; <ide> <ide> /*jslint evil: true */ <ide>
2
Go
Go
use timeouts instead of relying on runtime.gosched
fd672d59269d100acbb36abef4e4eddc1d30bdc7
<ide><path>pkg/locker/locker_test.go <ide> package locker <ide> <ide> import ( <del> "runtime" <ide> "testing" <add> "time" <ide> ) <ide> <ide> func TestLockCounter(t *testing.T) { <ide> func TestLockerLock(t *testing.T) { <ide> close(chDone) <ide> }() <ide> <del> runtime.Gosched() <add> chWaiting := make(chan struct{}) <add> go func() { <add> for range time.Tick(1 * time.Millisecond) { <add> if ctr.count() == 1 { <add> close(chWaiting) <add> break <add> } <add> } <add> }() <add> <add> select { <add> case <-chWaiting: <add> case <-time.After(3 * time.Second): <add> t.Fatal("timed out waiting for lock waiters to be incremented") <add> } <ide> <ide> select { <ide> case <-chDone: <ide> t.Fatal("lock should not have returned while it was still held") <ide> default: <ide> } <ide> <del> if ctr.count() != 1 { <del> t.Fatalf("expected waiters to be 1, got: %d", ctr.count()) <del> } <del> <ide> if err := l.Unlock("test"); err != nil { <ide> t.Fatal(err) <ide> } <del> runtime.Gosched() <ide> <ide> select { <ide> case <-chDone: <del> default: <del> // one more time just to be sure <del> runtime.Gosched() <del> select { <del> case <-chDone: <del> default: <del> t.Fatalf("lock should have completed") <del> } <add> case <-time.After(3 * time.Second): <add> t.Fatalf("lock should have completed") <ide> } <ide> <ide> if ctr.count() != 0 { <ide> func TestLockerUnlock(t *testing.T) { <ide> close(chDone) <ide> }() <ide> <del> runtime.Gosched() <del> <ide> select { <ide> case <-chDone: <del> default: <add> case <-time.After(3 * time.Second): <ide> t.Fatalf("lock should not be blocked") <ide> } <ide> }
1
Javascript
Javascript
introduce the ngmessages module and directives
0f4016c84a47e01a0fb993867dfd0a64828c089c
<ide><path>Gruntfile.js <ide> module.exports = function(grunt) { <ide> ngLocale: { <ide> files: { src: 'src/ngLocale/**/*.js' }, <ide> }, <add> ngMessages: { <add> files: { src: 'src/ngMessages/**/*.js' }, <add> }, <ide> ngMock: { <ide> files: { src: 'src/ngMock/**/*.js' }, <ide> }, <ide> module.exports = function(grunt) { <ide> dest: 'build/angular-resource.js', <ide> src: util.wrap(files['angularModules']['ngResource'], 'module') <ide> }, <add> messages: { <add> dest: 'build/angular-messages.js', <add> src: util.wrap(files['angularModules']['ngMessages'], 'module') <add> }, <ide> animate: { <ide> dest: 'build/angular-animate.js', <ide> src: util.wrap(files['angularModules']['ngAnimate'], 'module') <ide><path>angularFiles.js <ide> angularFiles = { <ide> 'ngCookies': [ <ide> 'src/ngCookies/cookies.js' <ide> ], <add> 'ngMessages': [ <add> 'src/ngMessages/messages.js' <add> ], <ide> 'ngResource': [ <ide> 'src/ngResource/resource.js' <ide> ], <ide> angularFiles = { <ide> 'test/auto/*.js', <ide> 'test/ng/**/*.js', <ide> 'test/ngAnimate/*.js', <add> 'test/ngMessages/*.js', <ide> 'test/ngCookies/*.js', <ide> 'test/ngResource/*.js', <ide> 'test/ngRoute/**/*.js', <ide> angularFiles = { <ide> <ide> angularFiles['angularSrcModules'] = [].concat( <ide> angularFiles['angularModules']['ngAnimate'], <add> angularFiles['angularModules']['ngMessages'], <ide> angularFiles['angularModules']['ngCookies'], <ide> angularFiles['angularModules']['ngResource'], <ide> angularFiles['angularModules']['ngRoute'], <ide><path>src/ngAnimate/animate.js <ide> * | {@link ng.directive:ngClass#usage_animations ngClass} | add and remove (the CSS class(es) present) | <ide> * | {@link ng.directive:ngShow#usage_animations ngShow} & {@link ng.directive:ngHide#usage_animations ngHide} | add and remove (the ng-hide class value) | <ide> * | {@link ng.directive:form#usage_animations form} & {@link ng.directive:ngModel#usage_animations ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) | <add> * | {@link ngMessages.directive:ngMessage#usage_animations ngMessages} | add and remove (ng-active & ng-inactive) | <add> * | {@link ngMessages.directive:ngMessage#usage_animations ngMessage} | enter and leave | <ide> * <ide> * You can find out more information about animations upon visiting each directive page. <ide> * <ide><path>src/ngMessages/messages.js <add>'use strict'; <add> <add>/** <add> * @ngdoc module <add> * @name ngMessages <add> * @description <add> * <add> * The `ngMessages` module provides enhanced support for displaying messages within templates <add> * (typically within forms or when rendering message objects that return key/value data). <add> * Instead of relying on JavaScript code and/or complex ng-if statements within your form template to <add> * show and hide error messages specific to the state of an input field, the `ngMessages` and <add> * `ngMessage` directives are designed to handle the complexity, inheritance and priority <add> * sequencing based on the order of how the messages are defined in the template. <add> * <add> * Currently, the ngMessages module only contains the code for the `ngMessages` <add> * and `ngMessage` directives. <add> * <add> * # Usage <add> * The `ngMessages` directive listens on a key/value collection which is set on the ngMessages attribute. <add> * Since the {@link ngModel ngModel} directive exposes an `$error` object, this error object can be <add> * used with `ngMessages` to display control error messages in an easier way than with just regular angular <add> * template directives. <add> * <add> * ```html <add> * <form name="myForm"> <add> * <input type="text" ng-model="field" name="myField" required minlength="5" /> <add> * <div ng-messages="myForm.myField.$error"> <add> * <div ng-message="required">You did not enter a field</div> <add> * <div ng-message="minlength">The value entered is too short</div> <add> * </div> <add> * </form> <add> * ``` <add> * <add> * Now whatever key/value entries are present within the provided object (in this case `$error`) then <add> * the ngMessages directive will render the inner first ngMessage directive (depending if the key values <add> * match the attribute value present on each ngMessage directive). In other words, if your errors <add> * object contains the following data: <add> * <add> * ```javascript <add> * <!-- keep in mind that ngModel automatically sets these error flags --> <add> * myField.$error = { minlength : true, required : false }; <add> * ``` <add> * <add> * Then the `required` message will be displayed first. When required is false then the `minlength` message <add> * will be displayed right after (since these messages are ordered this way in the template HTML code). <add> * The prioritization of each message is determined by what order they're present in the DOM. <add> * Therefore, instead of having custom JavaScript code determine the priority of what errors are <add> * present before others, the presentation of the errors are handled within the template. <add> * <add> * By default, ngMessages will only display one error at a time. However, if you wish to display all <add> * messages then the `ng-messages-multiple` attribute flag can be used on the element containing the <add> * ngMessages directive to make this happen. <add> * <add> * ```html <add> * <div ng-messages="myForm.myField.$error" ng-messages-multiple>...</div> <add> * ``` <add> * <add> * ## Reusing and Overriding Messages <add> * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline <add> * template. This allows for generic collection of messages to be reused across multiple parts of an <add> * application. <add> * <add> * ```html <add> * <script type="text/ng-template" id="error-messages"> <add> * <div ng-message="required">This field is required</div> <add> * <div ng-message="minlength">This field is too short</div> <add> * </script> <add> * <div ng-messages="myForm.myField.$error" ng-messages-include="error-messages"></div> <add> * ``` <add> * <add> * However, including generic messages may not be useful enough to match all input fields, therefore, <add> * `ngMessages` provides the ability to override messages defined in the remote template by redefining <add> * then within the directive container. <add> * <add> * ```html <add> * <!-- a generic template of error messages known as "my-custom-messages" --> <add> * <script type="text/ng-template" id="my-custom-messages"> <add> * <div ng-message="required">This field is required</div> <add> * <div ng-message="minlength">This field is too short</div> <add> * </script> <add> * <add> * <form name="myForm"> <add> * <input type="email" <add> * id="email" <add> * name="myEmail" <add> * ng-model="email" <add> * minlength="5" <add> * required /> <add> * <add> * <div ng-messages="myForm.myEmail.$error" ng-messages-include="my-custom-messages"> <add> * <!-- this required message has overridden the template message --> <add> * <div ng-message="required">You did not enter your email address</div> <add> * <add> * <!-- this is a brand new message and will appear last in the prioritization --> <add> * <div ng-message="email">Your email address is invalid</div> <add> * </div> <add> * </form> <add> * ``` <add> * <add> * In the example HTML code above the message that is set on required will override the corresponding <add> * required message defined within the remote template. Therefore, with particular input fields (such <add> * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied <add> * while more generic messages can be used to handle other, more general input errors. <add> * <add> * ## Animations <add> * If the `ngAnimate` module is active within the application then both the `ngMessages` and <add> * `ngMessage` directives will trigger animations whenever any messages are added and removed <add> * from the DOM by the `ngMessages` directive. <add> * <add> * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS <add> * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no <add> * animations present. Therefore, CSS transitions and keyframes as well as JavaScript animations can <add> * hook into the animations whenever these classes are added/removed. <add> * <add> * Let's say that our HTML code for our messages container looks like so: <add> * <add> * ```html <add> * <div ng-messages="myMessages" class="my-messages"> <add> * <div ng-message="alert" class="some-message">...</div> <add> * <div ng-message="fail" class="some-message">...</div> <add> * </div> <add> * ``` <add> * <add> * Then the CSS animation code for the message container looks like so: <add> * <add> * ```css <add> * .my-messages { <add> * transition:1s linear all; <add> * } <add> * .my-messages.ng-active { <add> * // messages are visible <add> * } <add> * .my-messages.ng-inactive { <add> * // messages are hidden <add> * } <add> * ``` <add> * <add> * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter <add> * and leave animation is triggered for each particular element bound to the `ngMessage` directive. <add> * <add> * Therefore, the CSS code for the inner messages looks like so: <add> * <add> * ```css <add> * .some-message { <add> * transition:1s linear all; <add> * } <add> * <add> * .some-message.ng-enter {} <add> * .some-message.ng-enter.ng-enter-active {} <add> * <add> * .some-message.ng-leave {} <add> * .some-message.ng-leave.ng-leave-active {} <add> * ``` <add> * <add> * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate. <add> */ <add>angular.module('ngMessages', []) <add> <add> /** <add> * @ngdoc directive <add> * @module ngMessages <add> * @name ngMessages <add> * @restrict AE <add> * <add> * @description <add> * # Overview <add> * `ngMessages` is a directive that is designed to show and hide messages based on the state <add> * of a key/value object that is listens on. The directive itself compliments error message <add> * reporting with the `ngModel` $error object (which stores a key/value state of validation errors). <add> * <add> * `ngMessages` manages the state of internal messages within its container element. The internal <add> * messages use the `ngMessage` directive and will be inserted/removed from the page depending <add> * on if they're present within the key/value object. By default, only one message will be displayed <add> * at a time and this depends on the prioritization of the messages within the template. (This can <add> * be changed by using the ng-messages-multiple on the directive container.) <add> * <add> * A remote template can also be used to promote message reuseability and messages can also be <add> * overridden. <add> * <add> * {@link ngMessages.directive:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. <add> * <add> * @usage <add> * ```html <add> * <!-- using attribute directives --> <add> * <ANY ng-messages="expression"> <add> * <ANY ng-message="keyValue1">...</ANY> <add> * <ANY ng-message="keyValue2">...</ANY> <add> * <ANY ng-message="keyValue3">...</ANY> <add> * </ANY> <add> * <add> * <!-- or by using element directives --> <add> * <ng-messages for="expression"> <add> * <ng-message when="keyValue1">...</ng-message> <add> * <ng-message when="keyValue2">...</ng-message> <add> * <ng-message when="keyValue3">...</ng-message> <add> * </ng-messages> <add> * ``` <add> * <add> * @param {string} ngMessages an angular expression evaluating to a key/value object <add> * (this is typically the $error object on an ngModel instance). <add> * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true <add> * @param {string=} ngMessagesInclude|include when set, the specified template will be included into the ng-messages container <add> * <add> * @example <add> * <example name="ngMessages-directive" module="ngMessagesExample" <add> * deps="angular-messages.js" <add> * animations="true" fixBase="true"> <add> * <file name="index.html"> <add> * <form name="myForm"> <add> * <label>Enter your name:</label> <add> * <input type="text" <add> * name="myName" <add> * ng-model="name" <add> * ng-minlength="5" <add> * ng-maxlength="20" <add> * required /> <add> * <add> * <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre> <add> * <add> * <div ng-messages="myForm.myName.$error" style="color:maroon"> <add> * <div ng-message="required">You did not enter a field</div> <add> * <div ng-message="minlength">Your field is too short</div> <add> * <div ng-message="maxlength">Your field is too long</div> <add> * </div> <add> * </form> <add> * </file> <add> * <file name="script.js"> <add> * angular.module('ngMessagesExample', ['ngMessages']); <add> * </file> <add> * </example> <add> */ <add> .directive('ngMessages', ['$compile', '$animate', '$http', '$templateCache', <add> function($compile, $animate, $http, $templateCache) { <add> var ACTIVE_CLASS = 'ng-active'; <add> var INACTIVE_CLASS = 'ng-inactive'; <add> <add> return { <add> restrict: 'AE', <add> controller: function($scope) { <add> this.$renderNgMessageClasses = angular.noop; <add> <add> var messages = []; <add> this.registerMessage = function(index, message) { <add> for(var i = 0; i < messages.length; i++) { <add> if(messages[i].type == message.type) { <add> if(index != i) { <add> var temp = messages[index]; <add> messages[index] = messages[i]; <add> if(index < messages.length) { <add> messages[i] = temp; <add> } else { <add> messages.splice(0, i); //remove the old one (and shift left) <add> } <add> } <add> return; <add> } <add> } <add> messages.splice(index, 0, message); //add the new one (and shift right) <add> }; <add> <add> this.renderMessages = function(values, multiple) { <add> values = values || {}; <add> <add> var found; <add> angular.forEach(messages, function(message) { <add> if((!found || multiple) && truthyVal(values[message.type])) { <add> message.attach(); <add> found = true; <add> } else { <add> message.detach(); <add> } <add> }); <add> <add> this.renderElementClasses(found); <add> <add> function truthyVal(value) { <add> return value !== null && value !== false && value; <add> } <add> }; <add> }, <add> require: 'ngMessages', <add> link: function($scope, element, $attrs, ctrl) { <add> ctrl.renderElementClasses = function(bool) { <add> bool ? $animate.setClass(element, ACTIVE_CLASS, INACTIVE_CLASS) <add> : $animate.setClass(element, INACTIVE_CLASS, ACTIVE_CLASS); <add> }; <add> <add> //JavaScript treats empty strings as false, but ng-message-multiple by itself is an empty string <add> var multiple = angular.isString($attrs.ngMessagesMultiple) || <add> angular.isString($attrs.multiple); <add> <add> var cachedValues, watchAttr = $attrs.ngMessages || $attrs['for']; //for is a reserved keyword <add> $scope.$watchCollection(watchAttr, function(values) { <add> cachedValues = values; <add> ctrl.renderMessages(values, multiple); <add> }); <add> <add> var tpl = $attrs.ngMessagesInclude || $attrs.include; <add> if(tpl) { <add> $http.get(tpl, { cache: $templateCache }) <add> .success(function processTemplate(html) { <add> var after, container = angular.element('<div/>').html(html); <add> angular.forEach(container.children(), function(elm) { <add> elm = angular.element(elm); <add> after ? after.after(elm) <add> : element.prepend(elm); //start of the container <add> after = elm; <add> $compile(elm)($scope); <add> }); <add> ctrl.renderMessages(cachedValues, multiple); <add> }); <add> } <add> } <add> }; <add> }]) <add> <add> <add> /** <add> * @ngdoc directive <add> * @name ngMessage <add> * @restrict AE <add> * @scope <add> * <add> * @description <add> * # Overview <add> * `ngMessage` is a directive with the purpose to show and hide a particular message. <add> * For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element <add> * must be situated since it determines which messages are visible based on the state <add> * of the provided key/value map that `ngMessages` listens on. <add> * <add> * @usage <add> * ```html <add> * <!-- using attribute directives --> <add> * <ANY ng-messages="expression"> <add> * <ANY ng-message="keyValue1">...</ANY> <add> * <ANY ng-message="keyValue2">...</ANY> <add> * <ANY ng-message="keyValue3">...</ANY> <add> * </ANY> <add> * <add> * <!-- or by using element directives --> <add> * <ng-messages for="expression"> <add> * <ng-message when="keyValue1">...</ng-message> <add> * <ng-message when="keyValue2">...</ng-message> <add> * <ng-message when="keyValue3">...</ng-message> <add> * </ng-messages> <add> * ``` <add> * <add> * {@link ngMessages.directive:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`. <add> * <add> * @param {string} ngMessage a string value corresponding to the message key. <add> */ <add> .directive('ngMessage', ['$animate', function($animate) { <add> var COMMENT_NODE = 8; <add> return { <add> require: '^ngMessages', <add> transclude: 'element', <add> terminal: true, <add> restrict: 'AE', <add> link: function($scope, $element, $attrs, ngMessages, $transclude) { <add> var index, element; <add> <add> var commentNode = $element[0]; <add> var parentNode = commentNode.parentNode; <add> for(var i = 0, j = 0; i < parentNode.childNodes.length; i++) { <add> var node = parentNode.childNodes[i]; <add> if(node.nodeType == COMMENT_NODE && node.nodeValue.indexOf('ngMessage') >= 0) { <add> if(node === commentNode) { <add> index = j; <add> break; <add> } <add> j++; <add> } <add> } <add> <add> ngMessages.registerMessage(index, { <add> type : $attrs.ngMessage || $attrs.when, <add> attach : function() { <add> if(!element) { <add> $transclude($scope, function(clone) { <add> $animate.enter(clone, null, $element); <add> element = clone; <add> }); <add> } <add> }, <add> detach : function(now) { <add> if(element) { <add> $animate.leave(element); <add> element = null; <add> } <add> } <add> }); <add> } <add> }; <add> }]); <ide><path>test/ngMessages/messagesSpec.js <add>'use strict'; <add> <add>describe('ngMessages', function() { <add> <add> beforeEach(module('ngMessages')); <add> <add> function they(msg, vals, spec, focus) { <add> forEach(vals, function(val, key) { <add> var m = msg.replace('$prop', key); <add> (focus ? iit : it)(m, function() { <add> spec(val); <add> }); <add> }); <add> } <add> <add> function tthey(msg, vals, spec) { <add> they(msg, vals, spec, true); <add> } <add> <add> function s(str) { <add> return str.replace(/\s+/g,''); <add> } <add> <add> var element; <add> afterEach(function() { <add> dealoc(element); <add> }); <add> <add> it('should render based off of a hashmap collection', inject(function($rootScope, $compile) { <add> element = $compile('<div ng-messages="col">' + <add> ' <div ng-message="val">Message is set</div>' + <add> '</div>')($rootScope); <add> $rootScope.$digest(); <add> <add> expect(element.text()).not.toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { val : true }; <add> }); <add> <add> expect(element.text()).toContain('Message is set'); <add> })); <add> <add> it('should use the data attribute when an element directive is used', <add> inject(function($rootScope, $compile) { <add> <add> element = $compile('<ng-messages for="col">' + <add> ' <ng-message when="val">Message is set</div>' + <add> '</ng-messages>')($rootScope); <add> $rootScope.$digest(); <add> <add> expect(element.text()).not.toContain('Message is set'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { val : true }; <add> }); <add> <add> expect(element.text()).toContain('Message is set'); <add> })); <add> <add> they('should render empty when $prop is used as a collection value', <add> { 'null': null, <add> 'false': false, <add> '0': 0, <add> '[]': [], <add> '[{}]': [{}], <add> '': '', <add> '{ val2 : true }': { val2 : true } }, <add> function(prop) { <add> inject(function($rootScope, $compile) { <add> element = $compile('<div ng-messages="col">' + <add> ' <div ng-message="val">Message is set</div>' + <add> '</div>')($rootScope); <add> $rootScope.$digest(); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = prop; <add> }); <add> expect(element.text()).not.toContain('Message is set'); <add> }); <add> }); <add> <add> they('should insert and remove matching inner elements when $prop is used as a value', <add> { 'true': true, <add> '1': 1, <add> '{}': {}, <add> '[]': [], <add> '[null]': [null] }, <add> function(prop) { <add> inject(function($rootScope, $compile) { <add> <add> element = $compile('<div ng-messages="col">' + <add> ' <div ng-message="blue">This message is blue</div>' + <add> ' <div ng-message="red">This message is red</div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = {}; <add> }); <add> <add> expect(element.children().length).toBe(0); <add> expect(trim(element.text())).toEqual(''); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { <add> blue : true, <add> red : false <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual('This message is blue'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { <add> red : prop <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual('This message is red'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = null; <add> }); <add> expect(element.children().length).toBe(0); <add> expect(trim(element.text())).toEqual(''); <add> <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { <add> blue : 0, <add> red : null <add> }; <add> }); <add> <add> expect(element.children().length).toBe(0); <add> expect(trim(element.text())).toEqual(''); <add> }); <add> }); <add> <add> it('should display the elements in the order defined in the DOM', <add> inject(function($rootScope, $compile) { <add> <add> element = $compile('<div ng-messages="col">' + <add> ' <div ng-message="one">Message#one</div>' + <add> ' <div ng-message="two">Message#two</div>' + <add> ' <div ng-message="three">Message#three</div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { <add> three : true, <add> one : true, <add> two : true <add> }; <add> }); <add> <add> angular.forEach(['one','two','three'], function(key) { <add> expect(s(element.text())).toEqual('Message#' + key); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col[key] = false; <add> }); <add> }); <add> <add> expect(s(element.text())).toEqual(''); <add> })); <add> <add> it('should add ng-active/ng-inactive CSS classes to the element when errors are/aren\'t displayed', <add> inject(function($rootScope, $compile) { <add> <add> element = $compile('<div ng-messages="col">' + <add> ' <div ng-message="ready">This message is ready</div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = {}; <add> }); <add> <add> expect(element.hasClass('ng-active')).toBe(false); <add> expect(element.hasClass('ng-inactive')).toBe(true); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { ready : true }; <add> }); <add> <add> expect(element.hasClass('ng-active')).toBe(true); <add> expect(element.hasClass('ng-inactive')).toBe(false); <add> })); <add> <add> it('should render animations when the active/inactive classes are added/removed', function() { <add> module('ngAnimate'); <add> module('ngAnimateMock'); <add> inject(function($rootScope, $compile, $animate) { <add> element = $compile('<div ng-messages="col">' + <add> ' <div ng-message="ready">This message is ready</div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = {}; <add> }); <add> <add> var event = $animate.queue.pop(); <add> expect(event.event).toBe('setClass'); <add> expect(event.args[1]).toBe('ng-inactive'); <add> expect(event.args[2]).toBe('ng-active'); <add> <add> $rootScope.$apply(function() { <add> $rootScope.col = { ready : true }; <add> }); <add> <add> event = $animate.queue.pop(); <add> expect(event.event).toBe('setClass'); <add> expect(event.args[1]).toBe('ng-active'); <add> expect(event.args[2]).toBe('ng-inactive'); <add> }); <add> }); <add> <add> describe('when including templates', function() { <add> they('should load a remote template using $prop', <add> {'<div ng-messages ng-messages-include="...">': <add> '<div ng-messages="data" ng-messages-include="abc.html"></div>', <add> '<ng-messages include="...">' : <add> '<ng-messages for="data" include="abc.html"></ng-messages>'}, <add> function(html) { <add> inject(function($compile, $rootScope, $templateCache) { <add> $templateCache.put('abc.html', '<div ng-message="a">A</div>' + <add> '<div ng-message="b">B</div>' + <add> '<div ng-message="c">C</div>'); <add> <add> element = $compile(html)($rootScope); <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'a': 1, <add> 'b': 2, <add> 'c': 3 <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("A"); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'c': 3 <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("C"); <add> }); <add> }); <add> <add> it('should cache the template after download', <add> inject(function($rootScope, $compile, $templateCache, $httpBackend) { <add> <add> $httpBackend.expect('GET', 'tpl').respond(201, 'abc'); <add> <add> expect($templateCache.get('tpl')).toBeUndefined(); <add> <add> element = $compile('<div ng-messages="data" ng-messages-include="tpl"></div>')($rootScope); <add> <add> $rootScope.$digest(); <add> $httpBackend.flush(); <add> <add> expect($templateCache.get('tpl')).toBeDefined(); <add> })); <add> <add> it('should re-render the messages after download without an extra digest', <add> inject(function($rootScope, $compile, $httpBackend) { <add> <add> $httpBackend.expect('GET', 'my-messages').respond(201,'<div ng-message="required">You did not enter a value</div>'); <add> <add> element = $compile('<div ng-messages="data" ng-messages-include="my-messages">' + <add> ' <div ng-message="failed">Your value is that of failure</div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.data = { <add> required : true, <add> failed : true <add> }; <add> <add> $rootScope.$digest(); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("Your value is that of failure"); <add> <add> $httpBackend.flush(); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("You did not enter a value"); <add> })); <add> <add> it('should allow for overriding the remote template messages within the element', <add> inject(function($compile, $rootScope, $templateCache) { <add> <add> $templateCache.put('abc.html', '<div ng-message="a">A</div>' + <add> '<div ng-message="b">B</div>' + <add> '<div ng-message="c">C</div>'); <add> <add> element = $compile('<div ng-messages="data" ng-messages-include="abc.html">' + <add> ' <div ng-message="a">AAA</div>' + <add> ' <div ng-message="c">CCC</div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'a': 1, <add> 'b': 2, <add> 'c': 3 <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("AAA"); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'b': 2, <add> 'c': 3 <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("B"); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'c': 3 <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("CCC"); <add> })); <add> <add> it('should retain the order of the remote template\'s messages when overriding within the element', <add> inject(function($compile, $rootScope, $templateCache) { <add> <add> $templateCache.put('abc.html', '<div ng-message="c">C</div>' + <add> '<div ng-message="a">A</div>' + <add> '<div ng-message="b">B</div>'); <add> <add> element = $compile('<div ng-messages="data" ng-messages-include="abc.html">' + <add> ' <div ng-message="a">AAA</div>' + <add> ' <div ng-message="c">CCC</div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'a': 1, <add> 'b': 2, <add> 'c': 3 <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("CCC"); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'a': 1, <add> 'b': 2, <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("AAA"); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'b': 3 <add> }; <add> }); <add> <add> expect(element.children().length).toBe(1); <add> expect(trim(element.text())).toEqual("B"); <add> })); <add> <add> }); <add> <add> describe('when multiple', function() { <add> they('should show all truthy messages when the $prop attr is present', <add> { 'multiple' : 'multiple', <add> 'ng-messages-multiple' : 'ng-messages-multiple' }, <add> function(prop) { <add> inject(function($rootScope, $compile) { <add> element = $compile('<div ng-messages="data" ' + prop + '>' + <add> ' <div ng-message="one">1</div>' + <add> ' <div ng-message="two">2</div>' + <add> ' <div ng-message="three">3</div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'one': true, <add> 'two': false, <add> 'three': true <add> }; <add> }); <add> <add> expect(element.children().length).toBe(2); <add> expect(s(element.text())).toContain("13"); <add> }); <add> }); <add> <add> it('should render all truthy messages from a remote template', <add> inject(function($rootScope, $compile, $templateCache) { <add> <add> $templateCache.put('xyz.html', '<div ng-message="x">X</div>' + <add> '<div ng-message="y">Y</div>' + <add> '<div ng-message="z">Z</div>'); <add> <add> element = $compile('<div ng-messages="data" ' + <add> 'ng-messages-multiple="true" ' + <add> 'ng-messages-include="xyz.html"></div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'x': 'a', <add> 'y': null, <add> 'z': true <add> }; <add> }); <add> <add> expect(element.children().length).toBe(2); <add> expect(s(element.text())).toEqual("XZ"); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data.y = {}; <add> }); <add> <add> expect(element.children().length).toBe(3); <add> expect(s(element.text())).toEqual("XYZ"); <add> })); <add> <add> it('should render and override all truthy messages from a remote template', <add> inject(function($rootScope, $compile, $templateCache) { <add> <add> $templateCache.put('xyz.html', '<div ng-message="x">X</div>' + <add> '<div ng-message="y">Y</div>' + <add> '<div ng-message="z">Z</div>'); <add> <add> element = $compile('<div ng-messages="data" ' + <add> 'ng-messages-multiple="true" ' + <add> 'ng-messages-include="xyz.html">' + <add> '<div ng-message="y">YYY</div>' + <add> '<div ng-message="z">ZZZ</div>' + <add> '</div>')($rootScope); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data = { <add> 'x': 'a', <add> 'y': null, <add> 'z': true <add> }; <add> }); <add> <add> expect(element.children().length).toBe(2); <add> expect(s(element.text())).toEqual("XZZZ"); <add> <add> $rootScope.$apply(function() { <add> $rootScope.data.y = {}; <add> }); <add> <add> expect(element.children().length).toBe(3); <add> expect(s(element.text())).toEqual("XYYYZZZ"); <add> })); <add> }); <add>});
5
Python
Python
fix fortran kind detection for aarch64 & s390x
e0c126dfc7b19f7681380b413e4793e94a85b065
<ide><path>numpy/f2py/crackfortran.py <ide> def _selected_real_kind_func(p, r=0, radix=0): <ide> if p < 16: <ide> return 8 <ide> machine = platform.machine().lower() <del> if machine.startswith('power') or machine.startswith('ppc64'): <add> if machine.startswith(('aarch64', 'power', 'ppc64', 's390x')): <ide> if p <= 20: <ide> return 16 <ide> else:
1
Python
Python
change signature of base class (see comment)
53f9917b04b184341607d4d44c27957a3edd6ebd
<ide><path>libcloud/compute/base.py <ide> def create_volume(self, size, name, location=None, snapshot=None): <ide> (optional) <ide> :type location: :class:`.NodeLocation` <ide> <del> :param snapshot: Name of snapshot from which to create the new <del> volume. (optional) <del> :type snapshot: ``str`` <add> :param snapshot: Snapshot from which to create the new <add> volume. (optional) <add> :type snapshot: :class:`.VolumeSnapshot` <ide> <ide> :return: The newly created volume. <ide> :rtype: :class:`StorageVolume`
1
Python
Python
switch convolutional layers to new regularization
8ef90a03b37b03a3d4b88b958462fa200be99d7b
<ide><path>keras/layers/convolutional.py <ide> class Convolution1D(Layer): <ide> def __init__(self, nb_filter, stack_size, filter_length, <ide> init='uniform', activation='linear', weights=None, <ide> image_shape=None, border_mode='valid', subsample_length=1, <del> W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None): <add> W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None): <ide> <ide> nb_row = 1 <ide> nb_col = filter_length <ide> def __init__(self, nb_filter, stack_size, filter_length, <ide> <ide> self.params = [self.W, self.b] <ide> <del> self.regularizers = [W_regularizer, b_regularizer] <add> self.regularizers = [] <add> if W_regularizer: <add> W_regularizer.set_param(self.W) <add> self.regularizers.append(W_regularizer) <add> if b_regularizer: <add> b_regularizer.set_param(self.b) <add> self.regularizers.append(b_regularizer) <add> if activity_regularizer: <add> activity_regularizer.set_layer(self) <add> self.regularizers.append(activity_regularizer) <add> <ide> self.constraints = [W_constraint, b_constraint] <ide> <ide> if weights is not None: <ide> class Convolution2D(Layer): <ide> def __init__(self, nb_filter, stack_size, nb_row, nb_col, <ide> init='glorot_uniform', activation='linear', weights=None, <ide> image_shape=None, border_mode='valid', subsample=(1,1), <del> W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None): <add> W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None): <ide> super(Convolution2D,self).__init__() <ide> <ide> self.init = initializations.get(init) <ide> def __init__(self, nb_filter, stack_size, nb_row, nb_col, <ide> <ide> self.params = [self.W, self.b] <ide> <del> self.regularizers = [W_regularizer, b_regularizer] <add> self.regularizers = [] <add> if W_regularizer: <add> W_regularizer.set_param(self.W) <add> self.regularizers.append(W_regularizer) <add> if b_regularizer: <add> b_regularizer.set_param(self.b) <add> self.regularizers.append(b_regularizer) <add> if activity_regularizer: <add> activity_regularizer.set_layer(self) <add> self.regularizers.append(activity_regularizer) <add> <ide> self.constraints = [W_constraint, b_constraint] <ide> <ide> if weights is not None:
1
Ruby
Ruby
remove unused code in fakerecord
8f1d11027171202a78ef784459d43cb11438ca92
<ide><path>activerecord/test/cases/arel/support/fake_record.rb <ide> # frozen_string_literal: true <ide> <ide> require "active_support/core_ext/enumerable" <del> <ide> require "date" <add> <ide> module FakeRecord <ide> class Column < Struct.new(:name, :type) <ide> end <ide> class Connection <ide> attr_reader :tables <ide> attr_accessor :visitor <ide> <del> def initialize(visitor = nil) <add> def initialize <ide> @tables = %w{ users photos developers products} <ide> @columns = { <ide> "users" => [ <ide> def initialize(visitor = nil) <ide> "users" => "id", <ide> "products" => "id" <ide> } <del> @visitor = visitor <add> @visitor = Arel::Visitors::ToSql.new(self) <ide> end <ide> <ide> def columns_hash(table_name) <ide> def quote(thing) <ide> end <ide> <ide> class ConnectionPool <del> class Spec < Struct.new(:adapter, keyword_init: true) <del> end <del> <del> attr_reader :spec, :connection <add> attr_reader :connection <ide> <ide> def initialize <del> @spec = Spec.new(adapter: "america") <ide> @connection = Connection.new <del> @connection.visitor = Arel::Visitors::ToSql.new(connection) <ide> end <ide> <ide> def with_connection
1
Mixed
Go
allow extra lines in /etc/hosts
68e48b65a64df10fc797cbaa89d6caa2188eadc9
<ide><path>daemon/container.go <ide> func (container *Container) buildHostsFiles(IP string) error { <ide> extraContent[alias] = child.NetworkSettings.IPAddress <ide> } <ide> <add> for _, extraHost := range container.hostConfig.ExtraHosts { <add> parts := strings.Split(extraHost, ":") <add> extraContent[parts[0]] = parts[1] <add> } <add> <ide> return etchosts.Build(container.HostsPath, IP, container.Config.Hostname, container.Config.Domainname, &extraContent) <ide> } <ide> <ide><path>docs/man/docker-run.1.md <ide> docker-run - Run a command in a new container <ide> # SYNOPSIS <ide> **docker run** <ide> [**-a**|**--attach**[=*[]*]] <add>[**--add-host**[=*[]*]] <ide> [**-c**|**--cpu-shares**[=*0*]] <ide> [**--cap-add**[=*[]*]] <ide> [**--cap-drop**[=*[]*]] <ide> error. It can even pretend to be a TTY (this is what most commandline <ide> executables expect) and pass along signals. The **-a** option can be set for <ide> each of stdin, stdout, and stderr. <ide> <add>**--add-host**=*hostname*:*ip* <add> Add a line to /etc/hosts. The format is hostname:ip. The **--add-host** <add>option can be set multiple times. <add> <ide> **-c**, **--cpu-shares**=0 <ide> CPU shares in relative weight. You can increase the priority of a container <ide> with the -c option. By default, all containers run at the same priority and get <ide><path>docs/sources/reference/commandline/cli.md <ide> removed before the image is removed. <ide> Run a command in a new container <ide> <ide> -a, --attach=[] Attach to STDIN, STDOUT or STDERR. <add> --add-host=[] Add a custom host-to-IP mapping (host:ip) <ide> -c, --cpu-shares=0 CPU shares (relative weight) <ide> --cap-add=[] Add Linux capabilities <ide> --cap-drop=[] Drop Linux capabilities <ide><path>docs/sources/reference/run.md <ide> example, `docker run ubuntu:14.04`. <ide> 'none': no networking for this container <ide> 'container:<name|id>': reuses another container network stack <ide> 'host': use the host network stack inside the container <add> --add-host="" : Add a line to /etc/hosts (host:IP) <ide> <ide> By default, all containers have networking enabled and they can make any <ide> outgoing connections. The operator can completely disable networking <ide> running the `redis-cli` command and connecting to the Redis server over the <ide> $ # use the redis container's network stack to access localhost <ide> $ sudo docker run --rm -ti --net container:redis example/redis-cli -h 127.0.0.1 <ide> <add>### Managing /etc/hosts <add> <add>Your container will have lines in `/etc/hosts` which define the hostname of the <add>container itself as well as `localhost` and a few other common things. The <add>`--add-host` flag can be used to add additional lines to `/etc/hosts`. <add> <add> $ /docker run -ti --add-host db-static:86.75.30.9 ubuntu cat /etc/hosts <add> 172.17.0.22 09d03f76bf2c <add> fe00::0 ip6-localnet <add> ff00::0 ip6-mcastprefix <add> ff02::1 ip6-allnodes <add> ff02::2 ip6-allrouters <add> 127.0.0.1 localhost <add> ::1 localhost ip6-localhost ip6-loopback <add> 86.75.30.9 db-static <add> <ide> ## Clean Up (–-rm) <ide> <ide> By default a container's file system persists even after the container <ide><path>integration-cli/docker_cli_run_test.go <ide> func TestDnsOptionsBasedOnHostResolvConf(t *testing.T) { <ide> logDone("run - dns options based on host resolv.conf") <ide> } <ide> <add>func TestRunAddHost(t *testing.T) { <add> defer deleteAllContainers() <add> cmd := exec.Command(dockerBinary, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts") <add> <add> out, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err, out) <add> } <add> <add> actual := strings.Trim(out, "\r\n") <add> if actual != "86.75.30.9\textra" { <add> t.Fatalf("expected '86.75.30.9\textra', but says: '%s'", actual) <add> } <add> <add> logDone("run - add-host option") <add>} <add> <ide> // Regression test for #6983 <ide> func TestAttachStdErrOnlyTTYMode(t *testing.T) { <ide> cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stderr", "busybox", "true") <ide><path>opts/opts.go <ide> func validateDomain(val string) (string, error) { <ide> return "", fmt.Errorf("%s is not a valid domain", val) <ide> } <ide> <add>func ValidateExtraHost(val string) (string, error) { <add> arr := strings.Split(val, ":") <add> if len(arr) != 2 || len(arr[0]) == 0 { <add> return "", fmt.Errorf("bad format for add-host: %s", val) <add> } <add> if _, err := ValidateIPAddress(arr[1]); err != nil { <add> return "", fmt.Errorf("bad format for add-host: %s", val) <add> } <add> return val, nil <add>} <add> <ide> // Validates an HTTP(S) registry mirror <ide> func ValidateMirror(val string) (string, error) { <ide> uri, err := url.Parse(val) <ide><path>runconfig/hostconfig.go <ide> type HostConfig struct { <ide> PublishAllPorts bool <ide> Dns []string <ide> DnsSearch []string <add> ExtraHosts []string <ide> VolumesFrom []string <ide> Devices []DeviceMapping <ide> NetworkMode NetworkMode <ide> func ContainerHostConfigFromJob(job *engine.Job) *HostConfig { <ide> if DnsSearch := job.GetenvList("DnsSearch"); DnsSearch != nil { <ide> hostConfig.DnsSearch = DnsSearch <ide> } <add> if ExtraHosts := job.GetenvList("ExtraHosts"); ExtraHosts != nil { <add> hostConfig.ExtraHosts = ExtraHosts <add> } <ide> if VolumesFrom := job.GetenvList("VolumesFrom"); VolumesFrom != nil { <ide> hostConfig.VolumesFrom = VolumesFrom <ide> } <ide><path>runconfig/parse.go <ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf <ide> flExpose = opts.NewListOpts(nil) <ide> flDns = opts.NewListOpts(opts.ValidateIPAddress) <ide> flDnsSearch = opts.NewListOpts(opts.ValidateDnsSearch) <add> flExtraHosts = opts.NewListOpts(opts.ValidateExtraHost) <ide> flVolumesFrom = opts.NewListOpts(nil) <ide> flLxcOpts = opts.NewListOpts(nil) <ide> flEnvFile = opts.NewListOpts(nil) <ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf <ide> cmd.Var(&flExpose, []string{"#expose", "-expose"}, "Expose a port from the container without publishing it to your host") <ide> cmd.Var(&flDns, []string{"#dns", "-dns"}, "Set custom DNS servers") <ide> cmd.Var(&flDnsSearch, []string{"-dns-search"}, "Set custom DNS search domains") <add> cmd.Var(&flExtraHosts, []string{"-add-host"}, "Add a custom host-to-IP mapping (host:ip)") <ide> cmd.Var(&flVolumesFrom, []string{"#volumes-from", "-volumes-from"}, "Mount volumes from the specified container(s)") <ide> cmd.Var(&flLxcOpts, []string{"#lxc-conf", "-lxc-conf"}, "(lxc exec-driver only) Add custom lxc options --lxc-conf=\"lxc.cgroup.cpuset.cpus = 0,1\"") <ide> <ide> func parseRun(cmd *flag.FlagSet, args []string, sysInfo *sysinfo.SysInfo) (*Conf <ide> PublishAllPorts: *flPublishAll, <ide> Dns: flDns.GetAll(), <ide> DnsSearch: flDnsSearch.GetAll(), <add> ExtraHosts: flExtraHosts.GetAll(), <ide> VolumesFrom: flVolumesFrom.GetAll(), <ide> NetworkMode: netMode, <ide> Devices: deviceMappings,
8
Python
Python
add head_mask/decoder_head_mask for bart
357fb1c5d8b6a16f042f9b504f023d935086e8e5
<ide><path>src/transformers/models/bart/modeling_bart.py <ide> def forward( <ide> key_value_states: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <ide> output_attentions: bool = False, <ide> ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: <ide> """Input shape: Batch x Time x Channel""" <ide> def forward( <ide> <ide> attn_weights = F.softmax(attn_weights, dim=-1) <ide> <add> if layer_head_mask is not None: <add> assert layer_head_mask.size() == ( <add> self.num_heads, <add> ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <add> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <add> <ide> if output_attentions: <ide> # this operation is a bit akward, but it's required to <ide> # make sure that attn_weights keeps its gradient. <ide> def __init__(self, config: BartConfig): <ide> self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) <ide> self.final_layer_norm = nn.LayerNorm(self.embed_dim) <ide> <del> def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool = False): <add> def forward( <add> self, <add> hidden_states: torch.Tensor, <add> attention_mask: torch.Tensor, <add> layer_head_mask: torch.Tensor, <add> output_attentions: bool = False, <add> ): <ide> """ <ide> Args: <ide> hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (:obj:`torch.FloatTensor`): attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> returned tensors for more detail. <ide> """ <ide> residual = hidden_states <ide> hidden_states, attn_weights, _ = self.self_attn( <del> hidden_states=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions <add> hidden_states=hidden_states, <add> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <add> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> hidden_states = residual + hidden_states <ide> def forward( <ide> attention_mask: Optional[torch.Tensor] = None, <ide> encoder_hidden_states: Optional[torch.Tensor] = None, <ide> encoder_attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <add> encoder_layer_head_mask: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> output_attentions: Optional[bool] = False, <ide> use_cache: Optional[bool] = True, <ide> def forward( <ide> encoder_hidden_states (:obj:`torch.FloatTensor`): cross attention input to the layer of shape `(seq_len, batch, embed_dim)` <ide> encoder_attention_mask (:obj:`torch.FloatTensor`): encoder attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <add> encoder_layer_head_mask (:obj:`torch.FloatTensor`): mask for encoder attention heads in a given layer of <add> size `(config.encoder_attention_heads,)`. <ide> past_key_value (:obj:`Tuple(torch.FloatTensor)`): cached past key and value projection states <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> def forward( <ide> hidden_states=hidden_states, <ide> past_key_value=self_attn_past_key_value, <ide> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <ide> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> def forward( <ide> hidden_states=hidden_states, <ide> key_value_states=encoder_hidden_states, <ide> attention_mask=encoder_attention_mask, <add> layer_head_mask=encoder_layer_head_mask, <ide> past_key_value=cross_attn_past_key_value, <ide> output_attentions=output_attentions, <ide> ) <ide> def __init_subclass__(self): <ide> If you want to change padding behavior, you should read :func:`modeling_bart._prepare_decoder_inputs` and <ide> modify to your needs. See diagram 1 in `the paper <https://arxiv.org/abs/1910.13461>`__ for more <ide> information on the default strategy. <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the head is **masked**. <add> <ide> encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`): <ide> Tuple consists of (:obj:`last_hidden_state`, `optional`: :obj:`hidden_states`, `optional`: <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> def forward( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> inputs_embeds=None, <ide> output_attentions=None, <ide> output_hidden_states=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): <ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded <ide> representation. This is useful if you want more control over how to convert :obj:`input_ids` indices <ide> def forward( <ide> <ide> encoder_states = () if output_hidden_states else None <ide> all_attentions = () if output_attentions else None <del> for encoder_layer in self.layers: <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> def custom_forward(*inputs): <ide> create_custom_forward(encoder_layer), <ide> hidden_states, <ide> attention_mask, <add> (head_mask[idx] if head_mask is not None else None), <ide> ) <ide> else: <del> layer_outputs = encoder_layer(hidden_states, attention_mask, output_attentions=output_attentions) <add> layer_outputs = encoder_layer( <add> hidden_states, <add> attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> output_attentions=output_attentions, <add> ) <ide> <ide> hidden_states = layer_outputs[0] <ide> <ide> def forward( <ide> attention_mask=None, <ide> encoder_hidden_states=None, <ide> encoder_attention_mask=None, <add> head_mask=None, <add> encoder_head_mask=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> use_cache=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> encoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention <add> on hidden heads. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <ide> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <ide> decoding. <ide> def forward( <ide> all_self_attns = () if output_attentions else None <ide> all_cross_attentions = () if output_attentions else None <ide> next_decoder_cache = () if use_cache else None <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide> def custom_forward(*inputs): <ide> combined_attention_mask, <ide> encoder_hidden_states, <ide> encoder_attention_mask, <add> head_mask[idx] if head_mask is not None else None, <add> encoder_head_mask[idx] if encoder_head_mask is not None else None, <ide> None, <ide> ) <ide> else: <ide> def custom_forward(*inputs): <ide> attention_mask=combined_attention_mask, <ide> encoder_hidden_states=encoder_hidden_states, <ide> encoder_attention_mask=encoder_attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> encoder_layer_head_mask=(encoder_head_mask[idx] if encoder_head_mask is not None else None), <ide> past_key_value=past_key_value, <ide> output_attentions=output_attentions, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> encoder_outputs = self.encoder( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> inputs_embeds=inputs_embeds, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> def forward( <ide> attention_mask=decoder_attention_mask, <ide> encoder_hidden_states=encoder_outputs[0], <ide> encoder_attention_mask=attention_mask, <add> head_mask=decoder_head_mask, <add> encoder_head_mask=head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=decoder_inputs_embeds, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> decoder_input_ids=decoder_input_ids, <ide> encoder_outputs=encoder_outputs, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide> def forward( <ide> ) <ide> <ide> def prepare_inputs_for_generation( <del> self, decoder_input_ids, past=None, attention_mask=None, use_cache=None, encoder_outputs=None, **kwargs <add> self, <add> decoder_input_ids, <add> past=None, <add> attention_mask=None, <add> head_mask=None, <add> use_cache=None, <add> encoder_outputs=None, <add> **kwargs <ide> ): <ide> # cut decoder_input_ids if past is used <ide> if past is not None: <ide> def prepare_inputs_for_generation( <ide> "past_key_values": past, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <add> "head_mask": head_mask, <ide> "use_cache": use_cache, # change this to avoid caching (presumably for debugging) <ide> } <ide> <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> inputs_embeds=None, <ide> decoder_inputs_embeds=None, <ide> def forward( <ide> attention_mask=attention_mask, <ide> decoder_input_ids=decoder_input_ids, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> encoder_outputs=encoder_outputs, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> start_positions=None, <ide> end_positions=None, <ide> def forward( <ide> attention_mask=attention_mask, <ide> decoder_input_ids=decoder_input_ids, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> encoder_outputs=encoder_outputs, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide><path>src/transformers/models/blenderbot/modeling_blenderbot.py <ide> def forward( <ide> key_value_states: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <ide> output_attentions: bool = False, <ide> ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: <ide> """Input shape: Batch x Time x Channel""" <ide> def forward( <ide> <ide> attn_weights = F.softmax(attn_weights, dim=-1) <ide> <add> if layer_head_mask is not None: <add> assert layer_head_mask.size() == ( <add> self.num_heads, <add> ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <add> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <add> <ide> if output_attentions: <ide> # this operation is a bit akward, but it's required to <ide> # make sure that attn_weights keeps its gradient. <ide> def __init__(self, config: BlenderbotConfig): <ide> self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) <ide> self.final_layer_norm = nn.LayerNorm(self.embed_dim) <ide> <del> def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool = False): <add> def forward( <add> self, <add> hidden_states: torch.Tensor, <add> attention_mask: torch.Tensor, <add> layer_head_mask: torch.Tensor, <add> output_attentions: bool = False, <add> ): <ide> """ <ide> Args: <ide> hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (:obj:`torch.FloatTensor`): attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> returned tensors for more detail. <ide> """ <ide> residual = hidden_states <ide> hidden_states = self.self_attn_layer_norm(hidden_states) <ide> hidden_states, attn_weights, _ = self.self_attn( <del> hidden_states=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions <add> hidden_states=hidden_states, <add> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <add> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> hidden_states = residual + hidden_states <ide> def forward( <ide> attention_mask: Optional[torch.Tensor] = None, <ide> encoder_hidden_states: Optional[torch.Tensor] = None, <ide> encoder_attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <add> encoder_layer_head_mask: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> output_attentions: Optional[bool] = False, <ide> use_cache: Optional[bool] = True, <ide> def forward( <ide> encoder_hidden_states (:obj:`torch.FloatTensor`): cross attention input to the layer of shape `(seq_len, batch, embed_dim)` <ide> encoder_attention_mask (:obj:`torch.FloatTensor`): encoder attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <add> encoder_layer_head_mask (:obj:`torch.FloatTensor`): mask for encoder attention heads in a given layer of <add> size `(config.encoder_attention_heads,)`. <ide> past_key_value (:obj:`Tuple(torch.FloatTensor)`): cached past key and value projection states <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> def forward( <ide> hidden_states=hidden_states, <ide> past_key_value=self_attn_past_key_value, <ide> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <ide> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> def forward( <ide> hidden_states=hidden_states, <ide> key_value_states=encoder_hidden_states, <ide> attention_mask=encoder_attention_mask, <add> layer_head_mask=layer_head_mask, <ide> past_key_value=cross_attn_past_key_value, <ide> output_attentions=output_attentions, <ide> ) <ide> def dummy_inputs(self): <ide> If you want to change padding behavior, you should read :func:`modeling_blenderbot._prepare_decoder_inputs` <ide> and modify to your needs. See diagram 1 in `the paper <https://arxiv.org/abs/1910.13461>`__ for more <ide> information on the default strategy. <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the head is **masked**. <add> <ide> encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`): <ide> Tuple consists of (:obj:`last_hidden_state`, `optional`: :obj:`hidden_states`, `optional`: <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> def forward( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> inputs_embeds=None, <ide> output_attentions=None, <ide> output_hidden_states=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): <ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded <ide> representation. This is useful if you want more control over how to convert :obj:`input_ids` indices <ide> def forward( <ide> <ide> encoder_states = () if output_hidden_states else None <ide> all_attentions = () if output_attentions else None <del> for encoder_layer in self.layers: <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> def custom_forward(*inputs): <ide> create_custom_forward(encoder_layer), <ide> hidden_states, <ide> attention_mask, <add> (head_mask[idx] if head_mask is not None else None), <ide> ) <ide> else: <del> layer_outputs = encoder_layer(hidden_states, attention_mask, output_attentions=output_attentions) <add> layer_outputs = encoder_layer( <add> hidden_states, <add> attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> output_attentions=output_attentions, <add> ) <ide> <ide> hidden_states = layer_outputs[0] <ide> <ide> def forward( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> encoder_hidden_states=None, <ide> encoder_attention_mask=None, <add> encoder_head_mask=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> use_cache=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, encoder_sequence_length, hidden_size)`, `optional`): <ide> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention <ide> of the decoder. <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> encoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention <add> on hidden heads. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <ide> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <ide> decoding. <ide> def forward( <ide> all_self_attns = () if output_attentions else None <ide> all_cross_attentions = () if output_attentions else None <ide> next_decoder_cache = () if use_cache else None <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide> def custom_forward(*inputs): <ide> combined_attention_mask, <ide> encoder_hidden_states, <ide> encoder_attention_mask, <add> head_mask[idx] if head_mask is not None else None, <add> encoder_head_mask[idx] if encoder_head_mask is not None else None, <ide> None, <ide> ) <ide> else: <ide> <ide> layer_outputs = decoder_layer( <ide> hidden_states, <ide> attention_mask=combined_attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <ide> encoder_hidden_states=encoder_hidden_states, <ide> encoder_attention_mask=encoder_attention_mask, <add> encoder_layer_head_mask=(encoder_head_mask[idx] if encoder_head_mask is not None else None), <ide> past_key_value=past_key_value, <ide> output_attentions=output_attentions, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> encoder_outputs = self.encoder( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> inputs_embeds=inputs_embeds, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> def forward( <ide> attention_mask=decoder_attention_mask, <ide> encoder_hidden_states=encoder_outputs[0], <ide> encoder_attention_mask=attention_mask, <add> head_mask=decoder_head_mask, <add> encoder_head_mask=head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=decoder_inputs_embeds, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> decoder_input_ids=decoder_input_ids, <ide> encoder_outputs=encoder_outputs, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide> def forward( <ide> ) <ide> <ide> def prepare_inputs_for_generation( <del> self, decoder_input_ids, past=None, attention_mask=None, use_cache=None, encoder_outputs=None, **kwargs <add> self, <add> decoder_input_ids, <add> past=None, <add> attention_mask=None, <add> head_mask=None, <add> use_cache=None, <add> encoder_outputs=None, <add> **kwargs <ide> ): <ide> # cut decoder_input_ids if past is used <ide> if past is not None: <ide> def prepare_inputs_for_generation( <ide> "past_key_values": past, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <add> "head_mask": head_mask, <ide> "use_cache": use_cache, # change this to avoid caching (presumably for debugging) <ide> } <ide> <ide><path>src/transformers/models/blenderbot_small/modeling_blenderbot_small.py <ide> def forward( <ide> key_value_states: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <ide> output_attentions: bool = False, <ide> ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: <ide> """Input shape: Batch x Time x Channel""" <ide> def forward( <ide> <ide> attn_weights = F.softmax(attn_weights, dim=-1) <ide> <add> if layer_head_mask is not None: <add> assert layer_head_mask.size() == ( <add> self.num_heads, <add> ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <add> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <add> <ide> if output_attentions: <ide> # this operation is a bit akward, but it's required to <ide> # make sure that attn_weights keeps its gradient. <ide> def __init__(self, config: BlenderbotSmallConfig): <ide> self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) <ide> self.final_layer_norm = nn.LayerNorm(self.embed_dim) <ide> <del> def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool = False): <add> def forward( <add> self, <add> hidden_states: torch.Tensor, <add> attention_mask: torch.Tensor, <add> layer_head_mask: torch.Tensor, <add> output_attentions: bool = False, <add> ): <ide> """ <ide> Args: <ide> hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (:obj:`torch.FloatTensor`): attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> returned tensors for more detail. <ide> """ <ide> residual = hidden_states <ide> hidden_states, attn_weights, _ = self.self_attn( <del> hidden_states=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions <add> hidden_states=hidden_states, <add> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <add> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> hidden_states = residual + hidden_states <ide> def forward( <ide> attention_mask: Optional[torch.Tensor] = None, <ide> encoder_hidden_states: Optional[torch.Tensor] = None, <ide> encoder_attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <add> encoder_layer_head_mask: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> output_attentions: Optional[bool] = False, <ide> use_cache: Optional[bool] = True, <ide> def forward( <ide> encoder_hidden_states (:obj:`torch.FloatTensor`): cross attention input to the layer of shape `(seq_len, batch, embed_dim)` <ide> encoder_attention_mask (:obj:`torch.FloatTensor`): encoder attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <add> encoder_layer_head_mask (:obj:`torch.FloatTensor`): mask for encoder attention heads in a given layer of <add> size `(config.encoder_attention_heads,)`. <ide> past_key_value (:obj:`Tuple(torch.FloatTensor)`): cached past key and value projection states <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> def forward( <ide> hidden_states=hidden_states, <ide> past_key_value=self_attn_past_key_value, <ide> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <ide> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> def forward( <ide> hidden_states=hidden_states, <ide> key_value_states=encoder_hidden_states, <ide> attention_mask=encoder_attention_mask, <add> layer_head_mask=encoder_layer_head_mask, <ide> past_key_value=cross_attn_past_key_value, <ide> output_attentions=output_attentions, <ide> ) <ide> def dummy_inputs(self): <ide> If you want to change padding behavior, you should read <ide> :func:`modeling_blenderbot_small._prepare_decoder_inputs` and modify to your needs. See diagram 1 in `the <ide> paper <https://arxiv.org/abs/1910.13461>`__ for more information on the default strategy. <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the head is **masked**. <add> <ide> encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`): <ide> Tuple consists of (:obj:`last_hidden_state`, `optional`: :obj:`hidden_states`, `optional`: <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> def forward( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> inputs_embeds=None, <ide> output_attentions=None, <ide> output_hidden_states=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): <ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded <ide> representation. This is useful if you want more control over how to convert :obj:`input_ids` indices <ide> def forward( <ide> <ide> encoder_states = () if output_hidden_states else None <ide> all_attentions = () if output_attentions else None <del> for encoder_layer in self.layers: <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> def custom_forward(*inputs): <ide> create_custom_forward(encoder_layer), <ide> hidden_states, <ide> attention_mask, <add> (head_mask[idx] if head_mask is not None else None), <ide> ) <ide> else: <del> layer_outputs = encoder_layer(hidden_states, attention_mask, output_attentions=output_attentions) <add> layer_outputs = encoder_layer( <add> hidden_states, <add> attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> output_attentions=output_attentions, <add> ) <ide> <ide> hidden_states = layer_outputs[0] <ide> <ide> def forward( <ide> attention_mask=None, <ide> encoder_hidden_states=None, <ide> encoder_attention_mask=None, <add> head_mask=None, <add> encoder_head_mask=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> use_cache=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> encoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention <add> on hidden heads. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <ide> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <ide> decoding. <ide> def forward( <ide> all_cross_attentions = () if output_attentions else None <ide> next_decoder_cache = () if use_cache else None <ide> <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide> def custom_forward(*inputs): <ide> combined_attention_mask, <ide> encoder_hidden_states, <ide> encoder_attention_mask, <add> head_mask[idx] if head_mask is not None else None, <add> encoder_head_mask[idx] if encoder_head_mask is not None else None, <ide> None, <ide> ) <ide> else: <ide> def custom_forward(*inputs): <ide> attention_mask=combined_attention_mask, <ide> encoder_hidden_states=encoder_hidden_states, <ide> encoder_attention_mask=encoder_attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> encoder_layer_head_mask=(encoder_head_mask[idx] if encoder_head_mask is not None else None), <ide> past_key_value=past_key_value, <ide> output_attentions=output_attentions, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> encoder_outputs = self.encoder( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> inputs_embeds=inputs_embeds, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> def forward( <ide> attention_mask=decoder_attention_mask, <ide> encoder_hidden_states=encoder_outputs[0], <ide> encoder_attention_mask=attention_mask, <add> head_mask=decoder_head_mask, <add> encoder_head_mask=head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=decoder_inputs_embeds, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> decoder_input_ids=decoder_input_ids, <ide> encoder_outputs=encoder_outputs, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide> def forward( <ide> ) <ide> <ide> def prepare_inputs_for_generation( <del> self, decoder_input_ids, past=None, attention_mask=None, use_cache=None, encoder_outputs=None, **kwargs <add> self, <add> decoder_input_ids, <add> past=None, <add> attention_mask=None, <add> head_mask=None, <add> use_cache=None, <add> encoder_outputs=None, <add> **kwargs <ide> ): <ide> # cut decoder_input_ids if past is used <ide> if past is not None: <ide> def prepare_inputs_for_generation( <ide> "past_key_values": past, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <add> "head_mask": head_mask, <ide> "use_cache": use_cache, # change this to avoid caching (presumably for debugging) <ide> } <ide> <ide><path>src/transformers/models/marian/modeling_marian.py <ide> def forward( <ide> key_value_states: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <ide> output_attentions: bool = False, <ide> ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: <ide> """Input shape: Batch x Time x Channel""" <ide> def forward( <ide> <ide> attn_weights = F.softmax(attn_weights, dim=-1) <ide> <add> if layer_head_mask is not None: <add> assert layer_head_mask.size() == ( <add> self.num_heads, <add> ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <add> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <add> <ide> if output_attentions: <ide> # this operation is a bit akward, but it's required to <ide> # make sure that attn_weights keeps its gradient. <ide> def __init__(self, config: MarianConfig): <ide> self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) <ide> self.final_layer_norm = nn.LayerNorm(self.embed_dim) <ide> <del> def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool = False): <add> def forward( <add> self, <add> hidden_states: torch.Tensor, <add> attention_mask: torch.Tensor, <add> layer_head_mask: torch.Tensor, <add> output_attentions: bool = False, <add> ): <ide> """ <ide> Args: <ide> hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (:obj:`torch.FloatTensor`): attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> returned tensors for more detail. <ide> """ <ide> residual = hidden_states <ide> hidden_states, attn_weights, _ = self.self_attn( <del> hidden_states=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions <add> hidden_states=hidden_states, <add> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <add> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> hidden_states = residual + hidden_states <ide> def forward( <ide> attention_mask: Optional[torch.Tensor] = None, <ide> encoder_hidden_states: Optional[torch.Tensor] = None, <ide> encoder_attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <add> encoder_layer_head_mask: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> output_attentions: Optional[bool] = False, <ide> use_cache: Optional[bool] = True, <ide> def forward( <ide> encoder_hidden_states (:obj:`torch.FloatTensor`): cross attention input to the layer of shape `(seq_len, batch, embed_dim)` <ide> encoder_attention_mask (:obj:`torch.FloatTensor`): encoder attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <add> encoder_layer_head_mask (:obj:`torch.FloatTensor`): mask for encoder attention heads in a given layer of <add> size `(config.encoder_attention_heads,)`. <ide> past_key_value (:obj:`Tuple(torch.FloatTensor)`): cached past key and value projection states <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> def forward( <ide> hidden_states=hidden_states, <ide> past_key_value=self_attn_past_key_value, <ide> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <ide> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> def forward( <ide> hidden_states=hidden_states, <ide> key_value_states=encoder_hidden_states, <ide> attention_mask=encoder_attention_mask, <add> layer_head_mask=encoder_layer_head_mask, <ide> past_key_value=cross_attn_past_key_value, <ide> output_attentions=output_attentions, <ide> ) <ide> def dummy_inputs(self): <ide> If you want to change padding behavior, you should read :func:`modeling_marian._prepare_decoder_inputs` and <ide> modify to your needs. See diagram 1 in `the paper <https://arxiv.org/abs/1910.13461>`__ for more <ide> information on the default strategy. <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the head is **masked**. <add> <ide> encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`): <ide> Tuple consists of (:obj:`last_hidden_state`, `optional`: :obj:`hidden_states`, `optional`: <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> def forward( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> inputs_embeds=None, <ide> output_attentions=None, <ide> output_hidden_states=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): <ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded <ide> representation. This is useful if you want more control over how to convert :obj:`input_ids` indices <ide> def forward( <ide> <ide> encoder_states = () if output_hidden_states else None <ide> all_attentions = () if output_attentions else None <del> for encoder_layer in self.layers: <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> def custom_forward(*inputs): <ide> create_custom_forward(encoder_layer), <ide> hidden_states, <ide> attention_mask, <add> (head_mask[idx] if head_mask is not None else None), <ide> ) <ide> else: <del> layer_outputs = encoder_layer(hidden_states, attention_mask, output_attentions=output_attentions) <add> layer_outputs = encoder_layer( <add> hidden_states, <add> attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> output_attentions=output_attentions, <add> ) <ide> <ide> hidden_states = layer_outputs[0] <ide> <ide> def forward( <ide> attention_mask=None, <ide> encoder_hidden_states=None, <ide> encoder_attention_mask=None, <add> head_mask=None, <add> encoder_head_mask=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> use_cache=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> encoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention <add> on hidden heads. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <ide> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <ide> decoding. <ide> def forward( <ide> all_self_attns = () if output_attentions else None <ide> all_cross_attentions = () if output_attentions else None <ide> next_decoder_cache = () if use_cache else None <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide> def custom_forward(*inputs): <ide> combined_attention_mask, <ide> encoder_hidden_states, <ide> encoder_attention_mask, <add> head_mask[idx] if head_mask is not None else None, <add> encoder_head_mask[idx] if encoder_head_mask is not None else None, <ide> None, <ide> ) <ide> else: <ide> def custom_forward(*inputs): <ide> attention_mask=combined_attention_mask, <ide> encoder_hidden_states=encoder_hidden_states, <ide> encoder_attention_mask=encoder_attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> encoder_layer_head_mask=(encoder_head_mask[idx] if encoder_head_mask is not None else None), <ide> past_key_value=past_key_value, <ide> output_attentions=output_attentions, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> encoder_outputs = self.encoder( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> inputs_embeds=inputs_embeds, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> def forward( <ide> attention_mask=decoder_attention_mask, <ide> encoder_hidden_states=encoder_outputs[0], <ide> encoder_attention_mask=attention_mask, <add> head_mask=decoder_head_mask, <add> encoder_head_mask=head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=decoder_inputs_embeds, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> decoder_input_ids=decoder_input_ids, <ide> encoder_outputs=encoder_outputs, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide> def forward( <ide> ) <ide> <ide> def prepare_inputs_for_generation( <del> self, decoder_input_ids, past=None, attention_mask=None, use_cache=None, encoder_outputs=None, **kwargs <add> self, <add> decoder_input_ids, <add> past=None, <add> attention_mask=None, <add> head_mask=None, <add> use_cache=None, <add> encoder_outputs=None, <add> **kwargs <ide> ): <ide> # cut decoder_input_ids if past is used <ide> if past is not None: <ide> def prepare_inputs_for_generation( <ide> "past_key_values": past, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <add> "head_mask": head_mask, <ide> "use_cache": use_cache, # change this to avoid caching (presumably for debugging) <ide> } <ide> <ide><path>src/transformers/models/mbart/modeling_mbart.py <ide> def forward( <ide> key_value_states: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <ide> output_attentions: bool = False, <ide> ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: <ide> """Input shape: Batch x Time x Channel""" <ide> def forward( <ide> <ide> attn_weights = F.softmax(attn_weights, dim=-1) <ide> <add> if layer_head_mask is not None: <add> assert layer_head_mask.size() == ( <add> self.num_heads, <add> ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <add> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <add> <ide> if output_attentions: <ide> # this operation is a bit akward, but it's required to <ide> # make sure that attn_weights keeps its gradient. <ide> def __init__(self, config: MBartConfig): <ide> self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) <ide> self.final_layer_norm = nn.LayerNorm(self.embed_dim) <ide> <del> def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool = False): <add> def forward( <add> self, <add> hidden_states: torch.Tensor, <add> attention_mask: torch.Tensor, <add> layer_head_mask: torch.Tensor, <add> output_attentions: bool = False, <add> ): <ide> """ <ide> Args: <ide> hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (:obj:`torch.FloatTensor`): attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> returned tensors for more detail. <ide> """ <ide> residual = hidden_states <ide> hidden_states = self.self_attn_layer_norm(hidden_states) <ide> hidden_states, attn_weights, _ = self.self_attn( <del> hidden_states=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions <add> hidden_states=hidden_states, <add> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <add> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> hidden_states = residual + hidden_states <ide> def forward( <ide> attention_mask: Optional[torch.Tensor] = None, <ide> encoder_hidden_states: Optional[torch.Tensor] = None, <ide> encoder_attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <add> encoder_layer_head_mask: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> output_attentions: Optional[bool] = False, <ide> use_cache: Optional[bool] = True, <ide> def forward( <ide> encoder_hidden_states (:obj:`torch.FloatTensor`): cross attention input to the layer of shape `(seq_len, batch, embed_dim)` <ide> encoder_attention_mask (:obj:`torch.FloatTensor`): encoder attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <add> encoder_layer_head_mask (:obj:`torch.FloatTensor`): mask for encoder attention heads in a given layer of <add> size `(config.encoder_attention_heads,)`. <ide> past_key_value (:obj:`Tuple(torch.FloatTensor)`): cached past key and value projection states <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> def forward( <ide> hidden_states=hidden_states, <ide> past_key_value=self_attn_past_key_value, <ide> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <ide> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> def forward( <ide> hidden_states=hidden_states, <ide> key_value_states=encoder_hidden_states, <ide> attention_mask=encoder_attention_mask, <add> layer_head_mask=layer_head_mask, <ide> past_key_value=cross_attn_past_key_value, <ide> output_attentions=output_attentions, <ide> ) <ide> def dummy_inputs(self): <ide> If you want to change padding behavior, you should read :func:`modeling_mbart._prepare_decoder_inputs` and <ide> modify to your needs. See diagram 1 in `the paper <https://arxiv.org/abs/1910.13461>`__ for more <ide> information on the default strategy. <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the head is **masked**. <add> <ide> encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`): <ide> Tuple consists of (:obj:`last_hidden_state`, `optional`: :obj:`hidden_states`, `optional`: <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> def forward( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> inputs_embeds=None, <ide> output_attentions=None, <ide> output_hidden_states=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): <ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded <ide> representation. This is useful if you want more control over how to convert :obj:`input_ids` indices <ide> def forward( <ide> <ide> encoder_states = () if output_hidden_states else None <ide> all_attentions = () if output_attentions else None <del> for encoder_layer in self.layers: <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> def custom_forward(*inputs): <ide> create_custom_forward(encoder_layer), <ide> hidden_states, <ide> attention_mask, <add> (head_mask[idx] if head_mask is not None else None), <ide> ) <ide> else: <del> layer_outputs = encoder_layer(hidden_states, attention_mask, output_attentions=output_attentions) <add> layer_outputs = encoder_layer( <add> hidden_states, <add> attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> output_attentions=output_attentions, <add> ) <ide> <ide> hidden_states = layer_outputs[0] <ide> <ide> def forward( <ide> attention_mask=None, <ide> encoder_hidden_states=None, <ide> encoder_attention_mask=None, <add> head_mask=None, <add> encoder_head_mask=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> use_cache=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> encoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention <add> on hidden heads. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <ide> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <ide> decoding. <ide> def forward( <ide> all_self_attns = () if output_attentions else None <ide> all_cross_attentions = () if output_attentions else None <ide> next_decoder_cache = () if use_cache else None <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide> def custom_forward(*inputs): <ide> combined_attention_mask, <ide> encoder_hidden_states, <ide> encoder_attention_mask, <add> head_mask[idx] if head_mask is not None else None, <add> encoder_head_mask[idx] if encoder_head_mask is not None else None, <ide> None, <ide> ) <ide> else: <ide> def custom_forward(*inputs): <ide> attention_mask=combined_attention_mask, <ide> encoder_hidden_states=encoder_hidden_states, <ide> encoder_attention_mask=encoder_attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> encoder_layer_head_mask=(encoder_head_mask[idx] if encoder_head_mask is not None else None), <ide> past_key_value=past_key_value, <ide> output_attentions=output_attentions, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> encoder_outputs = self.encoder( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> inputs_embeds=inputs_embeds, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> def forward( <ide> attention_mask=decoder_attention_mask, <ide> encoder_hidden_states=encoder_outputs[0], <ide> encoder_attention_mask=attention_mask, <add> head_mask=decoder_head_mask, <add> encoder_head_mask=head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=decoder_inputs_embeds, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> decoder_input_ids=decoder_input_ids, <ide> encoder_outputs=encoder_outputs, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> inputs_embeds=None, <ide> decoder_inputs_embeds=None, <ide> def forward( <ide> attention_mask=attention_mask, <ide> decoder_input_ids=decoder_input_ids, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> encoder_outputs=encoder_outputs, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> start_positions=None, <ide> end_positions=None, <ide> def forward( <ide> attention_mask=attention_mask, <ide> decoder_input_ids=decoder_input_ids, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> encoder_outputs=encoder_outputs, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide><path>src/transformers/models/pegasus/modeling_pegasus.py <ide> def forward( <ide> key_value_states: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <ide> output_attentions: bool = False, <ide> ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: <ide> """Input shape: Batch x Time x Channel""" <ide> def forward( <ide> <ide> attn_weights = F.softmax(attn_weights, dim=-1) <ide> <add> if layer_head_mask is not None: <add> assert layer_head_mask.size() == ( <add> self.num_heads, <add> ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}" <add> attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) <add> attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) <add> <ide> if output_attentions: <ide> # this operation is a bit akward, but it's required to <ide> # make sure that attn_weights keeps its gradient. <ide> def __init__(self, config: PegasusConfig): <ide> self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) <ide> self.final_layer_norm = nn.LayerNorm(self.embed_dim) <ide> <del> def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool = False): <add> def forward( <add> self, <add> hidden_states: torch.Tensor, <add> attention_mask: torch.Tensor, <add> layer_head_mask: torch.Tensor, <add> output_attentions: bool = False, <add> ): <ide> """ <ide> Args: <ide> hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)` <ide> attention_mask (:obj:`torch.FloatTensor`): attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> returned tensors for more detail. <ide> """ <ide> residual = hidden_states <ide> hidden_states = self.self_attn_layer_norm(hidden_states) <ide> hidden_states, attn_weights, _ = self.self_attn( <del> hidden_states=hidden_states, attention_mask=attention_mask, output_attentions=output_attentions <add> hidden_states=hidden_states, <add> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <add> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> hidden_states = residual + hidden_states <ide> def forward( <ide> attention_mask: Optional[torch.Tensor] = None, <ide> encoder_hidden_states: Optional[torch.Tensor] = None, <ide> encoder_attention_mask: Optional[torch.Tensor] = None, <add> layer_head_mask: Optional[torch.Tensor] = None, <add> encoder_layer_head_mask: Optional[torch.Tensor] = None, <ide> past_key_value: Optional[Tuple[torch.Tensor]] = None, <ide> output_attentions: Optional[bool] = False, <ide> use_cache: Optional[bool] = True, <ide> def forward( <ide> encoder_hidden_states (:obj:`torch.FloatTensor`): cross attention input to the layer of shape `(seq_len, batch, embed_dim)` <ide> encoder_attention_mask (:obj:`torch.FloatTensor`): encoder attention mask of size <ide> `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. <add> layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size <add> `(config.encoder_attention_heads,)`. <add> encoder_layer_head_mask (:obj:`torch.FloatTensor`): mask for encoder attention heads in a given layer of <add> size `(config.encoder_attention_heads,)`. <ide> past_key_value (:obj:`Tuple(torch.FloatTensor)`): cached past key and value projection states <ide> output_attentions (:obj:`bool`, `optional`): <ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under <ide> def forward( <ide> hidden_states=hidden_states, <ide> past_key_value=self_attn_past_key_value, <ide> attention_mask=attention_mask, <add> layer_head_mask=layer_head_mask, <ide> output_attentions=output_attentions, <ide> ) <ide> hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training) <ide> def forward( <ide> hidden_states=hidden_states, <ide> key_value_states=encoder_hidden_states, <ide> attention_mask=encoder_attention_mask, <add> layer_head_mask=layer_head_mask, <ide> past_key_value=cross_attn_past_key_value, <ide> output_attentions=output_attentions, <ide> ) <ide> def dummy_inputs(self): <ide> If you want to change padding behavior, you should read :func:`modeling_pegasus._prepare_decoder_inputs` <ide> and modify to your needs. See diagram 1 in `the paper <https://arxiv.org/abs/1910.13461>`__ for more <ide> information on the default strategy. <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> decoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the head is **masked**. <add> <ide> encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`): <ide> Tuple consists of (:obj:`last_hidden_state`, `optional`: :obj:`hidden_states`, `optional`: <ide> :obj:`attentions`) :obj:`last_hidden_state` of shape :obj:`(batch_size, sequence_length, hidden_size)`, <ide> def forward( <ide> self, <ide> input_ids=None, <ide> attention_mask=None, <add> head_mask=None, <ide> inputs_embeds=None, <ide> output_attentions=None, <ide> output_hidden_states=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`): <ide> Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded <ide> representation. This is useful if you want more control over how to convert :obj:`input_ids` indices <ide> def forward( <ide> <ide> encoder_states = () if output_hidden_states else None <ide> all_attentions = () if output_attentions else None <del> for encoder_layer in self.layers: <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <add> for idx, encoder_layer in enumerate(self.layers): <ide> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> def custom_forward(*inputs): <ide> create_custom_forward(encoder_layer), <ide> hidden_states, <ide> attention_mask, <add> (head_mask[idx] if head_mask is not None else None), <ide> ) <ide> else: <del> layer_outputs = encoder_layer(hidden_states, attention_mask, output_attentions=output_attentions) <add> layer_outputs = encoder_layer( <add> hidden_states, <add> attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> output_attentions=output_attentions, <add> ) <ide> <ide> hidden_states = layer_outputs[0] <ide> <ide> def forward( <ide> attention_mask=None, <ide> encoder_hidden_states=None, <ide> encoder_attention_mask=None, <add> head_mask=None, <add> encoder_head_mask=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> use_cache=None, <ide> def forward( <ide> - 0 for tokens that are **masked**. <ide> <ide> `What are attention masks? <../glossary.html#attention-mask>`__ <add> head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <add> encoder_head_mask (:obj:`torch.Tensor` of shape :obj:`(num_layers, num_heads)`, `optional`): <add> Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention <add> on hidden heads. Mask values selected in ``[0, 1]``: <add> <add> - 1 indicates the head is **not masked**, <add> - 0 indicates the heas is **masked**. <add> <ide> past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): <ide> Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up <ide> decoding. <ide> def forward( <ide> all_self_attns = () if output_attentions else None <ide> all_cross_attentions = () if output_attentions else None <ide> next_decoder_cache = () if use_cache else None <add> <add> # check if head_mask has a correct number of layers specified if desired <add> if head_mask is not None: <add> assert head_mask.size()[0] == ( <add> len(self.layers) <add> ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}." <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> if output_hidden_states: <ide> def custom_forward(*inputs): <ide> combined_attention_mask, <ide> encoder_hidden_states, <ide> encoder_attention_mask, <add> head_mask[idx] if head_mask is not None else None, <add> encoder_head_mask[idx] if encoder_head_mask is not None else None, <ide> None, <ide> ) <ide> else: <ide> def custom_forward(*inputs): <ide> attention_mask=combined_attention_mask, <ide> encoder_hidden_states=encoder_hidden_states, <ide> encoder_attention_mask=encoder_attention_mask, <add> layer_head_mask=(head_mask[idx] if head_mask is not None else None), <add> encoder_layer_head_mask=(encoder_head_mask[idx] if encoder_head_mask is not None else None), <ide> past_key_value=past_key_value, <ide> output_attentions=output_attentions, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> encoder_outputs = self.encoder( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <add> head_mask=head_mask, <ide> inputs_embeds=inputs_embeds, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> def forward( <ide> attention_mask=decoder_attention_mask, <ide> encoder_hidden_states=encoder_outputs[0], <ide> encoder_attention_mask=attention_mask, <add> head_mask=decoder_head_mask, <add> encoder_head_mask=head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=decoder_inputs_embeds, <ide> use_cache=use_cache, <ide> def forward( <ide> attention_mask=None, <ide> decoder_input_ids=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> encoder_outputs=None, <ide> past_key_values=None, <ide> inputs_embeds=None, <ide> def forward( <ide> decoder_input_ids=decoder_input_ids, <ide> encoder_outputs=encoder_outputs, <ide> decoder_attention_mask=decoder_attention_mask, <add> head_mask=head_mask, <add> decoder_head_mask=decoder_head_mask, <ide> past_key_values=past_key_values, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide> def forward( <ide> ) <ide> <ide> def prepare_inputs_for_generation( <del> self, decoder_input_ids, past=None, attention_mask=None, use_cache=None, encoder_outputs=None, **kwargs <add> self, <add> decoder_input_ids, <add> past=None, <add> attention_mask=None, <add> head_mask=None, <add> use_cache=None, <add> encoder_outputs=None, <add> **kwargs <ide> ): <ide> # cut decoder_input_ids if past is used <ide> if past is not None: <ide> def prepare_inputs_for_generation( <ide> "past_key_values": past, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <add> "head_mask": head_mask, <ide> "use_cache": use_cache, # change this to avoid caching (presumably for debugging) <ide> } <ide> <ide><path>tests/test_modeling_bart.py <ide> def prepare_bart_inputs_dict( <ide> decoder_input_ids=None, <ide> attention_mask=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> ): <ide> if attention_mask is None: <ide> attention_mask = input_ids.ne(config.pad_token_id) <ide> if decoder_attention_mask is None: <ide> decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) <add> if head_mask is None: <add> head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads) <add> if decoder_head_mask is None: <add> decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads) <ide> return { <ide> "input_ids": input_ids, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <ide> "decoder_attention_mask": attention_mask, <add> "head_mask": head_mask, <add> "decoder_head_mask": decoder_head_mask, <ide> } <ide> <ide> <ide> def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): <ide> model = BartModel(config=config).get_decoder().to(torch_device).eval() <ide> input_ids = inputs_dict["input_ids"] <ide> attention_mask = inputs_dict["attention_mask"] <add> head_mask = inputs_dict["head_mask"] <ide> <ide> # first forward pass <del> outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) <add> outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True) <ide> <ide> output, past_key_values = outputs.to_tuple() <ide> <ide> class BartModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): <ide> all_generative_model_classes = (BartForConditionalGeneration,) if is_torch_available() else () <ide> is_encoder_decoder = True <ide> test_pruning = False <del> test_head_masking = False <add> test_head_masking = True <ide> test_missing_keys = False <ide> <ide> def setUp(self): <ide><path>tests/test_modeling_blenderbot.py <ide> def prepare_blenderbot_inputs_dict( <ide> decoder_input_ids, <ide> attention_mask=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> ): <ide> if attention_mask is None: <ide> attention_mask = input_ids.ne(config.pad_token_id) <ide> if decoder_attention_mask is None: <ide> decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) <add> if head_mask is None: <add> head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads) <add> if decoder_head_mask is None: <add> decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads) <ide> return { <ide> "input_ids": input_ids, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <ide> "decoder_attention_mask": attention_mask, <add> "head_mask": head_mask, <add> "decoder_head_mask": decoder_head_mask, <ide> } <ide> <ide> <ide> def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): <ide> model = BlenderbotModel(config=config).get_decoder().to(torch_device).eval() <ide> input_ids = inputs_dict["input_ids"] <ide> attention_mask = inputs_dict["attention_mask"] <add> head_mask = inputs_dict["head_mask"] <ide> <ide> # first forward pass <del> outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) <add> outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True) <ide> <ide> output, past_key_values = outputs.to_tuple() <ide> <ide> class BlenderbotModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.Test <ide> all_generative_model_classes = (BlenderbotForConditionalGeneration,) if is_torch_available() else () <ide> is_encoder_decoder = True <ide> test_pruning = False <del> test_head_masking = False <add> test_head_masking = True <ide> test_missing_keys = False <ide> <ide> def setUp(self): <ide><path>tests/test_modeling_blenderbot_small.py <ide> def prepare_blenderbot_small_inputs_dict( <ide> decoder_input_ids, <ide> attention_mask=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> ): <ide> if attention_mask is None: <ide> attention_mask = input_ids.ne(config.pad_token_id) <ide> if decoder_attention_mask is None: <ide> decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) <add> if head_mask is None: <add> head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads) <add> if decoder_head_mask is None: <add> decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads) <ide> return { <ide> "input_ids": input_ids, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <ide> "decoder_attention_mask": attention_mask, <add> "head_mask": head_mask, <add> "decoder_head_mask": decoder_head_mask, <ide> } <ide> <ide> <ide> def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): <ide> model = BlenderbotSmallModel(config=config).get_decoder().to(torch_device).eval() <ide> input_ids = inputs_dict["input_ids"] <ide> attention_mask = inputs_dict["attention_mask"] <add> head_mask = inputs_dict["head_mask"] <ide> <ide> # first forward pass <del> outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) <add> outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True) <ide> <ide> output, past_key_values = outputs.to_tuple() <ide> <ide> class BlenderbotSmallModelTest(ModelTesterMixin, GenerationTesterMixin, unittest <ide> all_generative_model_classes = (BlenderbotSmallForConditionalGeneration,) if is_torch_available() else () <ide> is_encoder_decoder = True <ide> test_pruning = False <del> test_head_masking = False <add> test_head_masking = True <ide> test_missing_keys = False <ide> <ide> def setUp(self): <ide><path>tests/test_modeling_common.py <ide> def test_forward_signature(self): <ide> "attention_mask", <ide> "decoder_input_ids", <ide> "decoder_attention_mask", <del> "encoder_outputs", <ide> ] <del> self.assertListEqual(arg_names[:5], expected_arg_names) <add> expected_arg_names.extend( <add> ["head_mask", "decoder_head_mask", "encoder_outputs"] <add> if "head_mask" and "decoder_head_mask" in arg_names <add> else ["encoder_outputs"] <add> ) <add> self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) <ide> else: <ide> expected_arg_names = ["input_ids"] <ide> self.assertListEqual(arg_names[:1], expected_arg_names) <ide> def _create_and_check_torchscript(self, config, inputs_dict): <ide> attention_mask = inputs["attention_mask"] <ide> decoder_input_ids = inputs["decoder_input_ids"] <ide> decoder_attention_mask = inputs["decoder_attention_mask"] <del> <ide> traced_model = torch.jit.trace( <ide> model, (input_ids, attention_mask, decoder_input_ids, decoder_attention_mask) <ide> ) <ide> def test_headmasking(self): <ide> head_mask.requires_grad_(requires_grad=True) <ide> inputs = self._prepare_for_class(inputs_dict, model_class).copy() <ide> inputs["head_mask"] = head_mask <add> if model.config.is_encoder_decoder: <add> signature = inspect.signature(model.forward) <add> arg_names = [*signature.parameters.keys()] <add> if "decoder_head_mask" in arg_names: # necessary diferentiation because of T5 model <add> inputs["decoder_head_mask"] = head_mask <ide> <ide> outputs = model(**inputs, return_dict=True) <ide> <ide> def test_headmasking(self): <ide> output.backward() <ide> multihead_outputs = head_mask.grad <ide> <del> attentions = outputs[-1] <del> <del> # Remove Nan <del> for t in attentions: <del> self.assertLess( <del> torch.sum(torch.isnan(t)), t.numel() / 4 <del> ) # Check we don't have more than 25% nans (arbitrary) <del> attentions = [ <del> t.masked_fill(torch.isnan(t), 0.0) for t in attentions <del> ] # remove them (the test is less complete) <del> <ide> self.assertIsNotNone(multihead_outputs) <ide> self.assertEqual(len(multihead_outputs), self.model_tester.num_hidden_layers) <del> self.assertAlmostEqual(attentions[0][..., 0, :, :].flatten().sum().item(), 0.0) <del> self.assertNotEqual(attentions[0][..., -1, :, :].flatten().sum().item(), 0.0) <del> self.assertNotEqual(attentions[1][..., 0, :, :].flatten().sum().item(), 0.0) <del> self.assertAlmostEqual(attentions[-1][..., -2, :, :].flatten().sum().item(), 0.0) <del> self.assertNotEqual(attentions[-1][..., -1, :, :].flatten().sum().item(), 0.0) <add> <add> def check_attentions_validity(attentions): <add> # Remove Nan <add> for t in attentions: <add> self.assertLess( <add> torch.sum(torch.isnan(t)), t.numel() / 4 <add> ) # Check we don't have more than 25% nans (arbitrary) <add> attentions = [ <add> t.masked_fill(torch.isnan(t), 0.0) for t in attentions <add> ] # remove them (the test is less complete) <add> <add> self.assertAlmostEqual(attentions[0][..., 0, :, :].flatten().sum().item(), 0.0) <add> self.assertNotEqual(attentions[0][..., -1, :, :].flatten().sum().item(), 0.0) <add> if len(attentions) > 2: # encoder-decoder models have only 2 layers in each module <add> self.assertNotEqual(attentions[1][..., 0, :, :].flatten().sum().item(), 0.0) <add> self.assertAlmostEqual(attentions[-1][..., -2, :, :].flatten().sum().item(), 0.0) <add> self.assertNotEqual(attentions[-1][..., -1, :, :].flatten().sum().item(), 0.0) <add> <add> if model.config.is_encoder_decoder: <add> check_attentions_validity(outputs.encoder_attentions) <add> check_attentions_validity(outputs.decoder_attentions) <add> else: <add> check_attentions_validity(outputs.attentions) <ide> <ide> def test_head_pruning(self): <ide> if not self.test_pruning: <ide><path>tests/test_modeling_marian.py <ide> def prepare_marian_inputs_dict( <ide> decoder_input_ids, <ide> attention_mask=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> ): <ide> if attention_mask is None: <ide> attention_mask = input_ids.ne(config.pad_token_id) <ide> if decoder_attention_mask is None: <ide> decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) <add> if head_mask is None: <add> head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads) <add> if decoder_head_mask is None: <add> decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads) <ide> return { <ide> "input_ids": input_ids, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <ide> "decoder_attention_mask": attention_mask, <add> "head_mask": head_mask, <add> "decoder_head_mask": decoder_head_mask, <ide> } <ide> <ide> <ide> def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): <ide> model = MarianModel(config=config).get_decoder().to(torch_device).eval() <ide> input_ids = inputs_dict["input_ids"] <ide> attention_mask = inputs_dict["attention_mask"] <add> head_mask = inputs_dict["head_mask"] <ide> <ide> # first forward pass <del> outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) <add> outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True) <ide> <ide> output, past_key_values = outputs.to_tuple() <ide> <ide> class MarianModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase <ide> all_generative_model_classes = (MarianMTModel,) if is_torch_available() else () <ide> is_encoder_decoder = True <ide> test_pruning = False <del> test_head_masking = False <add> test_head_masking = True <ide> test_missing_keys = False <ide> <ide> def setUp(self): <ide><path>tests/test_modeling_mbart.py <ide> def prepare_mbart_inputs_dict( <ide> decoder_input_ids, <ide> attention_mask=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> ): <ide> if attention_mask is None: <ide> attention_mask = input_ids.ne(config.pad_token_id) <ide> if decoder_attention_mask is None: <ide> decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) <add> if head_mask is None: <add> head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads) <add> if decoder_head_mask is None: <add> decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads) <ide> return { <ide> "input_ids": input_ids, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <ide> "decoder_attention_mask": attention_mask, <add> "head_mask": head_mask, <add> "decoder_head_mask": decoder_head_mask, <ide> } <ide> <ide> <ide> def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): <ide> model = MBartModel(config=config).get_decoder().to(torch_device).eval() <ide> input_ids = inputs_dict["input_ids"] <ide> attention_mask = inputs_dict["attention_mask"] <add> head_mask = inputs_dict["head_mask"] <ide> <ide> # first forward pass <del> outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) <add> outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True) <ide> <ide> output, past_key_values = outputs.to_tuple() <ide> <ide> class MBartModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase) <ide> all_generative_model_classes = (MBartForConditionalGeneration,) if is_torch_available() else () <ide> is_encoder_decoder = True <ide> test_pruning = False <del> test_head_masking = False <add> test_head_masking = True <ide> test_missing_keys = False <ide> <ide> def setUp(self): <ide><path>tests/test_modeling_pegasus.py <ide> def prepare_pegasus_inputs_dict( <ide> decoder_input_ids, <ide> attention_mask=None, <ide> decoder_attention_mask=None, <add> head_mask=None, <add> decoder_head_mask=None, <ide> ): <ide> if attention_mask is None: <ide> attention_mask = input_ids.ne(config.pad_token_id) <ide> if decoder_attention_mask is None: <ide> decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) <add> if head_mask is None: <add> head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads) <add> if decoder_head_mask is None: <add> decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads) <ide> return { <ide> "input_ids": input_ids, <ide> "decoder_input_ids": decoder_input_ids, <ide> "attention_mask": attention_mask, <ide> "decoder_attention_mask": attention_mask, <add> "head_mask": head_mask, <add> "decoder_head_mask": decoder_head_mask, <ide> } <ide> <ide> <ide> def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): <ide> model = PegasusModel(config=config).get_decoder().to(torch_device).eval() <ide> input_ids = inputs_dict["input_ids"] <ide> attention_mask = inputs_dict["attention_mask"] <add> head_mask = inputs_dict["head_mask"] <ide> <ide> # first forward pass <del> outputs = model(input_ids, attention_mask=attention_mask, use_cache=True) <add> outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True) <ide> <ide> output, past_key_values = outputs.to_tuple() <ide> <ide> class PegasusModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCas <ide> all_generative_model_classes = (PegasusForConditionalGeneration,) if is_torch_available() else () <ide> is_encoder_decoder = True <ide> test_pruning = False <del> test_head_masking = False <add> test_head_masking = True <ide> test_missing_keys = False <ide> <ide> def setUp(self):
13
Text
Text
fix addon name in npm readme
c9ab11f5ff8d7c9d148d99e5f65873c2d54377b6
<ide><path>npm-react/README.md <ide> var React = require('react'); <ide> <ide> // Addons can be accessed individually from the "addons" directory. <ide> var createFragment = require('react/addons/createFragment'); <del>var immutabilityHelpers = require('react/addons/updates'); <add>var immutabilityHelpers = require('react/addons/update'); <ide> var CSSTransitionGroup = require('react/addons/CSSTransitionGroup'); <ide> ``` <ide> <del>For a complete list of addons visit the [addons documentation page](https://facebook.github.io/react/docs/addons.html) <del> <add>For a complete list of addons visit the [addons documentation page](https://facebook.github.io/react/docs/addons.html).
1
Text
Text
simplify recommendations in process.md
b07dc4d19fdbc15b4f76557dc45b3ce3a43ad0c3
<ide><path>doc/api/process.md <ide> <!-- source_link=lib/process.js --> <ide> <ide> The `process` object provides information about, and control over, the current <del>Node.js process. While it is available as a global, it is recommended to <del>explicitly access it via require or import: <add>Node.js process. <ide> <ide> ```mjs <ide> import process from 'process'; <ide> The following additional handling is implemented if the warning `type` is <ide> ### Avoiding duplicate warnings <ide> <ide> As a best practice, warnings should be emitted only once per process. To do <del>so, it is recommended to place the `emitWarning()` behind a simple boolean <del>flag as illustrated in the example below: <add>so, place the `emitWarning()` behind a boolean. <ide> <ide> ```mjs <ide> import { emitWarning } from 'process';
1
Javascript
Javascript
move standalone functions to the service scope
560951e9881b5f772262804384b4da9f673b925e
<ide><path>src/ng/interpolate.js <ide> function $InterpolateProvider() { <ide> return '\\\\\\' + ch; <ide> } <ide> <add> function unescapeText(text) { <add> return text.replace(escapedStartRegexp, startSymbol). <add> replace(escapedEndRegexp, endSymbol); <add> } <add> <add> function stringify(value) { <add> if (value == null) { // null || undefined <add> return ''; <add> } <add> switch (typeof value) { <add> case 'string': <add> break; <add> case 'number': <add> value = '' + value; <add> break; <add> default: <add> value = toJson(value); <add> } <add> <add> return value; <add> } <add> <ide> /** <ide> * @ngdoc service <ide> * @name $interpolate <ide> function $InterpolateProvider() { <ide> $sce.valueOf(value); <ide> }; <ide> <del> var stringify = function(value) { <del> if (value == null) { // null || undefined <del> return ''; <del> } <del> switch (typeof value) { <del> case 'string': <del> break; <del> case 'number': <del> value = '' + value; <del> break; <del> default: <del> value = toJson(value); <del> } <del> <del> return value; <del> }; <del> <ide> return extend(function interpolationFn(context) { <ide> var i = 0; <ide> var ii = expressions.length; <ide> function $InterpolateProvider() { <ide> }); <ide> } <ide> <del> function unescapeText(text) { <del> return text.replace(escapedStartRegexp, startSymbol). <del> replace(escapedEndRegexp, endSymbol); <del> } <del> <ide> function parseStringifyInterceptor(value) { <ide> try { <ide> value = getValue(value);
1
Text
Text
update upgrade docs
3f22451545704a27388eb9d352d4e467c684e228
<ide><path>docs/upgrading.md <ide> description: Learn how to upgrade Next.js. <ide> <ide> # Upgrade Guide <ide> <add>## Upgrading from 11 to 12 <add> <add>### SWC replacing Babel <add> <add>Next.js now uses Rust-based compiler [SWC](https://swc.rs/) to compile JavaScript/TypeScript. This new compiler is up to 17x faster than Babel when compiling individual files and up to 5x faster Fast Refresh. <add> <add>Next.js provides full backwards compatibility with applications that have [custom Babel configuration](https://nextjs.org/docs/advanced-features/customizing-babel-config). All transformations that Next.js handles by default like styled-jsx and tree-shaking of `getStaticProps` / `getStaticPaths` / `getServerSideProps` have been ported to Rust. <add> <add>When an application has a custom Babel configuration, Next.js will automatically opt-out of using SWC for compiling JavaScript/Typescript and will fall back to using Babel in the same way that it was used in Next.js 11. <add> <add>Many of the integrations with external libraries that currently require custom Babel transformations will be ported to Rust-based SWC transforms in the near future. These include but are not limited to: <add> <add>- Styled Components <add>- Emotion <add>- Relay <add> <add>In order to prioritize transforms that will help you adopt SWC, please provide your `.babelrc` on [the feedback thread](https://github.com/vercel/next.js/discussions/30174). <add> <add>### SWC replacing Terser for minification <add> <add>You can opt-in to replacing Terser with SWC for minifying JavaScript up to 7x faster using a flag in `next.config.js`: <add> <add>```js <add>module.exports = { <add> swcMinify: true, <add>} <add>``` <add> <add>Minification using SWC is an opt-in flag to ensure it can be tested against more real-world Next.js applications before it becomes the default in Next.js 12.1. If you have feedback about minification, please leave it on [the feedback thread](https://github.com/vercel/next.js/discussions/30237). <add> <add>### `next/image` changed wrapping element <add> <add>`next/image` now renders the `<img>` inside a `<span>` instead of `<div>`. <add> <add>If your application has specific CSS targeting span, for example `.container span`, upgrading to Next.js 12 might incorrectly match the wrapping element inside the `<Image>` component. You can avoid this by restricting the selector to a specific class such as `.container span.item` and updating the relevant component with that className, such as `<span className="item" />`. <add> <add>If you application has specific CSS targeting the `next/image` `<div>` tag, for example `.container div`, it may not match anymore. You can update the selector `.container span`, or preferably, add a new `<div className="wrapper">` wrapping the `<Image>` component and target that instead such as `.container .wrapper`. <add> <add>The `className` prop is unchanged and will still be passed to the underlying `<img>` element. <add> <add>See the [documentation](https://nextjs.org/docs/basic-features/image-optimization#styling) for more info. <add> <add>### Webpack 4 support has been removed <add> <add>If you are already using webpack 5 you can skip this section. <add> <add>Next.js has adopted webpack 5 as the default for compilation in Next.js 11. As communicated in the [webpack 5 upgrading documentation](https://nextjs.org/docs/messages/webpack5) Next.js 12 removes support for webpack 4. <add> <add>If your application is still using webpack 4 using the opt-out flag you will now see an error linking to the [webpack 5 upgrading documentation](https://nextjs.org/docs/messages/webpack5). <add> <add>### `target` option deprecated <add> <add>If you do not have `target` in `next.config.js` you can skip this section. <add> <add>The target option has been deprecated in favor of built-in support for tracing what dependencies are needed to run a page. <add> <add>During `next build`, Next.js will automatically trace each page and its dependencies to determine all of the files that are needed for deploying a production version of your application. <add> <add>If you are currently using the `target` option set to `serverless` please read the [documentation on how to leverage the new output](https://nextjs.org/docs/advanced-features/output-file-tracing). <add> <ide> ## Upgrading from version 10 to 11 <ide> <ide> ### Upgrade React version to latest
1
Javascript
Javascript
remove unnecessary array
a050008557631dce1049636f957abff7005d0542
<ide><path>packages/ember-handlebars/lib/controls/select.js <ide> Ember.Select = Ember.View.extend( <ide> <ide> groupedContent: Ember.computed(function() { <ide> var groupPath = get(this, 'optionGroupPath'); <del> var groupedContent = Ember.A([]); <add> var groupedContent = Ember.A(); <ide> <ide> forEach(get(this, 'content'), function(item) { <ide> var label = get(item, groupPath); <ide> <ide> if (get(groupedContent, 'lastObject.label') !== label) { <ide> groupedContent.pushObject({ <ide> label: label, <del> content: Ember.A([]) <add> content: Ember.A() <ide> }); <ide> } <ide> <ide><path>packages/ember-handlebars/tests/controls/select_test.js <ide> test("upon content change with Array-like content, the DOM should reflect the se <ide> sylvain = {id: 5, name: 'Sylvain'}; <ide> <ide> var proxy = Ember.ArrayProxy.create({ <del> content: Ember.A([]), <add> content: Ember.A(), <ide> selectedOption: sylvain <ide> }); <ide> <ide><path>packages/ember-handlebars/tests/helpers/each_test.js <ide> test("it supports {{else}}", function() { <ide> assertHTML(view, "onetwo"); <ide> <ide> Ember.run(function() { <del> view.set('items', Ember.A([])); <add> view.set('items', Ember.A()); <ide> }); <ide> <ide> assertHTML(view, "Nothing"); <ide><path>packages/ember-handlebars/tests/helpers/if_unless_test.js <ide> test("The `if` helper updates if an object proxy gains or loses context", functi <ide> <ide> test("The `if` helper updates if an array is empty or not", function() { <ide> view = Ember.View.create({ <del> array: Ember.A([]), <add> array: Ember.A(), <ide> <ide> template: compile('{{#if view.array}}Yep{{/if}}') <ide> }); <ide><path>packages/ember-handlebars/tests/helpers/yield_test.js <ide> test("templates should yield to block, when the yield is embedded in a hierarchy <ide> layout: Ember.Handlebars.compile('<div class="times">{{#each view.index}}{{yield}}{{/each}}</div>'), <ide> n: null, <ide> index: Ember.computed(function() { <del> var n = Ember.get(this, 'n'), indexArray = Ember.A([]); <add> var n = Ember.get(this, 'n'), indexArray = Ember.A(); <ide> for (var i=0; i < n; i++) { <ide> indexArray[i] = i; <ide> } <ide><path>packages/ember-runtime/lib/mixins/array.js <ide> Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.protot <ide> @return {Array} New array with specified slice <ide> */ <ide> slice: function(beginIndex, endIndex) { <del> var ret = Ember.A([]); <add> var ret = Ember.A(); <ide> var length = get(this, 'length') ; <ide> if (isNone(beginIndex)) beginIndex = 0 ; <ide> if (isNone(endIndex) || (endIndex > length)) endIndex = length ; <ide><path>packages/ember-runtime/lib/mixins/enumerable.js <ide> Ember.Enumerable = Ember.Mixin.create({ <ide> @return {Array} The mapped array. <ide> */ <ide> map: function(callback, target) { <del> var ret = Ember.A([]); <add> var ret = Ember.A(); <ide> this.forEach(function(x, idx, i) { <ide> ret[idx] = callback.call(target, x, idx,i); <ide> }); <ide> Ember.Enumerable = Ember.Mixin.create({ <ide> @return {Array} A filtered array. <ide> */ <ide> filter: function(callback, target) { <del> var ret = Ember.A([]); <add> var ret = Ember.A(); <ide> this.forEach(function(x, idx, i) { <ide> if (callback.call(target, x, idx, i)) ret.push(x); <ide> }); <ide> Ember.Enumerable = Ember.Mixin.create({ <ide> @return {Array} return values from calling invoke. <ide> */ <ide> invoke: function(methodName) { <del> var args, ret = Ember.A([]); <add> var args, ret = Ember.A(); <ide> if (arguments.length>1) args = a_slice.call(arguments, 1); <ide> <ide> this.forEach(function(x, idx) { <ide> Ember.Enumerable = Ember.Mixin.create({ <ide> @return {Array} the enumerable as an array. <ide> */ <ide> toArray: function() { <del> var ret = Ember.A([]); <add> var ret = Ember.A(); <ide> this.forEach(function(o, idx) { ret[idx] = o; }); <ide> return ret ; <ide> }, <ide> Ember.Enumerable = Ember.Mixin.create({ <ide> */ <ide> without: function(value) { <ide> if (!this.contains(value)) return this; // nothing to do <del> var ret = Ember.A([]); <add> var ret = Ember.A(); <ide> this.forEach(function(k) { <ide> if (k !== value) ret[ret.length] = k; <ide> }) ; <ide> Ember.Enumerable = Ember.Mixin.create({ <ide> @return {Ember.Enumerable} <ide> */ <ide> uniq: function() { <del> var ret = Ember.A([]); <add> var ret = Ember.A(); <ide> this.forEach(function(k){ <ide> if (a_indexOf(ret, k)<0) ret.push(k); <ide> }); <ide><path>packages/ember-runtime/tests/core/is_array_test.js <ide> module("Ember Type Checking"); <ide> <ide> test("Ember.isArray" ,function(){ <del> var arrayProxy = Ember.ArrayProxy.create({ content: Ember.A([]) }); <add> var arrayProxy = Ember.ArrayProxy.create({ content: Ember.A() }); <ide> <ide> equal(Ember.isArray(arrayProxy), true, "[]"); <ide> }); <ide><path>packages/ember-runtime/tests/core/is_empty_test.js <ide> module("Ember.isEmpty"); <ide> <ide> test("Ember.isEmpty", function() { <del> var arrayProxy = Ember.ArrayProxy.create({ content: Ember.A([]) }); <add> var arrayProxy = Ember.ArrayProxy.create({ content: Ember.A() }); <ide> <ide> equal(true, Ember.isEmpty(arrayProxy), "for an ArrayProxy that has empty content"); <ide> }); <ide><path>packages/ember-runtime/tests/system/array_proxy/content_update_test.js <ide> test("The `contentArrayDidChange` method is invoked after `content` is updated." <ide> var proxy, observerCalled = false; <ide> <ide> proxy = Ember.ArrayProxy.createWithMixins({ <del> content: Ember.A([]), <add> content: Ember.A(), <ide> <ide> arrangedContent: Ember.computed('content', function(key, value) { <ide> // setup arrangedContent as a different object than content,
10
Ruby
Ruby
add circleci to env check
f457c6ab327b0520c61021437b87be0cedc5f770
<ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb <ide> def check_xcode_up_to_date <ide> return unless MacOS::Xcode.installed? <ide> return unless MacOS::Xcode.outdated? <ide> <del> # Travis CI images are going to end up outdated so don't complain. <del> return if ENV["TRAVIS"] <add> # CI images are going to end up outdated so don't complain. <add> return if ENV["TRAVIS"] || ENV["CIRCLECI"] <ide> <ide> message = <<-EOS.undent <ide> Your Xcode (#{MacOS::Xcode.version}) is outdated.
1
Javascript
Javascript
add test for importing acorn
7ce6d23387967db636d1f15493d770fadcfb86c7
<ide><path>test/parallel/test-require-deps-deprecation.js <ide> 'use strict'; <ide> <ide> const common = require('../common'); <add>const assert = require('assert'); <ide> // The v8 modules when imported leak globals. Disable global check. <ide> common.globalCheck = false; <ide> <ide> const deprecatedModules = [ <ide> 'v8/tools/tickprocessor-driver' <ide> ]; <ide> <add>// Newly added deps that do not have a deprecation wrapper around it would <add>// throw an error, but no warning would be emitted. <add>const deps = [ <add> 'acorn/dist/acorn', <add> 'acorn/dist/walk' <add>]; <add> <ide> common.expectWarning('DeprecationWarning', deprecatedModules.map((m) => { <ide> return `Requiring Node.js-bundled '${m}' module is deprecated. ` + <ide> 'Please install the necessary module locally.'; <ide> for (const m of deprecatedModules) { <ide> require(m); <ide> } catch (err) {} <ide> } <add> <add>for (const m of deps) { <add> assert.throws(() => { require(m); }, /^Error: Cannot find module/); <add>}
1
Javascript
Javascript
put shell scripts outside of asar
33f5cdd7b3fa007fd5dbfc32c09dd3ab1f9f8687
<ide><path>script/lib/include-path-in-packaged-app.js <ide> const EXCLUDE_REGEXPS_SOURCES = [ <ide> // Ignore *.cc and *.h files from native modules <ide> escapeRegExp(path.sep) + '.+\\.(cc|h)$', <ide> <add> // Shell scripts need to be outside of ASAR because Git will call them <add> // directly <add> escapeRegExp(path.join('node_modules', 'github', 'bin')), <add> <ide> // Ignore build files <ide> escapeRegExp(path.sep) + 'binding\\.gyp$', <ide> escapeRegExp(path.sep) + '.+\\.target.mk$',
1