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
Text
Text
add v4.0.0-beta.6 to changelog
73baf3d3cb46c5f645e0d6a4fed0530463366b43
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.0.0-beta.6 (October 26, 2021) <add> <add>- [#19799](https://github.com/emberjs/ember.js/pull/19799) / [glimmerjs/glimmer-vm#1354](https://github.com/glimmerjs/glimmer-vm/pull/1354) Fixes for errors while precompiling inline templates (introduced in 3.28.2) <add> <ide> ### v4.0.0-beta.5 (October 11, 2021) <ide> <ide> - [#19761](https://github.com/emberjs/ember.js/pull/19761) [BREAKING] Require ember-auto-import >= 2 or higher to enable ember-source to become a v2 addon in the 4.x cycle
1
PHP
PHP
improve error message
89250d1dd2896b26e70c13466da1b8d07f4ac56e
<ide><path>src/View/Form/ContextFactory.php <ide> public function get(ServerRequest $request, array $data = []) <ide> $context = new NullContext($request, $data); <ide> } <ide> if (!($context instanceof ContextInterface)) { <del> throw new RuntimeException( <del> 'Context objects must implement Cake\View\Form\ContextInterface' <del> ); <add> throw new RuntimeException(sprintf( <add> 'Context providers must return object implementing %s. Got "%s" instead.', <add> 'Cake\View\Form\ContextInterface', <add> is_object($context) ? get_class($context) : gettype($context) <add> )); <ide> } <ide> <ide> return $context; <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testAddContextProviderAdd() <ide> * Test adding an invalid context class. <ide> * <ide> * @expectedException \RuntimeException <del> * @expectedExceptionMessage Context objects must implement Cake\View\Form\ContextInterface <add> * @expectedExceptionMessage Context providers must return object implementing Cake\View\Form\ContextInterface. Got "stdClass" instead. <ide> * @return void <ide> */ <ide> public function testAddContextProviderInvalid()
2
Go
Go
remove the last of pkg/httputil
4060d6ee0b130cf74294c309dfbd3c860fd2a7f8
<ide><path>builder/dockerfile/copy.go <ide> import ( <ide> <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/builder/remotecontext" <del> "github.com/docker/docker/pkg/httputils" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/progress" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> func errOnSourceDownload(_ string) (builder.Source, string, error) { <ide> } <ide> <ide> func downloadSource(output io.Writer, stdout io.Writer, srcURL string) (remote builder.Source, p string, err error) { <del> // get filename from URL <ide> u, err := url.Parse(srcURL) <ide> if err != nil { <ide> return <ide> func downloadSource(output io.Writer, stdout io.Writer, srcURL string) (remote b <ide> return <ide> } <ide> <del> // Initiate the download <del> resp, err := httputils.Download(srcURL) <add> resp, err := remotecontext.GetWithStatusError(srcURL) <ide> if err != nil { <ide> return <ide> } <ide><path>builder/remotecontext/remote.go <ide> package remotecontext <ide> <ide> import ( <ide> "bytes" <del> "errors" <ide> "fmt" <ide> "io" <ide> "io/ioutil" <add> "net/http" <ide> "regexp" <ide> <ide> "github.com/docker/docker/builder" <del> "github.com/docker/docker/pkg/httputils" <add> "github.com/pkg/errors" <ide> ) <ide> <ide> // When downloading remote contexts, limit the amount (in bytes) <ide> var mimeRe = regexp.MustCompile(acceptableRemoteMIME) <ide> // to be returned. If no match is found, it is assumed the body is a tar stream (compressed or not). <ide> // In either case, an (assumed) tar stream is passed to MakeTarSumContext whose result is returned. <ide> func MakeRemoteContext(remoteURL string, contentTypeHandlers map[string]func(io.ReadCloser) (io.ReadCloser, error)) (builder.Source, error) { <del> f, err := httputils.Download(remoteURL) <add> f, err := GetWithStatusError(remoteURL) <ide> if err != nil { <ide> return nil, fmt.Errorf("error downloading remote context %s: %v", remoteURL, err) <ide> } <ide> func MakeRemoteContext(remoteURL string, contentTypeHandlers map[string]func(io. <ide> return MakeTarSumContext(contextReader) <ide> } <ide> <add>// GetWithStatusError does an http.Get() and returns an error if the <add>// status code is 4xx or 5xx. <add>func GetWithStatusError(url string) (resp *http.Response, err error) { <add> if resp, err = http.Get(url); err != nil { <add> return nil, err <add> } <add> if resp.StatusCode < 400 { <add> return resp, nil <add> } <add> msg := fmt.Sprintf("failed to GET %s with status %s", url, resp.Status) <add> body, err := ioutil.ReadAll(resp.Body) <add> resp.Body.Close() <add> if err != nil { <add> return nil, errors.Wrapf(err, msg+": error reading body") <add> } <add> return nil, errors.Errorf(msg+": %s", bytes.TrimSpace(body)) <add>} <add> <ide> // inspectResponse looks into the http response data at r to determine whether its <ide> // content-type is on the list of acceptable content types for remote build contexts. <ide> // This function returns: <ide><path>builder/remotecontext/remote_test.go <ide> import ( <ide> <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/pkg/archive" <add> "github.com/docker/docker/pkg/testutil" <add> "github.com/stretchr/testify/assert" <add> "github.com/stretchr/testify/require" <ide> ) <ide> <ide> var binaryContext = []byte{0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00} //xz magic <ide> func TestMakeRemoteContext(t *testing.T) { <ide> t.Fatalf("File %s should have position 0, got %d", builder.DefaultDockerfileName, fileInfo.Pos()) <ide> } <ide> } <add> <add>func TestGetWithStatusError(t *testing.T) { <add> var testcases = []struct { <add> err error <add> statusCode int <add> expectedErr string <add> expectedBody string <add> }{ <add> { <add> statusCode: 200, <add> expectedBody: "THE BODY", <add> }, <add> { <add> statusCode: 400, <add> expectedErr: "with status 400 Bad Request: broke", <add> expectedBody: "broke", <add> }, <add> } <add> for _, testcase := range testcases { <add> ts := httptest.NewServer( <add> http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <add> buffer := bytes.NewBufferString(testcase.expectedBody) <add> w.WriteHeader(testcase.statusCode) <add> w.Write(buffer.Bytes()) <add> }), <add> ) <add> defer ts.Close() <add> response, err := GetWithStatusError(ts.URL) <add> <add> if testcase.expectedErr == "" { <add> require.NoError(t, err) <add> <add> body, err := testutil.ReadBody(response.Body) <add> require.NoError(t, err) <add> assert.Contains(t, string(body), testcase.expectedBody) <add> } else { <add> testutil.ErrorContains(t, err, testcase.expectedErr) <add> } <add> } <add>} <ide><path>daemon/import.go <ide> import ( <ide> "github.com/docker/distribution/reference" <ide> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/builder/dockerfile" <add> "github.com/docker/docker/builder/remotecontext" <ide> "github.com/docker/docker/dockerversion" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/archive" <del> "github.com/docker/docker/pkg/httputils" <ide> "github.com/docker/docker/pkg/progress" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> "github.com/pkg/errors" <ide> func (daemon *Daemon) ImportImage(src string, repository, tag string, msg string <ide> return err <ide> } <ide> <del> resp, err = httputils.Download(u.String()) <add> resp, err = remotecontext.GetWithStatusError(u.String()) <ide> if err != nil { <ide> return err <ide> } <ide><path>pkg/httputils/httputils.go <del>package httputils <del> <del>import ( <del> "fmt" <del> "net/http" <del>) <del> <del>// Download requests a given URL and returns an io.Reader. <del>func Download(url string) (resp *http.Response, err error) { <del> if resp, err = http.Get(url); err != nil { <del> return nil, err <del> } <del> if resp.StatusCode >= 400 { <del> return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status) <del> } <del> return resp, nil <del>} <ide><path>pkg/httputils/httputils_test.go <del>package httputils <del> <del>import ( <del> "fmt" <del> "io/ioutil" <del> "net/http" <del> "net/http/httptest" <del> "testing" <del> <del> "github.com/docker/docker/pkg/testutil" <del> "github.com/stretchr/testify/assert" <del> "github.com/stretchr/testify/require" <del>) <del> <del>func TestDownload(t *testing.T) { <del> expected := "Hello, docker !" <del> ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <del> fmt.Fprintf(w, expected) <del> })) <del> defer ts.Close() <del> response, err := Download(ts.URL) <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> actual, err := ioutil.ReadAll(response.Body) <del> response.Body.Close() <del> require.NoError(t, err) <del> assert.Equal(t, expected, string(actual)) <del>} <del> <del>func TestDownload400Errors(t *testing.T) { <del> expectedError := "Got HTTP status code >= 400: 403 Forbidden" <del> ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <del> // 403 <del> http.Error(w, "something failed (forbidden)", http.StatusForbidden) <del> })) <del> defer ts.Close() <del> // Expected status code = 403 <del> _, err := Download(ts.URL) <del> assert.EqualError(t, err, expectedError) <del>} <del> <del>func TestDownloadOtherErrors(t *testing.T) { <del> _, err := Download("I'm not an url..") <del> testutil.ErrorContains(t, err, "unsupported protocol scheme") <del>}
6
Python
Python
add sp_model_kwargs to unpickle of xlm roberta tok
e0db8276a635b674553cf38aa23699c6340cffd6
<ide><path>src/transformers/models/xlm_roberta/tokenization_xlm_roberta.py <ide> def __init__( <ide> # Mask token behave like a normal word, i.e. include the space before it <ide> mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token <ide> <del> sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs <add> self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs <ide> <ide> super().__init__( <ide> bos_token=bos_token, <ide> def __init__( <ide> cls_token=cls_token, <ide> pad_token=pad_token, <ide> mask_token=mask_token, <del> sp_model_kwargs=sp_model_kwargs, <add> sp_model_kwargs=self.sp_model_kwargs, <ide> **kwargs, <ide> ) <ide> <del> self.sp_model = spm.SentencePieceProcessor(**sp_model_kwargs) <add> self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) <ide> self.sp_model.Load(str(vocab_file)) <ide> self.vocab_file = vocab_file <ide> <ide> def __getstate__(self): <ide> <ide> def __setstate__(self, d): <ide> self.__dict__ = d <del> self.sp_model = spm.SentencePieceProcessor() <add> <add> # for backward compatibility <add> if not hasattr(self, "sp_model_kwargs"): <add> self.sp_model_kwargs = {} <add> <add> self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) <ide> self.sp_model.Load(self.vocab_file) <ide> <ide> def build_inputs_with_special_tokens( <ide><path>tests/test_tokenization_xlm_roberta.py <ide> <ide> import itertools <ide> import os <add>import pickle <ide> import unittest <ide> <ide> from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast <ide> def test_subword_regularization_tokenizer(self): <ide> <ide> self.assertFalse(all_equal) <ide> <add> def test_pickle_subword_regularization_tokenizer(self): <add> """Google pickle __getstate__ __setstate__ if you are struggling with this.""" <add> # Subword regularization is only available for the slow tokenizer. <add> sp_model_kwargs = {"enable_sampling": True, "alpha": 0.1, "nbest_size": -1} <add> tokenizer = XLMRobertaTokenizer(SAMPLE_VOCAB, keep_accents=True, sp_model_kwargs=sp_model_kwargs) <add> tokenizer_bin = pickle.dumps(tokenizer) <add> tokenizer_new = pickle.loads(tokenizer_bin) <add> <add> self.assertIsNotNone(tokenizer_new.sp_model_kwargs) <add> self.assertTrue(isinstance(tokenizer_new.sp_model_kwargs, dict)) <add> self.assertEqual(tokenizer_new.sp_model_kwargs, sp_model_kwargs) <add> <ide> @cached_property <ide> def big_tokenizer(self): <ide> return XLMRobertaTokenizer.from_pretrained("xlm-roberta-base")
2
PHP
PHP
remove inline assignment in view class
089efc14376169611ef498a541a1e57ed91a4896
<ide><path>src/View/View.php <ide> public function render($view = null, $layout = null) <ide> $this->layout = $layout; <ide> } <ide> <del> if ($view !== false && $viewFileName = $this->_getViewFileName($view)) { <add> $viewFileName = $view !== false ? $this->_getViewFileName($view) : null; <add> if ($viewFileName) { <ide> $this->_currentType = static::TYPE_TEMPLATE; <ide> $this->dispatchEvent('View.beforeRender', [$viewFileName]); <ide> $this->Blocks->set('content', $this->_render($viewFileName));
1
Python
Python
add intel 64-bit c compiler. closes #960
dede2691e7db9f0dacbc55444e5495856fa3f504
<ide><path>numpy/distutils/ccompiler.py <ide> def CCompiler_cxx_compiler(self): <ide> "Intel C Compiler for 32-bit applications") <ide> compiler_class['intele'] = ('intelccompiler','IntelItaniumCCompiler', <ide> "Intel C Itanium Compiler for Itanium-based applications") <add>compiler_class['intelem'] = ('intelccompiler','IntelEM64TCCompiler', <add> "Intel C Compiler for 64-bit applications") <ide> compiler_class['pathcc'] = ('pathccompiler','PathScaleCCompiler', <ide> "PathScale Compiler for SiCortex-based applications") <ide> ccompiler._default_compilers += (('linux.*','intel'), <ide> ('linux.*','intele'), <add> ('linux.*','intelem'), <ide> ('linux.*','pathcc')) <ide> <ide> if sys.platform == 'win32': <ide><path>numpy/distutils/intelccompiler.py <ide> class IntelCCompiler(UnixCCompiler): <ide> <ide> compiler_type = 'intel' <ide> cc_exe = 'icc' <add> cc_args = 'fPIC' <ide> <ide> def __init__ (self, verbose=0, dry_run=0, force=0): <ide> UnixCCompiler.__init__ (self, verbose,dry_run, force) <add> self.cc_exe = 'icc -fPIC' <ide> compiler = self.cc_exe <ide> self.set_executables(compiler=compiler, <ide> compiler_so=compiler, <ide> class IntelItaniumCCompiler(IntelCCompiler): <ide> for cc_exe in map(find_executable,['icc','ecc']): <ide> if cc_exe: <ide> break <add> <add>class IntelEM64TCCompiler(UnixCCompiler): <add> <add>""" A modified Intel x86_64 compiler compatible with a 64bit gcc built Python. <add> """ <add> <add> compiler_type = 'intelem' <add> cc_exe = 'icc -m64 -fPIC' <add> cc_args = "-fPIC" <add> def __init__ (self, verbose=0, dry_run=0, force=0): <add> UnixCCompiler.__init__ (self, verbose,dry_run, force) <add> self.cc_exe = 'icc -m64 -fPIC' <add> compiler = self.cc_exe <add> self.set_executables(compiler=compiler, <add> compiler_so=compiler, <add> compiler_cxx=compiler, <add> linker_exe=compiler, <add> linker_so=compiler + ' -shared')
2
Go
Go
fix containerd waittimeout
3bc02fc04005ff06730f178d5b8371f5d05ada0f
<ide><path>cmd/dockerd/daemon.go <ide> func (cli *DaemonCli) start(opts *daemonOptions) (err error) { <ide> } <ide> <ide> ctx, cancel := context.WithCancel(context.Background()) <del> if err := cli.initContainerD(ctx); err != nil { <add> waitForContainerDShutdown, err := cli.initContainerD(ctx) <add> if waitForContainerDShutdown != nil { <add> defer waitForContainerDShutdown(10 * time.Second) <add> } <add> if err != nil { <ide> cancel() <ide> return err <ide> } <ide><path>cmd/dockerd/daemon_unix.go <ide> func newCgroupParent(config *config.Config) string { <ide> return cgroupParent <ide> } <ide> <del>func (cli *DaemonCli) initContainerD(ctx context.Context) error { <add>func (cli *DaemonCli) initContainerD(ctx context.Context) (func(time.Duration) error, error) { <add> var waitForShutdown func(time.Duration) error <ide> if cli.Config.ContainerdAddr == "" { <ide> systemContainerdAddr, ok, err := systemContainerdRunning(cli.Config.IsRootless()) <ide> if err != nil { <del> return errors.Wrap(err, "could not determine whether the system containerd is running") <add> return nil, errors.Wrap(err, "could not determine whether the system containerd is running") <ide> } <ide> if !ok { <ide> opts, err := cli.getContainerdDaemonOpts() <ide> if err != nil { <del> return errors.Wrap(err, "failed to generate containerd options") <add> return nil, errors.Wrap(err, "failed to generate containerd options") <ide> } <ide> <ide> r, err := supervisor.Start(ctx, filepath.Join(cli.Config.Root, "containerd"), filepath.Join(cli.Config.ExecRoot, "containerd"), opts...) <ide> if err != nil { <del> return errors.Wrap(err, "failed to start containerd") <add> return nil, errors.Wrap(err, "failed to start containerd") <ide> } <ide> cli.Config.ContainerdAddr = r.Address() <ide> <ide> // Try to wait for containerd to shutdown <del> defer r.WaitTimeout(10 * time.Second) <add> waitForShutdown = r.WaitTimeout <ide> } else { <ide> cli.Config.ContainerdAddr = systemContainerdAddr <ide> } <ide> } <ide> <del> return nil <add> return waitForShutdown, nil <ide> } <ide><path>cmd/dockerd/daemon_windows.go <ide> import ( <ide> "fmt" <ide> "net" <ide> "os" <add> "time" <ide> <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/docker/docker/libcontainerd/supervisor" <ide> func newCgroupParent(config *config.Config) string { <ide> return "" <ide> } <ide> <del>func (cli *DaemonCli) initContainerD(_ context.Context) error { <add>func (cli *DaemonCli) initContainerD(_ context.Context) (func(time.Duration) error, error) { <ide> system.InitContainerdRuntime(cli.Config.Experimental, cli.Config.ContainerdAddr) <del> return nil <add> return nil, nil <ide> }
3
Mixed
Text
add django 1.11 into *.md and setup.py
34f88dc3f8c3a03e4e02537d519636d66f9a9cfd
<ide><path>README.md <ide> There is a live example API for testing purposes, [available here][sandbox]. <ide> # Requirements <ide> <ide> * Python (2.7, 3.2, 3.3, 3.4, 3.5) <del>* Django (1.8, 1.9, 1.10) <add>* Django (1.8, 1.9, 1.10, 1.11) <ide> <ide> # Installation <ide> <ide><path>docs/index.md <ide> continued development by **[signing up for a paid plan][funding]**. <ide> REST framework requires the following: <ide> <ide> * Python (2.7, 3.2, 3.3, 3.4, 3.5) <del>* Django (1.8, 1.9, 1.10) <add>* Django (1.8, 1.9, 1.10, 1.11) <ide> <ide> The following packages are optional: <ide> <ide><path>setup.py <ide> def get_package_data(package): <ide> 'Framework :: Django :: 1.8', <ide> 'Framework :: Django :: 1.9', <ide> 'Framework :: Django :: 1.10', <add> 'Framework :: Django :: 1.11', <ide> 'Intended Audience :: Developers', <ide> 'License :: OSI Approved :: BSD License', <ide> 'Operating System :: OS Independent',
3
PHP
PHP
add missing typehint
c8516edc48beda4a948f3a61a714cd6c798c595c
<ide><path>src/Log/Engine/BaseLog.php <ide> protected function _format(string $message, array $context = []): string <ide> * <ide> * @return string <ide> */ <del> protected function _getFormattedDate() <add> protected function _getFormattedDate(): string <ide> { <ide> return date($this->_config['dateFormat']); <ide> }
1
PHP
PHP
fix docblocks params
410d0c83d51f55cd428657e71891f918f73b8d7d
<ide><path>src/Illuminate/Auth/Notifications/VerifyEmail.php <ide> public function toMail($notifiable) <ide> /** <ide> * Get the verify email notification mail message for the given URL. <ide> * <del> * @param string $verificationUrl <add> * @param string $url <ide> * @return \Illuminate\Notifications\Messages\MailMessage <ide> */ <ide> protected function buildMailMessage($url) <ide><path>src/Illuminate/Database/Concerns/ManagesTransactions.php <ide> public function transactionLevel() <ide> /** <ide> * Execute the callback after a transaction commits. <ide> * <add> * @param callable $callback <ide> * @return void <ide> */ <ide> public function afterCommit($callback) <ide><path>src/Illuminate/Database/Console/DumpCommand.php <ide> class DumpCommand extends Command <ide> /** <ide> * Execute the console command. <ide> * <add> * @param \Illuminate\Database\ConnectionResolverInterface $connections <add> * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher <ide> * @return int <ide> */ <ide> public function handle(ConnectionResolverInterface $connections, Dispatcher $dispatcher) <ide><path>src/Illuminate/Database/Eloquent/Factories/Factory.php <ide> abstract class Factory <ide> * Create a new factory instance. <ide> * <ide> * @param int|null $count <del> * @param \Illuminate\Support\Collection $states <del> * @param \Illuminate\Support\Collection $has <del> * @param \Illuminate\Support\Collection $for <del> * @param \Illuminate\Support\Collection $afterMaking <del> * @param \Illuminate\Support\Collection $afterCreating <del> * @param string $connection <add> * @param \Illuminate\Support\Collection|null $states <add> * @param \Illuminate\Support\Collection|null $has <add> * @param \Illuminate\Support\Collection|null $for <add> * @param \Illuminate\Support\Collection|null $afterMaking <add> * @param \Illuminate\Support\Collection|null $afterCreating <add> * @param string|null $connection <ide> * @return void <ide> */ <ide> public function __construct($count = null, <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphTo.php <ide> public function morphWithCount(array $withCount) <ide> /** <ide> * Specify constraints on the query for a given morph types. <ide> * <del> * @param array $with <add> * @param array $callbacks <ide> * @return \Illuminate\Database\Eloquent\Relations\MorphTo <ide> */ <ide> public function constrain(array $callbacks) <ide><path>src/Illuminate/Database/PDO/SqlServerConnection.php <ide> public function rollBack() <ide> /** <ide> * Wrap quotes around the given input. <ide> * <del> * @param string $input <del> * @param string $type <add> * @param string $value <add> * @param int $type <ide> * @return string <ide> */ <ide> public function quote($value, $type = ParameterType::STRING) <ide><path>src/Illuminate/Database/PostgresConnection.php <ide> protected function getDefaultSchemaGrammar() <ide> /** <ide> * Get the schema state for the connection. <ide> * <del> * @param \Illuminate\Filesystem\Filesystem|null $files <add> * @param \Illuminate\Database\Filesystem|null $files <ide> * @param callable|null $processFactory <ide> * @return \Illuminate\Database\Schema\PostgresSchemaState <ide> */ <ide><path>src/Illuminate/Database/Query/Grammars/MySqlGrammar.php <ide> class MySqlGrammar extends Grammar <ide> /** <ide> * Add a "where null" clause to the query. <ide> * <del> * @param string|array $columns <del> * @param string $boolean <del> * @param bool $not <del> * @return $this <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param array $where <add> * @return string <ide> */ <ide> protected function whereNull(Builder $query, $where) <ide> { <ide> protected function whereNull(Builder $query, $where) <ide> /** <ide> * Add a "where not null" clause to the query. <ide> * <del> * @param string|array $columns <del> * @param string $boolean <del> * @return $this <add> * @param \Illuminate\Database\Query\Builder $query <add> * @param array $where <add> * @return string <ide> */ <ide> protected function whereNotNull(Builder $query, $where) <ide> { <ide><path>src/Illuminate/Database/Schema/SchemaState.php <ide> abstract class SchemaState <ide> * Create a new dumper instance. <ide> * <ide> * @param \Illuminate\Database\Connection $connection <del> * @param \Illuminate\Filesystem\Filesystem $files <del> * @param callable $processFactory <add> * @param \Illuminate\Filesystem\Filesystem|null $files <add> * @param callable|null $processFactory <ide> * @return void <ide> */ <ide> public function __construct(Connection $connection, Filesystem $files = null, callable $processFactory = null) <ide><path>src/Illuminate/Database/Schema/SqliteSchemaState.php <ide> public function dump(Connection $connection, $path) <ide> /** <ide> * Append the migration data to the schema dump. <ide> * <add> * @param string $path <ide> * @return void <ide> */ <ide> protected function appendMigrationData(string $path) <ide> protected function baseCommand() <ide> /** <ide> * Get the base variables for a dump / load command. <ide> * <add> * @param array $config <ide> * @return array <ide> */ <ide> protected function baseVariables(array $config) <ide><path>src/Illuminate/Encryption/MissingAppKeyException.php <ide> class MissingAppKeyException extends RuntimeException <ide> /** <ide> * Create a new exception instance. <ide> * <add> * @param string $message <ide> * @return void <ide> */ <ide> public function __construct($message = 'No application encryption key has been specified.') <ide><path>src/Illuminate/Foundation/Bus/Dispatchable.php <ide> public static function dispatch() <ide> * Dispatch the job with the given arguments if the given truth test passes. <ide> * <ide> * @param bool $boolean <add> * @param mixed ...$arguments <ide> * @return \Illuminate\Foundation\Bus\PendingDispatch|\Illuminate\Support\Fluent <ide> */ <ide> public static function dispatchIf($boolean, ...$arguments) <ide> public static function dispatchIf($boolean, ...$arguments) <ide> * Dispatch the job with the given arguments unless the given truth test passes. <ide> * <ide> * @param bool $boolean <add> * @param mixed ...$arguments <ide> * @return \Illuminate\Foundation\Bus\PendingDispatch|\Illuminate\Support\Fluent <ide> */ <ide> public static function dispatchUnless($boolean, ...$arguments) <ide><path>src/Illuminate/Foundation/Events/Dispatchable.php <ide> public static function dispatch() <ide> * Dispatch the event with the given arguments if the given truth test passes. <ide> * <ide> * @param bool $boolean <add> * @param mixed ...$arguments <ide> * @return void <ide> */ <ide> public static function dispatchIf($boolean, ...$arguments) <ide> public static function dispatchIf($boolean, ...$arguments) <ide> * Dispatch the event with the given arguments unless the given truth test passes. <ide> * <ide> * @param bool $boolean <add> * @param mixed ...$arguments <ide> * @return void <ide> */ <ide> public static function dispatchUnless($boolean, ...$arguments) <ide><path>src/Illuminate/Http/Concerns/InteractsWithInput.php <ide> public function dd(...$keys) <ide> /** <ide> * Dump the items. <ide> * <add> * @param array $keys <ide> * @return $this <ide> */ <ide> public function dump($keys = []) <ide><path>src/Illuminate/Queue/CallQueuedClosure.php <ide> public function onFailure($callback) <ide> /** <ide> * Handle a job failure. <ide> * <del> * @param \Exception $exception <add> * @param \Exception $e <ide> * @return void <ide> */ <ide> public function failed(Exception $e) <ide><path>src/Illuminate/Queue/SyncQueue.php <ide> protected function raiseExceptionOccurredJobEvent(Job $job, Throwable $e) <ide> /** <ide> * Handle an exception that occurred while processing a job. <ide> * <del> * @param \Illuminate\Queue\Jobs\Job $queueJob <add> * @param \Illuminate\Contracts\Queue\Job $queueJob <ide> * @param \Throwable $e <ide> * @return void <ide> * <ide><path>src/Illuminate/Routing/Middleware/ThrottleRequests.php <ide> protected function addHeaders(Response $response, $maxAttempts, $remainingAttemp <ide> * @param int $maxAttempts <ide> * @param int $remainingAttempts <ide> * @param int|null $retryAfter <del> * @param \Symfony\Component\HttpFoundation\Response $response <add> * @param \Symfony\Component\HttpFoundation\Response|null $response <ide> * @return array <ide> */ <ide> protected function getHeaders($maxAttempts, <ide><path>src/Illuminate/View/Compilers/ComponentTagCompiler.php <ide> class ComponentTagCompiler <ide> * Create new component tag compiler. <ide> * <ide> * @param array $aliases <del> * @param \Illuminate\View\Compilers\BladeCompiler|null <add> * @param array $namespaces <add> * @param \Illuminate\View\Compilers\BladeCompiler|null $blade <ide> * @return void <ide> */ <ide> public function __construct(array $aliases = [], array $namespaces = [], ?BladeCompiler $blade = null) <ide><path>src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php <ide> protected function compileEndSwitch() <ide> /** <ide> * Compile an once block into valid PHP. <ide> * <add> * @param string|null $id <ide> * @return string <ide> */ <ide> protected function compileOnce($id = null) <ide><path>src/Illuminate/View/DynamicComponent.php <ide> class DynamicComponent extends Component <ide> /** <ide> * Create a new component instance. <ide> * <add> * @param string $component <ide> * @return void <ide> */ <ide> public function __construct(string $component)
20
PHP
PHP
send unix timestamp to memcached
c5984af3757e492c6e79cef161169ea09b5b9c7a
<ide><path>src/Illuminate/Cache/MemcachedStore.php <ide> namespace Illuminate\Cache; <ide> <ide> use Memcached; <add>use Carbon\Carbon; <ide> use Illuminate\Contracts\Cache\Store; <ide> <ide> class MemcachedStore extends TaggableStore implements Store <ide> public function many(array $keys) <ide> */ <ide> public function put($key, $value, $minutes) <ide> { <del> $this->memcached->set($this->prefix.$key, $value, (int) ($minutes * 60)); <add> $this->memcached->set($this->prefix.$key, $value, $this->toTimestamp($minutes)); <ide> } <ide> <ide> /** <ide> public function putMany(array $values, $minutes) <ide> $prefixedValues[$this->prefix.$key] = $value; <ide> } <ide> <del> $this->memcached->setMulti($prefixedValues, (int) ($minutes * 60)); <add> $this->memcached->setMulti($prefixedValues, $this->toTimestamp($minutes)); <ide> } <ide> <ide> /** <ide> public function putMany(array $values, $minutes) <ide> */ <ide> public function add($key, $value, $minutes) <ide> { <del> return $this->memcached->add($this->prefix.$key, $value, (int) ($minutes * 60)); <add> return $this->memcached->add($this->prefix.$key, $value, $this->toTimestamp($minutes)); <ide> } <ide> <ide> /** <ide> public function flush() <ide> $this->memcached->flush(); <ide> } <ide> <add> /** <add> * Get the UNIX timestamp for the given number of minutes. <add> * <add> * @parma int $minutes <add> * @return int <add> */ <add> protected function toTimestamp($minutes) <add> { <add> return $minutes > 0 ? Carbon::now()->timestamp + ((int) $minutes * 60) : 0; <add> } <add> <ide> /** <ide> * Get the underlying Memcached connection. <ide> * <ide><path>tests/Cache/CacheMemcachedStoreTest.php <ide> public function testSetMethodProperlyCallsMemcache() <ide> $this->markTestSkipped('Memcached module not installed'); <ide> } <ide> <add> Carbon\Carbon::setTestNow($now = Carbon\Carbon::now()); <ide> $memcache = $this->getMockBuilder('Memcached')->setMethods(['set'])->getMock(); <del> $memcache->expects($this->once())->method('set')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(60)); <add> $memcache->expects($this->once())->method('set')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo($now->timestamp + 60)); <ide> $store = new Illuminate\Cache\MemcachedStore($memcache); <ide> $store->put('foo', 'bar', 1); <add> Carbon\Carbon::setTestNow(); <ide> } <ide> <ide> public function testIncrementMethodProperlyCallsMemcache()
2
Javascript
Javascript
fix infobox with id [ci skip]
a9da33c4d97abb0e9a09795d2383b3be3a10a3e9
<ide><path>website/src/components/infobox.js <del>import React from 'react' <add>import React, { Fragment } from 'react' <ide> import PropTypes from 'prop-types' <ide> import classNames from 'classnames' <ide> <ide> export default function Infobox({ <ide> className, <ide> children, <ide> }) { <add> const Wrapper = id ? 'div' : Fragment <ide> const infoboxClassNames = classNames(classes.root, className, { <ide> [classes.list]: !!list, <ide> [classes.warning]: variant === 'warning', <ide> [classes.danger]: variant === 'danger', <ide> }) <ide> return ( <del> <> <add> <Wrapper> <ide> {id && <a id={id} />} <ide> <aside className={infoboxClassNames}> <ide> {title && ( <ide> export default function Infobox({ <ide> )} <ide> {children} <ide> </aside> <del> </> <add> </Wrapper> <ide> ) <ide> } <ide>
1
Text
Text
add documentation for deprecation properties
c770f43a917ad818118570cfc979dac989fd4964
<ide><path>doc/api/process.md <ide> event loop **before** additional I/O is processed. As a result, <ide> recursively setting nextTick callbacks will block any I/O from <ide> happening, just like a `while(true);` loop. <ide> <add>## process.noDeprecation <add><!-- YAML <add>added: v0.8.0 <add>--> <add> <add>* {boolean} <add> <add>The `process.noDeprecation` property indicates whether the `--no-deprecation` <add>flag is set on the current Node.js process. See the documentation for <add>the [`warning` event][process_warning] and the <add>[`emitWarning` method][process_emit_warning] for more information about this <add>flag's behavior. <add> <ide> ## process.pid <ide> <!-- YAML <ide> added: v0.1.15 <ide> false <ide> <ide> See the [TTY][] documentation for more information. <ide> <add>## process.throwDeprecation <add><!-- YAML <add>added: v0.9.12 <add>--> <add> <add>* {boolean} <add> <add>The `process.throwDeprecation` property indicates whether the <add>`--throw-deprecation` flag is set on the current Node.js process. See the <add>documentation for the [`warning` event][process_warning] and the <add>[`emitWarning` method][process_emit_warning] for more information about this <add>flag's behavior. <add> <ide> ## process.title <ide> <!-- YAML <ide> added: v0.1.104 <ide> process. Node.js v0.8 allowed for longer process title strings by also <ide> overwriting the `environ` memory but that was potentially insecure and <ide> confusing in some (rather obscure) cases. <ide> <add>## process.traceDeprecation <add><!-- YAML <add>added: v0.8.0 <add>--> <add> <add>* {boolean} <add> <add>The `process.traceDeprecation` property indicates whether the <add>`--trace-deprecation` flag is set on the current Node.js process. See the <add>documentation for the [`warning` event][process_warning] and the <add>[`emitWarning` method][process_emit_warning] for more information about this <add>flag's behavior. <add> <ide> ## process.umask([mask]) <ide> <!-- YAML <ide> added: v0.1.19
1
Javascript
Javascript
use eslint to fix var->const/let
7a0e462f9facfff8ccd7b37eb5b65db1c2b2f55f
<ide><path>test/addons/buffer-free-callback/test.js <ide> const common = require('../../common'); <ide> const binding = require(`./build/${common.buildType}/binding`); <ide> <ide> function check(size, alignment, offset) { <del> var buf = binding.alloc(size, alignment, offset); <del> var slice = buf.slice(size >>> 1); <add> let buf = binding.alloc(size, alignment, offset); <add> let slice = buf.slice(size >>> 1); <ide> <ide> buf = null; <ide> binding.check(slice); <ide><path>test/addons/load-long-path/test.js <ide> common.refreshTmpDir(); <ide> // make a path that is more than 260 chars long. <ide> // Any given folder cannot have a name longer than 260 characters, <ide> // so create 10 nested folders each with 30 character long names. <del>var addonDestinationDir = path.resolve(common.tmpDir); <add>let addonDestinationDir = path.resolve(common.tmpDir); <ide> <del>for (var i = 0; i < 10; i++) { <add>for (let i = 0; i < 10; i++) { <ide> addonDestinationDir = path.join(addonDestinationDir, 'x'.repeat(30)); <ide> fs.mkdirSync(addonDestinationDir); <ide> } <ide> const addonPath = path.join(__dirname, <ide> const addonDestinationPath = path.join(addonDestinationDir, 'binding.node'); <ide> <ide> // Copy binary to long path destination <del>var contents = fs.readFileSync(addonPath); <add>const contents = fs.readFileSync(addonPath); <ide> fs.writeFileSync(addonDestinationPath, contents); <ide> <ide> // Attempt to load at long path destination <ide><path>test/addons/make-callback-recurse/test.js <ide> assert.throws(function() { <ide> results.push(2); <ide> <ide> setImmediate(common.mustCall(function() { <del> for (var i = 0; i < results.length; i++) { <add> for (let i = 0; i < results.length; i++) { <ide> assert.strictEqual(results[i], i, <ide> `verifyExecutionOrder(${arg}) results: ${results}`); <ide> } <ide><path>test/addons/repl-domain-abort/test.js <ide> const assert = require('assert'); <ide> const repl = require('repl'); <ide> const stream = require('stream'); <ide> const path = require('path'); <del>var buildType = process.config.target_defaults.default_configuration; <del>var buildPath = path.join(__dirname, 'build', buildType, 'binding'); <add>const buildType = process.config.target_defaults.default_configuration; <add>let buildPath = path.join(__dirname, 'build', buildType, 'binding'); <ide> // On Windows, escape backslashes in the path before passing it to REPL. <ide> if (common.isWindows) <ide> buildPath = buildPath.replace(/\\/g, '/'); <del>var cb_ran = false; <add>let cb_ran = false; <ide> <ide> process.on('exit', function() { <ide> assert(cb_ran); <ide> console.log('ok'); <ide> }); <ide> <del>var lines = [ <add>const lines = [ <ide> // This line shouldn't cause an assertion error. <ide> 'require(\'' + buildPath + '\')' + <ide> // Log output to double check callback ran. <ide> '.method(function() { console.log(\'cb_ran\'); });', <ide> ]; <ide> <del>var dInput = new stream.Readable(); <del>var dOutput = new stream.Writable(); <add>const dInput = new stream.Readable(); <add>const dOutput = new stream.Writable(); <ide> <ide> dInput._read = function _read(size) { <ide> while (lines.length > 0 && this.push(lines.shift())); <ide> dOutput._write = function _write(chunk, encoding, cb) { <ide> cb(); <ide> }; <ide> <del>var options = { <add>const options = { <ide> input: dInput, <ide> output: dOutput, <ide> terminal: false, <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-at-max.js <ide> if (!common.enoughTestMem) { <ide> return; <ide> } <ide> <add>let buf; <ide> try { <del> var buf = Buffer.allocUnsafe(kStringMaxLength); <add> buf = Buffer.allocUnsafe(kStringMaxLength); <ide> } catch (e) { <ide> // If the exception is not due to memory confinement then rethrow it. <ide> if (e.message !== 'Array buffer allocation failed') throw (e); <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-ascii.js <ide> if (!common.enoughTestMem) { <ide> // v8::String::kMaxLength defined in v8.h <ide> const kStringMaxLength = process.binding('buffer').kStringMaxLength; <ide> <add>let buf; <ide> try { <del> var buf = Buffer.allocUnsafe(kStringMaxLength + 1); <add> buf = Buffer.allocUnsafe(kStringMaxLength + 1); <ide> } catch (e) { <ide> // If the exception is not due to memory confinement then rethrow it. <ide> if (e.message !== 'Array buffer allocation failed') throw (e); <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-base64.js <ide> if (!common.enoughTestMem) { <ide> // v8::String::kMaxLength defined in v8.h <ide> const kStringMaxLength = process.binding('buffer').kStringMaxLength; <ide> <add>let buf; <ide> try { <del> var buf = Buffer.allocUnsafe(kStringMaxLength + 1); <add> buf = Buffer.allocUnsafe(kStringMaxLength + 1); <ide> } catch (e) { <ide> // If the exception is not due to memory confinement then rethrow it. <ide> if (e.message !== 'Array buffer allocation failed') throw (e); <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js <ide> if (!common.enoughTestMem) { <ide> // v8::String::kMaxLength defined in v8.h <ide> const kStringMaxLength = process.binding('buffer').kStringMaxLength; <ide> <add>let buf; <ide> try { <del> var buf = Buffer.allocUnsafe(kStringMaxLength + 1); <add> buf = Buffer.allocUnsafe(kStringMaxLength + 1); <ide> } catch (e) { <ide> // If the exception is not due to memory confinement then rethrow it. <ide> if (e.message !== 'Array buffer allocation failed') throw (e); <ide> assert.throws(function() { <ide> buf.toString('latin1'); <ide> }, /"toString\(\)" failed/); <ide> <del>var maxString = buf.toString('latin1', 1); <add>let maxString = buf.toString('latin1', 1); <ide> assert.strictEqual(maxString.length, kStringMaxLength); <ide> // Free the memory early instead of at the end of the next assignment <ide> maxString = undefined; <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-hex.js <ide> if (!common.enoughTestMem) { <ide> // v8::String::kMaxLength defined in v8.h <ide> const kStringMaxLength = process.binding('buffer').kStringMaxLength; <ide> <add>let buf; <ide> try { <del> var buf = Buffer.allocUnsafe(kStringMaxLength + 1); <add> buf = Buffer.allocUnsafe(kStringMaxLength + 1); <ide> } catch (e) { <ide> // If the exception is not due to memory confinement then rethrow it. <ide> if (e.message !== 'Array buffer allocation failed') throw (e); <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-utf8.js <ide> if (!common.enoughTestMem) { <ide> // v8::String::kMaxLength defined in v8.h <ide> const kStringMaxLength = process.binding('buffer').kStringMaxLength; <ide> <add>let buf; <ide> try { <del> var buf = Buffer.allocUnsafe(kStringMaxLength + 1); <add> buf = Buffer.allocUnsafe(kStringMaxLength + 1); <ide> } catch (e) { <ide> // If the exception is not due to memory confinement then rethrow it. <ide> if (e.message !== 'Array buffer allocation failed') throw (e); <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js <ide> if (!common.enoughTestMem) { <ide> // v8::String::kMaxLength defined in v8.h <ide> const kStringMaxLength = process.binding('buffer').kStringMaxLength; <ide> <add>let buf; <ide> try { <del> var buf = Buffer.allocUnsafe(kStringMaxLength + 2); <add> buf = Buffer.allocUnsafe(kStringMaxLength + 2); <ide> } catch (e) { <ide> // If the exception is not due to memory confinement then rethrow it. <ide> if (e.message !== 'Array buffer allocation failed') throw (e); <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max.js <ide> if (!common.enoughTestMem) { <ide> // v8::String::kMaxLength defined in v8.h <ide> const kStringMaxLength = process.binding('buffer').kStringMaxLength; <ide> <add>let buf; <ide> try { <del> var buf = Buffer.allocUnsafe(kStringMaxLength * 2 + 2); <add> buf = Buffer.allocUnsafe(kStringMaxLength * 2 + 2); <ide> } catch (e) { <ide> // If the exception is not due to memory confinement then rethrow it. <ide> if (e.message !== 'Array buffer allocation failed') throw (e); <ide><path>test/common.js <ide> exports.hasIPv6 = Object.keys(ifaces).some(function(name) { <ide> * the process aborts. <ide> */ <ide> exports.childShouldThrowAndAbort = function() { <del> var testCmd = ''; <add> let testCmd = ''; <ide> if (!exports.isWindows) { <ide> // Do not create core files, as it can take a lot of disk space on <ide> // continuous testing and developers' machines <ide><path>test/debugger/helper-debugger-repl.js <ide> const assert = require('assert'); <ide> const spawn = require('child_process').spawn; <ide> <ide> process.env.NODE_DEBUGGER_TIMEOUT = 2000; <del>var port = common.PORT; <add>const port = common.PORT; <ide> <del>var child; <del>var buffer = ''; <del>var expected = []; <del>var quit; <add>let child; <add>let buffer = ''; <add>const expected = []; <add>let quit; <ide> <ide> function startDebugger(scriptToDebug) { <ide> scriptToDebug = process.env.NODE_DEBUGGER_TEST_SCRIPT || <ide> function startDebugger(scriptToDebug) { <ide> console.log(line); <ide> assert.ok(expected.length > 0, 'Got unexpected line: ' + line); <ide> <del> var expectedLine = expected[0].lines.shift(); <add> const expectedLine = expected[0].lines.shift(); <ide> assert.ok(line.match(expectedLine) !== null, line + ' != ' + expectedLine); <ide> <ide> if (expected[0].lines.length === 0) { <del> var callback = expected[0].callback; <add> const callback = expected[0].callback; <ide> expected.shift(); <ide> callback && callback(); <ide> } <ide> }); <ide> <del> var childClosed = false; <add> let childClosed = false; <ide> child.on('close', function(code) { <ide> assert(!code); <ide> childClosed = true; <ide> }); <ide> <del> var quitCalled = false; <add> let quitCalled = false; <ide> quit = function() { <ide> if (quitCalled || childClosed) return; <ide> quitCalled = true; <ide> function startDebugger(scriptToDebug) { <ide> <ide> setTimeout(function() { <ide> console.error('dying badly buffer=%j', buffer); <del> var err = 'Timeout'; <add> let err = 'Timeout'; <ide> if (expected.length > 0 && expected[0].lines) { <ide> err = err + '. Expected: ' + expected[0].lines.shift(); <ide> } <ide> function addTest(input, output) { <ide> child.stdin.write(expected[0].input + '\n'); <ide> <ide> if (!expected[0].lines) { <del> var callback = expected[0].callback; <add> const callback = expected[0].callback; <ide> expected.shift(); <ide> <ide> callback && callback(); <ide> function addTest(input, output) { <ide> expected.push({input: input, lines: output, callback: next}); <ide> } <ide> <del>var handshakeLines = [ <add>const handshakeLines = [ <ide> /listening on /, <ide> /connecting.* ok/ <ide> ]; <ide> <del>var initialBreakLines = [ <add>const initialBreakLines = [ <ide> /break in .*:1/, <ide> /1/, /2/, /3/ <ide> ]; <ide> <del>var initialLines = handshakeLines.concat(initialBreakLines); <add>const initialLines = handshakeLines.concat(initialBreakLines); <ide> <ide> // Process initial lines <ide> addTest(null, initialLines); <ide><path>test/debugger/test-debugger-repl-restart.js <ide> require('../common'); <ide> const repl = require('./helper-debugger-repl.js'); <ide> <ide> repl.startDebugger('breakpoints.js'); <del>var linesWithBreakpoint = [ <add>const linesWithBreakpoint = [ <ide> /1/, /2/, /3/, /4/, /5/, /\* 6/ <ide> ]; <ide> // We slice here, because addTest will change the given array. <ide> repl.addTest('sb(6)', linesWithBreakpoint.slice()); <ide> <del>var initialLines = repl.initialLines.slice(); <add>const initialLines = repl.initialLines.slice(); <ide> initialLines.splice(2, 0, /Restoring/, /Warning/); <ide> <ide> // Restart the debugged script <ide><path>test/debugger/test-debugger-repl-term.js <ide> const repl = require('./helper-debugger-repl.js'); <ide> <ide> repl.startDebugger('breakpoints.js'); <ide> <del>var addTest = repl.addTest; <add>const addTest = repl.addTest; <ide> <ide> // next <ide> addTest('n', [ <ide><path>test/debugger/test-debugger-repl-utf8.js <ide> 'use strict'; <ide> const common = require('../common'); <del>var script = common.fixturesDir + '/breakpoints_utf8.js'; <add>const script = common.fixturesDir + '/breakpoints_utf8.js'; <ide> process.env.NODE_DEBUGGER_TEST_SCRIPT = script; <ide> <ide> require('./test-debugger-repl.js'); <ide><path>test/debugger/test-debugger-repl.js <ide> const repl = require('./helper-debugger-repl.js'); <ide> <ide> repl.startDebugger('breakpoints.js'); <ide> <del>var addTest = repl.addTest; <add>const addTest = repl.addTest; <ide> <ide> // Next <ide> addTest('n', [ <ide><path>test/gc/test-http-client-connaborted.js <ide> let countGC = 0; <ide> <ide> console.log('We should do ' + todo + ' requests'); <ide> <del>var server = http.createServer(serverHandler); <add>const server = http.createServer(serverHandler); <ide> server.listen(0, getall); <ide> <ide> function getall() { <ide> function getall() { <ide> statusLater(); <ide> } <ide> <del> var req = http.get({ <add> const req = http.get({ <ide> hostname: 'localhost', <ide> pathname: '/', <ide> port: server.address().port <ide> function getall() { <ide> setImmediate(getall); <ide> } <ide> <del>for (var i = 0; i < 10; i++) <add>for (let i = 0; i < 10; i++) <ide> getall(); <ide> <ide> function afterGC() { <ide> countGC++; <ide> } <ide> <del>var timer; <add>let timer; <ide> function statusLater() { <ide> global.gc(); <ide> if (timer) clearTimeout(timer); <ide><path>test/gc/test-http-client-onerror.js <ide> let countGC = 0; <ide> <ide> console.log('We should do ' + todo + ' requests'); <ide> <del>var server = http.createServer(serverHandler); <add>const server = http.createServer(serverHandler); <ide> server.listen(0, runTest); <ide> <ide> function getall() { <ide> function getall() { <ide> throw er; <ide> } <ide> <del> var req = http.get({ <add> const req = http.get({ <ide> hostname: 'localhost', <ide> pathname: '/', <ide> port: server.address().port <ide> function getall() { <ide> } <ide> <ide> function runTest() { <del> for (var i = 0; i < 10; i++) <add> for (let i = 0; i < 10; i++) <ide> getall(); <ide> } <ide> <ide> function afterGC() { <ide> countGC++; <ide> } <ide> <del>var timer; <add>let timer; <ide> function statusLater() { <ide> global.gc(); <ide> if (timer) clearTimeout(timer); <ide><path>test/gc/test-http-client-timeout.js <ide> let countGC = 0; <ide> <ide> console.log('We should do ' + todo + ' requests'); <ide> <del>var server = http.createServer(serverHandler); <add>const server = http.createServer(serverHandler); <ide> server.listen(0, getall); <ide> <ide> function getall() { <ide> function getall() { <ide> statusLater(); <ide> } <ide> <del> var req = http.get({ <add> const req = http.get({ <ide> hostname: 'localhost', <ide> pathname: '/', <ide> port: server.address().port <ide> function getall() { <ide> setImmediate(getall); <ide> } <ide> <del>for (var i = 0; i < 10; i++) <add>for (let i = 0; i < 10; i++) <ide> getall(); <ide> <ide> function afterGC() { <ide> countGC++; <ide> } <ide> <del>var timer; <add>let timer; <ide> function statusLater() { <ide> global.gc(); <ide> if (timer) clearTimeout(timer); <ide><path>test/gc/test-http-client.js <ide> let countGC = 0; <ide> <ide> console.log('We should do ' + todo + ' requests'); <ide> <del>var server = http.createServer(serverHandler); <add>const server = http.createServer(serverHandler); <ide> server.listen(0, getall); <ide> <ide> <ide> function getall() { <ide> res.on('end', global.gc); <ide> } <ide> <del> var req = http.get({ <add> const req = http.get({ <ide> hostname: 'localhost', <ide> pathname: '/', <ide> port: server.address().port <ide> function getall() { <ide> setImmediate(getall); <ide> } <ide> <del>for (var i = 0; i < 10; i++) <add>for (let i = 0; i < 10; i++) <ide> getall(); <ide> <ide> function afterGC() { <ide><path>test/gc/test-net-timeout.js <ide> require('../common'); <ide> function serverHandler(sock) { <ide> sock.setTimeout(120000); <ide> sock.resume(); <del> var timer; <ide> sock.on('close', function() { <ide> clearTimeout(timer); <ide> }); <ide> sock.on('error', function(err) { <ide> assert.strictEqual(err.code, 'ECONNRESET'); <ide> }); <del> timer = setTimeout(function() { <add> const timer = setTimeout(function() { <ide> sock.end('hello\n'); <ide> }, 100); <ide> } <ide> let countGC = 0; <ide> <ide> console.log('We should do ' + todo + ' requests'); <ide> <del>var server = net.createServer(serverHandler); <add>const server = net.createServer(serverHandler); <ide> server.listen(0, getall); <ide> <ide> function getall() { <ide> function getall() { <ide> setImmediate(getall); <ide> } <ide> <del>for (var i = 0; i < 10; i++) <add>for (let i = 0; i < 10; i++) <ide> getall(); <ide> <ide> function afterGC() { <ide><path>test/inspector/inspector-helper.js <ide> function makeBufferingDataCallback(dataCallback) { <ide> buffer = Buffer.alloc(0); <ide> else <ide> buffer = Buffer.from(lines.pop(), 'utf8'); <del> for (var line of lines) <add> for (const line of lines) <ide> dataCallback(line); <ide> }; <ide> } <ide> TestSession.prototype.sendInspectorCommands = function(commands) { <ide> }; <ide> <ide> TestSession.prototype.createCallbackWithTimeout_ = function(message) { <del> var promise = new Promise((resolve) => { <add> const promise = new Promise((resolve) => { <ide> this.enqueue((callback) => { <ide> const timeoutId = timeout(message); <ide> resolve(() => { <ide><path>test/internet/test-dgram-multicast-multi-process.js <ide> const messages = [ <ide> ]; <ide> const workers = {}; <ide> const listeners = 3; <add>let listening, sendSocket, done, timer, dead; <ide> <ide> <ide> // Skip test in FreeBSD jails. <ide> function launchChildProcess(index) { <ide> Object.keys(workers).forEach(function(pid) { <ide> const worker = workers[pid]; <ide> <del> var count = 0; <add> let count = 0; <ide> <ide> worker.messagesReceived.forEach(function(buf) { <del> for (var i = 0; i < messages.length; ++i) { <add> for (let i = 0; i < messages.length; ++i) { <ide> if (buf.toString() === messages[i].toString()) { <ide> count++; <ide> break; <ide> function killChildren(children) { <ide> } <ide> <ide> if (process.argv[2] !== 'child') { <del> var listening = 0; <del> var dead = 0; <del> var i = 0; <del> var done = 0; <add> listening = 0; <add> dead = 0; <add> let i = 0; <add> done = 0; <ide> <ide> // Exit the test if it doesn't succeed within TIMEOUT. <del> var timer = setTimeout(function() { <add> timer = setTimeout(function() { <ide> console.error('[PARENT] Responses were not received within %d ms.', <ide> TIMEOUT); <ide> console.error('[PARENT] Fail'); <ide> if (process.argv[2] !== 'child') { <ide> }, TIMEOUT); <ide> <ide> // Launch child processes. <del> for (var x = 0; x < listeners; x++) { <add> for (let x = 0; x < listeners; x++) { <ide> launchChildProcess(x); <ide> } <ide> <del> var sendSocket = dgram.createSocket('udp4'); <add> sendSocket = dgram.createSocket('udp4'); <ide> <ide> // The socket is actually created async now. <ide> sendSocket.on('listening', function() { <ide><path>test/internet/test-dgram-send-cb-quelches-error.js <ide> 'use strict'; <ide> const common = require('../common'); <del>var mustCall = common.mustCall; <add>const mustCall = common.mustCall; <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> const dns = require('dns'); <ide> <del>var socket = dgram.createSocket('udp4'); <del>var buffer = Buffer.from('gary busey'); <add>const socket = dgram.createSocket('udp4'); <add>const buffer = Buffer.from('gary busey'); <ide> <ide> dns.setServers([]); <ide> <ide><path>test/internet/test-dns-cares-domains.js <ide> const assert = require('assert'); <ide> const dns = require('dns'); <ide> const domain = require('domain'); <ide> <del>var methods = [ <add>const methods = [ <ide> 'resolve4', <ide> 'resolve6', <ide> 'resolveCname', <ide> var methods = [ <ide> ]; <ide> <ide> methods.forEach(function(method) { <del> var d = domain.create(); <add> const d = domain.create(); <ide> d.run(function() { <ide> dns[method]('google.com', function() { <ide> assert.strictEqual(process.domain, d, method + ' retains domain'); <ide><path>test/internet/test-dns.js <ide> const queue = []; <ide> <ide> function TEST(f) { <ide> function next() { <del> var f = queue.shift(); <add> const f = queue.shift(); <ide> if (f) { <ide> running = true; <ide> console.log(f.name); <ide> function checkWrap(req) { <ide> <ide> <ide> TEST(function test_reverse_bogus(done) { <del> var error; <add> let error; <ide> <ide> try { <ide> dns.reverse('bogus ip', function() { <ide> TEST(function test_reverse_bogus(done) { <ide> }); <ide> <ide> TEST(function test_resolve4_ttl(done) { <del> var req = dns.resolve4('google.com', { ttl: true }, function(err, result) { <add> const req = dns.resolve4('google.com', { ttl: true }, function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <del> for (var i = 0; i < result.length; i++) { <del> var item = result[i]; <add> for (let i = 0; i < result.length; i++) { <add> const item = result[i]; <ide> assert.ok(item); <ide> assert.strictEqual(typeof item, 'object'); <ide> assert.strictEqual(typeof item.ttl, 'number'); <ide> TEST(function test_resolve4_ttl(done) { <ide> }); <ide> <ide> TEST(function test_resolve6_ttl(done) { <del> var req = dns.resolve6('google.com', { ttl: true }, function(err, result) { <add> const req = dns.resolve6('google.com', { ttl: true }, function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <del> for (var i = 0; i < result.length; i++) { <del> var item = result[i]; <add> for (let i = 0; i < result.length; i++) { <add> const item = result[i]; <ide> assert.ok(item); <ide> assert.strictEqual(typeof item, 'object'); <ide> assert.strictEqual(typeof item.ttl, 'number'); <ide> TEST(function test_resolve6_ttl(done) { <ide> }); <ide> <ide> TEST(function test_resolveMx(done) { <del> var req = dns.resolveMx('gmail.com', function(err, result) { <add> const req = dns.resolveMx('gmail.com', function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <del> for (var i = 0; i < result.length; i++) { <del> var item = result[i]; <add> for (let i = 0; i < result.length; i++) { <add> const item = result[i]; <ide> assert.ok(item); <ide> assert.strictEqual(typeof item, 'object'); <ide> <ide> TEST(function test_resolveMx(done) { <ide> }); <ide> <ide> TEST(function test_resolveMx_failure(done) { <del> var req = dns.resolveMx('something.invalid', function(err, result) { <add> const req = dns.resolveMx('something.invalid', function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveMx_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveNs(done) { <del> var req = dns.resolveNs('rackspace.com', function(err, names) { <add> const req = dns.resolveNs('rackspace.com', function(err, names) { <ide> assert.ifError(err); <ide> assert.ok(names.length > 0); <ide> <del> for (var i = 0; i < names.length; i++) { <del> var name = names[i]; <add> for (let i = 0; i < names.length; i++) { <add> const name = names[i]; <ide> assert.ok(name); <ide> assert.strictEqual(typeof name, 'string'); <ide> } <ide> TEST(function test_resolveNs(done) { <ide> }); <ide> <ide> TEST(function test_resolveNs_failure(done) { <del> var req = dns.resolveNs('something.invalid', function(err, result) { <add> const req = dns.resolveNs('something.invalid', function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveNs_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveSrv(done) { <del> var req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { <add> const req = dns.resolveSrv('_jabber._tcp.google.com', function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <del> for (var i = 0; i < result.length; i++) { <del> var item = result[i]; <add> for (let i = 0; i < result.length; i++) { <add> const item = result[i]; <ide> assert.ok(item); <ide> assert.strictEqual(typeof item, 'object'); <ide> <ide> TEST(function test_resolveSrv(done) { <ide> }); <ide> <ide> TEST(function test_resolveSrv_failure(done) { <del> var req = dns.resolveSrv('something.invalid', function(err, result) { <add> const req = dns.resolveSrv('something.invalid', function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveSrv_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolvePtr(done) { <del> var req = dns.resolvePtr('8.8.8.8.in-addr.arpa', function(err, result) { <add> const req = dns.resolvePtr('8.8.8.8.in-addr.arpa', function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <del> for (var i = 0; i < result.length; i++) { <del> var item = result[i]; <add> for (let i = 0; i < result.length; i++) { <add> const item = result[i]; <ide> assert.ok(item); <ide> assert.strictEqual(typeof item, 'string'); <ide> } <ide> TEST(function test_resolvePtr(done) { <ide> }); <ide> <ide> TEST(function test_resolvePtr_failure(done) { <del> var req = dns.resolvePtr('something.invalid', function(err, result) { <add> const req = dns.resolvePtr('something.invalid', function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolvePtr_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveNaptr(done) { <del> var req = dns.resolveNaptr('sip2sip.info', function(err, result) { <add> const req = dns.resolveNaptr('sip2sip.info', function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result.length > 0); <ide> <del> for (var i = 0; i < result.length; i++) { <del> var item = result[i]; <add> for (let i = 0; i < result.length; i++) { <add> const item = result[i]; <ide> assert.ok(item); <ide> assert.strictEqual(typeof item, 'object'); <ide> <ide> TEST(function test_resolveNaptr(done) { <ide> }); <ide> <ide> TEST(function test_resolveNaptr_failure(done) { <del> var req = dns.resolveNaptr('something.invalid', function(err, result) { <add> const req = dns.resolveNaptr('something.invalid', function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveNaptr_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveSoa(done) { <del> var req = dns.resolveSoa('nodejs.org', function(err, result) { <add> const req = dns.resolveSoa('nodejs.org', function(err, result) { <ide> assert.ifError(err); <ide> assert.ok(result); <ide> assert.strictEqual(typeof result, 'object'); <ide> TEST(function test_resolveSoa(done) { <ide> }); <ide> <ide> TEST(function test_resolveSoa_failure(done) { <del> var req = dns.resolveSoa('something.invalid', function(err, result) { <add> const req = dns.resolveSoa('something.invalid', function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveSoa_failure(done) { <ide> }); <ide> <ide> TEST(function test_resolveCname(done) { <del> var req = dns.resolveCname('www.microsoft.com', function(err, names) { <add> const req = dns.resolveCname('www.microsoft.com', function(err, names) { <ide> assert.ifError(err); <ide> assert.ok(names.length > 0); <ide> <del> for (var i = 0; i < names.length; i++) { <del> var name = names[i]; <add> for (let i = 0; i < names.length; i++) { <add> const name = names[i]; <ide> assert.ok(name); <ide> assert.strictEqual(typeof name, 'string'); <ide> } <ide> TEST(function test_resolveCname(done) { <ide> }); <ide> <ide> TEST(function test_resolveCname_failure(done) { <del> var req = dns.resolveCname('something.invalid', function(err, result) { <add> const req = dns.resolveCname('something.invalid', function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveCname_failure(done) { <ide> <ide> <ide> TEST(function test_resolveTxt(done) { <del> var req = dns.resolveTxt('google.com', function(err, records) { <add> const req = dns.resolveTxt('google.com', function(err, records) { <ide> assert.ifError(err); <ide> assert.strictEqual(records.length, 1); <ide> assert.ok(util.isArray(records[0])); <ide> TEST(function test_resolveTxt(done) { <ide> }); <ide> <ide> TEST(function test_resolveTxt_failure(done) { <del> var req = dns.resolveTxt('something.invalid', function(err, result) { <add> const req = dns.resolveTxt('something.invalid', function(err, result) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> <ide> TEST(function test_resolveTxt_failure(done) { <ide> <ide> <ide> TEST(function test_lookup_failure(done) { <del> var req = dns.lookup('does.not.exist', 4, function(err, ip, family) { <add> const req = dns.lookup('does.not.exist', 4, function(err, ip, family) { <ide> assert.ok(err instanceof Error); <ide> assert.strictEqual(err.errno, dns.NOTFOUND); <ide> assert.strictEqual(err.errno, 'ENOTFOUND'); <ide> TEST(function test_lookup_failure(done) { <ide> <ide> <ide> TEST(function test_lookup_null(done) { <del> var req = dns.lookup(null, function(err, ip, family) { <add> const req = dns.lookup(null, function(err, ip, family) { <ide> assert.ifError(err); <ide> assert.strictEqual(ip, null); <ide> assert.strictEqual(family, 4); <ide> TEST(function test_lookup_null(done) { <ide> <ide> <ide> TEST(function test_lookup_ip_all(done) { <del> var req = dns.lookup('127.0.0.1', {all: true}, function(err, ips, family) { <add> const req = dns.lookup('127.0.0.1', {all: true}, function(err, ips, family) { <ide> assert.ifError(err); <ide> assert.ok(Array.isArray(ips)); <ide> assert.ok(ips.length > 0); <ide> TEST(function test_lookup_ip_all(done) { <ide> <ide> <ide> TEST(function test_lookup_null_all(done) { <del> var req = dns.lookup(null, {all: true}, function(err, ips, family) { <add> const req = dns.lookup(null, {all: true}, function(err, ips, family) { <ide> assert.ifError(err); <ide> assert.ok(Array.isArray(ips)); <ide> assert.strictEqual(ips.length, 0); <ide> TEST(function test_lookup_null_all(done) { <ide> <ide> <ide> TEST(function test_lookup_all_mixed(done) { <del> var req = dns.lookup('www.google.com', {all: true}, function(err, ips) { <add> const req = dns.lookup('www.google.com', {all: true}, function(err, ips) { <ide> assert.ifError(err); <ide> assert.ok(Array.isArray(ips)); <ide> assert.ok(ips.length > 0); <ide> TEST(function test_lookup_all_mixed(done) { <ide> <ide> <ide> TEST(function test_lookupservice_invalid(done) { <del> var req = dns.lookupService('1.2.3.4', 80, function(err, host, service) { <add> const req = dns.lookupService('1.2.3.4', 80, function(err, host, service) { <ide> assert(err instanceof Error); <ide> assert.strictEqual(err.code, 'ENOTFOUND'); <ide> assert.ok(/1\.2\.3\.4/.test(err.message)); <ide> TEST(function test_lookupservice_invalid(done) { <ide> <ide> <ide> TEST(function test_reverse_failure(done) { <del> var req = dns.reverse('0.0.0.0', function(err) { <add> const req = dns.reverse('0.0.0.0', function(err) { <ide> assert(err instanceof Error); <ide> assert.strictEqual(err.code, 'ENOTFOUND'); // Silly error code... <ide> assert.strictEqual(err.hostname, '0.0.0.0'); <ide> TEST(function test_reverse_failure(done) { <ide> <ide> <ide> TEST(function test_lookup_failure(done) { <del> var req = dns.lookup('nosuchhostimsure', function(err) { <add> const req = dns.lookup('nosuchhostimsure', function(err) { <ide> assert(err instanceof Error); <ide> assert.strictEqual(err.code, 'ENOTFOUND'); // Silly error code... <ide> assert.strictEqual(err.hostname, 'nosuchhostimsure'); <ide> TEST(function test_lookup_failure(done) { <ide> <ide> <ide> TEST(function test_resolve_failure(done) { <del> var req = dns.resolve4('nosuchhostimsure', function(err) { <add> const req = dns.resolve4('nosuchhostimsure', function(err) { <ide> assert(err instanceof Error); <ide> <ide> switch (err.code) { <ide> TEST(function test_resolve_failure(done) { <ide> }); <ide> <ide> <del>var getaddrinfoCallbackCalled = false; <add>let getaddrinfoCallbackCalled = false; <ide> <ide> console.log('looking up nodejs.org...'); <ide> <del>var cares = process.binding('cares_wrap'); <del>var req = new cares.GetAddrInfoReqWrap(); <add>const cares = process.binding('cares_wrap'); <add>const req = new cares.GetAddrInfoReqWrap(); <ide> cares.getaddrinfo(req, 'nodejs.org', 4); <ide> <ide> req.oncomplete = function(err, domains) { <ide><path>test/internet/test-net-connect-timeout.js <ide> const common = require('../common'); <ide> const net = require('net'); <ide> const assert = require('assert'); <ide> <del>var start = new Date(); <add>const start = new Date(); <ide> <del>var T = 100; <add>const T = 100; <ide> <ide> // 192.0.2.1 is part of subnet assigned as "TEST-NET" in RFC 5737. <ide> // For use solely in documentation and example source code. <ide> // In short, it should be unreachable. <ide> // In practice, it's a network black hole. <del>var socket = net.createConnection(9999, '192.0.2.1'); <add>const socket = net.createConnection(9999, '192.0.2.1'); <ide> <ide> socket.setTimeout(T); <ide> <ide> socket.on('timeout', common.mustCall(function() { <ide> console.error('timeout'); <del> var now = new Date(); <add> const now = new Date(); <ide> assert.ok(now - start < T + 500); <ide> socket.destroy(); <ide> })); <ide><path>test/internet/test-net-connect-unref.js <ide> const common = require('../common'); <ide> const net = require('net'); <ide> <del>var client; <del>var TIMEOUT = 10 * 1000; <add>const TIMEOUT = 10 * 1000; <ide> <del>client = net.createConnection(53, '8.8.8.8', function() { <add>const client = net.createConnection(53, '8.8.8.8', function() { <ide> client.unref(); <ide> }); <ide> <ide><path>test/internet/test-tls-connnect-melissadata.js <ide> if (!common.hasCrypto) { <ide> } <ide> <ide> const tls = require('tls'); <del>var socket = tls.connect(443, 'address.melissadata.net', function() { <add>const socket = tls.connect(443, 'address.melissadata.net', function() { <ide> socket.resume(); <ide> socket.destroy(); <ide> }); <ide><path>test/known_issues/test-url-parse-conformance.js <ide> const path = require('path'); <ide> <ide> const tests = require(path.join(common.fixturesDir, 'url-tests.json')); <ide> <del>var failed = 0; <del>var attempted = 0; <add>let failed = 0; <add>let attempted = 0; <ide> <ide> tests.forEach((test) => { <ide> attempted++; <ide> // Skip comments <ide> if (typeof test === 'string') return; <del> var parsed; <add> let parsed; <ide> <ide> try { <ide> // Attempt to parse <ide> tests.forEach((test) => { <ide> } else { <ide> // Test was not supposed to fail, so we're good so far. Now <ide> // check the results of the parse. <del> var username, password; <add> let username, password; <ide> try { <ide> assert.strictEqual(test.href, parsed.href); <ide> assert.strictEqual(test.protocol, parsed.protocol); <ide><path>test/message/eval_messages.js <ide> require('../common'); <ide> const spawn = require('child_process').spawn; <ide> <ide> function run(cmd, strict, cb) { <del> var args = []; <add> const args = []; <ide> if (strict) args.push('--use_strict'); <ide> args.push('-pe', cmd); <del> var child = spawn(process.execPath, args); <add> const child = spawn(process.execPath, args); <ide> child.stdout.pipe(process.stdout); <ide> child.stderr.pipe(process.stdout); <ide> child.on('close', cb); <ide> } <ide> <del>var queue = <add>const queue = <ide> [ 'with(this){__filename}', <ide> '42', <ide> 'throw new Error("hello")', <ide> 'var x = 100; y = x;', <ide> 'var ______________________________________________; throw 10' ]; <ide> <ide> function go() { <del> var c = queue.shift(); <add> const c = queue.shift(); <ide> if (!c) return console.log('done'); <ide> run(c, false, function() { <ide> run(c, true, go); <ide><path>test/message/max_tick_depth.js <ide> require('../common'); <ide> <ide> process.maxTickDepth = 10; <del>var i = 20; <add>let i = 20; <ide> process.nextTick(function f() { <ide> console.error('tick %d', i); <ide> if (i-- > 0) <ide><path>test/message/stdin_messages.js <ide> require('../common'); <ide> const spawn = require('child_process').spawn; <ide> <ide> function run(cmd, strict, cb) { <del> var args = []; <add> const args = []; <ide> if (strict) args.push('--use_strict'); <ide> args.push('-p'); <del> var child = spawn(process.execPath, args); <add> const child = spawn(process.execPath, args); <ide> child.stdout.pipe(process.stdout); <ide> child.stderr.pipe(process.stdout); <ide> child.stdin.end(cmd); <ide> child.on('close', cb); <ide> } <ide> <del>var queue = <add>const queue = <ide> [ 'with(this){__filename}', <ide> '42', <ide> 'throw new Error("hello")', <ide> 'var x = 100; y = x;', <ide> 'var ______________________________________________; throw 10' ]; <ide> <ide> function go() { <del> var c = queue.shift(); <add> const c = queue.shift(); <ide> if (!c) return console.log('done'); <ide> run(c, false, function() { <ide> run(c, true, go); <ide><path>test/parallel/test-assert-typedarray-deepequal.js <ide> const assert = require('assert'); <ide> const a = require('assert'); <ide> <ide> function makeBlock(f) { <del> var args = Array.prototype.slice.call(arguments, 1); <add> const args = Array.prototype.slice.call(arguments, 1); <ide> return function() { <ide> return f.apply(this, args); <ide> }; <ide><path>test/parallel/test-assert.js <ide> const assert = require('assert'); <ide> const a = require('assert'); <ide> <ide> function makeBlock(f) { <del> var args = Array.prototype.slice.call(arguments, 1); <add> const args = Array.prototype.slice.call(arguments, 1); <ide> return function() { <ide> return f.apply(this, args); <ide> }; <ide> assert.throws(makeBlock(a.deepEqual, {a: 4}, {a: 4, b: true}), <ide> assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], {0: 'a'})); <ide> //(although not necessarily the same order), <ide> assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4})); <del>var a1 = [1, 2, 3]; <del>var a2 = [1, 2, 3]; <add>const a1 = [1, 2, 3]; <add>const a2 = [1, 2, 3]; <ide> a1.a = 'test'; <ide> a1.b = true; <ide> a2.b = true; <ide> assert.throws(makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), <ide> assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2)); <ide> <ide> // having an identical prototype property <del>var nbRoot = { <add>const nbRoot = { <ide> toString: function() { return this.first + ' ' + this.last; } <ide> }; <ide> <ide> function nameBuilder2(first, last) { <ide> } <ide> nameBuilder2.prototype = nbRoot; <ide> <del>var nb1 = new nameBuilder('Ryan', 'Dahl'); <del>var nb2 = new nameBuilder2('Ryan', 'Dahl'); <add>const nb1 = new nameBuilder('Ryan', 'Dahl'); <add>let nb2 = new nameBuilder2('Ryan', 'Dahl'); <ide> <ide> assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2)); <ide> <ide> function Constructor2(first, last) { <ide> this.last = last; <ide> } <ide> <del>var obj1 = new Constructor1('Ryan', 'Dahl'); <del>var obj2 = new Constructor2('Ryan', 'Dahl'); <add>const obj1 = new Constructor1('Ryan', 'Dahl'); <add>let obj2 = new Constructor2('Ryan', 'Dahl'); <ide> <ide> assert.throws(makeBlock(a.deepStrictEqual, obj1, obj2), a.AssertionError); <ide> <ide> assert.throws(makeBlock(assert.deepStrictEqual, true, 1), <ide> assert.throws(makeBlock(assert.deepStrictEqual, Symbol(), Symbol()), <ide> a.AssertionError); <ide> <del>var s = Symbol(); <add>const s = Symbol(); <ide> assert.doesNotThrow(makeBlock(assert.deepStrictEqual, s, s)); <ide> <ide> <ide> assert.throws(makeBlock(thrower, a.AssertionError)); <ide> assert.throws(makeBlock(thrower, TypeError)); <ide> <ide> // when passing a type, only catch errors of the appropriate type <del>var threw = false; <add>let threw = false; <ide> try { <ide> a.throws(makeBlock(thrower, TypeError), a.AssertionError); <ide> } catch (e) { <ide> a.throws(makeBlock(thrower, TypeError), function(err) { <ide> // https://github.com/nodejs/node/issues/3188 <ide> threw = false; <ide> <add>let AnotherErrorType; <ide> try { <del> var ES6Error = class extends Error {}; <add> const ES6Error = class extends Error {}; <ide> <del> var AnotherErrorType = class extends Error {}; <add> AnotherErrorType = class extends Error {}; <ide> <ide> const functionThatThrows = function() { <ide> throw new AnotherErrorType('foo'); <ide> assert.ok(threw); <ide> a.throws(makeBlock(a.deepStrictEqual, d, e), /AssertionError/); <ide> } <ide> // GH-7178. Ensure reflexivity of deepEqual with `arguments` objects. <del>var args = (function() { return arguments; })(); <add>const args = (function() { return arguments; })(); <ide> a.throws(makeBlock(a.deepEqual, [], args)); <ide> a.throws(makeBlock(a.deepEqual, args, [])); <ide> <ide> a.throws(makeBlock(a.deepEqual, args, [])); <ide> a.doesNotThrow(makeBlock(a.deepEqual, someArgs, sameArgs)); <ide> } <ide> <del>var circular = {y: 1}; <add>const circular = {y: 1}; <ide> circular.x = circular; <ide> <ide> function testAssertionMessage(actual, expected) { <ide> try { <ide> <ide> // Verify that throws() and doesNotThrow() throw on non-function block <ide> function testBlockTypeError(method, block) { <del> var threw = true; <add> let threw = true; <ide> <ide> try { <ide> method(block); <ide><path>test/parallel/test-async-wrap-check-providers.js <ide> keyList.splice(0, 1); <ide> // want to improve under https://github.com/nodejs/node/issues/5085. <ide> // strip out fs watch related parts for now <ide> if (common.isAix) { <del> for (var i = 0; i < keyList.length; i++) { <add> for (let i = 0; i < keyList.length; i++) { <ide> if ((keyList[i] === 'FSEVENTWRAP') || (keyList[i] === 'STATWATCHER')) { <ide> keyList.splice(i, 1); <ide> } <ide><path>test/parallel/test-async-wrap-throw-from-callback.js <ide> const domain = require('domain'); <ide> const spawn = require('child_process').spawn; <ide> const callbacks = [ 'init', 'pre', 'post', 'destroy' ]; <ide> const toCall = process.argv[2]; <del>var msgCalled = 0; <del>var msgReceived = 0; <add>let msgCalled = 0; <add>let msgReceived = 0; <ide> <ide> function init() { <ide> if (toCall === 'init') <ide> if (typeof process.argv[2] === 'string') { <ide> msgCalled++; <ide> <ide> const child = spawn(process.execPath, [__filename, item]); <del> var errstring = ''; <add> let errstring = ''; <ide> <ide> child.stderr.on('data', (data) => { <ide> errstring += data.toString(); <ide><path>test/parallel/test-async-wrap-uid.js <ide> const assert = require('assert'); <ide> const async_wrap = process.binding('async_wrap'); <ide> <ide> // Give the event loop time to clear out the final uv_close(). <del>var si_cntr = 3; <add>let si_cntr = 3; <ide> process.on('beforeExit', () => { <ide> if (--si_cntr > 0) setImmediate(() => {}); <ide> }); <ide><path>test/parallel/test-buffer-ascii.js <ide> const expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' + <ide> <ide> const buf = Buffer.from(input); <ide> <del>for (var i = 0; i < expected.length; ++i) { <add>for (let i = 0; i < expected.length; ++i) { <ide> assert.strictEqual(buf.slice(i).toString('ascii'), expected.slice(i)); <ide> <ide> // Skip remainder of multi-byte sequence. <ide><path>test/parallel/test-buffer-bytelength.js <ide> assert(ArrayBuffer.isView(Buffer.allocUnsafeSlow(10))); <ide> assert(ArrayBuffer.isView(Buffer.from(''))); <ide> <ide> // buffer <del>var incomplete = Buffer.from([0xe4, 0xb8, 0xad, 0xe6, 0x96]); <add>const incomplete = Buffer.from([0xe4, 0xb8, 0xad, 0xe6, 0x96]); <ide> assert.strictEqual(Buffer.byteLength(incomplete), 5); <del>var ascii = Buffer.from('abc'); <add>const ascii = Buffer.from('abc'); <ide> assert.strictEqual(Buffer.byteLength(ascii), 3); <ide> <ide> // ArrayBuffer <del>var buffer = new ArrayBuffer(8); <add>const buffer = new ArrayBuffer(8); <ide> assert.strictEqual(Buffer.byteLength(buffer), 8); <ide> <ide> // TypedArray <del>var int8 = new Int8Array(8); <add>const int8 = new Int8Array(8); <ide> assert.strictEqual(Buffer.byteLength(int8), 8); <del>var uint8 = new Uint8Array(8); <add>const uint8 = new Uint8Array(8); <ide> assert.strictEqual(Buffer.byteLength(uint8), 8); <del>var uintc8 = new Uint8ClampedArray(2); <add>const uintc8 = new Uint8ClampedArray(2); <ide> assert.strictEqual(Buffer.byteLength(uintc8), 2); <del>var int16 = new Int16Array(8); <add>const int16 = new Int16Array(8); <ide> assert.strictEqual(Buffer.byteLength(int16), 16); <del>var uint16 = new Uint16Array(8); <add>const uint16 = new Uint16Array(8); <ide> assert.strictEqual(Buffer.byteLength(uint16), 16); <del>var int32 = new Int32Array(8); <add>const int32 = new Int32Array(8); <ide> assert.strictEqual(Buffer.byteLength(int32), 32); <del>var uint32 = new Uint32Array(8); <add>const uint32 = new Uint32Array(8); <ide> assert.strictEqual(Buffer.byteLength(uint32), 32); <del>var float32 = new Float32Array(8); <add>const float32 = new Float32Array(8); <ide> assert.strictEqual(Buffer.byteLength(float32), 32); <del>var float64 = new Float64Array(8); <add>const float64 = new Float64Array(8); <ide> assert.strictEqual(Buffer.byteLength(float64), 64); <ide> <ide> // DataView <del>var dv = new DataView(new ArrayBuffer(2)); <add>const dv = new DataView(new ArrayBuffer(2)); <ide> assert.strictEqual(Buffer.byteLength(dv), 2); <ide> <ide> // special case: zero length string <ide><path>test/parallel/test-buffer-concat.js <ide> const assert = require('assert'); <ide> const zero = []; <ide> const one = [ Buffer.from('asdf') ]; <ide> const long = []; <del>for (var i = 0; i < 10; i++) long.push(Buffer.from('asdf')); <add>for (let i = 0; i < 10; i++) long.push(Buffer.from('asdf')); <ide> <ide> const flatZero = Buffer.concat(zero); <ide> const flatOne = Buffer.concat(one); <ide><path>test/parallel/test-buffer-copy.js <ide> const assert = require('assert'); <ide> <ide> const b = Buffer.allocUnsafe(1024); <ide> const c = Buffer.allocUnsafe(512); <del>var cntr = 0; <add>let cntr = 0; <ide> <ide> { <ide> // copy 512 bytes, from 0 to 512. <ide><path>test/parallel/test-buffer-fill.js <ide> function writeToFill(string, offset, end, encoding) { <ide> // Convert "end" to "length" (which write understands). <ide> const length = end - offset < 0 ? 0 : end - offset; <ide> <del> var wasZero = false; <add> let wasZero = false; <ide> do { <ide> const written = buf2.write(string, offset, length, encoding); <ide> offset += written; <ide> Buffer.alloc(8, ''); <ide> { <ide> let elseWasLast = false; <ide> assert.throws(() => { <del> var ctr = 0; <add> let ctr = 0; <ide> const start = { <ide> [Symbol.toPrimitive]() { <ide> // We use this condition to get around the check in lib/buffer.js <ide> assert.throws(() => { <ide> { <ide> let elseWasLast = false; <ide> assert.throws(() => { <del> var ctr = 0; <add> let ctr = 0; <ide> const end = { <ide> [Symbol.toPrimitive]() { <ide> // We use this condition to get around the check in lib/buffer.js <ide><path>test/parallel/test-buffer-includes.js <ide> assert.strictEqual( <ide> <ide> <ide> // test usc2 encoding <del>var twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); <add>let twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); <ide> <ide> assert(twoByteString.includes('\u0395', 4, 'ucs2')); <ide> assert(twoByteString.includes('\u03a3', -4, 'ucs2')); <ide> assert(!mixedByteStringUtf8.includes('\u0396')); <ide> <ide> // Test complex string includes algorithms. Only trigger for long strings. <ide> // Long string that isn't a simple repeat of a shorter string. <del>var longString = 'A'; <add>let longString = 'A'; <ide> for (let i = 66; i < 76; i++) { // from 'B' to 'K' <ide> longString = longString + String.fromCharCode(i) + longString; <ide> } <ide> <ide> const longBufferString = Buffer.from(longString); <ide> <ide> // pattern of 15 chars, repeated every 16 chars in long <del>var pattern = 'ABACABADABACABA'; <add>let pattern = 'ABACABADABACABA'; <ide> for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { <ide> const includes = longBufferString.includes(pattern, i); <ide> assert(includes, 'Long ABACABA...-string at index ' + i); <ide> assert(!allCharsBufferUtf8.includes('notfound')); <ide> assert(!allCharsBufferUcs2.includes('notfound')); <ide> <ide> // Find substrings in Utf8. <del>var lengths = [1, 3, 15]; // Single char, simple and complex. <del>var indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b]; <add>let lengths = [1, 3, 15]; // Single char, simple and complex. <add>let indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b]; <ide> for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { <ide> for (let i = 0; i < indices.length; i++) { <ide> const index = indices[i]; <ide><path>test/parallel/test-buffer-indexof.js <ide> assert.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4); <ide> assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')); <ide> } <ide> <del>var mixedByteStringUcs2 = <add>const mixedByteStringUcs2 = <ide> Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2'); <ide> assert.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')); <ide> assert.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')); <ide> assert.equal( <ide> 6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon'); <ide> } <ide> <del>var mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395'); <add>const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395'); <ide> assert.equal(5, mixedByteStringUtf8.indexOf('bc')); <ide> assert.equal(5, mixedByteStringUtf8.indexOf('bc', 5)); <ide> assert.equal(5, mixedByteStringUtf8.indexOf('bc', -8)); <ide> assert.equal(-1, mixedByteStringUtf8.indexOf('\u0396')); <ide> <ide> // Test complex string indexOf algorithms. Only trigger for long strings. <ide> // Long string that isn't a simple repeat of a shorter string. <del>var longString = 'A'; <add>let longString = 'A'; <ide> for (let i = 66; i < 76; i++) { // from 'B' to 'K' <ide> longString = longString + String.fromCharCode(i) + longString; <ide> } <ide> <del>var longBufferString = Buffer.from(longString); <add>const longBufferString = Buffer.from(longString); <ide> <ide> // pattern of 15 chars, repeated every 16 chars in long <del>var pattern = 'ABACABADABACABA'; <add>let pattern = 'ABACABADABACABA'; <ide> for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { <ide> const index = longBufferString.indexOf(pattern, i); <ide> assert.equal((i + 15) & ~0xf, index, 'Long ABACABA...-string at index ' + i); <ide> assert.equal( <ide> 1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J'); <ide> <ide> // Search for a non-ASCII string in a pure ASCII string. <del>var asciiString = Buffer.from( <add>const asciiString = Buffer.from( <ide> 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf'); <ide> assert.equal(-1, asciiString.indexOf('\x2061')); <ide> assert.equal(3, asciiString.indexOf('leb', 0)); <ide> <ide> // Search in string containing many non-ASCII chars. <del>var allCodePoints = []; <add>const allCodePoints = []; <ide> for (let i = 0; i < 65536; i++) allCodePoints[i] = i; <del>var allCharsString = String.fromCharCode.apply(String, allCodePoints); <del>var allCharsBufferUtf8 = Buffer.from(allCharsString); <del>var allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2'); <add>const allCharsString = String.fromCharCode.apply(String, allCodePoints); <add>const allCharsBufferUtf8 = Buffer.from(allCharsString); <add>const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2'); <ide> <ide> // Search for string long enough to trigger complex search with ASCII pattern <ide> // and UC16 subject. <ide> assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1); <ide> length = 4 * length; <ide> } <ide> <del> var patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length); <add> const patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length); <ide> assert.equal(index, allCharsBufferUtf8.indexOf(patternBufferUtf8)); <ide> <del> var patternStringUtf8 = patternBufferUtf8.toString(); <add> const patternStringUtf8 = patternBufferUtf8.toString(); <ide> assert.equal(index, allCharsBufferUtf8.indexOf(patternStringUtf8)); <ide> } <ide> } <ide> assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1); <ide> const index = indices[i] * 2; <ide> const length = lengths[lengthIndex]; <ide> <del> var patternBufferUcs2 = <add> const patternBufferUcs2 = <ide> allCharsBufferUcs2.slice(index, index + length); <ide> assert.equal( <ide> index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2')); <ide> <del> var patternStringUcs2 = patternBufferUcs2.toString('ucs2'); <add> const patternStringUcs2 = patternBufferUcs2.toString('ucs2'); <ide> assert.equal( <ide> index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2')); <ide> } <ide> assert.strictEqual(buf_bc.lastIndexOf('你好', 5, 'binary'), -1); <ide> assert.strictEqual(buf_bc.lastIndexOf(Buffer.from('你好'), 7), -1); <ide> <ide> // Test lastIndexOf on a longer buffer: <del>var bufferString = new Buffer('a man a plan a canal panama'); <add>const bufferString = new Buffer('a man a plan a canal panama'); <ide> assert.equal(15, bufferString.lastIndexOf('canal')); <ide> assert.equal(21, bufferString.lastIndexOf('panama')); <ide> assert.equal(0, bufferString.lastIndexOf('a man a plan a canal panama')); <ide> assert.equal(511, longBufferString.lastIndexOf(pattern, 1534)); <ide> <ide> // countBits returns the number of bits in the binary reprsentation of n. <ide> function countBits(n) { <del> for (var count = 0; n > 0; count++) { <add> let count; <add> for (count = 0; n > 0; count++) { <ide> n = n & (n - 1); // remove top bit <ide> } <ide> return count; <ide> } <del>var parts = []; <del>for (var i = 0; i < 1000000; i++) { <add>const parts = []; <add>for (let i = 0; i < 1000000; i++) { <ide> parts.push((countBits(i) % 2 === 0) ? 'yolo' : 'swag'); <ide> } <del>var reallyLong = new Buffer(parts.join(' ')); <add>const reallyLong = new Buffer(parts.join(' ')); <ide> assert.equal('yolo swag swag yolo', reallyLong.slice(0, 19).toString()); <ide> <ide> // Expensive reverse searches. Stress test lastIndexOf: <ide><path>test/parallel/test-buffer-inspect.js <ide> const buffer = require('buffer'); <ide> <ide> buffer.INSPECT_MAX_BYTES = 2; <ide> <del>var b = Buffer.allocUnsafe(4); <add>let b = Buffer.allocUnsafe(4); <ide> b.fill('1234'); <ide> <del>var s = buffer.SlowBuffer(4); <add>let s = buffer.SlowBuffer(4); <ide> s.fill('1234'); <ide> <del>var expected = '<Buffer 31 32 ... >'; <add>let expected = '<Buffer 31 32 ... >'; <ide> <ide> assert.strictEqual(util.inspect(b), expected); <ide> assert.strictEqual(util.inspect(s), expected); <ide><path>test/parallel/test-buffer-iterator.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> <ide> const buffer = Buffer.from([1, 2, 3, 4, 5]); <del>var arr; <del>var b; <add>let arr; <add>let b; <ide> <ide> // buffers should be iterable <ide> <ide><path>test/parallel/test-buffer-swap.js <ide> assert.deepStrictEqual(buf3_64, Buffer.from([0x01, 0x02, 0x0a, 0x09, 0x08, 0x07, <ide> 0x0f, 0x10])); <ide> <ide> // Force use of native code (Buffer size above threshold limit for js impl) <del>var buf4A = new Uint32Array(256).fill(0x04030201); <del>var buf4 = Buffer.from(buf4A.buffer, buf4A.byteOffset); <del>var buf5A = new Uint32Array(256).fill(0x03040102); <del>var buf5 = Buffer.from(buf5A.buffer, buf5A.byteOffset); <add>const buf4A = new Uint32Array(256).fill(0x04030201); <add>const buf4 = Buffer.from(buf4A.buffer, buf4A.byteOffset); <add>const buf5A = new Uint32Array(256).fill(0x03040102); <add>const buf5 = Buffer.from(buf5A.buffer, buf5A.byteOffset); <ide> <ide> buf4.swap16(); <ide> assert.deepStrictEqual(buf4, buf5); <ide> <del>var buf6A = new Uint32Array(256).fill(0x04030201); <del>var buf6 = Buffer.from(buf6A.buffer); <del>var bu7A = new Uint32Array(256).fill(0x01020304); <del>var buf7 = Buffer.from(bu7A.buffer, bu7A.byteOffset); <add>const buf6A = new Uint32Array(256).fill(0x04030201); <add>const buf6 = Buffer.from(buf6A.buffer); <add>const bu7A = new Uint32Array(256).fill(0x01020304); <add>const buf7 = Buffer.from(bu7A.buffer, bu7A.byteOffset); <ide> <ide> buf6.swap32(); <ide> assert.deepStrictEqual(buf6, buf7); <ide> <del>var buf8A = new Uint8Array(256 * 8); <del>var buf9A = new Uint8Array(256 * 8); <add>const buf8A = new Uint8Array(256 * 8); <add>const buf9A = new Uint8Array(256 * 8); <ide> for (let i = 0; i < buf8A.length; i++) { <ide> buf8A[i] = i % 8; <ide> buf9A[buf9A.length - i - 1] = i % 8; <ide> } <del>var buf8 = Buffer.from(buf8A.buffer, buf8A.byteOffset); <del>var buf9 = Buffer.from(buf9A.buffer, buf9A.byteOffset); <add>const buf8 = Buffer.from(buf8A.buffer, buf8A.byteOffset); <add>const buf9 = Buffer.from(buf9A.buffer, buf9A.byteOffset); <ide> <ide> buf8.swap64(); <ide> assert.deepStrictEqual(buf8, buf9); <ide> <ide> // Test native code with buffers that are not memory-aligned <del>var buf10A = new Uint8Array(256 * 8); <del>var buf11A = new Uint8Array(256 * 8 - 2); <add>const buf10A = new Uint8Array(256 * 8); <add>const buf11A = new Uint8Array(256 * 8 - 2); <ide> for (let i = 0; i < buf10A.length; i++) { <ide> buf10A[i] = i % 2; <ide> } <ide> for (let i = 1; i < buf11A.length; i++) { <ide> buf11A[buf11A.length - i] = (i + 1) % 2; <ide> } <del>var buf10 = Buffer.from(buf10A.buffer, buf10A.byteOffset); <add>const buf10 = Buffer.from(buf10A.buffer, buf10A.byteOffset); <ide> // 0|1 0|1 0|1... <del>var buf11 = Buffer.from(buf11A.buffer, buf11A.byteOffset); <add>const buf11 = Buffer.from(buf11A.buffer, buf11A.byteOffset); <ide> // 0|0 1|0 1|0... <ide> <ide> buf10.slice(1, buf10.length - 1).swap16(); <ide> assert.deepStrictEqual(buf10.slice(0, buf11.length), buf11); <ide> <ide> <del>var buf12A = new Uint8Array(256 * 8); <del>var buf13A = new Uint8Array(256 * 8 - 4); <add>const buf12A = new Uint8Array(256 * 8); <add>const buf13A = new Uint8Array(256 * 8 - 4); <ide> for (let i = 0; i < buf12A.length; i++) { <ide> buf12A[i] = i % 4; <ide> } <ide> for (let i = 1; i < buf13A.length; i++) { <ide> buf13A[buf13A.length - i] = (i + 1) % 4; <ide> } <del>var buf12 = Buffer.from(buf12A.buffer, buf12A.byteOffset); <add>const buf12 = Buffer.from(buf12A.buffer, buf12A.byteOffset); <ide> // 0|1 2 3 0|1 2 3... <del>var buf13 = Buffer.from(buf13A.buffer, buf13A.byteOffset); <add>const buf13 = Buffer.from(buf13A.buffer, buf13A.byteOffset); <ide> // 0|0 3 2 1|0 3 2... <ide> <ide> buf12.slice(1, buf12.length - 3).swap32(); <ide> assert.deepStrictEqual(buf12.slice(0, buf13.length), buf13); <ide> <ide> <del>var buf14A = new Uint8Array(256 * 8); <del>var buf15A = new Uint8Array(256 * 8 - 8); <add>const buf14A = new Uint8Array(256 * 8); <add>const buf15A = new Uint8Array(256 * 8 - 8); <ide> for (let i = 0; i < buf14A.length; i++) { <ide> buf14A[i] = i % 8; <ide> } <ide> for (let i = 1; i < buf15A.length; i++) { <ide> buf15A[buf15A.length - i] = (i + 1) % 8; <ide> } <del>var buf14 = Buffer.from(buf14A.buffer, buf14A.byteOffset); <add>const buf14 = Buffer.from(buf14A.buffer, buf14A.byteOffset); <ide> // 0|1 2 3 4 5 6 7 0|1 2 3 4... <del>var buf15 = Buffer.from(buf15A.buffer, buf15A.byteOffset); <add>const buf15 = Buffer.from(buf15A.buffer, buf15A.byteOffset); <ide> // 0|0 7 6 5 4 3 2 1|0 7 6 5... <ide> <ide> buf14.slice(1, buf14.length - 7).swap64(); <ide><path>test/parallel/test-child-process-constructor.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const child_process = require('child_process'); <del>var ChildProcess = child_process.ChildProcess; <add>const ChildProcess = child_process.ChildProcess; <ide> assert.strictEqual(typeof ChildProcess, 'function'); <ide> <ide> // test that we can call spawn <del>var child = new ChildProcess(); <add>const child = new ChildProcess(); <ide> child.spawn({ <ide> file: process.execPath, <ide> args: ['--interactive'], <ide><path>test/parallel/test-child-process-default-options.js <ide> const spawn = require('child_process').spawn; <ide> <ide> process.env.HELLO = 'WORLD'; <ide> <del>var child; <add>let child; <ide> if (common.isWindows) { <ide> child = spawn('cmd.exe', ['/c', 'set'], {}); <ide> } else { <ide> child = spawn('/usr/bin/env', [], {}); <ide> } <ide> <del>var response = ''; <add>let response = ''; <ide> <ide> child.stdout.setEncoding('utf8'); <ide> <ide><path>test/parallel/test-child-process-double-pipe.js <ide> const spawn = require('child_process').spawn; <ide> // We're trying to reproduce: <ide> // $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ <ide> <del>var grep, sed, echo; <add>let grep, sed, echo; <ide> <ide> if (common.isWindows) { <ide> grep = spawn('grep', ['--binary', 'o']), <ide> grep.stdout.on('end', function(code) { <ide> }); <ide> <ide> <del>var result = ''; <add>let result = ''; <ide> <ide> // print sed's output <ide> sed.stdout.on('data', function(data) { <ide><path>test/parallel/test-child-process-env.js <ide> const assert = require('assert'); <ide> <ide> const spawn = require('child_process').spawn; <ide> <del>var env = { <add>const env = { <ide> 'HELLO': 'WORLD' <ide> }; <ide> Object.setPrototypeOf(env, { <ide> 'FOO': 'BAR' <ide> }); <ide> <del>var child; <add>let child; <ide> if (common.isWindows) { <ide> child = spawn('cmd.exe', ['/c', 'set'], {env: env}); <ide> } else { <ide> child = spawn('/usr/bin/env', [], {env: env}); <ide> } <ide> <ide> <del>var response = ''; <add>let response = ''; <ide> <ide> child.stdout.setEncoding('utf8'); <ide> <ide><path>test/parallel/test-child-process-exec-cwd.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const exec = require('child_process').exec; <ide> <del>var pwdcommand, dir; <add>let pwdcommand, dir; <ide> <ide> if (common.isWindows) { <ide> pwdcommand = 'echo %cd%'; <ide><path>test/parallel/test-child-process-exec-stdout-stderr-data-string.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const exec = require('child_process').exec; <ide> <del>var stdoutCalls = 0; <del>var stderrCalls = 0; <add>let stdoutCalls = 0; <add>let stderrCalls = 0; <ide> <ide> const command = common.isWindows ? 'dir' : 'ls'; <ide> exec(command).stdout.on('data', (data) => { <ide><path>test/parallel/test-child-process-exit-code.js <ide> const assert = require('assert'); <ide> const spawn = require('child_process').spawn; <ide> const path = require('path'); <ide> <del>var exitScript = path.join(common.fixturesDir, 'exit.js'); <del>var exitChild = spawn(process.argv[0], [exitScript, 23]); <add>const exitScript = path.join(common.fixturesDir, 'exit.js'); <add>const exitChild = spawn(process.argv[0], [exitScript, 23]); <ide> exitChild.on('exit', common.mustCall(function(code, signal) { <ide> assert.strictEqual(code, 23); <ide> assert.strictEqual(signal, null); <ide> })); <ide> <ide> <del>var errorScript = path.join(common.fixturesDir, <del> 'child_process_should_emit_error.js'); <del>var errorChild = spawn(process.argv[0], [errorScript]); <add>const errorScript = path.join(common.fixturesDir, <add> 'child_process_should_emit_error.js'); <add>const errorChild = spawn(process.argv[0], [errorScript]); <ide> errorChild.on('exit', common.mustCall(function(code, signal) { <ide> assert.ok(code !== 0); <ide> assert.strictEqual(signal, null); <ide><path>test/parallel/test-child-process-fork-close.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const fork = require('child_process').fork; <ide> <del>var cp = fork(common.fixturesDir + '/child-process-message-and-exit.js'); <add>const cp = fork(common.fixturesDir + '/child-process-message-and-exit.js'); <ide> <ide> let gotMessage = false; <ide> let gotExit = false; <ide><path>test/parallel/test-child-process-fork-dgram.js <ide> if (process.argv[2] === 'child') { <ide> <ide> const msg = Buffer.from('Some bytes'); <ide> <del> var childGotMessage = false; <del> var parentGotMessage = false; <add> let childGotMessage = false; <add> let parentGotMessage = false; <ide> <ide> parentServer.once('message', function(msg, rinfo) { <ide> parentGotMessage = true; <ide><path>test/parallel/test-child-process-fork-exec-argv.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const child_process = require('child_process'); <del>var spawn = child_process.spawn; <del>var fork = child_process.fork; <add>const spawn = child_process.spawn; <add>const fork = child_process.fork; <ide> <ide> if (process.argv[2] === 'fork') { <ide> process.stdout.write(JSON.stringify(process.execArgv), function() { <ide> if (process.argv[2] === 'fork') { <ide> } else if (process.argv[2] === 'child') { <ide> fork(__filename, ['fork']); <ide> } else { <del> var execArgv = ['--stack-size=256']; <del> var args = [__filename, 'child', 'arg0']; <add> const execArgv = ['--stack-size=256']; <add> const args = [__filename, 'child', 'arg0']; <ide> <del> var child = spawn(process.execPath, execArgv.concat(args)); <del> var out = ''; <add> const child = spawn(process.execPath, execArgv.concat(args)); <add> let out = ''; <ide> <ide> child.stdout.on('data', function(chunk) { <ide> out += chunk; <ide><path>test/parallel/test-child-process-fork-exec-path.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const path = require('path'); <del>var msg = {test: 'this'}; <del>var nodePath = process.execPath; <del>var copyPath = path.join(common.tmpDir, 'node-copy.exe'); <add>const msg = {test: 'this'}; <add>const nodePath = process.execPath; <add>const copyPath = path.join(common.tmpDir, 'node-copy.exe'); <ide> <ide> if (process.env.FORK) { <ide> assert(process.send); <ide> if (process.env.FORK) { <ide> fs.chmodSync(copyPath, '0755'); <ide> <ide> // slow but simple <del> var envCopy = JSON.parse(JSON.stringify(process.env)); <add> const envCopy = JSON.parse(JSON.stringify(process.env)); <ide> envCopy.FORK = 'true'; <ide> const child = require('child_process').fork(__filename, { <ide> execPath: copyPath, <ide><path>test/parallel/test-child-process-fork-net.js <ide> ProgressTracker.prototype.check = function() { <ide> <ide> if (process.argv[2] === 'child') { <ide> <del> var serverScope; <add> let serverScope; <ide> <ide> process.on('message', function onServer(msg, server) { <ide> if (msg.what !== 'server') return; <ide> if (process.argv[2] === 'child') { <ide> process.send({what: 'ready'}); <ide> } else { <ide> <del> var child = fork(process.argv[1], ['child']); <add> const child = fork(process.argv[1], ['child']); <ide> <ide> child.on('exit', function() { <ide> console.log('CHILD: died'); <ide> }); <ide> <ide> // send net.Server to child and test by connecting <del> var testServer = function(callback) { <add> const testServer = function(callback) { <ide> <ide> // destroy server execute callback when done <del> var progress = new ProgressTracker(2, function() { <add> const progress = new ProgressTracker(2, function() { <ide> server.on('close', function() { <ide> console.log('PARENT: server closed'); <ide> child.send({what: 'close'}); <ide> if (process.argv[2] === 'child') { <ide> }); <ide> <ide> // we expect 4 connections and close events <del> var connections = new ProgressTracker(4, progress.done.bind(progress)); <del> var closed = new ProgressTracker(4, progress.done.bind(progress)); <add> const connections = new ProgressTracker(4, progress.done.bind(progress)); <add> const closed = new ProgressTracker(4, progress.done.bind(progress)); <ide> <ide> // create server and send it to child <del> var server = net.createServer(); <add> const server = net.createServer(); <ide> server.on('connection', function(socket) { <ide> console.log('PARENT: got connection'); <ide> socket.destroy(); <ide> if (process.argv[2] === 'child') { <ide> server.listen(0); <ide> <ide> // handle client messages <del> var messageHandlers = function(msg) { <add> const messageHandlers = function(msg) { <ide> <ide> if (msg.what === 'listening') { <ide> // make connections <del> var socket; <del> for (var i = 0; i < 4; i++) { <add> let socket; <add> for (let i = 0; i < 4; i++) { <ide> socket = net.connect(server.address().port, function() { <ide> console.log('CLIENT: connected'); <ide> }); <ide> if (process.argv[2] === 'child') { <ide> }; <ide> <ide> // send net.Socket to child <del> var testSocket = function(callback) { <add> const testSocket = function(callback) { <ide> <ide> // create a new server and connect to it, <ide> // but the socket will be handled by the child <del> var server = net.createServer(); <add> const server = net.createServer(); <ide> server.on('connection', function(socket) { <ide> socket.on('close', function() { <ide> console.log('CLIENT: socket closed'); <ide> if (process.argv[2] === 'child') { <ide> // will have to do. <ide> server.listen(0, function() { <ide> console.error('testSocket, listening'); <del> var connect = net.connect(server.address().port); <del> var store = ''; <add> const connect = net.connect(server.address().port); <add> let store = ''; <ide> connect.on('data', function(chunk) { <ide> store += chunk; <ide> console.log('CLIENT: got data'); <ide> if (process.argv[2] === 'child') { <ide> }; <ide> <ide> // create server and send it to child <del> var serverSuccess = false; <del> var socketSuccess = false; <add> let serverSuccess = false; <add> let socketSuccess = false; <ide> child.on('message', function onReady(msg) { <ide> if (msg.what !== 'ready') return; <ide> child.removeListener('message', onReady); <ide><path>test/parallel/test-child-process-fork-net2.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const fork = require('child_process').fork; <ide> const net = require('net'); <del>var count = 12; <add>const count = 12; <ide> <ide> if (process.argv[2] === 'child') { <del> var needEnd = []; <del> var id = process.argv[3]; <add> const needEnd = []; <add> const id = process.argv[3]; <ide> <ide> process.on('message', function(m, socket) { <ide> if (!socket) return; <ide> if (process.argv[2] === 'child') { <ide> <ide> } else { <ide> <del> var child1 = fork(process.argv[1], ['child', '1']); <del> var child2 = fork(process.argv[1], ['child', '2']); <del> var child3 = fork(process.argv[1], ['child', '3']); <add> const child1 = fork(process.argv[1], ['child', '1']); <add> const child2 = fork(process.argv[1], ['child', '2']); <add> const child3 = fork(process.argv[1], ['child', '3']); <ide> <del> var server = net.createServer(); <add> const server = net.createServer(); <ide> <ide> let connected = 0; <ide> let closed = 0; <ide> if (process.argv[2] === 'child') { <ide> } <ide> }); <ide> <del> var disconnected = 0; <add> let disconnected = 0; <ide> server.on('listening', function() { <ide> <del> var j = count, client; <add> let j = count, client; <ide> while (j--) { <ide> client = net.connect(this.address().port, '127.0.0.1'); <ide> client.on('error', function() { <ide> if (process.argv[2] === 'child') { <ide> } <ide> }); <ide> <del> var closeEmitted = false; <add> let closeEmitted = false; <ide> server.on('close', common.mustCall(function() { <ide> closeEmitted = true; <ide> <ide> if (process.argv[2] === 'child') { <ide> <ide> server.listen(0, '127.0.0.1'); <ide> <del> var closeServer = function() { <add> const closeServer = function() { <ide> server.close(); <ide> <ide> setTimeout(function() { <ide><path>test/parallel/test-child-process-fork-ref.js <ide> if (process.argv[2] === 'child') { <ide> }); <ide> <ide> } else { <del> var child = fork(__filename, ['child'], {silent: true}); <add> const child = fork(__filename, ['child'], {silent: true}); <ide> <del> var ipc = [], stdout = ''; <add> const ipc = []; <add> let stdout = ''; <ide> <ide> child.on('message', function(msg) { <ide> ipc.push(msg); <ide><path>test/parallel/test-child-process-fork-ref2.js <ide> if (process.argv[2] === 'child') { <ide> }, 400); <ide> <ide> } else { <del> var child = fork(__filename, ['child']); <add> const child = fork(__filename, ['child']); <ide> <ide> child.on('disconnect', function() { <ide> console.log('parent -> disconnect'); <ide><path>test/parallel/test-child-process-fork-regr-gh-2847.js <ide> if (!cluster.isMaster) { <ide> return; <ide> } <ide> <del>var server = net.createServer(function(s) { <add>const server = net.createServer(function(s) { <ide> if (common.isWindows) { <ide> s.on('error', function(err) { <ide> // Prevent possible ECONNRESET errors from popping up <ide> var server = net.createServer(function(s) { <ide> s.destroy(); <ide> }, 100); <ide> }).listen(0, function() { <del> var worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> <ide> function send(callback) { <del> var s = net.connect(server.address().port, function() { <add> const s = net.connect(server.address().port, function() { <ide> worker.send({}, s, callback); <ide> }); <ide> <ide><path>test/parallel/test-child-process-fork.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const fork = require('child_process').fork; <del>var args = ['foo', 'bar']; <add>const args = ['foo', 'bar']; <ide> <del>var n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); <add>const n = fork(common.fixturesDir + '/child-process-spawn-node.js', args); <ide> <ide> assert.strictEqual(n.channel, n._channel); <ide> assert.deepStrictEqual(args, ['foo', 'bar']); <ide><path>test/parallel/test-child-process-internal.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> <ide> //messages <del>var PREFIX = 'NODE_'; <del>var normal = {cmd: 'foo' + PREFIX}; <del>var internal = {cmd: PREFIX + 'bar'}; <add>const PREFIX = 'NODE_'; <add>const normal = {cmd: 'foo' + PREFIX}; <add>const internal = {cmd: PREFIX + 'bar'}; <ide> <ide> if (process.argv[2] === 'child') { <ide> //send non-internal message containing PREFIX at a non prefix position <ide> if (process.argv[2] === 'child') { <ide> } else { <ide> <ide> const fork = require('child_process').fork; <del> var child = fork(process.argv[1], ['child']); <add> const child = fork(process.argv[1], ['child']); <ide> <ide> child.once('message', common.mustCall(function(data) { <ide> assert.deepStrictEqual(data, normal); <ide><path>test/parallel/test-child-process-send-returns-boolean.js <ide> assert.strictEqual(rv, true); <ide> <ide> const spawnOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }; <ide> const s = spawn(process.execPath, [emptyFile], spawnOptions); <del>var handle = null; <add>let handle = null; <ide> s.on('exit', function() { <ide> handle.close(); <ide> }); <ide><path>test/parallel/test-child-process-set-blocking.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const ch = require('child_process'); <ide> <del>var SIZE = 100000; <add>const SIZE = 100000; <ide> <del>var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { <add>const cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { <ide> stdio: 'inherit' <ide> }); <ide> <ide><path>test/parallel/test-child-process-silent.js <ide> if (process.argv[2] === 'pipe') { <ide> // testcase | start parent && child IPC test <ide> <ide> // testing: is stderr and stdout piped to parent <del> var args = [process.argv[1], 'parent']; <del> var parent = childProcess.spawn(process.execPath, args); <add> const args = [process.argv[1], 'parent']; <add> const parent = childProcess.spawn(process.execPath, args); <ide> <ide> //got any stderr or std data <del> var stdoutData = false; <add> let stdoutData = false; <ide> parent.stdout.on('data', function() { <ide> stdoutData = true; <ide> }); <del> var stderrData = false; <add> let stderrData = false; <ide> parent.stdout.on('data', function() { <ide> stderrData = true; <ide> }); <ide> if (process.argv[2] === 'pipe') { <ide> child.stderr.pipe(process.stderr, {end: false}); <ide> child.stdout.pipe(process.stdout, {end: false}); <ide> <del> var childSending = false; <del> var childReciveing = false; <add> let childSending = false; <add> let childReciveing = false; <ide> child.on('message', function(message) { <ide> if (childSending === false) { <ide> childSending = (message === 'message from child'); <ide><path>test/parallel/test-child-process-spawn-typeerror.js <ide> const invalidFileMsg = <ide> const empty = common.fixturesDir + '/empty.js'; <ide> <ide> assert.throws(function() { <del> var child = spawn(invalidcmd, 'this is not an array'); <add> const child = spawn(invalidcmd, 'this is not an array'); <ide> child.on('error', common.fail); <ide> }, TypeError); <ide> <ide><path>test/parallel/test-child-process-spawnsync-env.js <ide> const cp = require('child_process'); <ide> if (process.argv[2] === 'child') { <ide> console.log(process.env.foo); <ide> } else { <del> var expected = 'bar'; <del> var child = cp.spawnSync(process.execPath, [__filename, 'child'], { <add> const expected = 'bar'; <add> const child = cp.spawnSync(process.execPath, [__filename, 'child'], { <ide> env: Object.assign(process.env, { foo: expected }) <ide> }); <ide> <ide><path>test/parallel/test-child-process-spawnsync-input.js <ide> const args = [ <ide> `console.log("${msgOut}"); console.error("${msgErr}");` <ide> ]; <ide> <del>var ret; <add>let ret; <ide> <ide> <ide> function checkSpawnSyncRet(ret) { <ide> if (process.argv.indexOf('spawnchild') !== -1) { <ide> verifyBufOutput(spawnSync(process.execPath, [__filename, 'spawnchild', 1])); <ide> verifyBufOutput(spawnSync(process.execPath, [__filename, 'spawnchild', 2])); <ide> <del>var options = { <add>let options = { <ide> input: 1234 <ide> }; <ide> <ide><path>test/parallel/test-child-process-spawnsync-timeout.js <ide> const assert = require('assert'); <ide> <ide> const spawnSync = require('child_process').spawnSync; <ide> <del>var TIMER = 200; <del>var SLEEP = 5000; <add>const TIMER = 200; <add>const SLEEP = 5000; <ide> <ide> switch (process.argv[2]) { <ide> case 'child': <ide> switch (process.argv[2]) { <ide> }, SLEEP); <ide> break; <ide> default: <del> var start = Date.now(); <del> var ret = spawnSync(process.execPath, [__filename, 'child'], <add> const start = Date.now(); <add> const ret = spawnSync(process.execPath, [__filename, 'child'], <ide> {timeout: TIMER}); <ide> assert.strictEqual(ret.error.errno, 'ETIMEDOUT'); <ide> console.log(ret); <del> var end = Date.now() - start; <add> const end = Date.now() - start; <ide> assert(end < SLEEP); <ide> assert(ret.status > 128 || ret.signal); <ide> break; <ide><path>test/parallel/test-child-process-stdin-ipc.js <ide> if (process.argv[2] === 'child') { <ide> return; <ide> } <ide> <del>var proc = spawn(process.execPath, [__filename, 'child'], { <add>const proc = spawn(process.execPath, [__filename, 'child'], { <ide> stdio: ['ipc', 'inherit', 'inherit'] <ide> }); <ide> <ide><path>test/parallel/test-child-process-stdio-big-write-end.js <ide> function parent() { <ide> }); <ide> <ide> // Write until the buffer fills up. <add> let buf; <ide> do { <del> var buf = Buffer.alloc(BUFSIZE, '.'); <add> buf = Buffer.alloc(BUFSIZE, '.'); <ide> sent += BUFSIZE; <ide> } while (child.stdin.write(buf)); <ide> <ide><path>test/parallel/test-child-process-stdio-inherit.js <ide> else <ide> grandparent(); <ide> <ide> function grandparent() { <del> var child = spawn(process.execPath, [__filename, 'parent']); <add> const child = spawn(process.execPath, [__filename, 'parent']); <ide> child.stderr.pipe(process.stderr); <del> var output = ''; <del> var input = 'asdfasdf'; <add> let output = ''; <add> const input = 'asdfasdf'; <ide> <ide> child.stdout.on('data', function(chunk) { <ide> output += chunk; <ide><path>test/parallel/test-cli-eval.js <ide> const nodejs = '"' + process.execPath + '"'; <ide> <ide> // replace \ by / because windows uses backslashes in paths, but they're still <ide> // interpreted as the escape character when put between quotes. <del>var filename = __filename.replace(/\\/g, '/'); <add>const filename = __filename.replace(/\\/g, '/'); <ide> <ide> // assert that nothing is written to stdout <ide> child.exec(nodejs + ' --eval 42', <ide> child.exec(nodejs + ' --eval "console.error(42)"', <ide> <ide> // assert that the expected output is written to stdout <ide> ['--print', '-p -e', '-pe', '-p'].forEach(function(s) { <del> var cmd = nodejs + ' ' + s + ' '; <add> const cmd = nodejs + ' ' + s + ' '; <ide> <ide> child.exec(cmd + '42', <ide> function(err, stdout, stderr) { <ide><path>test/parallel/test-cli-syntax.js <ide> const assert = require('assert'); <ide> const spawnSync = require('child_process').spawnSync; <ide> const path = require('path'); <ide> <del>var node = process.execPath; <add>const node = process.execPath; <ide> <ide> // test both sets of arguments that check syntax <del>var syntaxArgs = [ <add>const syntaxArgs = [ <ide> ['-c'], <ide> ['--check'] <ide> ]; <ide> var syntaxArgs = [ <ide> <ide> // loop each possible option, `-c` or `--check` <ide> syntaxArgs.forEach(function(args) { <del> var _args = args.concat(file); <del> var c = spawnSync(node, _args, {encoding: 'utf8'}); <add> const _args = args.concat(file); <add> const c = spawnSync(node, _args, {encoding: 'utf8'}); <ide> <ide> // no output should be produced <ide> assert.strictEqual(c.stdout, '', 'stdout produced'); <ide> var syntaxArgs = [ <ide> <ide> // loop each possible option, `-c` or `--check` <ide> syntaxArgs.forEach(function(args) { <del> var _args = args.concat(file); <del> var c = spawnSync(node, _args, {encoding: 'utf8'}); <add> const _args = args.concat(file); <add> const c = spawnSync(node, _args, {encoding: 'utf8'}); <ide> <ide> // no stdout should be produced <ide> assert.strictEqual(c.stdout, '', 'stdout produced'); <ide> <ide> // stderr should have a syntax error message <del> var match = c.stderr.match(/^SyntaxError: Unexpected identifier$/m); <add> const match = c.stderr.match(/^SyntaxError: Unexpected identifier$/m); <ide> assert(match, 'stderr incorrect'); <ide> <ide> assert.strictEqual(c.status, 1, 'code == ' + c.status); <ide> var syntaxArgs = [ <ide> <ide> // loop each possible option, `-c` or `--check` <ide> syntaxArgs.forEach(function(args) { <del> var _args = args.concat(file); <del> var c = spawnSync(node, _args, {encoding: 'utf8'}); <add> const _args = args.concat(file); <add> const c = spawnSync(node, _args, {encoding: 'utf8'}); <ide> <ide> // no stdout should be produced <ide> assert.strictEqual(c.stdout, '', 'stdout produced'); <ide> <ide> // stderr should have a module not found error message <del> var match = c.stderr.match(/^Error: Cannot find module/m); <add> const match = c.stderr.match(/^Error: Cannot find module/m); <ide> assert(match, 'stderr incorrect'); <ide> <ide> assert.strictEqual(c.status, 1, 'code == ' + c.status); <ide><path>test/parallel/test-cluster-basic.js <ide> if (cluster.isWorker) { <ide> } <ide> }; <ide> <del> var worker; <ide> const stateNames = Object.keys(checks.worker.states); <ide> <ide> //Check events, states, and emit arguments <ide> if (cluster.isWorker) { <ide> checks.cluster.equal[name] = worker === arguments[0]; <ide> <ide> //Check state <del> var state = stateNames[index]; <add> const state = stateNames[index]; <ide> checks.worker.states[state] = (state === worker.state); <ide> })); <ide> }); <ide> if (cluster.isWorker) { <ide> cluster.on('exit', common.mustCall(() => {})); <ide> <ide> //Create worker <del> worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> assert.strictEqual(worker.id, 1); <ide> assert(worker instanceof cluster.Worker, <ide> 'the worker is not a instance of the Worker constructor'); <ide><path>test/parallel/test-cluster-bind-privileged-port.js <ide> if (cluster.isMaster) { <ide> assert.strictEqual(exitCode, 0); <ide> })); <ide> } else { <del> var s = net.createServer(common.fail); <add> const s = net.createServer(common.fail); <ide> s.listen(42, common.fail.bind(null, 'listen should have failed')); <ide> s.on('error', common.mustCall((err) => { <ide> assert.strictEqual(err.code, 'EACCES'); <ide><path>test/parallel/test-cluster-dgram-1.js <ide> else <ide> <ide> <ide> function master() { <del> var listening = 0; <add> let listening = 0; <ide> <ide> // Fork 4 workers. <del> for (var i = 0; i < NUM_WORKERS; i++) <add> for (let i = 0; i < NUM_WORKERS; i++) <ide> cluster.fork(); <ide> <ide> // Wait until all workers are listening. <ide> function master() { <ide> // Start sending messages. <ide> const buf = Buffer.from('hello world'); <ide> const socket = dgram.createSocket('udp4'); <del> var sent = 0; <add> let sent = 0; <ide> doSend(); <ide> <ide> function doSend() { <ide> function master() { <ide> } <ide> <ide> function setupWorker(worker) { <del> var received = 0; <add> let received = 0; <ide> <ide> worker.on('message', common.mustCall((msg) => { <ide> received = msg.received; <ide> function master() { <ide> <ide> <ide> function worker() { <del> var received = 0; <add> let received = 0; <ide> <ide> // Create udp socket and start listening. <del> var socket = dgram.createSocket('udp4'); <add> const socket = dgram.createSocket('udp4'); <ide> <ide> socket.on('message', common.mustCall((data, info) => { <ide> received++; <ide><path>test/parallel/test-cluster-dgram-2.js <ide> else <ide> <ide> <ide> function master() { <del> var received = 0; <add> let received = 0; <ide> <ide> // Start listening on a socket. <del> var socket = dgram.createSocket('udp4'); <add> const socket = dgram.createSocket('udp4'); <ide> socket.bind(common.PORT); <ide> <ide> // Disconnect workers when the expected number of messages have been <ide> function master() { <ide> }, NUM_WORKERS * PACKETS_PER_WORKER)); <ide> <ide> // Fork workers. <del> for (var i = 0; i < NUM_WORKERS; i++) <add> for (let i = 0; i < NUM_WORKERS; i++) <ide> cluster.fork(); <ide> } <ide> <ide><path>test/parallel/test-cluster-dgram-reuse.js <ide> function next() { <ide> <ide> // Work around health check issue <ide> process.nextTick(() => { <del> for (var i = 0; i < sockets.length; i++) <add> for (let i = 0; i < sockets.length; i++) <ide> sockets[i].close(close); <ide> }); <ide> } <ide> <del>var waiting = 2; <add>let waiting = 2; <ide> function close() { <ide> if (--waiting === 0) <ide> cluster.worker.disconnect(); <ide> } <ide> <del>for (var i = 0; i < 2; i++) <add>for (let i = 0; i < 2; i++) <ide> dgram.createSocket({ type: 'udp4', reuseAddr: true }).bind(common.PORT, next); <ide><path>test/parallel/test-cluster-disconnect-race.js <ide> if (common.isWindows) { <ide> cluster.schedulingPolicy = cluster.SCHED_NONE; <ide> <ide> if (cluster.isMaster) { <del> var worker1, worker2; <add> let worker2; <ide> <del> worker1 = cluster.fork(); <add> const worker1 = cluster.fork(); <ide> worker1.on('message', common.mustCall(function() { <ide> worker2 = cluster.fork(); <ide> worker1.disconnect(); <ide> if (cluster.isMaster) { <ide> return; <ide> } <ide> <del>var server = net.createServer(); <add>const server = net.createServer(); <ide> <ide> server.listen(common.PORT, function() { <ide> process.send('listening'); <ide><path>test/parallel/test-cluster-disconnect-suicide-race.js <ide> if (cluster.isMaster) { <ide> return cluster.fork(); <ide> } <ide> <del>var eventFired = false; <add>let eventFired = false; <ide> <ide> cluster.worker.disconnect(); <ide> <ide><path>test/parallel/test-cluster-disconnect-with-no-workers.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const cluster = require('cluster'); <ide> <del>var disconnected; <add>let disconnected; <ide> <ide> process.on('exit', function() { <ide> assert(disconnected); <ide><path>test/parallel/test-cluster-disconnect.js <ide> if (cluster.isWorker) { <ide> }).listen(common.PORT + 1, '127.0.0.1'); <ide> <ide> } else if (cluster.isMaster) { <del> var servers = 2; <add> const servers = 2; <ide> <ide> // test a single TCP server <ide> const testConnection = function(port, cb) { <del> var socket = net.connect(port, '127.0.0.1', () => { <add> const socket = net.connect(port, '127.0.0.1', () => { <ide> // buffer result <del> var result = ''; <add> let result = ''; <ide> socket.on('data', common.mustCall((chunk) => { result += chunk; })); <ide> <ide> // check result <ide> if (cluster.isWorker) { <ide> <ide> // test both servers created in the cluster <ide> const testCluster = function(cb) { <del> var done = 0; <add> let done = 0; <ide> <del> for (var i = 0, l = servers; i < l; i++) { <add> for (let i = 0, l = servers; i < l; i++) { <ide> testConnection(common.PORT + i, (success) => { <ide> assert.ok(success); <ide> done += 1; <ide> if (cluster.isWorker) { <ide> <ide> // start two workers and execute callback when both is listening <ide> const startCluster = function(cb) { <del> var workers = 8; <del> var online = 0; <add> const workers = 8; <add> let online = 0; <ide> <del> for (var i = 0, l = workers; i < l; i++) { <add> for (let i = 0, l = workers; i < l; i++) { <ide> cluster.fork().on('listening', common.mustCall(() => { <ide> online += 1; <ide> if (online === workers * servers) { <ide><path>test/parallel/test-cluster-eaccess.js <ide> if (cluster.isMaster) { <ide> <ide> } else { <ide> common.refreshTmpDir(); <del> var cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', <add> const cp = fork(common.fixturesDir + '/listen-on-socket-and-exit.js', <ide> { stdio: 'inherit' }); <ide> <ide> // message from the child indicates it's ready and listening <ide><path>test/parallel/test-cluster-eaddrinuse.js <ide> const assert = require('assert'); <ide> const fork = require('child_process').fork; <ide> const net = require('net'); <ide> <del>var id = '' + process.argv[2]; <add>const id = '' + process.argv[2]; <ide> <ide> if (id === 'undefined') { <ide> const server = net.createServer(common.fail); <ide> server.listen(common.PORT, function() { <del> var worker = fork(__filename, ['worker']); <add> const worker = fork(__filename, ['worker']); <ide> worker.on('message', function(msg) { <ide> if (msg !== 'stop-listening') return; <ide> server.close(function() { <ide><path>test/parallel/test-cluster-fork-env.js <ide> if (cluster.isWorker) { <ide> assert.strictEqual(result, true); <ide> } else if (cluster.isMaster) { <ide> <del> var checks = { <add> const checks = { <ide> using: false, <ide> overwrite: false <ide> }; <ide> if (cluster.isWorker) { <ide> process.env['cluster_test_overwrite'] = 'old'; <ide> <ide> // Fork worker <del> var worker = cluster.fork({ <add> const worker = cluster.fork({ <ide> 'cluster_test_prop': 'custom', <ide> 'cluster_test_overwrite': 'new' <ide> }); <ide><path>test/parallel/test-cluster-master-error.js <ide> if (cluster.isWorker) { <ide> } else if (process.argv[2] === 'cluster') { <ide> <ide> // Send PID to testcase process <del> var forkNum = 0; <add> let forkNum = 0; <ide> cluster.on('fork', common.mustCall(function forkEvent(worker) { <ide> <ide> // Send PID <ide> if (cluster.isWorker) { <ide> })); <ide> <ide> // Throw accidental error when all workers are listening <del> var listeningNum = 0; <add> let listeningNum = 0; <ide> cluster.on('listening', common.mustCall(function listeningEvent() { <ide> <ide> // When all workers are listening <ide> if (cluster.isWorker) { <ide> <ide> const fork = require('child_process').fork; <ide> <del> var masterExited = false; <del> var workersExited = false; <add> let masterExited = false; <add> let workersExited = false; <ide> <ide> // List all workers <ide> const workers = []; <ide> if (cluster.isWorker) { <ide> <ide> const pollWorkers = function() { <ide> // When master is dead all workers should be dead too <del> var alive = false; <add> let alive = false; <ide> workers.forEach((pid) => alive = common.isAlive(pid)); <ide> if (alive) { <ide> setTimeout(pollWorkers, 50); <ide><path>test/parallel/test-cluster-master-kill.js <ide> if (cluster.isWorker) { <ide> const master = fork(process.argv[1], ['cluster']); <ide> <ide> // get pid info <del> var pid = null; <add> let pid = null; <ide> master.once('message', (data) => { <ide> pid = data.pid; <ide> }); <ide> <ide> // When master is dead <del> var alive = true; <add> let alive = true; <ide> master.on('exit', common.mustCall((code) => { <ide> <ide> // make sure that the master died on purpose <ide><path>test/parallel/test-cluster-message.js <ide> function forEach(obj, fn) { <ide> if (cluster.isWorker) { <ide> // Create a tcp server. This will be used as cluster-shared-server and as an <ide> // alternative IPC channel. <del> var server = net.Server(); <del> var socket, message; <add> const server = net.Server(); <add> let socket, message; <ide> <ide> function maybeReply() { <ide> if (!socket || !message) return; <ide> if (cluster.isWorker) { <ide> server.listen(common.PORT, '127.0.0.1'); <ide> } else if (cluster.isMaster) { <ide> <del> var checks = { <add> const checks = { <ide> global: { <ide> 'receive': false, <ide> 'correct': false <ide> if (cluster.isWorker) { <ide> }; <ide> <ide> <del> var client; <del> var check = function(type, result) { <add> let client; <add> const check = function(type, result) { <ide> checks[type].receive = true; <ide> checks[type].correct = result; <ide> console.error('check', checks); <ide> <del> var missing = false; <add> let missing = false; <ide> forEach(checks, function(type) { <ide> if (type.receive === false) missing = true; <ide> }); <ide> if (cluster.isWorker) { <ide> }; <ide> <ide> // Spawn worker <del> var worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> <ide> // When a IPC message is received from the worker <ide> worker.on('message', function(message) { <ide><path>test/parallel/test-cluster-rr-domain-listen.js <ide> const domain = require('domain'); <ide> // cluster.schedulingPolicy = cluster.SCHED_RR; <ide> <ide> if (cluster.isWorker) { <del> var d = domain.create(); <add> const d = domain.create(); <ide> d.run(function() { }); <ide> <ide> const http = require('http'); <ide> http.Server(function() { }).listen(common.PORT, '127.0.0.1'); <ide> <ide> } else if (cluster.isMaster) { <del> var worker; <ide> <ide> //Kill worker when listening <ide> cluster.on('listening', function() { <ide> if (cluster.isWorker) { <ide> }); <ide> <ide> //Create worker <del> worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> } <ide><path>test/parallel/test-cluster-send-deadlock.js <ide> const cluster = require('cluster'); <ide> const net = require('net'); <ide> <ide> if (cluster.isMaster) { <del> var worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> worker.on('exit', function(code, signal) { <ide> assert.strictEqual(code, 0, 'Worker exited with an error code'); <ide> assert(!signal, 'Worker exited by a signal'); <ide> server.close(); <ide> }); <ide> <del> var server = net.createServer(function(socket) { <add> const server = net.createServer(function(socket) { <ide> worker.send('handle', socket); <ide> }); <ide> <ide> if (cluster.isMaster) { <ide> } else { <ide> process.on('message', function(msg, handle) { <ide> if (msg === 'listen') { <del> var client1 = net.connect({ host: 'localhost', port: common.PORT }); <del> var client2 = net.connect({ host: 'localhost', port: common.PORT }); <del> var waiting = 2; <add> const client1 = net.connect({ host: 'localhost', port: common.PORT }); <add> const client2 = net.connect({ host: 'localhost', port: common.PORT }); <add> let waiting = 2; <ide> client1.on('close', onclose); <ide> client2.on('close', onclose); <ide> function onclose() { <ide><path>test/parallel/test-cluster-setup-master-argv.js <ide> const cluster = require('cluster'); <ide> setTimeout(common.fail.bind(assert, 'setup not emitted'), 1000).unref(); <ide> <ide> cluster.on('setup', common.mustCall(function() { <del> var clusterArgs = cluster.settings.args; <del> var realArgs = process.argv; <add> const clusterArgs = cluster.settings.args; <add> const realArgs = process.argv; <ide> assert.strictEqual(clusterArgs[clusterArgs.length - 1], <ide> realArgs[realArgs.length - 1]); <ide> })); <ide><path>test/parallel/test-cluster-setup-master-multiple.js <ide> function cheapClone(obj) { <ide> return JSON.parse(JSON.stringify(obj)); <ide> } <ide> <del>var configs = []; <add>const configs = []; <ide> <ide> // Capture changes <ide> cluster.on('setup', function() { <ide> console.log('"setup" emitted', cluster.settings); <ide> configs.push(cheapClone(cluster.settings)); <ide> }); <ide> <del>var execs = [ <add>const execs = [ <ide> 'node-next', <ide> 'node-next-2', <ide> 'node-next-3', <ide><path>test/parallel/test-cluster-setup-master.js <ide> if (cluster.isWorker) { <ide> <ide> } else if (cluster.isMaster) { <ide> <del> var checks = { <add> const checks = { <ide> args: false, <ide> setupEvent: false, <ide> settingsObject: false <ide> }; <ide> <del> var totalWorkers = 2; <del> var onlineWorkers = 0; <add> const totalWorkers = 2; <add> let onlineWorkers = 0; <ide> <ide> // Setup master <ide> cluster.setupMaster({ <ide> if (cluster.isWorker) { <ide> cluster.once('setup', function() { <ide> checks.setupEvent = true; <ide> <del> var settings = cluster.settings; <add> const settings = cluster.settings; <ide> if (settings && <ide> settings.args && settings.args[0] === 'custom argument' && <ide> settings.silent === true && <ide> if (cluster.isWorker) { <ide> } <ide> }); <ide> <del> var correctIn = 0; <add> let correctIn = 0; <ide> <ide> cluster.on('online', function lisenter(worker) { <ide> <ide> if (cluster.isWorker) { <ide> assert.ok(checks.workers, 'Not all workers went online'); <ide> assert.ok(checks.args, 'The arguments was noy send to the worker'); <ide> assert.ok(checks.setupEvent, 'The setup event was never emitted'); <del> var m = 'The settingsObject do not have correct properties'; <add> const m = 'The settingsObject do not have correct properties'; <ide> assert.ok(checks.settingsObject, m); <ide> }); <ide> <ide><path>test/parallel/test-cluster-shared-leak.js <ide> const cluster = require('cluster'); <ide> cluster.schedulingPolicy = cluster.SCHED_NONE; <ide> <ide> if (cluster.isMaster) { <del> var conn, worker1, worker2; <add> let conn, worker2; <ide> <del> worker1 = cluster.fork(); <add> const worker1 = cluster.fork(); <ide> worker1.on('message', common.mustCall(function() { <ide> worker2 = cluster.fork(); <ide> worker2.on('online', function() { <ide><path>test/parallel/test-cluster-worker-death.js <ide> const cluster = require('cluster'); <ide> if (!cluster.isMaster) { <ide> process.exit(42); <ide> } else { <del> var worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> worker.on('exit', common.mustCall(function(exitCode, signalCode) { <ide> assert.strictEqual(exitCode, 42); <ide> assert.strictEqual(signalCode, null); <ide><path>test/parallel/test-cluster-worker-destroy.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const cluster = require('cluster'); <del>var worker1, worker2; <add>let worker1, worker2; <ide> <ide> if (cluster.isMaster) { <ide> worker1 = cluster.fork(); <ide><path>test/parallel/test-cluster-worker-events.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const cluster = require('cluster'); <ide> <del>var OK = 2; <add>const OK = 2; <ide> <ide> if (cluster.isMaster) { <ide> <del> var worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> <ide> worker.on('exit', function(code) { <ide> assert.strictEqual(code, OK); <ide> if (cluster.isMaster) { <ide> <ide> assert(cluster.isWorker); <ide> <del>var sawProcess; <del>var sawWorker; <add>let sawProcess; <add>let sawWorker; <ide> <ide> process.on('message', function(m) { <ide> assert(!sawProcess); <ide> cluster.worker.on('message', function(m) { <ide> check(m); <ide> }); <ide> <del>var messages = []; <add>const messages = []; <ide> <ide> function check(m) { <ide> messages.push(m); <ide><path>test/parallel/test-cluster-worker-forced-exit.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const cluster = require('cluster'); <ide> <del>var SENTINEL = 42; <add>const SENTINEL = 42; <ide> <ide> // workers forcibly exit when control channel is disconnected, if <ide> // their .exitedAfterDisconnect flag isn't set <ide><path>test/parallel/test-cluster-worker-isconnected.js <ide> const cluster = require('cluster'); <ide> const assert = require('assert'); <ide> <ide> if (cluster.isMaster) { <del> var worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> <ide> assert.ok(worker.isConnected(), <ide> 'isConnected() should return true as soon as the worker has ' + <ide><path>test/parallel/test-cluster-worker-isdead.js <ide> const cluster = require('cluster'); <ide> const assert = require('assert'); <ide> <ide> if (cluster.isMaster) { <del> var worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> assert.ok(!worker.isDead(), <ide> 'isDead() should return false right after the worker has been ' + <ide> 'created.'); <ide><path>test/parallel/test-cluster-worker-no-exit.js <ide> const assert = require('assert'); <ide> const cluster = require('cluster'); <ide> const net = require('net'); <ide> <del>var destroyed; <del>var success; <del>var worker; <del>var server; <add>let destroyed; <add>let success; <add>let worker; <add>let server; <ide> <ide> // workers do not exit on disconnect, they exit under normal node rules: when <ide> // they have nothing keeping their loop alive, like an active connection <ide> if (cluster.isMaster) { <ide> }); <ide> <ide> }).listen(common.PORT, function() { <del> var port = this.address().port; <add> const port = this.address().port; <ide> <ide> worker = cluster.fork() <ide> .on('online', function() { <ide><path>test/parallel/test-cluster-worker-wait-server-close.js <ide> const assert = require('assert'); <ide> const cluster = require('cluster'); <ide> const net = require('net'); <ide> <del>var serverClosed = false; <add>let serverClosed = false; <ide> <ide> if (cluster.isWorker) { <del> var server = net.createServer(function(socket) { <add> const server = net.createServer(function(socket) { <ide> // Wait for any data, then close connection <ide> socket.write('.'); <ide> socket.on('data', function discard() {}); <ide> if (cluster.isWorker) { <ide> <ide> // Although not typical, the worker process can exit before the disconnect <ide> // event fires. Use this to keep the process open until the event has fired. <del> var keepOpen = setInterval(function() {}, 9999); <add> const keepOpen = setInterval(function() {}, 9999); <ide> <ide> // Check worker events and properties <ide> process.once('disconnect', function() { <ide> if (cluster.isWorker) { <ide> }); <ide> } else if (cluster.isMaster) { <ide> // start worker <del> var worker = cluster.fork(); <add> const worker = cluster.fork(); <ide> <ide> // Disconnect worker when it is ready <ide> worker.once('listening', function() { <ide><path>test/parallel/test-console-instance.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const Stream = require('stream'); <ide> const Console = require('console').Console; <del>var called = false; <add>let called = false; <ide> <ide> const out = new Stream(); <ide> const err = new Stream(); <ide> assert.throws(function() { <ide> <ide> out.write = err.write = function(d) {}; <ide> <del>var c = new Console(out, err); <add>const c = new Console(out, err); <ide> <ide> out.write = err.write = function(d) { <ide> assert.strictEqual(d, 'test\n'); <ide><path>test/parallel/test-console-not-call-toString.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> <del>var func = function() {}; <del>var toStringCalled = false; <add>const func = function() {}; <add>let toStringCalled = false; <ide> func.toString = function() { <ide> toStringCalled = true; <ide> }; <ide><path>test/parallel/test-crypto-binary-default.js <ide> const hmacHash = crypto.createHmac('sha1', 'Node') <ide> assert.strictEqual(hmacHash, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892'); <ide> <ide> // Test HMAC-SHA-* (rfc 4231 Test Cases) <del>var rfc4231 = [ <add>const rfc4231 = [ <ide> { <ide> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), <ide> data: Buffer.from('4869205468657265', 'hex'), // 'Hi There' <ide> var rfc4231 = [ <ide> ]; <ide> <ide> for (let i = 0, l = rfc4231.length; i < l; i++) { <del> for (var hash in rfc4231[i]['hmac']) { <del> var result = crypto.createHmac(hash, rfc4231[i]['key']) <add> for (const hash in rfc4231[i]['hmac']) { <add> let result = crypto.createHmac(hash, rfc4231[i]['key']) <ide> .update(rfc4231[i]['data']) <ide> .digest('hex'); <ide> if (rfc4231[i]['truncate']) { <ide> for (let i = 0, l = rfc4231.length; i < l; i++) { <ide> } <ide> <ide> // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) <del>var rfc2202_md5 = [ <add>const rfc2202_md5 = [ <ide> { <ide> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), <ide> data: 'Hi There', <ide> var rfc2202_md5 = [ <ide> hmac: '6f630fad67cda0ee1fb1f562db3aa53e' <ide> } <ide> ]; <del>var rfc2202_sha1 = [ <add>const rfc2202_sha1 = [ <ide> { <ide> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), <ide> data: 'Hi There', <ide> for (let i = 0, l = rfc2202_sha1.length; i < l; i++) { <ide> } <ide> <ide> // Test hashing <del>var a1 = crypto.createHash('sha1').update('Test123').digest('hex'); <del>var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); <del>var a3 = crypto.createHash('sha512').update('Test123').digest(); // binary <del>var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); <add>const a1 = crypto.createHash('sha1').update('Test123').digest('hex'); <add>const a2 = crypto.createHash('sha256').update('Test123').digest('base64'); <add>const a3 = crypto.createHash('sha512').update('Test123').digest(); // binary <add>const a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); <ide> <ide> if (!common.hasFipsCrypto) { <del> var a0 = crypto.createHash('md5').update('Test123').digest('latin1'); <add> const a0 = crypto.createHash('md5').update('Test123').digest('latin1'); <ide> assert.strictEqual( <ide> a0, <ide> 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c', <ide> assert.deepStrictEqual( <ide> ); <ide> <ide> // Test multiple updates to same hash <del>var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); <del>var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); <add>const h1 = crypto.createHash('sha1').update('Test123').digest('hex'); <add>const h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); <ide> assert.strictEqual(h1, h2, 'multipled updates'); <ide> <ide> // Test hashing for binary files <del>var fn = path.join(common.fixturesDir, 'sample.png'); <del>var sha1Hash = crypto.createHash('sha1'); <del>var fileStream = fs.createReadStream(fn); <add>const fn = path.join(common.fixturesDir, 'sample.png'); <add>const sha1Hash = crypto.createHash('sha1'); <add>const fileStream = fs.createReadStream(fn); <ide> fileStream.on('data', function(data) { <ide> sha1Hash.update(data); <ide> }); <ide> assert.throws(function() { <ide> }, /^Error: Digest method not supported$/); <ide> <ide> // Test signing and verifying <del>var s1 = crypto.createSign('RSA-SHA1') <add>const s1 = crypto.createSign('RSA-SHA1') <ide> .update('Test123') <ide> .sign(keyPem, 'base64'); <del>var s1Verified = crypto.createVerify('RSA-SHA1') <add>const s1Verified = crypto.createVerify('RSA-SHA1') <ide> .update('Test') <ide> .update('123') <ide> .verify(certPem, s1, 'base64'); <ide> assert.strictEqual(s1Verified, true, 'sign and verify (base 64)'); <ide> <del>var s2 = crypto.createSign('RSA-SHA256') <add>const s2 = crypto.createSign('RSA-SHA256') <ide> .update('Test123') <ide> .sign(keyPem); // binary <del>var s2Verified = crypto.createVerify('RSA-SHA256') <add>const s2Verified = crypto.createVerify('RSA-SHA256') <ide> .update('Test') <ide> .update('123') <ide> .verify(certPem, s2); // binary <ide> assert.strictEqual(s2Verified, true, 'sign and verify (binary)'); <ide> <del>var s3 = crypto.createSign('RSA-SHA1') <add>const s3 = crypto.createSign('RSA-SHA1') <ide> .update('Test123') <ide> .sign(keyPem, 'buffer'); <del>var s3Verified = crypto.createVerify('RSA-SHA1') <add>const s3Verified = crypto.createVerify('RSA-SHA1') <ide> .update('Test') <ide> .update('123') <ide> .verify(certPem, s3); <ide> assert.strictEqual(s3Verified, true, 'sign and verify (buffer)'); <ide> <ide> function testCipher1(key) { <ide> // Test encryption and decryption <del> var plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; <del> var cipher = crypto.createCipher('aes192', key); <add> const plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; <add> const cipher = crypto.createCipher('aes192', key); <ide> <ide> // encrypt plaintext which is in utf8 format <ide> // to a ciphertext which will be in hex <del> var ciph = cipher.update(plaintext, 'utf8', 'hex'); <add> let ciph = cipher.update(plaintext, 'utf8', 'hex'); <ide> // Only use binary or hex, not base64. <ide> ciph += cipher.final('hex'); <ide> <del> var decipher = crypto.createDecipher('aes192', key); <del> var txt = decipher.update(ciph, 'hex', 'utf8'); <add> const decipher = crypto.createDecipher('aes192', key); <add> let txt = decipher.update(ciph, 'hex', 'utf8'); <ide> txt += decipher.final('utf8'); <ide> <ide> assert.strictEqual(txt, plaintext, 'encryption and decryption'); <ide> function testCipher1(key) { <ide> function testCipher2(key) { <ide> // encryption and decryption with Base64 <ide> // reported in https://github.com/joyent/node/issues/738 <del> var plaintext = <add> const plaintext = <ide> '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + <ide> 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + <ide> 'jAfaFg**'; <del> var cipher = crypto.createCipher('aes256', key); <add> const cipher = crypto.createCipher('aes256', key); <ide> <ide> // encrypt plaintext which is in utf8 format <ide> // to a ciphertext which will be in Base64 <del> var ciph = cipher.update(plaintext, 'utf8', 'base64'); <add> let ciph = cipher.update(plaintext, 'utf8', 'base64'); <ide> ciph += cipher.final('base64'); <ide> <del> var decipher = crypto.createDecipher('aes256', key); <del> var txt = decipher.update(ciph, 'base64', 'utf8'); <add> const decipher = crypto.createDecipher('aes256', key); <add> let txt = decipher.update(ciph, 'base64', 'utf8'); <ide> txt += decipher.final('utf8'); <ide> <ide> assert.strictEqual(txt, plaintext, 'encryption and decryption with Base64'); <ide> function testCipher2(key) { <ide> <ide> function testCipher3(key, iv) { <ide> // Test encyrption and decryption with explicit key and iv <del> var plaintext = <add> const plaintext = <ide> '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + <ide> 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + <ide> 'jAfaFg**'; <del> var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); <del> var ciph = cipher.update(plaintext, 'utf8', 'hex'); <add> const cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); <add> let ciph = cipher.update(plaintext, 'utf8', 'hex'); <ide> ciph += cipher.final('hex'); <ide> <del> var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); <del> var txt = decipher.update(ciph, 'hex', 'utf8'); <add> const decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); <add> let txt = decipher.update(ciph, 'hex', 'utf8'); <ide> txt += decipher.final('utf8'); <ide> <ide> assert.strictEqual(txt, plaintext, <ide> function testCipher3(key, iv) { <ide> <ide> function testCipher4(key, iv) { <ide> // Test encyrption and decryption with explicit key and iv <del> var plaintext = <add> const plaintext = <ide> '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + <ide> 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + <ide> 'jAfaFg**'; <del> var cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); <del> var ciph = cipher.update(plaintext, 'utf8', 'buffer'); <add> const cipher = crypto.createCipheriv('des-ede3-cbc', key, iv); <add> let ciph = cipher.update(plaintext, 'utf8', 'buffer'); <ide> ciph = Buffer.concat([ciph, cipher.final('buffer')]); <ide> <del> var decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); <del> var txt = decipher.update(ciph, 'buffer', 'utf8'); <add> const decipher = crypto.createDecipheriv('des-ede3-cbc', key, iv); <add> let txt = decipher.update(ciph, 'buffer', 'utf8'); <ide> txt += decipher.final('utf8'); <ide> <ide> assert.strictEqual(txt, plaintext, <ide> assert.throws(function() { <ide> <ide> // Test Diffie-Hellman with two parties sharing a secret, <ide> // using various encodings as we go along <del>var dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); <del>var p1 = dh1.getPrime('buffer'); <del>var dh2 = crypto.createDiffieHellman(p1, 'base64'); <del>var key1 = dh1.generateKeys(); <del>var key2 = dh2.generateKeys('hex'); <del>var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); <del>var secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); <add>const dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); <add>const p1 = dh1.getPrime('buffer'); <add>const dh2 = crypto.createDiffieHellman(p1, 'base64'); <add>const key1 = dh1.generateKeys(); <add>const key2 = dh2.generateKeys('hex'); <add>const secret1 = dh1.computeSecret(key2, 'hex', 'base64'); <add>const secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); <ide> <ide> assert.strictEqual(secret1, secret2.toString('base64')); <ide> <ide> // Create "another dh1" using generated keys from dh1, <ide> // and compute secret again <del>var dh3 = crypto.createDiffieHellman(p1, 'buffer'); <del>var privkey1 = dh1.getPrivateKey(); <add>const dh3 = crypto.createDiffieHellman(p1, 'buffer'); <add>const privkey1 = dh1.getPrivateKey(); <ide> dh3.setPublicKey(key1); <ide> dh3.setPrivateKey(privkey1); <ide> <ide> assert.strictEqual(dh1.getGenerator(), dh3.getGenerator()); <ide> assert.strictEqual(dh1.getPublicKey(), dh3.getPublicKey()); <ide> assert.strictEqual(dh1.getPrivateKey(), dh3.getPrivateKey()); <ide> <del>var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); <add>const secret3 = dh3.computeSecret(key2, 'hex', 'base64'); <ide> <ide> assert.strictEqual(secret1, secret3); <ide> <ide> // https://github.com/joyent/node/issues/2338 <del>var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + <del> '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + <del> '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + <del> 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; <del>var d = crypto.createDiffieHellman(p, 'hex'); <add>const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + <add> '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + <add> '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + <add> 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; <add>const d = crypto.createDiffieHellman(p, 'hex'); <ide> assert.strictEqual(d.verifyError, DH_NOT_SUITABLE_GENERATOR); <ide> <ide> // Test RSA key signing/verification <del>var rsaSign = crypto.createSign('RSA-SHA1'); <del>var rsaVerify = crypto.createVerify('RSA-SHA1'); <add>const rsaSign = crypto.createSign('RSA-SHA1'); <add>const rsaVerify = crypto.createVerify('RSA-SHA1'); <ide> assert.ok(rsaSign instanceof crypto.Sign); <ide> assert.ok(rsaVerify instanceof crypto.Verify); <ide> <ide> rsaSign.update(rsaPubPem); <del>var rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); <add>const rsaSignature = rsaSign.sign(rsaKeyPem, 'hex'); <ide> assert.strictEqual( <ide> rsaSignature, <ide> '5c50e3145c4e2497aadb0eabc83b342d0b0021ece0d4c4a064b7c' + <ide><path>test/parallel/test-crypto-certificate.js <ide> crypto.DEFAULT_ENCODING = 'buffer'; <ide> const fs = require('fs'); <ide> <ide> // Test Certificates <del>var spkacValid = fs.readFileSync(common.fixturesDir + '/spkac.valid'); <del>var spkacFail = fs.readFileSync(common.fixturesDir + '/spkac.fail'); <del>var spkacPem = fs.readFileSync(common.fixturesDir + '/spkac.pem'); <add>const spkacValid = fs.readFileSync(common.fixturesDir + '/spkac.valid'); <add>const spkacFail = fs.readFileSync(common.fixturesDir + '/spkac.fail'); <add>const spkacPem = fs.readFileSync(common.fixturesDir + '/spkac.pem'); <ide> <del>var certificate = new crypto.Certificate(); <add>const certificate = new crypto.Certificate(); <ide> <ide> assert.strictEqual(certificate.verifySpkac(spkacValid), true); <ide> assert.strictEqual(certificate.verifySpkac(spkacFail), false); <ide><path>test/parallel/test-crypto-dh-odd-key.js <ide> if (!common.hasCrypto) { <ide> const crypto = require('crypto'); <ide> <ide> function test() { <del> var odd = Buffer.alloc(39, 'A'); <add> const odd = Buffer.alloc(39, 'A'); <ide> <del> var c = crypto.createDiffieHellman(32); <add> const c = crypto.createDiffieHellman(32); <ide> c.setPrivateKey(odd); <ide> c.generateKeys(); <ide> } <ide><path>test/parallel/test-crypto-dh.js <ide> const DH_NOT_SUITABLE_GENERATOR = crypto.constants.DH_NOT_SUITABLE_GENERATOR; <ide> <ide> // Test Diffie-Hellman with two parties sharing a secret, <ide> // using various encodings as we go along <del>var dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); <del>var p1 = dh1.getPrime('buffer'); <del>var dh2 = crypto.createDiffieHellman(p1, 'buffer'); <del>var key1 = dh1.generateKeys(); <del>var key2 = dh2.generateKeys('hex'); <del>var secret1 = dh1.computeSecret(key2, 'hex', 'base64'); <del>var secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); <add>const dh1 = crypto.createDiffieHellman(common.hasFipsCrypto ? 1024 : 256); <add>const p1 = dh1.getPrime('buffer'); <add>const dh2 = crypto.createDiffieHellman(p1, 'buffer'); <add>let key1 = dh1.generateKeys(); <add>let key2 = dh2.generateKeys('hex'); <add>let secret1 = dh1.computeSecret(key2, 'hex', 'base64'); <add>let secret2 = dh2.computeSecret(key1, 'latin1', 'buffer'); <ide> <ide> assert.equal(secret1, secret2.toString('base64')); <ide> assert.equal(dh1.verifyError, 0); <ide> assert.throws(function() { <ide> <ide> // Create "another dh1" using generated keys from dh1, <ide> // and compute secret again <del>var dh3 = crypto.createDiffieHellman(p1, 'buffer'); <del>var privkey1 = dh1.getPrivateKey(); <add>const dh3 = crypto.createDiffieHellman(p1, 'buffer'); <add>const privkey1 = dh1.getPrivateKey(); <ide> dh3.setPublicKey(key1); <ide> dh3.setPrivateKey(privkey1); <ide> <ide> assert.deepStrictEqual(dh1.getPublicKey(), dh3.getPublicKey()); <ide> assert.deepStrictEqual(dh1.getPrivateKey(), dh3.getPrivateKey()); <ide> assert.equal(dh3.verifyError, 0); <ide> <del>var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); <add>const secret3 = dh3.computeSecret(key2, 'hex', 'base64'); <ide> <ide> assert.equal(secret1, secret3); <ide> <ide> assert.throws(function() { <ide> } <ide> <ide> // Create a shared using a DH group. <del>var alice = crypto.createDiffieHellmanGroup('modp5'); <del>var bob = crypto.createDiffieHellmanGroup('modp5'); <add>const alice = crypto.createDiffieHellmanGroup('modp5'); <add>const bob = crypto.createDiffieHellmanGroup('modp5'); <ide> alice.generateKeys(); <ide> bob.generateKeys(); <del>var aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); <del>var bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); <add>const aSecret = alice.computeSecret(bob.getPublicKey()).toString('hex'); <add>const bSecret = bob.computeSecret(alice.getPublicKey()).toString('hex'); <ide> assert.equal(aSecret, bSecret); <ide> assert.equal(alice.verifyError, DH_NOT_SUITABLE_GENERATOR); <ide> assert.equal(bob.verifyError, DH_NOT_SUITABLE_GENERATOR); <ide> <ide> /* Ensure specific generator (buffer) works as expected. <ide> * The values below (modp2/modp2buf) are for a 1024 bits long prime from <ide> * RFC 2412 E.2, see https://tools.ietf.org/html/rfc2412. */ <del>var modp2 = crypto.createDiffieHellmanGroup('modp2'); <del>var modp2buf = Buffer.from([ <add>const modp2 = crypto.createDiffieHellmanGroup('modp2'); <add>const modp2buf = Buffer.from([ <ide> 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, <ide> 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, <ide> 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, <ide> var modp2buf = Buffer.from([ <ide> 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, <ide> 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff <ide> ]); <del>var exmodp2 = crypto.createDiffieHellman(modp2buf, Buffer.from([2])); <add>const exmodp2 = crypto.createDiffieHellman(modp2buf, Buffer.from([2])); <ide> modp2.generateKeys(); <ide> exmodp2.generateKeys(); <del>var modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()).toString('hex'); <del>var exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()).toString('hex'); <add>let modp2Secret = modp2.computeSecret(exmodp2.getPublicKey()).toString('hex'); <add>const exmodp2Secret = exmodp2.computeSecret(modp2.getPublicKey()) <add> .toString('hex'); <ide> assert.equal(modp2Secret, exmodp2Secret); <ide> assert.equal(modp2.verifyError, DH_NOT_SUITABLE_GENERATOR); <ide> assert.equal(exmodp2.verifyError, DH_NOT_SUITABLE_GENERATOR); <ide> <ide> <ide> // Ensure specific generator (string with encoding) works as expected. <del>var exmodp2_2 = crypto.createDiffieHellman(modp2buf, '02', 'hex'); <add>const exmodp2_2 = crypto.createDiffieHellman(modp2buf, '02', 'hex'); <ide> exmodp2_2.generateKeys(); <ide> modp2Secret = modp2.computeSecret(exmodp2_2.getPublicKey()).toString('hex'); <del>var exmodp2_2Secret = exmodp2_2.computeSecret(modp2.getPublicKey()) <del> .toString('hex'); <add>const exmodp2_2Secret = exmodp2_2.computeSecret(modp2.getPublicKey()) <add> .toString('hex'); <ide> assert.equal(modp2Secret, exmodp2_2Secret); <ide> assert.equal(exmodp2_2.verifyError, DH_NOT_SUITABLE_GENERATOR); <ide> <ide> <ide> // Ensure specific generator (string without encoding) works as expected. <del>var exmodp2_3 = crypto.createDiffieHellman(modp2buf, '\x02'); <add>const exmodp2_3 = crypto.createDiffieHellman(modp2buf, '\x02'); <ide> exmodp2_3.generateKeys(); <ide> modp2Secret = modp2.computeSecret(exmodp2_3.getPublicKey()).toString('hex'); <del>var exmodp2_3Secret = exmodp2_3.computeSecret(modp2.getPublicKey()) <add>const exmodp2_3Secret = exmodp2_3.computeSecret(modp2.getPublicKey()) <ide> .toString('hex'); <ide> assert.equal(modp2Secret, exmodp2_3Secret); <ide> assert.equal(exmodp2_3.verifyError, DH_NOT_SUITABLE_GENERATOR); <ide> <ide> <ide> // Ensure specific generator (numeric) works as expected. <del>var exmodp2_4 = crypto.createDiffieHellman(modp2buf, 2); <add>const exmodp2_4 = crypto.createDiffieHellman(modp2buf, 2); <ide> exmodp2_4.generateKeys(); <ide> modp2Secret = modp2.computeSecret(exmodp2_4.getPublicKey()).toString('hex'); <del>var exmodp2_4Secret = exmodp2_4.computeSecret(modp2.getPublicKey()) <add>const exmodp2_4Secret = exmodp2_4.computeSecret(modp2.getPublicKey()) <ide> .toString('hex'); <ide> assert.equal(modp2Secret, exmodp2_4Secret); <ide> assert.equal(exmodp2_4.verifyError, DH_NOT_SUITABLE_GENERATOR); <ide> <ide> <del>var p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + <del> '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + <del> '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + <del> 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; <del>var bad_dh = crypto.createDiffieHellman(p, 'hex'); <add>const p = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' + <add> '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' + <add> '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' + <add> 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; <add>const bad_dh = crypto.createDiffieHellman(p, 'hex'); <ide> assert.equal(bad_dh.verifyError, DH_NOT_SUITABLE_GENERATOR); <ide> <ide> <ide><path>test/parallel/test-crypto-domain.js <ide> if (!common.hasCrypto) { <ide> const crypto = require('crypto'); <ide> <ide> function test(fn) { <del> var ex = new Error('BAM'); <del> var d = domain.create(); <add> const ex = new Error('BAM'); <add> const d = domain.create(); <ide> d.on('error', common.mustCall(function(err) { <ide> assert.strictEqual(err, ex); <ide> })); <del> var cb = common.mustCall(function() { <add> const cb = common.mustCall(function() { <ide> throw ex; <ide> }); <ide> d.run(cb); <ide><path>test/parallel/test-crypto-domains.js <ide> const common = require('../common'); <ide> const domain = require('domain'); <ide> const assert = require('assert'); <del>var d = domain.create(); <del>var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; <add>const d = domain.create(); <add>const expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; <ide> <ide> if (!common.hasCrypto) { <ide> common.skip('missing crypto'); <ide><path>test/parallel/test-crypto-fips.js <ide> const FIPS_ERROR_STRING = 'Error: Cannot set FIPS mode'; <ide> const OPTION_ERROR_STRING = 'bad option'; <ide> const CNF_FIPS_ON = path.join(common.fixturesDir, 'openssl_fips_enabled.cnf'); <ide> const CNF_FIPS_OFF = path.join(common.fixturesDir, 'openssl_fips_disabled.cnf'); <del>var num_children_ok = 0; <add>let num_children_ok = 0; <ide> <ide> function compiledWithFips() { <ide> return process.config.variables.openssl_fips ? true : false; <ide> } <ide> <ide> function addToEnv(newVar, value) { <del> var envCopy = {}; <add> const envCopy = {}; <ide> for (const e in process.env) { <ide> envCopy[e] = process.env[e]; <ide> } <ide><path>test/parallel/test-crypto-from-binary.js <ide> if (!common.hasCrypto) { <ide> } <ide> const crypto = require('crypto'); <ide> <del>var EXTERN_APEX = 0xFBEE9; <add>const EXTERN_APEX = 0xFBEE9; <ide> <ide> // manually controlled string for checking binary output <del>var ucs2_control = 'a\u0000'; <add>let ucs2_control = 'a\u0000'; <ide> <ide> // grow the strings to proper length <ide> while (ucs2_control.length <= EXTERN_APEX) { <ide> while (ucs2_control.length <= EXTERN_APEX) { <ide> <ide> <ide> // check resultant buffer and output string <del>var b = Buffer.from(ucs2_control + ucs2_control, 'ucs2'); <add>const b = Buffer.from(ucs2_control + ucs2_control, 'ucs2'); <ide> <ide> // <ide> // Test updating from birant data <ide><path>test/parallel/test-crypto-hash.js <ide> if (!common.hasCrypto) { <ide> const crypto = require('crypto'); <ide> <ide> // Test hashing <del>var a1 = crypto.createHash('sha1').update('Test123').digest('hex'); <del>var a2 = crypto.createHash('sha256').update('Test123').digest('base64'); <del>var a3 = crypto.createHash('sha512').update('Test123').digest(); // buffer <del>var a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); <add>const a1 = crypto.createHash('sha1').update('Test123').digest('hex'); <add>const a2 = crypto.createHash('sha256').update('Test123').digest('base64'); <add>const a3 = crypto.createHash('sha512').update('Test123').digest(); // buffer <add>const a4 = crypto.createHash('sha1').update('Test123').digest('buffer'); <ide> <ide> // stream interface <del>var a5 = crypto.createHash('sha512'); <add>let a5 = crypto.createHash('sha512'); <ide> a5.end('Test123'); <ide> a5 = a5.read(); <ide> <del>var a6 = crypto.createHash('sha512'); <add>let a6 = crypto.createHash('sha512'); <ide> a6.write('Te'); <ide> a6.write('st'); <ide> a6.write('123'); <ide> a6.end(); <ide> a6 = a6.read(); <ide> <del>var a7 = crypto.createHash('sha512'); <add>let a7 = crypto.createHash('sha512'); <ide> a7.end(); <ide> a7 = a7.read(); <ide> <del>var a8 = crypto.createHash('sha512'); <add>let a8 = crypto.createHash('sha512'); <ide> a8.write(''); <ide> a8.end(); <ide> a8 = a8.read(); <ide> <ide> if (!common.hasFipsCrypto) { <del> var a0 = crypto.createHash('md5').update('Test123').digest('latin1'); <add> const a0 = crypto.createHash('md5').update('Test123').digest('latin1'); <ide> assert.strictEqual( <ide> a0, <ide> 'h\u00ea\u00cb\u0097\u00d8o\fF!\u00fa+\u000e\u0017\u00ca\u00bd\u008c', <ide> assert.notStrictEqual(a7, undefined, 'no data should return data'); <ide> assert.notStrictEqual(a8, undefined, 'empty string should generate data'); <ide> <ide> // Test multiple updates to same hash <del>var h1 = crypto.createHash('sha1').update('Test123').digest('hex'); <del>var h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); <add>const h1 = crypto.createHash('sha1').update('Test123').digest('hex'); <add>const h2 = crypto.createHash('sha1').update('Test').update('123').digest('hex'); <ide> assert.strictEqual(h1, h2, 'multipled updates'); <ide> <ide> // Test hashing for binary files <del>var fn = path.join(common.fixturesDir, 'sample.png'); <del>var sha1Hash = crypto.createHash('sha1'); <del>var fileStream = fs.createReadStream(fn); <add>const fn = path.join(common.fixturesDir, 'sample.png'); <add>const sha1Hash = crypto.createHash('sha1'); <add>const fileStream = fs.createReadStream(fn); <ide> fileStream.on('data', function(data) { <ide> sha1Hash.update(data); <ide> }); <ide> assert.throws(function() { <ide> }, /Digest method not supported/); <ide> <ide> // Default UTF-8 encoding <del>var hutf8 = crypto.createHash('sha512').update('УТФ-8 text').digest('hex'); <add>const hutf8 = crypto.createHash('sha512').update('УТФ-8 text').digest('hex'); <ide> assert.strictEqual( <ide> hutf8, <ide> '4b21bbd1a68e690a730ddcb5a8bc94ead9879ffe82580767ad7ec6fa8ba2dea6' + <ide> assert.notStrictEqual( <ide> hutf8, <ide> crypto.createHash('sha512').update('УТФ-8 text', 'latin1').digest('hex')); <ide> <del>var h3 = crypto.createHash('sha256'); <add>const h3 = crypto.createHash('sha256'); <ide> h3.digest(); <ide> assert.throws(function() { <ide> h3.digest(); <ide><path>test/parallel/test-crypto-hmac.js <ide> if (!common.hasCrypto) { <ide> const crypto = require('crypto'); <ide> <ide> // Test HMAC <del>var h1 = crypto.createHmac('sha1', 'Node') <add>const h1 = crypto.createHmac('sha1', 'Node') <ide> .update('some data') <ide> .update('to hmac') <ide> .digest('hex'); <ide> assert.strictEqual(h1, '19fd6e1ba73d9ed2224dd5094a71babe85d9a892', 'test HMAC'); <ide> <ide> // Test HMAC (Wikipedia Test Cases) <del>var wikipedia = [ <add>const wikipedia = [ <ide> { <ide> key: 'key', data: 'The quick brown fox jumps over the lazy dog', <ide> hmac: { // HMACs lifted from Wikipedia. <ide> for (let i = 0, l = wikipedia.length; i < l; i++) { <ide> <ide> <ide> // Test HMAC-SHA-* (rfc 4231 Test Cases) <del>var rfc4231 = [ <add>const rfc4231 = [ <ide> { <ide> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), <ide> data: Buffer.from('4869205468657265', 'hex'), // 'Hi There' <ide> for (let i = 0, l = rfc4231.length; i < l; i++) { <ide> } <ide> <ide> // Test HMAC-MD5/SHA1 (rfc 2202 Test Cases) <del>var rfc2202_md5 = [ <add>const rfc2202_md5 = [ <ide> { <ide> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), <ide> data: 'Hi There', <ide> var rfc2202_md5 = [ <ide> hmac: '6f630fad67cda0ee1fb1f562db3aa53e' <ide> } <ide> ]; <del>var rfc2202_sha1 = [ <add>const rfc2202_sha1 = [ <ide> { <ide> key: Buffer.from('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'hex'), <ide> data: 'Hi There', <ide><path>test/parallel/test-crypto-rsa-dsa.js <ide> assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); <ide> rsaSign = crypto.createSign('RSA-SHA1'); <ide> rsaSign.update(rsaPubPem); <ide> assert.doesNotThrow(() => { <del> var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; <add> const signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; <ide> rsaSignature = rsaSign.sign(signOptions, 'hex'); <ide> }); <ide> assert.strictEqual(rsaSignature, expectedSignature); <ide> assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); <ide> rsaSign = crypto.createSign('RSA-SHA1'); <ide> rsaSign.update(rsaPubPem); <ide> assert.throws(() => { <del> var signOptions = { key: rsaKeyPemEncrypted, passphrase: 'wrong' }; <add> const signOptions = { key: rsaKeyPemEncrypted, passphrase: 'wrong' }; <ide> rsaSign.sign(signOptions, 'hex'); <ide> }, decryptError); <ide> <ide><path>test/parallel/test-crypto-sign-verify.js <ide> if (!common.hasCrypto) { <ide> const crypto = require('crypto'); <ide> <ide> // Test certificates <del>var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); <del>var keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); <add>const certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); <add>const keyPem = fs.readFileSync(common.fixturesDir + '/test_key.pem', 'ascii'); <ide> <ide> // Test signing and verifying <ide> { <ide><path>test/parallel/test-crypto-stream.js <ide> Stream2buffer.prototype._write = function(data, encodeing, done) { <ide> <ide> if (!common.hasFipsCrypto) { <ide> // Create an md5 hash of "Hallo world" <del> var hasher1 = crypto.createHash('md5'); <add> const hasher1 = crypto.createHash('md5'); <ide> hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { <ide> assert.strictEqual(err, null); <ide> assert.strictEqual( <ide><path>test/parallel/test-crypto-verify-failure.js <ide> crypto.DEFAULT_ENCODING = 'buffer'; <ide> <ide> const fs = require('fs'); <ide> <del>var certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); <add>const certPem = fs.readFileSync(common.fixturesDir + '/test_cert.pem', 'ascii'); <ide> <del>var options = { <add>const 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>const server = tls.Server(options, function(socket) { <ide> setImmediate(function() { <ide> console.log('sending'); <ide> verify(); <ide><path>test/parallel/test-cwd-enoent-repl.js <ide> if (common.isSunOS || common.isWindows || common.isAix) { <ide> return; <ide> } <ide> <del>var dirname = common.tmpDir + '/cwd-does-not-exist-' + process.pid; <add>const dirname = common.tmpDir + '/cwd-does-not-exist-' + process.pid; <ide> common.refreshTmpDir(); <ide> fs.mkdirSync(dirname); <ide> process.chdir(dirname); <ide> fs.rmdirSync(dirname); <ide> <del>var proc = spawn(process.execPath, ['--interactive']); <add>const proc = spawn(process.execPath, ['--interactive']); <ide> proc.stdout.pipe(process.stdout); <ide> proc.stderr.pipe(process.stderr); <ide> proc.stdin.write('require("path");\n'); <ide><path>test/parallel/test-cwd-enoent.js <ide> if (common.isSunOS || common.isWindows || common.isAix) { <ide> return; <ide> } <ide> <del>var dirname = common.tmpDir + '/cwd-does-not-exist-' + process.pid; <add>const dirname = common.tmpDir + '/cwd-does-not-exist-' + process.pid; <ide> common.refreshTmpDir(); <ide> fs.mkdirSync(dirname); <ide> process.chdir(dirname); <ide> fs.rmdirSync(dirname); <ide> <del>var proc = spawn(process.execPath, ['-e', '0']); <add>const proc = spawn(process.execPath, ['-e', '0']); <ide> proc.stdout.pipe(process.stdout); <ide> proc.stderr.pipe(process.stderr); <ide> <ide><path>test/parallel/test-debug-brk.js <ide> let run = () => {}; <ide> function test(extraArgs, stdoutPattern) { <ide> const next = run; <ide> run = () => { <del> var procStdout = ''; <del> var procStderr = ''; <del> var agentStdout = ''; <del> var debuggerListening = false; <del> var outputMatched = false; <del> var needToSpawnAgent = true; <del> var needToExit = true; <add> let procStdout = ''; <add> let procStderr = ''; <add> let agentStdout = ''; <add> let debuggerListening = false; <add> let outputMatched = false; <add> let needToSpawnAgent = true; <add> let needToExit = true; <ide> <ide> const procArgs = [`--debug-brk=${common.PORT}`].concat(extraArgs); <ide> const proc = spawn(process.execPath, procArgs); <ide><path>test/parallel/test-debug-port-from-cmdline.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const spawn = require('child_process').spawn; <ide> <del>var debugPort = common.PORT; <del>var args = ['--interactive', '--debug-port=' + debugPort]; <del>var childOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }; <del>var child = spawn(process.execPath, args, childOptions); <add>const debugPort = common.PORT; <add>const args = ['--interactive', '--debug-port=' + debugPort]; <add>const childOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }; <add>const child = spawn(process.execPath, args, childOptions); <ide> <ide> child.stdin.write("process.send({ msg: 'childready' });\n"); <ide> <ide> child.stderr.on('data', function(data) { <del> var lines = data.toString().replace(/\r/g, '').trim().split('\n'); <add> const lines = data.toString().replace(/\r/g, '').trim().split('\n'); <ide> lines.forEach(processStderrLine); <ide> }); <ide> <ide> process.on('exit', function() { <ide> assertOutputLines(); <ide> }); <ide> <del>var outputLines = []; <add>const outputLines = []; <ide> function processStderrLine(line) { <ide> console.log('> ' + line); <ide> outputLines.push(line); <ide> function processStderrLine(line) { <ide> } <ide> <ide> function assertOutputLines() { <del> var expectedLines = [ <add> const expectedLines = [ <ide> 'Starting debugger agent.', <ide> 'Debugger listening on 127.0.0.1:' + debugPort, <ide> ]; <ide> <ide> assert.strictEqual(outputLines.length, expectedLines.length); <del> for (var i = 0; i < expectedLines.length; i++) <add> for (let i = 0; i < expectedLines.length; i++) <ide> assert(expectedLines[i].includes(outputLines[i])); <ide> } <ide><path>test/parallel/test-debug-signal-cluster.js <ide> const args = [`--debug-port=${port}`, serverPath]; <ide> const options = { stdio: ['inherit', 'inherit', 'pipe', 'ipc'] }; <ide> const child = spawn(process.execPath, args, options); <ide> <del>var expectedContent = [ <add>let expectedContent = [ <ide> 'Starting debugger agent.', <ide> 'Debugger listening on 127.0.0.1:' + (port + 0), <ide> 'Starting debugger agent.', <ide> var expectedContent = [ <ide> ].join(os.EOL); <ide> expectedContent += os.EOL; // the last line also contains an EOL character <ide> <del>var debuggerAgentsOutput = ''; <del>var debuggerAgentsStarted = false; <add>let debuggerAgentsOutput = ''; <add>let debuggerAgentsStarted = false; <ide> <del>var pids; <add>let pids; <ide> <ide> child.stderr.on('data', function(data) { <ide> const childStderrOutputString = data.toString(); <ide><path>test/parallel/test-debug-uncaught-exception-async.js <ide> const spawn = require('child_process').spawn; <ide> const emitUncaught = path.join(common.fixturesDir, 'debug-uncaught-async.js'); <ide> const result = spawn(process.execPath, [emitUncaught], {encoding: 'utf8'}); <ide> <del>var stderr = ''; <add>let stderr = ''; <ide> result.stderr.on('data', (data) => { <ide> stderr += data; <ide> }); <ide><path>test/parallel/test-debug-usage.js <ide> const expectedUsageMessage = `Usage: node debug script.js <ide> node debug <host>:<port> <ide> node debug -p <pid> <ide> `; <del>var actualUsageMessage = ''; <add>let actualUsageMessage = ''; <ide> child.stderr.on('data', function(data) { <ide> actualUsageMessage += data.toString(); <ide> }); <ide><path>test/parallel/test-debugger-pid.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const spawn = require('child_process').spawn; <ide> <del>var buffer = ''; <add>let buffer = ''; <ide> <ide> // connect to debug agent <del>var interfacer = spawn(process.execPath, ['debug', '-p', '655555']); <add>const interfacer = spawn(process.execPath, ['debug', '-p', '655555']); <ide> <ide> console.error(process.execPath, 'debug', '-p', '655555'); <ide> interfacer.stdout.setEncoding('utf-8'); <ide> interfacer.stderr.setEncoding('utf-8'); <del>var onData = function(data) { <add>const onData = function(data) { <ide> data = (buffer + data).split('\n'); <ide> buffer = data.pop(); <ide> data.forEach(function(line) { <ide> var onData = function(data) { <ide> interfacer.stdout.on('data', onData); <ide> interfacer.stderr.on('data', onData); <ide> <del>var lineCount = 0; <add>let lineCount = 0; <ide> interfacer.on('line', function(line) { <del> var expected; <add> let expected; <ide> const pid = interfacer.pid; <ide> if (common.isWindows) { <ide> switch (++lineCount) { <ide><path>test/parallel/test-debugger-repeat-last.js <ide> const args = [ <ide> const proc = spawn(process.execPath, args, { stdio: 'pipe' }); <ide> proc.stdout.setEncoding('utf8'); <ide> <del>var stdout = ''; <add>let stdout = ''; <ide> <del>var sentCommand = false; <del>var sentEmpty = false; <del>var sentExit = false; <add>let sentCommand = false; <add>let sentEmpty = false; <add>let sentExit = false; <ide> <ide> proc.stdout.on('data', (data) => { <ide> stdout += data; <ide><path>test/parallel/test-dgram-address.js <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> <ide> // IPv4 Test <del>var socket_ipv4 = dgram.createSocket('udp4'); <del>var family_ipv4 = 'IPv4'; <add>const socket_ipv4 = dgram.createSocket('udp4'); <add>const family_ipv4 = 'IPv4'; <ide> <ide> socket_ipv4.on('listening', function() { <del> var address_ipv4 = socket_ipv4.address(); <add> const address_ipv4 = socket_ipv4.address(); <ide> assert.strictEqual(address_ipv4.address, common.localhostIPv4); <ide> assert.strictEqual(typeof address_ipv4.port, 'number'); <ide> assert.ok(isFinite(address_ipv4.port)); <ide> socket_ipv4.on('error', function(e) { <ide> socket_ipv4.bind(0, common.localhostIPv4); <ide> <ide> // IPv6 Test <del>var localhost_ipv6 = '::1'; <del>var socket_ipv6 = dgram.createSocket('udp6'); <del>var family_ipv6 = 'IPv6'; <add>const localhost_ipv6 = '::1'; <add>const socket_ipv6 = dgram.createSocket('udp6'); <add>const family_ipv6 = 'IPv6'; <ide> <ide> socket_ipv6.on('listening', function() { <del> var address_ipv6 = socket_ipv6.address(); <add> const address_ipv6 = socket_ipv6.address(); <ide> assert.strictEqual(address_ipv6.address, localhost_ipv6); <ide> assert.strictEqual(typeof address_ipv6.port, 'number'); <ide> assert.ok(isFinite(address_ipv6.port)); <ide><path>test/parallel/test-dgram-bind.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> <del>var socket = dgram.createSocket('udp4'); <add>const socket = dgram.createSocket('udp4'); <ide> <ide> socket.on('listening', function() { <ide> socket.close(); <ide> }); <ide> <del>var result = socket.bind(); // should not throw <add>const result = socket.bind(); // should not throw <ide> <ide> assert.strictEqual(result, socket); // should have returned itself <ide><path>test/parallel/test-dgram-bytes-length.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> <del>var message = Buffer.from('Some bytes'); <del>var client = dgram.createSocket('udp4'); <add>const message = Buffer.from('Some bytes'); <add>const client = dgram.createSocket('udp4'); <ide> client.send( <ide> message, <ide> 0, <ide><path>test/parallel/test-dgram-close-is-not-callback.js <ide> const common = require('../common'); <ide> const dgram = require('dgram'); <ide> <del>var buf = Buffer.alloc(1024, 42); <add>const buf = Buffer.alloc(1024, 42); <ide> <del>var socket = dgram.createSocket('udp4'); <add>const socket = dgram.createSocket('udp4'); <ide> <ide> socket.send(buf, 0, buf.length, common.PORT, 'localhost'); <ide> <ide><path>test/parallel/test-dgram-close.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> <del>var buf = Buffer.alloc(1024, 42); <add>const buf = Buffer.alloc(1024, 42); <ide> <del>var socket = dgram.createSocket('udp4'); <del>var handle = socket._handle; <add>let socket = dgram.createSocket('udp4'); <add>const handle = socket._handle; <ide> <ide> socket.send(buf, 0, buf.length, common.PORT, 'localhost'); <ide> assert.strictEqual(socket.close(common.mustCall(function() {})), socket); <ide><path>test/parallel/test-dgram-exclusive-implicit-bind.js <ide> const dgram = require('dgram'); <ide> // with ENOTSUP. <ide> <ide> if (cluster.isMaster) { <del> var messages = 0; <add> let messages = 0; <ide> const ports = {}; <ide> const pids = []; <ide> <del> var target = dgram.createSocket('udp4'); <add> const target = dgram.createSocket('udp4'); <ide> <ide> const done = common.mustCall(function() { <ide> cluster.disconnect(); <ide> if (cluster.isMaster) { <ide> } <ide> <ide> const source = dgram.createSocket('udp4'); <del>var interval; <ide> <ide> source.on('close', function() { <ide> clearInterval(interval); <ide> if (process.env.BOUND === 'y') { <ide> } <ide> <ide> const buf = Buffer.from(process.pid.toString()); <del>interval = setInterval(() => { <add>const interval = setInterval(() => { <ide> source.send(buf, common.PORT, '127.0.0.1'); <ide> }, 1).unref(); <ide><path>test/parallel/test-dgram-implicit-bind.js <ide> const common = require('../common'); <ide> const dgram = require('dgram'); <ide> <del>var source = dgram.createSocket('udp4'); <del>var target = dgram.createSocket('udp4'); <del>var messages = 0; <add>const source = dgram.createSocket('udp4'); <add>const target = dgram.createSocket('udp4'); <add>let messages = 0; <ide> <ide> target.on('message', common.mustCall(function(buf) { <ide> if (buf.toString() === 'abc') ++messages; <ide><path>test/parallel/test-dgram-listen-after-bind.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> <del>var socket = dgram.createSocket('udp4'); <add>const socket = dgram.createSocket('udp4'); <ide> <ide> socket.bind(); <ide> <del>var fired = false; <del>var timer = setTimeout(function() { <add>let fired = false; <add>const timer = setTimeout(function() { <ide> socket.close(); <ide> }, 100); <ide> <ide><path>test/parallel/test-dgram-oob-buffer.js <ide> const common = require('../common'); <ide> const dgram = require('dgram'); <ide> <del>var socket = dgram.createSocket('udp4'); <del>var buf = Buffer.from([1, 2, 3, 4]); <add>const socket = dgram.createSocket('udp4'); <add>const buf = Buffer.from([1, 2, 3, 4]); <ide> <ide> function ok() {} <ide> socket.send(buf, 0, 0, common.PORT, '127.0.0.1', ok); // useful? no <ide><path>test/parallel/test-dgram-regress-4496.js <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> <ide> // Should throw but not crash. <del>var socket = dgram.createSocket('udp4'); <add>const socket = dgram.createSocket('udp4'); <ide> assert.throws(function() { socket.send(true, 0, 1, 1, 'host'); }, TypeError); <ide> assert.throws(function() { socket.sendto(5, 0, 1, 1, 'host'); }, TypeError); <ide> socket.close(); <ide><path>test/parallel/test-dgram-send-bad-arguments.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const dgram = require('dgram'); <ide> <del>var buf = Buffer.from('test'); <del>var host = '127.0.0.1'; <del>var sock = dgram.createSocket('udp4'); <add>const buf = Buffer.from('test'); <add>const host = '127.0.0.1'; <add>const sock = dgram.createSocket('udp4'); <ide> <ide> assert.throws(function() { <ide> sock.send(); <ide><path>test/parallel/test-dgram-send-empty-array.js <ide> const dgram = require('dgram'); <ide> <ide> const client = dgram.createSocket('udp4'); <ide> <del>var interval; <add>let interval; <ide> <ide> client.on('message', common.mustCall(function onMessage(buf, info) { <ide> const expected = Buffer.alloc(0); <ide><path>test/parallel/test-dgram-send-empty-buffer.js <ide> client.bind(0, common.mustCall(function() { <ide> })); <ide> <ide> const buf = Buffer.alloc(0); <del> var interval = setInterval(function() { <add> const interval = setInterval(function() { <ide> client.send(buf, 0, 0, port, '127.0.0.1', common.mustCall(function() {})); <ide> }, 10); <ide> })); <ide><path>test/parallel/test-dgram-setTTL.js <ide> const socket = dgram.createSocket('udp4'); <ide> <ide> socket.bind(0); <ide> socket.on('listening', function() { <del> var result = socket.setTTL(16); <add> const result = socket.setTTL(16); <ide> assert.strictEqual(result, 16); <ide> <ide> assert.throws(function() { <ide><path>test/parallel/test-dgram-unref.js <ide> const common = require('../common'); <ide> const dgram = require('dgram'); <ide> <del>var s = dgram.createSocket('udp4'); <add>const s = dgram.createSocket('udp4'); <ide> s.bind(); <ide> s.unref(); <ide> <ide><path>test/parallel/test-dh-padding.js <ide> const crypto = require('crypto'); <ide> * } <ide> */ <ide> <del>var apub = <add>const apub = <ide> '5484455905d3eff34c70980e871f27f05448e66f5a6efbb97cbcba4e927196c2bd9ea272cded91\ <ide> 10a4977afa8d9b16c9139a444ed2d954a794650e5d7cb525204f385e1af81530518563822ecd0f9\ <ide> 524a958d02b3c269e79d6d69850f0968ad567a4404fbb0b19efc8bc73e267b6136b88cafb33299f\ <ide> f7c7cace3ffab1a88c2c9ee841f88b4c3679b4efc465f5c93cca11d487be57373e4c5926f634c4e\ <ide> efee6721d01db91cd66321615b2522f96368dbc818875d422140d0edf30bdb97d9721feddcb9ff6\ <ide> 453741a4f687ee46fc54bf1198801f1210ac789879a5ee123f79e2d2ce1209df2445d32166bc9e4\ <ide> 8f89e944ec9c3b2e16c8066cd8eebd4e33eb941'; <del>var bpub = <add>const bpub = <ide> '3fca64510e36bc7da8a3a901c7b74c2eabfa25deaf7cbe1d0c50235866136ad677317279e1fb0\ <ide> 06e9c0a07f63e14a3363c8e016fbbde2b2c7e79fed1cc3e08e95f7459f547a8cd0523ee9dc744d\ <ide> e5a956d92b937db4448917e1f6829437f05e408ee7aea70c0362b37370c7c75d14449d8b2d2133\ <ide> 04ac972302d349975e2265ca7103cfebd019d9e91234d638611abd049014f7abf706c1c5da6c88\ <ide> 788a1fdc6cdf17f5fffaf024ce8711a2ebde0b52e9f1cb56224483826d6e5ac6ecfaae07b75d20\ <ide> 6e8ac97f5be1a5b68f20382f2a7dac189cf169325c4cf845b26a0cd616c31fec905c5d9035e5f7\ <ide> 8e9880c812374ac0f3ca3d365f06e4be526b5affd4b79'; <del>var apriv = <add>const apriv = <ide> '62411e34704637d99c6c958a7db32ac22fcafafbe1c33d2cfdb76e12ded41f38fc16b792b9041\ <ide> 2e4c82755a3815ba52f780f0ee296ad46e348fc4d1dcd6b64f4eea1b231b2b7d95c5b1c2e26d34\ <ide> 83520558b9860a6eb668f01422a54e6604aa7702b4e67511397ef3ecb912bff1a83899c5a5bfb2\ <ide> 0ee29249a91b8a698e62486f7009a0e9eaebda69d77ecfa2ca6ba2db6c8aa81759c8c90c675979\ <ide> 08c3b3e6fc60668f7be81cce6784482af228dd7f489005253a165e292802cfd0399924f6c56827\ <ide> 7012f68255207722355634290acc7fddeefbba75650a85ece95b6a12de67eac016ba78960108dd\ <ide> 5dbadfaa43cc9fed515a1f307b7d90ae0623bc7b8cefb'; <del>var secret = <add>const secret = <ide> '00c37b1e06a436d6717816a40e6d72907a6f255638b93032267dcb9a5f0b4a9aa0236f3dce63b\ <ide> 1c418c60978a00acd1617dfeecf1661d8a3fafb4d0d8824386750f4853313400e7e4afd22847e4\ <ide> fa56bc9713872021265111906673b38db83d10cbfa1dea3b6b4c97c8655f4ae82125281af7f234\ <ide> dc8fe984ddaf532fc1531ce43155fa0ab32532bf1ece5356b8a3447b5267798a904f16f3f4e635\ <ide> 8612314311231f905f91c63a1aea52e0b60cead8b57df'; <ide> <ide> /* FIPS-friendly 2048 bit prime */ <del>var p = crypto.createDiffieHellman( <add>const p = crypto.createDiffieHellman( <ide> crypto.getDiffieHellman('modp14').getPrime()); <ide> <ide> p.setPublicKey(apub, 'hex'); <ide><path>test/parallel/test-dns-lookup-cb-error.js <ide> cares.getaddrinfo = function() { <ide> }; <ide> <ide> assert.doesNotThrow(() => { <del> var tickValue = 0; <add> let tickValue = 0; <ide> <ide> dns.lookup('example.com', common.mustCall((error, result, addressType) => { <ide> assert(error); <ide><path>test/parallel/test-domain-abort-on-uncaught.js <ide> const assert = require('assert'); <ide> const domain = require('domain'); <ide> const child_process = require('child_process'); <ide> <del>var errorHandlerCalled = false; <add>let errorHandlerCalled = false; <ide> <ide> const tests = [ <ide> function nextTick() { <ide> if (process.argv[2] === 'child') { <ide> } else { <ide> <ide> tests.forEach(function(test, testIndex) { <del> var testCmd = ''; <add> let testCmd = ''; <ide> if (!common.isWindows) { <ide> // Do not create core files, as it can take a lot of disk space on <ide> // continuous testing and developers' machines <ide> if (process.argv[2] === 'child') { <ide> testCmd += ' ' + 'child'; <ide> testCmd += ' ' + testIndex; <ide> <del> var child = child_process.exec(testCmd); <add> const child = child_process.exec(testCmd); <ide> <ide> child.on('exit', function onExit(code, signal) { <ide> assert.strictEqual(code, 0, 'Test at index ' + testIndex + <ide><path>test/parallel/test-domain-enter-exit.js <ide> function names(array) { <ide> }).join(', '); <ide> } <ide> <del>var a = domain.create(); <add>const a = domain.create(); <ide> a.name = 'a'; <del>var b = domain.create(); <add>const b = domain.create(); <ide> b.name = 'b'; <del>var c = domain.create(); <add>const c = domain.create(); <ide> c.name = 'c'; <ide> <ide> a.enter(); // push <ide><path>test/parallel/test-domain-exit-dispose-again.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const domain = require('domain'); <del>var disposalFailed = false; <add>let disposalFailed = false; <ide> <ide> // Repeatedly schedule a timer with a delay different than the timers attached <ide> // to a domain that will eventually be disposed to make sure that they are <ide> // called, regardless of what happens with those timers attached to domains <ide> // that will eventually be disposed. <del>var a = 0; <add>let a = 0; <ide> log(); <ide> function log() { <ide> console.log(a++, process.domain); <ide> if (a < 10) setTimeout(log, 20); <ide> } <ide> <del>var secondTimerRan = false; <add>let secondTimerRan = false; <ide> <ide> // Use the same timeout duration for both "firstTimer" and "secondTimer" <ide> // callbacks so that they are called during the same invocation of the <ide><path>test/parallel/test-domain-exit-dispose.js <ide> const assert = require('assert'); <ide> const domain = require('domain'); <ide> <ide> // no matter what happens, we should increment a 10 times. <del>var a = 0; <add>let a = 0; <ide> log(); <ide> function log() { <ide> console.log(a++, process.domain); <ide> function log() { <ide> // in 50ms we'll throw an error. <ide> setTimeout(err, 50); <ide> function err() { <del> var d = domain.create(); <add> const d = domain.create(); <ide> d.on('error', handle); <ide> d.run(err2); <ide> <ide><path>test/parallel/test-domain-http-server.js <ide> const domain = require('domain'); <ide> const http = require('http'); <ide> const assert = require('assert'); <ide> <del>var objects = { foo: 'bar', baz: {}, num: 42, arr: [1, 2, 3] }; <add>const objects = { foo: 'bar', baz: {}, num: 42, arr: [1, 2, 3] }; <ide> objects.baz.asdf = objects; <ide> <del>var serverCaught = 0; <del>var clientCaught = 0; <add>let serverCaught = 0; <add>let clientCaught = 0; <ide> <del>var server = http.createServer(function(req, res) { <del> var dom = domain.create(); <add>const server = http.createServer(function(req, res) { <add> const dom = domain.create(); <ide> req.resume(); <ide> dom.add(req); <ide> dom.add(res); <ide> var server = http.createServer(function(req, res) { <ide> dom.run(function() { <ide> // Now, an action that has the potential to fail! <ide> // if you request 'baz', then it'll throw a JSON circular ref error. <del> var data = JSON.stringify(objects[req.url.replace(/[^a-z]/g, '')]); <add> const data = JSON.stringify(objects[req.url.replace(/[^a-z]/g, '')]); <ide> <ide> // this line will throw if you pick an unknown key <ide> assert.notStrictEqual(data, undefined, 'Data should not be undefined'); <ide> function next() { <ide> const port = this.address().port; <ide> console.log('listening on localhost:%d', port); <ide> <del> var requests = 0; <del> var responses = 0; <add> let requests = 0; <add> let responses = 0; <ide> <ide> makeReq('/'); <ide> makeReq('/foo'); <ide> function next() { <ide> function makeReq(p) { <ide> requests++; <ide> <del> var dom = domain.create(); <add> const dom = domain.create(); <ide> dom.on('error', function(er) { <ide> clientCaught++; <ide> console.log('client error', er); <ide> req.socket.destroy(); <ide> }); <ide> <del> var req = http.get({ host: 'localhost', port: port, path: p }); <add> const req = http.get({ host: 'localhost', port: port, path: p }); <ide> dom.add(req); <ide> req.on('response', function(res) { <ide> responses++; <ide> function next() { <ide> } <ide> <ide> dom.add(res); <del> var d = ''; <add> let d = ''; <ide> res.on('data', function(c) { <ide> d += c; <ide> }); <ide><path>test/parallel/test-domain-implicit-fs.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const domain = require('domain'); <ide> <del>var d = new domain.Domain(); <add>const d = new domain.Domain(); <ide> <ide> d.on('error', common.mustCall(function(er) { <ide> console.error('caught', er); <ide><path>test/parallel/test-domain-multi.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const domain = require('domain'); <ide> <del>var caughtA = false; <del>var caughtB = false; <del>var caughtC = false; <add>let caughtA = false; <add>let caughtB = false; <add>let caughtC = false; <ide> <ide> <del>var a = domain.create(); <add>const a = domain.create(); <ide> a.enter(); // this will be our "root" domain <ide> a.on('error', function(er) { <ide> caughtA = true; <ide> a.on('error', function(er) { <ide> <ide> <ide> const http = require('http'); <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> // child domain of a. <del> var b = domain.create(); <add> const b = domain.create(); <ide> a.add(b); <ide> <ide> // treat these EE objects as if they are a part of the b domain <ide> var server = http.createServer(function(req, res) { <ide> })); <ide> <ide> }).listen(0, function() { <del> var c = domain.create(); <del> var req = http.get({ host: 'localhost', port: this.address().port }); <add> const c = domain.create(); <add> const req = http.get({ host: 'localhost', port: this.address().port }); <ide> <ide> // add the request to the C domain <ide> c.add(req); <ide><path>test/parallel/test-domain-nested-throw.js <ide> const assert = require('assert'); <ide> <ide> const domain = require('domain'); <ide> <del>var dispose; <add>let dispose; <ide> switch (process.argv[2]) { <ide> case 'true': <ide> dispose = true; <ide> switch (process.argv[2]) { <ide> } <ide> <ide> function parent() { <del> var node = process.execPath; <add> const node = process.execPath; <ide> const spawn = require('child_process').spawn; <del> var opt = { stdio: 'inherit' }; <del> var child = spawn(node, [__filename, 'true'], opt); <add> const opt = { stdio: 'inherit' }; <add> let child = spawn(node, [__filename, 'true'], opt); <ide> child.on('exit', function(c) { <ide> assert(!c); <ide> child = spawn(node, [__filename, 'false'], opt); <ide> function parent() { <ide> }); <ide> } <ide> <del>var gotDomain1Error = false; <del>var gotDomain2Error = false; <add>let gotDomain1Error = false; <add>let gotDomain2Error = false; <ide> <del>var threw1 = false; <del>var threw2 = false; <add>let threw1 = false; <add>let threw2 = false; <ide> <ide> function throw1() { <ide> threw1 = true; <ide> function throw2() { <ide> } <ide> <ide> function inner(throw1, throw2) { <del> var domain1 = domain.createDomain(); <add> const domain1 = domain.createDomain(); <ide> <ide> domain1.on('error', function(err) { <ide> if (gotDomain1Error) { <ide> function inner(throw1, throw2) { <ide> } <ide> <ide> function outer() { <del> var domain2 = domain.createDomain(); <add> const domain2 = domain.createDomain(); <ide> <ide> domain2.on('error', function(err) { <ide> if (gotDomain2Error) { <ide><path>test/parallel/test-domain-safe-exit.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const domain = require('domain'); <ide> <del>var a = domain.create(); <del>var b = domain.create(); <add>const a = domain.create(); <add>const b = domain.create(); <ide> <ide> a.enter(); // push <ide> b.enter(); // push <ide><path>test/parallel/test-domain-stack.js <ide> require('../common'); <ide> const domain = require('domain'); <ide> <del>var a = domain.create(); <add>const a = domain.create(); <ide> a.name = 'a'; <ide> <ide> a.on('error', function() { <ide> a.on('error', function() { <ide> } <ide> }); <ide> <del>var foo = a.bind(function() { <add>const foo = a.bind(function() { <ide> throw new Error('error from foo'); <ide> }); <ide> <del>for (var i = 0; i < 1000; i++) { <add>for (let i = 0; i < 1000; i++) { <ide> process.nextTick(foo); <ide> } <ide> <ide><path>test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js <ide> function runTestWithAbortOnUncaughtException() { <ide> } <ide> <ide> function createTestCmdLine(options) { <del> var testCmd = ''; <add> let testCmd = ''; <ide> <ide> if (!common.isWindows) { <ide> // Do not create core files, as it can take a lot of disk space on <ide><path>test/parallel/test-domain-timers.js <ide> const common = require('../common'); <ide> const domain = require('domain'); <ide> const assert = require('assert'); <ide> <del>var timeout; <del> <del>var timeoutd = domain.create(); <add>const timeoutd = domain.create(); <ide> <ide> timeoutd.on('error', common.mustCall(function(e) { <ide> assert.strictEqual(e.message, 'Timeout UNREFd', <ide> timeoutd.run(function() { <ide> }, 0).unref(); <ide> }); <ide> <del>var immediated = domain.create(); <add>const immediated = domain.create(); <ide> <ide> immediated.on('error', common.mustCall(function(e) { <ide> assert.strictEqual(e.message, 'Immediate Error', <ide> immediated.run(function() { <ide> }); <ide> }); <ide> <del>timeout = setTimeout(function() {}, 10 * 1000); <add>const timeout = setTimeout(function() {}, 10 * 1000); <ide><path>test/parallel/test-domain-top-level-error-handler-throw.js <ide> const internalExMessage = 'You should NOT see me'; <ide> <ide> if (process.argv[2] === 'child') { <ide> const domain = require('domain'); <del> var d = domain.create(); <add> const d = domain.create(); <ide> <ide> d.on('error', function() { <ide> throw new Error(domainErrHandlerExMessage); <ide> if (process.argv[2] === 'child') { <ide> const fork = require('child_process').fork; <ide> const assert = require('assert'); <ide> <del> var child = fork(process.argv[1], ['child'], {silent: true}); <del> var stderrOutput = ''; <add> const child = fork(process.argv[1], ['child'], {silent: true}); <add> let stderrOutput = ''; <ide> if (child) { <ide> child.stderr.on('data', function onStderrData(data) { <ide> stderrOutput += data.toString(); <ide> if (process.argv[2] === 'child') { <ide> }); <ide> <ide> child.on('exit', function onChildExited(exitCode, signal) { <del> var expectedExitCode = 7; <del> var expectedSignal = null; <add> const expectedExitCode = 7; <add> const expectedSignal = null; <ide> <ide> assert.strictEqual(exitCode, expectedExitCode); <ide> assert.strictEqual(signal, expectedSignal); <ide><path>test/parallel/test-domain-with-abort-on-uncaught-exception.js <ide> const domainErrHandlerExMessage = 'exception from domain error handler'; <ide> <ide> if (process.argv[2] === 'child') { <ide> const domain = require('domain'); <del> var d = domain.create(); <add> const d = domain.create(); <ide> <ide> process.on('uncaughtException', function onUncaughtException() { <ide> // The process' uncaughtException event must not be emitted when <ide> if (process.argv[2] === 'child') { <ide> cmdLineOption = undefined; <ide> } <ide> <del> var throwInDomainErrHandlerOpt; <add> let throwInDomainErrHandlerOpt; <ide> if (options.throwInDomainErrHandler) <ide> throwInDomainErrHandlerOpt = 'throwInDomainErrHandler'; <ide> <del> var cmdToExec = ''; <add> let cmdToExec = ''; <ide> if (!common.isWindows) { <ide> // Do not create core files, as it can take a lot of disk space on <ide> // continuous testing and developers' machines <ide> cmdToExec += 'ulimit -c 0 && '; <ide> } <ide> <del> var useTryCatchOpt; <add> let useTryCatchOpt; <ide> if (options.useTryCatch) <ide> useTryCatchOpt = 'useTryCatch'; <ide> <ide> if (process.argv[2] === 'child') { <ide> useTryCatchOpt <ide> ].join(' '); <ide> <del> var child = exec(cmdToExec); <add> const child = exec(cmdToExec); <ide> <ide> if (child) { <ide> child.on('exit', function onChildExited(exitCode, signal) { <ide><path>test/parallel/test-domain.js <ide> const assert = require('assert'); <ide> const domain = require('domain'); <ide> const events = require('events'); <ide> const fs = require('fs'); <del>var caught = 0; <del>var expectCaught = 0; <add>let caught = 0; <add>let expectCaught = 0; <ide> <del>var d = new domain.Domain(); <del>var e = new events.EventEmitter(); <add>const d = new domain.Domain(); <add>const e = new events.EventEmitter(); <ide> <ide> d.on('error', function(er) { <ide> console.error('caught', er && (er.message || er)); <ide> <del> var er_message = er.message; <del> var er_path = er.path; <add> let er_message = er.message; <add> let er_path = er.path; <ide> <ide> // On windows, error messages can contain full path names. If this is the <ide> // case, remove the directory part. <ide> if (typeof er_path === 'string') { <del> var slash = er_path.lastIndexOf('\\'); <add> const slash = er_path.lastIndexOf('\\'); <ide> if (slash !== -1) { <del> var dir = er_path.slice(0, slash + 1); <add> const dir = er_path.slice(0, slash + 1); <ide> er_path = er_path.replace(dir, ''); <ide> er_message = er_message.replace(dir, ''); <ide> } <ide> expectCaught++; <ide> // set up while in the scope of the d domain. <ide> d.run(function() { <ide> process.nextTick(function() { <del> var i = setInterval(function() { <add> const i = setInterval(function() { <ide> clearInterval(i); <ide> setTimeout(function() { <ide> fs.stat('this file does not exist', function(er, stat) { <ide> function fn() { <ide> throw new Error('This function should never be called!'); <ide> } <ide> <del>var bound = d.intercept(fn); <add>let bound = d.intercept(fn); <ide> bound(new Error('bound')); <ide> expectCaught++; <ide> <ide> expectCaught++; <ide> <ide> <ide> // implicit addition by being created within a domain-bound context. <del>var implicit; <add>let implicit; <ide> <ide> d.run(function() { <ide> implicit = new events.EventEmitter(); <ide> setTimeout(function() { <ide> expectCaught++; <ide> <ide> <del>var result = d.run(function() { <add>let result = d.run(function() { <ide> return 'return value'; <ide> }); <ide> assert.strictEqual(result, 'return value'); <ide> result = d.run(function(a, b) { <ide> assert.strictEqual(result, 'return value'); <ide> <ide> <del>var fst = fs.createReadStream('stream for nonexistent file'); <add>const fst = fs.createReadStream('stream for nonexistent file'); <ide> d.add(fst); <ide> expectCaught++; <ide> <ide> [42, null, , false, function() {}, 'string'].forEach(function(something) { <del> var d = new domain.Domain(); <add> const d = new domain.Domain(); <ide> d.run(function() { <ide> process.nextTick(function() { <ide> throw something; <ide><path>test/parallel/test-dsa-fips-invalid-key.js <ide> if (!common.hasFipsCrypto) { <ide> const crypto = require('crypto'); <ide> const fs = require('fs'); <ide> <del>var input = 'hello'; <add>const input = 'hello'; <ide> <del>var dsapri = fs.readFileSync(common.fixturesDir + <add>const dsapri = fs.readFileSync(common.fixturesDir + <ide> '/keys/dsa_private_1025.pem'); <del>var sign = crypto.createSign('DSS1'); <add>const sign = crypto.createSign('DSS1'); <ide> sign.update(input); <ide> <ide> assert.throws(function() { <ide><path>test/parallel/test-error-reporting.js <ide> const exec = require('child_process').exec; <ide> const path = require('path'); <ide> <ide> function errExec(script, callback) { <del> var cmd = '"' + process.argv[0] + '" "' + <del> path.join(common.fixturesDir, script) + '"'; <add> const cmd = '"' + process.argv[0] + '" "' + <add> path.join(common.fixturesDir, script) + '"'; <ide> return exec(cmd, function(err, stdout, stderr) { <ide> // There was some error <ide> assert.ok(err); <ide><path>test/parallel/test-event-emitter-check-listener-leaks.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const events = require('events'); <ide> <del>var e = new events.EventEmitter(); <add>let e = new events.EventEmitter(); <ide> <ide> // default <ide> for (let i = 0; i < 10; i++) { <ide><path>test/parallel/test-event-emitter-errors.js <ide> require('../common'); <ide> const EventEmitter = require('events'); <ide> const assert = require('assert'); <ide> <del>var EE = new EventEmitter(); <add>const EE = new EventEmitter(); <ide> <ide> assert.throws(function() { <ide> EE.emit('error', 'Accepts a string'); <ide><path>test/parallel/test-event-emitter-get-max-listeners.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const EventEmitter = require('events'); <ide> <del>var emitter = new EventEmitter(); <add>const emitter = new EventEmitter(); <ide> <ide> assert.strictEqual(emitter.getMaxListeners(), EventEmitter.defaultMaxListeners); <ide> <ide> emitter.setMaxListeners(3); <ide> assert.strictEqual(emitter.getMaxListeners(), 3); <ide> <ide> // https://github.com/nodejs/node/issues/523 - second call should not throw. <del>var recv = {}; <add>const recv = {}; <ide> EventEmitter.prototype.on.call(recv, 'event', function() {}); <ide> EventEmitter.prototype.on.call(recv, 'event', function() {}); <ide><path>test/parallel/test-event-emitter-listeners-side-effects.js <ide> const assert = require('assert'); <ide> <ide> const EventEmitter = require('events').EventEmitter; <ide> <del>var e = new EventEmitter(); <del>var fl; // foo listeners <add>const e = new EventEmitter(); <add>let fl; // foo listeners <ide> <ide> fl = e.listeners('foo'); <ide> assert(Array.isArray(fl)); <ide><path>test/parallel/test-event-emitter-method-names.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const events = require('events'); <ide> <del>var E = events.EventEmitter.prototype; <add>const E = events.EventEmitter.prototype; <ide> assert.strictEqual(E.constructor.name, 'EventEmitter'); <ide> assert.strictEqual(E.on, E.addListener); // Same method. <ide> Object.getOwnPropertyNames(E).forEach(function(name) { <ide><path>test/parallel/test-event-emitter-no-error-provided-to-error-event.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const events = require('events'); <ide> const domain = require('domain'); <del>var e = new events.EventEmitter(); <add>const e = new events.EventEmitter(); <ide> <del>var d = domain.create(); <add>const d = domain.create(); <ide> d.add(e); <ide> d.on('error', common.mustCall(function(er) { <ide> assert(er instanceof Error, 'error created'); <ide><path>test/parallel/test-event-emitter-num-args.js <ide> const e = new events.EventEmitter(); <ide> const num_args_emited = []; <ide> <ide> e.on('numArgs', function() { <del> var numArgs = arguments.length; <add> const numArgs = arguments.length; <ide> console.log('numArgs: ' + numArgs); <ide> num_args_emited.push(numArgs); <ide> }); <ide><path>test/parallel/test-event-emitter-once.js <ide> e.emit('hello', 'a', 'b'); <ide> e.emit('hello', 'a', 'b'); <ide> e.emit('hello', 'a', 'b'); <ide> <del>var remove = function() { <add>const remove = function() { <ide> common.fail('once->foo should not be emitted'); <ide> }; <ide> <ide><path>test/parallel/test-event-emitter-prepend.js <ide> const EventEmitter = require('events'); <ide> const assert = require('assert'); <ide> <ide> const myEE = new EventEmitter(); <del>var m = 0; <add>let m = 0; <ide> // This one comes last. <ide> myEE.on('foo', common.mustCall(() => assert.equal(m, 2))); <ide> <ide><path>test/parallel/test-event-emitter-remove-all-listeners.js <ide> function listener() {} <ide> <ide> { <ide> const ee = new events.EventEmitter(); <del> var expectLength = 2; <add> let expectLength = 2; <ide> ee.on('removeListener', function(name, listener) { <ide> assert.strictEqual(expectLength--, this.listeners('baz').length); <ide> }); <ide><path>test/parallel/test-event-emitter-set-max-listeners-side-effects.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const events = require('events'); <ide> <del>var e = new events.EventEmitter(); <add>const e = new events.EventEmitter(); <ide> <ide> assert(!(e._events instanceof Object)); <ide> assert.deepStrictEqual(Object.keys(e._events), []); <ide><path>test/parallel/test-event-emitter-subclass.js <ide> function MyEE(cb) { <ide> EventEmitter.call(this); <ide> } <ide> <del>var myee = new MyEE(common.mustCall(function() {})); <add>const myee = new MyEE(common.mustCall(function() {})); <ide> <ide> <ide> util.inherits(ErrorEE, EventEmitter); <ide> function MyEE2() { <ide> <ide> MyEE2.prototype = new EventEmitter(); <ide> <del>var ee1 = new MyEE2(); <del>var ee2 = new MyEE2(); <add>const ee1 = new MyEE2(); <add>const ee2 = new MyEE2(); <ide> <ide> ee1.on('x', function() {}); <ide> <ide><path>test/parallel/test-exception-handler.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> <del>var MESSAGE = 'catch me if you can'; <add>const MESSAGE = 'catch me if you can'; <ide> <ide> process.on('uncaughtException', common.mustCall(function(e) { <ide> console.log('uncaught exception! 1'); <ide><path>test/parallel/test-file-write-stream2.js <ide> const fs = require('fs'); <ide> <ide> <ide> const filepath = path.join(common.tmpDir, 'write.txt'); <del>var file; <ide> <ide> const EXPECTED = '012345678910'; <ide> <ide> const cb_expected = 'write open drain write drain close error '; <del>var cb_occurred = ''; <add>let cb_occurred = ''; <ide> <del>var countDrains = 0; <add>let countDrains = 0; <ide> <ide> <ide> process.on('exit', function() { <ide> function removeTestFile() { <ide> common.refreshTmpDir(); <ide> <ide> // drain at 0, return false at 10. <del>file = fs.createWriteStream(filepath, { <add>const file = fs.createWriteStream(filepath, { <ide> highWaterMark: 11 <ide> }); <ide> <ide> file.on('error', function(err) { <ide> }); <ide> <ide> <del>for (var i = 0; i < 11; i++) { <add>for (let i = 0; i < 11; i++) { <ide> const ret = file.write(i + ''); <ide> console.error('%d %j', i, ret); <ide> <ide><path>test/parallel/test-force-repl-with-eval.js <ide> const spawn = require('child_process').spawn; <ide> <ide> // spawn a node child process in "interactive" mode (force the repl) and eval <ide> const cp = spawn(process.execPath, ['-i', '-e', 'console.log("42")']); <del>var gotToEnd = false; <add>let gotToEnd = false; <ide> <ide> cp.stdout.setEncoding('utf8'); <ide> <del>var output = ''; <add>let output = ''; <ide> cp.stdout.on('data', function(b) { <ide> output += b; <ide> if (output === '> 42\n') { <ide><path>test/parallel/test-force-repl.js <ide> const spawn = require('child_process').spawn; <ide> <ide> // spawn a node child process in "interactive" mode (force the repl) <ide> const cp = spawn(process.execPath, ['-i']); <del>var timeoutId = setTimeout(function() { <add>const timeoutId = setTimeout(function() { <ide> common.fail('timeout!'); <ide> }, common.platformTimeout(5000)); // give node + the repl 5 seconds to start <ide> <ide><path>test/parallel/test-freelist.js <ide> assert.strictEqual(typeof freelist.FreeList, 'function'); <ide> const flist1 = new freelist.FreeList('flist1', 3, String); <ide> <ide> // Allocating when empty, should not change the list size <del>var result = flist1.alloc('test'); <add>const result = flist1.alloc('test'); <ide> assert.strictEqual(typeof result, 'string'); <ide> assert.strictEqual(result, 'test'); <ide> assert.strictEqual(flist1.list.length, 0); <ide><path>test/parallel/test-fs-access.js <ide> assert.doesNotThrow(() => { <ide> }); <ide> <ide> assert.doesNotThrow(() => { <del> var mode = fs.F_OK | fs.R_OK | fs.W_OK; <add> const mode = fs.F_OK | fs.R_OK | fs.W_OK; <ide> <ide> fs.accessSync(readWriteFile, mode); <ide> }); <ide><path>test/parallel/test-fs-chmod.js <ide> fs.open(file2, 'a', common.mustCall((err, fd) => { <ide> <ide> // lchmod <ide> if (fs.lchmod) { <del> var link = path.join(common.tmpDir, 'symbolic-link'); <add> const link = path.join(common.tmpDir, 'symbolic-link'); <ide> <ide> common.refreshTmpDir(); <ide> fs.symlinkSync(file2, link); <ide><path>test/parallel/test-fs-exists.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <del>var f = __filename; <add>const f = __filename; <ide> <ide> fs.exists(f, common.mustCall(function(y) { <ide> assert.strictEqual(y, true); <ide><path>test/parallel/test-fs-long-path.js <ide> if (!common.isWindows) { <ide> } <ide> <ide> // make a path that will be at least 260 chars long. <del>var fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); <del>var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); <del>var fullPath = path.resolve(fileName); <add>const fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); <add>const fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); <add>const fullPath = path.resolve(fileName); <ide> <ide> common.refreshTmpDir(); <ide> <ide><path>test/parallel/test-fs-open-flags.js <ide> const assert = require('assert'); <ide> <ide> const fs = require('fs'); <ide> <del>var O_APPEND = fs.constants.O_APPEND || 0; <del>var O_CREAT = fs.constants.O_CREAT || 0; <del>var O_EXCL = fs.constants.O_EXCL || 0; <del>var O_RDONLY = fs.constants.O_RDONLY || 0; <del>var O_RDWR = fs.constants.O_RDWR || 0; <del>var O_TRUNC = fs.constants.O_TRUNC || 0; <del>var O_WRONLY = fs.constants.O_WRONLY || 0; <add>const O_APPEND = fs.constants.O_APPEND || 0; <add>const O_CREAT = fs.constants.O_CREAT || 0; <add>const O_EXCL = fs.constants.O_EXCL || 0; <add>const O_RDONLY = fs.constants.O_RDONLY || 0; <add>const O_RDWR = fs.constants.O_RDWR || 0; <add>const O_TRUNC = fs.constants.O_TRUNC || 0; <add>const O_WRONLY = fs.constants.O_WRONLY || 0; <ide> <ide> const { stringToFlags } = require('internal/fs'); <ide> <ide><path>test/parallel/test-fs-read-stream-fd-leak.js <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> <del>var openCount = 0; <add>let openCount = 0; <ide> const _fsopen = fs.open; <ide> const _fsclose = fs.close; <ide> <ide> fs.close = function() { <ide> function testLeak(endFn, callback) { <ide> console.log('testing for leaks from fs.createReadStream().%s()...', endFn); <ide> <del> var i = 0; <del> var check = 0; <add> let i = 0; <add> let check = 0; <ide> <ide> const checkFunction = function() { <ide> if (openCount !== 0 && check < totalCheck) { <ide><path>test/parallel/test-fs-read-stream-resume.js <ide> const file = path.join(common.fixturesDir, 'x.txt'); <ide> let data = ''; <ide> let first = true; <ide> <del>var stream = fs.createReadStream(file); <add>const stream = fs.createReadStream(file); <ide> stream.setEncoding('utf8'); <ide> stream.on('data', function(chunk) { <ide> data += chunk; <ide><path>test/parallel/test-fs-read-stream.js <ide> const fs = require('fs'); <ide> const fn = path.join(common.fixturesDir, 'elipses.txt'); <ide> const rangeFile = path.join(common.fixturesDir, 'x.txt'); <ide> <del>var callbacks = { open: 0, end: 0, close: 0 }; <add>const callbacks = { open: 0, end: 0, close: 0 }; <ide> <del>var paused = false; <del>var bytesRead = 0; <add>let paused = false; <add>let bytesRead = 0; <ide> <del>var file = fs.ReadStream(fn); <del>var fileSize = fs.statSync(fn).size; <add>const file = fs.ReadStream(fn); <add>const fileSize = fs.statSync(fn).size; <ide> <ide> assert.strictEqual(file.bytesRead, 0); <ide> <ide> file.on('close', function() { <ide> //assert.equal(fs.readFileSync(fn), fileContent); <ide> }); <ide> <del>var file3 = fs.createReadStream(fn, {encoding: 'utf8'}); <add>const file3 = fs.createReadStream(fn, {encoding: 'utf8'}); <ide> file3.length = 0; <ide> file3.on('data', function(data) { <ide> assert.strictEqual('string', typeof data); <ide> file3.length += data.length; <ide> <del> for (var i = 0; i < data.length; i++) { <add> for (let i = 0; i < data.length; i++) { <ide> // http://www.fileformat.info/info/unicode/char/2026/index.htm <ide> assert.strictEqual('\u2026', data[i]); <ide> } <ide> process.on('exit', function() { <ide> console.error('ok'); <ide> }); <ide> <del>var file4 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1, end: 2}); <del>var contentRead = ''; <add>const file4 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1, end: 2}); <add>let contentRead = ''; <ide> file4.on('data', function(data) { <ide> contentRead += data.toString('utf-8'); <ide> }); <ide> file4.on('end', function(data) { <ide> assert.strictEqual(contentRead, 'yz'); <ide> }); <ide> <del>var file5 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1}); <add>const file5 = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1}); <ide> file5.data = ''; <ide> file5.on('data', function(data) { <ide> file5.data += data.toString('utf-8'); <ide> file5.on('end', function() { <ide> }); <ide> <ide> // https://github.com/joyent/node/issues/2320 <del>var file6 = fs.createReadStream(rangeFile, {bufferSize: 1.23, start: 1}); <add>const file6 = fs.createReadStream(rangeFile, {bufferSize: 1.23, start: 1}); <ide> file6.data = ''; <ide> file6.on('data', function(data) { <ide> file6.data += data.toString('utf-8'); <ide> assert.throws(function() { <ide> fs.createReadStream(rangeFile, {start: 10, end: 2}); <ide> }, /"start" option must be <= "end" option/); <ide> <del>var stream = fs.createReadStream(rangeFile, { start: 0, end: 0 }); <add>const stream = fs.createReadStream(rangeFile, { start: 0, end: 0 }); <ide> stream.data = ''; <ide> <ide> stream.on('data', function(chunk) { <ide> stream.on('end', function() { <ide> }); <ide> <ide> // pause and then resume immediately. <del>var pauseRes = fs.createReadStream(rangeFile); <add>const pauseRes = fs.createReadStream(rangeFile); <ide> pauseRes.pause(); <ide> pauseRes.resume(); <ide> <del>var file7 = fs.createReadStream(rangeFile, {autoClose: false }); <add>let file7 = fs.createReadStream(rangeFile, {autoClose: false }); <ide> file7.on('data', function() {}); <ide> file7.on('end', function() { <ide> process.nextTick(function() { <ide> function file7Next() { <ide> } <ide> <ide> // Just to make sure autoClose won't close the stream because of error. <del>var file8 = fs.createReadStream(null, {fd: 13337, autoClose: false }); <add>const file8 = fs.createReadStream(null, {fd: 13337, autoClose: false }); <ide> file8.on('data', function() {}); <ide> file8.on('error', common.mustCall(function() {})); <ide> <ide> // Make sure stream is destroyed when file does not exist. <del>var file9 = fs.createReadStream('/path/to/file/that/does/not/exist'); <add>const file9 = fs.createReadStream('/path/to/file/that/does/not/exist'); <ide> file9.on('data', function() {}); <ide> file9.on('error', common.mustCall(function() {})); <ide> <ide><path>test/parallel/test-fs-readfile-fd.js <ide> function tempFd(callback) { <ide> } <ide> <ide> function tempFdSync(callback) { <del> var fd = fs.openSync(fn, 'r'); <add> const fd = fs.openSync(fn, 'r'); <ide> callback(fd); <ide> fs.closeSync(fd); <ide> } <ide><path>test/parallel/test-fs-readfile-tostring-fail.js <ide> const stream = fs.createWriteStream(file, { <ide> const size = kStringMaxLength / 200; <ide> const a = Buffer.alloc(size, 'a'); <ide> <del>for (var i = 0; i < 201; i++) { <add>for (let i = 0; i < 201; i++) { <ide> stream.write(a); <ide> } <ide> <ide><path>test/parallel/test-fs-realpath-buffer-encoding.js <ide> const buffer_dir = Buffer.from(string_dir); <ide> <ide> const encodings = ['ascii', 'utf8', 'utf16le', 'ucs2', <ide> 'base64', 'binary', 'hex']; <del>var expected = {}; <add>const expected = {}; <ide> encodings.forEach((encoding) => { <ide> expected[encoding] = buffer_dir.toString(encoding); <ide> }); <ide> <ide> <ide> // test sync version <del>for (var encoding in expected) { <add>let encoding; <add>for (encoding in expected) { <ide> const expected_value = expected[encoding]; <ide> let result; <ide> <ide><path>test/parallel/test-fs-realpath-on-substed-drive.js <ide> let result; <ide> // create a subst drive <ide> const driveLetters = 'ABCDEFGHIJKLMNOPQRSTUWXYZ'; <ide> let drive; <del>for (var i = 0; i < driveLetters.length; ++i) { <add>let i; <add>for (i = 0; i < driveLetters.length; ++i) { <ide> drive = `${driveLetters[i]}:`; <ide> result = spawnSync('subst', [drive, common.fixturesDir]); <ide> if (result.status === 0) <ide><path>test/parallel/test-fs-realpath.js <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> const exec = require('child_process').exec; <del>var async_completed = 0, async_expected = 0, unlink = []; <del>var skipSymlinks = false; <add>let async_completed = 0, async_expected = 0; <add>const unlink = []; <add>let skipSymlinks = false; <ide> <ide> common.refreshTmpDir(); <ide> <del>var root = '/'; <del>var assertEqualPath = assert.strictEqual; <add>let root = '/'; <add>let assertEqualPath = assert.strictEqual; <ide> if (common.isWindows) { <ide> // something like "C:\\" <ide> root = process.cwd().substr(0, 3); <ide> fs.mkdirSync(path.join(targetsAbsDir, 'nested-index', 'two')); <ide> function asynctest(testBlock, args, callback, assertBlock) { <ide> async_expected++; <ide> testBlock.apply(testBlock, args.concat(function(err) { <del> var ignoreError = false; <add> let ignoreError = false; <ide> if (assertBlock) { <ide> try { <ide> ignoreError = assertBlock.apply(assertBlock, arguments); <ide> function test_cyclic_link_overprotection(callback) { <ide> const expected = fs.realpathSync(cycles); <ide> const folder = cycles + '/folder'; <ide> const link = folder + '/cycles'; <del> var testPath = cycles; <add> let testPath = cycles; <ide> testPath += '/folder/cycles'.repeat(10); <ide> try { fs.unlinkSync(link); } catch (ex) {} <ide> fs.symlinkSync(cycles, link, 'dir'); <ide> const tests = [ <ide> test_up_multiple <ide> ]; <ide> const numtests = tests.length; <del>var testsRun = 0; <add>let testsRun = 0; <ide> function runNextTest(err) { <ide> assert.ifError(err); <ide> const test = tests.shift(); <ide><path>test/parallel/test-fs-sir-writes-alot.js <ide> const fs = require('fs'); <ide> const assert = require('assert'); <ide> const join = require('path').join; <ide> <del>var filename = join(common.tmpDir, 'out.txt'); <add>const filename = join(common.tmpDir, 'out.txt'); <ide> <ide> common.refreshTmpDir(); <ide> <del>var fd = fs.openSync(filename, 'w'); <add>const fd = fs.openSync(filename, 'w'); <ide> <del>var line = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n'; <add>const line = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n'; <ide> <del>var N = 10240, complete = 0; <del>for (var i = 0; i < N; i++) { <add>const N = 10240; <add>let complete = 0; <add> <add>for (let i = 0; i < N; i++) { <ide> // Create a new buffer for each write. Before the write is actually <ide> // executed by the thread pool, the buffer will be collected. <del> var buffer = Buffer.from(line); <add> const buffer = Buffer.from(line); <ide> fs.write(fd, buffer, 0, buffer.length, null, function(er, written) { <ide> complete++; <ide> if (complete === N) { <ide> fs.closeSync(fd); <del> var s = fs.createReadStream(filename); <add> const s = fs.createReadStream(filename); <ide> s.on('data', testBuffer); <ide> } <ide> }); <ide> } <ide> <del>var bytesChecked = 0; <add>let bytesChecked = 0; <ide> <ide> function testBuffer(b) { <del> for (var i = 0; i < b.length; i++) { <add> for (let i = 0; i < b.length; i++) { <ide> bytesChecked++; <ide> if (b[i] !== 'a'.charCodeAt(0) && b[i] !== '\n'.charCodeAt(0)) { <ide> throw new Error('invalid char ' + i + ',' + b[i]); <ide><path>test/parallel/test-fs-stat.js <ide> fs.open('.', 'r', undefined, common.mustCall(function(err, fd) { <ide> <ide> // fstatSync <ide> fs.open('.', 'r', undefined, common.mustCall(function(err, fd) { <del> var stats; <add> let stats; <ide> try { <ide> stats = fs.fstatSync(fd); <ide> } catch (err) { <ide><path>test/parallel/test-fs-symlink-dir-junction-relative.js <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> const fs = require('fs'); <ide> <del>var linkPath1 = path.join(common.tmpDir, 'junction1'); <del>var linkPath2 = path.join(common.tmpDir, 'junction2'); <del>var linkTarget = path.join(common.fixturesDir); <del>var linkData = path.join(common.fixturesDir); <add>const linkPath1 = path.join(common.tmpDir, 'junction1'); <add>const linkPath2 = path.join(common.tmpDir, 'junction2'); <add>const linkTarget = path.join(common.fixturesDir); <add>const linkData = path.join(common.fixturesDir); <ide> <ide> common.refreshTmpDir(); <ide> <ide> fs.symlinkSync(linkData, linkPath2, 'junction'); <ide> verifyLink(linkPath2); <ide> <ide> function verifyLink(linkPath) { <del> var stats = fs.lstatSync(linkPath); <add> const stats = fs.lstatSync(linkPath); <ide> assert.ok(stats.isSymbolicLink()); <ide> <del> var data1 = fs.readFileSync(linkPath + '/x.txt', 'ascii'); <del> var data2 = fs.readFileSync(linkTarget + '/x.txt', 'ascii'); <add> const data1 = fs.readFileSync(linkPath + '/x.txt', 'ascii'); <add> const data2 = fs.readFileSync(linkTarget + '/x.txt', 'ascii'); <ide> assert.strictEqual(data1, data2); <ide> <ide> // Clean up. <ide><path>test/parallel/test-fs-symlink.js <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> const fs = require('fs'); <ide> <del>var linkTime; <del>var fileTime; <add>let linkTime; <add>let fileTime; <ide> <ide> if (!common.canCreateSymLink()) { <ide> common.skip('insufficient privileges'); <ide><path>test/parallel/test-fs-sync-fd-leak.js <ide> fs.fstatSync = function() { <ide> throw new Error('BAM'); <ide> }; <ide> <add>let close_called = 0; <ide> ensureThrows(function() { <ide> fs.readFileSync('dummy'); <ide> }); <ide> ensureThrows(function() { <ide> fs.appendFileSync('dummy', 'xxx'); <ide> }); <ide> <del>var close_called = 0; <ide> function ensureThrows(cb) { <del> var got_exception = false; <add> let got_exception = false; <ide> <ide> close_called = 0; <ide> try { <ide><path>test/parallel/test-fs-truncate-GH-6233.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> <del>var filename = common.tmpDir + '/truncate-file.txt'; <add>const filename = common.tmpDir + '/truncate-file.txt'; <ide> <ide> common.refreshTmpDir(); <ide> <ide><path>test/parallel/test-fs-watch-recursive.js <ide> const filepathOne = path.join(testsubdir, filenameOne); <ide> <ide> const watcher = fs.watch(testDir, {recursive: true}); <ide> <del>var watcherClosed = false; <add>let watcherClosed = false; <ide> watcher.on('change', function(event, filename) { <ide> assert.ok('change' === event || 'rename' === event); <ide> <ide> watcher.on('change', function(event, filename) { <ide> watcherClosed = true; <ide> }); <ide> <add>let interval; <ide> if (common.isOSX) { <del> var interval = setInterval(function() { <add> interval = setInterval(function() { <ide> fs.writeFileSync(filepathOne, 'world'); <ide> }, 10); <ide> } else { <ide><path>test/parallel/test-fs-watchfile.js <ide> common.refreshTmpDir(); <ide> <ide> // If the file initially didn't exist, and gets created at a later point of <ide> // time, the callback should be invoked again with proper values in stat object <del>var fileExists = false; <add>let fileExists = false; <ide> <ide> fs.watchFile(enoentFile, {interval: 0}, common.mustCall(function(curr, prev) { <ide> if (!fileExists) { <ide><path>test/parallel/test-fs-write-buffer.js <ide> common.refreshTmpDir(); <ide> assert.strictEqual(expected.length, written); <ide> fs.closeSync(fd); <ide> <del> var found = fs.readFileSync(filename, 'utf8'); <add> const found = fs.readFileSync(filename, 'utf8'); <ide> assert.strictEqual(expected.toString(), found); <ide> }); <ide> <ide><path>test/parallel/test-fs-write-file-buffer.js <ide> const join = require('path').join; <ide> const util = require('util'); <ide> const fs = require('fs'); <ide> <del>var data = [ <add>let data = [ <ide> '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcH', <ide> 'Bw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/', <ide> '2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e', <ide> data = data.join('\n'); <ide> <ide> common.refreshTmpDir(); <ide> <del>var buf = Buffer.from(data, 'base64'); <add>const buf = Buffer.from(data, 'base64'); <ide> fs.writeFileSync(join(common.tmpDir, 'test.jpg'), buf); <ide> <ide> util.log('Done!'); <ide><path>test/parallel/test-fs-write-stream-change-open.js <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> const fs = require('fs'); <ide> <del>var file = path.join(common.tmpDir, 'write.txt'); <add>const file = path.join(common.tmpDir, 'write.txt'); <ide> <ide> common.refreshTmpDir(); <ide> <ide><path>test/parallel/test-fs-write-stream-err.js <ide> const fs = require('fs'); <ide> <ide> common.refreshTmpDir(); <ide> <del>var stream = fs.createWriteStream(common.tmpDir + '/out', { <add>const stream = fs.createWriteStream(common.tmpDir + '/out', { <ide> highWaterMark: 10 <ide> }); <del>var err = new Error('BAM'); <add>const err = new Error('BAM'); <ide> <del>var write = fs.write; <del>var writeCalls = 0; <add>const write = fs.write; <add>let writeCalls = 0; <ide> fs.write = function() { <ide> switch (writeCalls++) { <ide> case 0: <ide> fs.write = function() { <ide> case 1: <ide> // then it breaks <ide> console.error('second write'); <del> var cb = arguments[arguments.length - 1]; <add> const cb = arguments[arguments.length - 1]; <ide> return process.nextTick(function() { <ide> cb(err); <ide> }); <ide><path>test/parallel/test-fs-write-stream.js <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> const fs = require('fs'); <ide> <del>var file = path.join(common.tmpDir, 'write.txt'); <add>const file = path.join(common.tmpDir, 'write.txt'); <ide> <ide> common.refreshTmpDir(); <ide> <ide><path>test/parallel/test-fs-write-string-coerce.js <ide> const fs = require('fs'); <ide> <ide> common.refreshTmpDir(); <ide> <del>var fn = path.join(common.tmpDir, 'write-string-coerce.txt'); <del>var data = true; <del>var expected = data + ''; <add>const fn = path.join(common.tmpDir, 'write-string-coerce.txt'); <add>const data = true; <add>const expected = data + ''; <ide> <ide> fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) { <ide> assert.ifError(err); <ide><path>test/parallel/test-global-console-exists.js <ide> const assert = require('assert'); <ide> const EventEmitter = require('events'); <ide> const leak_warning = /EventEmitter memory leak detected\. 2 hello listeners/; <ide> <del>var write_calls = 0; <add>let write_calls = 0; <ide> <ide> process.on('warning', (warning) => { <ide> // This will be called after the default internal <ide><path>test/parallel/test-http-1.0-keep-alive.js <ide> check([{ <ide> }]); <ide> <ide> function check(tests) { <del> var test = tests[0]; <del> var server; <add> const test = tests[0]; <add> let server; <ide> if (test) { <ide> server = http.createServer(serverHandler).listen(0, '127.0.0.1', client); <ide> } <del> var current = 0; <add> let current = 0; <ide> <ide> function next() { <ide> check(tests.slice(1)); <ide> } <ide> <ide> function serverHandler(req, res) { <ide> if (current + 1 === test.responses.length) this.close(); <del> var ctx = test.responses[current]; <add> const ctx = test.responses[current]; <ide> console.error('< SERVER SENDING RESPONSE', ctx); <ide> res.writeHead(200, ctx.headers); <ide> ctx.chunks.slice(0, -1).forEach(function(chunk) { res.write(chunk); }); <ide> function check(tests) { <ide> function client() { <ide> if (current === test.requests.length) return next(); <ide> const port = server.address().port; <del> var conn = net.createConnection(port, '127.0.0.1', connected); <add> const conn = net.createConnection(port, '127.0.0.1', connected); <ide> <ide> function connected() { <del> var ctx = test.requests[current]; <add> const ctx = test.requests[current]; <ide> console.error(' > CLIENT SENDING REQUEST', ctx); <ide> conn.setEncoding('utf8'); <ide> conn.write(ctx.data); <ide><path>test/parallel/test-http-1.0.js <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> const http = require('http'); <ide> <del>var body = 'hello world\n'; <add>const body = 'hello world\n'; <ide> <ide> function test(handler, request_generator, response_validator) { <del> var server = http.createServer(handler); <add> const server = http.createServer(handler); <ide> <del> var client_got_eof = false; <del> var server_response = ''; <add> let client_got_eof = false; <add> let server_response = ''; <ide> <ide> server.listen(0); <ide> server.on('listening', function() { <del> var c = net.createConnection(this.address().port); <add> const c = net.createConnection(this.address().port); <ide> <ide> c.setEncoding('utf8'); <ide> <ide><path>test/parallel/test-http-abort-before-end.js <ide> const common = require('../common'); <ide> const http = require('http'); <ide> const assert = require('assert'); <ide> <del>var server = http.createServer(common.fail); <add>const server = http.createServer(common.fail); <ide> <ide> server.listen(0, function() { <del> var req = http.request({ <add> const req = http.request({ <ide> method: 'GET', <ide> host: '127.0.0.1', <ide> port: this.address().port <ide><path>test/parallel/test-http-abort-client.js <ide> const common = require('../common'); <ide> const http = require('http'); <ide> <del>var server = http.Server(function(req, res) { <add>const server = http.Server(function(req, res) { <ide> console.log('Server accepted request.'); <ide> res.writeHead(200); <ide> res.write('Part of my res.'); <ide><path>test/parallel/test-http-abort-queued.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var complete; <add>let complete; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> // We should not see the queued /thatotherone request within the server <ide> // as it should be aborted before it is sent. <ide> assert.equal(req.url, '/'); <ide> var server = http.createServer(function(req, res) { <ide> server.listen(0, function() { <ide> console.log('listen', server.address().port); <ide> <del> var agent = new http.Agent({maxSockets: 1}); <add> const agent = new http.Agent({maxSockets: 1}); <ide> assert.equal(Object.keys(agent.sockets).length, 0); <ide> <del> var options = { <add> const options = { <ide> hostname: 'localhost', <ide> port: server.address().port, <ide> method: 'GET', <ide> path: '/', <ide> agent: agent <ide> }; <ide> <del> var req1 = http.request(options); <add> const req1 = http.request(options); <ide> req1.on('response', function(res1) { <ide> assert.equal(Object.keys(agent.sockets).length, 1); <ide> assert.equal(Object.keys(agent.requests).length, 0); <ide> <del> var req2 = http.request({ <add> const req2 = http.request({ <ide> method: 'GET', <ide> host: 'localhost', <ide> port: server.address().port, <ide><path>test/parallel/test-http-after-connect.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var clientResponses = 0; <add>let clientResponses = 0; <ide> <ide> const server = http.createServer(common.mustCall(function(req, res) { <ide> console.error('Server got GET request'); <ide> function doRequest(i) { <ide> path: '/request' + i <ide> }, common.mustCall(function(res) { <ide> console.error('Client got GET response'); <del> var data = ''; <add> let data = ''; <ide> res.setEncoding('utf8'); <ide> res.on('data', function(chunk) { <ide> data += chunk; <ide><path>test/parallel/test-http-agent-destroyed-socket.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.end('Hello World\n'); <ide> }).listen(0, function() { <del> var agent = new http.Agent({maxSockets: 1}); <add> const agent = new http.Agent({maxSockets: 1}); <ide> <ide> agent.on('free', function(socket, host, port) { <ide> console.log('freeing socket. destroyed? ', socket.destroyed); <ide> }); <ide> <del> var requestOptions = { <add> const requestOptions = { <ide> agent: agent, <ide> host: 'localhost', <ide> port: this.address().port, <ide> path: '/' <ide> }; <ide> <del> var request1 = http.get(requestOptions, function(response) { <add> const request1 = http.get(requestOptions, function(response) { <ide> // assert request2 is queued in the agent <del> var key = agent.getName(requestOptions); <add> const key = agent.getName(requestOptions); <ide> assert.strictEqual(agent.requests[key].length, 1); <ide> console.log('got response1'); <ide> request1.socket.on('close', function() { <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> }); <ide> <del> var request2 = http.get(requestOptions, function(response) { <add> const request2 = http.get(requestOptions, function(response) { <ide> assert(!request2.socket.destroyed); <ide> assert(request1.socket.destroyed); <ide> // assert not reusing the same socket, since it was destroyed. <ide> assert.notStrictEqual(request1.socket, request2.socket); <ide> console.log('got response2'); <del> var gotClose = false; <del> var gotResponseEnd = false; <add> let gotClose = false; <add> let gotResponseEnd = false; <ide> request2.socket.on('close', function() { <ide> console.log('request2 socket closed'); <ide> gotClose = true; <ide><path>test/parallel/test-http-agent-error-on-idle.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <del>var Agent = http.Agent; <add>const Agent = http.Agent; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.end('hello world'); <ide> }); <ide> <ide> server.listen(0, function() { <del> var agent = new Agent({ <add> const agent = new Agent({ <ide> keepAlive: true, <ide> }); <ide> <del> var requestParams = { <add> const requestParams = { <ide> host: 'localhost', <ide> port: this.address().port, <ide> agent: agent, <ide> path: '/' <ide> }; <ide> <del> var socketKey = agent.getName(requestParams); <add> const socketKey = agent.getName(requestParams); <ide> <ide> get(function(res) { <ide> assert.equal(res.statusCode, 200); <ide> res.resume(); <ide> res.on('end', function() { <ide> process.nextTick(function() { <del> var freeSockets = agent.freeSockets[socketKey]; <add> const freeSockets = agent.freeSockets[socketKey]; <ide> assert.equal(freeSockets.length, 1, <ide> 'expect a free socket on ' + socketKey); <ide> <ide> //generate a random error on the free socket <del> var freeSocket = freeSockets[0]; <add> const freeSocket = freeSockets[0]; <ide> freeSocket.emit('error', new Error('ECONNRESET: test')); <ide> <ide> get(done); <ide><path>test/parallel/test-http-agent-false.js <ide> const http = require('http'); <ide> // sending `agent: false` when `port: null` is also passed in (i.e. the result <ide> // of a `url.parse()` call with the default port used, 80 or 443), should not <ide> // result in an assertion error... <del>var opts = { <add>const opts = { <ide> host: '127.0.0.1', <ide> port: null, <ide> path: '/', <ide> method: 'GET', <ide> agent: false <ide> }; <ide> <del>var good = false; <add>let good = false; <ide> process.on('exit', function() { <ide> assert(good, 'expected either an "error" or "response" event'); <ide> }); <ide> <ide> // we just want an "error" (no local HTTP server on port 80) or "response" <ide> // to happen (user happens ot have HTTP server running on port 80). <ide> // As long as the process doesn't crash from a C++ assertion then we're good. <del>var req = http.request(opts); <add>const req = http.request(opts); <ide> req.on('response', function(res) { <ide> good = true; <ide> }); <ide><path>test/parallel/test-http-agent-maxsockets-regress-4050.js <ide> function get(path, callback) { <ide> } <ide> <ide> server.listen(0, function() { <del> var finished = 0; <add> let finished = 0; <ide> const num_requests = 6; <del> for (var i = 0; i < num_requests; i++) { <add> for (let i = 0; i < num_requests; i++) { <ide> const request = get('/1', function() { <ide> }); <ide> request.on('response', function() { <ide><path>test/parallel/test-http-agent-maxsockets.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var agent = new http.Agent({ <add>const agent = new http.Agent({ <ide> keepAlive: true, <ide> keepAliveMsecs: 1000, <ide> maxSockets: 2, <ide> maxFreeSockets: 2 <ide> }); <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.end('hello world'); <ide> }); <ide> <ide> function get(path, callback) { <ide> }, callback); <ide> } <ide> <del>var count = 0; <add>let count = 0; <ide> function done() { <ide> if (++count !== 2) { <ide> return; <ide> } <del> var freepool = agent.freeSockets[Object.keys(agent.freeSockets)[0]]; <add> const freepool = agent.freeSockets[Object.keys(agent.freeSockets)[0]]; <ide> assert.equal(freepool.length, 2, <ide> 'expect keep 2 free sockets, but got ' + freepool.length); <ide> agent.destroy(); <ide><path>test/parallel/test-http-agent-no-protocol.js <ide> const common = require('../common'); <ide> const http = require('http'); <ide> const url = require('url'); <ide> <del>var server = http.createServer(common.mustCall(function(req, res) { <add>const server = http.createServer(common.mustCall(function(req, res) { <ide> res.end(); <ide> })).listen(0, '127.0.0.1', common.mustCall(function() { <del> var opts = url.parse(`http://127.0.0.1:${this.address().port}/`); <add> const 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><path>test/parallel/test-http-agent-null.js <ide> const common = require('../common'); <ide> const http = require('http'); <ide> <del>var server = http.createServer(common.mustCall(function(req, res) { <add>const server = http.createServer(common.mustCall(function(req, res) { <ide> res.end(); <ide> })).listen(0, common.mustCall(function() { <del> var options = { <add> const options = { <ide> agent: null, <ide> port: this.address().port <ide> }; <ide><path>test/parallel/test-http-agent.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var server = http.Server(function(req, res) { <add>const server = http.Server(function(req, res) { <ide> res.writeHead(200); <ide> res.end('hello world\n'); <ide> }); <ide> <del>var responses = 0; <del>var N = 4; <del>var M = 4; <add>let responses = 0; <add>const N = 4; <add>const M = 4; <ide> <ide> server.listen(0, function() { <ide> const port = this.address().port; <del> for (var i = 0; i < N; i++) { <add> for (let i = 0; i < N; i++) { <ide> setTimeout(function() { <del> for (var j = 0; j < M; j++) { <add> for (let j = 0; j < M; j++) { <ide> http.get({ port: port, path: '/' }, function(res) { <ide> console.log('%d %d', responses, res.statusCode); <ide> if (++responses === N * M) { <ide><path>test/parallel/test-http-automatic-headers.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.setHeader('X-Date', 'foo'); <ide> res.setHeader('X-Connection', 'bar'); <ide> res.setHeader('X-Content-Length', 'baz'); <ide> var server = http.createServer(function(req, res) { <ide> server.listen(0); <ide> <ide> server.on('listening', function() { <del> var agent = new http.Agent({ port: this.address().port, maxSockets: 1 }); <add> const agent = new http.Agent({ port: this.address().port, maxSockets: 1 }); <ide> http.get({ <ide> port: this.address().port, <ide> path: '/hello', <ide><path>test/parallel/test-http-blank-header.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const net = require('net'); <ide> <del>var server = http.createServer(common.mustCall(function(req, res) { <add>const server = http.createServer(common.mustCall(function(req, res) { <ide> assert.equal('GET', req.method); <ide> assert.equal('/blah', req.url); <ide> assert.deepStrictEqual({ <ide> var server = http.createServer(common.mustCall(function(req, res) { <ide> <ide> <ide> server.listen(0, function() { <del> var c = net.createConnection(this.address().port); <add> const c = net.createConnection(this.address().port); <ide> <ide> c.on('connect', function() { <ide> c.write('GET /blah HTTP/1.1\r\n' + <ide><path>test/parallel/test-http-buffer-sanity.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var bufferSize = 5 * 1024 * 1024; <del>var measuredSize = 0; <add>const bufferSize = 5 * 1024 * 1024; <add>let measuredSize = 0; <ide> <del>var buffer = Buffer.allocUnsafe(bufferSize); <del>for (var i = 0; i < buffer.length; i++) { <add>const buffer = Buffer.allocUnsafe(bufferSize); <add>for (let i = 0; i < buffer.length; i++) { <ide> buffer[i] = i % 256; <ide> } <ide> <ide> <del>var web = http.Server(function(req, res) { <add>const web = http.Server(function(req, res) { <ide> web.close(); <ide> <ide> console.log(req.headers); <ide> <del> var i = 0; <add> let i = 0; <ide> <ide> req.on('data', function(d) { <ide> process.stdout.write(','); <ide> measuredSize += d.length; <del> for (var j = 0; j < d.length; j++) { <add> for (let j = 0; j < d.length; j++) { <ide> assert.equal(buffer[i], d[j]); <ide> i++; <ide> } <ide> var web = http.Server(function(req, res) { <ide> web.listen(0, common.mustCall(function() { <ide> console.log('Making request'); <ide> <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port, <ide> method: 'GET', <ide> path: '/', <ide><path>test/parallel/test-http-byteswritten.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var body = 'hello world\n'; <add>const body = 'hello world\n'; <ide> <del>var httpServer = http.createServer(common.mustCall(function(req, res) { <add>const httpServer = http.createServer(common.mustCall(function(req, res) { <ide> httpServer.close(); <ide> <ide> res.on('finish', common.mustCall(function() { <ide> var httpServer = http.createServer(common.mustCall(function(req, res) { <ide> <ide> // Write 1.5mb to cause some requests to buffer <ide> // Also, mix up the encodings a bit. <del> var chunk = new Array(1024 + 1).join('7'); <del> var bchunk = Buffer.from(chunk); <del> for (var i = 0; i < 1024; i++) { <add> const chunk = new Array(1024 + 1).join('7'); <add> const bchunk = Buffer.from(chunk); <add> for (let i = 0; i < 1024; i++) { <ide> res.write(chunk); <ide> res.write(bchunk); <ide> res.write(chunk, 'hex'); <ide><path>test/parallel/test-http-chunked.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' + <del> '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + <del> '贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + <del> '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + <del> '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + <del> '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。' + <del> '南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + <del> '采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + <del> '有效的改善了岭南地区落后的政治、经济现状。'; <add>const UTF8_STRING = '南越国是前203年至前111年存在于岭南地区的一个国家,' + <add> '国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、' + <add> '贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,' + <add> '由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,' + <add> '南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' + <add> '南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。' + <add> '南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,' + <add> '采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,' + <add> '有效的改善了岭南地区落后的政治、经济现状。'; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'}); <ide> res.end(UTF8_STRING, 'utf8'); <ide> }); <ide> server.listen(0, function() { <del> var data = ''; <del> var get = http.get({ <add> let data = ''; <add> const get = http.get({ <ide> path: '/', <ide> host: 'localhost', <ide> port: this.address().port <ide><path>test/parallel/test-http-client-abort-event.js <ide> 'use strict'; <ide> const common = require('../common'); <ide> const http = require('http'); <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.end(); <ide> }); <ide> <ide> server.listen(0, common.mustCall(function() { <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port <ide> }, common.fail); <ide> <ide><path>test/parallel/test-http-client-abort.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var clientAborts = 0; <add>let clientAborts = 0; <ide> <ide> const server = http.Server(function(req, res) { <ide> console.log('Got connection'); <ide> const server = http.Server(function(req, res) { <ide> }); <ide> }); <ide> <del>var responses = 0; <add>let responses = 0; <ide> const N = 8; <ide> const requests = []; <ide> <ide> server.listen(0, function() { <ide> console.log('Server listening.'); <ide> <del> for (var i = 0; i < N; i++) { <add> for (let i = 0; i < N; i++) { <ide> console.log('Making client ' + i); <del> var options = { port: this.address().port, path: '/?id=' + i }; <del> var req = http.get(options, function(res) { <add> const options = { port: this.address().port, path: '/?id=' + i }; <add> const req = http.get(options, function(res) { <ide> console.log('Client response code ' + res.statusCode); <ide> <ide> res.resume(); <ide><path>test/parallel/test-http-client-abort2.js <ide> require('../common'); <ide> const http = require('http'); <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.end('Hello'); <ide> }); <ide> <ide> server.listen(0, function() { <del> var req = http.get({port: this.address().port}, function(res) { <add> const req = http.get({port: this.address().port}, function(res) { <ide> res.on('data', function(data) { <ide> req.abort(); <ide> server.close(); <ide><path>test/parallel/test-http-client-agent.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var name; <del>var max = 3; <del>var count = 0; <add>let name; <add>const max = 3; <add>let count = 0; <ide> <del>var server = http.Server(function(req, res) { <add>const server = http.Server(function(req, res) { <ide> if (req.url === '/0') { <ide> setTimeout(function() { <ide> res.writeHead(200); <ide> var server = http.Server(function(req, res) { <ide> }); <ide> server.listen(0, function() { <ide> name = http.globalAgent.getName({ port: this.address().port }); <del> for (var i = 0; i < max; ++i) { <add> for (let i = 0; i < max; ++i) { <ide> request(i); <ide> } <ide> }); <ide> <ide> function request(i) { <del> var req = http.get({ <add> const req = http.get({ <ide> port: server.address().port, <ide> path: '/' + i <ide> }, function(res) { <del> var socket = req.socket; <add> const socket = req.socket; <ide> socket.on('close', function() { <ide> ++count; <ide> if (count < max) { <ide><path>test/parallel/test-http-client-default-headers-exist.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var expectedHeaders = { <add>const expectedHeaders = { <ide> 'DELETE': ['host', 'connection'], <ide> 'GET': ['host', 'connection'], <ide> 'HEAD': ['host', 'connection'], <ide> var expectedHeaders = { <ide> 'PUT': ['host', 'connection', 'content-length'] <ide> }; <ide> <del>var expectedMethods = Object.keys(expectedHeaders); <add>const expectedMethods = Object.keys(expectedHeaders); <ide> <del>var requestCount = 0; <add>let requestCount = 0; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> requestCount++; <ide> res.end(); <ide> <ide> assert(expectedHeaders.hasOwnProperty(req.method), <ide> req.method + ' was an unexpected method'); <ide> <del> var requestHeaders = Object.keys(req.headers); <add> const requestHeaders = Object.keys(req.headers); <ide> requestHeaders.forEach(function(header) { <ide> assert.notStrictEqual( <ide> expectedHeaders[req.method].indexOf(header.toLowerCase()), <ide><path>test/parallel/test-http-client-get-url.js <ide> const http = require('http'); <ide> const url = require('url'); <ide> const URL = url.URL; <ide> <del>var server = http.createServer(common.mustCall(function(req, res) { <add>const 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><path>test/parallel/test-http-client-parse-error.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const net = require('net'); <ide> <del>var connects = 0; <del>var parseErrors = 0; <add>let connects = 0; <add>let parseErrors = 0; <ide> <ide> // Create a TCP server <ide> net.createServer(function(c) { <ide> net.createServer(function(c) { <ide> this.close(); <ide> } <ide> }).listen(0, '127.0.0.1', function() { <del> for (var i = 0; i < 2; i++) { <add> for (let i = 0; i < 2; i++) { <ide> http.request({ <ide> host: '127.0.0.1', <ide> port: this.address().port, <ide><path>test/parallel/test-http-client-pipe-end.js <ide> const common = require('../common'); <ide> const http = require('http'); <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> req.resume(); <ide> req.once('end', function() { <ide> res.writeHead(200); <ide> var server = http.createServer(function(req, res) { <ide> common.refreshTmpDir(); <ide> <ide> server.listen(common.PIPE, function() { <del> var req = http.request({ <add> const req = http.request({ <ide> socketPath: common.PIPE, <ide> headers: {'Content-Length': '1'}, <ide> method: 'POST', <ide><path>test/parallel/test-http-client-race-2.js <ide> const url = require('url'); <ide> // condition involving the parsers FreeList used internally by http.Client. <ide> // <ide> <del>var body1_s = '1111111111111111'; <del>var body2_s = '22222'; <del>var body3_s = '3333333333333333333'; <add>const body1_s = '1111111111111111'; <add>const body2_s = '22222'; <add>const body3_s = '3333333333333333333'; <ide> <del>var server = http.createServer(function(req, res) { <del> var pathname = url.parse(req.url).pathname; <add>const server = http.createServer(function(req, res) { <add> const pathname = url.parse(req.url).pathname; <ide> <del> var body; <add> let body; <ide> switch (pathname) { <ide> case '/1': body = body1_s; break; <ide> case '/2': body = body2_s; break; <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> server.listen(0); <ide> <del>var body1 = ''; <del>var body2 = ''; <del>var body3 = ''; <add>let body1 = ''; <add>let body2 = ''; <add>let body3 = ''; <ide> <ide> server.on('listening', function() { <ide> // <ide> // Client #1 is assigned Parser #1 <ide> // <del> var req1 = http.get({ port: this.address().port, path: '/1' }); <add> const req1 = http.get({ port: this.address().port, path: '/1' }); <ide> req1.on('response', function(res1) { <ide> res1.setEncoding('utf8'); <ide> <ide> server.on('listening', function() { <ide> // At this point, the bug would manifest itself and crash because the <ide> // internal state of the parser was no longer valid for use by Client #1 <ide> // <del> var req2 = http.get({ port: server.address().port, path: '/2' }); <add> const req2 = http.get({ port: server.address().port, path: '/2' }); <ide> req2.on('response', function(res2) { <ide> res2.setEncoding('utf8'); <ide> res2.on('data', function(chunk) { body2 += chunk; }); <ide> server.on('listening', function() { <ide> // Just to be really sure we've covered all our bases, execute a <ide> // request using client2. <ide> // <del> var req3 = http.get({ port: server.address().port, path: '/3' }); <add> const req3 = http.get({ port: server.address().port, path: '/3' }); <ide> req3.on('response', function(res3) { <ide> res3.setEncoding('utf8'); <ide> res3.on('data', function(chunk) { body3 += chunk; }); <ide><path>test/parallel/test-http-client-race.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const url = require('url'); <ide> <del>var body1_s = '1111111111111111'; <del>var body2_s = '22222'; <add>const body1_s = '1111111111111111'; <add>const body2_s = '22222'; <ide> <del>var server = http.createServer(function(req, res) { <del> var body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s; <add>const server = http.createServer(function(req, res) { <add> const body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s; <ide> res.writeHead(200, <ide> {'Content-Type': 'text/plain', 'Content-Length': body.length}); <ide> res.end(body); <ide> }); <ide> server.listen(0); <ide> <del>var body1 = ''; <del>var body2 = ''; <add>let body1 = ''; <add>let body2 = ''; <ide> <ide> server.on('listening', function() { <del> var req1 = http.request({ port: this.address().port, path: '/1' }); <add> const req1 = http.request({ port: this.address().port, path: '/1' }); <ide> req1.end(); <ide> req1.on('response', function(res1) { <ide> res1.setEncoding('utf8'); <ide> server.on('listening', function() { <ide> }); <ide> <ide> res1.on('end', function() { <del> var req2 = http.request({ port: server.address().port, path: '/2' }); <add> const req2 = http.request({ port: server.address().port, path: '/2' }); <ide> req2.end(); <ide> req2.on('response', function(res2) { <ide> res2.setEncoding('utf8'); <ide><path>test/parallel/test-http-client-read-in-error.js <ide> function Agent() { <ide> util.inherits(Agent, http.Agent); <ide> <ide> Agent.prototype.createConnection = function() { <del> var self = this; <del> var socket = new net.Socket(); <add> const self = this; <add> const socket = new net.Socket(); <ide> <ide> socket.on('error', function() { <ide> socket.push('HTTP/1.1 200\r\n\r\n'); <ide> Agent.prototype.breakSocket = function breakSocket(socket) { <ide> socket.emit('error', new Error('Intentional error')); <ide> }; <ide> <del>var agent = new Agent(); <add>const agent = new Agent(); <ide> <ide> http.request({ <ide> agent: agent <ide><path>test/parallel/test-http-client-readable.js <ide> util.inherits(FakeAgent, http.Agent); <ide> <ide> FakeAgent.prototype.createConnection = function() { <ide> const s = new Duplex(); <del> var once = false; <add> let once = false; <ide> <ide> s._read = function() { <ide> if (once) <ide> FakeAgent.prototype.createConnection = function() { <ide> return s; <ide> }; <ide> <del>var received = ''; <add>let received = ''; <ide> <ide> const req = http.request({ <ide> agent: new FakeAgent() <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 d; <add>let d; <ide> <ide> common.refreshTmpDir(); <ide> <ide> // first fire up a simple HTTP server <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.writeHead(200); <ide> res.end(); <ide> server.close(); <ide> function test() { <ide> assert.equal('should be caught by domain', err.message); <ide> })); <ide> <del> var req = http.get({ <add> const req = http.get({ <ide> socketPath: common.PIPE, <ide> headers: {'Content-Length': '1'}, <ide> method: 'POST', <ide><path>test/parallel/test-http-client-timeout-agent.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var requests_sent = 0; <del>var requests_done = 0; <del>var options = { <add>let requests_sent = 0; <add>let requests_done = 0; <add>const options = { <ide> method: 'GET', <ide> port: undefined, <ide> host: '127.0.0.1', <ide> }; <ide> <ide> //http.globalAgent.maxSockets = 15; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> const m = /\/(.*)/.exec(req.url); <ide> const reqid = parseInt(m[1], 10); <ide> if (reqid % 2) { <ide> var server = http.createServer(function(req, res) { <ide> <ide> server.listen(0, options.host, function() { <ide> options.port = this.address().port; <del> var req; <add> let req; <ide> <ide> for (requests_sent = 0; requests_sent < 30; requests_sent += 1) { <ide> options.path = '/' + requests_sent; <ide><path>test/parallel/test-http-client-timeout-option.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var options = { <add>const options = { <ide> method: 'GET', <ide> port: undefined, <ide> host: '127.0.0.1', <ide> path: '/', <ide> timeout: 1 <ide> }; <ide> <del>var server = http.createServer(); <add>const server = http.createServer(); <ide> <ide> server.listen(0, options.host, function() { <ide> options.port = this.address().port; <del> var req = http.request(options); <add> const req = http.request(options); <ide> req.on('error', function() { <ide> // this space is intentionally left blank <ide> }); <ide> req.on('close', common.mustCall(() => server.close())); <ide> <del> var timeout_events = 0; <add> let timeout_events = 0; <ide> req.on('timeout', common.mustCall(() => timeout_events += 1)); <ide> setTimeout(function() { <ide> req.destroy(); <ide><path>test/parallel/test-http-client-timeout-with-data.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var nchunks = 0; <add>let nchunks = 0; <ide> <ide> const options = { <ide> method: 'GET', <ide><path>test/parallel/test-http-client-timeout.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var options = { <add>const options = { <ide> method: 'GET', <ide> port: undefined, <ide> host: '127.0.0.1', <ide> path: '/' <ide> }; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> // this space intentionally left blank <ide> }); <ide> <ide> server.listen(0, options.host, function() { <ide> options.port = this.address().port; <del> var req = http.request(options, function(res) { <add> const req = http.request(options, function(res) { <ide> // this space intentionally left blank <ide> }); <ide> req.on('close', function() { <ide> server.listen(0, options.host, function() { <ide> function destroy() { <ide> req.destroy(); <ide> } <del> var s = req.setTimeout(1, destroy); <add> const s = req.setTimeout(1, destroy); <ide> assert.ok(s instanceof http.ClientRequest); <ide> req.on('error', destroy); <ide> req.end(); <ide><path>test/parallel/test-http-client-upload-buf.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var N = 1024; <add>const N = 1024; <ide> <del>var server = http.createServer(common.mustCall(function(req, res) { <add>const server = http.createServer(common.mustCall(function(req, res) { <ide> assert.equal('POST', req.method); <ide> <del> var bytesReceived = 0; <add> let bytesReceived = 0; <ide> <ide> req.on('data', function(chunk) { <ide> bytesReceived += chunk.length; <ide> var server = http.createServer(common.mustCall(function(req, res) { <ide> server.listen(0); <ide> <ide> server.on('listening', common.mustCall(function() { <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port, <ide> method: 'POST', <ide> path: '/' <ide><path>test/parallel/test-http-client-upload.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var server = http.createServer(common.mustCall(function(req, res) { <add>const server = http.createServer(common.mustCall(function(req, res) { <ide> assert.equal('POST', req.method); <ide> req.setEncoding('utf8'); <ide> <del> var sent_body = ''; <add> let sent_body = ''; <ide> <ide> req.on('data', function(chunk) { <ide> console.log('server got: ' + JSON.stringify(chunk)); <ide> var server = http.createServer(common.mustCall(function(req, res) { <ide> server.listen(0); <ide> <ide> server.on('listening', common.mustCall(function() { <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port, <ide> method: 'POST', <ide> path: '/' <ide><path>test/parallel/test-http-conn-reset.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const net = require('net'); <ide> <del>var options = { <add>const options = { <ide> host: '127.0.0.1', <ide> port: undefined <ide> }; <ide> <ide> // start a tcp server that closes incoming connections immediately <del>var server = net.createServer(function(client) { <add>const server = net.createServer(function(client) { <ide> client.destroy(); <ide> server.close(); <ide> }); <ide> server.listen(0, options.host, common.mustCall(onListen)); <ide> // do a GET request, expect it to fail <ide> function onListen() { <ide> options.port = this.address().port; <del> var req = http.request(options, function(res) { <add> const req = http.request(options, function(res) { <ide> assert.ok(false, 'this should never run'); <ide> }); <ide> req.on('error', common.mustCall(function(err) { <ide><path>test/parallel/test-http-connect-req-res.js <ide> server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) { <ide> 'Head' <ide> ); <ide> <del> var data = firstBodyChunk.toString(); <add> let data = firstBodyChunk.toString(); <ide> socket.on('data', function(buf) { <ide> data += buf.toString(); <ide> }); <ide> server.listen(0, common.mustCall(function() { <ide> assert.equal(socket.listeners('connect').length, 0); <ide> assert.equal(socket.listeners('data').length, 0); <ide> <del> var data = firstBodyChunk.toString(); <add> let data = firstBodyChunk.toString(); <ide> <ide> // test that the firstBodyChunk was not parsed as HTTP <ide> assert.equal(data, 'Head'); <ide><path>test/parallel/test-http-content-length.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var expectedHeadersMultipleWrites = { <add>const expectedHeadersMultipleWrites = { <ide> 'connection': 'close', <ide> 'transfer-encoding': 'chunked', <ide> }; <ide> <del>var expectedHeadersEndWithData = { <add>const expectedHeadersEndWithData = { <ide> 'connection': 'close', <ide> 'content-length': String('hello world'.length) <ide> }; <ide> <del>var expectedHeadersEndNoData = { <add>const expectedHeadersEndNoData = { <ide> 'connection': 'close', <ide> 'content-length': '0', <ide> }; <ide> <del>var receivedRequests = 0; <del>var totalRequests = 3; <add>let receivedRequests = 0; <add>const totalRequests = 3; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.removeHeader('Date'); <ide> <ide> switch (req.url.substr(1)) { <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> server.listen(0, function() { <del> var req; <add> let req; <ide> <ide> req = http.request({ <ide> port: this.address().port, <ide><path>test/parallel/test-http-contentLength0.js <ide> const http = require('http'); <ide> // I.E. a space character after the 'Content-Length' throws an `error` event. <ide> <ide> <del>var s = http.createServer(function(req, res) { <add>const s = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Length': '0 '}); <ide> res.end(); <ide> }); <ide> s.listen(0, function() { <ide> <del> var request = http.request({ port: this.address().port }, function(response) { <add> const request = http.request({ port: this.address().port }, (response) => { <ide> console.log('STATUS: ' + response.statusCode); <ide> s.close(); <ide> response.resume(); <ide><path>test/parallel/test-http-date-header.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var testResBody = 'other stuff!\n'; <add>const testResBody = 'other stuff!\n'; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> assert.ok(!('date' in req.headers), <ide> 'Request headers contained a Date.'); <ide> res.writeHead(200, { <ide> server.listen(0); <ide> <ide> <ide> server.addListener('listening', function() { <del> var options = { <add> const options = { <ide> port: this.address().port, <ide> path: '/', <ide> method: 'GET' <ide> }; <del> var req = http.request(options, function(res) { <add> const req = http.request(options, function(res) { <ide> assert.ok('date' in res.headers, <ide> 'Response headers didn\'t contain a Date.'); <ide> res.addListener('end', function() { <ide><path>test/parallel/test-http-default-encoding.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var expected = 'This is a unicode text: سلام'; <del>var result = ''; <add>const expected = 'This is a unicode text: سلام'; <add>let result = ''; <ide> <del>var server = http.Server(function(req, res) { <add>const server = http.Server(function(req, res) { <ide> req.setEncoding('utf8'); <ide> req.on('data', function(chunk) { <ide> result += chunk; <ide><path>test/parallel/test-http-destroyed-socket-write2.js <ide> const assert = require('assert'); <ide> // where the server has ended the socket. <ide> <ide> const http = require('http'); <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> setImmediate(function() { <ide> res.destroy(); <ide> }); <ide> }); <ide> <ide> server.listen(0, function() { <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port, <ide> path: '/', <ide> method: 'POST' <ide><path>test/parallel/test-http-eof-on-connect.js <ide> const http = require('http'); <ide> // It is separate from test-http-malformed-request.js because it is only <ide> // reproduceable on the first packet on the first connection to a server. <ide> <del>var server = http.createServer(function(req, res) {}); <add>const server = http.createServer(function(req, res) {}); <ide> server.listen(0); <ide> <ide> server.on('listening', function() { <ide><path>test/parallel/test-http-exceptions.js <ide> require('../common'); <ide> const http = require('http'); <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> intentionally_not_defined(); // eslint-disable-line no-undef <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.write('Thank you, come again.'); <ide> res.end(); <ide> }); <ide> <ide> server.listen(0, function() { <del> for (var i = 0; i < 4; i += 1) { <add> for (let i = 0; i < 4; i += 1) { <ide> http.get({ port: this.address().port, path: '/busy/' + i }); <ide> } <ide> }); <ide> <del>var exception_count = 0; <add>let exception_count = 0; <ide> <ide> process.on('uncaughtException', function(err) { <ide> console.log('Caught an exception: ' + err); <ide><path>test/parallel/test-http-expect-continue.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var outstanding_reqs = 0; <del>var test_req_body = 'some stuff...\n'; <del>var test_res_body = 'other stuff!\n'; <del>var sent_continue = false; <del>var got_continue = false; <add>let outstanding_reqs = 0; <add>const test_req_body = 'some stuff...\n'; <add>const test_res_body = 'other stuff!\n'; <add>let sent_continue = false; <add>let got_continue = false; <ide> <ide> function handler(req, res) { <ide> assert.equal(sent_continue, true, 'Full response sent before 100 Continue'); <ide> function handler(req, res) { <ide> res.end(test_res_body); <ide> } <ide> <del>var server = http.createServer(handler); <add>const server = http.createServer(handler); <ide> server.on('checkContinue', function(req, res) { <ide> console.error('Server got Expect: 100-continue...'); <ide> res.writeContinue(); <ide> server.listen(0); <ide> <ide> <ide> server.on('listening', function() { <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port, <ide> method: 'POST', <ide> path: '/world', <ide> headers: { 'Expect': '100-continue' } <ide> }); <ide> console.error('Client sending request...'); <ide> outstanding_reqs++; <del> var body = ''; <add> let body = ''; <ide> req.on('continue', function() { <ide> console.error('Client got 100 Continue...'); <ide> got_continue = true; <ide><path>test/parallel/test-http-extra-response.js <ide> const net = require('net'); <ide> // node should ignore it and drop the connection. <ide> // Demos this bug: https://github.com/joyent/node/issues/680 <ide> <del>var body = 'hello world\r\n'; <del>var fullResponse = <add>const body = 'hello world\r\n'; <add>const fullResponse = <ide> 'HTTP/1.1 500 Internal Server Error\r\n' + <ide> 'Content-Length: ' + body.length + '\r\n' + <ide> 'Content-Type: text/plain\r\n' + <ide> var fullResponse = <ide> '\r\n' + <ide> body; <ide> <del>var server = net.createServer(function(socket) { <del> var postBody = ''; <add>const server = net.createServer(function(socket) { <add> let postBody = ''; <ide> <ide> socket.setEncoding('utf8'); <ide> <ide> var server = net.createServer(function(socket) { <ide> <ide> server.listen(0, common.mustCall(function() { <ide> http.get({ port: this.address().port }, common.mustCall(function(res) { <del> var buffer = ''; <add> let buffer = ''; <ide> console.log('Got res code: ' + res.statusCode); <ide> <ide> res.setEncoding('utf8'); <ide><path>test/parallel/test-http-flush-response-headers.js <ide> server.on('request', function(req, res) { <ide> res.flushHeaders(); // Should be idempotent. <ide> }); <ide> server.listen(0, common.localhostIPv4, function() { <del> var req = http.request({ <add> const req = http.request({ <ide> method: 'GET', <ide> host: common.localhostIPv4, <ide> port: this.address().port, <ide><path>test/parallel/test-http-flush.js <ide> http.createServer(function(req, res) { <ide> res.end('ok'); <ide> this.close(); <ide> }).listen(0, '127.0.0.1', function() { <del> var req = http.request({ <add> const req = http.request({ <ide> method: 'POST', <ide> host: '127.0.0.1', <ide> port: this.address().port, <ide><path>test/parallel/test-http-full-response.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const exec = require('child_process').exec; <ide> <del>var bodyLength = 12345; <add>const bodyLength = 12345; <ide> <del>var body = 'c'.repeat(bodyLength); <add>const body = 'c'.repeat(bodyLength); <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.writeHead(200, { <ide> 'Content-Length': bodyLength, <ide> 'Content-Type': 'text/plain' <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> function runAb(opts, callback) { <del> var command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; <add> const command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; <ide> exec(command, function(err, stdout, stderr) { <ide> if (err) { <ide> if (/ab|apr/mi.test(stderr)) { <ide> function runAb(opts, callback) { <ide> return; <ide> } <ide> <del> var m = /Document Length:\s*(\d+) bytes/mi.exec(stdout); <del> var documentLength = parseInt(m[1]); <add> let m = /Document Length:\s*(\d+) bytes/mi.exec(stdout); <add> const documentLength = parseInt(m[1]); <ide> <ide> m = /Complete requests:\s*(\d+)/mi.exec(stdout); <del> var completeRequests = parseInt(m[1]); <add> const completeRequests = parseInt(m[1]); <ide> <ide> m = /HTML transferred:\s*(\d+) bytes/mi.exec(stdout); <del> var htmlTransfered = parseInt(m[1]); <add> const htmlTransfered = parseInt(m[1]); <ide> <ide> assert.equal(bodyLength, documentLength); <ide> assert.equal(completeRequests * documentLength, htmlTransfered); <ide><path>test/parallel/test-http-get-pipeline-problem.js <ide> http.globalAgent.maxSockets = 1; <ide> <ide> common.refreshTmpDir(); <ide> <del>var image = fs.readFileSync(common.fixturesDir + '/person.jpg'); <add>const image = fs.readFileSync(common.fixturesDir + '/person.jpg'); <ide> <ide> console.log('image.length = ' + image.length); <ide> <del>var total = 10; <del>var requests = 0, responses = 0; <add>const total = 10; <add>let requests = 0, responses = 0; <ide> <del>var server = http.Server(function(req, res) { <add>const server = http.Server(function(req, res) { <ide> if (++requests === total) { <ide> server.close(); <ide> } <ide> var server = http.Server(function(req, res) { <ide> <ide> <ide> server.listen(0, function() { <del> for (var i = 0; i < total; i++) { <add> for (let i = 0; i < total; i++) { <ide> (function() { <del> var x = i; <add> const x = i; <ide> <del> var opts = { <add> const opts = { <ide> port: server.address().port, <ide> headers: { connection: 'close' } <ide> }; <ide> <ide> http.get(opts, function(res) { <ide> console.error('recv ' + x); <del> var s = fs.createWriteStream(common.tmpDir + '/' + x + '.jpg'); <add> const s = fs.createWriteStream(common.tmpDir + '/' + x + '.jpg'); <ide> res.pipe(s); <ide> <ide> s.on('finish', function() { <ide> server.listen(0, function() { <ide> }); <ide> <ide> <del>var checkedFiles = false; <add>let checkedFiles = false; <ide> function checkFiles() { <ide> // Should see 1.jpg, 2.jpg, ..., 100.jpg in tmpDir <del> var files = fs.readdirSync(common.tmpDir); <add> const files = fs.readdirSync(common.tmpDir); <ide> assert(total <= files.length); <ide> <del> for (var i = 0; i < total; i++) { <del> var fn = i + '.jpg'; <add> for (let i = 0; i < total; i++) { <add> const fn = i + '.jpg'; <ide> assert.ok(files.indexOf(fn) >= 0, "couldn't find '" + fn + "'"); <del> var stat = fs.statSync(common.tmpDir + '/' + fn); <add> const stat = fs.statSync(common.tmpDir + '/' + fn); <ide> assert.equal(image.length, stat.size, <ide> "size doesn't match on '" + fn + <ide> "'. Got " + stat.size + ' bytes'); <ide><path>test/parallel/test-http-head-request.js <ide> const common = require('../common'); <ide> const http = require('http'); <ide> <del>var body = 'hello world\n'; <add>const body = 'hello world\n'; <ide> <ide> function test(headers) { <del> var server = http.createServer(function(req, res) { <add> const server = http.createServer(function(req, res) { <ide> console.error('req: %s headers: %j', req.method, headers); <ide> res.writeHead(200, headers); <ide> res.end(); <ide> server.close(); <ide> }); <ide> <ide> server.listen(0, common.mustCall(function() { <del> var request = http.request({ <add> const request = http.request({ <ide> port: this.address().port, <ide> method: 'HEAD', <ide> path: '/' <ide><path>test/parallel/test-http-head-response-has-no-body-end.js <ide> const http = require('http'); <ide> // responds to a HEAD request with data to res.end, <ide> // it does not send any body. <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.writeHead(200); <ide> res.end('FAIL'); // broken: sends FAIL from hot path. <ide> }); <ide> server.listen(0); <ide> <ide> server.on('listening', common.mustCall(function() { <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port, <ide> method: 'HEAD', <ide> path: '/' <ide><path>test/parallel/test-http-head-response-has-no-body.js <ide> const http = require('http'); <ide> // responds to a HEAD request, it does not send any body. <ide> // In this case it was sending '0\r\n\r\n' <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.writeHead(200); // broken: defaults to TE chunked <ide> res.end(); <ide> }); <ide> server.listen(0); <ide> <ide> server.on('listening', common.mustCall(function() { <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port, <ide> method: 'HEAD', <ide> path: '/' <ide><path>test/parallel/test-http-header-read.js <ide> const http = require('http'); <ide> // Verify that ServerResponse.getHeader() works correctly even after <ide> // the response header has been sent. Issue 752 on github. <ide> <del>var s = http.createServer(function(req, res) { <del> var contentType = 'Content-Type'; <del> var plain = 'text/plain'; <add>const s = http.createServer(function(req, res) { <add> const contentType = 'Content-Type'; <add> const plain = 'text/plain'; <ide> res.setHeader(contentType, plain); <ide> assert.ok(!res.headersSent); <ide> res.writeHead(200); <ide><path>test/parallel/test-http-hex-write.js <ide> const assert = require('assert'); <ide> <ide> const http = require('http'); <ide> <del>var expect = 'hex\nutf8\n'; <add>const expect = 'hex\nutf8\n'; <ide> <ide> http.createServer(function(q, s) { <ide> s.setHeader('content-length', expect.length); <ide> http.createServer(function(q, s) { <ide> }).listen(0, common.mustCall(function() { <ide> http.request({ port: this.address().port }) <ide> .on('response', common.mustCall(function(res) { <del> var data = ''; <add> let data = ''; <ide> <ide> res.setEncoding('ascii'); <ide> res.on('data', function(c) { <ide><path>test/parallel/test-http-host-header-ipv6-fail.js <ide> const http = require('http'); <ide> const hostname = '::1'; <ide> <ide> function httpreq() { <del> var req = http.request({ <add> const req = http.request({ <ide> host: hostname, <ide> port: server.address().port, <ide> path: '/', <ide><path>test/parallel/test-http-host-headers.js <ide> testHttp(); <ide> <ide> function testHttp() { <ide> <del> var counter = 0; <add> let counter = 0; <ide> <ide> function cb(res) { <ide> counter--; <ide><path>test/parallel/test-http-invalidheaderfield.js <ide> const EventEmitter = require('events'); <ide> const http = require('http'); <ide> <ide> const ee = new EventEmitter(); <del>var count = 3; <add>let count = 3; <ide> <ide> const server = http.createServer(function(req, res) { <ide> assert.doesNotThrow(function() { <ide> server.listen(0, function() { <ide> <ide> assert.throws( <ide> function() { <del> var options = { <add> const options = { <ide> port: server.address().port, <ide> headers: {'testing 123': 123} <ide> }; <ide> server.listen(0, function() { <ide> <ide> assert.doesNotThrow( <ide> function() { <del> var options = { <add> const options = { <ide> port: server.address().port, <ide> headers: {'testing_123': 123} <ide> }; <ide><path>test/parallel/test-http-keep-alive-close-on-header.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var body = 'hello world\n'; <del>var headers = {'connection': 'keep-alive'}; <add>const body = 'hello world\n'; <add>const headers = {'connection': 'keep-alive'}; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Length': body.length, 'Connection': 'close'}); <ide> res.write(body); <ide> res.end(); <ide> }); <ide> <del>var connectCount = 0; <add>let connectCount = 0; <ide> <ide> <ide> server.listen(0, function() { <del> var agent = new http.Agent({ maxSockets: 1 }); <del> var name = agent.getName({ port: this.address().port }); <del> var request = http.request({ <add> const agent = new http.Agent({ maxSockets: 1 }); <add> const name = agent.getName({ port: this.address().port }); <add> let request = http.request({ <ide> method: 'GET', <ide> path: '/', <ide> headers: headers, <ide><path>test/parallel/test-http-keepalive-client.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <ide> <del>var serverSocket = null; <del>var server = http.createServer(function(req, res) { <add>let serverSocket = null; <add>const server = http.createServer(function(req, res) { <ide> // They should all come in on the same server socket. <ide> if (serverSocket) { <ide> assert.equal(req.socket, serverSocket); <ide> server.listen(0, function() { <ide> makeRequest(expectRequests); <ide> }); <ide> <del>var agent = http.Agent({ keepAlive: true }); <add>const agent = http.Agent({ keepAlive: true }); <ide> <ide> <del>var clientSocket = null; <del>var expectRequests = 10; <del>var actualRequests = 0; <add>let clientSocket = null; <add>const expectRequests = 10; <add>let actualRequests = 0; <ide> <ide> <ide> function makeRequest(n) { <ide> function makeRequest(n) { <ide> return; <ide> } <ide> <del> var req = http.request({ <add> const req = http.request({ <ide> port: server.address().port, <ide> agent: agent, <ide> path: '/' + n <ide> function makeRequest(n) { <ide> }); <ide> <ide> req.on('response', function(res) { <del> var data = ''; <add> let data = ''; <ide> res.setEncoding('utf8'); <ide> res.on('data', function(c) { <ide> data += c; <ide><path>test/parallel/test-http-keepalive-maxsockets.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <ide> <del>var serverSockets = []; <del>var server = http.createServer(function(req, res) { <add>const serverSockets = []; <add>const server = http.createServer(function(req, res) { <ide> if (serverSockets.indexOf(req.socket) === -1) { <ide> serverSockets.push(req.socket); <ide> } <ide> res.end(req.url); <ide> }); <ide> server.listen(0, function() { <del> var agent = http.Agent({ <add> const agent = http.Agent({ <ide> keepAlive: true, <ide> maxSockets: 5, <ide> maxFreeSockets: 2 <ide> }); <ide> <del> var closed = false; <add> let closed = false; <ide> makeReqs(10, function(er) { <ide> assert.ifError(er); <ide> assert.equal(count(agent.freeSockets), 2); <ide> server.listen(0, function() { <ide> // make 10 requests in parallel, <ide> // then 10 more when they all finish. <ide> function makeReqs(n, cb) { <del> for (var i = 0; i < n; i++) <add> for (let i = 0; i < n; i++) <ide> makeReq(i, then); <ide> <ide> function then(er) { <ide> server.listen(0, function() { <ide> path: '/' + i, <ide> agent: agent <ide> }, function(res) { <del> var data = ''; <add> let data = ''; <ide> res.setEncoding('ascii'); <ide> res.on('data', function(c) { <ide> data += c; <ide><path>test/parallel/test-http-keepalive-request.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <ide> <del>var serverSocket = null; <del>var server = http.createServer(function(req, res) { <add>let serverSocket = null; <add>const server = http.createServer(function(req, res) { <ide> // They should all come in on the same server socket. <ide> if (serverSocket) { <ide> assert.equal(req.socket, serverSocket); <ide> server.listen(0, function() { <ide> makeRequest(expectRequests); <ide> }); <ide> <del>var agent = http.Agent({ keepAlive: true }); <add>const agent = http.Agent({ keepAlive: true }); <ide> <ide> <del>var clientSocket = null; <del>var expectRequests = 10; <del>var actualRequests = 0; <add>let clientSocket = null; <add>const expectRequests = 10; <add>let actualRequests = 0; <ide> <ide> <ide> function makeRequest(n) { <ide> function makeRequest(n) { <ide> return; <ide> } <ide> <del> var req = http.request({ <add> const req = http.request({ <ide> port: server.address().port, <ide> path: '/' + n, <ide> agent: agent <ide> function makeRequest(n) { <ide> }); <ide> <ide> req.on('response', function(res) { <del> var data = ''; <add> let data = ''; <ide> res.setEncoding('utf8'); <ide> res.on('data', function(c) { <ide> data += c; <ide><path>test/parallel/test-http-localaddress-bind-error.js <ide> const common = require('../common'); <ide> const http = require('http'); <ide> <del>var invalidLocalAddress = '1.2.3.4'; <add>const invalidLocalAddress = '1.2.3.4'; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> console.log('Connect from: ' + req.connection.remoteAddress); <ide> <ide> req.on('end', function() { <ide><path>test/parallel/test-http-localaddress.js <ide> if (!common.hasMultiLocalhost()) { <ide> return; <ide> } <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> console.log('Connect from: ' + req.connection.remoteAddress); <ide> assert.equal('127.0.0.2', req.connection.remoteAddress); <ide> <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> server.listen(0, '127.0.0.1', function() { <del> var options = { host: 'localhost', <del> port: this.address().port, <del> path: '/', <del> method: 'GET', <del> localAddress: '127.0.0.2' }; <add> const options = { host: 'localhost', <add> port: this.address().port, <add> path: '/', <add> method: 'GET', <add> localAddress: '127.0.0.2' }; <ide> <del> var req = http.request(options, function(res) { <add> const req = http.request(options, function(res) { <ide> res.on('end', function() { <ide> server.close(); <ide> process.exit(); <ide><path>test/parallel/test-http-malformed-request.js <ide> const url = require('url'); <ide> // Make sure no exceptions are thrown when receiving malformed HTTP <ide> // requests. <ide> <del>var nrequests_completed = 0; <del>var nrequests_expected = 1; <add>let nrequests_completed = 0; <add>const nrequests_expected = 1; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> console.log('req: ' + JSON.stringify(url.parse(req.url))); <ide> <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> var server = http.createServer(function(req, res) { <ide> server.listen(0); <ide> <ide> server.on('listening', function() { <del> var c = net.createConnection(this.address().port); <add> const c = net.createConnection(this.address().port); <ide> c.on('connect', function() { <ide> c.write('GET /hello?foo=%99bar HTTP/1.1\r\n\r\n'); <ide> c.end(); <ide><path>test/parallel/test-http-many-ended-pipelines.js <ide> require('../common'); <ide> <ide> // no warnings should happen! <del>var trace = console.trace; <add>const trace = console.trace; <ide> console.trace = function() { <ide> trace.apply(console, arguments); <ide> throw new Error('no tracing should happen here'); <ide> console.trace = function() { <ide> const http = require('http'); <ide> const net = require('net'); <ide> <del>var numRequests = 20; <del>var first = false; <add>const numRequests = 20; <add>let first = false; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> if (!first) { <ide> first = true; <ide> req.socket.on('close', function() { <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> server.listen(0, function() { <del> var client = net.connect({ port: this.address().port, allowHalfOpen: true }); <del> for (var i = 0; i < numRequests; i++) { <add> const client = net.connect({ port: this.address().port, <add> allowHalfOpen: true }); <add> for (let i = 0; i < numRequests; i++) { <ide> client.write('GET / HTTP/1.1\r\n' + <ide> 'Host: some.host.name\r\n' + <ide> '\r\n\r\n'); <ide><path>test/parallel/test-http-max-headers-count.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var requests = 0; <del>var responses = 0; <add>let requests = 0; <add>let responses = 0; <ide> <del>var headers = {}; <del>var N = 2000; <del>for (var i = 0; i < N; ++i) { <add>const headers = {}; <add>const N = 2000; <add>for (let i = 0; i < N; ++i) { <ide> headers['key' + i] = i; <ide> } <ide> <del>var maxAndExpected = [ // for server <add>const maxAndExpected = [ // for server <ide> [50, 50], <ide> [1500, 1500], <ide> [0, N + 2] // Host and Connection <ide> ]; <del>var max = maxAndExpected[requests][0]; <del>var expected = maxAndExpected[requests][1]; <add>let max = maxAndExpected[requests][0]; <add>let expected = maxAndExpected[requests][1]; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> assert.equal(Object.keys(req.headers).length, expected); <ide> if (++requests < maxAndExpected.length) { <ide> max = maxAndExpected[requests][0]; <ide> var server = http.createServer(function(req, res) { <ide> server.maxHeadersCount = max; <ide> <ide> server.listen(0, function() { <del> var maxAndExpected = [ // for client <add> const maxAndExpected = [ // for client <ide> [20, 20], <ide> [1200, 1200], <ide> [0, N + 3] // Connection, Date and Transfer-Encoding <ide> ]; <ide> doRequest(); <ide> <ide> function doRequest() { <del> var max = maxAndExpected[responses][0]; <del> var expected = maxAndExpected[responses][1]; <del> var req = http.request({ <add> const max = maxAndExpected[responses][0]; <add> const expected = maxAndExpected[responses][1]; <add> const req = http.request({ <ide> port: server.address().port, <ide> headers: headers <ide> }, function(res) { <ide><path>test/parallel/test-http-multi-line-headers.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const net = require('net'); <ide> <del>var server = net.createServer(function(conn) { <del> var body = 'Yet another node.js server.'; <add>const server = net.createServer(function(conn) { <add> const body = 'Yet another node.js server.'; <ide> <del> var response = <add> const response = <ide> 'HTTP/1.1 200 OK\r\n' + <ide> 'Connection: close\r\n' + <ide> 'Content-Length: ' + body.length + '\r\n' + <ide><path>test/parallel/test-http-no-content-length.js <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> const http = require('http'); <ide> <del>var server = net.createServer(function(socket) { <add>const server = net.createServer(function(socket) { <ide> // Neither Content-Length nor Connection <ide> socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); <ide> }).listen(0, common.mustCall(function() { <ide> http.get({port: this.address().port}, common.mustCall(function(res) { <del> var body = ''; <add> let body = ''; <ide> <ide> res.setEncoding('utf8'); <ide> res.on('data', function(chunk) { <ide><path>test/parallel/test-http-outgoing-finish.js <ide> http.createServer(function(req, res) { <ide> }); <ide> this.close(); <ide> }).listen(0, function() { <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port, <ide> method: 'PUT' <ide> }); <ide> http.createServer(function(req, res) { <ide> }); <ide> }); <ide> <del>var buf = Buffer.alloc(1024 * 16, 'x'); <add>const buf = Buffer.alloc(1024 * 16, 'x'); <ide> function write(out) { <del> var name = out.constructor.name; <del> var finishEvent = false; <del> var endCb = false; <add> const name = out.constructor.name; <add> let finishEvent = false; <add> let endCb = false; <ide> <ide> // first, write until it gets some backpressure <ide> while (out.write(buf)) {} <ide><path>test/parallel/test-http-parser-bad-ref.js <ide> <ide> require('../common'); <ide> const assert = require('assert'); <del>var HTTPParser = process.binding('http_parser').HTTPParser; <add>const HTTPParser = process.binding('http_parser').HTTPParser; <ide> <del>var kOnHeaders = HTTPParser.kOnHeaders | 0; <del>var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; <del>var kOnBody = HTTPParser.kOnBody | 0; <del>var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; <add>const kOnHeaders = HTTPParser.kOnHeaders | 0; <add>const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; <add>const kOnBody = HTTPParser.kOnBody | 0; <add>const kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; <ide> <del>var headersComplete = 0; <del>var messagesComplete = 0; <add>let headersComplete = 0; <add>let messagesComplete = 0; <ide> <ide> function flushPool() { <ide> Buffer.allocUnsafe(Buffer.poolSize - 1); <ide> function flushPool() { <ide> function demoBug(part1, part2) { <ide> flushPool(); <ide> <del> var parser = new HTTPParser('REQUEST'); <add> const parser = new HTTPParser('REQUEST'); <ide> <ide> parser.headers = []; <ide> parser.url = ''; <ide> function demoBug(part1, part2) { <ide> // We use a function to eliminate references to the Buffer b <ide> // We want b to be GCed. The parser will hold a bad reference to it. <ide> (function() { <del> var b = Buffer.from(part1); <add> const b = Buffer.from(part1); <ide> flushPool(); <ide> <ide> console.log('parse the first part of the message'); <ide> function demoBug(part1, part2) { <ide> flushPool(); <ide> <ide> (function() { <del> var b = Buffer.from(part2); <add> const b = Buffer.from(part2); <ide> <ide> console.log('parse the second part of the message'); <ide> parser.execute(b, 0, b.length); <ide><path>test/parallel/test-http-parser-free.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <del>var N = 100; <del>var responses = 0; <add>const N = 100; <add>let responses = 0; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> res.end('Hello'); <ide> }); <ide> <ide> server.listen(0, function() { <ide> http.globalAgent.maxSockets = 1; <del> var parser; <del> for (var i = 0; i < N; ++i) { <add> let parser; <add> for (let i = 0; i < N; ++i) { <ide> (function makeRequest(i) { <del> var req = http.get({port: server.address().port}, function(res) { <add> const req = http.get({port: server.address().port}, function(res) { <ide> if (!parser) { <ide> parser = req.parser; <ide> } else { <ide><path>test/parallel/test-http-parser.js <ide> const binding = process.binding('http_parser'); <ide> const methods = binding.methods; <ide> const HTTPParser = binding.HTTPParser; <ide> <del>var CRLF = '\r\n'; <del>var REQUEST = HTTPParser.REQUEST; <del>var RESPONSE = HTTPParser.RESPONSE; <add>const CRLF = '\r\n'; <add>const REQUEST = HTTPParser.REQUEST; <add>const RESPONSE = HTTPParser.RESPONSE; <ide> <del>var kOnHeaders = HTTPParser.kOnHeaders | 0; <del>var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; <del>var kOnBody = HTTPParser.kOnBody | 0; <del>var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; <add>const kOnHeaders = HTTPParser.kOnHeaders | 0; <add>const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; <add>const kOnBody = HTTPParser.kOnBody | 0; <add>const kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; <ide> <ide> // The purpose of this test is not to check HTTP compliance but to test the <ide> // binding. Tests for pathological http messages should be submitted <ide> var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; <ide> <ide> <ide> function newParser(type) { <del> var parser = new HTTPParser(type); <add> const parser = new HTTPParser(type); <ide> <ide> parser.headers = []; <ide> parser.url = ''; <ide> function newParser(type) { <ide> <ide> <ide> function mustCall(f, times) { <del> var actual = 0; <add> let actual = 0; <ide> <ide> process.setMaxListeners(256); <ide> process.on('exit', function() { <ide> function mustCall(f, times) { <ide> <ide> function expectBody(expected) { <ide> return mustCall(function(buf, start, len) { <del> var body = '' + buf.slice(start, start + len); <add> const body = '' + buf.slice(start, start + len); <ide> assert.equal(body, expected); <ide> }); <ide> } <ide> function expectBody(expected) { <ide> assert.strictEqual(expected_body, ''); <ide> } <ide> <del> for (var i = 1; i < request.length - 1; ++i) { <del> var a = request.slice(0, i); <add> for (let i = 1; i < request.length - 1; ++i) { <add> const a = request.slice(0, i); <ide> console.error('request.slice(0, ' + i + ') = ', <ide> JSON.stringify(a.toString())); <del> var b = request.slice(i); <add> const b = request.slice(i); <ide> console.error('request.slice(' + i + ') = ', <ide> JSON.stringify(b.toString())); <ide> test(a, b); <ide> function expectBody(expected) { <ide> // Test parser 'this' safety <ide> // https://github.com/joyent/node/issues/6690 <ide> assert.throws(function() { <del> var request = Buffer.from( <add> const request = Buffer.from( <ide> 'GET /hello HTTP/1.1' + CRLF + <ide> CRLF); <ide> <del> var parser = newParser(REQUEST); <del> var notparser = { execute: parser.execute }; <add> const parser = newParser(REQUEST); <add> const notparser = { execute: parser.execute }; <ide> notparser.execute(request, 0, request.length); <ide> }, TypeError); <ide><path>test/parallel/test-http-pause.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var expectedServer = 'Request Body from Client'; <del>var resultServer = ''; <del>var expectedClient = 'Response Body from Server'; <del>var resultClient = ''; <add>const expectedServer = 'Request Body from Client'; <add>let resultServer = ''; <add>const expectedClient = 'Response Body from Server'; <add>let resultClient = ''; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> console.error('pause server request'); <ide> req.pause(); <ide> setTimeout(function() { <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> server.listen(0, function() { <del> var req = http.request({ <add> const req = http.request({ <ide> port: this.address().port, <ide> path: '/', <ide> method: 'POST' <ide><path>test/parallel/test-http-pipe-fs.js <ide> const path = require('path'); <ide> <ide> common.refreshTmpDir(); <ide> <del>var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); <add>const file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); <ide> <del>var server = http.createServer(common.mustCall(function(req, res) { <del> var stream = fs.createWriteStream(file); <add>const server = http.createServer(common.mustCall(function(req, res) { <add> const stream = fs.createWriteStream(file); <ide> req.pipe(stream); <ide> stream.on('close', function() { <ide> res.writeHead(200); <ide> var server = http.createServer(common.mustCall(function(req, res) { <ide> }, 2)).listen(0, function() { <ide> http.globalAgent.maxSockets = 1; <ide> <del> for (var i = 0; i < 2; ++i) { <add> for (let i = 0; i < 2; ++i) { <ide> (function(i) { <del> var req = http.request({ <add> const req = http.request({ <ide> port: server.address().port, <ide> method: 'POST', <ide> headers: { <ide><path>test/parallel/test-http-pipeline-flood.js <ide> switch (process.argv[2]) { <ide> function parent() { <ide> const http = require('http'); <ide> const bigResponse = Buffer.alloc(10240, 'x'); <del> var backloggedReqs = 0; <add> let backloggedReqs = 0; <ide> <ide> const server = http.createServer(function(req, res) { <ide> res.setHeader('content-length', bigResponse.length); <ide> function child() { <ide> const port = +process.argv[3]; <ide> const conn = net.connect({ port: port }); <ide> <del> var req = `GET / HTTP/1.1\r\nHost: localhost:${port}\r\nAccept: */*\r\n\r\n`; <add> let req = `GET / HTTP/1.1\r\nHost: localhost:${port}\r\nAccept: */*\r\n\r\n`; <ide> <ide> req = new Array(10241).join(req); <ide> <ide><path>test/parallel/test-http-pipeline-regr-2639.js <ide> const net = require('net'); <ide> <ide> const COUNT = 10; <ide> <del>var received = 0; <add>let received = 0; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> // Close the server, we have only one TCP connection anyway <ide> if (received++ === 0) <ide> server.close(); <ide> var server = http.createServer(function(req, res) { <ide> }).listen(0, function() { <ide> const s = net.connect(this.address().port); <ide> <del> var big = 'GET / HTTP/1.0\r\n\r\n'.repeat(COUNT); <add> const big = 'GET / HTTP/1.0\r\n\r\n'.repeat(COUNT); <ide> <ide> s.write(big); <ide> s.resume(); <ide><path>test/parallel/test-http-pipeline-regr-3332.js <ide> const big = Buffer.alloc(16 * 1024, 'A'); <ide> <ide> const COUNT = 1e4; <ide> <del>var received = 0; <add>let received = 0; <ide> <del>var client; <add>let client; <ide> const server = http.createServer(function(req, res) { <ide> res.end(big, function() { <ide> if (++received === COUNT) { <ide> const server = http.createServer(function(req, res) { <ide> } <ide> }); <ide> }).listen(0, function() { <del> var req = new Array(COUNT + 1).join('GET / HTTP/1.1\r\n\r\n'); <add> const req = new Array(COUNT + 1).join('GET / HTTP/1.1\r\n\r\n'); <ide> client = net.connect(this.address().port, function() { <ide> client.write(req); <ide> }); <ide><path>test/parallel/test-http-pipeline-regr-3508.js <ide> require('../common'); <ide> const http = require('http'); <ide> const net = require('net'); <ide> <del>var once = false; <del>var first = null; <del>var second = null; <add>let once = false; <add>let first = null; <add>let second = null; <ide> <ide> const chunk = Buffer.alloc(1024, 'X'); <ide> <del>var size = 0; <add>let size = 0; <ide> <del>var more; <del>var done; <add>let more; <add>let done; <ide> <del>var server = http.createServer(function(req, res) { <add>const server = http.createServer(function(req, res) { <ide> if (!once) <ide> server.close(); <ide> once = true; <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> first.end('hello'); <ide> }).listen(0, function() { <del> var s = net.connect(this.address().port); <add> const s = net.connect(this.address().port); <ide> more = function() { <ide> s.write('GET / HTTP/1.1\r\n\r\n'); <ide> }; <ide><path>test/parallel/test-http-proxy.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const url = require('url'); <ide> <del>var cookies = [ <add>const cookies = [ <ide> 'session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT', <ide> 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' <ide> ]; <ide> <del>var headers = {'content-type': 'text/plain', <del> 'set-cookie': cookies, <del> 'hello': 'world' }; <add>const headers = {'content-type': 'text/plain', <add> 'set-cookie': cookies, <add> 'hello': 'world' }; <ide> <del>var backend = http.createServer(function(req, res) { <add>const backend = http.createServer(function(req, res) { <ide> console.error('backend request'); <ide> res.writeHead(200, headers); <ide> res.write('hello world\n'); <ide> res.end(); <ide> }); <ide> <del>var proxy = http.createServer(function(req, res) { <add>const proxy = http.createServer(function(req, res) { <ide> console.error('proxy req headers: ' + JSON.stringify(req.headers)); <ide> http.get({ <ide> port: backend.address().port, <ide> var proxy = http.createServer(function(req, res) { <ide> }); <ide> }); <ide> <del>var body = ''; <add>let body = ''; <ide> <del>var nlistening = 0; <add>let nlistening = 0; <ide> function startReq() { <ide> nlistening++; <ide> if (nlistening < 2) return; <ide><path>test/parallel/test-http-raw-headers.js <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <ide> http.createServer(function(req, res) { <del> var expectRawHeaders = [ <add> const expectRawHeaders = [ <ide> 'Host', <ide> `localhost:${this.address().port}`, <ide> 'transfer-ENCODING', <ide> http.createServer(function(req, res) { <ide> 'Connection', <ide> 'close' <ide> ]; <del> var expectHeaders = { <add> const expectHeaders = { <ide> host: `localhost:${this.address().port}`, <ide> 'transfer-encoding': 'CHUNKED', <ide> 'x-bar': 'yoyoyo', <ide> connection: 'close' <ide> }; <del> var expectRawTrailers = [ <add> const expectRawTrailers = [ <ide> 'x-bAr', <ide> 'yOyOyOy', <ide> 'x-baR', <ide> http.createServer(function(req, res) { <ide> 'X-baR', <ide> 'OyOyOyO' <ide> ]; <del> var expectTrailers = { 'x-bar': 'yOyOyOy, OyOyOyO, yOyOyOy, OyOyOyO' }; <add> const expectTrailers = { 'x-bar': 'yOyOyOy, OyOyOyO, yOyOyOy, OyOyOyO' }; <ide> <ide> this.close(); <ide> <ide> http.createServer(function(req, res) { <ide> ]); <ide> res.end('x f o o'); <ide> }).listen(0, function() { <del> var req = http.request({ port: this.address().port, path: '/' }); <add> const req = http.request({ port: this.address().port, path: '/' }); <ide> req.addTrailers([ <ide> ['x-bAr', 'yOyOyOy'], <ide> ['x-baR', 'OyOyOyO'], <ide> http.createServer(function(req, res) { <ide> req.setHeader('x-BaR', 'yoyoyo'); <ide> req.end('y b a r'); <ide> req.on('response', function(res) { <del> var expectRawHeaders = [ <add> const expectRawHeaders = [ <ide> 'Trailer', <ide> 'x-foo', <ide> 'Date', <ide> http.createServer(function(req, res) { <ide> 'Transfer-Encoding', <ide> 'chunked' <ide> ]; <del> var expectHeaders = { <add> const expectHeaders = { <ide> trailer: 'x-foo', <ide> date: null, <ide> connection: 'close', <ide> http.createServer(function(req, res) { <ide> assert.deepStrictEqual(res.rawHeaders, expectRawHeaders); <ide> assert.deepStrictEqual(res.headers, expectHeaders); <ide> res.on('end', function() { <del> var expectRawTrailers = [ <add> const expectRawTrailers = [ <ide> 'x-fOo', <ide> 'xOxOxOx', <ide> 'x-foO', <ide> http.createServer(function(req, res) { <ide> 'X-foO', <ide> 'OxOxOxO' <ide> ]; <del> var expectTrailers = { 'x-foo': 'xOxOxOx, OxOxOxO, xOxOxOx, OxOxOxO' }; <add> const expectTrailers = { 'x-foo': 'xOxOxOx, OxOxOxO, xOxOxOx, OxOxOxO' }; <ide> <ide> assert.deepStrictEqual(res.rawTrailers, expectRawTrailers); <ide> assert.deepStrictEqual(res.trailers, expectTrailers); <ide><path>test/parallel/test-http-remove-header-stays-removed.js <ide> const assert = require('assert'); <ide> <ide> const http = require('http'); <ide> <del>var server = http.createServer(function(request, response) { <add>const server = http.createServer(function(request, response) { <ide> // removed headers should stay removed, even if node automatically adds them <ide> // to the output: <ide> response.removeHeader('connection'); <ide> var server = http.createServer(function(request, response) { <ide> this.close(); <ide> }); <ide> <del>var response = ''; <add>let response = ''; <ide> <ide> process.on('exit', function() { <ide> assert.equal('beep boop\n', response); <ide><path>test/parallel/test-http-request-dont-override-options.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var requests = 0; <add>let requests = 0; <ide> <ide> http.createServer(function(req, res) { <ide> res.writeHead(200); <ide> res.end('ok'); <ide> <ide> requests++; <ide> }).listen(0, function() { <del> var agent = new http.Agent(); <add> const agent = new http.Agent(); <ide> agent.defaultPort = this.address().port; <ide> <ide> // options marked as explicitly undefined for readability <ide> // in this test, they should STAY undefined as options should not <ide> // be mutable / modified <del> var options = { <add> const options = { <ide> host: undefined, <ide> hostname: common.localhostIPv4, <ide> port: undefined, <ide><path>test/parallel/test-http-request-end-twice.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> <del>var server = http.Server(function(req, res) { <add>const server = http.Server(function(req, res) { <ide> res.writeHead(200, {'Content-Type': 'text/plain'}); <ide> res.end('hello world\n'); <ide> }); <ide> server.listen(0, function() { <del> var req = http.get({port: this.address().port}, function(res) { <add> const req = http.get({port: this.address().port}, function(res) { <ide> res.on('end', function() { <ide> assert.ok(!req.end()); <ide> server.close();
300
Ruby
Ruby
ignore another exception
1e96c6fec4b449f1357744404d0cc62125db6888
<ide><path>Library/Homebrew/formula_versions.rb <ide> class FormulaVersions <ide> IGNORED_EXCEPTIONS = [ <ide> ArgumentError, NameError, SyntaxError, TypeError, <ide> FormulaSpecificationError, FormulaValidationError, <del> ErrorDuringExecution, <add> ErrorDuringExecution, LoadError, <ide> ] <ide> <ide> attr_reader :f
1
Javascript
Javascript
use ie8 feature detect instead of try catch
d4adaee4eba49922e771db352a75181a9415a76a
<ide><path>src/browser/ui/dom/DOMChildrenOperations.js <ide> function insertChildAt(parentNode, childNode, index) { <ide> // browsers so we must replace it with `null`. <ide> <ide> // fix render order error in safari <del> try { <add> if (!(document.all && !document.addEventListener)) { <ide> parentNode.insertBefore( <ide> childNode, <ide> parentNode.childNodes.item(index) || null <ide> ); <del> } catch (e) { <del> //IE8 can't use `item` when childNodes is empty. <add> } else { <add> //IE8 can't use `item` when childNodes is empty or dynamic insert. <add> //But read is well after insert. <ide> parentNode.insertBefore( <ide> childNode, <ide> parentNode.childNodes[index] || null
1
Python
Python
fix typo learningratescheduler
4bb6ac0b04838e8d82d14d7c0f001569f543518b
<ide><path>keras/callbacks.py <ide> def __init__(self, schedule): <ide> self.schedule = schedule <ide> <ide> def on_epoch_begin(self, epoch, logs={}): <del> model.lr.set_value(self.schedule(epoch)) <add> self.model.optimizer.lr.set_value(self.schedule(epoch))
1
Javascript
Javascript
update onlychild invariant message
921d8c151ba8114a2314f32cd453d8954aeb19fc
<ide><path>src/isomorphic/children/onlyChild.js <ide> var invariant = require('invariant'); <ide> function onlyChild(children) { <ide> invariant( <ide> ReactElement.isValidElement(children), <del> 'onlyChild must be passed a children with exactly one child.' <add> 'React.Children.only expected to receive a single React element child.' <ide> ); <ide> return children; <ide> }
1
Ruby
Ruby
fix issue with standalone actionview
16a48a95e3cb0044587df7b0e83b017a94506739
<ide><path>actionpack/lib/action_view/render/partials.rb <ide> def find_template(path = @path) <ide> end <ide> <ide> def _find_template(path) <del> prefix = @view.controller.controller_path unless path.include?(?/) <add> if controller = @view.controller <add> prefix = controller.controller_path unless path.include?(?/) <add> end <add> <ide> @view.find(path, {:formats => @view.formats}, prefix, true) <ide> end <ide>
1
Python
Python
increase test coverage
3d9428d3445a429b535a247168d93b8a5910219d
<ide><path>tests/keras/backend/backend_test.py <ide> def test_pool3d(self): <ide> cntk_check_single_tensor_operation('pool3d', (5, 9, 11, 5, 3), pool_size=(2, 3, 2), <ide> strides=(1, 1, 1), pool_mode='avg') <ide> <add> check_single_tensor_operation('pool3d', (2, 6, 6, 6, 3), [KTH, KTF], pool_size=(3, 3, 3), <add> strides=(1, 1, 1), padding='same', pool_mode='avg') <add> <ide> def test_random_normal(self): <ide> mean = 0. <ide> std = 1. <ide><path>tests/keras/preprocessing/image_test.py <ide> def test_directory_iterator(self, tmpdir): <ide> assert(len(dir_iterator.classes) == count) <ide> assert(sorted(dir_iterator.filenames) == sorted(filenames)) <ide> <add> # Test invalid use cases <add> with pytest.raises(ValueError): <add> generator.flow_from_directory(str(tmpdir), color_mode='cmyk') <add> with pytest.raises(ValueError): <add> generator.flow_from_directory(str(tmpdir), class_mode='output') <add> <ide> def test_directory_iterator_class_mode_input(self, tmpdir): <ide> tmpdir.join('class-1').mkdir() <ide>
2
Python
Python
set the peak_time to 6 seconds
38c7ee987622e67bdb4f12b878b12c9c8afd862e
<ide><path>glances/core/glances_logs.py <ide> def reset_process_sort(self): <ide> glances_processes.sort_key = 'cpu_percent' <ide> <ide> def add(self, item_state, item_type, item_value, <del> proc_list=None, proc_desc="", peak_time=3): <add> proc_list=None, proc_desc="", peak_time=6): <ide> """Add a new item to the logs list. <ide> <ide> If 'item' is a 'new one', add the new item at the beginning of the logs
1
Go
Go
fix mistaken call to fmt.println
52ef89f9c20d02ca341c979e3d4cb8bd13aa0146
<ide><path>api.go <ide> func postBuild(srv *Server, w http.ResponseWriter, r *http.Request, vars map[str <ide> defer in.Close() <ide> fmt.Fprintf(out, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") <ide> if err := srv.ImageCreateFromFile(in, out); err != nil { <del> fmt.Fprintln(out, "Error: %s\n", err) <add> fmt.Fprintf(out, "Error: %s\n", err) <ide> } <ide> return nil <ide> }
1
Text
Text
improve spanish translate
1392ac445bf9fad71713c5fa58b10c7c521fd149
<ide><path>guide/spanish/git/authenticate-with-github-using-ssh/index.md <ide> --- <ide> title: How to authenticate with GitHub using SSH <del>localeTitle: Cómo autenticar con GitHub usando SSH <add>localeTitle: Cómo autenticarse con GitHub usando SSH <ide> --- <del># Cómo autenticar con GitHub usando SSH <add># Cómo autenticarse con GitHub usando SSH <ide> <del>Verifique que no haya archivos `rsa` aquí antes de continuar, use: <add>Verifique que no haya archivos `rsa` en esta ruta antes de continuar, usando: <ide> <ide> ```shell <ide> ls -al ~/.ssh <ide> ``` <ide> <del>Si no hay nada que enumerar (es decir, no existe `: No such file or directory` ), use: <add>Si no hay nada que enumerar (es decir, no existe el directorio `: No such file or directory` ), use: <ide> <ide> ```shell <ide> mkdir $HOME/.ssh <ide> ``` <ide> <del>Si no hay nada allí entonces genere un nuevo keygen con: <add>Si no hay nada en este directorio entonces genere un nuevo keygen con: <ide> <ide> ```shell <ide> ssh-keygen -t rsa -b 4096 -C [email protected] <ide> ``` <ide> <del>Ahora usando `ls -al ~/.ssh` mostrará nuestro archivo `id_rsa.pub` . <add>Ahora usando el comando `ls -al ~/.ssh` nos mostrará un nuevo archivo denominado `id_rsa.pub` . <ide> <ide> Agregue la clave SSH al agente SSH: <ide> <ide> clip < ~/.ssh/id_rsa.pub # Windows <ide> cat ~/.ssh/id_rsa.pub # Linux <ide> ``` <ide> <del>Vaya a la página de [configuración de](https://github.com/settings/keys) GitHub y haga clic en el botón 'Nueva clave SSH' para pegar en su clave generada. <add>Vaya a la página de [configuración](https://github.com/settings/keys) de GitHub y haga clic en el botón 'Nueva clave SSH' para pegar la clave generada anteriormente. <ide> <ide> Luego autentíquese con: <ide> <ide> ```shell <ide> ssh -T [email protected] <ide> <del>``` <ide>\ No newline at end of file <add>```
1
Javascript
Javascript
drop workspace from metro lookup
864235636787cf7888938070df5dec030547df19
<ide><path>setupBabel.js <ide> function buildRegExps(basePath, dirPaths) { <ide> folderPath => <ide> folderPath === 'metro' <ide> // metro uses flow (for example) which needs to be stripped out w/babel. <del> // it'll resolve to .../metro/packages/metro/src/index.js we want root <del> ? path.resolve(require.resolve('metro'), '..', '..', '..', '..') <add> // it'll resolve to .../metro/src/index.js we want root <add> ? path.resolve(require.resolve('metro'), '..') <ide> // Babel `only` option works with forward slashes in the RegExp so replace <ide> // backslashes for Windows. <ide> : folderPath instanceof RegExp
1
Javascript
Javascript
add tests for ember.view helpers
e596ab0cb9b3a176e1598b0a1d59629c2043669b
<ide><path>packages/ember-views/tests/views/view/class_string_for_value_test.js <add>module("Ember.View - _classStringForValue"); <add> <add>var cSFV = Ember.View._classStringForValue; <add> <add>test("returns dasherized version of last path part if value is true", function() { <add> equal(cSFV("propertyName", true), "property-name", "class is dasherized"); <add> equal(cSFV("content.propertyName", true), "property-name", "class is dasherized"); <add>}); <add> <add>test("returns className if value is true and className is specified", function() { <add> equal(cSFV("propertyName", true, "truthyClass"), "truthyClass", "returns className if given"); <add> equal(cSFV("content.propertyName", true, "truthyClass"), "truthyClass", "returns className if given"); <add>}); <add> <add>test("returns falsyClassName if value is false and falsyClassName is specified", function() { <add> equal(cSFV("propertyName", false, "truthyClass", "falsyClass"), "falsyClass", "returns falsyClassName if given"); <add> equal(cSFV("content.propertyName", false, "truthyClass", "falsyClass"), "falsyClass", "returns falsyClassName if given"); <add>}); <add> <add>test("returns null if value is false and falsyClassName is not specified", function() { <add> equal(cSFV("propertyName", false, "truthyClass"), null, "returns null if falsyClassName is not specified"); <add> equal(cSFV("content.propertyName", false, "truthyClass"), null, "returns null if falsyClassName is not specified"); <add>}); <add> <add>test("returns null if value is false", function() { <add> equal(cSFV("propertyName", false), null, "returns null if value is false"); <add> equal(cSFV("content.propertyName", false), null, "returns null if value is false"); <add>}); <add> <add>test("returns the value if the value is truthy", function() { <add> equal(cSFV("propertyName", "myString"), "myString", "returns value if the value is truthy"); <add> equal(cSFV("content.propertyName", "myString"), "myString", "returns value if the value is truthy"); <add> <add> equal(cSFV("propertyName", "123"), 123, "returns value if the value is truthy"); <add> equal(cSFV("content.propertyName", 123), 123, "returns value if the value is truthy"); <add>}); <ide>\ No newline at end of file <ide><path>packages/ember-views/tests/views/view/parse_property_path_test.js <add>module("Ember.View - _parsePropertyPath"); <add> <add>test("it works with a simple property path", function() { <add> var parsed = Ember.View._parsePropertyPath("simpleProperty"); <add> <add> equal(parsed.path, "simpleProperty", "path is parsed correctly"); <add> equal(parsed.className, undefined, "there is no className"); <add> equal(parsed.falsyClassName, undefined, "there is no falsyClassName"); <add> equal(parsed.classNames, "", "there is no classNames"); <add>}); <add> <add>test("it works with a more complex property path", function() { <add> var parsed = Ember.View._parsePropertyPath("content.simpleProperty"); <add> <add> equal(parsed.path, "content.simpleProperty", "path is parsed correctly"); <add> equal(parsed.className, undefined, "there is no className"); <add> equal(parsed.falsyClassName, undefined, "there is no falsyClassName"); <add> equal(parsed.classNames, "", "there is no classNames"); <add>}); <add> <add>test("className is extracted", function() { <add> var parsed = Ember.View._parsePropertyPath("content.simpleProperty:class"); <add> <add> equal(parsed.path, "content.simpleProperty", "path is parsed correctly"); <add> equal(parsed.className, "class", "className is extracted"); <add> equal(parsed.falsyClassName, undefined, "there is no falsyClassName"); <add> equal(parsed.classNames, ":class", "there is a classNames"); <add>}); <add> <add>test("falsyClassName is extracted", function() { <add> var parsed = Ember.View._parsePropertyPath("content.simpleProperty?class:falsyClass"); <add> <add> equal(parsed.path, "content.simpleProperty", "path is parsed correctly"); <add> equal(parsed.className, "class", "className is extracted"); <add> equal(parsed.falsyClassName, "falsyClass", "falsyClassName is extracted"); <add> equal(parsed.classNames, "?class:falsyClass", "there is a classNames"); <add>}); <ide>\ No newline at end of file
2
PHP
PHP
remove unnecessary "else" conditions
01408ab085348f1f7c09df50c9c67b3c27c3d236
<ide><path>src/Illuminate/Auth/AuthManager.php <ide> protected function resolve($name) <ide> <ide> if (isset($this->customCreators[$config['driver']])) { <ide> return $this->callCustomCreator($name, $config); <del> } else { <del> $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; <del> <del> if (method_exists($this, $driverMethod)) { <del> return $this->{$driverMethod}($name, $config); <del> } else { <del> throw new InvalidArgumentException("Auth guard driver [{$name}] is not defined."); <del> } <ide> } <add> <add> $driverMethod = 'create'.ucfirst($config['driver']).'Driver'; <add> <add> if (method_exists($this, $driverMethod)) { <add> return $this->{$driverMethod}($name, $config); <add> } <add> <add> throw new InvalidArgumentException("Auth guard driver [{$name}] is not defined."); <ide> } <ide> <ide> /**
1
Ruby
Ruby
keep assert_redirected_to backwards compatible
e7a1740114ba2e4d8ee8db77e11158e1e4b093d0
<ide><path>actionpack/lib/action_dispatch/testing/assertions/response.rb <ide> def assert_response(type, message = nil) <ide> # # Permanently). <ide> # assert_redirected_to "/some/path", status: :moved_permanently <ide> def assert_redirected_to(url_options = {}, options = {}, message = nil) <del> options, message = message, nil if message.is_a?(Hash) && options.empty? <add> options, message = {}, options unless options.is_a?(Hash) <ide> <ide> status = options[:status] || :redirect <ide> assert_response(status, message)
1
PHP
PHP
fix funny warning
6725a30fe21224f362ab4bc571c0a3d1752a09ed
<ide><path>lib/Cake/TestSuite/templates/menu.php <ide> <li style="padding-top: 10px"> <ide> <span style="font-size: 18px"><?php echo $plugin; ?></span> <ide> <ul> <del> <li><a href='<?php echo $cases; ?>&amp;plugin=<?php echo $plugin; ?>'>Tests</a></li> <add> <li><?php printf('<a href="%s&amp;plugin=%s">Tests</a>', $cases, $plugin); ?></li> <ide> </ul> <ide> </li> <ide> </ul>
1
Javascript
Javascript
add cleardepth attribute to renderpass
e0df8d13c12bf1b261a4f14430e94cada838e307
<ide><path>examples/js/postprocessing/RenderPass.js <ide> THREE.RenderPass = function ( scene, camera, overrideMaterial, clearColor, clear <ide> this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0; <ide> <ide> this.clear = true; <add> this.clearDepth = false; <ide> this.needsSwap = false; <ide> <ide> }; <ide> THREE.RenderPass.prototype = Object.assign( Object.create( THREE.Pass.prototype <ide> <ide> } <ide> <add> if ( this.clearDepth ) { <add> <add> renderer.clearDepth(); <add> <add> } <add> <ide> renderer.render( this.scene, this.camera, this.renderToScreen ? null : readBuffer, this.clear ); <ide> <ide> if ( this.clearColor ) {
1
Python
Python
remove erronous pre_save
922ee61d8611b41e2944b6503af736b1790abe83
<ide><path>rest_framework/generics.py <ide> def post_save(self, obj, created=False): <ide> """ <ide> pass <ide> <del> def pre_save(self, obj): <del> pass <del> <ide> <ide> class MultipleObjectAPIView(MultipleObjectMixin, GenericAPIView): <ide> """
1
Text
Text
provide model card for roberta-base-squad2-covid
4a94c062a409a87a1503748f039beeeeefb9f8d3
<ide><path>model_cards/deepset/roberta-base-squad2-covid/README.md <add># roberta-base-squad2 for QA on COVID-19 <add> <add>## Overview <add>**Language model:** deepset/roberta-base-squad2 <add>**Language:** English <add>**Downstream-task:** Extractive QA <add>**Training data:** [SQuAD-style CORD-19 annotations](https://github.com/deepset-ai/COVID-QA/tree/master/data/question-answering) <add>**Code:** See [example](https://github.com/deepset-ai/FARM/blob/master/examples/question_answering_crossvalidation.py) in [FARM](https://github.com/deepset-ai/FARM) <add>**Infrastructure**: Tesla v100 <add> <add>## Hyperparameters <add>``` <add>batch_size = 24 <add>n_epochs = 3 <add>base_LM_model = "deepset/roberta-base-squad2" <add>max_seq_len = 384 <add>learning_rate = 3e-5 <add>lr_schedule = LinearWarmup <add>warmup_proportion = 0.1 <add>doc_stride = 128 <add>xval_folds = 5 <add>dev_split = 0 <add>no_ans_boost = -100 <add>``` <add> <add>## Performance <add>5-fold cross-validation on the data set led to the following results: <add> <add>**Single EM-Scores:** [0.222, 0.123, 0.234, 0.159, 0.158] <add>**Single F1-Scores:** [0.476, 0.493, 0.599, 0.461, 0.465] <add>**Single top\_3\_recall Scores:** [0.827, 0.776, 0.860, 0.771, 0.777] <add>**XVAL EM:** 0.17890995260663506 <add>**XVAL f1:** 0.49925444207319924 <add>**XVAL top\_3\_recall:** 0.8021327014218009 <add> <add>This model is the model obtained from the **third** fold of the cross-validation. <add> <add>## Usage <add> <add>### In Transformers <add>```python <add>from transformers.pipelines import pipeline <add>from transformers.modeling_auto import AutoModelForQuestionAnswering <add>from transformers.tokenization_auto import AutoTokenizer <add> <add>model_name = "deepset/roberta-base-squad2-covid" <add> <add># a) Get predictions <add>nlp = pipeline('question-answering', model=model_name, tokenizer=model_name) <add>QA_input = { <add> 'question': 'Why is model conversion important?', <add> 'context': 'The option to convert models between FARM and transformers gives freedom to the user and let people easily switch between frameworks.' <add>} <add>res = nlp(QA_input) <add> <add># b) Load model & tokenizer <add>model = AutoModelForQuestionAnswering.from_pretrained(model_name) <add>tokenizer = AutoTokenizer.from_pretrained(model_name) <add>``` <add> <add>### In FARM <add>```python <add>from farm.modeling.adaptive_model import AdaptiveModel <add>from farm.modeling.tokenization import Tokenizer <add>from farm.infer import Inferencer <add> <add>model_name = "deepset/roberta-base-squad2-covid" <add> <add># a) Get predictions <add>nlp = Inferencer.load(model_name, task_type="question_answering") <add>QA_input = [{"questions": ["Why is model conversion important?"], <add> "text": "The option to convert models between FARM and transformers gives freedom to the user and let people easily switch between frameworks."}] <add>res = nlp.inference_from_dicts(dicts=QA_input, rest_api_schema=True) <add> <add># b) Load model & tokenizer <add>model = AdaptiveModel.convert_from_transformers(model_name, device="cpu", task_type="question_answering") <add>tokenizer = Tokenizer.load(model_name) <add>``` <add> <add>### In haystack <add>For doing QA at scale (i.e. many docs instead of single paragraph), you can load the model also in [haystack](https://github.com/deepset-ai/haystack/): <add>```python <add>reader = FARMReader(model_name_or_path="deepset/roberta-base-squad2-covid") <add># or <add>reader = TransformersReader(model="deepset/roberta-base-squad2",tokenizer="deepset/roberta-base-squad2-covid") <add>``` <add> <add>## Authors <add>Branden Chan: `branden.chan [at] deepset.ai` <add>Timo Möller: `timo.moeller [at] deepset.ai` <add>Malte Pietsch: `malte.pietsch [at] deepset.ai` <add>Tanay Soni: `tanay.soni [at] deepset.ai` <add>Bogdan Kostić: `bogdan.kostic [at] deepset.ai` <add> <add>## About us <add>![deepset logo](https://raw.githubusercontent.com/deepset-ai/FARM/master/docs/img/deepset_logo.png) <add> <add>We bring NLP to the industry via open source! <add>Our focus: Industry specific language models & large scale QA systems. <add> <add>Some of our work: <add>- [German BERT (aka "bert-base-german-cased")](https://deepset.ai/german-bert) <add>- [FARM](https://github.com/deepset-ai/FARM) <add>- [Haystack](https://github.com/deepset-ai/haystack/) <add> <add>Get in touch: <add>[Twitter](https://twitter.com/deepset_ai) | [LinkedIn](https://www.linkedin.com/company/deepset-ai/) | [Website](https://deepset.ai) <ide>\ No newline at end of file
1
Python
Python
return self on __enter__
7f03932477f92cb5a3b5ae0379f3ee7499a340b0
<ide><path>spacy/language.py <ide> def __init__(self, nlp, *names): <ide> self.extend(nlp.remove_pipe(name) for name in names) <ide> <ide> def __enter__(self): <del> pass <add> return self <ide> <ide> def __exit__(self, *args): <ide> self.restore()
1
Text
Text
use the caret character to use the latest minor..
df3c470b46c928d05be46553a75d38f13dea1eb7
<ide><path>guide/english/certifications/apis-and-microservices/managing-packages-with-npm/use-the-caret-character-to-use-the-latest-minor-version-of-a-dependency/index.md <ide> title: Use the Caret-Character to Use the Latest Minor Version of a Dependency <ide> --- <ide> ## Use the Caret-Character to Use the Latest Minor Version of a Dependency <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/managing-packages-with-npm/use-the-caret-character-to-use-the-latest-minor-version-of-a-dependency/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>## Hint 1 <add>* the package `moment` should be in your package.json, specifically in the <add>dependencies property. <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add>## Hint 2 <add>* `moment` version should have a caret character within it. <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>## Solution: <add>```js <add>"dependencies": { <add> "moment": "^2.10.2" <add>} <add>```
1
Text
Text
fix typo in docs. s/methodoligies/methodologies/
191adcfb637ea1b52d2da9a75e4e1e4938d9550c
<ide><path>docs/understanding-docker.md <ide> Docker is an open platform for developing, shipping, and running applications. <ide> Docker enables you to separate your applications from your infrastructure so <ide> you can deliver software quickly. With Docker, you can manage your infrastructure <ide> in the same ways you manage your applications. By taking advantage of Docker's <del>methodoligies for shipping, testing, and deploying code quickly, you can <add>methodologies for shipping, testing, and deploying code quickly, you can <ide> significantly reduce the delay between writing code and running it in production. <ide> <ide> ## What is the Docker platform?
1
PHP
PHP
remove @package tags
11289af9c4154ad4eea02107083b6151b20cb581
<ide><path>lib/Cake/Network/Email/AbstractTransport.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Network.Email <ide> * @since CakePHP(tm) v 2.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> /** <ide> * Abstract transport for sending email <ide> * <del> * @package Cake.Network.Email <ide> */ <ide> abstract class AbstractTransport { <ide> <ide><path>lib/Cake/Network/Email/DebugTransport.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Network.Email <ide> * @since CakePHP(tm) v 2.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> * Debug Transport class, useful for emulate the email sending process and inspect the resulted <ide> * email message before actually send it during development <ide> * <del> * @package Cake.Network.Email <ide> */ <ide> class DebugTransport extends AbstractTransport { <ide> <ide><path>lib/Cake/Network/Email/Email.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Network.Email <ide> * @since CakePHP(tm) v 2.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> /** <ide> * Cake e-mail class. <ide> * <del> * This class is used for handling Internet Message Format based <del> * based on the standard outlined in http://www.rfc-editor.org/rfc/rfc2822.txt <del> * <del> * @package Cake.Network.Email <add> * This class is used for sending Internet Message Format based <add> * on the standard outlined in http://www.rfc-editor.org/rfc/rfc2822.txt <ide> */ <ide> class Email { <ide> <ide><path>lib/Cake/Network/Email/MailTransport.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Network.Email <ide> * @since CakePHP(tm) v 2.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> /** <ide> * Send mail using mail() function <ide> * <del> * @package Cake.Network.Email <ide> */ <ide> class MailTransport extends AbstractTransport { <ide> <ide><path>lib/Cake/Network/Email/SmtpTransport.php <ide> * <ide> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Network.Email <ide> * @since CakePHP(tm) v 2.0.0 <ide> * @license http://www.opensource.org/licenses/mit-license.php MIT License <ide> */ <ide> <ide> /** <ide> * Send mail using SMTP protocol <del> * <del> * @package Cake.Network.Email <ide> */ <ide> class SmtpTransport extends AbstractTransport { <ide>
5
Python
Python
fix serialization of weight offsets
f1acdaab55aede4b64ff7ada87affdd9951b7530
<ide><path>spacy/util.py <ide> def model_to_bytes(model): <ide> weights.append(layer._mem.weights) <ide> else: <ide> weights.append(layer._mem.weights.get()) <del> metas.append(tuple(layer._mem._offsets)) <add> metas.append(layer._mem._offsets) <ide> dims.append(getattr(layer, '_dims', None)) <ide> i += 1 <ide> if hasattr(layer, '_layers'): <ide> queue.extend(layer._layers) <del> data = {'metas': metas, 'weights': weights, 'dims': dims} <add> data = {'metas': ujson.dumps(metas), 'weights': weights, 'dims': ujson.dumps(dims)} <ide> return msgpack.dumps(data) <ide> <ide> <ide> def model_from_bytes(model, bytes_data): <ide> data = msgpack.loads(bytes_data) <ide> weights = data['weights'] <del> metas = data['metas'] <del> dims = data['dims'] <add> metas = ujson.loads(data['metas']) <add> dims = ujson.loads(data['dims']) <ide> queue = [model] <ide> i = 0 <ide> for layer in queue: <ide> def model_from_bytes(model, bytes_data): <ide> i += 1 <ide> if hasattr(layer, '_layers'): <ide> queue.extend(layer._layers) <del> <add> <ide> <ide> def print_table(data, title=None): <ide> """Print data in table format.
1
Text
Text
fix broken wikipedia link
f84c0ec4badff4818d596ea79a40430456093e68
<ide><path>docs/style-guide/style-guide.md <ide> To fix this, **treat reducers as "state machines", where the combination of both <ide> <summary> <ide> <h4>Detailed Explanation</h4> <ide> </summary> <del> <add> <ide> A [finite state machine](https://en.wikipedia.org/wiki/Finite-state_machine) is a useful way of modeling something that should only be in one of a finite number of "finite states" at any time. For example, if you have a `fetchUserReducer`, the finite states can be: <ide> <ide> - `"idle"` (fetching not started yet)
1
Javascript
Javascript
fix style errors
3e61a6ac9750cdc428f57b6dafb4277533a4f41a
<ide><path>packages/ember-htmlbars/lib/keywords/view.js <ide> function swapKey(hash, original, update) { <ide> var newHash = {}; <ide> <ide> for (var prop in hash) { <del> if (prop === original) { newHash[update] = hash[prop]; } <del> else { newHash[prop] = hash[prop]; } <add> if (prop === original) { <add> newHash[update] = hash[prop]; <add> } else { <add> newHash[prop] = hash[prop]; <add> } <ide> } <ide> <ide> return newHash; <ide><path>packages/ember-htmlbars/tests/helpers/view_test.js <ide> QUnit.test("View lookup - 'fu'", function() { <ide> <ide> view = EmberView.extend({ <ide> template: compile("{{view 'fu'}}"), <del> container: container, <add> container: container <ide> }).create(); <ide> <ide> runAppend(view); <ide><path>packages/ember-htmlbars/tests/helpers/yield_test.js <ide> QUnit.module("ember-htmlbars: Component {{yield}}", { <ide> <ide> QUnit.skip("yield with nested components (#3220)", function() { <ide> var InnerComponent = Component.extend({ <del> layout: compile("{{yield}}"), <add> layout: compile("{{yield}}") <ide> }); <ide> <ide> registerHelper('inner-component', makeViewHelper(InnerComponent)); <ide><path>packages/ember-template-compiler/lib/plugins/transform-each-into-collection.js <ide> function validate(node) { <ide> return (node.type === 'BlockStatement' || node.type === 'MustacheStatement') && <ide> node.sexpr.path.original === 'each' && <ide> any(node.sexpr.hash.pairs, pair => { <del> return pair.key === 'itemController' || <del> pair.key === 'itemView' || <del> pair.key === 'itemViewClass' || <del> pair.key === 'tagName' || <del> pair.key === 'emptyView' || <del> pair.key === 'emptyViewClass'; <del> }); <add> let key = pair.key; <add> return key === 'itemController' || <add> key === 'itemView' || <add> key === 'itemViewClass' || <add> key === 'tagName' || <add> key === 'emptyView' || <add> key === 'emptyViewClass'; <add> }); <ide> } <ide> <ide> function any(list, predicate) {
4
Python
Python
fix permission error on non-posix filesystem
6c6b77a87891ee81ed384124e309dff72a85c02f
<ide><path>airflow/utils/log/file_task_handler.py <ide> def _init_file(self, ti): <ide> if not os.path.exists(full_path): <ide> open(full_path, "a").close() <ide> # TODO: Investigate using 444 instead of 666. <del> os.chmod(full_path, 0o666) <add> try: <add> os.chmod(full_path, 0o666) <add> except OSError: <add> logging.warning("OSError while change ownership of the log file") <ide> <ide> return full_path
1
Python
Python
fix bogus output in polyval example
b7a5b170ff68fc502e4fbc5055d23a8ed082482a
<ide><path>numpy/polynomial/polynomial.py <ide> def polyval(x, c, tensor=True): <ide> 6.0 <ide> >>> a = np.arange(4).reshape(2,2) <ide> >>> a <del> array([[[ 0, 1], <del> [ 2, 3]], <add> array([[0, 1], <add> [2, 3]]) <ide> >>> polyval(a, [1,2,3]) <ide> array([[ 1., 6.], <ide> [ 17., 34.]]) <ide> >>> coef = np.arange(4).reshape(2,2) # multidimensional coefficients <ide> >>> coef <del> array([[[ 0, 1], <del> [ 2, 3]], <add> array([[0, 1], <add> [2, 3]]) <ide> >>> polyval([1,2], coef, tensor=True) <ide> array([[ 2., 4.], <ide> [ 4., 7.]])
1
PHP
PHP
fix email rendering when using 2 different plugins
4ec81542dba716619a5221308a6bdbe0fbbee091
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> protected function _renderTemplates($content) { <ide> $View->plugin = $layoutPlugin; <ide> } <ide> <del> // Convert null to false, as View needs false to disable <del> // the layout. <del> if ($layout === null) { <del> $layout = false; <del> } <del> <ide> if ($View->get('content') === null) { <ide> $View->set('content', $content); <ide> } <ide> <add> // Convert null to false, as View needs false to disable <add> // the layout. <add> if ($this->_layout === null) { <add> $this->_layout = false; <add> } <add> <ide> foreach ($types as $type) { <ide> $View->hasRendered = false; <ide> $View->viewPath = $View->layoutPath = 'Emails' . DS . $type; <ide> <del> $render = $View->render($template, $layout); <add> $render = $View->render($this->_template, $this->_layout); <ide> $render = str_replace(array("\r\n", "\r"), "\n", $render); <ide> $rendered[$type] = $this->_encodeString($render, $this->charset); <ide> } <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testSendRenderPlugin() { <ide> App::build(array( <ide> 'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS) <ide> )); <del> CakePlugin::load('TestPlugin'); <add> CakePlugin::load(array('TestPlugin', 'TestPluginTwo')); <ide> <ide> $this->CakeEmail->reset(); <ide> $this->CakeEmail->transport('debug'); <ide> public function testSendRenderPlugin() { <ide> $this->assertContains('Into TestPlugin.', $result['message']); <ide> $this->assertContains('This email was sent using the TestPlugin.', $result['message']); <ide> <add> $this->CakeEmail->template( <add> 'TestPlugin.test_plugin_tpl', <add> 'TestPluginTwo.default' <add> ); <add> $result = $this->CakeEmail->send(); <add> $this->assertContains('Into TestPlugin.', $result['message']); <add> $this->assertContains('This email was sent using TestPluginTwo.', $result['message']); <add> <ide> // test plugin template overridden by theme <ide> $this->CakeEmail->theme('TestTheme'); <ide> $result = $this->CakeEmail->send();
2
PHP
PHP
fix resource routing not allowing generation
977482bdd3578bd78be243fafd2a3f2e5f6e5089
<ide><path>src/Routing/RouteBuilder.php <ide> public function resources($name, $options = [], $callback = null) <ide> 'controller' => $name, <ide> 'action' => $action, <ide> '_method' => $params['method'], <del> '_ext' => $ext <ide> ]; <ide> $routeOptions = $connectOptions + [ <ide> 'id' => $options['id'], <del> 'pass' => ['id'] <add> 'pass' => ['id'], <add> '_ext' => $ext, <ide> ]; <ide> $this->connect($url, $params, $routeOptions); <ide> } <ide><path>tests/TestCase/Routing/RouteBuilderTest.php <ide> public function testResources() <ide> $this->assertCount(5, $all); <ide> <ide> $this->assertEquals('/api/articles', $all[0]->template); <del> $this->assertEquals('json', $all[0]->defaults['_ext']); <add> $this->assertEquals( <add> ['controller', 'action', '_method', 'prefix', 'plugin'], <add> array_keys($all[0]->defaults) <add> ); <add> $this->assertEquals('json', $all[0]->options['_ext']); <ide> $this->assertEquals('Articles', $all[0]->defaults['controller']); <ide> } <ide> <add> /** <add> * Test connecting resources. <add> * <add> * @return void <add> */ <add> public function testResourcesInScope() <add> { <add> Router::scope('/api', ['prefix' => 'api'], function ($routes) { <add> $routes->extensions(['json']); <add> $routes->resources('Articles'); <add> }); <add> $url = Router::url([ <add> 'prefix' => 'api', <add> 'controller' => 'Articles', <add> 'action' => 'edit', <add> '_method' => 'PUT', <add> 'id' => 99 <add> ]); <add> $this->assertEquals('/api/articles/99', $url); <add> <add> $url = Router::url([ <add> 'prefix' => 'api', <add> 'controller' => 'Articles', <add> 'action' => 'edit', <add> '_method' => 'PUT', <add> '_ext' => 'json', <add> 'id' => 99 <add> ]); <add> $this->assertEquals('/api/articles/99.json', $url); <add> } <add> <ide> /** <ide> * Test resource parsing. <ide> * <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testMapResources() <ide> 'controller' => 'Posts', <ide> 'action' => 'index', <ide> '_method' => 'GET', <del> '_ext' => null <ide> ]; <ide> $result = Router::parse('/posts'); <ide> $this->assertEquals($expected, $result); <ide> public function testMapResources() <ide> 'action' => 'view', <ide> 'id' => '13', <ide> '_method' => 'GET', <del> '_ext' => null <ide> ]; <ide> $result = Router::parse('/posts/13'); <ide> $this->assertEquals($expected, $result); <ide> public function testMapResources() <ide> 'controller' => 'Posts', <ide> 'action' => 'add', <ide> '_method' => 'POST', <del> '_ext' => null <ide> ]; <ide> $result = Router::parse('/posts'); <ide> $this->assertEquals($expected, $result); <ide> public function testMapResources() <ide> 'action' => 'edit', <ide> 'id' => '13', <ide> '_method' => ['PUT', 'PATCH'], <del> '_ext' => null <ide> ]; <ide> $result = Router::parse('/posts/13'); <ide> $this->assertEquals($expected, $result); <ide> public function testMapResources() <ide> 'action' => 'edit', <ide> 'id' => '475acc39-a328-44d3-95fb-015000000000', <ide> '_method' => ['PUT', 'PATCH'], <del> '_ext' => null <ide> ]; <ide> $result = Router::parse('/posts/475acc39-a328-44d3-95fb-015000000000'); <ide> $this->assertEquals($expected, $result); <ide> public function testMapResources() <ide> 'action' => 'delete', <ide> 'id' => '13', <ide> '_method' => 'DELETE', <del> '_ext' => null <ide> ]; <ide> $result = Router::parse('/posts/13'); <ide> $this->assertEquals($expected, $result); <ide> public function testMapResources() <ide> 'action' => 'view', <ide> 'id' => 'add', <ide> '_method' => 'GET', <del> '_ext' => null <ide> ]; <ide> $result = Router::parse('/posts/add'); <ide> $this->assertEquals($expected, $result); <ide> public function testMapResources() <ide> 'action' => 'edit', <ide> 'id' => 'name', <ide> '_method' => ['PUT', 'PATCH'], <del> '_ext' => null <ide> ]; <ide> $result = Router::parse('/posts/name'); <ide> $this->assertEquals($expected, $result); <ide> public function testPluginMapResources() <ide> 'controller' => 'TestPlugin', <ide> 'action' => 'index', <ide> '_method' => 'GET', <del> '_ext' => null <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testPluginMapResources() <ide> 'action' => 'view', <ide> 'id' => '13', <ide> '_method' => 'GET', <del> '_ext' => null <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testMapResourcesWithPrefix() <ide> 'pass' => [], <ide> 'prefix' => 'api', <ide> '_method' => 'GET', <del> '_ext' => null <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testMapResourcesWithExtension() <ide> 'action' => 'index', <ide> 'pass' => [], <ide> '_method' => 'GET', <del> '_ext' => 'json', <ide> ]; <ide> <ide> $result = Router::parse('/posts'); <ide> $this->assertEquals($expected, $result); <ide> <ide> $result = Router::parse('/posts.json'); <add> $expected['_ext'] = 'json'; <ide> $this->assertEquals($expected, $result); <ide> <del> $expected['_ext'] = 'xml'; <ide> $result = Router::parse('/posts.xml'); <del> $this->assertEquals($expected, $result); <add> $this->assertArrayNotHasKey('_method', $result, 'Not an extension/resource route.'); <ide> } <ide> <ide> /** <ide> public function testPluginMapResourcesWithPrefix() <ide> 'prefix' => 'api', <ide> 'action' => 'index', <ide> '_method' => 'GET', <del> '_ext' => null <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testPluginMapResourcesWithPrefix() <ide> 'action' => 'index', <ide> '_method' => 'GET', <ide> 'prefix' => 'api', <del> '_ext' => null <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testExtensionsWithScopedRoutes() <ide> $this->assertEquals(['json', 'rss', 'xml'], array_values(Router::extensions())); <ide> } <ide> <add> /** <add> * Test connecting resources. <add> * <add> * @return void <add> */ <add> public function testResourcesInScope() <add> { <add> Router::scope('/api', ['prefix' => 'api'], function ($routes) { <add> $routes->extensions(['json']); <add> $routes->resources('Articles'); <add> }); <add> $url = Router::url([ <add> 'prefix' => 'api', <add> 'controller' => 'Articles', <add> 'action' => 'edit', <add> '_method' => 'PUT', <add> 'id' => 99 <add> ]); <add> $this->assertEquals('/api/articles/99', $url); <add> <add> $url = Router::url([ <add> 'prefix' => 'api', <add> 'controller' => 'Articles', <add> 'action' => 'edit', <add> '_method' => 'PUT', <add> '_ext' => 'json', <add> 'id' => 99 <add> ]); <add> $this->assertEquals('/api/articles/99.json', $url); <add> } <add> <ide> /** <ide> * testExtensionParsing method <ide> *
3
Java
Java
improve unit test determinism
0485a6d7c458f03d561bf367ab9662391b93601a
<ide><path>rxjava-core/src/main/java/rx/plugins/RxJavaPlugins.java <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import org.junit.After; <add>import org.junit.Before; <ide> import org.junit.Test; <ide> <ide> /** <ide> private static Object getPluginImplementationViaProperty(Class<?> pluginClass) { <ide> public static class UnitTest { <ide> <ide> @After <add> @Before <ide> public void reset() { <ide> // use private access to reset so we can test different initializations via the public static flow <ide> RxJavaPlugins.getInstance().errorHandler.set(null);
1
Text
Text
fix writable.write callback description
7c524fb092b143470795c8ca869de4654c728fe1
<ide><path>doc/api/stream.md <ide> The `writable.write()` method writes some data to the stream, and calls the <ide> supplied `callback` once the data has been fully handled. If an error <ide> occurs, the `callback` *may or may not* be called with the error as its <ide> first argument. To reliably detect write errors, add a listener for the <del>`'error'` event. If `callback` is called with an error, it will be called <del>before the `'error'` event is emitted. <add>`'error'` event. The `callback` is called asynchronously and before `'error'` is <add>emitted. <ide> <ide> The return value is `true` if the internal buffer is less than the <ide> `highWaterMark` configured when the stream was created after admitting `chunk`. <ide> methods only. <ide> The `callback` method must be called to signal either that the write completed <ide> successfully or failed with an error. The first argument passed to the <ide> `callback` must be the `Error` object if the call failed or `null` if the <del>write succeeded. The `callback` method will always be called asynchronously and <del>before `'error'` is emitted. <add>write succeeded. The `callback` must be called synchronously inside of <add>`writable._write()` or asynchronously (i.e. different tick). <ide> <ide> All calls to `writable.write()` that occur between the time `writable._write()` <ide> is called and the `callback` is called will cause the written data to be
1
Mixed
Javascript
show weak(set|map) entries in inspect
1029dd36861d7ab592d4e219362706d2c161839a
<ide><path>doc/api/util.md <ide> stream.write('With ES6'); <ide> <!-- YAML <ide> added: v0.3.0 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/19259 <add> description: WeakMap and WeakSet entries can now be inspected as well. <ide> - version: REPLACEME <ide> pr-url: https://github.com/nodejs/node/pull/17907 <ide> description: The `depth` default changed to Infinity. <ide> changes: <ide> * `object` {any} Any JavaScript primitive or Object. <ide> * `options` {Object} <ide> * `showHidden` {boolean} If `true`, the `object`'s non-enumerable symbols and <del> properties will be included in the formatted result. Defaults to `false`. <add> properties will be included in the formatted result as well as [`WeakMap`][] <add> and [`WeakSet`][] entries. Defaults to `false`. <ide> * `colors` {boolean} If `true`, the output will be styled with ANSI color <ide> codes. Defaults to `false`. Colors are customizable, see <ide> [Customizing `util.inspect` colors][]. <ide> changes: <ide> * `showProxy` {boolean} If `true`, then objects and functions that are <ide> `Proxy` objects will be introspected to show their `target` and `handler` <ide> objects. Defaults to `false`. <del> * `maxArrayLength` {number} Specifies the maximum number of array and <del> `TypedArray` elements to include when formatting. Defaults to `100`. Set to <del> `null` or `Infinity` to show all array elements. Set to `0` or negative to <del> show no array elements. <add> <!-- <add> TODO(BridgeAR): Deprecate `maxArrayLength` and replace it with <add> `maxEntries`. <add> --> <add> * `maxArrayLength` {number} Specifies the maximum number of `Array`, <add> [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when <add> formatting. Defaults to `100`. Set to `null` or `Infinity` to show all <add> elements. Set to `0` or negative to show no elements. <ide> * `breakLength` {number} The length at which an object's keys are split <ide> across multiple lines. Set to `Infinity` to format an object as a single <ide> line. Defaults to 60 for legacy compatibility. <ide> console.log(util.inspect(o, { compact: false, breakLength: 80 })); <ide> // chunks. <ide> ``` <ide> <add>Using the `showHidden` option allows to inspect [`WeakMap`][] and [`WeakSet`][] <add>entries. If there are more entries than `maxArrayLength`, there is no guarantee <add>which entries are displayed. That means retrieving the same ['WeakSet'][] <add>entries twice might actually result in a different output. Besides this any item <add>might be collected at any point of time by the garbage collector if there is no <add>strong reference left to that object. Therefore there is no guarantee to get a <add>reliable output. <add> <add>```js <add>const { inspect } = require('util'); <add> <add>const obj = { a: 1 }; <add>const obj2 = { b: 2 }; <add>const weakSet = new WeakSet([obj, obj2]); <add> <add>console.log(inspect(weakSet, { showHidden: true })); <add>// WeakSet { { a: 1 }, { b: 2 } } <add>``` <add> <ide> Please note that `util.inspect()` is a synchronous method that is mainly <ide> intended as a debugging tool. Some input values can have a significant <ide> performance overhead that can block the event loop. Use this function <ide><path>lib/internal/bootstrap/node.js <ide> const v8 = NativeModule.require('internal/v8'); <ide> v8.previewMapIterator(new Map().entries()); <ide> v8.previewSetIterator(new Set().entries()); <add> v8.previewWeakMap(new WeakMap(), 1); <add> v8.previewWeakSet(new WeakSet(), 1); <ide> // Disable --allow_natives_syntax again unless it was explicitly <ide> // specified on the command line. <ide> const re = /^--allow[-_]natives[-_]syntax$/; <ide><path>lib/internal/v8.js <ide> function previewSetIterator(it) { <ide> return %SetIteratorClone(it); <ide> } <ide> <add>// Retrieve all WeakMap instance key / value pairs up to `max`. `max` limits the <add>// number of key / value pairs returned. Make sure it is a positive number, <add>// otherwise V8 aborts. Passing through `0` returns all elements. <add>function previewWeakMap(weakMap, max) { <add> return %GetWeakMapEntries(weakMap, max); <add>} <add> <add>// Retrieve all WeakSet instance values up to `max`. `max` limits the <add>// number of key / value pairs returned. Make sure it is a positive number, <add>// otherwise V8 aborts. Passing through `0` returns all elements. <add>function previewWeakSet(weakSet, max) { <add> return %GetWeakSetValues(weakSet, max); <add>} <add> <ide> module.exports = { <ide> previewMapIterator, <del> previewSetIterator <add> previewSetIterator, <add> previewWeakMap, <add> previewWeakSet <ide> }; <ide><path>lib/util.js <ide> const { isBuffer } = require('buffer').Buffer; <ide> <ide> const { <ide> previewMapIterator, <del> previewSetIterator <add> previewSetIterator, <add> previewWeakMap, <add> previewWeakSet <ide> } = require('internal/v8'); <ide> <ide> const { <ide> const { <ide> isPromise, <ide> isSet, <ide> isSetIterator, <add> isWeakMap, <add> isWeakSet, <ide> isRegExp, <ide> isDate, <ide> isTypedArray <ide> function inspect(value, opts) { <ide> colors: inspectDefaultOptions.colors, <ide> customInspect: inspectDefaultOptions.customInspect, <ide> showProxy: inspectDefaultOptions.showProxy, <add> // TODO(BridgeAR): Deprecate `maxArrayLength` and replace it with <add> // `maxEntries`. <ide> maxArrayLength: inspectDefaultOptions.maxArrayLength, <ide> breakLength: inspectDefaultOptions.breakLength, <ide> indentationLvl: 0, <ide> Object.defineProperty(inspect, 'defaultOptions', { <ide> if (options === null || typeof options !== 'object') { <ide> throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); <ide> } <add> // TODO(BridgeAR): Add input validation and make sure `defaultOptions` are <add> // not configurable. <ide> return _extend(inspectDefaultOptions, options); <ide> } <ide> }); <ide> function formatValue(ctx, value, recurseTimes, ln) { <ide> let braces; <ide> let noIterator = true; <ide> let raw; <add> let extra; <ide> <ide> // Iterators and the rest are split to reduce checks <ide> if (value[Symbol.iterator]) { <ide> function formatValue(ctx, value, recurseTimes, ln) { <ide> } else if (isPromise(value)) { <ide> braces[0] = `${prefix}{`; <ide> formatter = formatPromise; <add> } else if (isWeakSet(value)) { <add> braces[0] = `${prefix}{`; <add> if (ctx.showHidden) { <add> formatter = formatWeakSet; <add> } else { <add> extra = '[items unknown]'; <add> } <add> } else if (isWeakMap(value)) { <add> braces[0] = `${prefix}{`; <add> if (ctx.showHidden) { <add> formatter = formatWeakMap; <add> } else { <add> extra = '[items unknown]'; <add> } <ide> } else { <ide> // Check boxed primitives other than string with valueOf() <ide> // NOTE: `Date` has to be checked first! <ide> function formatValue(ctx, value, recurseTimes, ln) { <ide> ctx.seen.push(value); <ide> const output = formatter(ctx, value, recurseTimes, keys); <ide> <add> if (extra !== undefined) <add> output.unshift(extra); <add> <ide> for (var i = 0; i < symbols.length; i++) { <ide> output.push(formatProperty(ctx, value, recurseTimes, symbols[i], 0)); <ide> } <ide> function formatMap(ctx, value, recurseTimes, keys) { <ide> return output; <ide> } <ide> <add>function formatWeakSet(ctx, value, recurseTimes, keys) { <add> const maxArrayLength = Math.max(ctx.maxArrayLength, 0); <add> const entries = previewWeakSet(value, maxArrayLength + 1); <add> const maxLength = Math.min(maxArrayLength, entries.length); <add> let output = new Array(maxLength); <add> for (var i = 0; i < maxLength; ++i) <add> output[i] = formatValue(ctx, entries[i], recurseTimes); <add> // Sort all entries to have a halfway reliable output (if more entries than <add> // retrieved ones exist, we can not reliably return the same output). <add> output = output.sort(); <add> if (entries.length > maxArrayLength) <add> output.push('... more items'); <add> for (i = 0; i < keys.length; i++) <add> output.push(formatProperty(ctx, value, recurseTimes, keys[i], 0)); <add> return output; <add>} <add> <add>function formatWeakMap(ctx, value, recurseTimes, keys) { <add> const maxArrayLength = Math.max(ctx.maxArrayLength, 0); <add> const entries = previewWeakMap(value, maxArrayLength + 1); <add> // Entries exist as [key1, val1, key2, val2, ...] <add> const remainder = entries.length / 2 > maxArrayLength; <add> const len = entries.length / 2 - (remainder ? 1 : 0); <add> const maxLength = Math.min(maxArrayLength, len); <add> let output = new Array(maxLength); <add> for (var i = 0; i < len; i++) { <add> const pos = i * 2; <add> output[i] = `${formatValue(ctx, entries[pos], recurseTimes)} => ` + <add> formatValue(ctx, entries[pos + 1], recurseTimes); <add> } <add> // Sort all entries to have a halfway reliable output (if more entries than <add> // retrieved ones exist, we can not reliably return the same output). <add> output = output.sort(); <add> if (remainder > 0) <add> output.push('... more items'); <add> for (i = 0; i < keys.length; i++) <add> output.push(formatProperty(ctx, value, recurseTimes, keys[i], 0)); <add> return output; <add>} <add> <ide> function formatCollectionIterator(preview, ctx, value, recurseTimes, keys) { <ide> const output = []; <ide> for (const entry of preview(value)) { <ide><path>test/parallel/test-util-inspect.js <ide> util.inspect(process); <ide> expect = '{\n a: \'12 45 78 01 34 \' +\n \'67 90 23\'\n}'; <ide> assert.strictEqual(out, expect); <ide> } <add> <add>{ // Test WeakMap <add> const obj = {}; <add> const arr = []; <add> const weakMap = new WeakMap([[obj, arr], [arr, obj]]); <add> let out = util.inspect(weakMap, { showHidden: true }); <add> let expect = 'WeakMap { [ [length]: 0 ] => {}, {} => [ [length]: 0 ] }'; <add> assert.strictEqual(out, expect); <add> <add> out = util.inspect(weakMap); <add> expect = 'WeakMap { [items unknown] }'; <add> assert.strictEqual(out, expect); <add> <add> out = util.inspect(weakMap, { maxArrayLength: 0, showHidden: true }); <add> expect = 'WeakMap { ... more items }'; <add> assert.strictEqual(out, expect); <add> <add> weakMap.extra = true; <add> out = util.inspect(weakMap, { maxArrayLength: 1, showHidden: true }); <add> // It is not possible to determine the output reliable. <add> expect = 'WeakMap { [ [length]: 0 ] => {}, ... more items, extra: true }'; <add> const expectAlt = 'WeakMap { {} => [ [length]: 0 ], ... more items, ' + <add> 'extra: true }'; <add> assert(out === expect || out === expectAlt); <add>} <add> <add>{ // Test WeakSet <add> const weakSet = new WeakSet([{}, [1]]); <add> let out = util.inspect(weakSet, { showHidden: true }); <add> let expect = 'WeakSet { [ 1, [length]: 1 ], {} }'; <add> assert.strictEqual(out, expect); <add> <add> out = util.inspect(weakSet); <add> expect = 'WeakSet { [items unknown] }'; <add> assert.strictEqual(out, expect); <add> <add> out = util.inspect(weakSet, { maxArrayLength: -2, showHidden: true }); <add> expect = 'WeakSet { ... more items }'; <add> assert.strictEqual(out, expect); <add> <add> weakSet.extra = true; <add> out = util.inspect(weakSet, { maxArrayLength: 1, showHidden: true }); <add> // It is not possible to determine the output reliable. <add> expect = 'WeakSet { {}, ... more items, extra: true }'; <add> const expectAlt = 'WeakSet { [ 1, [length]: 1 ], ... more items, ' + <add> 'extra: true }'; <add> assert(out === expect || out === expectAlt); <add>}
5
PHP
PHP
remove mocks from belongstomany test
46847ac20747350f717eb939197bde579dfc3c65
<ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> */ <ide> class BelongsToManyTest extends TestCase <ide> { <add> /** <add> * Fixtures <add> * <add> * @var array <add> */ <add> public $fixtures = ['core.articles', 'core.special_tags', 'core.articles_tags', 'core.tags']; <ide> <ide> /** <ide> * Set up <ide> public function setUp() <ide> 'primary' => ['type' => 'primary', 'columns' => ['id']] <ide> ] <ide> ]); <del> TableRegistry::set('Articles', $this->article); <del> TableRegistry::get('ArticlesTags', [ <del> 'table' => 'articles_tags', <del> 'schema' => [ <del> 'article_id' => ['type' => 'integer'], <del> 'tag_id' => ['type' => 'integer'], <del> '_constraints' => [ <del> 'primary' => ['type' => 'primary', 'columns' => ['article_id', 'tag_id']] <del> ] <del> ] <del> ]); <del> $this->tagsTypeMap = new TypeMap([ <del> 'Tags.id' => 'integer', <del> 'id' => 'integer', <del> 'Tags.name' => 'string', <del> 'name' => 'string', <del> ]); <del> $this->articlesTagsTypeMap = new TypeMap([ <del> 'ArticlesTags.article_id' => 'integer', <del> 'article_id' => 'integer', <del> 'ArticlesTags.tag_id' => 'integer', <del> 'tag_id' => 'integer', <del> ]); <ide> } <ide> <ide> /** <ide> public function testCascadeDeleteDependent() <ide> */ <ide> public function testCascadeDeleteWithCallbacks() <ide> { <del> $articleTag = $this->getMock('Cake\ORM\Table', ['find', 'delete'], []); <add> $articleTag = TableRegistry::get('ArticlesTags'); <ide> $config = [ <ide> 'sourceTable' => $this->article, <ide> 'targetTable' => $this->tag, <ide> 'cascadeCallbacks' => true, <ide> ]; <ide> $association = new BelongsToMany('Tag', $config); <ide> $association->junction($articleTag); <del> $this->article <del> ->association($articleTag->alias()) <del> ->conditions(['click_count' => 3]); <del> <del> $articleTagOne = new Entity(['article_id' => 1, 'tag_id' => 2]); <del> $articleTagTwo = new Entity(['article_id' => 1, 'tag_id' => 4]); <del> $iterator = new \ArrayIterator([ <del> $articleTagOne, <del> $articleTagTwo <del> ]); <del> <del> $query = $this->getMock('\Cake\ORM\Query', [], [], '', false); <del> $query->expects($this->at(0)) <del> ->method('where') <del> ->with(['click_count' => 3]) <del> ->will($this->returnSelf()); <del> $query->expects($this->at(1)) <del> ->method('where') <del> ->with(['article_id' => 1]) <del> ->will($this->returnSelf()); <del> <del> $query->expects($this->any()) <del> ->method('getIterator') <del> ->will($this->returnValue($iterator)); <del> <del> $articleTag->expects($this->once()) <del> ->method('find') <del> ->will($this->returnValue($query)); <del> <del> $articleTag->expects($this->at(1)) <del> ->method('delete') <del> ->with($articleTagOne, []); <del> $articleTag->expects($this->at(2)) <del> ->method('delete') <del> ->with($articleTagTwo, []); <add> $this->article->association($articleTag->alias()); <ide> <del> $articleTag->expects($this->never()) <del> ->method('deleteAll'); <add> $counter = $this->getMock('StdClass', ['__invoke']); <add> $counter->expects($this->exactly(2))->method('__invoke'); <add> $articleTag->eventManager()->on('Model.beforeDelete', $counter); <ide> <add> $this->assertEquals(2, $articleTag->find()->where(['article_id' => 1])->count()); <ide> $entity = new Entity(['id' => 1, 'name' => 'PHP']); <ide> $association->cascadeDelete($entity); <add> <add> $this->assertEquals(0, $articleTag->find()->where(['article_id' => 1])->count()); <ide> } <ide> <ide> /** <ide> public function testUnlinkWithNotPersistedTarget() <ide> */ <ide> public function testUnlinkSuccess() <ide> { <del> $connection = ConnectionManager::get('test'); <del> $joint = $this->getMock( <del> '\Cake\ORM\Table', <del> ['delete', 'find'], <del> [['alias' => 'ArticlesTags', 'connection' => $connection]] <del> ); <del> $config = [ <del> 'sourceTable' => $this->article, <del> 'targetTable' => $this->tag, <del> 'through' => $joint, <del> 'joinTable' => 'tags_articles' <del> ]; <del> $assoc = $this->article->belongsToMany('Test', $config); <del> $assoc->junction(); <del> $this->article->association('ArticlesTags') <del> ->conditions(['foo' => 1]); <del> <del> $query1 = $this->getMock('\Cake\ORM\Query', [], [$connection, $joint]); <del> $query2 = $this->getMock('\Cake\ORM\Query', [], [$connection, $joint]); <del> <del> $joint->expects($this->at(0))->method('find') <del> ->with('all') <del> ->will($this->returnValue($query1)); <del> <del> $joint->expects($this->at(1))->method('find') <del> ->with('all') <del> ->will($this->returnValue($query2)); <del> <del> $query1->expects($this->at(0)) <del> ->method('where') <del> ->with(['foo' => 1]) <del> ->will($this->returnSelf()); <del> $query1->expects($this->at(1)) <del> ->method('where') <del> ->with(['article_id' => 1]) <del> ->will($this->returnSelf()); <del> $query1->expects($this->at(2)) <del> ->method('andWhere') <del> ->with(['tag_id' => 2]) <del> ->will($this->returnSelf()); <del> $query1->expects($this->once()) <del> ->method('union') <del> ->with($query2) <del> ->will($this->returnSelf()); <del> <del> $query2->expects($this->at(0)) <del> ->method('where') <del> ->with(['foo' => 1]) <del> ->will($this->returnSelf()); <del> $query2->expects($this->at(1)) <del> ->method('where') <del> ->with(['article_id' => 1]) <del> ->will($this->returnSelf()); <del> $query2->expects($this->at(2)) <del> ->method('andWhere') <del> ->with(['tag_id' => 3]) <del> ->will($this->returnSelf()); <del> <del> $jointEntities = [ <del> new Entity(['article_id' => 1, 'tag_id' => 2]), <del> new Entity(['article_id' => 1, 'tag_id' => 3]) <del> ]; <del> <del> $query1->expects($this->once()) <del> ->method('toArray') <del> ->will($this->returnValue($jointEntities)); <del> <del> $opts = ['markNew' => false]; <del> $tags = [new Entity(['id' => 2], $opts), new Entity(['id' => 3], $opts)]; <del> $entity = new Entity(['id' => 1, 'test' => $tags], $opts); <add> $joint = TableRegistry::get('SpecialTags'); <add> $articles = TableRegistry::get('Articles'); <add> $tags = TableRegistry::get('Tags'); <ide> <del> $joint->expects($this->at(2)) <del> ->method('delete') <del> ->with($jointEntities[0]); <add> $assoc = $articles->belongsToMany('Tags', [ <add> 'sourceTable' => $articles, <add> 'targetTable' => $tags, <add> 'through' => $joint, <add> 'joinTable' => 'special_tags', <add> ]); <add> $entity = $articles->get(2, ['contain' => 'Tags']); <add> $initial = $entity->tags; <add> $this->assertCount(1, $initial); <ide> <del> $joint->expects($this->at(3)) <del> ->method('delete') <del> ->with($jointEntities[1]); <add> $assoc->unlink($entity, $entity->tags); <add> $this->assertEmpty($entity->get('tags'), 'Property should be empty'); <ide> <del> $assoc->unlink($entity, $tags); <del> $this->assertEmpty($entity->get('test')); <add> $new = $articles->get(2, ['contain' => 'Tags']); <add> $this->assertCount(0, $new->tags, 'DB should be clean'); <add> $this->assertSame(3, $tags->find()->count(), 'Tags should still exist'); <ide> } <ide> <ide> /** <ide> public function testUnlinkSuccess() <ide> */ <ide> public function testUnlinkWithoutPropertyClean() <ide> { <del> $connection = ConnectionManager::get('test'); <del> $joint = $this->getMock( <del> '\Cake\ORM\Table', <del> ['delete', 'find'], <del> [['alias' => 'ArticlesTags', 'connection' => $connection]] <del> ); <del> $config = [ <del> 'sourceTable' => $this->article, <del> 'targetTable' => $this->tag, <del> 'through' => $joint, <del> 'joinTable' => 'tags_articles' <del> ]; <del> $assoc = new BelongsToMany('Test', $config); <del> $assoc <del> ->junction() <del> ->association('tags') <del> ->conditions(['foo' => 1]); <add> $joint = TableRegistry::get('SpecialTags'); <add> $articles = TableRegistry::get('Articles'); <add> $tags = TableRegistry::get('Tags'); <ide> <del> $joint->expects($this->never())->method('find'); <del> $opts = ['markNew' => false]; <del> $jointEntities = [ <del> new Entity(['article_id' => 1, 'tag_id' => 2]), <del> new Entity(['article_id' => 1, 'tag_id' => 3]) <del> ]; <del> $tags = [ <del> new Entity(['id' => 2, '_joinData' => $jointEntities[0]], $opts), <del> new Entity(['id' => 3, '_joinData' => $jointEntities[1]], $opts) <del> ]; <del> $entity = new Entity(['id' => 1, 'test' => $tags], $opts); <del> <del> $joint->expects($this->at(0)) <del> ->method('delete') <del> ->with($jointEntities[0]); <add> $assoc = $articles->belongsToMany('Tags', [ <add> 'sourceTable' => $articles, <add> 'targetTable' => $tags, <add> 'through' => $joint, <add> 'joinTable' => 'special_tags', <add> 'conditions' => ['SpecialTags.highlighted' => true] <add> ]); <add> $entity = $articles->get(2, ['contain' => 'Tags']); <add> $initial = $entity->tags; <add> $this->assertCount(1, $initial); <ide> <del> $joint->expects($this->at(1)) <del> ->method('delete') <del> ->with($jointEntities[1]); <add> $assoc->unlink($entity, $initial, ['cleanProperty' => false]); <add> $this->assertNotEmpty($entity->get('tags'), 'Property should not be empty'); <add> $this->assertEquals($initial, $entity->get('tags'), 'Property should be untouched'); <ide> <del> $assoc->unlink($entity, $tags, ['cleanProperty' => false]); <del> $this->assertEquals($tags, $entity->get('test')); <add> $new = $articles->get(2, ['contain' => 'Tags']); <add> $this->assertCount(0, $new->tags, 'DB should be clean'); <ide> } <ide> <ide> /** <ide> public function testReplaceWithMissingPrimaryKey() <ide> */ <ide> public function testReplaceLinksUpdateToEmptySet() <ide> { <del> $connection = ConnectionManager::get('test'); <del> $joint = $this->getMock( <del> '\Cake\ORM\Table', <del> ['delete', 'find'], <del> [['alias' => 'ArticlesTags', 'connection' => $connection]] <del> ); <del> $config = [ <del> 'sourceTable' => $this->article, <del> 'targetTable' => $this->tag, <del> 'through' => $joint, <del> 'joinTable' => 'tags_articles' <del> ]; <del> $assoc = $this->getMock( <del> '\Cake\ORM\Association\BelongsToMany', <del> ['_collectJointEntities', '_saveTarget'], <del> ['tags', $config] <del> ); <del> $assoc->junction(); <del> <del> $this->article <del> ->association('ArticlesTags') <del> ->conditions(['foo' => 1]); <del> <del> $query1 = $this->getMock( <del> '\Cake\ORM\Query', <del> ['where', 'andWhere', 'addDefaultTypes'], <del> [$connection, $joint] <del> ); <add> $joint = TableRegistry::get('ArticlesTags'); <add> $articles = TableRegistry::get('Articles'); <add> $tags = TableRegistry::get('Tags'); <ide> <del> $joint->expects($this->at(0))->method('find') <del> ->with('all') <del> ->will($this->returnValue($query1)); <del> <del> $query1->expects($this->at(0)) <del> ->method('where') <del> ->with(['foo' => 1]) <del> ->will($this->returnSelf()); <del> $query1->expects($this->at(1)) <del> ->method('where') <del> ->with(['article_id' => 1]) <del> ->will($this->returnSelf()); <del> <del> $existing = [ <del> new Entity(['article_id' => 1, 'tag_id' => 2]), <del> new Entity(['article_id' => 1, 'tag_id' => 4]), <del> ]; <del> $query1->setResult(new \ArrayIterator($existing)); <del> <del> $tags = []; <del> $entity = new Entity(['id' => 1, 'test' => $tags]); <del> <del> $assoc->expects($this->once())->method('_collectJointEntities') <del> ->with($entity, $tags) <del> ->will($this->returnValue([])); <add> $assoc = $articles->belongsToMany('Tags', [ <add> 'sourceTable' => $articles, <add> 'targetTable' => $tags, <add> 'through' => $joint, <add> 'joinTable' => 'articles_tags', <add> ]); <ide> <del> $joint->expects($this->at(1)) <del> ->method('delete') <del> ->with($existing[0]); <del> $joint->expects($this->at(2)) <del> ->method('delete') <del> ->with($existing[1]); <add> $entity = $articles->get(1, ['contain' => 'Tags']); <add> $this->assertCount(2, $entity->tags); <ide> <del> $assoc->expects($this->never()) <del> ->method('_saveTarget'); <add> $assoc->replaceLinks($entity, []); <add> $this->assertSame([], $entity->tags, 'Property should be empty'); <add> $this->assertFalse($entity->dirty('tags'), 'Property should be cleaned'); <ide> <del> $assoc->replaceLinks($entity, $tags); <del> $this->assertSame([], $entity->tags); <del> $this->assertFalse($entity->dirty('tags')); <add> $new = $articles->get(1, ['contain' => 'Tags']); <add> $this->assertSame([], $entity->tags, 'Should not be data in db'); <ide> } <ide> <ide> /** <ide> public function testReplaceLinksUpdateToEmptySet() <ide> */ <ide> public function testReplaceLinkSuccess() <ide> { <del> $connection = ConnectionManager::get('test'); <del> $joint = $this->getMock( <del> '\Cake\ORM\Table', <del> ['delete', 'find'], <del> [['alias' => 'ArticlesTags', 'connection' => $connection]] <del> ); <del> $config = [ <del> 'sourceTable' => $this->article, <del> 'targetTable' => $this->tag, <del> 'through' => $joint, <del> 'joinTable' => 'tags_articles' <del> ]; <del> $assoc = $this->getMock( <del> '\Cake\ORM\Association\BelongsToMany', <del> ['_collectJointEntities', '_saveTarget'], <del> ['tags', $config] <del> ); <del> $assoc->junction(); <del> <del> $this->article <del> ->association('ArticlesTags') <del> ->conditions(['foo' => 1]); <del> <del> $query1 = $this->getMock( <del> '\Cake\ORM\Query', <del> ['where', 'andWhere', 'addDefaultTypes'], <del> [$connection, $joint] <del> ); <del> <del> $joint->expects($this->at(0))->method('find') <del> ->with('all') <del> ->will($this->returnValue($query1)); <del> <del> $query1->expects($this->at(0)) <del> ->method('where') <del> ->with(['foo' => 1]) <del> ->will($this->returnSelf()); <del> $query1->expects($this->at(1)) <del> ->method('where') <del> ->with(['article_id' => 1]) <del> ->will($this->returnSelf()); <del> <del> $existing = [ <del> new Entity(['article_id' => 1, 'tag_id' => 2]), <del> new Entity(['article_id' => 1, 'tag_id' => 4]), <del> new Entity(['article_id' => 1, 'tag_id' => 5]), <del> new Entity(['article_id' => 1, 'tag_id' => 6]) <del> ]; <del> $query1->setResult(new \ArrayIterator($existing)); <add> $joint = TableRegistry::get('ArticlesTags'); <add> $articles = TableRegistry::get('Articles'); <add> $tags = TableRegistry::get('Tags'); <ide> <del> $opts = ['markNew' => false]; <del> $tags = [ <del> new Entity(['id' => 2], $opts), <del> new Entity(['id' => 3], $opts), <del> new Entity(['id' => 6]) <del> ]; <del> $entity = new Entity(['id' => 1, 'test' => $tags], $opts); <add> $assoc = $articles->belongsToMany('Tags', [ <add> 'sourceTable' => $articles, <add> 'targetTable' => $tags, <add> 'through' => $joint, <add> 'joinTable' => 'articles_tags', <add> ]); <add> $entity = $articles->get(1, ['contain' => 'Tags']); <ide> <del> $jointEntities = [ <del> new Entity(['article_id' => 1, 'tag_id' => 2]) <add> // 1=existing, 2=removed, 3=new link, & new tag <add> $tagData = [ <add> new Entity(['id' => 1], ['markNew' => false]), <add> new Entity(['id' => 3]), <add> new Entity(['name' => 'net new']), <ide> ]; <del> $assoc->expects($this->once())->method('_collectJointEntities') <del> ->with($entity, $tags) <del> ->will($this->returnValue($jointEntities)); <ide> <del> $joint->expects($this->at(1)) <del> ->method('delete') <del> ->with($existing[1]); <del> $joint->expects($this->at(2)) <del> ->method('delete') <del> ->with($existing[2]); <add> $assoc->replaceLinks($entity, $tagData, ['associated' => false]); <add> $this->assertSame($tagData, $entity->tags, 'Tags should match replaced objects'); <add> $this->assertFalse($entity->dirty('tags'), 'Should be clean'); <ide> <del> $options = ['foo' => 'bar']; <del> $assoc->expects($this->once()) <del> ->method('_saveTarget') <del> ->with($entity, [1 => $tags[1], 2 => $tags[2]], $options + ['associated' => false]) <del> ->will($this->returnCallback(function ($entity, $inserts) use ($tags) { <del> $this->assertSame([1 => $tags[1], 2 => $tags[2]], $inserts); <del> $entity->tags = $inserts; <del> return true; <del> })); <add> $fresh = $articles->get(1, ['contain' => 'Tags']); <add> $this->assertCount(3, $fresh->tags, 'Records should be in db'); <ide> <del> $assoc->replaceLinks($entity, $tags, $options + ['associated' => false]); <del> $this->assertSame($tags, $entity->tags); <del> $this->assertFalse($entity->dirty('tags')); <add> $this->assertNotEmpty($tags->get(2), 'Unlinked tag should still exist'); <ide> } <ide> <ide> /** <ide> * Tests that replaceLinks() will contain() the target table when <ide> * there are conditions present on the association. <ide> * <add> * In this case the replacement will fail because the association conditions <add> * hide the fixture data. <add> * <ide> * @return void <ide> */ <ide> public function testReplaceLinkWithConditions() <ide> { <del> $connection = ConnectionManager::get('test'); <del> $joint = $this->getMock( <del> '\Cake\ORM\Table', <del> ['find'], <del> [['alias' => 'ArticlesTags', 'connection' => $connection]] <del> ); <del> $config = [ <del> 'sourceTable' => $this->article, <del> 'targetTable' => $this->tag, <del> 'through' => $joint, <del> 'joinTable' => 'tags_articles', <del> 'conditions' => ['Tags.id' => 'blah'], <del> ]; <del> $assoc = $this->getMock( <del> '\Cake\ORM\Association\BelongsToMany', <del> ['_collectJointEntities'], <del> ['tags', $config] <del> ); <del> $assoc->junction(); <add> $joint = TableRegistry::get('SpecialTags'); <add> $articles = TableRegistry::get('Articles'); <add> $tags = TableRegistry::get('Tags'); <ide> <del> $query1 = $this->getMock( <del> '\Cake\ORM\Query', <del> ['where', 'andWhere', 'addDefaultTypes', 'contain'], <del> [$connection, $joint] <del> ); <del> $query1->expects($this->at(0)) <del> ->method('where') <del> ->will($this->returnSelf()); <del> $query1->expects($this->at(1)) <del> ->method('where') <del> ->will($this->returnSelf()); <del> $query1->expects($this->at(2)) <del> ->method('contain') <del> ->with('Tags') <del> ->will($this->returnSelf()); <del> $query1->expects($this->at(3)) <del> ->method('andWhere') <del> ->with($config['conditions']) <del> ->will($this->returnSelf()); <del> $query1->setResult(new \ArrayIterator([])); <del> <del> $joint->expects($this->at(0))->method('find') <del> ->with('all') <del> ->will($this->returnValue($query1)); <del> <del> $entity = new Entity(['id' => 1, 'test' => []]); <del> <del> $assoc->expects($this->once())->method('_collectJointEntities') <del> ->with($entity, []) <del> ->will($this->returnValue([])); <add> $assoc = $articles->belongsToMany('Tags', [ <add> 'sourceTable' => $articles, <add> 'targetTable' => $tags, <add> 'through' => $joint, <add> 'joinTable' => 'special_tags', <add> 'conditions' => ['SpecialTags.highlighted' => true] <add> ]); <add> $entity = $articles->get(1, ['contain' => 'Tags']); <ide> <ide> $assoc->replaceLinks($entity, [], ['associated' => false]); <add> $this->assertSame([], $entity->tags, 'Tags should match replaced objects'); <add> $this->assertFalse($entity->dirty('tags'), 'Should be clean'); <add> <add> $fresh = $articles->get(1, ['contain' => 'Tags']); <add> $this->assertCount(0, $fresh->tags, 'Association should be empty'); <add> <add> $jointCount = $joint->find()->where(['article_id' => 1])->count(); <add> $this->assertSame(1, $jointCount, 'Non matching joint record should remain.'); <ide> } <ide> <ide> /**
1
Text
Text
fix white spaces
223ed2b4832d63853b61ccb8e9ff82fcd835e61f
<ide><path>guides/source/routing.md <ide> Both methods will list all of your routes, in the same order that they appear in <ide> For example, here's a small section of the `rake routes` output for a RESTful route: <ide> <ide> ``` <del> users GET /users(.:format) users#index <add>users GET /users(.:format) users#index <ide> POST /users(.:format) users#create <del> new_user GET /users/new(.:format) users#new <add>new_user GET /users/new(.:format) users#new <ide> edit_user GET /users/:id/edit(.:format) users#edit <ide> ``` <ide>
1
Javascript
Javascript
fix error handling
4f77bb847624a337a603db2f20c2a2c0cc4cc59e
<ide><path>website/assets/js/models.js <ide> export class ModelLoader { <ide> this.renderCompat(tpl, modelId); <ide> tpl.get('download').setAttribute('href', `${this.repo}/releases/tag/${model}`); <ide> tpl.get('table').removeAttribute('data-loading'); <add> tpl.get('error').style.display = 'none'; <ide> } <ide> <ide> renderDetails(tpl, { version, size, description, notes, author, url, <ide> export class ModelComparer { <ide> } <ide> <ide> showError(err) { <del> console.error(err); <add> console.error(err || 'Error'); <ide> this.tpl.get('result').style.display = 'none'; <ide> this.tpl.get('error').style.display = 'block'; <ide> } <ide> export class ModelComparer { <ide> this.chart.update(); <ide> [model1, model2].forEach((model, i) => this.renderTable(metaKeys, i + 1, model)); <ide> this.tpl.get('result').removeAttribute('data-loading'); <add> this.tpl.get('error').style.display = 'none'; <add> this.tpl.get('result').style.display = 'block'; <ide> } <ide> <ide> renderTable(metaKeys, i, { lang, name, version, size, description,
1
Python
Python
handle precision in selected_real_kind
3c340e2b2813b4e614fc87a9cb563f68976b6cf7
<ide><path>numpy/f2py/crackfortran.py <ide> def get_parameters(vars, global_params={}): <ide> elif iscomplex(vars[n]): <ide> outmess(f'get_parameters[TODO]: ' <ide> f'implement evaluation of complex expression {v}\n') <del> <ide> try: <ide> params[n] = eval(v, g_params, params) <ide> except Exception as msg: <add> # Handle _dp for gh-6624 <add> if real16pattern.search(v): <add> v = 8 <add> elif real8pattern.search(v): <add> v = 4 <ide> params[n] = v <ide> # Don't report if the parameter is numeric gh-20460 <del> if not real16pattern.match(v): <add> if not real16pattern.search(v) and not real8pattern.search(v): <ide> outmess('get_parameters: got "%s" on %s\n' % (msg, repr(v))) <ide> if isstring(vars[n]) and isinstance(params[n], int): <ide> params[n] = chr(params[n])
1
Javascript
Javascript
fix failing test
b322d6610f1edfdaf310b43e1a8d99fde51a451a
<ide><path>server/boot/story.js <ide> module.exports = function(app) { <ide> ); <ide> } <ide> <del> function hot(req, res) { <del> return res.render('stories/index', { <del> title: 'Top Stories on Camper News', <del> page: 'hot' <del> }); <del> } <del> <ide> function submitNew(req, res) { <ide> if (!req.user.isGithubCool) { <ide> req.flash('errors', {
1
Ruby
Ruby
allow insert into <table> select queries
214af496460c3639e8963c85834ee064f203cc6b
<ide><path>lib/arel/insert_manager.rb <ide> def into table <ide> def columns; @ast.columns end <ide> def values= val; @ast.values = val; end <ide> <add> def select select <add> @ast.select = select <add> end <add> <ide> def insert fields <ide> return if fields.empty? <ide> <ide><path>lib/arel/nodes/insert_statement.rb <ide> module Arel <ide> module Nodes <ide> class InsertStatement < Arel::Nodes::Node <del> attr_accessor :relation, :columns, :values <add> attr_accessor :relation, :columns, :values, :select <ide> <ide> def initialize <ide> super() <ide> @relation = nil <ide> @columns = [] <ide> @values = nil <add> @select = nil <ide> end <ide> <ide> def initialize_copy other <ide> super <ide> @columns = @columns.clone <ide> @values = @values.clone if @values <add> @select = @select.clone if @select <ide> end <ide> <ide> def hash <del> [@relation, @columns, @values].hash <add> [@relation, @columns, @values, @select].hash <ide> end <ide> <ide> def eql? other <ide> self.class == other.class && <ide> self.relation == other.relation && <ide> self.columns == other.columns && <add> self.select == other.select && <ide> self.values == other.values <ide> end <ide> alias :== :eql? <ide><path>lib/arel/visitors/to_sql.rb <ide> def visit_Arel_Nodes_InsertStatement o, collector <ide> }.join ', '})" <ide> end <ide> <del> maybe_visit o.values, collector <add> if o.values <add> maybe_visit o.values, collector <add> elsif o.select <add> maybe_visit o.select, collector <add> else <add> collector <add> end <ide> end <ide> <ide> def visit_Arel_Nodes_Exists o, collector <ide><path>test/test_insert_manager.rb <ide> module Arel <ide> } <ide> end <ide> end <add> <add> describe "select" do <add> <add> it "accepts a select query in place of a VALUES clause" do <add> table = Table.new :users <add> <add> manager = Arel::InsertManager.new Table.engine <add> manager.into table <add> <add> select = Arel::SelectManager.new Table.engine <add> select.project Arel.sql('1') <add> select.project Arel.sql('"aaron"') <add> <add> manager.select select <add> manager.columns << table[:id] <add> manager.columns << table[:name] <add> manager.to_sql.must_be_like %{ <add> INSERT INTO "users" ("id", "name") SELECT 1, "aaron" <add> } <add> end <add> <add> end <add> <ide> end <ide> end
4
Text
Text
fix inconsistent of remote api and document
22fda380a97795cd83ad8bc4027e1bcd1ad490a6
<ide><path>docs/sources/reference/api/docker_remote_api_v1.19.md <ide> Status Codes: <ide> <ide> `GET /images/search` <ide> <del>Search for an image on [Docker Hub](https://hub.docker.com). <add>Search for an image on [Docker Hub](https://hub.docker.com). This API <add>returns both `is_trusted` and `is_automated` images. Currently, they <add>are considered identical. In the future, the `is_trusted` property will <add>be deprecated and replaced by the `is_automated` property. <ide> <ide> > **Note**: <ide> > The response keys have changed from API v1.6 to reflect the JSON <ide> Search for an image on [Docker Hub](https://hub.docker.com). <ide> HTTP/1.1 200 OK <ide> Content-Type: application/json <ide> <del> [ <del> { <del> "description": "", <del> "is_official": false, <del> "is_automated": false, <del> "name": "wma55/u1210sshd", <del> "star_count": 0 <del> }, <del> { <del> "description": "", <del> "is_official": false, <del> "is_automated": false, <del> "name": "jdswinbank/sshd", <del> "star_count": 0 <del> }, <del> { <del> "description": "", <del> "is_official": false, <del> "is_automated": false, <del> "name": "vgauthier/sshd", <del> "star_count": 0 <del> } <del> ... <del> ] <add> [ <add> { <add> "star_count": 12, <add> "is_official": false, <add> "name": "wma55/u1210sshd", <add> "is_trusted": false, <add> "is_automated": false, <add> "description": "", <add> }, <add> { <add> "star_count": 10, <add> "is_official": false, <add> "name": "jdswinbank/sshd", <add> "is_trusted": false, <add> "is_automated": false, <add> "description": "", <add> }, <add> { <add> "star_count": 18, <add> "is_official": false, <add> "name": "vgauthier/sshd", <add> "is_trusted": false, <add> "is_automated": false, <add> "description": "", <add> } <add> ... <add> ] <ide> <ide> Query Parameters: <ide>
1
Ruby
Ruby
adjust updater tests for `git config` calls
19a0aa51a1e8e5df95f9b802b165ea9ffce9cf27
<ide><path>Library/Homebrew/test/test_updater.rb <ide> def test_init_homebrew <ide> updater = RefreshBrewMock.new <ide> updater.git_repo = false <ide> updater.in_prefix_expect("git init") <add> updater.in_prefix_expect("git config core.autocrlf false") <ide> updater.in_prefix_expect("git remote add origin #{RefreshBrewMock::REPOSITORY_URL}") <ide> updater.in_prefix_expect("git fetch origin") <ide> updater.in_prefix_expect("git reset --hard origin/master") <add> updater.in_prefix_expect("git config core.autocrlf false") <ide> updater.in_prefix_expect("git pull origin refs/heads/master:refs/remotes/origin/master") <ide> updater.in_prefix_expect("git rev-parse HEAD", "1234abcd") <ide> <ide> def test_update_homebrew_without_any_changes <ide> updater.in_prefix_expect("git checkout -q master") <ide> updater.in_prefix_expect("git rev-parse HEAD", "1234abcd") <ide> updater.in_prefix_expect("git remote", "origin") <add> updater.in_prefix_expect("git config core.autocrlf false") <ide> updater.in_prefix_expect("git pull origin refs/heads/master:refs/remotes/origin/master") <ide> updater.in_prefix_expect("git rev-parse HEAD", "3456cdef") <ide> updater.in_prefix_expect("git diff-tree -r --name-status -z 1234abcd 3456cdef", "") <ide> def test_update_homebrew_without_formulae_changes <ide> updater.in_prefix_expect("git checkout -q master") <ide> updater.in_prefix_expect("git rev-parse HEAD", "1234abcd") <ide> updater.in_prefix_expect("git remote", "origin") <add> updater.in_prefix_expect("git config core.autocrlf false") <ide> updater.in_prefix_expect("git pull origin refs/heads/master:refs/remotes/origin/master") <ide> updater.in_prefix_expect("git rev-parse HEAD", "3456cdef") <ide> updater.in_prefix_expect("git diff-tree -r --name-status -z 1234abcd 3456cdef", diff_output.gsub(/\s+/, "\0")) <ide> def test_update_homebrew_with_formulae_changes <ide> updater.in_prefix_expect("git checkout -q master") <ide> updater.in_prefix_expect("git rev-parse HEAD", "1234abcd") <ide> updater.in_prefix_expect("git remote", "origin") <add> updater.in_prefix_expect("git config core.autocrlf false") <ide> updater.in_prefix_expect("git pull origin refs/heads/master:refs/remotes/origin/master") <ide> updater.in_prefix_expect("git rev-parse HEAD", "3456cdef") <ide> updater.in_prefix_expect("git diff-tree -r --name-status -z 1234abcd 3456cdef", diff_output.gsub(/\s+/, "\0"))
1
Ruby
Ruby
use getbyte and not getc
4c0545619d3aaa91f78e00a0d13e662a078a6543
<ide><path>install_homebrew.rb <ide> def sudo *args <ide> <ide> def getc # NOTE only tested on OS X <ide> system "/bin/stty raw -echo" <del> STDIN.getc <add> STDIN.getbyte <ide> ensure <ide> system "/bin/stty -raw echo" <ide> end
1
Text
Text
add trade republic to list of airflow users
84b4e6e80bd79849526401fc70d022df642ccfe1
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Deseret Digital Media](http://deseretdigital.com/) [[@formigone](https://github.com/formigone) <ide> 1. [Digital First Media](http://www.digitalfirstmedia.com/) [[@duffn](https://github.com/duffn) & [@mschmo](https://github.com/mschmo) & [@seanmuth](https://github.com/seanmuth)] <ide> 1. [DigitalOcean](https://digitalocean.com/) [[@ajbosco](https://github.com/ajbosco)] <del>1. [Digitas Pixelpark](https://www.digitaspixelpark.com/) [[@feluelle](https://github.com/feluelle)] <ide> 1. [DoorDash](https://www.doordash.com/) <ide> 1. [Dotmodus](http://dotmodus.com) [[@dannylee12](https://github.com/dannylee12)] <ide> 1. [Drivy](https://www.drivy.com) [[@AntoineAugusti](https://github.com/AntoineAugusti)] <ide> Currently, **officially** using Airflow: <ide> 1. [Tink](https://tink.com/) [[@tink-ab](https://github.com/tink-ab)] <ide> 1. [TokenAnalyst](https://github.com/tokenanalyst) [[@simonohanlon101](https://github.com/simonohanlon101), [@ankitchiplunkar](https://github.com/ankitchiplunkar), [@sidshekhar](https://github.com/sidshekhar), [@sp6pe](https://github.com/sp6pe)] <ide> 1. [Tokopedia](https://www.tokopedia.com/) [[@topedmaria](https://github.com/topedmaria)] <add>1. [Trade Republic](https://traderepublic.com/) [[@feluelle](https://github.com/feluelle)] <ide> 1. [Trocafone](https://www.trocafone.com/) [[@idontdomath](https://github.com/idontdomath) & [@gseva](https://github.com/gseva) & [@ordonezf](https://github.com/ordonezf) & [@PalmaLeandro](https://github.com/PalmaLeandro)] <ide> 1. [TruFactor](https://trufactor.io/) [[@gholmes](https://github.com/gholmes) & [@angadsingh](https://github.com/angadsingh/)] <ide> 1. [Twine Labs](https://www.twinelabs.com/) [[@ivorpeles](https://github.com/ivorpeles)]
1
Text
Text
stabilize part of asynclocalstorage
7612d82c44c3a7f7e8bf58d57541606f3e7da37b
<ide><path>doc/api/async_context.md <add># Asynchronous Context Tracking <add> <add>> Stability: 2 - Stable <add> <add><!-- source_link=lib/async_hooks.js --> <add> <add>## Introduction <add>These classes are used to associate state and propagate it throughout <add>callbacks and promise chains. <add>They allow storing data throughout the lifetime of a web request <add>or any other asynchronous duration. It is similar to thread-local storage <add>in other languages. <add> <add>The `AsyncLocalStorage` and `AsyncResource` classes are part of the <add>`async_hooks` module: <add> <add>```js <add>const async_hooks = require('async_hooks'); <add>``` <add> <add>## Class: `AsyncLocalStorage` <add><!-- YAML <add>added: <add> - v13.10.0 <add> - v12.17.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/37675 <add> description: AsyncLocalStorage is now Stable. Previously, it had been Experimental. <add>--> <add> <add>This class creates stores that stay coherent through asynchronous operations. <add> <add>While you can create your own implementation on top of the `async_hooks` module, <add>`AsyncLocalStorage` should be preferred as it is a performant and memory safe <add>implementation that involves significant optimizations that are non-obvious to <add>implement. <add> <add>The following example uses `AsyncLocalStorage` to build a simple logger <add>that assigns IDs to incoming HTTP requests and includes them in messages <add>logged within each request. <add> <add>```js <add>const http = require('http'); <add>const { AsyncLocalStorage } = require('async_hooks'); <add> <add>const asyncLocalStorage = new AsyncLocalStorage(); <add> <add>function logWithId(msg) { <add> const id = asyncLocalStorage.getStore(); <add> console.log(`${id !== undefined ? id : '-'}:`, msg); <add>} <add> <add>let idSeq = 0; <add>http.createServer((req, res) => { <add> asyncLocalStorage.run(idSeq++, () => { <add> logWithId('start'); <add> // Imagine any chain of async operations here <add> setImmediate(() => { <add> logWithId('finish'); <add> res.end(); <add> }); <add> }); <add>}).listen(8080); <add> <add>http.get('http://localhost:8080'); <add>http.get('http://localhost:8080'); <add>// Prints: <add>// 0: start <add>// 1: start <add>// 0: finish <add>// 1: finish <add>``` <add> <add>Each instance of `AsyncLocalStorage` maintains an independent storage context. <add>Multiple instances can safely exist simultaneously without risk of interfering <add>with each other data. <add> <add>### `new AsyncLocalStorage()` <add><!-- YAML <add>added: <add> - v13.10.0 <add> - v12.17.0 <add>--> <add> <add>Creates a new instance of `AsyncLocalStorage`. Store is only provided within a <add>`run()` call or after an `enterWith()` call. <add> <add>### `asyncLocalStorage.disable()` <add><!-- YAML <add>added: <add> - v13.10.0 <add> - v12.17.0 <add>--> <add> <add>> Stability: 1 - Experimental <add> <add>Disables the instance of `AsyncLocalStorage`. All subsequent calls <add>to `asyncLocalStorage.getStore()` will return `undefined` until <add>`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. <add> <add>When calling `asyncLocalStorage.disable()`, all current contexts linked to the <add>instance will be exited. <add> <add>Calling `asyncLocalStorage.disable()` is required before the <add>`asyncLocalStorage` can be garbage collected. This does not apply to stores <add>provided by the `asyncLocalStorage`, as those objects are garbage collected <add>along with the corresponding async resources. <add> <add>Use this method when the `asyncLocalStorage` is not in use anymore <add>in the current process. <add> <add>### `asyncLocalStorage.getStore()` <add><!-- YAML <add>added: <add> - v13.10.0 <add> - v12.17.0 <add>--> <add> <add>* Returns: {any} <add> <add>Returns the current store. <add>If called outside of an asynchronous context initialized by <add>calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it <add>returns `undefined`. <add> <add>### `asyncLocalStorage.enterWith(store)` <add><!-- YAML <add>added: <add> - v13.11.0 <add> - v12.17.0 <add>--> <add> <add>> Stability: 1 - Experimental <add> <add>* `store` {any} <add> <add>Transitions into the context for the remainder of the current <add>synchronous execution and then persists the store through any following <add>asynchronous calls. <add> <add>Example: <add> <add>```js <add>const store = { id: 1 }; <add>// Replaces previous store with the given store object <add>asyncLocalStorage.enterWith(store); <add>asyncLocalStorage.getStore(); // Returns the store object <add>someAsyncOperation(() => { <add> asyncLocalStorage.getStore(); // Returns the same object <add>}); <add>``` <add> <add>This transition will continue for the _entire_ synchronous execution. <add>This means that if, for example, the context is entered within an event <add>handler subsequent event handlers will also run within that context unless <add>specifically bound to another context with an `AsyncResource`. That is why <add>`run()` should be preferred over `enterWith()` unless there are strong reasons <add>to use the latter method. <add> <add>```js <add>const store = { id: 1 }; <add> <add>emitter.on('my-event', () => { <add> asyncLocalStorage.enterWith(store); <add>}); <add>emitter.on('my-event', () => { <add> asyncLocalStorage.getStore(); // Returns the same object <add>}); <add> <add>asyncLocalStorage.getStore(); // Returns undefined <add>emitter.emit('my-event'); <add>asyncLocalStorage.getStore(); // Returns the same object <add>``` <add> <add>### `asyncLocalStorage.run(store, callback[, ...args])` <add><!-- YAML <add>added: <add> - v13.10.0 <add> - v12.17.0 <add>--> <add> <add>* `store` {any} <add>* `callback` {Function} <add>* `...args` {any} <add> <add>Runs a function synchronously within a context and returns its <add>return value. The store is not accessible outside of the callback function or <add>the asynchronous operations created within the callback. <add> <add>The optional `args` are passed to the callback function. <add> <add>If the callback function throws an error, the error is thrown by `run()` too. <add>The stacktrace is not impacted by this call and the context is exited. <add> <add>Example: <add> <add>```js <add>const store = { id: 2 }; <add>try { <add> asyncLocalStorage.run(store, () => { <add> asyncLocalStorage.getStore(); // Returns the store object <add> throw new Error(); <add> }); <add>} catch (e) { <add> asyncLocalStorage.getStore(); // Returns undefined <add> // The error will be caught here <add>} <add>``` <add> <add>### `asyncLocalStorage.exit(callback[, ...args])` <add><!-- YAML <add>added: <add> - v13.10.0 <add> - v12.17.0 <add>--> <add> <add>> Stability: 1 - Experimental <add> <add>* `callback` {Function} <add>* `...args` {any} <add> <add>Runs a function synchronously outside of a context and returns its <add>return value. The store is not accessible within the callback function or <add>the asynchronous operations created within the callback. Any `getStore()` <add>call done within the callback function will always return `undefined`. <add> <add>The optional `args` are passed to the callback function. <add> <add>If the callback function throws an error, the error is thrown by `exit()` too. <add>The stacktrace is not impacted by this call and the context is re-entered. <add> <add>Example: <add> <add>```js <add>// Within a call to run <add>try { <add> asyncLocalStorage.getStore(); // Returns the store object or value <add> asyncLocalStorage.exit(() => { <add> asyncLocalStorage.getStore(); // Returns undefined <add> throw new Error(); <add> }); <add>} catch (e) { <add> asyncLocalStorage.getStore(); // Returns the same object or value <add> // The error will be caught here <add>} <add>``` <add> <add>### Usage with `async/await` <add> <add>If, within an async function, only one `await` call is to run within a context, <add>the following pattern should be used: <add> <add>```js <add>async function fn() { <add> await asyncLocalStorage.run(new Map(), () => { <add> asyncLocalStorage.getStore().set('key', value); <add> return foo(); // The return value of foo will be awaited <add> }); <add>} <add>``` <add> <add>In this example, the store is only available in the callback function and the <add>functions called by `foo`. Outside of `run`, calling `getStore` will return <add>`undefined`. <add> <add>### Troubleshooting: Context loss <add> <add>In most cases your application or library code should have no issues with <add>`AsyncLocalStorage`. But in rare cases you may face situations when the <add>current store is lost in one of the asynchronous operations. In those cases, <add>consider the following options. <add> <add>If your code is callback-based, it is enough to promisify it with <add>[`util.promisify()`][], so it starts working with native promises. <add> <add>If you need to keep using callback-based API, or your code assumes <add>a custom thenable implementation, use the [`AsyncResource`][] class <add>to associate the asynchronous operation with the correct execution context. To <add>do so, you will need to identify the function call responsible for the <add>context loss. You can do that by logging the content of <add>`asyncLocalStorage.getStore()` after the calls you suspect are responsible for <add>the loss. When the code logs `undefined`, the last callback called is probably <add>responsible for the context loss. <add> <add>## Class: `AsyncResource` <add><!-- YAML <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/37675 <add> description: AsyncResource is now Stable. Previously, it had been Experimental. <add>--> <add> <add>The class `AsyncResource` is designed to be extended by the embedder's async <add>resources. Using this, users can easily trigger the lifetime events of their <add>own resources. <add> <add>The `init` hook will trigger when an `AsyncResource` is instantiated. <add> <add>The following is an overview of the `AsyncResource` API. <add> <add>```js <add>const { AsyncResource, executionAsyncId } = require('async_hooks'); <add> <add>// AsyncResource() is meant to be extended. Instantiating a <add>// new AsyncResource() also triggers init. If triggerAsyncId is omitted then <add>// async_hook.executionAsyncId() is used. <add>const asyncResource = new AsyncResource( <add> type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } <add>); <add> <add>// Run a function in the execution context of the resource. This will <add>// * establish the context of the resource <add>// * trigger the AsyncHooks before callbacks <add>// * call the provided function `fn` with the supplied arguments <add>// * trigger the AsyncHooks after callbacks <add>// * restore the original execution context <add>asyncResource.runInAsyncScope(fn, thisArg, ...args); <add> <add>// Call AsyncHooks destroy callbacks. <add>asyncResource.emitDestroy(); <add> <add>// Return the unique ID assigned to the AsyncResource instance. <add>asyncResource.asyncId(); <add> <add>// Return the trigger ID for the AsyncResource instance. <add>asyncResource.triggerAsyncId(); <add>``` <add> <add>### `new AsyncResource(type[, options])` <add> <add>* `type` {string} The type of async event. <add>* `options` {Object} <add> * `triggerAsyncId` {number} The ID of the execution context that created this <add> async event. **Default:** `executionAsyncId()`. <add> * `requireManualDestroy` {boolean} If set to `true`, disables `emitDestroy` <add> when the object is garbage collected. This usually does not need to be set <add> (even if `emitDestroy` is called manually), unless the resource's `asyncId` <add> is retrieved and the sensitive API's `emitDestroy` is called with it. <add> When set to `false`, the `emitDestroy` call on garbage collection <add> will only take place if there is at least one active `destroy` hook. <add> **Default:** `false`. <add> <add>Example usage: <add> <add>```js <add>class DBQuery extends AsyncResource { <add> constructor(db) { <add> super('DBQuery'); <add> this.db = db; <add> } <add> <add> getInfo(query, callback) { <add> this.db.get(query, (err, data) => { <add> this.runInAsyncScope(callback, null, err, data); <add> }); <add> } <add> <add> close() { <add> this.db = null; <add> this.emitDestroy(); <add> } <add>} <add>``` <add> <add>### Static method: `AsyncResource.bind(fn[, type, [thisArg]])` <add><!-- YAML <add>added: <add> - v14.8.0 <add> - v12.19.0 <add>changes: <add> - version: v16.0.0 <add> pr-url: https://github.com/nodejs/node/pull/36782 <add> description: Added optional thisArg. <add>--> <add> <add>* `fn` {Function} The function to bind to the current execution context. <add>* `type` {string} An optional name to associate with the underlying <add> `AsyncResource`. <add>* `thisArg` {any} <add> <add>Binds the given function to the current execution context. <add> <add>The returned function will have an `asyncResource` property referencing <add>the `AsyncResource` to which the function is bound. <add> <add>### `asyncResource.bind(fn[, thisArg])` <add><!-- YAML <add>added: <add> - v14.8.0 <add> - v12.19.0 <add>changes: <add> - version: v16.0.0 <add> pr-url: https://github.com/nodejs/node/pull/36782 <add> description: Added optional thisArg. <add>--> <add> <add>* `fn` {Function} The function to bind to the current `AsyncResource`. <add>* `thisArg` {any} <add> <add>Binds the given function to execute to this `AsyncResource`'s scope. <add> <add>The returned function will have an `asyncResource` property referencing <add>the `AsyncResource` to which the function is bound. <add> <add>### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])` <add><!-- YAML <add>added: v9.6.0 <add>--> <add> <add>* `fn` {Function} The function to call in the execution context of this async <add> resource. <add>* `thisArg` {any} The receiver to be used for the function call. <add>* `...args` {any} Optional arguments to pass to the function. <add> <add>Call the provided function with the provided arguments in the execution context <add>of the async resource. This will establish the context, trigger the AsyncHooks <add>before callbacks, call the function, trigger the AsyncHooks after callbacks, and <add>then restore the original execution context. <add> <add>### `asyncResource.emitDestroy()` <add> <add>* Returns: {AsyncResource} A reference to `asyncResource`. <add> <add>Call all `destroy` hooks. This should only ever be called once. An error will <add>be thrown if it is called more than once. This **must** be manually called. If <add>the resource is left to be collected by the GC then the `destroy` hooks will <add>never be called. <add> <add>### `asyncResource.asyncId()` <add> <add>* Returns: {number} The unique `asyncId` assigned to the resource. <add> <add>### `asyncResource.triggerAsyncId()` <add> <add>* Returns: {number} The same `triggerAsyncId` that is passed to the <add> `AsyncResource` constructor. <add> <add><a id="async-resource-worker-pool"></a> <add>### Using `AsyncResource` for a `Worker` thread pool <add> <add>The following example shows how to use the `AsyncResource` class to properly <add>provide async tracking for a [`Worker`][] pool. Other resource pools, such as <add>database connection pools, can follow a similar model. <add> <add>Assuming that the task is adding two numbers, using a file named <add>`task_processor.js` with the following content: <add> <add>```js <add>const { parentPort } = require('worker_threads'); <add>parentPort.on('message', (task) => { <add> parentPort.postMessage(task.a + task.b); <add>}); <add>``` <add> <add>a Worker pool around it could use the following structure: <add> <add>```js <add>const { AsyncResource } = require('async_hooks'); <add>const { EventEmitter } = require('events'); <add>const path = require('path'); <add>const { Worker } = require('worker_threads'); <add> <add>const kTaskInfo = Symbol('kTaskInfo'); <add>const kWorkerFreedEvent = Symbol('kWorkerFreedEvent'); <add> <add>class WorkerPoolTaskInfo extends AsyncResource { <add> constructor(callback) { <add> super('WorkerPoolTaskInfo'); <add> this.callback = callback; <add> } <add> <add> done(err, result) { <add> this.runInAsyncScope(this.callback, null, err, result); <add> this.emitDestroy(); // `TaskInfo`s are used only once. <add> } <add>} <add> <add>class WorkerPool extends EventEmitter { <add> constructor(numThreads) { <add> super(); <add> this.numThreads = numThreads; <add> this.workers = []; <add> this.freeWorkers = []; <add> this.tasks = []; <add> <add> for (let i = 0; i < numThreads; i++) <add> this.addNewWorker(); <add> <add> // Any time the kWorkerFreedEvent is emitted, dispatch <add> // the next task pending in the queue, if any. <add> this.on(kWorkerFreedEvent, () => { <add> if (this.tasks.length > 0) { <add> const { task, callback } = this.tasks.shift(); <add> this.runTask(task, callback); <add> } <add> }); <add> } <add> <add> addNewWorker() { <add> const worker = new Worker(path.resolve(__dirname, 'task_processor.js')); <add> worker.on('message', (result) => { <add> // In case of success: Call the callback that was passed to `runTask`, <add> // remove the `TaskInfo` associated with the Worker, and mark it as free <add> // again. <add> worker[kTaskInfo].done(null, result); <add> worker[kTaskInfo] = null; <add> this.freeWorkers.push(worker); <add> this.emit(kWorkerFreedEvent); <add> }); <add> worker.on('error', (err) => { <add> // In case of an uncaught exception: Call the callback that was passed to <add> // `runTask` with the error. <add> if (worker[kTaskInfo]) <add> worker[kTaskInfo].done(err, null); <add> else <add> this.emit('error', err); <add> // Remove the worker from the list and start a new Worker to replace the <add> // current one. <add> this.workers.splice(this.workers.indexOf(worker), 1); <add> this.addNewWorker(); <add> }); <add> this.workers.push(worker); <add> this.freeWorkers.push(worker); <add> this.emit(kWorkerFreedEvent); <add> } <add> <add> runTask(task, callback) { <add> if (this.freeWorkers.length === 0) { <add> // No free threads, wait until a worker thread becomes free. <add> this.tasks.push({ task, callback }); <add> return; <add> } <add> <add> const worker = this.freeWorkers.pop(); <add> worker[kTaskInfo] = new WorkerPoolTaskInfo(callback); <add> worker.postMessage(task); <add> } <add> <add> close() { <add> for (const worker of this.workers) worker.terminate(); <add> } <add>} <add> <add>module.exports = WorkerPool; <add>``` <add> <add>Without the explicit tracking added by the `WorkerPoolTaskInfo` objects, <add>it would appear that the callbacks are associated with the individual `Worker` <add>objects. However, the creation of the `Worker`s is not associated with the <add>creation of the tasks and does not provide information about when tasks <add>were scheduled. <add> <add>This pool could be used as follows: <add> <add>```js <add>const WorkerPool = require('./worker_pool.js'); <add>const os = require('os'); <add> <add>const pool = new WorkerPool(os.cpus().length); <add> <add>let finished = 0; <add>for (let i = 0; i < 10; i++) { <add> pool.runTask({ a: 42, b: 100 }, (err, result) => { <add> console.log(i, err, result); <add> if (++finished === 10) <add> pool.close(); <add> }); <add>} <add>``` <add> <add>### Integrating `AsyncResource` with `EventEmitter` <add> <add>Event listeners triggered by an [`EventEmitter`][] may be run in a different <add>execution context than the one that was active when `eventEmitter.on()` was <add>called. <add> <add>The following example shows how to use the `AsyncResource` class to properly <add>associate an event listener with the correct execution context. The same <add>approach can be applied to a [`Stream`][] or a similar event-driven class. <add> <add>```js <add>const { createServer } = require('http'); <add>const { AsyncResource, executionAsyncId } = require('async_hooks'); <add> <add>const server = createServer((req, res) => { <add> req.on('close', AsyncResource.bind(() => { <add> // Execution context is bound to the current outer scope. <add> })); <add> req.on('close', () => { <add> // Execution context is bound to the scope that caused 'close' to emit. <add> }); <add> res.end(); <add>}).listen(3000); <add>``` <add>[`AsyncResource`]: #async_context_class_asyncresource <add>[`EventEmitter`]: events.md#events_class_eventemitter <add>[`Stream`]: stream.md#stream_stream <add>[`Worker`]: worker_threads.md#worker_threads_class_worker <add>[`util.promisify()`]: util.md#util_util_promisify_original <ide><path>doc/api/async_hooks.md <ide> like I/O, connection pooling, or managing callback queues may use the <ide> <ide> ### Class: `AsyncResource` <ide> <del>The class `AsyncResource` is designed to be extended by the embedder's async <del>resources. Using this, users can easily trigger the lifetime events of their <del>own resources. <del> <del>The `init` hook will trigger when an `AsyncResource` is instantiated. <del> <del>The following is an overview of the `AsyncResource` API. <del> <del>```js <del>const { AsyncResource, executionAsyncId } = require('async_hooks'); <del> <del>// AsyncResource() is meant to be extended. Instantiating a <del>// new AsyncResource() also triggers init. If triggerAsyncId is omitted then <del>// async_hook.executionAsyncId() is used. <del>const asyncResource = new AsyncResource( <del> type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } <del>); <del> <del>// Run a function in the execution context of the resource. This will <del>// * establish the context of the resource <del>// * trigger the AsyncHooks before callbacks <del>// * call the provided function `fn` with the supplied arguments <del>// * trigger the AsyncHooks after callbacks <del>// * restore the original execution context <del>asyncResource.runInAsyncScope(fn, thisArg, ...args); <del> <del>// Call AsyncHooks destroy callbacks. <del>asyncResource.emitDestroy(); <del> <del>// Return the unique ID assigned to the AsyncResource instance. <del>asyncResource.asyncId(); <del> <del>// Return the trigger ID for the AsyncResource instance. <del>asyncResource.triggerAsyncId(); <del>``` <del> <del>#### `new AsyncResource(type[, options])` <del> <del>* `type` {string} The type of async event. <del>* `options` {Object} <del> * `triggerAsyncId` {number} The ID of the execution context that created this <del> async event. **Default:** `executionAsyncId()`. <del> * `requireManualDestroy` {boolean} If set to `true`, disables `emitDestroy` <del> when the object is garbage collected. This usually does not need to be set <del> (even if `emitDestroy` is called manually), unless the resource's `asyncId` <del> is retrieved and the sensitive API's `emitDestroy` is called with it. <del> When set to `false`, the `emitDestroy` call on garbage collection <del> will only take place if there is at least one active `destroy` hook. <del> **Default:** `false`. <del> <del>Example usage: <del> <del>```js <del>class DBQuery extends AsyncResource { <del> constructor(db) { <del> super('DBQuery'); <del> this.db = db; <del> } <del> <del> getInfo(query, callback) { <del> this.db.get(query, (err, data) => { <del> this.runInAsyncScope(callback, null, err, data); <del> }); <del> } <del> <del> close() { <del> this.db = null; <del> this.emitDestroy(); <del> } <del>} <del>``` <del> <del>#### Static method: `AsyncResource.bind(fn[, type, [thisArg]])` <del><!-- YAML <del>added: <del> - v14.8.0 <del> - v12.19.0 <del>changes: <del> - version: v16.0.0 <del> pr-url: https://github.com/nodejs/node/pull/36782 <del> description: Added optional thisArg. <del>--> <del> <del>* `fn` {Function} The function to bind to the current execution context. <del>* `type` {string} An optional name to associate with the underlying <del> `AsyncResource`. <del>* `thisArg` {any} <del> <del>Binds the given function to the current execution context. <del> <del>The returned function will have an `asyncResource` property referencing <del>the `AsyncResource` to which the function is bound. <del> <del>#### `asyncResource.bind(fn[, thisArg])` <del><!-- YAML <del>added: <del> - v14.8.0 <del> - v12.19.0 <del>changes: <del> - version: v16.0.0 <del> pr-url: https://github.com/nodejs/node/pull/36782 <del> description: Added optional thisArg. <del>--> <del> <del>* `fn` {Function} The function to bind to the current `AsyncResource`. <del>* `thisArg` {any} <del> <del>Binds the given function to execute to this `AsyncResource`'s scope. <del> <del>The returned function will have an `asyncResource` property referencing <del>the `AsyncResource` to which the function is bound. <del> <del>#### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])` <del><!-- YAML <del>added: v9.6.0 <del>--> <del> <del>* `fn` {Function} The function to call in the execution context of this async <del> resource. <del>* `thisArg` {any} The receiver to be used for the function call. <del>* `...args` {any} Optional arguments to pass to the function. <del> <del>Call the provided function with the provided arguments in the execution context <del>of the async resource. This will establish the context, trigger the AsyncHooks <del>before callbacks, call the function, trigger the AsyncHooks after callbacks, and <del>then restore the original execution context. <del> <del>#### `asyncResource.emitDestroy()` <del> <del>* Returns: {AsyncResource} A reference to `asyncResource`. <del> <del>Call all `destroy` hooks. This should only ever be called once. An error will <del>be thrown if it is called more than once. This **must** be manually called. If <del>the resource is left to be collected by the GC then the `destroy` hooks will <del>never be called. <del> <del>#### `asyncResource.asyncId()` <del> <del>* Returns: {number} The unique `asyncId` assigned to the resource. <del> <del>#### `asyncResource.triggerAsyncId()` <del> <del>* Returns: {number} The same `triggerAsyncId` that is passed to the <del> `AsyncResource` constructor. <del> <del><a id="async-resource-worker-pool"></a> <del>### Using `AsyncResource` for a `Worker` thread pool <del> <del>The following example shows how to use the `AsyncResource` class to properly <del>provide async tracking for a [`Worker`][] pool. Other resource pools, such as <del>database connection pools, can follow a similar model. <del> <del>Assuming that the task is adding two numbers, using a file named <del>`task_processor.js` with the following content: <del> <del>```js <del>const { parentPort } = require('worker_threads'); <del>parentPort.on('message', (task) => { <del> parentPort.postMessage(task.a + task.b); <del>}); <del>``` <del> <del>a Worker pool around it could use the following structure: <del> <del>```js <del>const { AsyncResource } = require('async_hooks'); <del>const { EventEmitter } = require('events'); <del>const path = require('path'); <del>const { Worker } = require('worker_threads'); <del> <del>const kTaskInfo = Symbol('kTaskInfo'); <del>const kWorkerFreedEvent = Symbol('kWorkerFreedEvent'); <del> <del>class WorkerPoolTaskInfo extends AsyncResource { <del> constructor(callback) { <del> super('WorkerPoolTaskInfo'); <del> this.callback = callback; <del> } <del> <del> done(err, result) { <del> this.runInAsyncScope(this.callback, null, err, result); <del> this.emitDestroy(); // `TaskInfo`s are used only once. <del> } <del>} <del> <del>class WorkerPool extends EventEmitter { <del> constructor(numThreads) { <del> super(); <del> this.numThreads = numThreads; <del> this.workers = []; <del> this.freeWorkers = []; <del> this.tasks = []; <del> <del> for (let i = 0; i < numThreads; i++) <del> this.addNewWorker(); <del> <del> // Any time the kWorkerFreedEvent is emitted, dispatch <del> // the next task pending in the queue, if any. <del> this.on(kWorkerFreedEvent, () => { <del> if (this.tasks.length > 0) { <del> const { task, callback } = this.tasks.shift(); <del> this.runTask(task, callback); <del> } <del> }); <del> } <del> <del> addNewWorker() { <del> const worker = new Worker(path.resolve(__dirname, 'task_processor.js')); <del> worker.on('message', (result) => { <del> // In case of success: Call the callback that was passed to `runTask`, <del> // remove the `TaskInfo` associated with the Worker, and mark it as free <del> // again. <del> worker[kTaskInfo].done(null, result); <del> worker[kTaskInfo] = null; <del> this.freeWorkers.push(worker); <del> this.emit(kWorkerFreedEvent); <del> }); <del> worker.on('error', (err) => { <del> // In case of an uncaught exception: Call the callback that was passed to <del> // `runTask` with the error. <del> if (worker[kTaskInfo]) <del> worker[kTaskInfo].done(err, null); <del> else <del> this.emit('error', err); <del> // Remove the worker from the list and start a new Worker to replace the <del> // current one. <del> this.workers.splice(this.workers.indexOf(worker), 1); <del> this.addNewWorker(); <del> }); <del> this.workers.push(worker); <del> this.freeWorkers.push(worker); <del> this.emit(kWorkerFreedEvent); <del> } <del> <del> runTask(task, callback) { <del> if (this.freeWorkers.length === 0) { <del> // No free threads, wait until a worker thread becomes free. <del> this.tasks.push({ task, callback }); <del> return; <del> } <del> <del> const worker = this.freeWorkers.pop(); <del> worker[kTaskInfo] = new WorkerPoolTaskInfo(callback); <del> worker.postMessage(task); <del> } <del> <del> close() { <del> for (const worker of this.workers) worker.terminate(); <del> } <del>} <del> <del>module.exports = WorkerPool; <del>``` <del> <del>Without the explicit tracking added by the `WorkerPoolTaskInfo` objects, <del>it would appear that the callbacks are associated with the individual `Worker` <del>objects. However, the creation of the `Worker`s is not associated with the <del>creation of the tasks and does not provide information about when tasks <del>were scheduled. <del> <del>This pool could be used as follows: <del> <del>```js <del>const WorkerPool = require('./worker_pool.js'); <del>const os = require('os'); <del> <del>const pool = new WorkerPool(os.cpus().length); <del> <del>let finished = 0; <del>for (let i = 0; i < 10; i++) { <del> pool.runTask({ a: 42, b: 100 }, (err, result) => { <del> console.log(i, err, result); <del> if (++finished === 10) <del> pool.close(); <del> }); <del>} <del>``` <del> <del>### Integrating `AsyncResource` with `EventEmitter` <del> <del>Event listeners triggered by an [`EventEmitter`][] may be run in a different <del>execution context than the one that was active when `eventEmitter.on()` was <del>called. <del> <del>The following example shows how to use the `AsyncResource` class to properly <del>associate an event listener with the correct execution context. The same <del>approach can be applied to a [`Stream`][] or a similar event-driven class. <del> <del>```js <del>const { createServer } = require('http'); <del>const { AsyncResource, executionAsyncId } = require('async_hooks'); <del> <del>const server = createServer((req, res) => { <del> req.on('close', AsyncResource.bind(() => { <del> // Execution context is bound to the current outer scope. <del> })); <del> req.on('close', () => { <del> // Execution context is bound to the scope that caused 'close' to emit. <del> }); <del> res.end(); <del>}).listen(3000); <del>``` <add>The documentation for this class has moved [`AsyncResource`][]. <ide> <ide> ## Class: `AsyncLocalStorage` <del><!-- YAML <del>added: <del> - v13.10.0 <del> - v12.17.0 <del>--> <del> <del>This class is used to create asynchronous state within callbacks and promise <del>chains. It allows storing data throughout the lifetime of a web request <del>or any other asynchronous duration. It is similar to thread-local storage <del>in other languages. <del> <del>While you can create your own implementation on top of the `async_hooks` module, <del>`AsyncLocalStorage` should be preferred as it is a performant and memory safe <del>implementation that involves significant optimizations that are non-obvious to <del>implement. <del> <del>The following example uses `AsyncLocalStorage` to build a simple logger <del>that assigns IDs to incoming HTTP requests and includes them in messages <del>logged within each request. <del> <del>```js <del>const http = require('http'); <del>const { AsyncLocalStorage } = require('async_hooks'); <del> <del>const asyncLocalStorage = new AsyncLocalStorage(); <del> <del>function logWithId(msg) { <del> const id = asyncLocalStorage.getStore(); <del> console.log(`${id !== undefined ? id : '-'}:`, msg); <del>} <del> <del>let idSeq = 0; <del>http.createServer((req, res) => { <del> asyncLocalStorage.run(idSeq++, () => { <del> logWithId('start'); <del> // Imagine any chain of async operations here <del> setImmediate(() => { <del> logWithId('finish'); <del> res.end(); <del> }); <del> }); <del>}).listen(8080); <del> <del>http.get('http://localhost:8080'); <del>http.get('http://localhost:8080'); <del>// Prints: <del>// 0: start <del>// 1: start <del>// 0: finish <del>// 1: finish <del>``` <del> <del>When having multiple instances of `AsyncLocalStorage`, they are independent <del>from each other. It is safe to instantiate this class multiple times. <del> <del>### `new AsyncLocalStorage()` <del><!-- YAML <del>added: <del> - v13.10.0 <del> - v12.17.0 <del>--> <del> <del>Creates a new instance of `AsyncLocalStorage`. Store is only provided within a <del>`run()` call or after an `enterWith()` call. <del> <del>### `asyncLocalStorage.disable()` <del><!-- YAML <del>added: <del> - v13.10.0 <del> - v12.17.0 <del>--> <del> <del>Disables the instance of `AsyncLocalStorage`. All subsequent calls <del>to `asyncLocalStorage.getStore()` will return `undefined` until <del>`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. <del> <del>When calling `asyncLocalStorage.disable()`, all current contexts linked to the <del>instance will be exited. <del> <del>Calling `asyncLocalStorage.disable()` is required before the <del>`asyncLocalStorage` can be garbage collected. This does not apply to stores <del>provided by the `asyncLocalStorage`, as those objects are garbage collected <del>along with the corresponding async resources. <del> <del>Use this method when the `asyncLocalStorage` is not in use anymore <del>in the current process. <del> <del>### `asyncLocalStorage.getStore()` <del><!-- YAML <del>added: <del> - v13.10.0 <del> - v12.17.0 <del>--> <del> <del>* Returns: {any} <del> <del>Returns the current store. <del>If called outside of an asynchronous context initialized by <del>calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it <del>returns `undefined`. <del> <del>### `asyncLocalStorage.enterWith(store)` <del><!-- YAML <del>added: <del> - v13.11.0 <del> - v12.17.0 <del>--> <del> <del>* `store` {any} <del> <del>Transitions into the context for the remainder of the current <del>synchronous execution and then persists the store through any following <del>asynchronous calls. <del> <del>Example: <del> <del>```js <del>const store = { id: 1 }; <del>// Replaces previous store with the given store object <del>asyncLocalStorage.enterWith(store); <del>asyncLocalStorage.getStore(); // Returns the store object <del>someAsyncOperation(() => { <del> asyncLocalStorage.getStore(); // Returns the same object <del>}); <del>``` <del> <del>This transition will continue for the _entire_ synchronous execution. <del>This means that if, for example, the context is entered within an event <del>handler subsequent event handlers will also run within that context unless <del>specifically bound to another context with an `AsyncResource`. That is why <del>`run()` should be preferred over `enterWith()` unless there are strong reasons <del>to use the latter method. <del> <del>```js <del>const store = { id: 1 }; <del> <del>emitter.on('my-event', () => { <del> asyncLocalStorage.enterWith(store); <del>}); <del>emitter.on('my-event', () => { <del> asyncLocalStorage.getStore(); // Returns the same object <del>}); <del> <del>asyncLocalStorage.getStore(); // Returns undefined <del>emitter.emit('my-event'); <del>asyncLocalStorage.getStore(); // Returns the same object <del>``` <del> <del>### `asyncLocalStorage.run(store, callback[, ...args])` <del><!-- YAML <del>added: <del> - v13.10.0 <del> - v12.17.0 <del>--> <del> <del>* `store` {any} <del>* `callback` {Function} <del>* `...args` {any} <del> <del>Runs a function synchronously within a context and returns its <del>return value. The store is not accessible outside of the callback function. <del>The store is accessible to any asynchronous operations created within the <del>callback. <del> <del>The optional `args` are passed to the callback function. <del> <del>If the callback function throws an error, the error is thrown by `run()` too. <del>The stacktrace is not impacted by this call and the context is exited. <del> <del>Example: <del> <del>```js <del>const store = { id: 2 }; <del>try { <del> asyncLocalStorage.run(store, () => { <del> asyncLocalStorage.getStore(); // Returns the store object <del> setTimeout(() => { <del> asyncLocalStorage.getStore(); // Returns the store object <del> }, 200); <del> throw new Error(); <del> }); <del>} catch (e) { <del> asyncLocalStorage.getStore(); // Returns undefined <del> // The error will be caught here <del>} <del>``` <del> <del>### `asyncLocalStorage.exit(callback[, ...args])` <del><!-- YAML <del>added: <del> - v13.10.0 <del> - v12.17.0 <del>--> <del> <del>* `callback` {Function} <del>* `...args` {any} <del> <del>Runs a function synchronously outside of a context and returns its <del>return value. The store is not accessible within the callback function or <del>the asynchronous operations created within the callback. Any `getStore()` <del>call done within the callback function will always return `undefined`. <del> <del>The optional `args` are passed to the callback function. <del> <del>If the callback function throws an error, the error is thrown by `exit()` too. <del>The stacktrace is not impacted by this call and the context is re-entered. <del> <del>Example: <del> <del>```js <del>// Within a call to run <del>try { <del> asyncLocalStorage.getStore(); // Returns the store object or value <del> asyncLocalStorage.exit(() => { <del> asyncLocalStorage.getStore(); // Returns undefined <del> throw new Error(); <del> }); <del>} catch (e) { <del> asyncLocalStorage.getStore(); // Returns the same object or value <del> // The error will be caught here <del>} <del>``` <del> <del>### Usage with `async/await` <del> <del>If, within an async function, only one `await` call is to run within a context, <del>the following pattern should be used: <del> <del>```js <del>async function fn() { <del> await asyncLocalStorage.run(new Map(), () => { <del> asyncLocalStorage.getStore().set('key', value); <del> return foo(); // The return value of foo will be awaited <del> }); <del>} <del>``` <del> <del>In this example, the store is only available in the callback function and the <del>functions called by `foo`. Outside of `run`, calling `getStore` will return <del>`undefined`. <del> <del>### Troubleshooting <del> <del>In most cases your application or library code should have no issues with <del>`AsyncLocalStorage`. But in rare cases you may face situations when the <del>current store is lost in one of asynchronous operations. In those cases, <del>consider the following options. <del> <del>If your code is callback-based, it is enough to promisify it with <del>[`util.promisify()`][], so it starts working with native promises. <ide> <del>If you need to keep using callback-based API, or your code assumes <del>a custom thenable implementation, use the [`AsyncResource`][] class <del>to associate the asynchronous operation with the correct execution context. <add>The documentation for this class has moved [`AsyncLocalStorage`][]. <ide> <ide> [Hook Callbacks]: #async_hooks_hook_callbacks <ide> [PromiseHooks]: https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit <del>[`AsyncResource`]: #async_hooks_class_asyncresource <add>[`AsyncLocalStorage`]: async_context.md#async_context_class_asynclocalstorage <add>[`AsyncResource`]: async_context.md#async_context_class_asyncresource <ide> [`after` callback]: #async_hooks_after_asyncid <ide> [`before` callback]: #async_hooks_before_asyncid <ide> [`destroy` callback]: #async_hooks_destroy_asyncid <ide> [`init` callback]: #async_hooks_init_asyncid_type_triggerasyncid_resource <ide> [`promiseResolve` callback]: #async_hooks_promiseresolve_asyncid <del>[`EventEmitter`]: events.md#events_class_eventemitter <del>[`Stream`]: stream.md#stream_stream <ide> [`Worker`]: worker_threads.md#worker_threads_class_worker <del>[`util.promisify()`]: util.md#util_util_promisify_original <ide> [promise execution tracking]: #async_hooks_promise_execution_tracking <ide><path>doc/api/deprecations.md <ide> deprecated and should no longer be used. <ide> [`SlowBuffer`]: buffer.md#buffer_class_slowbuffer <ide> [`WriteStream.open()`]: fs.md#fs_class_fs_writestream <ide> [`assert`]: assert.md <del>[`asyncResource.runInAsyncScope()`]: async_hooks.md#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args <add>[`asyncResource.runInAsyncScope()`]: async_context.md#async_context_asyncresource_runinasyncscope_fn_thisarg_args <ide> [`child_process`]: child_process.md <ide> [`clearInterval()`]: timers.md#timers_clearinterval_timeout <ide> [`clearTimeout()`]: timers.md#timers_cleartimeout_timeout <ide><path>doc/api/index.md <ide> <hr class="line"/> <ide> <ide> * [Assertion testing](assert.md) <add>* [Async_context](async_context.md) <ide> * [Async hooks](async_hooks.md) <ide> * [Buffer](buffer.md) <ide> * [C++ addons](addons.md)
4
Mixed
Python
fix the first `nlp` call for `ja` (closes )
10189d90925b12c638d75f444b376199ea731c97
<ide><path>.github/contributors/kbulygin.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [x] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [ ] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Kirill Bulygin | <add>| Company name (if applicable) | | <add>| Title or role (if applicable) | | <add>| Date | 2018-12-18 | <add>| GitHub username | kbulygin | <add>| Website (optional) | | <ide><path>spacy/lang/ja/__init__.py <ide> def resolve_pos(token): <ide> <ide> Under Universal Dependencies, sometimes the same Unidic POS tag can <ide> be mapped differently depending on the literal token or its context <del> in the sentence. This function adds information to the POS tag to <add> in the sentence. This function adds information to the POS tag to <ide> resolve ambiguous mappings. <ide> """ <ide> <ide> def __init__(self, cls, nlp=None): <ide> <ide> MeCab = try_mecab_import() <ide> self.tokenizer = MeCab.Tagger() <add> self.tokenizer.parseToNode('') # see #2901 <ide> <ide> def __call__(self, text): <ide> dtokens = detailed_tokens(self.tokenizer, text) <ide><path>spacy/tests/regression/test_issue2901.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <add>import pytest <add> <add>from ...lang.ja import Japanese <add> <add> <add>def test_issue2901(): <add> """Test that `nlp` doesn't fail.""" <add> try: <add> nlp = Japanese() <add> except ImportError: <add> pytest.skip() <add> <add> doc = nlp("pythonが大好きです") <add> assert doc
3
Ruby
Ruby
remove the `text?` predicate from the type objects
3559230720d4ea52d290da4ff4734b5236220fcd
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb <ide> class SpecializedString < Type::String # :nodoc: <ide> def initialize(type) <ide> @type = type <ide> end <del> <del> def text? <del> false <del> end <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/type/string.rb <ide> def type <ide> :string <ide> end <ide> <del> def text? <del> true <del> end <del> <ide> def changed_in_place?(raw_old_value, new_value) <ide> if new_value.is_a?(::String) <ide> raw_old_value != new_value <ide><path>activerecord/lib/active_record/type/value.rb <ide> def type_cast_for_schema(value) # :nodoc: <ide> <ide> # These predicates are not documented, as I need to look further into <ide> # their use, and see if they can be removed entirely. <del> def text? # :nodoc: <del> false <del> end <del> <ide> def number? # :nodoc: <ide> false <ide> end <ide><path>activerecord/lib/active_record/validations/uniqueness.rb <ide> def build_relation(klass, table, attribute, value) #:nodoc: <ide> <ide> column = klass.columns_hash[attribute_name] <ide> value = klass.connection.type_cast(value, column) <del> value = value.to_s[0, column.limit] if value && column.limit && column.text? <add> if value.is_a?(String) && column.limit <add> value = value.to_s[0, column.limit] <add> end <ide> <del> if !options[:case_sensitive] && value && column.text? <add> if !options[:case_sensitive] && value.is_a?(String) <ide> # will use SQL LOWER function before comparison, unless it detects a case insensitive collation <ide> klass.connection.case_insensitive_comparison(table, attribute, column, value) <ide> else <ide><path>activerecord/test/cases/adapters/postgresql/array_test.rb <ide> def test_column <ide> assert_equal :string, @column.type <ide> assert_equal "character varying", @column.sql_type <ide> assert @column.array <del> assert_not @column.text? <ide> assert_not @column.number? <ide> assert_not @column.binary? <ide> <ide><path>activerecord/test/cases/adapters/postgresql/bit_string_test.rb <ide> def test_bit_string_column <ide> column = PostgresqlBitString.columns_hash["a_bit"] <ide> assert_equal :bit, column.type <ide> assert_equal "bit(8)", column.sql_type <del> assert_not column.text? <ide> assert_not column.number? <ide> assert_not column.binary? <ide> assert_not column.array <ide> def test_bit_string_varying_column <ide> column = PostgresqlBitString.columns_hash["a_bit_varying"] <ide> assert_equal :bit_varying, column.type <ide> assert_equal "bit varying(4)", column.sql_type <del> assert_not column.text? <ide> assert_not column.number? <ide> assert_not column.binary? <ide> assert_not column.array <ide><path>activerecord/test/cases/adapters/postgresql/citext_test.rb <ide> def test_column <ide> column = Citext.columns_hash['cival'] <ide> assert_equal :citext, column.type <ide> assert_equal 'citext', column.sql_type <del> assert_not column.text? <ide> assert_not column.number? <ide> assert_not column.binary? <ide> assert_not column.array <ide><path>activerecord/test/cases/adapters/postgresql/composite_test.rb <ide> def test_column <ide> assert_nil column.type <ide> assert_equal "full_address", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide> def test_column <ide> assert_equal :full_address, column.type <ide> assert_equal "full_address", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/domain_test.rb <ide> def test_column <ide> assert_equal :decimal, column.type <ide> assert_equal "custom_money", column.sql_type <ide> assert column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/enum_test.rb <ide> def test_column <ide> assert_equal :enum, column.type <ide> assert_equal "mood", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/full_text_test.rb <ide> def test_tsvector_column <ide> assert_equal :tsvector, column.type <ide> assert_equal "tsvector", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/geometric_test.rb <ide> def test_column <ide> column = PostgresqlPoint.columns_hash["x"] <ide> assert_equal :point, column.type <ide> assert_equal "point", column.sql_type <del> assert_not column.text? <ide> assert_not column.number? <ide> assert_not column.binary? <ide> assert_not column.array <ide><path>activerecord/test/cases/adapters/postgresql/hstore_test.rb <ide> def test_column <ide> assert_equal :hstore, @column.type <ide> assert_equal "hstore", @column.sql_type <ide> assert_not @column.number? <del> assert_not @column.text? <ide> assert_not @column.binary? <ide> assert_not @column.array <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/json_test.rb <ide> def test_column <ide> assert_equal :json, column.type <ide> assert_equal "json", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/ltree_test.rb <ide> def test_column <ide> assert_equal :ltree, column.type <ide> assert_equal "ltree", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/money_test.rb <ide> def test_column <ide> assert_equal "money", column.sql_type <ide> assert_equal 2, column.scale <ide> assert column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/network_test.rb <ide> def test_cidr_column <ide> assert_equal :cidr, column.type <ide> assert_equal "cidr", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide> def test_inet_column <ide> assert_equal :inet, column.type <ide> assert_equal "inet", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide> def test_macaddr_column <ide> assert_equal :macaddr, column.type <ide> assert_equal "macaddr", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb <ide> def test_data_type_of_uuid_types <ide> assert_equal :uuid, column.type <ide> assert_equal "uuid", column.sql_type <ide> assert_not column.number? <del> assert_not column.text? <ide> assert_not column.binary? <ide> assert_not column.array <ide> end
18
Javascript
Javascript
remove unused code
a6ab4c692fd385b338fe837587c2cd1452010482
<ide><path>packages/ember-runtime/lib/system/application.js <del>import Namespace from './namespace'; <del> <del>export default Namespace.extend(); <ide><path>packages/ember-runtime/tests/system/application/base_test.js <del>import Namespace from '../../../system/namespace'; <del>import Application from '../../../system/application'; <del>import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; <del> <del>moduleFor( <del> 'Ember.Application', <del> class extends AbstractTestCase { <del> ['@test Ember.Application should be a subclass of Ember.Namespace'](assert) { <del> assert.ok(Namespace.detect(Application), 'Ember.Application subclass of Ember.Namespace'); <del> } <del> } <del>);
2
Python
Python
use request.query_params internally
2c634c0e5cd03cb47674b0d4b76bd7494e030e36
<ide><path>rest_framework/filters.py <ide> def filter_queryset(self, request, queryset, view): <ide> filter_class = self.get_filter_class(view) <ide> <ide> if filter_class: <del> return filter_class(request.GET, queryset=queryset) <add> return filter_class(request.QUERY_PARAMS, queryset=queryset) <ide> <ide> return queryset <ide><path>rest_framework/negotiation.py <ide> def select_renderer(self, request, renderers, format_suffix=None): <ide> """ <ide> # Allow URL style format override. eg. "?format=json <ide> format_query_param = self.settings.URL_FORMAT_OVERRIDE <del> format = format_suffix or request.GET.get(format_query_param) <add> format = format_suffix or request.QUERY_PARAMS.get(format_query_param) <ide> <ide> if format: <ide> renderers = self.filter_renderers(renderers, format) <ide> def get_accept_list(self, request): <ide> Allows URL style accept override. eg. "?accept=application/json" <ide> """ <ide> header = request.META.get('HTTP_ACCEPT', '*/*') <del> header = request.GET.get(self.settings.URL_ACCEPT_OVERRIDE, header) <add> header = request.QUERY_PARAMS.get(self.settings.URL_ACCEPT_OVERRIDE, header) <ide> return [token.strip() for token in header.split(',')] <ide><path>rest_framework/renderers.py <ide> def get_callback(self, renderer_context): <ide> Determine the name of the callback to wrap around the json output. <ide> """ <ide> request = renderer_context.get('request', None) <del> params = request and request.GET or {} <add> params = request and request.QUERY_PARAMS or {} <ide> return params.get(self.callback_parameter, self.default_callback) <ide> <ide> def render(self, data, accepted_media_type=None, renderer_context=None): <ide><path>rest_framework/tests/negotiation.py <ide> from django.test import TestCase <ide> from django.test.client import RequestFactory <ide> from rest_framework.negotiation import DefaultContentNegotiation <add>from rest_framework.request import Request <add> <ide> <ide> factory = RequestFactory() <ide> <ide> def select_renderer(self, request): <ide> return self.negotiator.select_renderer(request, self.renderers) <ide> <ide> def test_client_without_accept_use_renderer(self): <del> request = factory.get('/') <add> request = Request(factory.get('/')) <ide> accepted_renderer, accepted_media_type = self.select_renderer(request) <ide> self.assertEquals(accepted_media_type, 'application/json') <ide> <ide> def test_client_underspecifies_accept_use_renderer(self): <del> request = factory.get('/', HTTP_ACCEPT='*/*') <add> request = Request(factory.get('/', HTTP_ACCEPT='*/*')) <ide> accepted_renderer, accepted_media_type = self.select_renderer(request) <ide> self.assertEquals(accepted_media_type, 'application/json') <ide> <ide> def test_client_overspecifies_accept_use_client(self): <del> request = factory.get('/', HTTP_ACCEPT='application/json; indent=8') <add> request = Request(factory.get('/', HTTP_ACCEPT='application/json; indent=8')) <ide> accepted_renderer, accepted_media_type = self.select_renderer(request) <ide> self.assertEquals(accepted_media_type, 'application/json; indent=8')
4
Ruby
Ruby
add bundle check to release task
89b7396191937134e5524bc4813b18357704ec99
<ide><path>tasks/release.rb <ide> end <ide> end <ide> <add> task :bundle do <add> sh 'bundle check' <add> end <add> <ide> task :commit do <ide> File.open('pkg/commit_message.txt', 'w') do |f| <ide> f.puts "# Preparing for #{version} release\n" <ide> sh "git push --tags" <ide> end <ide> <del> task :release => %w(ensure_clean_state build commit tag push) <add> task :release => %w(ensure_clean_state build bundle commit tag push) <ide> end
1
Javascript
Javascript
remove stripe card from donate page
5f1f5554b2930d08c5eb84c7ed3a4c122b7d7f34
<ide><path>client/src/components/Donation/DonateForm.js <ide> class DonateForm extends Component { <ide> skipAddDonation={!isSignedIn} <ide> /> <ide> </Col> <del> <del> <Col sm={10} smOffset={1} xs={12}> <del> {subscriptionPayment ? ( <del> <Fragment> <del> <Spacer /> <del> <b>Or donate with a credit card:</b> <del> <Spacer /> <del> </Fragment> <del> ) : ( <del> '' <del> )} <del> {this.renderDonationOptions()} <del> </Col> <ide> </Row> <ide> ); <ide> } <ide><path>config/donation-settings.js <ide> // Configuration for client side <ide> const durationsConfig = { <ide> year: 'yearly', <del> month: 'monthly', <del> onetime: 'one-time' <add> month: 'monthly' <ide> }; <ide> const amountsConfig = { <ide> year: [100000, 25000, 6000],
2
Java
Java
add info, and menu key event support to android tv
bb33c1050ba6098a68d70055e33186d9438c4374
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactAndroidHWInputDeviceHelper.java <ide> public class ReactAndroidHWInputDeviceHelper { <ide> .put(KeyEvent.KEYCODE_DPAD_RIGHT, "right") <ide> .put(KeyEvent.KEYCODE_DPAD_DOWN, "down") <ide> .put(KeyEvent.KEYCODE_DPAD_LEFT, "left") <add> .put(KeyEvent.KEYCODE_INFO, "info") <add> .put(KeyEvent.KEYCODE_MENU, "menu") <ide> .build(); <ide> <ide> /**
1
Ruby
Ruby
use tasks instead of comments
410d87744e699c49348d618a953591a8732c4949
<ide><path>actionpack/lib/action_controller/metal/responder.rb <ide> module ActionController #:nodoc: <ide> # <ide> # def create <ide> # @project = Project.find(params[:project_id]) <del> # @task = @project.comments.build(params[:task]) <add> # @task = @project.tasks.build(params[:task]) <ide> # respond_with(@project, @task, :status => 201) do |format| <ide> # if @task.save <ide> # flash[:notice] = 'Task was successfully created.'
1
PHP
PHP
update textarea() to use new widget features
a1a3122b24070d04b1a310f242ab6d73294ca4b5
<ide><path>src/View/Helper/FormHelper.php <ide> class FormHelper extends Helper { <ide> 'formend' => '</form>', <ide> 'hiddenblock' => '<div style="display:none;">{{content}}</div>', <ide> 'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}>', <add> 'textarea' => '<textarea name="{{name}}"{{attrs}}>{{value}}</textarea>', <ide> ]; <ide> <ide> /** <ide> public function textarea($fieldName, $options = array()) { <ide> $options = $this->_initInputField($fieldName, $options); <ide> $value = null; <ide> <del> if (array_key_exists('value', $options)) { <del> $value = $options['value']; <add> if (array_key_exists('val', $options)) { <add> $value = $options['val']; <ide> if (!array_key_exists('escape', $options) || $options['escape'] !== false) { <ide> $value = h($value); <ide> } <del> unset($options['value']); <ide> } <del> return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => null, 'name' => null)), $value); <add> unset($options['val']); <add> return $this->formatTemplate('textarea', [ <add> 'name' => $options['name'], <add> 'value' => $value, <add> 'attrs' => $this->_templater->formatAttributes($options, ['name']), <add> ]); <ide> } <ide> <ide> /** <ide> protected function _initInputField($field, $options = []) { <ide> } <ide> <ide> if (!isset($options['name'])) { <del> $options['name'] = $field; <add> $parts = explode('.', $field); <add> $first = array_shift($parts); <add> $options['name'] = $first . ($parts ? '[' . implode('][', $parts) . ']' : ''); <ide> } <ide> if (isset($options['value']) && !isset($options['val'])) { <ide> $options['val'] = $options['value']; <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testInputDateMaxYear() { <ide> * @return void <ide> */ <ide> public function testTextArea() { <del> $this->markTestIncomplete('Need to revisit once models work again.'); <del> $this->Form->request->data = array('Model' => array('field' => 'some test data')); <del> $result = $this->Form->textarea('Model.field'); <add> $this->Form->request->data = array('field' => 'some test data'); <add> $result = $this->Form->textarea('field'); <ide> $expected = array( <del> 'textarea' => array('name' => 'Model[field]', 'id' => 'ModelField'), <add> 'textarea' => array('name' => 'field'), <ide> 'some test data', <ide> '/textarea', <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> $result = $this->Form->textarea('Model.tmp'); <add> $result = $this->Form->textarea('user.bio'); <ide> $expected = array( <del> 'textarea' => array('name' => 'Model[tmp]', 'id' => 'ModelTmp'), <add> 'textarea' => array('name' => 'user[bio]'), <ide> '/textarea', <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> $this->Form->request->data = array('Model' => array('field' => 'some <strong>test</strong> data with <a href="#">HTML</a> chars')); <del> $result = $this->Form->textarea('Model.field'); <add> $this->Form->request->data = array('field' => 'some <strong>test</strong> data with <a href="#">HTML</a> chars'); <add> $result = $this->Form->textarea('field'); <ide> $expected = array( <del> 'textarea' => array('name' => 'Model[field]', 'id' => 'ModelField'), <add> 'textarea' => array('name' => 'field'), <ide> htmlentities('some <strong>test</strong> data with <a href="#">HTML</a> chars'), <ide> '/textarea', <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> $this->Form->request->data = array('Model' => array('field' => 'some <strong>test</strong> data with <a href="#">HTML</a> chars')); <del> $result = $this->Form->textarea('Model.field', array('escape' => false)); <add> $this->Form->request->data = [ <add> 'Model' => ['field' => 'some <strong>test</strong> data with <a href="#">HTML</a> chars'] <add> ]; <add> $result = $this->Form->textarea('Model.field', ['escape' => false]); <ide> $expected = array( <del> 'textarea' => array('name' => 'Model[field]', 'id' => 'ModelField'), <add> 'textarea' => array('name' => 'Model[field]'), <ide> 'some <strong>test</strong> data with <a href="#">HTML</a> chars', <ide> '/textarea', <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> $this->Form->request->data['Model']['0']['OtherModel']['field'] = null; <del> $result = $this->Form->textarea('Model.0.OtherModel.field'); <add> $result = $this->Form->textarea('0.OtherModel.field'); <ide> $expected = array( <del> 'textarea' => array('name' => 'Model[0][OtherModel][field]', 'id' => 'Model0OtherModelField'), <add> 'textarea' => array('name' => '0[OtherModel][field]'), <ide> '/textarea' <ide> ); <ide> $this->assertTags($result, $expected); <ide> public function testTextArea() { <ide> * @return void <ide> */ <ide> public function testTextAreaWithStupidCharacters() { <del> $this->markTestIncomplete('Need to revisit once models work again.'); <del> $this->loadFixtures('Post'); <del> $result = $this->Form->input('Post.content', array( <del> 'label' => 'Current Text', 'value' => "GREAT®", 'rows' => '15', 'cols' => '75' <del> )); <del> $expected = array( <del> 'div' => array('class' => 'input textarea'), <del> 'label' => array('for' => 'PostContent'), <del> 'Current Text', <del> '/label', <del> 'textarea' => array('name' => 'Post[content]', 'id' => 'PostContent', 'rows' => '15', 'cols' => '75'), <del> 'GREAT®', <del> '/textarea', <del> '/div' <del> ); <add> $result = $this->Form->textarea('Post.content', [ <add> 'value' => "GREAT®", <add> 'rows' => '15', <add> 'cols' => '75' <add> ]); <add> $expected = [ <add> 'textarea' => ['name' => 'Post[content]', 'rows' => '15', 'cols' => '75'], <add> 'GREAT®', <add> '/textarea', <add> ]; <ide> $this->assertTags($result, $expected); <ide> } <ide>
2
Python
Python
add more custom rules for abbreviations
877f09218bb5bbe268c2f2b9fe2cd6f66413c325
<ide><path>spacy/en/language_data.py <ide> "that's": [ <ide> {ORTH: "that"}, <ide> {ORTH: "'s"} <del> ] <add> ], <add> <add> "'em": [ <add> {ORTH: "'em", LEMMA: PRON_LEMMA} <add> ], <add> <add> "ol'": [ <add> {ORTH: "ol'", LEMMA: "old"} <add> ], <add> <add> "Ak.": [ <add> {ORTH: "Ak.", LEMMA: "Alaska"} <add> ], <add> <add> "Ala.": [ <add> {ORTH: "Ala.", LEMMA: "Alabama"} <add> ], <add> <add> "Apr.": [ <add> {ORTH: "Apr.", LEMMA: "April"} <add> ], <add> <add> "Ariz.": [ <add> {ORTH: "Ariz.", LEMMA: "Arizona"} <add> ], <add> <add> "Ark.": [ <add> {ORTH: "Ark.", LEMMA: "Arkansas"} <add> ], <add> <add> "Aug.": [ <add> {ORTH: "Aug.", LEMMA: "August"} <add> ], <add> <add> "Calif.": [ <add> {ORTH: "Calif.", LEMMA: "California"} <add> ], <add> <add> "Colo.": [ <add> {ORTH: "Colo.", LEMMA: "Colorado"} <add> ], <add> <add> "Conn.": [ <add> {ORTH: "Conn.", LEMMA: "Connecticut"} <add> ], <add> <add> "Dec.": [ <add> {ORTH: "Dec.", LEMMA: "December"} <add> ], <add> <add> "Del.": [ <add> {ORTH: "Del.", LEMMA: "Delaware"} <add> ], <add> <add> "Feb.": [ <add> {ORTH: "Feb.", LEMMA: "February"} <add> ], <add> <add> "Fla.": [ <add> {ORTH: "Fla.", LEMMA: "Florida"} <add> ], <add> <add> "Ga.": [ <add> {ORTH: "Ga.", LEMMA: "Georgia"} <add> ], <add> <add> "Ia.": [ <add> {ORTH: "Ia.", LEMMA: "Iowa"} <add> ], <add> <add> "Id.": [ <add> {ORTH: "Id.", LEMMA: "Idaho"} <add> ], <add> <add> "Ill.": [ <add> {ORTH: "Ill.", LEMMA: "Illinois"} <add> ], <add> <add> "Ind.": [ <add> {ORTH: "Ind.", LEMMA: "Indiana"} <add> ], <add> <add> "Jan.": [ <add> {ORTH: "Jan.", LEMMA: "January"} <add> ], <add> <add> "Jul.": [ <add> {ORTH: "Jul.", LEMMA: "July"} <add> ], <add> <add> "Jun.": [ <add> {ORTH: "Jun.", LEMMA: "June"} <add> ], <add> <add> "Kan.": [ <add> {ORTH: "Kan.", LEMMA: "Kansas"} <add> ], <add> <add> "Kans.": [ <add> {ORTH: "Kans.", LEMMA: "Kansas"} <add> ], <add> <add> "Ky.": [ <add> {ORTH: "Ky.", LEMMA: "Kentucky"} <add> ], <add> <add> "La.": [ <add> {ORTH: "La.", LEMMA: "Louisiana"} <add> ], <add> <add> "Mar.": [ <add> {ORTH: "Mar.", LEMMA: "March"} <add> ], <add> <add> "Mass.": [ <add> {ORTH: "Mass.", LEMMA: "Massachusetts"} <add> ], <add> <add> "May.": [ <add> {ORTH: "May.", LEMMA: "May"} <add> ], <add> <add> "Mich.": [ <add> {ORTH: "Mich.", LEMMA: "Michigan"} <add> ], <add> <add> "Minn.": [ <add> {ORTH: "Minn.", LEMMA: "Minnesota"} <add> ], <add> <add> "Miss.": [ <add> {ORTH: "Miss.", LEMMA: "Mississippi"} <add> ], <add> <add> "N.C.": [ <add> {ORTH: "N.C.", LEMMA: "North Carolina"} <add> ], <add> <add> "N.D.": [ <add> {ORTH: "N.D.", LEMMA: "North Dakota"} <add> ], <add> <add> "N.H.": [ <add> {ORTH: "N.H.", LEMMA: "New Hampshire"} <add> ], <add> <add> "N.J.": [ <add> {ORTH: "N.J.", LEMMA: "New Jersey"} <add> ], <add> <add> "N.M.": [ <add> {ORTH: "N.M.", LEMMA: "New Mexico"} <add> ], <add> <add> "N.Y.": [ <add> {ORTH: "N.Y.", LEMMA: "New York"} <add> ], <add> <add> "Neb.": [ <add> {ORTH: "Neb.", LEMMA: "Nebraska"} <add> ], <add> <add> "Nebr.": [ <add> {ORTH: "Nebr.", LEMMA: "Nebraska"} <add> ], <add> <add> "Nev.": [ <add> {ORTH: "Nev.", LEMMA: "Nevada"} <add> ], <add> <add> "Nov.": [ <add> {ORTH: "Nov.", LEMMA: "November"} <add> ], <add> <add> "Oct.": [ <add> {ORTH: "Oct.", LEMMA: "October"} <add> ], <add> <add> "Okla.": [ <add> {ORTH: "Okla.", LEMMA: "Oklahoma"} <add> ], <add> <add> "Ore.": [ <add> {ORTH: "Ore.", LEMMA: "Oregon"} <add> ], <add> <add> "Pa.": [ <add> {ORTH: "Pa.", LEMMA: "Pennsylvania"} <add> ], <add> <add> "S.C.": [ <add> {ORTH: "S.C.", LEMMA: "South Carolina"} <add> ], <add> <add> "Sep.": [ <add> {ORTH: "Sep.", LEMMA: "September"} <add> ], <add> <add> "Sept.": [ <add> {ORTH: "Sept.", LEMMA: "September"} <add> ], <add> <add> "Tenn.": [ <add> {ORTH: "Tenn.", LEMMA: "Tennessee"} <add> ], <add> <add> "Va.": [ <add> {ORTH: "Va.", LEMMA: "Virginia"} <add> ], <add> <add> "Wash.": [ <add> {ORTH: "Wash.", LEMMA: "Washington"} <add> ], <add> <add> "Wis.": [ <add> {ORTH: "Wis.", LEMMA: "Wisconsin"} <add> ], <ide> } <ide> <ide> <ide> self_map = [ <ide> "''", <del> "'em", <del> "'ol'", <ide> "\")", <ide> "a.", <ide> "a.m.", <ide> "Adm.", <del> "Ala.", <del> "Apr.", <del> "Ariz.", <del> "Ark.", <del> "Aug.", <ide> "b.", <ide> "Bros.", <ide> "c.", <del> "Calif.", <ide> "co.", <ide> "Co.", <del> "Colo.", <del> "Conn.", <ide> "Corp.", <ide> "d.", <ide> "D.C.", <del> "Dec.", <del> "Del.", <ide> "Dr.", <ide> "e.", <ide> "e.g.", <ide> "E.g.", <ide> "E.G.", <ide> "f.", <del> "Feb.", <del> "Fla.", <ide> "g.", <del> "Ga.", <ide> "Gen.", <ide> "Gov.", <ide> "h.", <ide> "i.", <ide> "i.e.", <ide> "I.e.", <ide> "I.E.", <del> "Ill.", <ide> "Inc.", <del> "Ind.", <ide> "j.", <del> "Jan.", <ide> "Jr.", <del> "Jul.", <del> "Jun.", <ide> "k.", <del> "Kan.", <del> "Kans.", <del> "Ky.", <ide> "l.", <del> "La.", <ide> "Ltd.", <ide> "m.", <del> "Mar.", <del> "Mass.", <del> "May." <ide> "Md.", <ide> "Messrs.", <del> "Mich.", <del> "Minn.", <del> "Miss.", <ide> "Mo.", <ide> "Mont.", <ide> "Mr.", <ide> "Mrs.", <ide> "Ms.", <ide> "n.", <del> "N.C.", <del> "N.D.", <del> "N.H.", <del> "N.J.", <del> "N.M.", <del> "N.Y.", <del> "Neb.", <del> "Nebr.", <del> "Nev.", <del> "Nov.", <ide> "o.", <del> "Oct.", <del> "Okla.", <del> "Ore.", <ide> "p.", <ide> "p.m.", <del> "Pa.", <ide> "Ph.D.", <ide> "q.", <ide> "r.", <ide> "Rep.", <ide> "Rev.", <ide> "s.", <ide> "Sen.", <del> "Sep.", <del> "Sept.", <ide> "St.", <ide> "t.", <del> "Tenn.", <ide> "u.", <ide> "v.", <del> "Va.", <ide> "vs.", <ide> "w.", <del> "Wash.", <del> "Wis.", <ide> "x.", <ide> "y.", <ide> "z."
1
Mixed
Go
allow option to override kernel check in overlay2
ff98da0607c4d6a94a2356d9ccaa64cc9d7f6a78
<ide><path>daemon/graphdriver/overlay2/overlay.go <ide> import ( <ide> "os" <ide> "os/exec" <ide> "path" <add> "strconv" <ide> "strings" <ide> "syscall" <ide> <ide> import ( <ide> "github.com/docker/docker/pkg/directory" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/mount" <add> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/parsers/kernel" <ide> <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> func init() { <ide> // If overlay filesystem is not supported on the host, graphdriver.ErrNotSupported is returned as error. <ide> // If a overlay filesystem is not supported over a existing filesystem then error graphdriver.ErrIncompatibleFS is returned. <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) { <add> opts, err := parseOptions(options) <add> if err != nil { <add> return nil, err <add> } <ide> <ide> if err := supportsOverlay(); err != nil { <ide> return nil, graphdriver.ErrNotSupported <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> return nil, err <ide> } <ide> if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 0, Minor: 0}) < 0 { <del> return nil, graphdriver.ErrNotSupported <add> if !opts.overrideKernelCheck { <add> return nil, graphdriver.ErrNotSupported <add> } <add> logrus.Warnf("Using pre-4.0.0 kernel for overlay2, mount failures may require kernel update") <ide> } <ide> <ide> fsMagic, err := graphdriver.GetFSMagic(home) <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> return d, nil <ide> } <ide> <add>type overlayOptions struct { <add> overrideKernelCheck bool <add>} <add> <add>func parseOptions(options []string) (*overlayOptions, error) { <add> o := &overlayOptions{} <add> for _, option := range options { <add> key, val, err := parsers.ParseKeyValueOpt(option) <add> if err != nil { <add> return nil, err <add> } <add> key = strings.ToLower(key) <add> switch key { <add> case "overlay2.override_kernel_check": <add> o.overrideKernelCheck, err = strconv.ParseBool(val) <add> if err != nil { <add> return nil, err <add> } <add> default: <add> return nil, fmt.Errorf("overlay2: Unknown option %s\n", key) <add> } <add> } <add> return o, nil <add>} <add> <ide> func supportsOverlay() error { <ide> // We can try to modprobe overlay first before looking at <ide> // proc/filesystems for when overlay is supported <ide><path>docs/reference/commandline/dockerd.md <ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`. <ide> Example use: <ide> $ docker daemon -s btrfs --storage-opt btrfs.min_space=10G <ide> <add>#### Overlay2 options <add> <add>* `overlay2.override_kernel_check` <add> <add> Overrides the Linux kernel version check allowing overlay2. Support for <add> specifying multiple lower directories needed by overlay2 was added to the <add> Linux kernel in 4.0.0. However some older kernel versions may be patched <add> to add multiple lower directory support for OverlayFS. This option should <add> only be used after verifying this support exists in the kernel. Applying <add> this option on a kernel without this support will cause failures on mount. <add> <ide> ## Docker runtime execution options <ide> <ide> The Docker daemon relies on a
2
Javascript
Javascript
handle input starting with control chars
35ae69682253ea51e59610a9a9e132c78f5e71d5
<ide><path>lib/readline.js <ide> function emitKey(stream, s) { <ide> key.name = 'space'; <ide> key.meta = (s.length === 2); <ide> <del> } else if (s <= '\x1a') { <add> } else if (s.length === 1 && s <= '\x1a') { <ide> // ctrl+letter <ide> key.name = String.fromCharCode(s.charCodeAt(0) + 'a'.charCodeAt(0) - 1); <ide> key.ctrl = true; <ide><path>test/simple/test-readline-interface.js <ide> FakeInput.prototype.end = function() {}; <ide> assert.equal(callCount, expectedLines.length - 1); <ide> rli.close(); <ide> <add> // \r at start of input should output blank line <add> fi = new FakeInput(); <add> rli = new readline.Interface({ input: fi, output: fi, terminal: true }); <add> expectedLines = ['', 'foo' ]; <add> callCount = 0; <add> rli.on('line', function(line) { <add> assert.equal(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> fi.emit('data', '\rfoo\r'); <add> assert.equal(callCount, expectedLines.length); <add> rli.close(); <ide> <ide> // sending a multi-byte utf8 char over multiple writes <ide> var buf = Buffer('☮', 'utf8');
2
Python
Python
fix return shape of tensorinv doc
88cf0e4f6d722b12f2d57e3acb6452d6a015cc93
<ide><path>numpy/linalg/linalg.py <ide> def tensorinv(a, ind=2): <ide> Returns <ide> ------- <ide> b : ndarray <del> `a`'s tensordot inverse, shape ``a.shape[:ind] + a.shape[ind:]``. <add> `a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``. <ide> <ide> Raises <ide> ------
1
Text
Text
fix changelog.md parsing issue
79402c0eaaaca8daa2fe3bbbd99f66b8d956bb92
<ide><path>CHANGELOG.md <ide> release. <ide> <ide> ## 2015-09-08, Version 4.0.0 (Stable), @rvagg <ide> <del><a href="doc/changelogs/CHANGELOG_V4.md#4.0.0>Moved to doc/changelogs/CHANGELOG_V6.md#6.0.0</a>. <add><a href="doc/changelogs/CHANGELOG_V4.md#4.0.0">Moved to doc/changelogs/CHANGELOG_V6.md#6.0.0</a>. <ide> <ide> ## 2015-09-02, Version 3.3.0, @rvagg <ide>
1
Javascript
Javascript
fix version check in models directory [ci skip]
1aef484985b99917dbde389e4155e0a75792a6a6
<ide><path>website/src/templates/models.js <ide> function isStableVersion(v) { <ide> function getLatestVersion(modelId, compatibility) { <ide> for (let [version, models] of Object.entries(compatibility)) { <ide> if (isStableVersion(version) && models[modelId]) { <del> return models[modelId][0] <add> const modelVersions = models[modelId] <add> for (let modelVersion of modelVersions) { <add> if (isStableVersion(modelVersion)) { <add> return modelVersion <add> } <add> } <ide> } <ide> } <ide> }
1
Python
Python
remove unused import
e8d45d1821cacac9774a66240f4c1b4736239a23
<ide><path>libcloud/test/compute/test_openstack.py <ide> OpenStackKeyPair, <ide> OpenStack_1_0_Connection, <ide> OpenStack_2_FloatingIpPool, <del> OpenStackNodeDriver, <ide> OpenStack_2_NodeDriver, <ide> OpenStack_2_PortInterfaceState, <ide> OpenStackNetwork,
1
Javascript
Javascript
remove root from "roots" list on unmount
037071c0e11fbf9e5626e95cab8ac3e1d7284659
<ide><path>src/devtools/store.js <ide> export default class Store extends EventEmitter { <ide> this._idToElement.delete(id); <ide> <ide> parentElement = ((this._idToElement.get(parentID): any): Element); <del> if (parentElement != null) { <add> if (parentElement == null) { <add> this._roots = this._roots.filter(rootID => rootID !== id); <add> } else { <ide> parentElement.children = parentElement.children.filter( <ide> childID => childID !== id <ide> );
1
PHP
PHP
defer uri language support to l4
a95b5eb4b9a6a3f6f6bcee28f20979f663963ef6
<ide><path>laravel/url.php <ide> public static function to_asset($url, $https = null) <ide> $url = str_replace($index.'/', '', $url); <ide> } <ide> <del> if (count(Config::get('application.languages')) > 0) <del> { <del> $url = str_replace(Config::get('application.language').'/', '', $url); <del> } <del> <ide> return $url; <ide> } <ide>
1
Javascript
Javascript
update grunt default, grunt test and grunt travis
23e641ab87974be4629c061f690e7ab18c2ef141
<ide><path>Gruntfile.js <ide> module.exports = function (grunt) { <ide> require('load-grunt-tasks')(grunt); <ide> <ide> // Default task. <del> grunt.registerTask('default', ['jshint', 'jscs', 'nodeunit']); <add> grunt.registerTask('default', ['lint', 'test:node']); <add> <add> // linting <add> grunt.registerTask('lint', ['jshint', 'jscs']); <ide> <ide> // test tasks <del> grunt.registerTask('test', ['test:node', 'test:browser']); <del> grunt.registerTask('test:node', ['nodeunit']); <add> grunt.registerTask('test', ['test:node']); <add> grunt.registerTask('test:node', ['transpile', 'qtest']); <ide> grunt.registerTask('test:server', ['concat', 'embedLocales', 'karma:server']); <ide> grunt.registerTask('test:browser', ['concat', 'embedLocales', 'karma:chrome', 'karma:firefox']); <ide> grunt.registerTask('test:sauce-browser', ['concat', 'embedLocales', 'env:sauceLabs', 'karma:sauce']); <ide> grunt.registerTask('test:travis-sauce-browser', ['concat', 'embedLocales', 'karma:sauce']); <ide> grunt.registerTask('test:meteor', ['exec:meteor-init', 'exec:meteor-test', 'exec:meteor-cleanup']); <ide> <ide> // travis build task <del> grunt.registerTask('build:travis', [ <del> // code style <del> 'jshint', 'jscs', <del> // node tests <del> 'test:node' <del> ]); <del> <add> grunt.registerTask('build:travis', ['default']); <ide> grunt.registerTask('meteor-publish', ['exec:meteor-init', 'exec:meteor-publish', 'exec:meteor-cleanup']); <ide> <ide> // Task to be run when releasing a new version
1
Python
Python
move package loader to _import_tools.py
2f01cc8b3c368242224f7ff63e1e5343cf890e9c
<ide><path>numpy/__init__.py <ide> except ImportError: <ide> show_core_config = None <ide> <del>class PackageLoader: <del> def __init__(self): <del> """ Manages loading NumPy packages. <del> """ <del> <del> self.parent_frame = frame = sys._getframe(1) <del> self.parent_name = eval('__name__',frame.f_globals,frame.f_locals) <del> self.parent_path = eval('__path__',frame.f_globals,frame.f_locals) <del> if not frame.f_locals.has_key('__all__'): <del> exec('__all__ = []',frame.f_globals,frame.f_locals) <del> self.parent_export_names = eval('__all__',frame.f_globals,frame.f_locals) <del> <del> self.info_modules = None <del> self.imported_packages = [] <del> self.verbose = None <del> <del> def _get_info_files(self, package_dir, parent_path, parent_package=None): <del> """ Return list of (package name,info.py file) from parent_path subdirectories. <del> """ <del> from glob import glob <del> files = glob(os.path.join(parent_path,package_dir,'info.py')) <del> for info_file in glob(os.path.join(parent_path,package_dir,'info.pyc')): <del> if info_file[:-1] not in files: <del> files.append(info_file) <del> info_files = [] <del> for info_file in files: <del> package_name = os.path.dirname(info_file[len(parent_path)+1:])\ <del> .replace(os.sep,'.') <del> if parent_package: <del> package_name = parent_package + '.' + package_name <del> info_files.append((package_name,info_file)) <del> info_files.extend(self._get_info_files('*', <del> os.path.dirname(info_file), <del> package_name)) <del> return info_files <del> <del> def _init_info_modules(self, packages=None): <del> """Initialize info_modules = {<package_name>: <package info.py module>}. <del> """ <del> import imp <del> info_files = [] <del> if packages is None: <del> for path in self.parent_path: <del> info_files.extend(self._get_info_files('*',path)) <del> else: <del> for package_name in packages: <del> package_dir = os.path.join(*package_name.split('.')) <del> for path in self.parent_path: <del> names_files = self._get_info_files(package_dir, path) <del> if names_files: <del> info_files.extend(names_files) <del> break <del> else: <del> self.warn('Package %r does not have info.py file. Ignoring.'\ <del> % package_name) <del> <del> info_modules = self.info_modules <del> for package_name,info_file in info_files: <del> if info_modules.has_key(package_name): <del> continue <del> fullname = self.parent_name +'.'+ package_name <del> if info_file[-1]=='c': <del> filedescriptor = ('.pyc','rb',2) <del> else: <del> filedescriptor = ('.py','U',1) <del> <del> try: <del> info_module = imp.load_module(fullname+'.info', <del> open(info_file,filedescriptor[1]), <del> info_file, <del> filedescriptor) <del> except Exception,msg: <del> self.error(msg) <del> info_module = None <del> <del> if info_module is None or getattr(info_module,'ignore',False): <del> info_modules.pop(package_name,None) <del> else: <del> self._init_info_modules(getattr(info_module,'depends',[])) <del> info_modules[package_name] = info_module <del> <del> return <del> <del> def _get_sorted_names(self): <del> """ Return package names sorted in the order as they should be <del> imported due to dependence relations between packages. <del> """ <del> <del> depend_dict = {} <del> for name,info_module in self.info_modules.items(): <del> depend_dict[name] = getattr(info_module,'depends',[]) <del> package_names = [] <del> <del> for name in depend_dict.keys(): <del> if not depend_dict[name]: <del> package_names.append(name) <del> del depend_dict[name] <del> <del> while depend_dict: <del> for name, lst in depend_dict.items(): <del> new_lst = [n for n in lst if depend_dict.has_key(n)] <del> if not new_lst: <del> package_names.append(name) <del> del depend_dict[name] <del> else: <del> depend_dict[name] = new_lst <del> <del> return package_names <del> <del> def __call__(self,*packages, **options): <del> """Load one or more packages into numpy's top-level namespace. <del> <del> Usage: <del> <del> This function is intended to shorten the need to import many of numpy's <del> submodules constantly with statements such as <del> <del> import numpy.linalg, numpy.fft, numpy.etc... <del> <del> Instead, you can say: <del> <del> import numpy <del> numpy.pkgload('linalg','fft',...) <del> <del> or <del> <del> numpy.pkgload() <del> <del> to load all of them in one call. <del> <del> If a name which doesn't exist in numpy's namespace is <del> given, an exception [[WHAT? ImportError, probably?]] is raised. <del> [NotImplemented] <del> <del> Inputs: <del> <del> - the names (one or more strings) of all the numpy modules one wishes to <del> load into the top-level namespace. <del> <del> Optional keyword inputs: <del> <del> - verbose - integer specifying verbosity level [default: 0]. <del> - force - when True, force reloading loaded packages [default: False]. <del> - postpone - when True, don't load packages [default: False] <del> <del> If no input arguments are given, then all of numpy's subpackages are <del> imported. <del> <del> <del> Outputs: <del> <del> The function returns a tuple with all the names of the modules which <del> were actually imported. [NotImplemented] <del> <del> """ <del> frame = self.parent_frame <del> self.info_modules = {} <del> if options.get('force',False): <del> self.imported_packages = [] <del> self.verbose = verbose = options.get('verbose',False) <del> postpone = options.get('postpone',False) <del> <del> self._init_info_modules(packages or None) <del> <del> self.log('Imports to %r namespace\n----------------------------'\ <del> % self.parent_name) <del> <del> for package_name in self._get_sorted_names(): <del> if package_name in self.imported_packages: <del> continue <del> info_module = self.info_modules[package_name] <del> global_symbols = getattr(info_module,'global_symbols',[]) <del> if postpone and not global_symbols: <del> self.log('__all__.append(%r)' % (package_name)) <del> if '.' not in package_name: <del> self.parent_export_names.append(package_name) <del> continue <del> <del> old_object = frame.f_locals.get(package_name,None) <del> <del> cmdstr = 'import '+package_name <del> if self._execcmd(cmdstr): <del> continue <del> self.imported_packages.append(package_name) <del> <del> if verbose!=-1: <del> new_object = frame.f_locals.get(package_name) <del> if old_object is not None and old_object is not new_object: <del> self.warn('Overwriting %s=%s (was %s)' \ <del> % (package_name,self._obj2str(new_object), <del> self._obj2str(old_object))) <del> <del> if '.' not in package_name: <del> self.parent_export_names.append(package_name) <del> <del> for symbol in global_symbols: <del> if symbol=='*': <del> symbols = eval('getattr(%s,"__all__",None)'\ <del> % (package_name), <del> frame.f_globals,frame.f_locals) <del> if symbols is None: <del> symbols = eval('dir(%s)' % (package_name), <del> frame.f_globals,frame.f_locals) <del> symbols = filter(lambda s:not s.startswith('_'),symbols) <del> else: <del> symbols = [symbol] <del> <del> if verbose!=-1: <del> old_objects = {} <del> for s in symbols: <del> if frame.f_locals.has_key(s): <del> old_objects[s] = frame.f_locals[s] <del> <del> cmdstr = 'from '+package_name+' import '+symbol <del> if self._execcmd(cmdstr): <del> continue <del> <del> if verbose!=-1: <del> for s,old_object in old_objects.items(): <del> new_object = frame.f_locals[s] <del> if new_object is not old_object: <del> self.warn('Overwriting %s=%s (was %s)' \ <del> % (s,self._obj2repr(new_object), <del> self._obj2repr(old_object))) <del> <del> if symbol=='*': <del> self.parent_export_names.extend(symbols) <del> else: <del> self.parent_export_names.append(symbol) <del> <del> return <del> <del> def _execcmd(self,cmdstr): <del> """ Execute command in parent_frame.""" <del> frame = self.parent_frame <del> try: <del> exec (cmdstr, frame.f_globals,frame.f_locals) <del> except Exception,msg: <del> self.error('%s -> failed: %s' % (cmdstr,msg)) <del> return True <del> else: <del> self.log('%s -> success' % (cmdstr)) <del> return <del> <del> def _obj2repr(self,obj): <del> """ Return repr(obj) with""" <del> module = getattr(obj,'__module__',None) <del> file = getattr(obj,'__file__',None) <del> if module is not None: <del> return repr(obj) + ' from ' + module <del> if file is not None: <del> return repr(obj) + ' from ' + file <del> return repr(obj) <del> <del> def log(self,mess): <del> if self.verbose>1: <del> print >> sys.stderr, str(mess) <del> def warn(self,mess): <del> if self.verbose>=0: <del> print >> sys.stderr, str(mess) <del> def error(self,mess): <del> if self.verbose!=-1: <del> print >> sys.stderr, str(mess) <del> <ide> try: <ide> import pkg_resources # activate namespace packages (manipulates __path__) <ide> except ImportError: <ide> pass <ide> <del>pkgload = PackageLoader() <add>import _import_tools <add>pkgload = _import_tools.PackageLoader() <ide> <ide> if show_core_config is None: <ide> print >> sys.stderr, 'Running from numpy core source directory.' <ide> def error(self,mess): <ide> pkgload('testing','core','lib','dft','linalg','random', <ide> verbose=NUMPY_IMPORT_VERBOSE) <ide> <del> <ide> test = ScipyTest('numpy').test <ide> __all__.append('test') <ide> <ide><path>numpy/_import_tools.py <ide> def import_packages(self, packages=None): <ide> print >> sys.stderr, msg <ide> <ide> return self._format_titles(titles) <add> <add>class PackageLoader: <add> def __init__(self): <add> """ Manages loading NumPy packages. <add> """ <add> <add> self.parent_frame = frame = sys._getframe(1) <add> self.parent_name = eval('__name__',frame.f_globals,frame.f_locals) <add> self.parent_path = eval('__path__',frame.f_globals,frame.f_locals) <add> if not frame.f_locals.has_key('__all__'): <add> exec('__all__ = []',frame.f_globals,frame.f_locals) <add> self.parent_export_names = eval('__all__',frame.f_globals,frame.f_locals) <add> <add> self.info_modules = None <add> self.imported_packages = [] <add> self.verbose = None <add> <add> def _get_info_files(self, package_dir, parent_path, parent_package=None): <add> """ Return list of (package name,info.py file) from parent_path subdirectories. <add> """ <add> from glob import glob <add> files = glob(os.path.join(parent_path,package_dir,'info.py')) <add> for info_file in glob(os.path.join(parent_path,package_dir,'info.pyc')): <add> if info_file[:-1] not in files: <add> files.append(info_file) <add> info_files = [] <add> for info_file in files: <add> package_name = os.path.dirname(info_file[len(parent_path)+1:])\ <add> .replace(os.sep,'.') <add> if parent_package: <add> package_name = parent_package + '.' + package_name <add> info_files.append((package_name,info_file)) <add> info_files.extend(self._get_info_files('*', <add> os.path.dirname(info_file), <add> package_name)) <add> return info_files <add> <add> def _init_info_modules(self, packages=None): <add> """Initialize info_modules = {<package_name>: <package info.py module>}. <add> """ <add> import imp <add> info_files = [] <add> if packages is None: <add> for path in self.parent_path: <add> info_files.extend(self._get_info_files('*',path)) <add> else: <add> for package_name in packages: <add> package_dir = os.path.join(*package_name.split('.')) <add> for path in self.parent_path: <add> names_files = self._get_info_files(package_dir, path) <add> if names_files: <add> info_files.extend(names_files) <add> break <add> else: <add> self.warn('Package %r does not have info.py file. Ignoring.'\ <add> % package_name) <add> <add> info_modules = self.info_modules <add> for package_name,info_file in info_files: <add> if info_modules.has_key(package_name): <add> continue <add> fullname = self.parent_name +'.'+ package_name <add> if info_file[-1]=='c': <add> filedescriptor = ('.pyc','rb',2) <add> else: <add> filedescriptor = ('.py','U',1) <add> <add> try: <add> info_module = imp.load_module(fullname+'.info', <add> open(info_file,filedescriptor[1]), <add> info_file, <add> filedescriptor) <add> except Exception,msg: <add> self.error(msg) <add> info_module = None <add> <add> if info_module is None or getattr(info_module,'ignore',False): <add> info_modules.pop(package_name,None) <add> else: <add> self._init_info_modules(getattr(info_module,'depends',[])) <add> info_modules[package_name] = info_module <add> <add> return <add> <add> def _get_sorted_names(self): <add> """ Return package names sorted in the order as they should be <add> imported due to dependence relations between packages. <add> """ <add> <add> depend_dict = {} <add> for name,info_module in self.info_modules.items(): <add> depend_dict[name] = getattr(info_module,'depends',[]) <add> package_names = [] <add> <add> for name in depend_dict.keys(): <add> if not depend_dict[name]: <add> package_names.append(name) <add> del depend_dict[name] <add> <add> while depend_dict: <add> for name, lst in depend_dict.items(): <add> new_lst = [n for n in lst if depend_dict.has_key(n)] <add> if not new_lst: <add> package_names.append(name) <add> del depend_dict[name] <add> else: <add> depend_dict[name] = new_lst <add> <add> return package_names <add> <add> def __call__(self,*packages, **options): <add> """Load one or more packages into numpy's top-level namespace. <add> <add> Usage: <add> <add> This function is intended to shorten the need to import many of numpy's <add> submodules constantly with statements such as <add> <add> import numpy.linalg, numpy.fft, numpy.etc... <add> <add> Instead, you can say: <add> <add> import numpy <add> numpy.pkgload('linalg','fft',...) <add> <add> or <add> <add> numpy.pkgload() <add> <add> to load all of them in one call. <add> <add> If a name which doesn't exist in numpy's namespace is <add> given, an exception [[WHAT? ImportError, probably?]] is raised. <add> [NotImplemented] <add> <add> Inputs: <add> <add> - the names (one or more strings) of all the numpy modules one wishes to <add> load into the top-level namespace. <add> <add> Optional keyword inputs: <add> <add> - verbose - integer specifying verbosity level [default: 0]. <add> - force - when True, force reloading loaded packages [default: False]. <add> - postpone - when True, don't load packages [default: False] <add> <add> If no input arguments are given, then all of numpy's subpackages are <add> imported. <add> <add> <add> Outputs: <add> <add> The function returns a tuple with all the names of the modules which <add> were actually imported. [NotImplemented] <add> <add> """ <add> frame = self.parent_frame <add> self.info_modules = {} <add> if options.get('force',False): <add> self.imported_packages = [] <add> self.verbose = verbose = options.get('verbose',False) <add> postpone = options.get('postpone',False) <add> <add> self._init_info_modules(packages or None) <add> <add> self.log('Imports to %r namespace\n----------------------------'\ <add> % self.parent_name) <add> <add> for package_name in self._get_sorted_names(): <add> if package_name in self.imported_packages: <add> continue <add> info_module = self.info_modules[package_name] <add> global_symbols = getattr(info_module,'global_symbols',[]) <add> if postpone and not global_symbols: <add> self.log('__all__.append(%r)' % (package_name)) <add> if '.' not in package_name: <add> self.parent_export_names.append(package_name) <add> continue <add> <add> old_object = frame.f_locals.get(package_name,None) <add> <add> cmdstr = 'import '+package_name <add> if self._execcmd(cmdstr): <add> continue <add> self.imported_packages.append(package_name) <add> <add> if verbose!=-1: <add> new_object = frame.f_locals.get(package_name) <add> if old_object is not None and old_object is not new_object: <add> self.warn('Overwriting %s=%s (was %s)' \ <add> % (package_name,self._obj2str(new_object), <add> self._obj2str(old_object))) <add> <add> if '.' not in package_name: <add> self.parent_export_names.append(package_name) <add> <add> for symbol in global_symbols: <add> if symbol=='*': <add> symbols = eval('getattr(%s,"__all__",None)'\ <add> % (package_name), <add> frame.f_globals,frame.f_locals) <add> if symbols is None: <add> symbols = eval('dir(%s)' % (package_name), <add> frame.f_globals,frame.f_locals) <add> symbols = filter(lambda s:not s.startswith('_'),symbols) <add> else: <add> symbols = [symbol] <add> <add> if verbose!=-1: <add> old_objects = {} <add> for s in symbols: <add> if frame.f_locals.has_key(s): <add> old_objects[s] = frame.f_locals[s] <add> <add> cmdstr = 'from '+package_name+' import '+symbol <add> if self._execcmd(cmdstr): <add> continue <add> <add> if verbose!=-1: <add> for s,old_object in old_objects.items(): <add> new_object = frame.f_locals[s] <add> if new_object is not old_object: <add> self.warn('Overwriting %s=%s (was %s)' \ <add> % (s,self._obj2repr(new_object), <add> self._obj2repr(old_object))) <add> <add> if symbol=='*': <add> self.parent_export_names.extend(symbols) <add> else: <add> self.parent_export_names.append(symbol) <add> <add> return <add> <add> def _execcmd(self,cmdstr): <add> """ Execute command in parent_frame.""" <add> frame = self.parent_frame <add> try: <add> exec (cmdstr, frame.f_globals,frame.f_locals) <add> except Exception,msg: <add> self.error('%s -> failed: %s' % (cmdstr,msg)) <add> return True <add> else: <add> self.log('%s -> success' % (cmdstr)) <add> return <add> <add> def _obj2repr(self,obj): <add> """ Return repr(obj) with""" <add> module = getattr(obj,'__module__',None) <add> file = getattr(obj,'__file__',None) <add> if module is not None: <add> return repr(obj) + ' from ' + module <add> if file is not None: <add> return repr(obj) + ' from ' + file <add> return repr(obj) <add> <add> def log(self,mess): <add> if self.verbose>1: <add> print >> sys.stderr, str(mess) <add> def warn(self,mess): <add> if self.verbose>=0: <add> print >> sys.stderr, str(mess) <add> def error(self,mess): <add> if self.verbose!=-1: <add> print >> sys.stderr, str(mess) <add>
2
Javascript
Javascript
add renderer prop in onbeforecompile
a4b8c30be485b4ff661c60151f84ecb57e441227
<ide><path>src/renderers/WebGLRenderer.js <ide> function WebGLRenderer( parameters ) { <ide> name: material.type, <ide> uniforms: UniformsUtils.clone( shader.uniforms ), <ide> vertexShader: shader.vertexShader, <del> fragmentShader: shader.fragmentShader <add> fragmentShader: shader.fragmentShader, <add> renderer: _this <ide> }; <ide> <ide> } else { <ide> function WebGLRenderer( parameters ) { <ide> name: material.type, <ide> uniforms: material.uniforms, <ide> vertexShader: material.vertexShader, <del> fragmentShader: material.fragmentShader <add> fragmentShader: material.fragmentShader, <add> renderer: _this <ide> }; <ide> <ide> }
1
Javascript
Javascript
update jstime to last call
08c338eebf67ef6c8c8fb7e3a91bbf89bbc2bb4c
<ide><path>Libraries/Utilities/createPerformanceLogger.js <ide> type Timespan = { <ide> export type IPerformanceLogger = { <ide> addTimespan(string, number, string | void): void, <ide> startTimespan(string, string | void): void, <del> stopTimespan(string): void, <add> stopTimespan(string, options?: {update?: boolean}): void, <ide> clear(): void, <ide> clearCompleted(): void, <ide> clearExceptTimespans(Array<string>): void, <ide> function createPerformanceLogger(): IPerformanceLogger { <ide> } <ide> }, <ide> <del> stopTimespan(key: string) { <add> stopTimespan(key: string, options?: {update?: boolean}) { <ide> const timespan = this._timespans[key]; <ide> if (!timespan || !timespan.startTime) { <ide> if (PRINT_TO_CONSOLE && __DEV__) { <ide> function createPerformanceLogger(): IPerformanceLogger { <ide> } <ide> return; <ide> } <del> if (timespan.endTime) { <add> if (timespan.endTime && !options?.update) { <ide> if (PRINT_TO_CONSOLE && __DEV__) { <ide> infoLog( <ide> 'PerformanceLogger: Attempting to end a timespan that has already ended ', <ide> function createPerformanceLogger(): IPerformanceLogger { <ide> infoLog('PerformanceLogger.js', 'end: ' + key); <ide> } <ide> <del> Systrace.endAsyncEvent(key, _cookies[key]); <del> delete _cookies[key]; <add> if (_cookies[key] != null) { <add> Systrace.endAsyncEvent(key, _cookies[key]); <add> delete _cookies[key]; <add> } <ide> }, <ide> <ide> clear() {
1
Ruby
Ruby
pass -s to du instead of -d0
9a4567c2f971320fa63cef3b5e31638a0177aae6
<ide><path>Library/Homebrew/extend/pathname.rb <ide> def abv <ide> out='' <ide> n=`find #{to_s} -type f ! -name .DS_Store | wc -l`.to_i <ide> out<<"#{n} files, " if n > 1 <del> out<<`/usr/bin/du -hd0 #{to_s} | cut -d"\t" -f1`.strip <add> out<<`/usr/bin/du -hs #{to_s} | cut -d"\t" -f1`.strip <ide> end <ide> <ide> def version
1
Javascript
Javascript
test shallow copy of mock controller bindings
c01b1f47c0c4651305bd5a7e7536df7d090003e7
<ide><path>test/ngMock/angular-mocksSpec.js <ide> describe('ngMock', function() { <ide> module(function($controllerProvider) { <ide> $controllerProvider.register('testCtrl', function() { <ide> called = true; <del> expect(this.data).toEqual(data); <add> expect(this.data).toBe(data); <ide> }); <ide> }); <ide> inject(function($controller, $rootScope) {
1
Text
Text
remove stale links
bcc12c2d88f45e621d69fd8366ff87a6fde6a857
<ide><path>README.md <ide> or are automatically applied via regex from your webpack configuration. <ide> | <a href="https://github.com/TypeStrong/ts-loader"><img width="48" height="48" src="https://cdn.rawgit.com/Microsoft/TypeScript/master/doc/logo.svg"></a> | ![type-npm] | ![type-size] | Loads TypeScript like JavaScript | <ide> | <a href="https://github.com/webpack-contrib/coffee-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a> | ![coffee-npm] | ![coffee-size] | Loads CoffeeScript like JavaScript | <ide> <del>[script-npm]: https://img.shields.io/npm/v/script-loader.svg <del>[script-size]: https://packagephobia.com/badge?p=script-loader <ide> [babel-npm]: https://img.shields.io/npm/v/babel-loader.svg <ide> [babel-size]: https://packagephobia.com/badge?p=babel-loader <ide> [traceur-npm]: https://img.shields.io/npm/v/traceur-loader.svg <ide> or are automatically applied via regex from your webpack configuration. <ide> [coffee-size]: https://packagephobia.com/badge?p=coffee-loader <ide> [type-npm]: https://img.shields.io/npm/v/ts-loader.svg <ide> [type-size]: https://packagephobia.com/badge?p=ts-loader <del>[awesome-typescript-npm]: https://img.shields.io/npm/v/awesome-typescript-loader.svg <del>[awesome-typescript-size]: https://packagephobia.com/badge?p=awesome-typescript-loader <ide> <ide> #### Templating <ide>
1
Javascript
Javascript
add support for timeout in cancellable actions
d641901be6887cdd93dc678eb514366eb759d21e
<ide><path>src/ngResource/resource.js <ide> function shallowClearAndCopy(src, dst) { <ide> * @requires $http <ide> * @requires ng.$log <ide> * @requires $q <add> * @requires $timeout <ide> * <ide> * @description <ide> * A factory which creates a resource object that lets you interact with <ide> function shallowClearAndCopy(src, dst) { <ide> * will be cancelled (if not already completed) by calling `$cancelRequest()` on the call's <ide> * return value. Calling `$cancelRequest()` for a non-cancellable or an already <ide> * completed/cancelled request will have no effect.<br /> <del> * **Note:** If a timeout is specified in millisecondes, `cancellable` is ignored. <ide> * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the <ide> * XHR object. See <ide> * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5) <ide> angular.module('ngResource', ['ng']). <ide> } <ide> }; <ide> <del> this.$get = ['$http', '$log', '$q', function($http, $log, $q) { <add> this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) { <ide> <ide> var noop = angular.noop, <ide> forEach = angular.forEach, <ide> angular.module('ngResource', ['ng']). <ide> <ide> forEach(actions, function(action, name) { <ide> var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); <del> var cancellable = false; <del> <del> if (!angular.isNumber(action.timeout)) { <del> if (action.timeout) { <del> $log.debug('ngResource:\n' + <del> ' Only numeric values are allowed as `timeout`.\n' + <del> ' Promises are not supported in $resource, because the same value would ' + <del> 'be used for multiple requests. If you are looking for a way to cancel ' + <del> 'requests, you should use the `cancellable` option.'); <del> delete action.timeout; <del> } <del> cancellable = angular.isDefined(action.cancellable) ? action.cancellable : <del> (options && angular.isDefined(options.cancellable)) ? options.cancellable : <del> provider.defaults.cancellable; <add> var numericTimeout = action.timeout; <add> var cancellable = angular.isDefined(action.cancellable) ? action.cancellable : <add> (options && angular.isDefined(options.cancellable)) ? options.cancellable : <add> provider.defaults.cancellable; <add> <add> if (numericTimeout && !angular.isNumber(numericTimeout)) { <add> $log.debug('ngResource:\n' + <add> ' Only numeric values are allowed as `timeout`.\n' + <add> ' Promises are not supported in $resource, because the same value would ' + <add> 'be used for multiple requests. If you are looking for a way to cancel ' + <add> 'requests, you should use the `cancellable` option.'); <add> delete action.timeout; <add> numericTimeout = null; <ide> } <ide> <ide> Resource[name] = function(a1, a2, a3, a4) { <ide> angular.module('ngResource', ['ng']). <ide> var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || <ide> undefined; <ide> var timeoutDeferred; <add> var numericTimeoutPromise; <ide> <ide> forEach(action, function(value, key) { <ide> switch (key) { <ide> angular.module('ngResource', ['ng']). <ide> if (!isInstanceCall && cancellable) { <ide> timeoutDeferred = $q.defer(); <ide> httpConfig.timeout = timeoutDeferred.promise; <add> <add> if (numericTimeout) { <add> numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout); <add> } <ide> } <ide> <ide> if (hasBody) httpConfig.data = data; <ide> angular.module('ngResource', ['ng']). <ide> value.$resolved = true; <ide> if (!isInstanceCall && cancellable) { <ide> value.$cancelRequest = angular.noop; <del> timeoutDeferred = httpConfig.timeout = null; <add> $timeout.cancel(numericTimeoutPromise); <add> timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null; <ide> } <ide> }); <ide> <ide><path>test/ngResource/resourceSpec.js <ide> describe('cancelling requests', function() { <ide> var httpSpy; <ide> var $httpBackend; <ide> var $resource; <add> var $timeout; <ide> <ide> beforeEach(module('ngResource', function($provide) { <ide> $provide.decorator('$http', function($delegate) { <ide> describe('cancelling requests', function() { <ide> }); <ide> })); <ide> <del> beforeEach(inject(function(_$httpBackend_, _$resource_) { <add> beforeEach(inject(function(_$httpBackend_, _$resource_, _$timeout_) { <ide> $httpBackend = _$httpBackend_; <ide> $resource = _$resource_; <add> $timeout = _$timeout_; <ide> })); <ide> <ide> it('should accept numeric timeouts in actions and pass them to $http', function() { <ide> describe('cancelling requests', function() { <ide> expect(creditCard3.$cancelRequest).toBeUndefined(); <ide> }); <ide> <del> it('should not make the request cancellable if there is a timeout', function() { <add> it('should accept numeric timeouts in cancellable actions and cancel the request when timeout occurs', function() { <add> $httpBackend.whenGET('/CreditCard').respond({}); <add> <ide> var CreditCard = $resource('/CreditCard', {}, { <ide> get: { <ide> method: 'GET', <ide> describe('cancelling requests', function() { <ide> } <ide> }); <ide> <del> var creditCard = CreditCard.get(); <add> CreditCard.get(); <add> $timeout.flush(); <add> expect($httpBackend.flush).toThrow(new Error('No pending request to flush !')); <add> <add> CreditCard.get(); <add> expect($httpBackend.flush).not.toThrow(); <ide> <del> expect(creditCard.$cancelRequest).toBeUndefined(); <ide> }); <ide> <ide> it('should cancel the request (if cancellable), when calling `$cancelRequest`', function() { <ide> describe('cancelling requests', function() { <ide> expect($httpBackend.flush).not.toThrow(); <ide> }); <ide> <add> it('should cancel the request, when calling `$cancelRequest` in cancellable actions with timeout defined', function() { <add> $httpBackend.whenGET('/CreditCard').respond({}); <add> <add> var CreditCard = $resource('/CreditCard', {}, { <add> get: { <add> method: 'GET', <add> timeout: 10000, <add> cancellable: true <add> } <add> }); <add> <add> CreditCard.get().$cancelRequest(); <add> expect($httpBackend.flush).toThrow(new Error('No pending request to flush !')); <add> <add> CreditCard.get(); <add> expect($httpBackend.flush).not.toThrow(); <add> }); <add> <ide> it('should reset `$cancelRequest` after the response arrives', function() { <ide> $httpBackend.whenGET('/CreditCard').respond({}); <ide>
2
Ruby
Ruby
fix interpolation for hash merging
ef1d1e1492e3c48884f7653103bc9313dd04cfad
<ide><path>activerecord/lib/active_record/relation/merger.rb <ide> <ide> module ActiveRecord <ide> class Relation <del> class Merger <del> attr_reader :relation, :other <add> class HashMerger <add> attr_reader :relation, :hash <ide> <del> def initialize(relation, other) <del> @relation = relation <add> def initialize(relation, hash) <add> hash.assert_valid_keys(*Relation::VALUE_METHODS) <ide> <del> if other.default_scoped? && other.klass != relation.klass <del> @other = other.with_default_scope <del> else <del> @other = other <del> end <add> @relation = relation <add> @hash = hash <ide> end <ide> <ide> def merge <del> HashMerger.new(relation, other.values).merge <add> Merger.new(relation, other).merge <add> end <add> <add> # Applying values to a relation has some side effects. E.g. <add> # interpolation might take place for where values. So we should <add> # build a relation to merge in rather than directly merging <add> # the values. <add> def other <add> other = Relation.new(relation.klass, relation.table) <add> hash.each { |k, v| other.send("#{k}!", v) } <add> other <ide> end <ide> end <ide> <del> class HashMerger <add> class Merger <ide> attr_reader :relation, :values <ide> <del> def initialize(relation, values) <del> values.assert_valid_keys(*Relation::VALUE_METHODS) <add> def initialize(relation, other) <add> if other.default_scoped? && other.klass != relation.klass <add> other = other.with_default_scope <add> end <ide> <ide> @relation = relation <del> @values = values <add> @values = other.values <ide> end <ide> <ide> def normal_values <ide> def merged_binds <ide> <ide> def merged_wheres <ide> if values[:where] <del> merged_wheres = relation.where_values + Array(values[:where]) <add> merged_wheres = relation.where_values + values[:where] <ide> <ide> unless relation.where_values.empty? <ide> # Remove duplicates, last one wins. <ide><path>activerecord/lib/active_record/relation/spawn_methods.rb <ide> def merge(other) <ide> end <ide> <ide> def merge!(other) <del> if other.is_a?(Hash) <del> Relation::HashMerger.new(self, other).merge <del> else <del> Relation::Merger.new(self, other).merge <del> end <add> klass = other.is_a?(Hash) ? Relation::HashMerger : Relation::Merger <add> klass.new(self, other).merge <ide> end <ide> <ide> # Removes from the query the condition(s) specified in +skips+. <ide><path>activerecord/test/cases/relation_test.rb <ide> def test_references_values_dont_duplicate <ide> <ide> test 'merging a hash into a relation' do <ide> relation = Relation.new :a, :b <del> relation = relation.merge where: ['lol'], readonly: true <add> relation = relation.merge where: :lol, readonly: true <ide> <del> assert_equal ['lol'], relation.where_values <add> assert_equal [:lol], relation.where_values <ide> assert_equal true, relation.readonly_value <ide> end <ide> <ide> def test_references_values_dont_duplicate <ide> relation.merge!(where: :foo) <ide> assert_equal [:foo], relation.where_values <ide> end <add> <add> test 'merging a hash interpolates conditions' do <add> klass = stub <add> klass.stubs(:sanitize_sql).with(['foo = ?', 'bar']).returns('foo = bar') <add> <add> relation = Relation.new(klass, :b) <add> relation.merge!(where: ['foo = ?', 'bar']) <add> assert_equal ['foo = bar'], relation.where_values <add> end <ide> end <ide> <ide> class RelationMutationTest < ActiveSupport::TestCase <ide> def relation <ide> end <ide> <ide> test 'merge!' do <del> assert relation.merge!(where: ['foo']).equal?(relation) <del> assert_equal ['foo'], relation.where_values <add> assert relation.merge!(where: :foo).equal?(relation) <add> assert_equal [:foo], relation.where_values <ide> end <ide> end <ide> end
3
Text
Text
add services guide to manage a swarm
861d4dc989ae738a1c219291a96333a7577b1699
<ide><path>docs/swarm/services.md <add><!--[metadata]> <add>+++ <add>title = "Deploy services to a swarm" <add>description = "Deploy services to a swarm" <add>keywords = ["guide", "swarm mode", "swarm", "service"] <add>[menu.main] <add>identifier="services-guide" <add>parent="engine_swarm" <add>weight=15 <add>+++ <add><![end-metadata]--> <add> <add># Deploy services to a swarm <add> <add>When you are running Docker Engine in swarm mode, you run <add>`docker service create` to deploy your application in the swarm. The swarm <add>manager accepts the service description as the desired state for your <add>application. The built-in swarm orchestrator and scheduler deploy your <add>application to nodes in your swarm to achieve and maintain the desired state. <add> <add>For an overview of how services work, refer to [How services work](how-swarm-mode-works/services.md). <add> <add>This guide assumes you are working with the Docker Engine running in swarm <add>mode. You must run all `docker service` commands from a manager node. <add> <add>If you haven't already, read through [Swarm mode key concepts](key-concepts.md) <add>and [How services work](how-swarm-mode-works/services.md). <add> <add>## Create a service <add> <add>To create the simplest type of service in a swarm, you only need to supply <add>a container image: <add> <add>```bash <add>$ docker service create <IMAGE> <add>``` <add> <add>The swarm orchestrator schedules one task on an available node. The task invokes <add>a container based upon the image. For example, you could run the following <add>command to create a service of one instance of an nginx web server: <add> <add>```bash <add>$ docker service create --name my_web nginx <add> <add>anixjtol6wdfn6yylbkrbj2nx <add>``` <add> <add>In this example the `--name` flag names the service `my_web`. <add> <add>To list the service, run `docker service ls` from a manager node: <add> <add>```bash <add>$ docker service ls <add> <add>ID NAME REPLICAS IMAGE COMMAND <add>anixjtol6wdf my_web 1/1 nginx <add>``` <add> <add>To make the web server accessible from outside the swarm, you need to <add>[publish the port](#publish-ports-externally-to-the-swarm) where the swarm <add>listens for web requests. <add> <add>You can include a command to run inside containers after the image: <add> <add>```bash <add>$ docker service create <IMAGE> <COMMAND> <add>``` <add> <add>For example to start an `alpine` image that runs `ping docker.com`: <add> <add>```bash <add>$ docker service create --name helloworld alpine ping docker.com <add> <add>9uk4639qpg7npwf3fn2aasksr <add>``` <add> <add>## Configure the runtime environment <add> <add>You can configure the following options for the runtime environment in the <add>container: <add> <add>* environment variables using the `--env` flag <add>* the working directory inside the container using the `--workdir` flag <add>* the username or UID using the `--user` flag <add> <add>For example: <add> <add>```bash <add>$ docker service create --name helloworld \ <add> --env MYVAR=myvalue \ <add> --workdir /tmp \ <add> --user my_user \ <add> alpine ping docker.com <add> <add>9uk4639qpg7npwf3fn2aasksr <add>``` <add> <add>## Control service scale and placement <add> <add>Swarm mode has two types of services, replicated and global. For replicated <add>services, you specify the number of replica tasks for the swarm manager to <add>schedule onto available nodes. For global services, the scheduler places one <add>task on each available node. <add> <add>You control the type of service using the `--mode` flag. If you don't specify a <add>mode, the service defaults to `replicated`. For replicated services, you specify <add>the number of replica tasks you want to start using the `--replicas` flag. For <add>example, to start a replicated nginx service with 3 replica tasks: <add> <add>```bash <add>$ docker service create --name my_web --replicas 3 nginx <add>``` <add> <add>To start a global service on each available node, pass `--mode global` to <add>`docker service create`. Every time a new node becomes available, the scheduler <add>places a task for the global service on the new node. For example to start a <add>service that runs alpine on every node in the swarm: <add> <add>```bash <add>$ docker service create --name myservice --mode global alpine top <add>``` <add> <add>Service constraints let you set criteria for a node to meet before the scheduler <add>deploys a service to the node. You can apply constraints to the <add>service based upon node attributes and metadata or engine metadata. For more <add>information on constraints, refer to the `docker service create` [CLI reference](../reference/commandline/service_create.md). <add> <add> <add>## Configure service networking options <add> <add>Swarm mode lets you network services in a couple of ways: <add> <add>* publish ports externally to the swarm using ingress networking <add>* connect services and tasks within the swarm using overlay networks <add> <add>### Publish ports externally to the swarm <add> <add>You publish service ports externally to the swarm using the `--publish <add><TARGET-PORT>:<SERVICE-PORT>` flag. When you publish a service port, the swarm <add>makes the service accessible at the target port on every node regardless if <add>there is a task for the service running on the node. <add> <add>For example, imagine you want to deploy a 3-replica nginx service to a 10-node <add>swarm as follows: <add> <add>```bash <add>docker service create --name my_web --replicas 3 --publish 8080:80 nginx <add>``` <add> <add>The scheduler will deploy nginx tasks to a maximum of 3 nodes. However, the <add>swarm makes nginx port 80 from the task container accessible at port 8080 on any <add>node in the swarm. You can direct `curl` at port 8080 of any node in the swarm <add>to access the web server: <add> <add>```bash <add>$ curl localhost:8080 <add> <add><!DOCTYPE html> <add><html> <add><head> <add><title>Welcome to nginx!</title> <add><style> <add> body { <add> width: 35em; <add> margin: 0 auto; <add> font-family: Tahoma, Verdana, Arial, sans-serif; <add> } <add></style> <add></head> <add><body> <add><h1>Welcome to nginx!</h1> <add><p>If you see this page, the nginx web server is successfully installed and <add>working. Further configuration is required.</p> <add> <add><p>For online documentation and support please refer to <add><a href="http://nginx.org/">nginx.org</a>.<br/> <add>Commercial support is available at <add><a href="http://nginx.com/">nginx.com</a>.</p> <add> <add><p><em>Thank you for using nginx.</em></p> <add></body> <add></html> <add>``` <add> <add>### Add an overlay network <add> <add>Use overlay networks to connect one or more services within the swarm. <add> <add>First, create an overlay network on a manager node the `docker network create` <add>command: <add> <add>```bash <add>$ docker network create --driver overlay my-network <add> <add>etjpu59cykrptrgw0z0hk5snf <add>``` <add> <add>After you create an overlay network in swarm mode, all manager nodes have access <add>to the network. <add> <add>When you create a service and pass the `--network` flag to attach the service to <add>the overlay network: <add> <add>```bash <add>$ docker service create \ <add> --replicas 3 \ <add> --network my-multi-host-network \ <add> --name my-web \ <add> nginx <add> <add>716thylsndqma81j6kkkb5aus <add>``` <add> <add>The swarm extends `my-network` to each node running the service. <add> <add><!-- TODO when overlay-security-model is published <add>For more information, refer to [Note on Docker 1.12 Overlay Network Security Model](../userguide/networking/overlay-security-model.md).--> <add> <add>## Configure update behavior <add> <add>When you create a service, you can specify a rolling update behavior for how the <add>swarm should apply changes to the service when you run `docker service update`. <add>You can also specify these flags as part of the update, as arguments to <add>`docker service update`. <add> <add>The `--update-delay` flag configures the time delay between updates to a service <add>task or sets of tasks. You can describe the time `T` as a combination of the <add>number of seconds `Ts`, minutes `Tm`, or hours `Th`. So `10m30s` indicates a 10 <add>minute 30 second delay. <add> <add>By default the scheduler updates 1 task at a time. You can pass the <add>`--update-parallelism` flag to configure the maximum number of service tasks <add>that the scheduler updates simultaneously. <add> <add>When an update to an individual task returns a state of `RUNNING`, the scheduler <add>continues the update by continuing to another task until all tasks are updated. <add>If, at any time during an update a task returns `FAILED`, the scheduler pauses <add>the update. You can control the behavior using the `--update-failure-action` <add>flag for `docker service create` or `docker service update`. <add> <add>In the example service below, the scheduler applies updates to a maximum of 2 <add>replicas at a time. When an updated task returns either `RUNNING` or `FAILED`, <add>the scheduler waits 10 seconds before stopping the next task to update: <add> <add>```bash <add>$ docker service create \ <add> --replicas 10 \ <add> --name my_web \ <add> --update-delay 10s \ <add> --update-parallelism 2 \ <add> --update-failure-action continue \ <add> alpine <add> <add>0u6a4s31ybk7yw2wyvtikmu50 <add>``` <add> <add>## Configure mounts <add> <add>You can create two types of mounts for services in a swarm, `volume` mounts or <add>`bind` mounts. You pass the `--mount` flag when you create a service. The <add>default is a volume mount if you don't specify a type. <add> <add>* Volumes are storage that remain alive after a container for a task has <add>been removed. The preferred method to mount volumes is to leverage an existing <add>volume: <add> <add>```bash <add>$ docker service create \ <add> --mount src=<VOLUME-NAME>,dst=<CONTAINER-PATH> \ <add> --name myservice \ <add> <IMAGE> <add>``` <add> <add>For more information on how to create a volume, see the `volume create` [CLI reference](../reference/commandline/volume_create.md). <add> <add>The following method creates the volume at deployment time when the scheduler <add>dispatches a task, just before the starting the container: <add> <add>```bash <add>$ docker service create \ <add> --mount type=volume,src=<VOLUME-NAME>,dst=<CONTAINER-PATH>,volume-driver=<DRIVER>,volume-opt=<KEY0>=<VALUE0>,volume-opt=<KEY1>=<VALUE1> <add> --name myservice \ <add> <IMAGE> <add>``` <add> <add>* Bind mounts are file system paths from the host where the scheduler deploys <add>the container for the task. Docker mounts the path into the container. The <add>file system path must exist before the swarm initializes the container for the <add>task. <add> <add>The following examples show bind mount syntax: <add> <add>```bash <add># Mount a read-write bind <add>$ docker service create \ <add> --mount type=bind,src=<HOST-PATH>,dst=<CONTAINER-PATH> \ <add> --name myservice \ <add> <IMAGE> <add> <add># Mount a read-only bind <add>$ docker service create \ <add> --mount type=bind,src=<HOST-PATH>,dst=<CONTAINER-PATH>,readonly \ <add> --name myservice \ <add> <IMAGE> <add>``` <add> <add>>**Important note:** Bind mounts can be useful but they are also dangerous. In <add>most cases, we recommend that you architect your application such that mounting <add>paths from the host is unnecessary. The main risks include the following:<br /> <add>> <br /> <add>> If you bind mount a host path into your service’s containers, the path <add>> must exist on every machine. The Docker swarm mode scheduler can schedule <add>> containers on any machine that meets resource availability requirements <add>> and satisfies all `--constraint`s you specify.<br /> <add>> <br /> <add>> The Docker swarm mode scheduler may reschedule your running service <add>> containers at any time if they become unhealthy or unreachable.<br /> <add>> <br /> <add>> Host bind mounts are completely non-portable. When you use bind mounts, <add>> there is no guarantee that your application will run the same way in <add>> development as it does in production. <add> <add> <add>## Learn More <add> <add>* [Swarm administration guide](admin_guide.md) <add>* [Docker Engine command line reference](../reference/commandline/index.md) <add>* [Swarm mode tutorial](swarm-tutorial/index.md)
1
PHP
PHP
use faker_locale config
f08ef78444a6db54ce11329503543a7a14e15439
<ide><path>src/Illuminate/Foundation/Testing/WithFaker.php <ide> protected function faker($locale = null) <ide> */ <ide> protected function makeFaker($locale = null) <ide> { <del> return Factory::create($locale ?? Factory::DEFAULT_LOCALE); <add> return Factory::create($locale ?? config('app.faker_locale', Factory::DEFAULT_LOCALE)); <ide> } <ide> }
1
PHP
PHP
add deprecations to deprecated methods
efca5f20ab772488d74a9bcee76b8b13d613682f
<ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> public function mapAlias($alias) <ide> */ <ide> public function addInputType($type, $handler) <ide> { <add> trigger_error( <add> 'RequestHandlerComponent::addInputType() is deprecated. Use config("inputTypeMap", ...) instead.', <add> E_USER_DEPRECATED <add> ); <ide> if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) { <ide> throw new Exception('You must give a handler callback.'); <ide> } <ide> public function addInputType($type, $handler) <ide> */ <ide> public function viewClassMap($type = null, $viewClass = null) <ide> { <add> trigger_error( <add> 'RequestHandlerComponent::viewClassMap() is deprecated. Use config("viewClassMap", ...) instead.', <add> E_USER_DEPRECATED <add> ); <ide> if (!$viewClass && is_string($type)) { <ide> return $this->config('viewClassMap.' . $type); <ide> } <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testInitializeContentTypeAndExtensionMismatch() <ide> */ <ide> public function testViewClassMap() <ide> { <add> $restore = error_reporting(E_ALL & ~E_USER_DEPRECATED); <add> <ide> $this->RequestHandler->config(['viewClassMap' => ['json' => 'CustomJson']]); <ide> $this->RequestHandler->initialize([]); <ide> $result = $this->RequestHandler->viewClassMap(); <ide> public function testViewClassMap() <ide> <ide> $this->RequestHandler->renderAs($this->Controller, 'json'); <ide> $this->assertEquals('TestApp\View\CustomJsonView', $this->Controller->viewClass); <add> error_reporting($restore); <ide> } <ide> <ide> /** <ide> public function testStartupIgnoreFileAsXml() <ide> */ <ide> public function testStartupCustomTypeProcess() <ide> { <del> if (!function_exists('str_getcsv')) { <del> $this->markTestSkipped('Need "str_getcsv" for this test.'); <del> } <add> $restore = error_reporting(E_ALL & ~E_USER_DEPRECATED); <ide> $this->Controller->request = $this->getMock('Cake\Network\Request', ['_readInput']); <ide> $this->Controller->request->expects($this->once()) <ide> ->method('_readInput') <ide> public function testStartupCustomTypeProcess() <ide> 'A', 'csv', 'string' <ide> ]; <ide> $this->assertEquals($expected, $this->Controller->request->data); <add> error_reporting($restore); <ide> } <ide> <ide> /** <ide> public function testBeforeRedirectCallbackWithArrayUrl() <ide> */ <ide> public function testAddInputTypeException() <ide> { <add> $restore = error_reporting(E_ALL & ~E_USER_DEPRECATED); <ide> $this->RequestHandler->addInputType('csv', ['I am not callable']); <add> error_reporting($restore); <ide> } <ide> <ide> /**
2
Python
Python
fix vps.net test name
863a6253be8a7e4fe66f13ae3b8534b8045a8f7c
<ide><path>test/test_vpsnet.py <ide> <ide> from secrets import VPSNET_USER, VPSNET_KEY <ide> <del>class EC2Tests(unittest.TestCase): <add>class VPSNetTests(unittest.TestCase): <ide> <ide> def setUp(self): <ide> VPSNetNodeDriver.connectionCls.conn_classes = (None, VPSNetMockHttp)
1
Javascript
Javascript
make path relative
0739934c5084293061122d2602766d65d867bedc
<ide><path>public/js/main.js <ide> $(document).ready(function() { <ide> }, <ide> function(res) { <ide> if (res) { <del> window.location.href = 'http://localhost:3001/bonfires' <add> window.location.href = '/bonfires' <ide> } <ide> }) <ide> }
1
Ruby
Ruby
remove the warning when testing whiny_nil
e722fbb50f5d95fd5d5c3451f7fbf6f71b561683
<ide><path>activesupport/test/whiny_nil_test.rb <ide> def test_array <ide> end <ide> <ide> def test_id <del> nil.stubs(:object_id).returns(999) <ide> nil.id <ide> rescue RuntimeError => nme <ide> assert_no_match(/nil:NilClass/, nme.message) <del> assert_match(/999/, nme.message) <add> assert_match(Regexp.new(nil.object_id.to_s), nme.message) <ide> end <ide> <ide> def test_no_to_ary_coercion
1
Go
Go
move inspectexecid test to exec
957cbdbf302750f3fb3467237bebf29d87234208
<ide><path>integration-cli/docker_cli_exec_test.go <ide> func TestExecCgroup(t *testing.T) { <ide> <ide> logDone("exec - exec has the container cgroups") <ide> } <add> <add>func TestInspectExecID(t *testing.T) { <add> defer deleteAllContainers() <add> <add> out, exitCode, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "busybox", "top")) <add> if exitCode != 0 || err != nil { <add> t.Fatalf("failed to run container: %s, %v", out, err) <add> } <add> id := strings.TrimSuffix(out, "\n") <add> <add> out, err = inspectField(id, "ExecIDs") <add> if err != nil { <add> t.Fatalf("failed to inspect container: %s, %v", out, err) <add> } <add> if out != "<no value>" { <add> t.Fatalf("ExecIDs should be empty, got: %s", out) <add> } <add> <add> exitCode, err = runCommand(exec.Command(dockerBinary, "exec", "-d", id, "ls", "/")) <add> if exitCode != 0 || err != nil { <add> t.Fatalf("failed to exec in container: %s, %v", out, err) <add> } <add> <add> out, err = inspectField(id, "ExecIDs") <add> if err != nil { <add> t.Fatalf("failed to inspect container: %s, %v", out, err) <add> } <add> <add> out = strings.TrimSuffix(out, "\n") <add> if out == "[]" || out == "<no value>" { <add> t.Fatalf("ExecIDs should not be empty, got: %s", out) <add> } <add> <add> logDone("inspect - inspect a container with ExecIDs") <add>} <ide><path>integration-cli/docker_cli_inspect_test.go <ide> func TestInspectImage(t *testing.T) { <ide> <ide> logDone("inspect - inspect an image") <ide> } <del> <del>func TestInspectExecID(t *testing.T) { <del> defer deleteAllContainers() <del> <del> out, exitCode, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "busybox", "top")) <del> if exitCode != 0 || err != nil { <del> t.Fatalf("failed to run container: %s, %v", out, err) <del> } <del> id := strings.TrimSuffix(out, "\n") <del> <del> out, err = inspectField(id, "ExecIDs") <del> if err != nil { <del> t.Fatalf("failed to inspect container: %s, %v", out, err) <del> } <del> if out != "<no value>" { <del> t.Fatalf("ExecIDs should be empty, got: %s", out) <del> } <del> <del> exitCode, err = runCommand(exec.Command(dockerBinary, "exec", "-d", id, "ls", "/")) <del> if exitCode != 0 || err != nil { <del> t.Fatalf("failed to exec in container: %s, %v", out, err) <del> } <del> <del> out, err = inspectField(id, "ExecIDs") <del> if err != nil { <del> t.Fatalf("failed to inspect container: %s, %v", out, err) <del> } <del> <del> out = strings.TrimSuffix(out, "\n") <del> if out == "[]" || out == "<no value>" { <del> t.Fatalf("ExecIDs should not be empty, got: %s", out) <del> } <del> <del> logDone("inspect - inspect a container with ExecIDs") <del>}
2
Mixed
Javascript
fix request with option timeout and agent
949e8851484c016c07f6cc9e5889f0f2e56baf2a
<ide><path>doc/api/http.md <ide> added: v0.3.4 <ide> * `maxFreeSockets` {number} Maximum number of sockets to leave open <ide> in a free state. Only relevant if `keepAlive` is set to `true`. <ide> **Default:** `256`. <add> * `timeout` {number} Socket timeout in milliseconds. <add> This will set the timeout after the socket is connected. <ide> <ide> The default [`http.globalAgent`][] that is used by [`http.request()`][] has all <ide> of these values set to their respective defaults. <ide><path>lib/_http_agent.js <ide> function Agent(options) { <ide> <ide> if (socket.writable && <ide> this.requests[name] && this.requests[name].length) { <del> this.requests[name].shift().onSocket(socket); <add> const req = this.requests[name].shift(); <add> setRequestSocket(this, req, socket); <ide> if (this.requests[name].length === 0) { <ide> // don't leak <ide> delete this.requests[name]; <ide> Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, <ide> delete this.freeSockets[name]; <ide> <ide> this.reuseSocket(socket, req); <del> req.onSocket(socket); <add> setRequestSocket(this, req, socket); <ide> this.sockets[name].push(socket); <ide> } else if (sockLen < this.maxSockets) { <ide> debug('call onSocket', sockLen, freeLen); <ide> // If we are under maxSockets create a new one. <del> this.createSocket(req, options, handleSocketCreation(req, true)); <add> this.createSocket(req, options, handleSocketCreation(this, req, true)); <ide> } else { <ide> debug('wait for socket'); <ide> // We are over limit so we'll add it to the queue. <ide> Agent.prototype.removeSocket = function removeSocket(s, options) { <ide> <ide> if (this.requests[name] && this.requests[name].length) { <ide> debug('removeSocket, have a request, make a socket'); <del> var req = this.requests[name][0]; <add> const req = this.requests[name][0]; <ide> // If we have pending requests and a socket gets closed make a new one <del> this.createSocket(req, options, handleSocketCreation(req, false)); <add> const socketCreationHandler = handleSocketCreation(this, req, false); <add> this.createSocket(req, options, socketCreationHandler); <ide> } <ide> }; <ide> <ide> Agent.prototype.destroy = function destroy() { <ide> } <ide> }; <ide> <del>function handleSocketCreation(request, informRequest) { <add>function handleSocketCreation(agent, request, informRequest) { <ide> return function handleSocketCreation_Inner(err, socket) { <ide> if (err) { <ide> process.nextTick(emitErrorNT, request, err); <ide> return; <ide> } <ide> if (informRequest) <del> request.onSocket(socket); <add> setRequestSocket(agent, request, socket); <ide> else <ide> socket.emit('free'); <ide> }; <ide> } <ide> <add>function setRequestSocket(agent, req, socket) { <add> req.onSocket(socket); <add> const agentTimeout = agent.options.timeout || 0; <add> if (req.timeout === undefined || req.timeout === agentTimeout) { <add> return; <add> } <add> socket.setTimeout(req.timeout); <add> // reset timeout after response end <add> req.once('response', (res) => { <add> res.once('end', () => { <add> if (socket.timeout !== agentTimeout) { <add> socket.setTimeout(agentTimeout); <add> } <add> }); <add> }); <add>} <add> <ide> function emitErrorNT(emitter, err) { <ide> emitter.emit('error', err); <ide> } <ide><path>lib/_http_client.js <ide> function tickOnSocket(req, socket) { <ide> socket.on('end', socketOnEnd); <ide> socket.on('close', socketCloseListener); <ide> <del> if (req.timeout) { <del> const emitRequestTimeout = () => req.emit('timeout'); <del> socket.once('timeout', emitRequestTimeout); <del> req.once('response', (res) => { <del> res.once('end', () => { <del> socket.removeListener('timeout', emitRequestTimeout); <del> }); <del> }); <add> if (req.timeout !== undefined) { <add> listenSocketTimeout(req); <ide> } <ide> req.emit('socket', socket); <ide> } <ide> <add>function listenSocketTimeout(req) { <add> if (req.timeoutCb) { <add> return; <add> } <add> const emitRequestTimeout = () => req.emit('timeout'); <add> // Set timeoutCb so it will get cleaned up on request end. <add> req.timeoutCb = emitRequestTimeout; <add> // Delegate socket timeout event. <add> if (req.socket) { <add> req.socket.once('timeout', emitRequestTimeout); <add> } else { <add> req.on('socket', (socket) => { <add> socket.once('timeout', emitRequestTimeout); <add> }); <add> } <add> // Remove socket timeout listener after response end. <add> req.once('response', (res) => { <add> res.once('end', () => { <add> req.socket.removeListener('timeout', emitRequestTimeout); <add> }); <add> }); <add>} <add> <ide> ClientRequest.prototype.onSocket = function onSocket(socket) { <ide> process.nextTick(onSocketNT, this, socket); <ide> }; <ide> function _deferToConnect(method, arguments_, cb) { <ide> } <ide> <ide> ClientRequest.prototype.setTimeout = function setTimeout(msecs, callback) { <add> listenSocketTimeout(this); <ide> msecs = validateTimerDuration(msecs); <ide> if (callback) this.once('timeout', callback); <ide> <del> const emitTimeout = () => this.emit('timeout'); <del> <del> if (this.socket && this.socket.writable) { <del> if (this.timeoutCb) <del> this.socket.setTimeout(0, this.timeoutCb); <del> this.timeoutCb = emitTimeout; <del> this.socket.setTimeout(msecs, emitTimeout); <del> return this; <del> } <del> <del> // Set timeoutCb so that it'll get cleaned up on request end <del> this.timeoutCb = emitTimeout; <ide> if (this.socket) { <del> var sock = this.socket; <del> this.socket.once('connect', function() { <del> sock.setTimeout(msecs, emitTimeout); <del> }); <del> return this; <add> setSocketTimeout(this.socket, msecs); <add> } else { <add> this.once('socket', (sock) => setSocketTimeout(sock, msecs)); <ide> } <ide> <del> this.once('socket', function(sock) { <del> if (sock.connecting) { <del> sock.once('connect', function() { <del> sock.setTimeout(msecs, emitTimeout); <del> }); <del> } else { <del> sock.setTimeout(msecs, emitTimeout); <del> } <del> }); <del> <ide> return this; <ide> }; <ide> <add>function setSocketTimeout(sock, msecs) { <add> if (sock.connecting) { <add> sock.once('connect', function() { <add> sock.setTimeout(msecs); <add> }); <add> } else { <add> sock.setTimeout(msecs); <add> } <add>} <add> <ide> ClientRequest.prototype.setNoDelay = function setNoDelay(noDelay) { <ide> this._deferToConnect('setNoDelay', [noDelay]); <ide> }; <ide><path>lib/net.js <ide> function writeAfterFIN(chunk, encoding, cb) { <ide> } <ide> <ide> Socket.prototype.setTimeout = function(msecs, callback) { <add> this.timeout = msecs; <ide> // Type checking identical to timers.enroll() <ide> msecs = validateTimerDuration(msecs); <ide> <ide><path>test/parallel/test-http-client-set-timeout.js <add>'use strict'; <add>const common = require('../common'); <add> <add>// Test that `req.setTimeout` will fired exactly once. <add> <add>const assert = require('assert'); <add>const http = require('http'); <add> <add>const HTTP_CLIENT_TIMEOUT = 2000; <add> <add>const options = { <add> method: 'GET', <add> port: undefined, <add> host: '127.0.0.1', <add> path: '/', <add> timeout: HTTP_CLIENT_TIMEOUT, <add>}; <add> <add>const server = http.createServer(() => { <add> // Never respond. <add>}); <add> <add>server.listen(0, options.host, function() { <add> doRequest(); <add>}); <add> <add>function doRequest() { <add> options.port = server.address().port; <add> const req = http.request(options); <add> req.setTimeout(HTTP_CLIENT_TIMEOUT / 2); <add> req.on('error', () => { <add> // This space is intentionally left blank. <add> }); <add> req.on('close', common.mustCall(() => server.close())); <add> <add> let timeout_events = 0; <add> req.on('timeout', common.mustCall(() => { <add> timeout_events += 1; <add> })); <add> req.end(); <add> <add> setTimeout(function() { <add> req.destroy(); <add> assert.strictEqual(timeout_events, 1); <add> }, common.platformTimeout(HTTP_CLIENT_TIMEOUT)); <add>} <ide><path>test/parallel/test-http-client-timeout-option-with-agent.js <add>'use strict'; <add>const common = require('../common'); <add> <add>// Test that when http request uses both timeout and agent, <add>// timeout will work as expected. <add> <add>const assert = require('assert'); <add>const http = require('http'); <add> <add>const HTTP_AGENT_TIMEOUT = 1000; <add>const HTTP_CLIENT_TIMEOUT = 3000; <add> <add>const agent = new http.Agent({ timeout: HTTP_AGENT_TIMEOUT }); <add>const options = { <add> method: 'GET', <add> port: undefined, <add> host: '127.0.0.1', <add> path: '/', <add> timeout: HTTP_CLIENT_TIMEOUT, <add> agent, <add>}; <add> <add>const server = http.createServer(() => { <add> // Never respond. <add>}); <add> <add>server.listen(0, options.host, function() { <add> doRequest(); <add>}); <add> <add>function doRequest() { <add> options.port = server.address().port; <add> const req = http.request(options); <add> const start = Date.now(); <add> req.on('error', () => { <add> // This space is intentionally left blank. <add> }); <add> req.on('close', common.mustCall(() => server.close())); <add> <add> let timeout_events = 0; <add> req.on('timeout', common.mustCall(() => { <add> timeout_events += 1; <add> const duration = Date.now() - start; <add> // The timeout event cannot be precisely timed. It will delay <add> // some number of milliseconds, so test it in second units. <add> assert.strictEqual(duration / 1000 | 0, HTTP_CLIENT_TIMEOUT / 1000); <add> })); <add> req.end(); <add> <add> setTimeout(function() { <add> req.destroy(); <add> assert.strictEqual(timeout_events, 1); <add> // Ensure the `timeout` event fired only once. <add> }, common.platformTimeout(HTTP_CLIENT_TIMEOUT * 2)); <add>}
6
Javascript
Javascript
detect subscriptions wrapped in starttransition
a3fde2358896e32201f49bc81acd2f228951ca84
<ide><path>packages/react-reconciler/src/ReactFiberHooks.new.js <ide> import { <ide> } from './ReactUpdateQueue.new'; <ide> import {pushInterleavedQueue} from './ReactFiberInterleavedUpdates.new'; <ide> import {getIsStrictModeForDevtools} from './ReactFiberReconciler.new'; <add>import {warnOnSubscriptionInsideStartTransition} from 'shared/ReactFeatureFlags'; <ide> <ide> const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals; <ide> <ide> function startTransition(setPending, callback) { <ide> } finally { <ide> setCurrentUpdatePriority(previousPriority); <ide> ReactCurrentBatchConfig.transition = prevTransition; <add> if (__DEV__) { <add> if ( <add> prevTransition !== 1 && <add> warnOnSubscriptionInsideStartTransition && <add> ReactCurrentBatchConfig._updatedFibers <add> ) { <add> const updatedFibersCount = ReactCurrentBatchConfig._updatedFibers.size; <add> if (updatedFibersCount > 10) { <add> console.warn( <add> 'Detected a large number of updates inside startTransition. ' + <add> 'If this is due to a subscription please re-write it to use React provided hooks. ' + <add> 'Otherwise concurrent mode guarantees are off the table.', <add> ); <add> } <add> ReactCurrentBatchConfig._updatedFibers.clear(); <add> } <add> } <ide> } <ide> } <ide> <ide><path>packages/react-reconciler/src/ReactFiberHooks.old.js <ide> import { <ide> } from './ReactUpdateQueue.old'; <ide> import {pushInterleavedQueue} from './ReactFiberInterleavedUpdates.old'; <ide> import {getIsStrictModeForDevtools} from './ReactFiberReconciler.old'; <add>import {warnOnSubscriptionInsideStartTransition} from 'shared/ReactFeatureFlags'; <ide> <ide> const {ReactCurrentDispatcher, ReactCurrentBatchConfig} = ReactSharedInternals; <ide> <ide> function startTransition(setPending, callback) { <ide> } finally { <ide> setCurrentUpdatePriority(previousPriority); <ide> ReactCurrentBatchConfig.transition = prevTransition; <add> if (__DEV__) { <add> if ( <add> prevTransition !== 1 && <add> warnOnSubscriptionInsideStartTransition && <add> ReactCurrentBatchConfig._updatedFibers <add> ) { <add> const updatedFibersCount = ReactCurrentBatchConfig._updatedFibers.size; <add> if (updatedFibersCount > 10) { <add> console.warn( <add> 'Detected a large number of updates inside startTransition. ' + <add> 'If this is due to a subscription please re-write it to use React provided hooks. ' + <add> 'Otherwise concurrent mode guarantees are off the table.', <add> ); <add> } <add> ReactCurrentBatchConfig._updatedFibers.clear(); <add> } <add> } <ide> } <ide> } <ide> <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import { <ide> enableStrictEffects, <ide> skipUnmountedBoundaries, <ide> enableUpdaterTracking, <add> warnOnSubscriptionInsideStartTransition, <ide> } from 'shared/ReactFeatureFlags'; <ide> import ReactSharedInternals from 'shared/ReactSharedInternals'; <ide> import invariant from 'shared/invariant'; <ide> export function requestUpdateLane(fiber: Fiber): Lane { <ide> <ide> const isTransition = requestCurrentTransition() !== NoTransition; <ide> if (isTransition) { <add> if ( <add> __DEV__ && <add> warnOnSubscriptionInsideStartTransition && <add> ReactCurrentBatchConfig._updatedFibers <add> ) { <add> ReactCurrentBatchConfig._updatedFibers.add(fiber); <add> } <ide> // The algorithm for assigning an update to a lane should be stable for all <ide> // updates at the same priority within the same event. To do this, the <ide> // inputs to the algorithm must be the same. <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> import { <ide> enableStrictEffects, <ide> skipUnmountedBoundaries, <ide> enableUpdaterTracking, <add> warnOnSubscriptionInsideStartTransition, <ide> } from 'shared/ReactFeatureFlags'; <ide> import ReactSharedInternals from 'shared/ReactSharedInternals'; <ide> import invariant from 'shared/invariant'; <ide> export function requestUpdateLane(fiber: Fiber): Lane { <ide> <ide> const isTransition = requestCurrentTransition() !== NoTransition; <ide> if (isTransition) { <add> if ( <add> __DEV__ && <add> warnOnSubscriptionInsideStartTransition && <add> ReactCurrentBatchConfig._updatedFibers <add> ) { <add> ReactCurrentBatchConfig._updatedFibers.add(fiber); <add> } <ide> // The algorithm for assigning an update to a lane should be stable for all <ide> // updates at the same priority within the same event. To do this, the <ide> // inputs to the algorithm must be the same. <ide><path>packages/react/src/ReactCurrentBatchConfig.js <ide> * @flow <ide> */ <ide> <add>import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; <add> <add>type BatchConfig = { <add> transition: number, <add> _updatedFibers?: Set<Fiber>, <add>}; <ide> /** <ide> * Keeps track of the current batch's configuration such as how long an update <ide> * should suspend for if it needs to. <ide> */ <del>const ReactCurrentBatchConfig = { <del> transition: (0: number), <add>const ReactCurrentBatchConfig: BatchConfig = { <add> transition: 0, <ide> }; <ide> <add>if (__DEV__) { <add> ReactCurrentBatchConfig._updatedFibers = new Set(); <add>} <add> <ide> export default ReactCurrentBatchConfig; <ide><path>packages/react/src/ReactStartTransition.js <ide> */ <ide> <ide> import ReactCurrentBatchConfig from './ReactCurrentBatchConfig'; <add>import {warnOnSubscriptionInsideStartTransition} from 'shared/ReactFeatureFlags'; <ide> <ide> export function startTransition(scope: () => void) { <ide> const prevTransition = ReactCurrentBatchConfig.transition; <ide> export function startTransition(scope: () => void) { <ide> scope(); <ide> } finally { <ide> ReactCurrentBatchConfig.transition = prevTransition; <add> if (__DEV__) { <add> if ( <add> prevTransition !== 1 && <add> warnOnSubscriptionInsideStartTransition && <add> ReactCurrentBatchConfig._updatedFibers <add> ) { <add> const updatedFibersCount = ReactCurrentBatchConfig._updatedFibers.size; <add> if (updatedFibersCount > 10) { <add> console.warn( <add> 'Detected a large number of updates inside startTransition. ' + <add> 'If this is due to a subscription please re-write it to use React provided hooks. ' + <add> 'Otherwise concurrent mode guarantees are off the table.', <add> ); <add> } <add> ReactCurrentBatchConfig._updatedFibers.clear(); <add> } <add> } <ide> } <ide> } <ide><path>packages/react/src/__tests__/ReactStartTransition-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> * @emails react-core <add> */ <add> <add>'use strict'; <add> <add>let React; <add>let ReactTestRenderer; <add>let act; <add>let useState; <add>let useTransition; <add> <add>const SUSPICIOUS_NUMBER_OF_FIBERS_UPDATED = 10; <add> <add>describe('ReactStartTransition', () => { <add> beforeEach(() => { <add> jest.resetModules(); <add> React = require('react'); <add> ReactTestRenderer = require('react-test-renderer'); <add> act = require('jest-react').act; <add> useState = React.useState; <add> useTransition = React.useTransition; <add> }); <add> <add> // @gate warnOnSubscriptionInsideStartTransition || !__DEV__ <add> it('Warns if a suspicious number of fibers are updated inside startTransition', () => { <add> const subs = new Set(); <add> const useUserSpaceSubscription = () => { <add> const setState = useState(0)[1]; <add> subs.add(setState); <add> }; <add> <add> let triggerHookTransition; <add> <add> const Component = ({level}) => { <add> useUserSpaceSubscription(); <add> if (level === 0) { <add> triggerHookTransition = useTransition()[1]; <add> } <add> if (level < SUSPICIOUS_NUMBER_OF_FIBERS_UPDATED) { <add> return <Component level={level + 1} />; <add> } <add> return null; <add> }; <add> <add> act(() => { <add> ReactTestRenderer.create(<Component level={0} />, { <add> unstable_isConcurrent: true, <add> }); <add> }); <add> <add> expect(() => { <add> act(() => { <add> React.startTransition(() => { <add> subs.forEach(setState => { <add> setState(state => state + 1); <add> }); <add> }); <add> }); <add> }).toWarnDev( <add> [ <add> 'Detected a large number of updates inside startTransition. ' + <add> 'If this is due to a subscription please re-write it to use React provided hooks. ' + <add> 'Otherwise concurrent mode guarantees are off the table.', <add> ], <add> {withoutStack: true}, <add> ); <add> <add> expect(() => { <add> act(() => { <add> triggerHookTransition(() => { <add> subs.forEach(setState => { <add> setState(state => state + 1); <add> }); <add> }); <add> }); <add> }).toWarnDev( <add> [ <add> 'Detected a large number of updates inside startTransition. ' + <add> 'If this is due to a subscription please re-write it to use React provided hooks. ' + <add> 'Otherwise concurrent mode guarantees are off the table.', <add> ], <add> {withoutStack: true}, <add> ); <add> }); <add>}); <ide><path>packages/shared/ReactFeatureFlags.js <ide> export const enableTrustedTypesIntegration = false; <ide> // a deprecated pattern we want to get rid of in the future <ide> export const warnAboutSpreadingKeyToJSX = false; <ide> <add>export const warnOnSubscriptionInsideStartTransition = false; <add> <ide> export const enableComponentStackLocations = true; <ide> <ide> export const enableNewReconciler = false; <ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js <ide> export const disableTextareaChildren = false; <ide> export const disableModulePatternComponents = false; <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <add>export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableComponentStackLocations = false; <ide> export const enableLegacyFBSupport = false; <ide> export const enableFilterEmptyStringAttributesDOM = false; <ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js <ide> export const disableTextareaChildren = false; <ide> export const disableModulePatternComponents = false; <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <add>export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableComponentStackLocations = false; <ide> export const enableLegacyFBSupport = false; <ide> export const enableFilterEmptyStringAttributesDOM = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js <ide> export const disableTextareaChildren = false; <ide> export const disableModulePatternComponents = false; <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <add>export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableComponentStackLocations = true; <ide> export const enableLegacyFBSupport = false; <ide> export const enableFilterEmptyStringAttributesDOM = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.native.js <ide> export const enableSuspenseLayoutEffectSemantics = false; <ide> export const enableGetInspectorDataForInstanceInProduction = false; <ide> export const enableNewReconciler = false; <ide> export const deferRenderPhaseUpdateToNextBatch = false; <del> <add>export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableStrictEffects = false; <ide> export const createRootStrictEffectsByDefault = false; <ide> export const enableUseRefAccessWarning = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js <ide> export const disableTextareaChildren = false; <ide> export const disableModulePatternComponents = true; <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <add>export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableComponentStackLocations = true; <ide> export const enableLegacyFBSupport = false; <ide> export const enableFilterEmptyStringAttributesDOM = false; <ide><path>packages/shared/forks/ReactFeatureFlags.testing.js <ide> export const disableTextareaChildren = false; <ide> export const disableModulePatternComponents = false; <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <add>export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableComponentStackLocations = true; <ide> export const enableLegacyFBSupport = false; <ide> export const enableFilterEmptyStringAttributesDOM = false; <ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js <ide> export const disableTextareaChildren = __EXPERIMENTAL__; <ide> export const disableModulePatternComponents = true; <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <add>export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableComponentStackLocations = true; <ide> export const enableLegacyFBSupport = !__EXPERIMENTAL__; <ide> export const enableFilterEmptyStringAttributesDOM = false; <ide><path>packages/shared/forks/ReactFeatureFlags.www-dynamic.js <ide> export const disableSchedulerTimeoutInWorkLoop = __VARIANT__; <ide> export const enableLazyContextPropagation = __VARIANT__; <ide> export const enableSyncDefaultUpdates = __VARIANT__; <ide> export const consoleManagedByDevToolsDuringStrictMode = __VARIANT__; <add>export const warnOnSubscriptionInsideStartTransition = __VARIANT__; <ide> <ide> // Enable this flag to help with concurrent mode debugging. <ide> // It logs information to the console about React scheduling, rendering, and commit phases. <ide><path>packages/shared/forks/ReactFeatureFlags.www.js <ide> export const { <ide> disableSchedulerTimeoutInWorkLoop, <ide> enableLazyContextPropagation, <ide> enableSyncDefaultUpdates, <add> warnOnSubscriptionInsideStartTransition, <ide> } = dynamicFeatureFlags; <ide> <ide> // On WWW, __EXPERIMENTAL__ is used for a new modern build. <ide> export const enableSchedulingProfiler = <ide> // For now, we'll turn it on for everyone because it's *already* on for everyone in practice. <ide> // At least this will let us stop shipping <Profiler> implementation to all users. <ide> export const enableSchedulerDebugging = true; <del> <ide> export const warnAboutDeprecatedLifecycles = true; <ide> export const disableLegacyContext = __EXPERIMENTAL__; <ide> export const warnAboutStringRefs = false;
17
Javascript
Javascript
add tests for missing https agent options
18c9913ce18135953ef1ac02ded8604de9f42e2c
<ide><path>test/parallel/test-https-agent-additional-options.js <ide> const updatedValues = new Map([ <ide> ['dhparam', fixtures.readKey('dh2048.pem')], <ide> ['ecdhCurve', 'secp384r1'], <ide> ['honorCipherOrder', true], <add> ['minVersion', 'TLSv1.1'], <add> ['maxVersion', 'TLSv1.3'], <ide> ['secureOptions', crypto.constants.SSL_OP_CIPHER_SERVER_PREFERENCE], <ide> ['secureProtocol', 'TLSv1_1_method'], <ide> ['sessionIdContext', 'sessionIdContext'],
1
Ruby
Ruby
improve rack/cgi tests
2a7aca8ec34ebfe0e30dd5e8696918b083ef56f5
<ide><path>actionpack/test/controller/cgi_test.rb <ide> def default_test; end <ide> private <ide> <ide> def set_content_data(data) <add> @request.env['REQUEST_METHOD'] = 'POST' <ide> @request.env['CONTENT_LENGTH'] = data.length <ide> @request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' <ide> @request.env['RAW_POST_DATA'] = data <ide> def test_cookie_syntax_resilience <ide> <ide> class CgiRequestParamsParsingTest < BaseCgiTest <ide> def test_doesnt_break_when_content_type_has_charset <del> data = 'flamenco=love' <del> @request.env['CONTENT_LENGTH'] = data.length <del> @request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' <del> @request.env['RAW_POST_DATA'] = data <add> set_content_data 'flamenco=love' <add> <ide> assert_equal({"flamenco"=> "love"}, @request.request_parameters) <ide> end <ide> <ide> def test_post <ide> end <ide> <ide> def test_put <del> @request.env['REQUEST_METHOD'] = 'POST' <ide> set_content_data '_method=put' <ide> <ide> assert_equal :put, @request.request_method <ide> end <ide> <ide> def test_delete <del> @request.env['REQUEST_METHOD'] = 'POST' <ide> set_content_data '_method=delete' <ide> <ide> assert_equal :delete, @request.request_method <ide><path>actionpack/test/controller/rack_test.rb <ide> def default_test; end <ide> private <ide> <ide> def set_content_data(data) <add> @request.env['REQUEST_METHOD'] = 'POST' <ide> @request.env['CONTENT_LENGTH'] = data.length <ide> @request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' <ide> @request.env['RAW_POST_DATA'] = data <ide> def test_cookie_syntax_resilience <ide> <ide> class RackRequestParamsParsingTest < BaseRackTest <ide> def test_doesnt_break_when_content_type_has_charset <del> data = 'flamenco=love' <del> @request.env['CONTENT_LENGTH'] = data.length <del> @request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=utf-8' <del> @request.env['RAW_POST_DATA'] = data <add> set_content_data 'flamenco=love' <add> <ide> assert_equal({"flamenco"=> "love"}, @request.request_parameters) <ide> end <ide> <ide> def test_post <ide> end <ide> <ide> def test_put <del> @request.env['REQUEST_METHOD'] = 'POST' <ide> set_content_data '_method=put' <ide> <ide> assert_equal :put, @request.request_method <ide> end <ide> <ide> def test_delete <del> @request.env['REQUEST_METHOD'] = 'POST' <ide> set_content_data '_method=delete' <ide> <ide> assert_equal :delete, @request.request_method
2
Java
Java
improve mappingmatch determination in mock request
8a9b082d8a0f84e7b72416e57e9b6a7a9321567e
<ide><path>spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java <ide> /* <del> * Copyright 2002-2021 the original author or authors. <add> * Copyright 2002-2022 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 jakarta.servlet.ServletRequest; <ide> import jakarta.servlet.ServletResponse; <ide> import jakarta.servlet.http.Cookie; <add>import jakarta.servlet.http.HttpServletMapping; <ide> import jakarta.servlet.http.HttpServletRequest; <ide> import jakarta.servlet.http.HttpServletResponse; <ide> import jakarta.servlet.http.HttpSession; <ide> import jakarta.servlet.http.HttpUpgradeHandler; <add>import jakarta.servlet.http.MappingMatch; <ide> import jakarta.servlet.http.Part; <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.StreamUtils; <ide> import org.springframework.util.StringUtils; <add>import org.springframework.web.util.UrlPathHelper; <ide> <ide> /** <ide> * Mock implementation of the {@link jakarta.servlet.http.HttpServletRequest} interface. <ide> public class MockHttpServletRequest implements HttpServletRequest { <ide> <ide> private final MultiValueMap<String, Part> parts = new LinkedMultiValueMap<>(); <ide> <add> @Nullable <add> private HttpServletMapping httpServletMapping; <add> <ide> <ide> // --------------------------------------------------------------------- <ide> // Constructors <ide> public Collection<Part> getParts() throws IOException, ServletException { <ide> return result; <ide> } <ide> <add> public void setHttpServletMapping(@Nullable HttpServletMapping httpServletMapping) { <add> this.httpServletMapping = httpServletMapping; <add> } <add> <add> @Override <add> public HttpServletMapping getHttpServletMapping() { <add> return (this.httpServletMapping == null ? <add> new MockHttpServletMapping("", "", "", determineMappingMatch()) : <add> this.httpServletMapping); <add> } <add> <add> /** <add> * Best effort to detect a Servlet path mapping, e.g. {@code "/foo/*"}, by <add> * checking whether the length of requestURI > contextPath + servletPath. <add> * This helps {@link org.springframework.web.util.ServletRequestPathUtils} <add> * to take into account the Servlet path when parsing the requestURI. <add> */ <add> @Nullable <add> private MappingMatch determineMappingMatch() { <add> if (StringUtils.hasText(this.requestURI) && StringUtils.hasText(this.servletPath)) { <add> String path = UrlPathHelper.defaultInstance.getRequestUri(this); <add> String prefix = this.contextPath + this.servletPath; <add> return (path.startsWith(prefix) && (path.length() > prefix.length()) ? MappingMatch.PATH : null); <add> } <add> return null; <add> } <add> <ide> @Override <ide> public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) throws IOException, ServletException { <ide> throw new UnsupportedOperationException(); <ide><path>spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockHttpServletRequest.java <ide> /* <del> * Copyright 2002-2021 the original author or authors. <add> * Copyright 2002-2022 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 jakarta.servlet.http.HttpServletResponse; <ide> import jakarta.servlet.http.HttpSession; <ide> import jakarta.servlet.http.HttpUpgradeHandler; <add>import jakarta.servlet.http.MappingMatch; <ide> import jakarta.servlet.http.Part; <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.StreamUtils; <ide> import org.springframework.util.StringUtils; <add>import org.springframework.web.util.UrlPathHelper; <ide> <ide> /** <ide> * Mock implementation of the {@link jakarta.servlet.http.HttpServletRequest} interface. <ide> public class MockHttpServletRequest implements HttpServletRequest { <ide> <ide> private final MultiValueMap<String, Part> parts = new LinkedMultiValueMap<>(); <ide> <del> private HttpServletMapping httpServletMapping = new MockHttpServletMapping("", "", "", null); <add> @Nullable <add> private HttpServletMapping httpServletMapping; <ide> <ide> <ide> // --------------------------------------------------------------------- <ide> public Collection<Part> getParts() throws IOException, ServletException { <ide> return result; <ide> } <ide> <del> public void setHttpServletMapping(HttpServletMapping httpServletMapping) { <add> public void setHttpServletMapping(@Nullable HttpServletMapping httpServletMapping) { <ide> this.httpServletMapping = httpServletMapping; <ide> } <ide> <ide> @Override <ide> public HttpServletMapping getHttpServletMapping() { <del> return this.httpServletMapping; <add> return (this.httpServletMapping == null ? <add> new MockHttpServletMapping("", "", "", determineMappingMatch()) : <add> this.httpServletMapping); <add> } <add> <add> /** <add> * Best effort to detect a Servlet path mapping, e.g. {@code "/foo/*"}, by <add> * checking whether the length of requestURI > contextPath + servletPath. <add> * This helps {@link org.springframework.web.util.ServletRequestPathUtils} <add> * to take into account the Servlet path when parsing the requestURI. <add> */ <add> @Nullable <add> private MappingMatch determineMappingMatch() { <add> if (StringUtils.hasText(this.requestURI) && StringUtils.hasText(this.servletPath)) { <add> String path = UrlPathHelper.defaultInstance.getRequestUri(this); <add> String prefix = this.contextPath + this.servletPath; <add> return (path.startsWith(prefix) && (path.length() > prefix.length()) ? MappingMatch.PATH : null); <add> } <add> return null; <ide> } <ide> <ide> @Override
2
Python
Python
update deprecation message to be more clearer
a5a5102b28815a55983d2d346bcd0a836d4ba38b
<ide><path>official/nlp/bert/model_training_utils.py <ide> def write_txt_summary(training_summary, summary_dir): <ide> <ide> <ide> @deprecation.deprecated( <del> None, 'This function is deprecated. Please use Keras compile/fit instead.') <add> None, 'This function is deprecated and we do not expect adding new ' <add> 'functionalities. Please do not have your code depending ' <add> 'on this library.') <ide> def run_customized_training_loop( <ide> # pylint: disable=invalid-name <ide> _sentinel=None,
1
Python
Python
define xrange() for python 3
1d5dba6914c6f5707b17c2fa3089af52acf8971d
<ide><path>rebar/rebar_train.py <ide> import rebar <ide> import datasets <ide> import logger as L <add> <add>try: <add> xrange # Python 2 <add>except NameError: <add> xrange = range # Python 3 <add> <ide> gfile = tf.gfile <ide> <ide> tf.app.flags.DEFINE_string("working_dir", "/tmp/rebar",
1
Python
Python
fix sample_weight and class_weight in validation
9773e810a527d88b97239e0117be0967a3b4214f
<ide><path>keras/models.py <ide> def get_function_name(o): <ide> <ide> class Model(object): <ide> def _fit(self, f, ins, out_labels=[], batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <del> validation_split=0., val_f=None, val_ins=None, shuffle=True, metrics=[]): <add> val_f=None, val_ins=None, shuffle=True, metrics=[]): <ide> ''' <ide> Abstract fit function for f(*ins). Assume that f returns a list, labelled by out_labels. <ide> ''' <ide> def _fit(self, f, ins, out_labels=[], batch_size=128, nb_epoch=100, verbose=1, c <ide> do_validation = True <ide> if verbose: <ide> print("Train on %d samples, validate on %d samples" % (len(ins[0]), len(val_ins[0]))) <del> else: <del> if 0 < validation_split < 1: <del> do_validation = True <del> split_at = int(len(ins[0]) * (1 - validation_split)) <del> (ins, val_ins) = (slice_X(ins, 0, split_at), slice_X(ins, split_at)) <del> if verbose: <del> print("Train on %d samples, validate on %d samples" % (len(ins[0]), len(val_ins[0]))) <ide> <ide> nb_train_sample = len(ins[0]) <ide> index_array = np.arange(nb_train_sample) <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> <ide> X = standardize_X(X) <ide> y = standardize_y(y) <del> sample_weight = standardize_weights(y, class_weight=class_weight, sample_weight=sample_weight) <ide> <ide> val_f = None <ide> val_ins = None <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> else: <ide> val_f = self._test <ide> if validation_data: <del> try: <add> if len(validation_data) == 2: <ide> X_val, y_val = validation_data <del> except: <del> raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val). \ <add> sample_weight_val = np.ones(y_val.shape[:-1] + (1,)) <add> elif len(validation_data) == 3: <add> X_val, y_val, sample_weight_val = validation_data <add> else: <add> raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val) or (X_val, y_val, sample_weight). \ <ide> X_val may be a numpy array or a list of numpy arrays depending on your model input.") <ide> X_val = standardize_X(X_val) <ide> y_val = standardize_y(y_val) <del> val_ins = X_val + [y_val, np.ones(y_val.shape[:-1] + (1,))] <add> val_ins = X_val + [y_val, sample_weight_val] <add> <add> elif 0 < validation_split < 1: <add> split_at = int(len(X[0]) * (1 - validation_split)) <add> X, X_val = (slice_X(X, 0, split_at), slice_X(X, split_at)) <add> y, y_val = (slice_X(y, 0, split_at), slice_X(y, split_at)) <add> if sample_weight: <add> sample_weight, sample_weight_val = (slice_X(sample_weight, 0, split_at), slice_X(sample_weight, split_at)) <add> else: <add> sample_weight_val = np.ones(y_val.shape[:-1] + (1,)) <add> val_ins = X_val + [y_val, sample_weight_val] <ide> <ide> if show_accuracy: <ide> f = self._train_with_acc <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> f = self._train <ide> out_labels = ['loss'] <ide> <add> sample_weight = standardize_weights(y, class_weight=class_weight, sample_weight=sample_weight) <ide> ins = X + [y, sample_weight] <ide> metrics = ['loss', 'acc', 'val_loss', 'val_acc'] <ide> return self._fit(f, ins, out_labels=out_labels, batch_size=batch_size, nb_epoch=nb_epoch, <ide> verbose=verbose, callbacks=callbacks, <del> validation_split=validation_split, val_f=val_f, val_ins=val_ins, <add> val_f=val_f, val_ins=val_ins, <ide> shuffle=shuffle, metrics=metrics) <ide> <ide> def predict(self, X, batch_size=128, verbose=0): <ide> def train_on_batch(self, data, class_weight={}, sample_weight={}): <ide> <ide> def test_on_batch(self, data, sample_weight={}): <ide> # data is a dictionary mapping input names to arrays <del> sample_weight = [standardize_weights(data[name]) for name in self.output_order] <del> <add> sample_weight = [standardize_weights(data[name], <add> sample_weight=sample_weight.get(name)) for name in self.output_order] <ide> ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight <ide> return self._test(*ins) <ide> <ide> def predict_on_batch(self, data): <ide> <ide> def fit(self, data, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> validation_split=0., validation_data=None, shuffle=True, class_weight={}, sample_weight={}): <del> sample_weight = [standardize_weights(data[name], <del> sample_weight=sample_weight.get(name), <del> class_weight=class_weight.get(name)) for name in self.output_order] <del> ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight <add> X = [data[name] for name in self.input_order] <add> y = [standardize_y(data[name]) for name in self.output_order] <add> sample_weight_list = [standardize_weights(data[name], <add> sample_weight=sample_weight.get(name)) for name in self.output_order] <add> class_weight_list = [class_weight.get(name) for name in self.output_order] <ide> <ide> val_f = None <ide> val_ins = None <ide> if validation_data or validation_split: <ide> val_f = self._test <ide> if validation_data: <add> # can't use sample weights with validation data at this point <ide> sample_weight = [standardize_weights(validation_data[name]) for name in self.output_order] <ide> val_ins = [validation_data[name] for name in self.input_order] + [standardize_y(validation_data[name]) for name in self.output_order] + sample_weight <ide> <add> elif 0 < validation_split < 1: <add> split_at = int(len(X[0]) * (1 - validation_split)) <add> X, X_val = (slice_X(X, 0, split_at), slice_X(X, split_at)) <add> y, y_val = (slice_X(y, 0, split_at), slice_X(y, split_at)) <add> sample_weight_list, sample_weight_list_val = (slice_X(sample_weight_list, 0, split_at), slice_X(sample_weight_list, split_at)) <add> val_ins = X_val + y_val + sample_weight_val <add> <ide> f = self._train <ide> out_labels = ['loss'] <ide> metrics = ['loss', 'val_loss'] <add> <add> sample_weight_list = [standardize_weights(y[i], <add> sample_weight=sample_weight_list[i], <add> class_weight=class_weight_list[i]) for i in range(len(self.output_order))] <add> ins = X + y + sample_weight_list <add> <ide> history = self._fit(f, ins, out_labels=out_labels, batch_size=batch_size, nb_epoch=nb_epoch, <ide> verbose=verbose, callbacks=callbacks, <del> validation_split=validation_split, val_f=val_f, val_ins=val_ins, <add> val_f=val_f, val_ins=val_ins, <ide> shuffle=shuffle, metrics=metrics) <ide> return history <ide> <ide> def evaluate(self, data, batch_size=128, verbose=0, sample_weight={}): <del> sample_weight = [standardize_weights(data[name], sample_weight.get(name)) for name in self.output_order] <add> sample_weight = [standardize_weights(data[name], <add> sample_weight=sample_weight.get(name)) for name in self.output_order] <ide> <ide> ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight <ide> outs = self._test_loop(self._test, ins, batch_size, verbose) <ide><path>tests/auto/test_graph_model.py <ide> def test_2o_1i_sample_weights(self): <ide> <ide> weights1 = np.random.uniform(size=y_train.shape[0]) <ide> weights2 = np.random.uniform(size=y2_train.shape[0]) <add> weights1_test = np.random.uniform(size=y_test.shape[0]) <add> weights2_test = np.random.uniform(size=y2_test.shape[0]) <ide> <ide> graph.compile('rmsprop', {'output1': 'mse', 'output2': 'mse'}) <ide> <ide> def test_2o_1i_sample_weights(self): <ide> assert(type(out == dict)) <ide> assert(len(out) == 2) <ide> loss = graph.test_on_batch({'input1': X_test, 'output1': y_test, 'output2': y2_test}, <del> sample_weight={'output1': weights1, 'output2': weights2}) <add> sample_weight={'output1': weights1_test, 'output2': weights2_test}) <ide> loss = graph.train_on_batch({'input1': X_train, 'output1': y_train, 'output2': y2_train}, <ide> sample_weight={'output1': weights1, 'output2': weights2}) <ide> loss = graph.evaluate({'input1': X_train, 'output1': y_train, 'output2': y2_train}, <ide> sample_weight={'output1': weights1, 'output2': weights2}) <del> print(loss) <ide> <ide> def test_recursive(self): <ide> print('test layer-like API')
2
Text
Text
fetch data in componentdidmount instead
774f5a022eacbb054b09aa5a7d596186874b2600
<ide><path>docs/docs/tutorial.md <ide> var CommentBox = React.createClass({ <ide> getInitialState: function() { <ide> return {data: []}; <ide> }, <del> componentWillMount: function() { <add> componentDidMount: function() { <ide> $.ajax({ <ide> url: this.props.url, <ide> dataType: 'json', <ide> var CommentBox = React.createClass({ <ide> }); <ide> ``` <ide> <del>Here, `componentWillMount` is a method called automatically by React before a component is rendered. The key to dynamic updates is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is only a minor change to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies. <add>Here, `componentDidMount` is a method called automatically by React when a component is rendered. The key to dynamic updates is the call to `this.setState()`. We replace the old array of comments with the new one from the server and the UI automatically updates itself. Because of this reactivity, it is only a minor change to add live updates. We will use simple polling here but you could easily use WebSockets or other technologies. <ide> <ide> ```javascript{3,19-20,34} <ide> // tutorial14.js <ide> var CommentBox = React.createClass({ <ide> getInitialState: function() { <ide> return {data: []}; <ide> }, <del> componentWillMount: function() { <add> componentDidMount: function() { <ide> this.loadCommentsFromServer(); <ide> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <ide> }, <ide> var CommentBox = React.createClass({ <ide> getInitialState: function() { <ide> return {data: []}; <ide> }, <del> componentWillMount: function() { <add> componentDidMount: function() { <ide> this.loadCommentsFromServer(); <ide> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <ide> }, <ide> var CommentBox = React.createClass({ <ide> getInitialState: function() { <ide> return {data: []}; <ide> }, <del> componentWillMount: function() { <add> componentDidMount: function() { <ide> this.loadCommentsFromServer(); <ide> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <ide> }, <ide> var CommentBox = React.createClass({ <ide> getInitialState: function() { <ide> return {data: []}; <ide> }, <del> componentWillMount: function() { <add> componentDidMount: function() { <ide> this.loadCommentsFromServer(); <ide> setInterval(this.loadCommentsFromServer, this.props.pollInterval); <ide> },
1
Text
Text
update changelog for 2.9.0
f381a441f0a963ef4176c86492f41edc642b7a10
<ide><path>CHANGELOG.md <ide> <ide> - [#14156](https://github.com/emberjs/ember.js/pull/14156) [FEATURE ember-glimmer] Enable by default. <ide> <add>### 2.9.0 (October 17, 2016) <add> <add>- No changes from 2.8.2. <add> <ide> ### 2.8.2 (October 6, 2016) <ide> <ide> - [#14365](https://github.com/emberjs/ember.js/pull/14365) [BUGFIX] Fix an issue with URLs with encoded characters and a trailing slash.
1