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 | use ascii order for md refs | ccc50a982044812e9e307a4626442c564cd60cf8 | <ide><path>doc/api/assert.md
<ide> argument.
<ide> [SameValue Comparison]: https://tc39.github.io/ecma262/#sec-samevalue
<ide> [Strict Equality Comparison]: https://tc39.github.io/ecma262/#sec-strict-equality-comparison
<ide> [`AssertionError`]: #assert_class_assert_assertionerror
<add>[`CallTracker`]: #assert_class_assert_calltracker
<ide> [`Class`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
<ide> [`ERR_INVALID_RETURN_VALUE`]: errors.md#errors_err_invalid_return_value
<ide> [`Error.captureStackTrace`]: errors.md#errors_error_capturestacktrace_targetobject_constructoropt
<ide> argument.
<ide> [`TypeError`]: errors.md#errors_class_typeerror
<ide> [`WeakMap`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
<ide> [`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet
<del>[`CallTracker`]: #assert_class_assert_calltracker
<ide> [`assert.deepEqual()`]: #assert_assert_deepequal_actual_expected_message
<ide> [`assert.deepStrictEqual()`]: #assert_assert_deepstrictequal_actual_expected_message
<ide> [`assert.doesNotThrow()`]: #assert_assert_doesnotthrow_fn_error_message
<ide> argument.
<ide> [`process.on('exit')`]: process.md#process_event_exit
<ide> [`tracker.calls()`]: #assert_tracker_calls_fn_exact
<ide> [`tracker.verify()`]: #assert_tracker_verify
<del>[strict assertion mode]: #assert_strict_assertion_mode
<ide> [enumerable "own" properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
<ide> [prototype-spec]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
<add>[strict assertion mode]: #assert_strict_assertion_mode
<ide><path>doc/api/async_hooks.md
<ide> The documentation for this class has moved [`AsyncLocalStorage`][].
<ide> [PromiseHooks]: https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit
<ide> [`AsyncLocalStorage`]: async_context.md#async_context_class_asynclocalstorage
<ide> [`AsyncResource`]: async_context.md#async_context_class_asyncresource
<add>[`Worker`]: worker_threads.md#worker_threads_class_worker
<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>[`Worker`]: worker_threads.md#worker_threads_class_worker
<ide> [promise execution tracking]: #async_hooks_promise_execution_tracking
<ide><path>doc/api/cluster.md
<ide> socket.on('data', (id) => {
<ide> [`child_process.fork()`]: child_process.md#child_process_child_process_fork_modulepath_args_options
<ide> [`child_process` event: `'exit'`]: child_process.md#child_process_event_exit
<ide> [`child_process` event: `'message'`]: child_process.md#child_process_event_message
<add>[`cluster.isPrimary`]: #cluster_cluster_isprimary
<ide> [`cluster.settings`]: #cluster_cluster_settings
<ide> [`disconnect()`]: child_process.md#child_process_subprocess_disconnect
<del>[`cluster.isPrimary`]: #cluster_cluster_isprimary
<ide> [`kill()`]: process.md#process_process_kill_pid_signal
<ide> [`process` event: `'message'`]: process.md#process_event_message
<ide> [`server.close()`]: net.md#net_event_close
<ide><path>doc/api/crypto.md
<ide> See the [list of SSL OP Flags][] for details.
<ide> [AEAD algorithms]: https://en.wikipedia.org/wiki/Authenticated_encryption
<ide> [CCM mode]: #crypto_ccm_mode
<ide> [Caveats]: #crypto_support_for_weak_or_compromised_algorithms
<del>[caveats when using strings as inputs to cryptographic APIs]: #crypto_using_strings_as_inputs_to_cryptographic_apis
<ide> [Crypto constants]: #crypto_crypto_constants_1
<ide> [HTML 5.2]: https://www.w3.org/TR/html52/changes.html#features-removed
<ide> [HTML5's `keygen` element]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen
<ide> See the [list of SSL OP Flags][] for details.
<ide> [`util.promisify()`]: util.md#util_util_promisify_original
<ide> [`verify.update()`]: #crypto_verify_update_data_inputencoding
<ide> [`verify.verify()`]: #crypto_verify_verify_object_signature_signatureencoding
<add>[caveats when using strings as inputs to cryptographic APIs]: #crypto_using_strings_as_inputs_to_cryptographic_apis
<ide> [certificate object]: tls.md#tls_certificate_object
<ide> [encoding]: buffer.md#buffer_buffers_and_character_encodings
<ide> [initialization vector]: https://en.wikipedia.org/wiki/Initialization_vector
<ide><path>doc/api/diagnostics_channel.md
<ide> channel.subscribe(onMessage);
<ide> channel.unsubscribe(onMessage);
<ide> ```
<ide>
<del>[`diagnostics_channel.channel(name)`]: #diagnostics_channel_diagnostics_channel_channel_name
<del>[`channel.subscribe(onMessage)`]: #diagnostics_channel_channel_subscribe_onmessage
<ide> [`'uncaughtException'`]: process.md#process_event_uncaughtexception
<add>[`channel.subscribe(onMessage)`]: #diagnostics_channel_channel_subscribe_onmessage
<add>[`diagnostics_channel.channel(name)`]: #diagnostics_channel_diagnostics_channel_channel_name
<ide><path>doc/api/esm.md
<ide> success!
<ide> [`data:` URLs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
<ide> [`export`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
<ide> [`import()`]: #esm_import_expressions
<del>[`import.meta.url`]: #esm_import_meta_url
<ide> [`import.meta.resolve`]: #esm_import_meta_resolve_specifier_parent
<add>[`import.meta.url`]: #esm_import_meta_url
<ide> [`import`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
<ide> [`module.createRequire()`]: module.md#module_module_createrequire_filename
<ide> [`module.syncBuiltinESMExports()`]: module.md#module_module_syncbuiltinesmexports
<ide> [`package.json`]: packages.md#packages_node_js_package_json_field_definitions
<ide> [`process.dlopen`]: process.md#process_process_dlopen_module_filename_flags
<del>[`transformSource` hook]: #esm_transformsource_source_context_defaulttransformsource
<ide> [`string`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
<add>[`transformSource` hook]: #esm_transformsource_source_context_defaulttransformsource
<ide> [`util.TextDecoder`]: util.md#util_class_util_textdecoder
<ide> [cjs-module-lexer]: https://github.com/guybedford/cjs-module-lexer/tree/1.2.1
<ide> [custom https loader]: #esm_https_loader
<ide><path>doc/api/events.md
<ide> to the `EventTarget`.
<ide> [`fs.ReadStream`]: fs.md#fs_class_fs_readstream
<ide> [`net.Server`]: net.md#net_class_net_server
<ide> [`process.on('warning')`]: process.md#process_event_warning
<del>[stream]: stream.md
<ide> [capturerejections]: #events_capture_rejections_of_promises
<add>[error]: #events_error_events
<ide> [rejection]: #events_emitter_symbol_for_nodejs_rejection_err_eventname_args
<ide> [rejectionsymbol]: #events_events_capturerejectionsymbol
<del>[error]: #events_error_events
<add>[stream]: stream.md
<ide><path>doc/api/fs.md
<ide> the file contents.
<ide> [Naming Files, Paths, and Namespaces]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file
<ide> [Readable Stream]: stream.md#stream_class_stream_readable
<ide> [Writable Stream]: stream.md#stream_class_stream_writable
<del>[caveats]: #fs_caveats
<ide> [`AHAFS`]: https://developer.ibm.com/articles/au-aix_event_infrastructure/
<ide> [`Buffer.byteLength`]: buffer.md#buffer_static_method_buffer_bytelength_string_encoding
<ide> [`FSEvents`]: https://developer.apple.com/documentation/coreservices/file_system_events
<ide> the file contents.
<ide> [`kqueue(2)`]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
<ide> [`util.promisify()`]: util.md#util_util_promisify_original
<ide> [bigints]: https://tc39.github.io/proposal-bigint
<add>[caveats]: #fs_caveats
<ide> [chcp]: https://ss64.com/nt/chcp.html
<ide> [inode]: https://en.wikipedia.org/wiki/Inode
<ide> [support of file system `flags`]: #fs_file_system_flags
<ide><path>doc/api/http.md
<ide> try {
<ide> }
<ide> ```
<ide>
<del>[`--insecure-http-parser`]: cli.md#cli_insecure_http_parser
<del>[`--max-http-header-size`]: cli.md#cli_max_http_header_size_size
<ide> [`'checkContinue'`]: #http_event_checkcontinue
<ide> [`'finish'`]: #http_event_finish
<ide> [`'request'`]: #http_event_request
<ide> [`'response'`]: #http_event_response
<ide> [`'upgrade'`]: #http_event_upgrade
<add>[`--insecure-http-parser`]: cli.md#cli_insecure_http_parser
<add>[`--max-http-header-size`]: cli.md#cli_max_http_header_size_size
<ide> [`Agent`]: #http_class_http_agent
<ide> [`Buffer.byteLength()`]: buffer.md#buffer_static_method_buffer_bytelength_string_encoding
<ide> [`Duplex`]: stream.md#stream_class_stream_duplex
<ide> try {
<ide> [`http.Agent`]: #http_class_http_agent
<ide> [`http.ClientRequest`]: #http_class_http_clientrequest
<ide> [`http.IncomingMessage`]: #http_class_http_incomingmessage
<del>[`http.Server`]: #http_class_http_server
<ide> [`http.ServerResponse`]: #http_class_http_serverresponse
<add>[`http.Server`]: #http_class_http_server
<ide> [`http.get()`]: #http_http_get_options_callback
<ide> [`http.globalAgent`]: #http_http_globalagent
<ide> [`http.request()`]: #http_http_request_options_callback
<ide> [`message.headers`]: #http_message_headers
<add>[`message.socket`]: #http_message_socket
<ide> [`net.Server.close()`]: net.md#net_server_close_callback
<ide> [`net.Server`]: net.md#net_class_net_server
<ide> [`net.Socket`]: net.md#net_class_net_socket
<ide> [`net.createConnection()`]: net.md#net_net_createconnection_options_connectlistener
<ide> [`new URL()`]: url.md#url_new_url_input_base
<del>[`message.socket`]: #http_message_socket
<ide> [`outgoingMessage.socket`]: #http_outgoingMessage.socket
<ide> [`removeHeader(name)`]: #http_request_removeheader_name
<del>[`request.end()`]: #http_request_end_data_encoding_callback
<ide> [`request.destroy()`]: #http_request_destroy_error
<add>[`request.end()`]: #http_request_end_data_encoding_callback
<ide> [`request.flushHeaders()`]: #http_request_flushheaders
<ide> [`request.getHeader()`]: #http_request_getheader_name
<ide> [`request.setHeader()`]: #http_request_setheader_name_value
<ide> [`request.setTimeout()`]: #http_request_settimeout_timeout_callback
<ide> [`request.socket.getPeerCertificate()`]: tls.md#tls_tlssocket_getpeercertificate_detailed
<ide> [`request.socket`]: #http_request_socket
<del>[`request.writableFinished`]: #http_request_writablefinished
<ide> [`request.writableEnded`]: #http_request_writableended
<add>[`request.writableFinished`]: #http_request_writablefinished
<ide> [`request.write(data, encoding)`]: #http_request_write_chunk_encoding_callback
<ide> [`response.end()`]: #http_response_end_data_encoding_callback
<ide> [`response.getHeader()`]: #http_response_getheader_name
<ide> [`response.setHeader()`]: #http_response_setheader_name_value
<ide> [`response.socket`]: #http_response_socket
<del>[`response.writableFinished`]: #http_response_writablefinished
<ide> [`response.writableEnded`]: #http_response_writableended
<add>[`response.writableFinished`]: #http_response_writablefinished
<ide> [`response.write()`]: #http_response_write_chunk_encoding_callback
<ide> [`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback
<ide> [`response.writeContinue()`]: #http_response_writecontinue
<ide><path>doc/api/http2.md
<ide> you need to implement any fall-back behavior yourself.
<ide> [RFC 7838]: https://tools.ietf.org/html/rfc7838
<ide> [RFC 8336]: https://tools.ietf.org/html/rfc8336
<ide> [RFC 8441]: https://tools.ietf.org/html/rfc8441
<add>[Sensitive headers]: #http2_sensitive_headers
<ide> [`'checkContinue'`]: #http2_event_checkcontinue
<ide> [`'connect'`]: #http2_event_connect
<ide> [`'request'`]: #http2_event_request
<ide> you need to implement any fall-back behavior yourself.
<ide> [`net.connect()`]: net.md#net_net_connect
<ide> [`net.createServer()`]: net.md#net_net_createserver_options_connectionlistener
<ide> [`request.authority`]: #http2_request_authority
<del>[`request.socket`]: #http2_request_socket
<ide> [`request.socket.getPeerCertificate()`]: tls.md#tls_tlssocket_getpeercertificate_detailed
<add>[`request.socket`]: #http2_request_socket
<ide> [`response.end()`]: #http2_response_end_data_encoding_callback
<ide> [`response.setHeader()`]: #http2_response_setheader_name_value
<ide> [`response.socket`]: #http2_response_socket
<ide> you need to implement any fall-back behavior yourself.
<ide> [`tls.createServer()`]: tls.md#tls_tls_createserver_options_secureconnectionlistener
<ide> [`writable.writableFinished`]: stream.md#stream_writable_writablefinished
<ide> [error code]: #http2_error_codes_for_rst_stream_and_goaway
<del>[Sensitive headers]: #http2_sensitive_headers
<ide><path>doc/api/modules.md
<ide> This section was moved to
<ide> [`Error`]: errors.md#errors_class_error
<ide> [`__dirname`]: #modules_dirname
<ide> [`__filename`]: #modules_filename
<del>[`module` object]: #modules_the_module_object
<del>[`module.id`]: #modules_module_id
<ide> [`module.children`]: #modules_module_children
<add>[`module.id`]: #modules_module_id
<add>[`module` object]: #modules_the_module_object
<ide> [`package.json`]: packages.md#packages_node_js_package_json_field_definitions
<ide> [`path.dirname()`]: path.md#path_path_dirname_path
<ide> [`require.main`]: #modules_require_main
<ide><path>doc/api/packages.md
<ide> Import maps permit mapping to external packages.
<ide> This field defines [subpath imports][] for the current package.
<ide>
<ide> [Babel]: https://babeljs.io/
<del>[Conditional exports]: #packages_conditional_exports
<ide> [CommonJS]: modules.md
<add>[Conditional exports]: #packages_conditional_exports
<ide> [ES module]: esm.md
<ide> [ES modules]: esm.md
<ide> [Node.js documentation for this section]: https://github.com/nodejs/node/blob/HEAD/doc/api/packages.md#conditions-definitions
<del>[`ERR_PACKAGE_PATH_NOT_EXPORTED`]: errors.md#errors_err_package_path_not_exported
<del>[`esm`]: https://github.com/standard-things/esm#readme
<ide> [`"exports"`]: #packages_exports
<add>[`"imports"`]: #packages_imports
<ide> [`"main"`]: #packages_main
<ide> [`"name"`]: #packages_name
<del>[`"imports"`]: #packages_imports
<ide> [`"type"`]: #packages_type
<add>[`ERR_PACKAGE_PATH_NOT_EXPORTED`]: errors.md#errors_err_package_path_not_exported
<add>[`esm`]: https://github.com/standard-things/esm#readme
<ide> [`package.json`]: #packages_node_js_package_json_field_definitions
<ide> [entry points]: #packages_package_entry_points
<ide> [self-reference]: #packages_self_referencing_a_package_using_its_name
<ide> [subpath exports]: #packages_subpath_exports
<ide> [subpath imports]: #packages_subpath_imports
<ide> [subpath patterns]: #packages_subpath_patterns
<del>[the full specifier path]: esm.md#esm_mandatory_file_extensions
<ide> [the dual CommonJS/ES module packages section]: #packages_dual_commonjs_es_module_packages
<add>[the full specifier path]: esm.md#esm_mandatory_file_extensions
<ide><path>doc/api/stream.md
<ide> contain multi-byte characters.
<ide> [HTTP requests, on the client]: http.md#http_class_http_clientrequest
<ide> [HTTP responses, on the server]: http.md#http_class_http_serverresponse
<ide> [TCP sockets]: net.md#net_class_net_socket
<add>[Three states]: #stream_three_states
<ide> [`'data'`]: #stream_event_data
<ide> [`'drain'`]: #stream_event_drain
<ide> [`'end'`]: #stream_event_end
<ide> contain multi-byte characters.
<ide> [`readable.push('')`]: #stream_readable_push
<ide> [`readable.setEncoding()`]: #stream_readable_setencoding_encoding
<ide> [`stream.Readable.from()`]: #stream_stream_readable_from_iterable_options
<add>[`stream.addAbortSignal()`]: #stream_stream_addabortsignal_signal_stream
<ide> [`stream.cork()`]: #stream_writable_cork
<ide> [`stream.finished()`]: #stream_stream_finished_stream_options_callback
<ide> [`stream.pipe()`]: #stream_readable_pipe_destination_options
<ide> [`stream.pipeline()`]: #stream_stream_pipeline_source_transforms_destination_callback
<del>[`stream.addAbortSignal()`]: #stream_stream_addabortsignal_signal_stream
<ide> [`stream.uncork()`]: #stream_writable_uncork
<ide> [`stream.unpipe()`]: #stream_readable_unpipe_destination
<ide> [`stream.wrap()`]: #stream_readable_wrap_stream
<ide> contain multi-byte characters.
<ide> [stream-resume]: #stream_readable_resume
<ide> [stream-uncork]: #stream_writable_uncork
<ide> [stream-write]: #stream_writable_write_chunk_encoding_callback
<del>[Three states]: #stream_three_states
<ide> [writable-_construct]: #stream_writable_construct_callback
<ide> [writable-_destroy]: #stream_writable_destroy_err_callback
<ide> [writable-destroy]: #stream_writable_destroy_error
<ide><path>doc/api/tls.md
<ide> added: v11.4.0
<ide> [Session Resumption]: #tls_session_resumption
<ide> [Stream]: stream.md#stream_stream
<ide> [TLS recommendations]: https://wiki.mozilla.org/Security/Server_Side_TLS
<del>[`--tls-cipher-list`]: cli.md#cli_tls_cipher_list_list
<del>[`Duplex`]: stream.md#stream_class_stream_duplex
<del>[`NODE_OPTIONS`]: cli.md#cli_node_options_options
<ide> [`'newSession'`]: #tls_event_newsession
<ide> [`'resumeSession'`]: #tls_event_resumesession
<ide> [`'secureConnect'`]: #tls_event_secureconnect
<ide> [`'secureConnection'`]: #tls_event_secureconnection
<ide> [`'session'`]: #tls_event_session
<add>[`--tls-cipher-list`]: cli.md#cli_tls_cipher_list_list
<add>[`Duplex`]: stream.md#stream_class_stream_duplex
<add>[`NODE_OPTIONS`]: cli.md#cli_node_options_options
<ide> [`SSL_export_keying_material`]: https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html
<ide> [`SSL_get_version`]: https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html
<ide> [`crypto.getCurves()`]: crypto.md#crypto_crypto_getcurves
<ide> added: v11.4.0
<ide> [cipher list format]: https://www.openssl.org/docs/man1.1.1/man1/ciphers.html#CIPHER-LIST-FORMAT
<ide> [forward secrecy]: https://en.wikipedia.org/wiki/Perfect_forward_secrecy
<ide> [modifying the default cipher suite]: #tls_modifying_the_default_tls_cipher_suite
<del>[specific attacks affecting larger AES key sizes]: https://www.schneier.com/blog/archives/2009/07/another_new_aes.html
<ide> [perfect forward secrecy]: #tls_perfect_forward_secrecy
<add>[specific attacks affecting larger AES key sizes]: https://www.schneier.com/blog/archives/2009/07/another_new_aes.html
<ide><path>doc/api/url.md
<ide> console.log(myURL.origin);
<ide>
<ide> [ICU]: intl.md#intl_options_for_building_node_js
<ide> [Punycode]: https://tools.ietf.org/html/rfc5891#section-4.4
<del>[WHATWG URL Standard]: https://url.spec.whatwg.org/
<ide> [WHATWG URL]: #url_the_whatwg_url_api
<add>[WHATWG URL Standard]: https://url.spec.whatwg.org/
<ide> [`Error`]: errors.md#errors_class_error
<ide> [`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
<ide> [`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
<ide><path>doc/api/worker_threads.md
<ide> thread spawned will spawn another until the application crashes.
<ide> [`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
<ide> [`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
<ide> [`WebAssembly.Module`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module
<add>[`Worker constructor options`]: #worker_threads_new_worker_filename_options
<ide> [`Worker`]: #worker_threads_class_worker
<ide> [`cluster` module]: cluster.md
<ide> [`data:` URL]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
<ide> thread spawned will spawn another until the application crashes.
<ide> [`process.title`]: process.md#process_process_title
<ide> [`require('worker_threads').isMainThread`]: #worker_threads_worker_ismainthread
<ide> [`require('worker_threads').parentPort.on('message')`]: #worker_threads_event_message
<del>[`require('worker_threads').parentPort`]: #worker_threads_worker_parentport
<ide> [`require('worker_threads').parentPort.postMessage()`]: #worker_threads_worker_postmessage_value_transferlist
<add>[`require('worker_threads').parentPort`]: #worker_threads_worker_parentport
<ide> [`require('worker_threads').threadId`]: #worker_threads_worker_threadid
<ide> [`require('worker_threads').workerData`]: #worker_threads_worker_workerdata
<ide> [`trace_events`]: tracing.md
<ide> [`v8.getHeapSnapshot()`]: v8.md#v8_v8_getheapsnapshot
<ide> [`vm`]: vm.md
<del>[`Worker constructor options`]: #worker_threads_new_worker_filename_options
<add>[`worker.SHARE_ENV`]: #worker_threads_worker_share_env
<ide> [`worker.on('message')`]: #worker_threads_event_message_1
<ide> [`worker.postMessage()`]: #worker_threads_worker_postmessage_value_transferlist
<del>[`worker.SHARE_ENV`]: #worker_threads_worker_share_env
<ide> [`worker.terminate()`]: #worker_threads_worker_terminate
<ide> [`worker.threadId`]: #worker_threads_worker_threadid_1
<ide> [async-resource-worker-pool]: async_hooks.md#async-resource-worker-pool
<ide><path>src/README.md
<ide> static void GetUserInfo(const FunctionCallbackInfo<Value>& args) {
<ide> [exception handling]: #exception-handling
<ide> [internal field]: #internal-fields
<ide> [introduction for V8 embedders]: https://v8.dev/docs/embed
<add>[libuv]: https://libuv.org/
<ide> [libuv handles]: #libuv-handles-and-requests
<ide> [libuv requests]: #libuv-handles-and-requests
<del>[libuv]: https://libuv.org/
<ide> [reference documentation for the libuv API]: http://docs.libuv.org/en/v1.x/ | 17 |
PHP | PHP | allow pgsql enum fields /w reserved words as names | 9a4ae9e13f126aedb4e22d9d3e2a7fdb52d6e14a | <ide><path>src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php
<ide> protected function typeEnum(Fluent $column)
<ide> {
<ide> $allowed = array_map(function($a) { return "'".$a."'"; }, $column->allowed);
<ide>
<del> return "varchar(255) check ({$column->name} in (".implode(', ', $allowed)."))";
<add> return "varchar(255) check (\"{$column->name}\" in (".implode(', ', $allowed)."))";
<ide> }
<ide>
<ide> /**
<ide><path>tests/Database/DatabasePostgresSchemaGrammarTest.php
<ide> public function testAddingEnum()
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<ide> $this->assertEquals(1, count($statements));
<del> $this->assertEquals('alter table "users" add column "foo" varchar(255) check (foo in (\'bar\', \'baz\')) not null', $statements[0]);
<add> $this->assertEquals('alter table "users" add column "foo" varchar(255) check ("foo" in (\'bar\', \'baz\')) not null', $statements[0]);
<ide> }
<ide>
<ide> | 2 |
Mixed | Javascript | add createrequirefunction method | 246f6332e5a5f395d1e39a3594ee5d6fe869d622 | <ide><path>doc/api/modules.md
<ide> by the [module wrapper][]. To access it, require the `Module` module:
<ide> const builtin = require('module').builtinModules;
<ide> ```
<ide>
<add>### module.createRequireFromPath(filename)
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>* `filename` {string} Filename to be used to construct the relative require
<add> function.
<add>* Returns: {[`require`][]} Require function
<add>
<add>```js
<add>const { createRequireFromPath } = require('module');
<add>const requireUtil = createRequireFromPath('../src/utils');
<add>
<add>// require `../src/utils/some-tool`
<add>requireUtil('./some-tool');
<add>```
<add>
<ide> [`__dirname`]: #modules_dirname
<ide> [`__filename`]: #modules_filename
<ide> [`Error`]: errors.html#errors_class_error
<ide> [`module` object]: #modules_the_module_object
<ide> [`path.dirname()`]: path.html#path_path_dirname_path
<ide> [GLOBAL_FOLDERS]: #modules_loading_from_the_global_folders
<add>[`require`]: #modules_require
<ide> [exports shortcut]: #modules_exports_shortcut
<ide> [module resolution]: #modules_all_together
<ide> [module wrapper]: #modules_the_module_wrapper
<ide><path>lib/internal/modules/cjs/loader.js
<ide>
<ide> const { internalBinding, NativeModule } = require('internal/bootstrap/loaders');
<ide> const util = require('util');
<add>const { pathToFileURL } = require('internal/url');
<ide> const vm = require('vm');
<ide> const assert = require('assert').ok;
<ide> const fs = require('fs');
<ide> module.exports = Module;
<ide> let asyncESM;
<ide> let ModuleJob;
<ide> let createDynamicModule;
<del>let pathToFileURL;
<ide> let decorateErrorStack;
<ide>
<ide> function lazyLoadESM() {
<ide> function lazyLoadESM() {
<ide> createDynamicModule = require(
<ide> 'internal/modules/esm/create_dynamic_module');
<ide> decorateErrorStack = require('internal/util').decorateErrorStack;
<del> pathToFileURL = require('internal/url').pathToFileURL;
<ide> }
<ide>
<ide> const {
<ide> Module.runMain = function() {
<ide> process._tickCallback();
<ide> };
<ide>
<add>Module.createRequireFromPath = (filename) => {
<add> const m = new Module(filename);
<add> m.filename = filename;
<add> m.paths = Module._nodeModulePaths(path.dirname(filename));
<add> return makeRequireFunction(m);
<add>};
<add>
<ide> Module._initPaths = function() {
<ide> var homeDir;
<ide> var nodePath;
<ide><path>test/parallel/test-module-create-require.js
<add>'use strict';
<add>
<add>require('../common');
<add>const assert = require('assert');
<add>const path = require('path');
<add>
<add>const { createRequireFromPath } = require('module');
<add>
<add>const p = path.resolve(__dirname, '..', 'fixtures', 'fake.js');
<add>
<add>const req = createRequireFromPath(p);
<add>assert.strictEqual(req('./baz'), 'perhaps I work'); | 3 |
Ruby | Ruby | make enhanced routing concerns more tell-don't-ask | 05136e5c0b3d7b841bdec53847879321309604d3 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def name_for_action(as, action) #:nodoc:
<ide> end
<ide> end
<ide>
<del> # Routing Concerns allows you to declare common routes that can be reused
<add> # Routing Concerns allow you to declare common routes that can be reused
<ide> # inside others resources and routes.
<ide> #
<ide> # concern :commentable do
<ide> def name_for_action(as, action) #:nodoc:
<ide> # concerns :commentable
<ide> # end
<ide> module Concerns
<del> # Define a routing concern using a name. If a second parameter is
<del> # supplied, it should respond to call, which will receive the mapper
<del> # as a parameter, allowing for customized behavior based on the current
<del> # scope.
<add> # Define a routing concern using a name.
<ide> #
<del> # concern :commentable do
<del> # resources :comments
<add> # Concerns may be defined inline, using a block, or handled by
<add> # another object, by passing that object as the second parameter.
<add> #
<add> # The concern object, if supplied, should respond to <tt>call</tt>,
<add> # which will receive two parameters:
<add> #
<add> # * The current mapper
<add> # * A hash of options which the concern object may use
<add> #
<add> # Options may also be used by concerns defined in a block by accepting
<add> # a block parameter. So, using a block, you might do something as
<add> # simple as limit the actions available on certain resources, passing
<add> # standard resource options through the concern:
<add> #
<add> # concern :commentable do |options|
<add> # resources :comments, options
<add> # end
<add> #
<add> # resources :posts, concerns: :commentable
<add> # resources :archived_posts do
<add> # # Don't allow comments on archived posts
<add> # concerns :commentable, only: [:index, :show]
<ide> # end
<ide> #
<del> # # - or -
<add> # Or, using a callable object, you might implement something more
<add> # specific to your application, which would be out of place in your
<add> # routes file.
<ide> #
<del> # class Commentable
<del> # def self.call(mapper)
<del> # if mapper.current_scope[:controller] == 'videos'
<del> # mapper.resources :video_comments, as: :comments
<del> # else
<del> # mapper.resources :comments
<del> # end
<add> # # purchasable.rb
<add> # class Purchasable
<add> # def initialize(defaults = {})
<add> # @defaults = defaults
<add> # end
<add> #
<add> # def call(mapper, options = {})
<add> # options = @defaults.merge(options)
<add> # mapper.resources :purchases
<add> # mapper.resources :receipts
<add> # mapper.resources :returns if options[:returnable]
<ide> # end
<ide> # end
<ide> #
<del> # concern :commentable, Commentable
<add> # # routes.rb
<add> # concern :purchasable, Purchasable.new(returnable: true)
<add> #
<add> # resources :toys, concerns: :purchasable
<add> # resources :electronics, concerns: :purchasable
<add> # resources :pets do
<add> # concerns :purchasable, returnable: false
<add> # end
<ide> #
<del> # Any routing helpers can be used inside a concern.
<add> # Any routing helpers can be used inside a concern. If using a
<add> # callable, they're accessible from the Mapper that's passed to
<add> # <tt>call</tt>.
<ide> def concern(name, callable = nil, &block)
<del> @concerns[name] = callable || lambda { |m| m.instance_eval(&block) }
<add> callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) }
<add> @concerns[name] = callable
<ide> end
<ide>
<ide> # Use the named concerns
<ide> def concern(name, callable = nil, &block)
<ide> # namespace :posts do
<ide> # concerns :commentable
<ide> # end
<del> def concerns(*names)
<del> names.flatten.each do |name|
<add> def concerns(*args)
<add> options = args.extract_options!
<add> args.flatten.each do |name|
<ide> if concern = @concerns[name]
<del> concern.call(self)
<add> concern.call(self, options)
<ide> else
<ide> raise ArgumentError, "No concern named #{name} was found!"
<ide> end
<ide> def initialize(set) #:nodoc:
<ide> @concerns = {}
<ide> end
<ide>
<del> def current_scope
<del> @scope
<del> end
<del>
<ide> include Base
<ide> include HttpHelpers
<ide> include Redirection
<ide><path>actionpack/test/dispatch/routing/concerns_test.rb
<ide>
<ide> class RoutingConcernsTest < ActionDispatch::IntegrationTest
<ide> class Reviewable
<del> def self.call(mapper)
<del> if mapper.current_scope[:controller] == 'posts'
<del> mapper.resources :reviews
<del> elsif mapper.current_scope[:controller] == 'videos'
<del> mapper.resources :reviews, as: :video_reviews
<del> end
<add> def self.call(mapper, options = {})
<add> mapper.resources :reviews, options
<ide> end
<ide> end
<ide>
<ide> Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
<ide> app.draw do
<del> concern :commentable do
<del> resources :comments
<add> concern :commentable do |options|
<add> resources :comments, options
<ide> end
<ide>
<ide> concern :image_attachable do
<ide> def self.call(mapper)
<ide> concern :reviewable, Reviewable
<ide>
<ide> resources :posts, concerns: [:commentable, :image_attachable, :reviewable] do
<del> resource :video, concerns: [:commentable, :reviewable]
<add> resource :video, concerns: :commentable do
<add> concerns :reviewable, as: :video_reviews
<add> end
<ide> end
<ide>
<ide> resource :picture, concerns: :commentable do
<ide> resources :posts, concerns: :commentable
<ide> end
<ide>
<ide> scope "/videos" do
<del> concerns :commentable
<add> concerns :commentable, except: :destroy
<ide> end
<ide> end
<ide> end
<ide> def test_accessing_concern_from_resources_using_only_option
<ide> assert_equal "404", @response.code
<ide> end
<ide>
<del> def test_accessing_callable_concern_from_resources
<add> def test_accessing_callable_concern_
<ide> get "/posts/1/reviews/1"
<ide> assert_equal "200", @response.code
<ide> assert_equal "/posts/1/reviews/1", post_review_path(post_id: 1, id: 1)
<ide> end
<ide>
<del> def test_callable_concern_can_adapt_to_mapper
<add> def test_callable_concerns_accept_options
<ide> get "/posts/1/video/reviews/1"
<ide> assert_equal "200", @response.code
<ide> assert_equal "/posts/1/video/reviews/1", post_video_video_review_path(post_id: 1, id: 1)
<ide> def test_accessing_concern_from_a_scope
<ide> assert_equal "200", @response.code
<ide> end
<ide>
<add> def test_concerns_accept_options
<add> delete "/videos/comments/1"
<add> assert_equal "404", @response.code
<add> end
<add>
<ide> def test_with_an_invalid_concern_name
<ide> e = assert_raise ArgumentError do
<ide> ActionDispatch::Routing::RouteSet.new.tap do |app| | 2 |
Text | Text | add privacy consideration note | f3e1c59c920a38533290fd5f4ac52cd5252f90bb | <ide><path>curriculum/challenges/english/09-information-security/information-security-projects/stock-price-checker.md
<ide> When you are done, make sure a working demo of your project is hosted somewhere
<ide> 3. You will add any security features to `server.js`
<ide> 4. You will create all of the functional tests in `tests/2_functional-tests.js`
<ide>
<add>**Note** Privacy Considerations: Due to the requirement that only 1 like per IP should be accepted, you will have to save IP addresses. It is important to remain compliant with data privacy laws such as the General Data Protection Regulation. One option is to get permission to save the user's data, but it is much simpler to anonymize it. For this challenge, remember to anonymize IP addresses before saving them to the database. If you need ideas on how to do this, you may choose to hash the data, truncate it, or set part of the IP address to 0.
<add>
<ide> Write the following tests in `tests/2_functional-tests.js`:
<ide>
<ide> - Viewing one stock: GET request to `/api/stock-prices/` | 1 |
Python | Python | fix exception causes in __init__.py | 5dd1fe6d2335cd56d5e93b5a3f9484456b961a4f | <ide><path>numpy/__init__.py
<ide> def _sanity_check():
<ide> "by incorrect BLAS library being linked in, or by mixing "
<ide> "package managers (pip, conda, apt, ...). Search closed "
<ide> "numpy issues for similar problems.")
<del> raise RuntimeError(msg.format(__file__))
<add> raise RuntimeError(msg.format(__file__)) from None
<ide>
<ide> _sanity_check()
<ide> del _sanity_check | 1 |
Python | Python | fix broken main | 86d40a95c4b6085ddea7b4d14bb6d91c126138dc | <ide><path>setup.py
<ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version
<ide> 'jira',
<ide> 'jsondiff',
<ide> 'mongomock',
<del> 'moto[glue]>=3.1.6',
<add> # Version 3.1.10 is breaking main bump to 3.1.11 when released.
<add> # Fix already merged but was not released https://github.com/spulec/moto/pull/5165
<add> 'moto[glue]>=3.1.6, <3.1.10',
<ide> 'parameterized',
<ide> 'paramiko',
<ide> 'pipdeptree', | 1 |
Text | Text | add voltrexmaster to collaborators | dd7a92990f0700af2e3f044f2d72f391fd02bde8 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Rich Trott** \<rtrott@gmail.com> (he/him)
<ide> * [vdeturckheim](https://github.com/vdeturckheim) -
<ide> **Vladimir de Turckheim** \<vlad2t@hotmail.com> (he/him)
<add>* [VoltrexMaster](https://github.com/VoltrexMaster) -
<add> **Voltrex** \<mohammadkeyvanzade94@gmail.com> (he/him)
<ide> * [watilde](https://github.com/watilde) -
<ide> **Daijiro Wachi** \<daijiro.wachi@gmail.com> (he/him)
<ide> * [watson](https://github.com/watson) - | 1 |
Ruby | Ruby | fix enum predicate methods on object enum keys | 24416e5df411b841bb49f1469323cdb5061ed73e | <ide><path>activerecord/lib/active_record/enum.rb
<ide> def enum(definitions)
<ide>
<ide> value_method_name = "#{prefix}#{label}#{suffix}"
<ide> value_method_names << value_method_name
<del> define_enum_methods(name, value_method_name, label, enum_scopes)
<add> define_enum_methods(name, value_method_name, value, enum_scopes)
<ide>
<ide> method_friendly_label = label.gsub(/[\W&&[:ascii:]]+/, "_")
<ide> value_method_alias = "#{prefix}#{method_friendly_label}#{suffix}"
<ide>
<ide> if value_method_alias != value_method_name && !value_method_names.include?(value_method_alias)
<ide> value_method_names << value_method_alias
<del> define_enum_methods(name, value_method_alias, label, enum_scopes)
<add> define_enum_methods(name, value_method_alias, value, enum_scopes)
<ide> end
<ide> end
<ide> end
<ide> def initialize(klass)
<ide> private
<ide> attr_reader :klass
<ide>
<del> def define_enum_methods(name, value_method_name, label, enum_scopes)
<del> # def active?() status == "active" end
<add> def define_enum_methods(name, value_method_name, value, enum_scopes)
<add> # def active?() status_for_database == 0 end
<ide> klass.send(:detect_enum_conflict!, name, "#{value_method_name}?")
<del> define_method("#{value_method_name}?") { self[name] == label }
<add> define_method("#{value_method_name}?") { public_send(:"#{name}_for_database") == value }
<ide>
<ide> # def active!() update!(status: 0) end
<ide> klass.send(:detect_enum_conflict!, name, "#{value_method_name}!")
<del> define_method("#{value_method_name}!") { update!(name => label) }
<add> define_method("#{value_method_name}!") { update!(name => value) }
<ide>
<ide> # scope :active, -> { where(status: 0) }
<ide> # scope :not_active, -> { where.not(status: 0) }
<ide> if enum_scopes != false
<ide> klass.send(:detect_enum_conflict!, name, value_method_name, true)
<del> klass.scope value_method_name, -> { where(name => label) }
<add> klass.scope value_method_name, -> { where(name => value) }
<ide>
<ide> klass.send(:detect_enum_conflict!, name, "not_#{value_method_name}", true)
<del> klass.scope "not_#{value_method_name}", -> { where.not(name => label) }
<add> klass.scope "not_#{value_method_name}", -> { where.not(name => value) }
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/enum_test.rb
<ide> def self.name; "Book"; end
<ide> end
<ide>
<ide> test "deserialize enum value to original hash key" do
<del> proposed = Class.new
<del> written = Class.new
<add> proposed = Struct.new(:to_s).new("proposed")
<add> written = Struct.new(:to_s).new("written")
<ide> klass = Class.new(ActiveRecord::Base) do
<ide> self.table_name = "books"
<ide> enum status: { proposed => 0, written => 1 }
<ide> end
<ide>
<ide> book = klass.create!(status: 0)
<ide> assert_equal proposed, book.status
<add> assert_predicate book, :proposed?
<add> assert_not_predicate book, :written?
<ide> end
<ide>
<ide> test "enum logs a warning if auto-generated negative scopes would clash with other enum names" do | 2 |
Ruby | Ruby | use _read_attribute(primary_key) instead of id | b584cc68fc28492147ed3ed127ad8a7441ca8161 | <ide><path>activerecord/lib/active_record/persistence.rb
<ide> def touch(*names, time: nil)
<ide>
<ide> clear_attribute_changes(changes.keys)
<ide> primary_key = self.class.primary_key
<del> scope = self.class.unscoped.where(primary_key => id)
<add> scope = self.class.unscoped.where(primary_key => _read_attribute(primary_key))
<ide>
<ide> if locking_enabled?
<ide> locking_column = self.class.locking_column | 1 |
Java | Java | fix the typos | 0cb8978c1d21363eac53299272295567efb13a55 | <ide><path>src/main/java/io/reactivex/rxjava3/schedulers/Schedulers.java
<ide> public static Scheduler single() {
<ide> * because such circumstances prevent RxJava from progressing flow-related activities correctly.
<ide> * If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws,
<ide> * the {@code RejectedExecutionException} is routed to the global error handler via
<del> * {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-reladed problems, it is recommended
<add> * {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended
<ide> * all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying
<ide> * {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue,
<ide> * it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work.
<ide> public static Scheduler from(@NonNull Executor executor) {
<ide> * because such circumstances prevent RxJava from progressing flow-related activities correctly.
<ide> * If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws,
<ide> * the {@code RejectedExecutionException} is routed to the global error handler via
<del> * {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-reladed problems, it is recommended
<add> * {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended
<ide> * all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying
<ide> * {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue,
<ide> * it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work.
<ide> public static Scheduler from(@NonNull Executor executor, boolean interruptibleWo
<ide> * because such circumstances prevent RxJava from progressing flow-related activities correctly.
<ide> * If the {@link Executor#execute(Runnable)} or {@link ExecutorService#submit(Callable)} throws,
<ide> * the {@code RejectedExecutionException} is routed to the global error handler via
<del> * {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-reladed problems, it is recommended
<add> * {@link RxJavaPlugins#onError(Throwable)}. To avoid shutdown-related problems, it is recommended
<ide> * all flows using the returned {@code Scheduler} to be canceled/disposed before the underlying
<ide> * {@code Executor} is shut down. To avoid problems due to the {@code Executor} having a bounded-queue,
<ide> * it is recommended to rephrase the flow to utilize backpressure as the means to limit outstanding work. | 1 |
Javascript | Javascript | fix a spacing issue | b8a5b76db5cd20dfba5891e9f70de27fe46aa46f | <ide><path>fonts.js
<ide> var Font = (function Font() {
<ide>
<ide> // Character to glyphs mapping
<ide> 'cmap': createCMapTable(charstrings.slice(),
<del> ('glyphIds' in font) ? font.glyphIds: null),
<add> ('glyphIds' in font) ? font.glyphIds : null),
<ide>
<ide> // Font header
<ide> 'head': (function fontFieldsHead() { | 1 |
Python | Python | honor existing attention mask in tokenzier.pad | 4a18337baed89e8cfd524c4b307a93b451ea1ef6 | <ide><path>src/transformers/feature_extraction_sequence_utils.py
<ide> def _pad(
<ide>
<ide> needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) < max_length
<ide>
<add> if return_attention_mask and "attention_mask" not in processed_features:
<add> processed_features["attention_mask"] = np.ones(len(required_input), dtype=np.int32)
<add>
<ide> if needs_to_be_padded:
<ide> difference = max_length - len(required_input)
<ide> if self.padding_side == "right":
<ide> if return_attention_mask:
<del> attention_mask = np.zeros(max_length, dtype=np.int32)
<del> attention_mask[: len(required_input)] = 1
<del> processed_features["attention_mask"] = attention_mask
<add> processed_features["attention_mask"] = np.pad(
<add> processed_features["attention_mask"], (0, difference)
<add> )
<ide> padding_shape = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
<ide> processed_features[self.model_input_names[0]] = np.pad(
<ide> required_input, padding_shape, "constant", constant_values=self.padding_value
<ide> )
<ide> elif self.padding_side == "left":
<ide> if return_attention_mask:
<del> attention_mask = np.zeros(max_length, dtype=np.int32)
<del> attention_mask[-len(required_input) :] = 1
<del> processed_features["attention_mask"] = attention_mask
<add> processed_features["attention_mask"] = np.pad(
<add> processed_features["attention_mask"], (difference, 0)
<add> )
<ide> padding_shape = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
<ide> processed_features[self.model_input_names[0]] = np.pad(
<ide> required_input, padding_shape, "constant", constant_values=self.padding_value
<ide> )
<ide> else:
<ide> raise ValueError("Invalid padding strategy:" + str(self.padding_side))
<del> elif return_attention_mask and "attention_mask" not in processed_features:
<del> processed_features["attention_mask"] = np.ones(len(required_input), dtype=np.int32)
<ide>
<ide> return processed_features
<ide>
<ide><path>src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
<ide> def _pad(
<ide>
<ide> needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
<ide>
<add> # Initialize attention mask if not present.
<add> if return_attention_mask and "attention_mask" not in encoded_inputs:
<add> encoded_inputs["attention_mask"] = [1] * len(required_input)
<add>
<ide> if needs_to_be_padded:
<ide> difference = max_length - len(required_input)
<ide> if self.padding_side == "right":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [1] * len(required_input) + [0] * difference
<add> encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = (
<ide> encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
<ide> def _pad(
<ide> encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
<ide> elif self.padding_side == "left":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [0] * difference + [1] * len(required_input)
<add> encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
<ide> "token_type_ids"
<ide> def _pad(
<ide> encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
<ide> else:
<ide> raise ValueError("Invalid padding strategy:" + str(self.padding_side))
<del> elif return_attention_mask and "attention_mask" not in encoded_inputs:
<del> encoded_inputs["attention_mask"] = [1] * len(required_input)
<ide>
<ide> return encoded_inputs
<ide>
<ide><path>src/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
<ide> def _pad(
<ide>
<ide> needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
<ide>
<add> # Initialize attention mask if not present.
<add> if return_attention_mask and "attention_mask" not in encoded_inputs:
<add> encoded_inputs["attention_mask"] = [1] * len(required_input)
<add>
<ide> if needs_to_be_padded:
<ide> difference = max_length - len(required_input)
<ide> if self.padding_side == "right":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [1] * len(required_input) + [0] * difference
<add> encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = (
<ide> encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
<ide> def _pad(
<ide> encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
<ide> elif self.padding_side == "left":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [0] * difference + [1] * len(required_input)
<add> encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
<ide> "token_type_ids"
<ide> def _pad(
<ide> encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
<ide> else:
<ide> raise ValueError("Invalid padding strategy:" + str(self.padding_side))
<del> elif return_attention_mask and "attention_mask" not in encoded_inputs:
<del> encoded_inputs["attention_mask"] = [1] * len(required_input)
<ide>
<ide> return encoded_inputs
<ide>
<ide><path>src/transformers/models/luke/tokenization_luke.py
<ide> def _pad(
<ide> or (entities_provided and len(encoded_inputs["entity_ids"]) != max_entity_length)
<ide> )
<ide>
<add> # Initialize attention mask if not present.
<add> if return_attention_mask and "attention_mask" not in encoded_inputs:
<add> encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
<add> if entities_provided and return_attention_mask and "entity_attention_mask" not in encoded_inputs:
<add> encoded_inputs["entity_attention_mask"] = [1] * len(encoded_inputs["entity_ids"])
<add>
<ide> if needs_to_be_padded:
<ide> difference = max_length - len(encoded_inputs["input_ids"])
<ide> if entities_provided:
<ide> entity_difference = max_entity_length - len(encoded_inputs["entity_ids"])
<ide> if self.padding_side == "right":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"]) + [0] * difference
<add> encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
<ide> if entities_provided:
<del> encoded_inputs["entity_attention_mask"] = [1] * len(encoded_inputs["entity_ids"]) + [
<del> 0
<del> ] * entity_difference
<add> encoded_inputs["entity_attention_mask"] = (
<add> encoded_inputs["entity_attention_mask"] + [0] * entity_difference
<add> )
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = encoded_inputs["token_type_ids"] + [0] * difference
<ide> if entities_provided:
<ide> def _pad(
<ide>
<ide> elif self.padding_side == "left":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [0] * difference + [1] * len(encoded_inputs["input_ids"])
<add> encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
<ide> if entities_provided:
<del> encoded_inputs["entity_attention_mask"] = [0] * entity_difference + [1] * len(
<del> encoded_inputs["entity_ids"]
<del> )
<add> encoded_inputs["entity_attention_mask"] = [0] * entity_difference + encoded_inputs[
<add> "entity_attention_mask"
<add> ]
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = [0] * difference + encoded_inputs["token_type_ids"]
<ide> if entities_provided:
<ide> def _pad(
<ide> ]
<ide> else:
<ide> raise ValueError("Invalid padding strategy:" + str(self.padding_side))
<del> else:
<del> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
<del> if entities_provided:
<del> encoded_inputs["entity_attention_mask"] = [1] * len(encoded_inputs["entity_ids"])
<ide>
<ide> return encoded_inputs
<ide>
<ide><path>src/transformers/models/tapas/tokenization_tapas.py
<ide> def _pad(
<ide> padding_strategy != PaddingStrategy.DO_NOT_PAD and len(encoded_inputs["input_ids"]) != max_length
<ide> )
<ide>
<add> # Initialize attention mask if not present.
<add> if return_attention_mask and "attention_mask" not in encoded_inputs:
<add> encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
<add>
<ide> if needs_to_be_padded:
<ide> difference = max_length - len(encoded_inputs["input_ids"])
<ide> if self.padding_side == "right":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"]) + [0] * difference
<add> encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = (
<ide> encoded_inputs["token_type_ids"] + [[self.pad_token_type_id] * 7] * difference
<ide> def _pad(
<ide> encoded_inputs["input_ids"] = encoded_inputs["input_ids"] + [self.pad_token_id] * difference
<ide> elif self.padding_side == "left":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [0] * difference + [1] * len(encoded_inputs["input_ids"])
<add> encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = [[self.pad_token_type_id] * 7] * difference + encoded_inputs[
<ide> "token_type_ids"
<ide> def _pad(
<ide> encoded_inputs["input_ids"] = [self.pad_token_id] * difference + encoded_inputs["input_ids"]
<ide> else:
<ide> raise ValueError("Invalid padding strategy:" + str(self.padding_side))
<del> else:
<del> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [1] * len(encoded_inputs["input_ids"])
<ide>
<ide> return encoded_inputs
<ide>
<ide><path>src/transformers/tokenization_utils_base.py
<ide> def _pad(
<ide>
<ide> needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
<ide>
<add> # Initialize attention mask if not present.
<add> if return_attention_mask and "attention_mask" not in encoded_inputs:
<add> encoded_inputs["attention_mask"] = [1] * len(required_input)
<add>
<ide> if needs_to_be_padded:
<ide> difference = max_length - len(required_input)
<add>
<ide> if self.padding_side == "right":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [1] * len(required_input) + [0] * difference
<add>
<add> encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = (
<ide> encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
<ide> def _pad(
<ide> encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
<ide> elif self.padding_side == "left":
<ide> if return_attention_mask:
<del> encoded_inputs["attention_mask"] = [0] * difference + [1] * len(required_input)
<add> encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
<ide> if "token_type_ids" in encoded_inputs:
<ide> encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
<ide> "token_type_ids"
<ide> def _pad(
<ide> encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
<ide> else:
<ide> raise ValueError("Invalid padding strategy:" + str(self.padding_side))
<del> elif return_attention_mask and "attention_mask" not in encoded_inputs:
<del> encoded_inputs["attention_mask"] = [1] * len(required_input)
<ide>
<ide> return encoded_inputs
<ide>
<ide><path>tests/test_tokenization_common.py
<ide> def test_padding_to_multiple_of(self):
<ide> pad_to_multiple_of=8,
<ide> )
<ide>
<add> def test_padding_with_attention_mask(self):
<add> tokenizers = self.get_tokenizers()
<add> for tokenizer in tokenizers:
<add> with self.subTest(f"{tokenizer.__class__.__name__}"):
<add> if tokenizer.pad_token is None:
<add> self.skipTest("No padding token.")
<add> if "attention_mask" not in tokenizer.model_input_names:
<add> self.skipTest("This model does not use attention mask.")
<add>
<add> features = [
<add> {"input_ids": [1, 2, 3, 4, 5, 6], "attention_mask": [1, 1, 1, 1, 1, 0]},
<add> {"input_ids": [1, 2, 3], "attention_mask": [1, 1, 0]},
<add> ]
<add> padded_features = tokenizer.pad(features)
<add> if tokenizer.padding_side == "right":
<add> self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0]])
<add> else:
<add> self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0]])
<add>
<ide> def test_encode_plus_with_padding(self):
<ide> tokenizers = self.get_tokenizers(do_lower_case=False)
<ide> for tokenizer in tokenizers: | 7 |
Go | Go | normalize comment formatting | cbc9de0abe6cf0183e83490866dccb816252c9a1 | <ide><path>image/tarexport/tarexport.go
<ide> type tarexporter struct {
<ide>
<ide> // LogImageEvent defines interface for event generation related to image tar(load and save) operations
<ide> type LogImageEvent interface {
<del> //LogImageEvent generates an event related to an image operation
<add> // LogImageEvent generates an event related to an image operation
<ide> LogImageEvent(imageID, refName, action string)
<ide> }
<ide> | 1 |
PHP | PHP | fix scopes on builder helpers | 5d4a492e5816227389de4e42fbe8e12e89ce2c7d | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function chunk($count, callable $callback)
<ide> */
<ide> public function pluck($column, $key = null)
<ide> {
<del> $results = $this->query->pluck($column, $key);
<add> $results = $this->toBase()->pluck($column, $key);
<ide>
<ide> // If the model has a mutator for the requested column, we will spin through
<ide> // the results and mutate the values so that the mutated version of these
<ide> public function lists($column, $key = null)
<ide> */
<ide> public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
<ide> {
<del> $total = $this->query->getCountForPagination();
<add> $query = $this->toBase();
<ide>
<del> $this->query->forPage(
<add> $total = $query->getCountForPagination();
<add>
<add> $query->forPage(
<ide> $page = $page ?: Paginator::resolveCurrentPage($pageName),
<ide> $perPage = $perPage ?: $this->model->getPerPage()
<ide> );
<ide><path>tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
<ide>
<ide> use Carbon\Carbon;
<ide> use Illuminate\Database\Connection;
<add>use Illuminate\Pagination\Paginator;
<ide> use Illuminate\Database\Query\Builder;
<ide> use Illuminate\Database\Eloquent\SoftDeletes;
<ide> use Illuminate\Database\Capsule\Manager as DB;
<ide> public function testSoftDeletesAreNotRetrievedFromBaseQuery()
<ide> $this->assertCount(1, $query->get());
<ide> }
<ide>
<add> public function testSoftDeletesAreNotRetrievedFromBuilderHelpers()
<add> {
<add> $this->createUsers();
<add>
<add> $count = 0;
<add> $query = SoftDeletesTestUser::query();
<add> $query->chunk(2, function ($user) use (&$count) {
<add> $count += count($user);
<add> });
<add> $this->assertEquals(1, $count);
<add>
<add> $query = SoftDeletesTestUser::query();
<add> $this->assertCount(1, $query->pluck('email')->all());
<add>
<add> Paginator::currentPageResolver(function () { return 1; });
<add>
<add> $query = SoftDeletesTestUser::query();
<add> $this->assertCount(1, $query->paginate(2)->all());
<add>
<add> $query = SoftDeletesTestUser::query();
<add> $this->assertCount(1, $query->simplePaginate(2)->all());
<add> }
<add>
<ide> public function testWithTrashedReturnsAllRecords()
<ide> {
<ide> $this->createUsers();
<ide> public function testWhereHasWithNestedDeletedRelationship()
<ide> public function testOrWhereWithSoftDeleteConstraint()
<ide> {
<ide> $this->createUsers();
<del> SoftDeletesTestUser::create(['id' => 3, 'email' => 'something@else.com']);
<ide>
<del> $users = SoftDeletesTestUser::where('email', 'something@else.com')->orWhere('email', 'abigailotwell@gmail.com');
<del> $this->assertEquals(2, count($users->get()));
<del> $this->assertEquals(['abigailotwell@gmail.com', 'something@else.com'], $users->orderBy('id')->pluck('email')->all());
<add> $users = SoftDeletesTestUser::where('email', 'taylorotwell@gmail.com')->orWhere('email', 'abigailotwell@gmail.com');
<add> $this->assertEquals(['abigailotwell@gmail.com'], $users->pluck('email')->all());
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | improve error for style mutation | 9faf1f39698463cd5220e58a5d325c8e2c006997 | <ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> function legacyReplaceProps(partialProps, callback) {
<ide> }
<ide> }
<ide>
<add>function friendlyStringify(obj) {
<add> if (typeof obj === 'object') {
<add> if (Array.isArray(obj)) {
<add> return '[' + obj.map(friendlyStringify).join(', ') + ']';
<add> } else {
<add> var pairs = [];
<add> for (var key in obj) {
<add> if (Object.prototype.hasOwnProperty.call(obj, key)) {
<add> var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ?
<add> key :
<add> JSON.stringify(key);
<add> pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key]));
<add> }
<add> }
<add> return '{' + pairs.join(', ') + '}';
<add> }
<add> } else if (typeof obj === 'string') {
<add> return JSON.stringify(obj);
<add> } else if (typeof obj === 'function') {
<add> return '[function object]';
<add> }
<add> // Differs from JSON.stringify in that undefined becauses undefined and that
<add> // inf and nan don't become null
<add> return String(obj);
<add>}
<add>
<ide> var styleMutationWarning = {};
<ide>
<ide> function checkAndWarnForMutatedStyle(style1, style2, component) {
<ide> function checkAndWarnForMutatedStyle(style1, style2, component) {
<ide> 'the `render` %s. Previous style: %s. Mutated style: %s.',
<ide> componentName,
<ide> owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>',
<del> JSON.stringify(style1),
<del> JSON.stringify(style2)
<add> friendlyStringify(style1),
<add> friendlyStringify(style2)
<ide> );
<ide> }
<ide>
<ide><path>src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', function() {
<ide> 'Warning: `div` was passed a style object that has previously been ' +
<ide> 'mutated. Mutating `style` is deprecated. Consider cloning it ' +
<ide> 'beforehand. Check the `render` of `App`. Previous style: ' +
<del> '{"border":"1px solid black"}. Mutated style: ' +
<del> '{"border":"1px solid black","position":"absolute"}.'
<add> '{border: "1px solid black"}. Mutated style: ' +
<add> '{border: "1px solid black", position: "absolute"}.'
<ide> );
<ide>
<ide> style = {background: 'red'};
<ide> describe('ReactDOMComponent', function() {
<ide> expect(console.error.argsForCall.length).toBe(2);
<ide> });
<ide>
<add> it('should warn semi-nicely about NaN in style', function() {
<add> spyOn(console, 'error');
<add>
<add> var style = {fontSize: NaN};
<add> var div = document.createElement('div');
<add> ReactDOM.render(<span style={style}></span>, div);
<add> ReactDOM.render(<span style={style}></span>, div);
<add>
<add> expect(console.error.argsForCall.length).toBe(1);
<add> expect(console.error.argsForCall[0][0]).toEqual(
<add> 'Warning: `span` was passed a style object that has previously been ' +
<add> 'mutated. Mutating `style` is deprecated. Consider cloning it ' +
<add> 'beforehand. Check the `render` using <span>. Previous style: ' +
<add> '{fontSize: NaN}. Mutated style: {fontSize: NaN}.'
<add> );
<add> });
<add>
<ide> it('should update styles if initially null', function() {
<ide> var styles = null;
<ide> var container = document.createElement('div'); | 2 |
Ruby | Ruby | add superenv for linux | 76bfd0cecbe8ca74af5b8ea35a4a7251dd1fc729 | <ide><path>Library/Homebrew/build.rb
<ide> def expand_deps
<ide> def install
<ide> formula_deps = deps.map(&:to_formula)
<ide> keg_only_deps = formula_deps.select(&:keg_only?)
<add> run_time_deps = deps.reject(&:build?).map(&:to_formula)
<ide>
<ide> formula_deps.each do |dep|
<ide> fixopt(dep) unless dep.opt_prefix.directory?
<ide> def install
<ide> if superenv?
<ide> ENV.keg_only_deps = keg_only_deps
<ide> ENV.deps = formula_deps
<add> ENV.run_time_deps = run_time_deps
<ide> ENV.x11 = reqs.any? { |rq| rq.is_a?(X11Requirement) }
<ide> ENV.setup_build_environment(formula)
<ide> post_superenv_hacks
<ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> module Superenv
<ide> include SharedEnvExtension
<ide>
<ide> # @private
<del> attr_accessor :keg_only_deps, :deps
<add> attr_accessor :keg_only_deps, :deps, :run_time_deps
<ide> attr_accessor :x11
<ide>
<ide> def self.extended(base)
<ide> base.keg_only_deps = []
<ide> base.deps = []
<add> base.run_time_deps = []
<ide> end
<ide>
<ide> # @private
<ide> def setup_build_environment(formula = nil)
<ide> self["HOMEBREW_ISYSTEM_PATHS"] = determine_isystem_paths
<ide> self["HOMEBREW_INCLUDE_PATHS"] = determine_include_paths
<ide> self["HOMEBREW_LIBRARY_PATHS"] = determine_library_paths
<add> self["HOMEBREW_RPATH_PATHS"] = determine_rpath_paths(formula)
<add> self["HOMEBREW_DYNAMIC_LINKER"] = determine_dynamic_linker_path
<ide> self["HOMEBREW_DEPENDENCIES"] = determine_dependencies
<ide> self["HOMEBREW_FORMULA_PREFIX"] = formula.prefix unless formula.nil?
<ide>
<ide> def determine_library_paths
<ide> keg_only_deps.map(&:opt_lib),
<ide> HOMEBREW_PREFIX/"lib",
<ide> ]
<del>
<del> if compiler == :llvm_clang
<del> if MacOS::CLT.installed?
<del> paths << "/usr/lib"
<del> else
<del> paths << "#{MacOS.sdk_path}/usr/lib"
<del> end
<del> paths << Formula["llvm"].opt_lib.to_s
<del> end
<del>
<ide> paths += homebrew_extra_library_paths
<ide> PATH.new(paths).existing
<ide> end
<ide>
<add> def determine_extra_rpath_paths(_formula)
<add> []
<add> end
<add>
<add> def determine_rpath_paths(formula)
<add> PATH.new(determine_extra_rpath_paths(formula))
<add> end
<add>
<add> def determine_dynamic_linker_path
<add> nil
<add> end
<add>
<ide> def determine_dependencies
<ide> deps.map(&:name).join(",")
<ide> end
<ide><path>Library/Homebrew/extend/os/extend/ENV/super.rb
<del>require "extend/os/mac/extend/ENV/super" if OS.mac?
<add>if OS.mac?
<add> require "extend/os/mac/extend/ENV/super"
<add>elsif OS.linux?
<add> require "extend/os/linux/extend/ENV/super"
<add>end
<ide><path>Library/Homebrew/extend/os/linux/extend/ENV/super.rb
<add>module Superenv
<add> # @private
<add> def self.bin
<add> (HOMEBREW_SHIMS_PATH/"linux/super").realpath
<add> end
<add>
<add> def homebrew_extra_paths
<add> paths = []
<add> paths += %w[binutils make].map do |f|
<add> begin
<add> bin = Formula[f].opt_bin
<add> bin if bin.directory?
<add> rescue FormulaUnavailableError
<add> nil
<add> end
<add> end.compact
<add> paths
<add> end
<add>
<add> def determine_extra_rpath_paths(formula)
<add> PATH.new(
<add> formula&.lib,
<add> "#{HOMEBREW_PREFIX}/lib",
<add> PATH.new(run_time_deps.map { |dep| dep.opt_lib.to_s }).existing,
<add> )
<add> end
<add>
<add> def determine_dynamic_linker_path
<add> path = "#{HOMEBREW_PREFIX}/lib/ld.so"
<add> return unless File.readable? path
<add> path
<add> end
<add>end
<ide><path>Library/Homebrew/extend/os/mac/extend/ENV/super.rb
<ide> def homebrew_extra_isystem_paths
<ide>
<ide> def homebrew_extra_library_paths
<ide> paths = []
<add> if compiler == :llvm_clang
<add> if MacOS::CLT.installed?
<add> paths << "/usr/lib"
<add> else
<add> paths << "#{MacOS.sdk_path}/usr/lib"
<add> end
<add> paths << Formula["llvm"].opt_lib.to_s
<add> end
<ide> paths << MacOS::X11.lib.to_s if x11?
<ide> paths << "#{effective_sysroot}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries"
<ide> paths | 5 |
Python | Python | fix another signature formatting issue | ad9cd295863cdc7a96f219574b15cd2f03189693 | <ide><path>doc/sphinxext/autosummary.py
<ide> def append_row(*column_texts):
<ide> sig = re.sub(r'=[^,)]+,', ',', sig)
<ide> sig = re.sub(r'=[^,)]+\)$', '])', sig)
<ide> # shorten long strings
<del> sig = re.sub(r'(\[.{16,16}[^,)]*?),.*?\]\)', r'\1, ...])', sig)
<add> sig = re.sub(r'(\[.{16,16}[^,]*?),.*?\]\)', r'\1, ...])', sig)
<ide> else:
<del> sig = re.sub(r'(\(.{16,16}[^,)]*?),.*?\)', r'\1, ...)', sig)
<add> sig = re.sub(r'(\(.{16,16}[^,]*?),.*?\)', r'\1, ...)', sig)
<ide> # make signature contain non-breaking spaces
<ide> col1 += u"\\ \u00a0" + unicode(sig).replace(u" ", u"\u00a0")
<ide> col2 = title | 1 |
Text | Text | add example for model2model in quickstart | 4e3f745ba4e754e415c184d53c874031101d263b | <ide><path>docs/source/quickstart.md
<ide> sequence = tokenizer.decode(generated)
<ide> print(sequence)
<ide> ```
<ide>
<del>The model only requires a single token as input as all the previous tokens' key/value pairs are contained in the `past`.
<ide>\ No newline at end of file
<add>The model only requires a single token as input as all the previous tokens' key/value pairs are contained in the `past`.
<add>
<add>### Model2Model example
<add>
<add>Encoder-decoder architectures require two tokenized inputs: one for the encoder and the other one for the decoder. Let's assume that we want to use `Model2Model` for generative question answering, and start by tokenizing the question and answer that will be fed to the model.
<add>
<add>```python
<add>import torch
<add>from transformers import BertTokenizer, Model2Model
<add>
<add># OPTIONAL: if you want to have more information on what's happening under the hood, activate the logger as follows
<add>import logging
<add>logging.basicConfig(level=logging.INFO)
<add>
<add># Load pre-trained model tokenizer (vocabulary)
<add>tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
<add>
<add># Encode the input to the encoder (the question)
<add>question = "Who was Jim Henson?"
<add>encoded_question = tokenizer.encode(question)
<add>
<add># Encode the input to the decoder (the answer)
<add>answer = "Jim Henson was a puppeteer"
<add>encoded_answer = tokenizer.encode(answer)
<add>
<add># Convert inputs to PyTorch tensors
<add>question_tensor = torch.tensor([encoded_question])
<add>answer_tensor = torch.tensor([encoded_answer])
<add>```
<add>
<add>Let's see how we can use `Model2Model` to get the value of the loss associated with this (question, answer) pair:
<add>
<add>```python
<add># In order to compute the loss we need to provide language model
<add># labels (the token ids that the model should have produced) to
<add># the decoder.
<add>lm_labels = encoded_answer
<add>labels_tensor = torch.tensor([lm_labels])
<add>
<add># Load pre-trained model (weights)
<add>model = Model2Model.from_pretrained('bert-base-uncased')
<add>
<add># Set the model in evaluation mode to deactivate the DropOut modules
<add># This is IMPORTANT to have reproducible results during evaluation!
<add>model.eval()
<add>
<add># If you have a GPU, put everything on cuda
<add>question_tensor = question_tensor.to('cuda')
<add>answer_tensor = answer_tensor.to('cuda')
<add>labels_tensor = labels_tensor.to('cuda')
<add>model.to('cuda')
<add>
<add># Predict hidden states features for each layer
<add>with torch.no_grad():
<add> # See the models docstrings for the detail of the inputs
<add> outputs = model(question_tensor, answer_tensor, decoder_lm_labels=labels_tensor)
<add> # Transformers models always output tuples.
<add> # See the models docstrings for the detail of all the outputs
<add> # In our case, the first element is the value of the LM loss
<add> lm_loss = outputs[0]
<add>```
<add>
<add>This loss can be used to fine-tune `Model2Model` on the question answering task. Assuming that we fine-tuned the model, let us now see how to generate an answer:
<add>
<add>```python
<add># Let's re-use the previous question
<add>question = "Who was Jim Henson?"
<add>encoded_question = tokenizer.encode(question)
<add>question_tensor = torch.tensor([encoded_question])
<add>
<add># This time we try to generate the answer, so we start with an empty sequence
<add>answer = "[CLS]"
<add>encoded_answer = tokenizer.encode(answer, add_special_tokens=False)
<add>answer_tensor = torch.tensor([encoded_answer])
<add>
<add># Load pre-trained model (weights)
<add>model = Model2Model.from_pretrained('fine-tuned-weights')
<add>model.eval()
<add>
<add># If you have a GPU, put everything on cuda
<add>question_tensor = encoded_question.to('cuda')
<add>answer_tensor = encoded_answer.to('cuda')
<add>model.to('cuda')
<add>
<add># Predict all tokens
<add>with torch.no_grad():
<add> outputs = model(question_tensor, answer_tensor)
<add> predictions = outputs[0]
<add>
<add># confirm we were able to predict 'jim'
<add>predicted_index = torch.argmax(predictions[0, -1]).item()
<add>predicted_token = tokenizer.convert_ids_to_tokens([predicted_index])[0]
<add>assert predicted_token == 'jim'
<add>``` | 1 |
Text | Text | fix minor typo in `update` `$push` directive | 5fc2ecbe92c936128db32dc868467121045fb2c6 | <ide><path>docs/docs/09.6-update.md
<ide> While this is fairly performant (since it only shallow copies `log n` objects an
<ide> ```javascript
<ide> var newData = React.addons.update(myData, {
<ide> x: {y: {z: {$set: 7}}},
<del> a: {b: {$push: [7]}}
<add> a: {b: {$push: [9]}}
<ide> });
<ide> ```
<ide> | 1 |
Python | Python | fix invalid vdot documentation | eca8f94e294003336d901b7e718375fad0c2619c | <ide><path>numpy/add_newdocs.py
<ide> dot(`a`, `b`). If the first argument is complex the complex conjugate
<ide> of the first argument is used for the calculation of the dot product.
<ide>
<del> For 2-D arrays it is equivalent to matrix multiplication, and for 1-D
<del> arrays to inner product of vectors (with complex conjugation of `a`).
<del> For N dimensions it is a sum product over the last axis of `a` and
<del> the second-to-last of `b`::
<del>
<del> dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
<add> Note that `vdot` handles multidimensional arrays differently than `dot`:
<add> it does *not* perform a matrix product, but flattens input arguments
<add> to 1-D vectors first. Consequently, it should only be used for vectors.
<ide>
<ide> Parameters
<ide> ----------
<ide> Returns
<ide> -------
<ide> output : ndarray
<del> Returns dot product of `a` and `b`. Can be an int, float, or
<add> Dot product of `a` and `b`. Can be an int, float, or
<ide> complex depending on the types of `a` and `b`.
<ide>
<ide> See Also
<ide> --------
<ide> dot : Return the dot product without using the complex conjugate of the
<ide> first argument.
<ide>
<del> Notes
<del> -----
<del> The dot product is the summation of element wise multiplication.
<del>
<del> .. math::
<del> a \\cdot b = \\sum_{i=1}^n a_i^*b_i = a_1^*b_1+a_2^*b_2+\\cdots+a_n^*b_n
<del>
<ide> Examples
<ide> --------
<ide> >>> a = np.array([1+2j,3+4j])
<ide> (70-8j)
<ide> >>> np.vdot(b, a)
<ide> (70+8j)
<add>
<add> Note that higher-dimensional arrays are flattened!
<add>
<ide> >>> a = np.array([[1, 4], [5, 6]])
<ide> >>> b = np.array([[4, 1], [2, 2]])
<ide> >>> np.vdot(a, b)
<ide> 30
<ide> >>> np.vdot(b, a)
<ide> 30
<add> >>> 1*4 + 4*1 + 5*2 + 6*2
<add> 30
<ide>
<ide> """)
<ide> | 1 |
Javascript | Javascript | pass app bundle identifiers to electron-packager | dc7973f1e7e81240abdd9a2e8aa89ffac9fd7019 | <ide><path>script/lib/package-application.js
<ide> module.exports = function () {
<ide> console.log(`Running electron-packager on ${CONFIG.intermediateAppPath} with app name "${appName}"`)
<ide> return runPackager({
<ide> 'app-version': CONFIG.appMetadata.version,
<add> 'app-bundle-id': 'com.github.atom',
<ide> 'arch': process.arch,
<ide> 'asar': {unpack: buildAsarUnpackGlobExpression()},
<ide> 'build-version': CONFIG.appMetadata.version,
<ide> 'download': {cache: CONFIG.cachePath},
<ide> 'dir': CONFIG.intermediateAppPath,
<add> 'helper-bundle-id': 'com.github.atom.helper',
<ide> 'icon': getIcon(),
<ide> 'name': appName,
<ide> 'out': CONFIG.buildOutputPath, | 1 |
Javascript | Javascript | add code example for emberarray.addarrayobserver | f4ba42ab54ef660e62565b05b3556b560b79d72b | <ide><path>packages/@ember/-internals/runtime/lib/mixins/array.js
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> `willChange` and `didChange` option.
<ide> @return {EmberArray} receiver
<ide> @public
<add> @example
<add> import Service from '@ember/service';
<add>
<add> export default Service.extend({
<add> data: Ember.A(),
<add>
<add> init() {
<add> this._super(...arguments);
<add>
<add> this.data.addArrayObserver(this, {
<add> willChange: 'dataWillChange',
<add> didChange: 'dataDidChange'
<add> });
<add> },
<add>
<add> dataWillChange(array, start, removeCount, addCount) {
<add> console.log('array will change', array, start, removeCount, addCount);
<add> },
<add>
<add> dataDidChange(array, start, removeCount, addCount) {
<add> console.log('array did change', array, start, removeCount, addCount);
<add> }
<add> });
<ide> */
<ide>
<ide> addArrayObserver(target, opts) { | 1 |
Javascript | Javascript | remove duplicate code | bad65ea69dc4032384bfdd08390a566f4666f457 | <ide><path>lib/_http_server.js
<ide> function onParserExecuteCommon(server, socket, parser, state, ret, d) {
<ide>
<ide> if (ret instanceof Error) {
<ide> prepareError(ret, parser, d);
<del> ret.rawPacket = d || parser.getCurrentBuffer();
<ide> debug('parse error', ret);
<ide> socketOnError.call(socket, ret);
<ide> } else if (parser.incoming && parser.incoming.upgrade) { | 1 |
Javascript | Javascript | use custom element on workspace-element | e362a8f0f722d9be9fb8e944c573797b658482f3 | <ide><path>src/workspace-element.js
<ide> const scrollbarStyle = require('scrollbar-style');
<ide> const _ = require('underscore-plus');
<ide>
<ide> class WorkspaceElement extends HTMLElement {
<del> attachedCallback() {
<add> connectedCallback() {
<ide> this.focus();
<ide> this.htmlElement = document.querySelector('html');
<ide> this.htmlElement.addEventListener('mouseleave', this.handleCenterLeave);
<ide> }
<ide>
<del> detachedCallback() {
<add> disconnectedCallback() {
<ide> this.subscriptions.dispose();
<ide> this.htmlElement.removeEventListener('mouseleave', this.handleCenterLeave);
<ide> }
<ide> class WorkspaceElement extends HTMLElement {
<ide> }
<ide> }
<ide>
<del>module.exports = document.registerElement('atom-workspace', {
<del> prototype: WorkspaceElement.prototype
<del>});
<del>
<ide> function isTab(element) {
<ide> let el = element;
<ide> while (el != null) {
<ide> function isTab(element) {
<ide> }
<ide> return false;
<ide> }
<add>
<add>window.customElements.define('atom-workspace', WorkspaceElement);
<add>
<add>function createWorkspaceElement() {
<add> return document.createElement('atom-workspace');
<add>}
<add>
<add>module.exports = {
<add> createWorkspaceElement
<add>};
<ide><path>src/workspace.js
<ide> const Panel = require('./panel');
<ide> const PanelContainer = require('./panel-container');
<ide> const Task = require('./task');
<ide> const WorkspaceCenter = require('./workspace-center');
<del>const WorkspaceElement = require('./workspace-element');
<add>const { createWorkspaceElement } = require('./workspace-element');
<ide>
<ide> const STOPPED_CHANGING_ACTIVE_PANE_ITEM_DELAY = 100;
<ide> const ALL_LOCATIONS = ['center', 'left', 'right', 'bottom'];
<ide> module.exports = class Workspace extends Model {
<ide>
<ide> getElement() {
<ide> if (!this.element) {
<del> this.element = new WorkspaceElement().initialize(this, {
<add> this.element = createWorkspaceElement().initialize(this, {
<ide> config: this.config,
<ide> project: this.project,
<ide> viewRegistry: this.viewRegistry, | 2 |
Javascript | Javascript | add titleplaceholder in template.config.js | 8ffa180d80b9c9acb76a0631b5a709d2c0adcd86 | <ide><path>template.config.js
<ide>
<ide> module.exports = {
<ide> placeholderName: 'HelloWorld',
<add> titlePlaceholder: 'Hello App Display Name',
<ide> templateDir: './template',
<ide> }; | 1 |
Javascript | Javascript | increase test coverage for fs/promises.js | fcc46ee5a9ea9fdc66934cbba6a5e7b1486bb1aa | <ide><path>test/parallel/test-fs-promises.js
<ide> function verifyStatObject(stat) {
<ide> stats = await stat(dest);
<ide> verifyStatObject(stats);
<ide>
<add> stats = await handle.stat();
<add> verifyStatObject(stats);
<add>
<ide> await fdatasync(handle);
<add> await handle.datasync();
<ide> await fsync(handle);
<add> await handle.sync();
<ide>
<del> const buf = Buffer.from('hello world');
<del>
<add> const buf = Buffer.from('hello fsPromises');
<add> const bufLen = buf.length;
<ide> await write(handle, buf);
<del>
<del> const ret = await read(handle, Buffer.alloc(11), 0, 11, 0);
<del> assert.strictEqual(ret.bytesRead, 11);
<add> const ret = await read(handle, Buffer.alloc(bufLen), 0, bufLen, 0);
<add> assert.strictEqual(ret.bytesRead, bufLen);
<ide> assert.deepStrictEqual(ret.buffer, buf);
<ide>
<add> const buf2 = Buffer.from('hello FileHandle');
<add> const buf2Len = buf2.length;
<add> await handle.write(buf2, 0, buf2Len, 0);
<add> const ret2 = await handle.read(Buffer.alloc(buf2Len), 0, buf2Len, 0);
<add> assert.strictEqual(ret2.bytesRead, buf2Len);
<add> assert.deepStrictEqual(ret2.buffer, buf2);
<add>
<ide> await chmod(dest, 0o666);
<ide> await fchmod(handle, 0o666);
<add> await handle.chmod(0o666);
<add>
<add> // `mode` can't be > 0o777
<add> assert.rejects(
<add> async () => chmod(handle, (0o777 + 1)),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError [ERR_INVALID_ARG_TYPE]'
<add> }
<add> );
<add> assert.rejects(
<add> async () => fchmod(handle, (0o777 + 1)),
<add> {
<add> code: 'ERR_OUT_OF_RANGE',
<add> name: 'RangeError [ERR_OUT_OF_RANGE]'
<add> }
<add> );
<add> assert.rejects(
<add> async () => handle.chmod(handle, (0o777 + 1)),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError [ERR_INVALID_ARG_TYPE]'
<add> }
<add> );
<ide>
<ide> await utimes(dest, new Date(), new Date());
<ide>
<ide> try {
<ide> await futimes(handle, new Date(), new Date());
<add> await handle.utimes(new Date(), new Date());
<ide> } catch (err) {
<ide> // Some systems do not have futimes. If there is an error,
<ide> // expect it to be ENOSYS
<ide> function verifyStatObject(stat) {
<ide> await rmdir(newdir);
<ide>
<ide> await mkdtemp(path.resolve(tmpDir, 'FOO'));
<add> assert.rejects(
<add> // mkdtemp() expects to get a string prefix.
<add> async () => mkdtemp(1),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError [ERR_INVALID_ARG_TYPE]'
<add> }
<add> );
<add>
<ide> }
<ide>
<ide> doTest().then(common.mustCall()); | 1 |
Python | Python | feature qubole hook support headers | 996965aad9874e9c6dad0a1f147d779adc462278 | <ide><path>airflow/providers/qubole/hooks/qubole.py
<ide> def get_results(
<ide> cmd_id = ti.xcom_pull(key="qbol_cmd_id", task_ids=self.task_id)
<ide> self.cmd = self.cls.find(cmd_id)
<ide>
<add> include_headers_str = 'true' if include_headers else 'false'
<ide> self.cmd.get_results(
<del> fp, inline, delim, fetch, arguments=[include_headers]
<add> fp, inline, delim, fetch, arguments=[include_headers_str]
<ide> ) # type: ignore[attr-defined]
<ide> fp.flush()
<ide> fp.close()
<ide><path>airflow/providers/qubole/hooks/qubole_check.py
<ide> def get_query_results(self) -> Optional[str]:
<ide> cmd_id = self.cmd.id
<ide> self.log.info("command id: %d", cmd_id)
<ide> query_result_buffer = StringIO()
<del> self.cmd.get_results(fp=query_result_buffer, inline=True, delim=COL_DELIM, arguments=[True])
<add> self.cmd.get_results(fp=query_result_buffer, inline=True, delim=COL_DELIM, arguments=['true'])
<ide> query_result = query_result_buffer.getvalue()
<ide> query_result_buffer.close()
<ide> return query_result
<ide><path>tests/providers/qubole/hooks/test_qubole.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide> #
<del>import unittest
<add>from unittest import TestCase, mock
<add>
<add>from qds_sdk.commands import PrestoCommand
<ide>
<ide> from airflow.providers.qubole.hooks.qubole import QuboleHook
<ide>
<add>DAG_ID = "qubole_test_dag"
<add>TASK_ID = "test_task"
<add>RESULTS_WITH_HEADER = 'header1\theader2\nval1\tval2'
<add>RESULTS_WITH_NO_HEADER = 'val1\tval2'
<add>
<ide> add_tags = QuboleHook._add_tags
<ide>
<ide>
<del>class TestQuboleHook(unittest.TestCase):
<add># pylint: disable = unused-argument
<add>def get_result_mock(fp, inline, delim, fetch, arguments):
<add> if arguments[0] == 'true':
<add> fp.write(bytearray(RESULTS_WITH_HEADER, 'utf-8'))
<add> else:
<add> fp.write(bytearray(RESULTS_WITH_NO_HEADER, 'utf-8'))
<add>
<add>
<add>class TestQuboleHook(TestCase):
<ide> def test_add_string_to_tags(self):
<ide> tags = {'dag_id', 'task_id'}
<ide> add_tags(tags, 'string')
<ide> def test_add_tuple_to_tags(self):
<ide> tags = {'dag_id', 'task_id'}
<ide> add_tags(tags, ('value1', 'value2'))
<ide> assert {'dag_id', 'task_id', 'value1', 'value2'} == tags
<add>
<add> @mock.patch('qds_sdk.commands.Command.get_results', new=get_result_mock)
<add> def test_get_results_with_headers(self):
<add> dag = mock.MagicMock()
<add> dag.dag_id = DAG_ID
<add> hook = QuboleHook(task_id=TASK_ID, command_type='prestocmd', dag=dag)
<add>
<add> task = mock.MagicMock()
<add> task.xcom_pull.return_value = 'test_command_id'
<add> with mock.patch('qds_sdk.resource.Resource.find', return_value=PrestoCommand):
<add> results = open(hook.get_results(ti=task, include_headers=True)).read()
<add> assert results == RESULTS_WITH_HEADER
<add>
<add> @mock.patch('qds_sdk.commands.Command.get_results', new=get_result_mock)
<add> def test_get_results_without_headers(self):
<add> dag = mock.MagicMock()
<add> dag.dag_id = DAG_ID
<add> hook = QuboleHook(task_id=TASK_ID, command_type='prestocmd', dag=dag)
<add>
<add> task = mock.MagicMock()
<add> task.xcom_pull.return_value = 'test_command_id'
<add>
<add> with mock.patch('qds_sdk.resource.Resource.find', return_value=PrestoCommand):
<add> results = open(hook.get_results(ti=task, include_headers=False)).read()
<add> assert results == RESULTS_WITH_NO_HEADER
<ide><path>tests/providers/qubole/operators/test_qubole.py
<ide> # under the License.
<ide> #
<ide>
<del>import unittest
<add>from unittest import TestCase, mock
<ide>
<ide> from airflow import settings
<ide> from airflow.models import DAG, Connection
<ide> DEFAULT_DATE = datetime(2017, 1, 1)
<ide>
<ide>
<del>class TestQuboleOperator(unittest.TestCase):
<add>class TestQuboleOperator(TestCase):
<ide> def setUp(self):
<ide> db.merge_conn(Connection(conn_id=DEFAULT_CONN, conn_type='HTTP'))
<ide> db.merge_conn(Connection(conn_id=TEST_CONN, conn_type='HTTP', host='http://localhost/api'))
<ide> def test_parameter_pool_passed(self):
<ide> test_pool = 'test_pool'
<ide> op = QuboleOperator(task_id=TASK_ID, pool=test_pool)
<ide> assert op.pool == test_pool
<add>
<add> @mock.patch('airflow.providers.qubole.hooks.qubole.QuboleHook.get_results')
<add> def test_parameter_include_header_passed(self, mock_get_results):
<add> dag = DAG(DAG_ID, start_date=DEFAULT_DATE)
<add> qubole_operator = QuboleOperator(task_id=TASK_ID, dag=dag, command_type='prestocmd')
<add> qubole_operator.get_results(include_headers=True)
<add> mock_get_results.asset_called_with('include_headers', True)
<add>
<add> @mock.patch('airflow.providers.qubole.hooks.qubole.QuboleHook.get_results')
<add> def test_parameter_include_header_missing(self, mock_get_results):
<add> dag = DAG(DAG_ID, start_date=DEFAULT_DATE)
<add> qubole_operator = QuboleOperator(task_id=TASK_ID, dag=dag, command_type='prestocmd')
<add> qubole_operator.get_results()
<add> mock_get_results.asset_called_with('include_headers', False) | 4 |
Javascript | Javascript | remove duplicate checks | 0e7e91f39773f7f7936ce3dcc602091680ea2943 | <ide><path>lib/internal/quic/util.js
<ide> function validateQuicStreamOptions(options = {}) {
<ide>
<ide> function validateQuicEndpointOptions(options = {}, name = 'options') {
<ide> validateObject(options, name);
<del> if (options === null || typeof options !== 'object')
<del> throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
<ide> const {
<ide> address,
<ide> lookup, | 1 |
Text | Text | fix example code | 8faa78053e694dabda6ad0f232ffd2d117c0e477 | <ide><path>src/ORM/README.md
<ide> $cacheConfig = [
<ide> 'duration' => '+1 year',
<ide> 'serialize' => true,
<ide> 'prefix' => 'orm_',
<del>],
<add>];
<ide> Cache::setConfig('_cake_model_', $cacheConfig);
<ide> ```
<ide> | 1 |
Javascript | Javascript | add test for multiple bundles | 53a339a45970252a3e0c4c91bd02061f2e2ed099 | <ide><path>local-cli/util/__mocks__/fs.js
<ide> fs.close.mockImplementation((fd, callback = noop) => {
<ide>
<ide> let filesystem = {};
<ide>
<add>fs.mock = {
<add> clear() {
<add> filesystem = {};
<add> },
<add>};
<add>
<ide> fs.createReadStream.mockImplementation(filepath => {
<ide> if (!filepath.startsWith('/')) {
<ide> throw Error('Cannot open file ' + filepath); | 1 |
Javascript | Javascript | fix mmdphysics _updateboneposition() | d7ed0a01cd4a93ad62f6fc5f1c6e957e2253896d | <ide><path>examples/js/animation/MMDPhysics.js
<ide> THREE.MMDPhysics = ( function () {
<ide> _getWorldTransformForBone: function () {
<ide>
<ide> var manager = this.manager;
<del>
<del> var tr = manager.allocTransform();
<del> this.body.getMotionState().getWorldTransform( tr );
<del> var tr2 = manager.multiplyTransforms( tr, this.boneOffsetFormInverse );
<del>
<del> manager.freeTransform( tr );
<del>
<del> return tr2;
<add> var tr = this.body.getCenterOfMassTransform();
<add> return manager.multiplyTransforms( tr, this.boneOffsetFormInverse );
<ide>
<ide> },
<ide>
<ide> THREE.MMDPhysics = ( function () {
<ide>
<ide> var manager = this.manager;
<ide>
<del> var tr = this.body.getCenterOfMassTransform();
<del> var origin = tr.getOrigin();
<del>
<del> var matrixInv = manager.allocThreeMatrix4();
<del> matrixInv.copy( this.bone.parent.matrixWorld ).getInverse( matrixInv );
<del>
<del> var pos = manager.allocThreeVector3();
<del> pos.set( origin.x(), origin.y(), origin.z() ).applyMatrix4( matrixInv );
<del>
<del> this.bone.position.copy( pos );
<del>
<del> manager.freeThreeVector3( pos );
<del> manager.freeThreeMatrix4( matrixInv );
<add> var tr = this._getWorldTransformForBone();
<add>
<add> var thV = manager.allocThreeVector3();
<add>
<add> var o = manager.getOrigin( tr );
<add> thV.set( o.x(), o.y(), o.z() );
<add>
<add> if ( this.bone.parent ) {
<add>
<add> this.bone.parent.worldToLocal( thV );
<add>
<add> }
<add>
<add> this.bone.position.copy( thV );
<add>
<add> manager.freeThreeVector3( thV );
<add>
<add> manager.freeTransform( tr );
<ide>
<ide> }
<ide> | 1 |
Text | Text | update doc for `brew livecheck` | 07ac5bf3b60278dbff15d13dbd798d342588347e | <ide><path>docs/Brew-Livecheck.md
<ide> # `brew livecheck`
<ide>
<del>The `brew livecheck` command finds the newest version of a formula or cask's software by checking upstream. Livecheck has [strategies](https://rubydoc.brew.sh/Homebrew/Livecheck/Strategy.html) to identify versions from various sources, such as Git repositories, websites, etc.
<add>The `brew livecheck` command finds the newest version of a formula, cask or resource's software by checking upstream. Livecheck has [strategies](https://rubydoc.brew.sh/Homebrew/Livecheck/Strategy.html) to identify versions from various sources, such as Git repositories, websites, etc.
<ide>
<ide> ## Behavior
<ide>
<ide> When livecheck isn't given instructions for how to check for upstream versions, it does the following by default:
<ide>
<del>1. For formulae: Collect the `head`, `stable`, and `homepage` URLs, in that order. For casks: Collect the `url` and `homepage` URLs, in that order.
<del>1. Determine if any strategies apply to the first URL. If not, try the next URL.
<del>1. If a strategy can be applied, use it to check for new versions.
<del>1. Return the newest version (or an error if versions could not be found at any available URLs).
<add>1. For __formulae__: Collect the `stable`, `head` and `homepage` URLs, in that order. For __casks__: Collect the `appcast`, `url` and `homepage` URLs, in that order. For __resource__: Collect the `url` (since resource's url is considered `stable` by default)
<add>2. Determine if any strategies apply to the first URL. If not, try the next URL.
<add>3. If a strategy can be applied, use it to check for new versions.
<add>4. Return the newest version (or an error if versions could not be found at any available URLs).
<ide>
<ide> It's sometimes necessary to override this default behavior to create a working check. If a source doesn't provide the newest version, we need to check a different one. If livecheck doesn't correctly match version text, we need to provide an appropriate regex or `strategy` block.
<ide>
<del>This can be accomplished by adding a `livecheck` block to the formula/cask. For more information on the available methods, please refer to the [`Livecheck` class documentation](https://rubydoc.brew.sh/Livecheck.html).
<add>This can be accomplished by adding a `livecheck` block to the formula/cask/resource. For more information on the available methods, please refer to the [`Livecheck` class documentation](https://rubydoc.brew.sh/Livecheck.html).
<ide>
<ide> ## Creating a check
<ide>
<del>1. **Use the debug output to understand the situation**. `brew livecheck --debug <formula>|<cask>` provides information about which URLs livecheck tries, any strategies that apply, matched versions, etc.
<add>1. **Use the debug output to understand the situation**. `brew livecheck --debug <formula>|<cask>` provides information about which URLs livecheck tries, any strategies that apply, matched versions, etc. `brew livecheck --debug --resources <formula>` will provides livecheck's debug information about the resources as well.
<ide>
<del>1. **Research available sources to select a URL**. Try removing the file name from `stable`/`url`, to see if this is a directory listing page. If that doesn't work, try to find a page that links to the file (e.g. a download page). If it's not possible to find the newest version on the website, try checking other sources from the formula/cask. When necessary, search for other sources outside of the formula/cask.
<add>> Note: `--resources` flag only works with Formulae.
<ide>
<del>1. **Create a regex, if necessary**. If the check works without a regex and wouldn't benefit from having one, it's usually fine to omit it. More information on creating regexes can be found in the [regex guidelines](#regex-guidelines) section.
<add>2. **Research available sources to select a URL**. Try removing the file name from `stable`/`url`, to see if this is a directory listing page. If that doesn't work, try to find a page that links to the file (e.g. a download page). If it's not possible to find the newest version on the website, try checking other sources from the formula/cask. When necessary, search for other sources outside of the formula/cask.
<add>
<add>3. **Create a regex, if necessary**. If the check works without a regex and wouldn't benefit from having one, it's usually fine to omit it. More information on creating regexes can be found in the [regex guidelines](#regex-guidelines) section.
<ide>
<ide> ### General guidelines
<ide> | 1 |
PHP | PHP | set the entityclass for the mock | 19e00a9f7067ccd4d4e88eecef3233b330a546ba | <ide><path>src/TestSuite/TestCase.php
<ide> public function getMockForModel($alias, array $methods = array(), array $options
<ide> $options += TableRegistry::config($alias);
<ide>
<ide> $mock = $this->getMock($options['className'], $methods, [$options]);
<add>
<add> if (empty($options['entityClass']) && $mock->entityClass() === '\Cake\ORM\Entity') {
<add> $parts = explode('\\', $options['className']);
<add> $entityAlias = Inflector::singularize(substr(array_pop($parts), 0, -5));
<add> $entityClass = implode('\\', array_slice($parts, 0, -1)) . '\Entity\\' . $entityAlias;
<add> if (class_exists($entityClass)) {
<add> $mock->entityClass($entityClass);
<add> }
<add> }
<add>
<ide> TableRegistry::set($baseClass, $mock);
<ide> return $mock;
<ide> } | 1 |
Javascript | Javascript | fix markdown formatting | 4cac4c78c0b53fb5b787894f7e5c1683334e11c4 | <ide><path>packages/ember-testing/lib/helpers/pause_test.js
<ide> export function resumeTest() {
<ide> Pauses the current test - this is useful for debugging while testing or for test-driving.
<ide> It allows you to inspect the state of your application at any point.
<ide> Example (The test will pause before clicking the button):
<add>
<ide> ```javascript
<ide> visit('/')
<ide> return pauseTest(); | 1 |
Java | Java | use original query string of forwarded request | bf83e4e8612512ef51272d8a7dd8533686e8a4e4 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/AbstractFlashMapManager.java
<ide> private FlashMap getMatchingFlashMap(List<FlashMap> allMaps, HttpServletRequest
<ide> */
<ide> protected boolean isFlashMapForRequest(FlashMap flashMap, HttpServletRequest request) {
<ide> String expectedPath = flashMap.getTargetRequestPath();
<add> String requestUri = getUrlPathHelper().getOriginatingRequestUri(request);
<ide> if (expectedPath != null) {
<del> String requestUri = getUrlPathHelper().getOriginatingRequestUri(request);
<ide> if (!requestUri.equals(expectedPath) && !requestUri.equals(expectedPath + "/")) {
<ide> return false;
<ide> }
<ide> }
<del> UriComponents uriComponents = ServletUriComponentsBuilder.fromRequest(request).build();
<add> String queryString = getUrlPathHelper().getOriginatingQueryString(request);
<add> UriComponents uriComponents = ServletUriComponentsBuilder.fromUriString(requestUri).query(queryString).build();
<ide> MultiValueMap<String, String> actualParams = uriComponents.getQueryParams();
<ide> MultiValueMap<String, String> expectedParams = flashMap.getTargetRequestParams();
<ide> for (String expectedName : expectedParams.keySet()) {
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/support/FlashMapManagerTests.java
<ide> public void flashAttributesWithQueryParamsWithSpace() throws Exception {
<ide> assertEquals("value", flashMap.get("key"));
<ide> }
<ide>
<add> // SPR-15505
<add>
<add> @Test
<add> public void retrieveAndUpdateMatchByOriginatingPathAndQueryString() {
<add> FlashMap flashMap = new FlashMap();
<add> flashMap.put("key", "value");
<add> flashMap.setTargetRequestPath("/accounts");
<add> flashMap.addTargetRequestParam("a", "b");
<add>
<add> this.flashMapManager.setFlashMaps(Arrays.asList(flashMap));
<add>
<add> this.request.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, "/accounts");
<add> this.request.setAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE, "a=b");
<add> this.request.setRequestURI("/mvc/accounts");
<add> this.request.setQueryString("x=y");
<add> FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response);
<add>
<add> assertEquals(flashMap, inputFlashMap);
<add> assertEquals("Input FlashMap should have been removed", 0, this.flashMapManager.getFlashMaps().size());
<add> }
<ide>
<ide> private static class TestFlashMapManager extends AbstractFlashMapManager {
<ide> | 2 |
PHP | PHP | use mutable date for date base class | 037e1d63969b547fa5fc186a56b26fbf2b927cd9 | <ide><path>src/Database/Type/DateType.php
<ide> namespace Cake\Database\Type;
<ide>
<ide> use Cake\Database\Driver;
<del>use DateTimeImmutable;
<add>use DateTime;
<ide>
<ide> class DateType extends DateTimeType
<ide> {
<ide><path>src/I18n/Date.php
<ide> */
<ide> namespace Cake\I18n;
<ide>
<del>use Cake\Chronos\Date as BaseDate;
<add>use Cake\Chronos\MutableDate;
<ide> use IntlDateFormatter;
<ide> use JsonSerializable;
<ide>
<ide> *
<ide> * Adds handy methods and locale-aware formatting helpers
<ide> */
<del>class Date extends BaseDate implements JsonSerializable
<add>class Date extends MutableDate implements JsonSerializable
<ide> {
<ide> use DateFormatTrait;
<ide> | 2 |
Javascript | Javascript | add new help rooms and logic | eebd0cf76377423395cfc239b375643a5a060109 | <ide><path>index.js
<ide> destroy()
<ide> var isBeta = !!challengeSpec.isBeta;
<ide> var isComingSoon = !!challengeSpec.isComingSoon;
<ide> var fileName = challengeSpec.fileName;
<add> var helpRoom = challengeSpec.helpRoom || 'Help';
<add>
<ide> console.log('parsed %s successfully', block);
<ide>
<ide> // challenge file has no challenges...
<ide> destroy()
<ide> .replace(/\s/g, '-');
<ide>
<ide> challenge.fileName = fileName;
<add> challenge.helpRoom = helpRoom;
<ide> challenge.order = order;
<ide> challenge.suborder = index + 1;
<ide> challenge.block = block; | 1 |
Text | Text | add release notes for 1.1.4 and 1.0.6 | 7729b58edaee80503cb6ed704f51780436f6072b | <ide><path>CHANGELOG.md
<add><a name="1.1.4"></a>
<add># 1.1.4 quantum-manipulation (2013-04-03)
<add>
<add>_Note: 1.1.x releases are [considered unstable](http://blog.angularjs.org/2012/07/angularjs-10-12-roadmap.html).
<add>They pass all tests but we reserve the right to change new features/apis in between minor releases. Check them
<add>out and please give us feedback._
<add>
<add>_Note: This release also contains all bug fixes available in [1.0.6](#1.0.6)._
<add>
<add>
<add>## Features
<add>
<add>- **$compile:**
<add> - allow directives to modify interpolated attributes
<add> ([fe8d893b](https://github.com/angular/angular.js/commit/fe8d893b839e9b14e3e55a3a0523cc1e6355bdd5))
<add> - support for dynamic template generation
<add> ([eb53423a](https://github.com/angular/angular.js/commit/eb53423a41136fcda0c5e711f2d104952080354b))
<add> - add attribute binding support via ngAttr*
<add> ([cf17c6af](https://github.com/angular/angular.js/commit/cf17c6af475eace31cf52944afd8e10d3afcf6c0),
<add> [#1050](https://github.com/angular/angular.js/issues/1050), [#1925](https://github.com/angular/angular.js/issues/1925))
<add> - `'=?'` makes `'='` binding optional
<add> ([ac899d0d](https://github.com/angular/angular.js/commit/ac899d0da59157fa1c6429510791b6c3103d9401),
<add> [#909](https://github.com/angular/angular.js/issues/909), [#1435](https://github.com/angular/angular.js/issues/1435))
<add>
<add>- **$q:** `$q.all()` now accepts hash
<add> ([e27bb6eb](https://github.com/angular/angular.js/commit/e27bb6eb132a68665c8fca3f5a216b19b1129ba6))
<add>
<add>- **$resource:** ability to override url in resource actions
<add> ([60f1f099](https://github.com/angular/angular.js/commit/60f1f099fc7e5197808cd6acb7407cdc40f50a3f))
<add>
<add>- **$route:** add `caseInsensitiveMatch` option for url matching
<add> ([5e18a15f](https://github.com/angular/angular.js/commit/5e18a15fb01d2e81adda68503754289fa9655082))
<add>
<add>- **http:**
<add> - support request/response promise chaining
<add> ([4ae46814](https://github.com/angular/angular.js/commit/4ae46814ff4e7c0bbcdbbefc0a97277283a84065))
<add> - set custom default cache in $http.defaults.cache
<add> ([99f3b70b](https://github.com/angular/angular.js/commit/99f3b70b2d316f5bb39e21249e752c29f49c90ab))
<add>
<add>
<add>- **JQLite:** `ready()` now supports `document.readyState=='complete'`
<add> ([753fc9e5](https://github.com/angular/angular.js/commit/753fc9e58d5e554d4930548558efecc283557eeb))
<add>
<add>- **Scenario:** autodisable animations when running e2e tests
<add> ([fec4ef38](https://github.com/angular/angular.js/commit/fec4ef38815340e8e5a6b65fd6c08f5c74e701d8))
<add>
<add>- **Scope:** add `$watchCollection` method for observing collections
<add> ([5eb96855](https://github.com/angular/angular.js/commit/5eb968553a1130461ab8704535691e00eb154ac2))
<add>
<add>- **angular.bootstrap:** support deferred bootstrap (mainly useful for tools like test runners and Batarang)
<add> ([603fe0d1](https://github.com/angular/angular.js/commit/603fe0d19608ffe1915d8bc23bf412912e7ee1ac))
<add>
<add>- **ngMobile:** add ngMobile module with mobile-specific ngClick
<add> ([707c65d5](https://github.com/angular/angular.js/commit/707c65d5a228b44ab3aea2fad95516fe6c57169a))
<add>
<add>- **Directives:**
<add> - **ngKeypress:** add ngKeypress directive for handling keypress event
<add> ([f20646bc](https://github.com/angular/angular.js/commit/f20646bce5f0c914992a78fc2556bda136c27ac9))
<add> - **ngSwitch:** Preserve the order of the elements not in the ng-switch
<add> ([e88d6179](https://github.com/angular/angular.js/commit/e88d6179c3a6a137e75fa09de906fc83c6515db2),
<add> [#1074](https://github.com/angular/angular.js/issues/1074))
<add> - **ngAnimate:** add support for animation
<add> ([0b6f1ce5](https://github.com/angular/angular.js/commit/0b6f1ce5f89f47f9302ff1e8cd8f4b92f837c413))
<add> - **ngRepeat:** add support for custom tracking of items
<add> ([61f2767c](https://github.com/angular/angular.js/commit/61f2767ce65562257599649d9eaf9da08f321655))
<add>
<add>
<add>## Breaking Changes
<add>
<add>- **$route:** due to [6f71e809](https://github.com/angular/angular.js/commit/6f71e809141bf89501e55c378921d6e7ec9512bc),
<add> in $routeChangeStart event, nextRoute.$route property is gone. Use the nextRoute object itself instead of nextRoute.$route.
<add>
<add>- **ngRepeat:** due to [61f2767c](https://github.com/angular/angular.js/commit/61f2767ce65562257599649d9eaf9da08f321655), it is now considered an error to have two identical items (identified by the new "track by" expression) in a collection that is fed into the repeater. This behavior was previously tolerated.
<add>
<add>- **ngSwitch:** due to [e88d6179](https://github.com/angular/angular.js/commit/e88d6179c3a6a137e75fa09de906fc83c6515db2),
<add> elements not in the ng-switch were rendered after the ng-switch elements. Now they are rendered in-place.
<add>
<add> Templates with ngSwitch directives and nested non-ngSwitchWhen elements should be updated to preserve render order.
<add>
<add> For example: The following was previously rendered with `<li>1</li>` after `<li>2</li>`:
<add>
<add> <ul ng-switch="select">
<add> <li>1</li>
<add> <li ng-switch-when="option">2</li>
<add> </ul>
<add>
<add> To keep the old behaviour, use:
<add>
<add> <ul ng-switch="select">
<add> <li ng-switch-when="1">2</li>
<add> <li>1</li>
<add> </ul>
<add>
<add>
<add>
<add><a name="1.0.6"></a>
<add># 1.1.3 universal-irreversibility (2013-04-04)
<add>
<add>
<add>## Bug Fixes
<add>
<add>- **$compile:**
<add> - compile replace directives in external template
<add> ([398691be](https://github.com/angular/angular.js/commit/398691beb3fc40a481afa258d181de06ec0d153c),
<add> [#1859](https://github.com/angular/angular.js/issues/1859))
<add> - whitelist file:// in url sanitization
<add> ([7b236b29](https://github.com/angular/angular.js/commit/7b236b29aa3a6f6dfe722815e0a2667d9b7f0899))
<add> - handle elements with no childNodes property
<add> ([bec614fd](https://github.com/angular/angular.js/commit/bec614fd90c48c3921a4b659912008574e553b40))
<add>- **$http:** don't encode URL query substring "null" to "+"
<add> ([86d191ed](https://github.com/angular/angular.js/commit/86d191ed4aea9015adc71b852223475c5c762c34))
<add>- **$httpBackend:** prevent DOM err due to dereferencing .responseText
<add> ([509ec745](https://github.com/angular/angular.js/commit/509ec745fdbb54b54672fbf8595a4958c16f2b53),
<add> [#1922](https://github.com/angular/angular.js/issues/1922))
<add>- **$location:**
<add> - parse FirefoxOS packaged app urls
<add> ([3a81dd8b](https://github.com/angular/angular.js/commit/3a81dd8bddbade81c4c9f734813458d0d969a4bf),
<add> [#2112](https://github.com/angular/angular.js/issues/2112))
<add> - correctly rewrite html5 url to hashbang url
<add> ([9befe370](https://github.com/angular/angular.js/commit/9befe37014141fbfdf0cded318d28322fc058c13))
<add>- **$route:** make nextRoute.$route private
<add> ([6f71e809](https://github.com/angular/angular.js/commit/6f71e809141bf89501e55c378921d6e7ec9512bc),
<add> [#1907](https://github.com/angular/angular.js/issues/1907))
<add>- **mocks:** prevent NPE when module definition outside of it.
<add> ([5c735eb4](https://github.com/angular/angular.js/commit/5c735eb4ab07144a62949472ed388cb185099201))
<add>- **dateFilter:** correct timezone date filter for 1/2 hour offsets
<add> ([1c1cd4fd](https://github.com/angular/angular.js/commit/1c1cd4fdf6b6d7511c7b8dc61b8042011dc54830))
<add>
<add>
<add>
<add>
<add>
<add>
<add>
<ide> <a name="1.1.3"></a>
<ide> # 1.1.3 radioactive-gargle (2013-02-20)
<ide> | 1 |
Text | Text | use "sudo" for dockerd examples | 87b174080bd8b1b9ea2bbfad8ef35a4c0dfe8ad4 | <ide><path>docs/reference/commandline/dockerd.md
<ide> find examples of using Systemd socket activation with Docker and Systemd in the
<ide> You can configure the Docker daemon to listen to multiple sockets at the same
<ide> time using multiple `-H` options:
<ide>
<del> # listen using the default unix socket, and on 2 specific IP addresses on this host.
<del> dockerd -H unix:///var/run/docker.sock -H tcp://192.168.59.106 -H tcp://10.10.10.2
<add>```bash
<add># listen using the default unix socket, and on 2 specific IP addresses on this host.
<add>$ sudo dockerd -H unix:///var/run/docker.sock -H tcp://192.168.59.106 -H tcp://10.10.10.2
<add>```
<ide>
<ide> The Docker client will honor the `DOCKER_HOST` environment variable to set the
<ide> `-H` flag for the client.
<ide>
<del> $ docker -H tcp://0.0.0.0:2375 ps
<del> # or
<del> $ export DOCKER_HOST="tcp://0.0.0.0:2375"
<del> $ docker ps
<del> # both are equal
<add>```bash
<add>$ docker -H tcp://0.0.0.0:2375 ps
<add># or
<add>$ export DOCKER_HOST="tcp://0.0.0.0:2375"
<add>$ docker ps
<add># both are equal
<add>```
<ide>
<ide> Setting the `DOCKER_TLS_VERIFY` environment variable to any value other than
<ide> the empty string is equivalent to setting the `--tlsverify` flag. The following
<ide> are equivalent:
<ide>
<del> $ docker --tlsverify ps
<del> # or
<del> $ export DOCKER_TLS_VERIFY=1
<del> $ docker ps
<add>```bash
<add>$ docker --tlsverify ps
<add># or
<add>$ export DOCKER_TLS_VERIFY=1
<add>$ docker ps
<add>```
<ide>
<ide> The Docker client will honor the `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY`
<ide> environment variables (or the lowercase versions thereof). `HTTPS_PROXY` takes
<ide> For example:
<ide> `-H`, when empty, will default to the same value as
<ide> when no `-H` was passed in.
<ide>
<del>`-H` also accepts short form for TCP bindings:
<del>
<del> `host:` or `host:port` or `:port`
<add>`-H` also accepts short form for TCP bindings: `host:` or `host:port` or `:port`
<ide>
<ide> Run Docker in daemon mode:
<ide>
<del> $ sudo <path to>/dockerd -H 0.0.0.0:5555 &
<add>```bash
<add>$ sudo <path to>/dockerd -H 0.0.0.0:5555 &
<add>```
<ide>
<ide> Download an `ubuntu` image:
<ide>
<del> $ docker -H :5555 pull ubuntu
<add>```bash
<add>$ docker -H :5555 pull ubuntu
<add>```
<ide>
<ide> You can use multiple `-H`, for example, if you want to listen on both
<ide> TCP and a Unix socket
<ide>
<del> # Run docker in daemon mode
<del> $ sudo <path to>/dockerd -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock &
<del> # Download an ubuntu image, use default Unix socket
<del> $ docker pull ubuntu
<del> # OR use the TCP port
<del> $ docker -H tcp://127.0.0.1:2375 pull ubuntu
<add>```bash
<add># Run docker in daemon mode
<add>$ sudo <path to>/dockerd -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock &
<add># Download an ubuntu image, use default Unix socket
<add>$ docker pull ubuntu
<add># OR use the TCP port
<add>$ docker -H tcp://127.0.0.1:2375 pull ubuntu
<add>```
<ide>
<ide> ### Daemon storage-driver option
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> * `dm.thinpooldev`
<ide>
<del> Specifies a custom block storage device to use for the thin pool.
<add> Specifies a custom block storage device to use for the thin pool.
<ide>
<del> If using a block device for device mapper storage, it is best to use `lvm`
<del> to create and manage the thin-pool volume. This volume is then handed to Docker
<del> to exclusively create snapshot volumes needed for images and containers.
<add> If using a block device for device mapper storage, it is best to use `lvm`
<add> to create and manage the thin-pool volume. This volume is then handed to Docker
<add> to exclusively create snapshot volumes needed for images and containers.
<ide>
<del> Managing the thin-pool outside of Engine makes for the most feature-rich
<del> method of having Docker utilize device mapper thin provisioning as the
<del> backing storage for Docker containers. The highlights of the lvm-based
<del> thin-pool management feature include: automatic or interactive thin-pool
<del> resize support, dynamically changing thin-pool features, automatic thinp
<del> metadata checking when lvm activates the thin-pool, etc.
<add> Managing the thin-pool outside of Engine makes for the most feature-rich
<add> method of having Docker utilize device mapper thin provisioning as the
<add> backing storage for Docker containers. The highlights of the lvm-based
<add> thin-pool management feature include: automatic or interactive thin-pool
<add> resize support, dynamically changing thin-pool features, automatic thinp
<add> metadata checking when lvm activates the thin-pool, etc.
<ide>
<del> As a fallback if no thin pool is provided, loopback files are
<del> created. Loopback is very slow, but can be used without any
<del> pre-configuration of storage. It is strongly recommended that you do
<del> not use loopback in production. Ensure your Engine daemon has a
<del> `--storage-opt dm.thinpooldev` argument provided.
<add> As a fallback if no thin pool is provided, loopback files are
<add> created. Loopback is very slow, but can be used without any
<add> pre-configuration of storage. It is strongly recommended that you do
<add> not use loopback in production. Ensure your Engine daemon has a
<add> `--storage-opt dm.thinpooldev` argument provided.
<ide>
<del> Example use:
<add> Example use:
<ide>
<del> $ dockerd \
<del> --storage-opt dm.thinpooldev=/dev/mapper/thin-pool
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.thinpooldev=/dev/mapper/thin-pool
<add> ```
<ide>
<ide> * `dm.basesize`
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt dm.basesize=50G
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.basesize=50G
<add> ```
<add>
<ide>
<ide> This will increase the base device size to 50G. The Docker daemon will throw an
<ide> error if existing base device size is larger than 50G. A user can use
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide> that may already be initialized and inherited by pulled images. Typically,
<ide> a change to this value requires additional steps to take effect:
<ide>
<del> $ sudo service docker stop
<del> $ sudo rm -rf /var/lib/docker
<del> $ sudo service docker start
<add> ```bash
<add> $ sudo service docker stop
<add> $ sudo rm -rf /var/lib/docker
<add> $ sudo service docker start
<add> ```
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt dm.basesize=20G
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.basesize=20G
<add> ```
<ide>
<ide> * `dm.loopdatasize`
<ide>
<ide> > **Note**:
<del> > This option configures devicemapper loopback, which should not
<del> > be used in production.
<add> > This option configures devicemapper loopback, which should not
<add> > be used in production.
<ide>
<ide> Specifies the size to use when creating the loopback file for the
<ide> "data" device which is used for the thin pool. The default size is
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt dm.loopdatasize=200G
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.loopdatasize=200G
<add> ```
<ide>
<ide> * `dm.loopmetadatasize`
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt dm.loopmetadatasize=4G
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.loopmetadatasize=4G
<add> ```
<ide>
<ide> * `dm.fs`
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt dm.fs=ext4
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.fs=ext4
<add> ```
<ide>
<ide> * `dm.mkfsarg`
<ide>
<ide> Specifies extra mkfs arguments to be used when creating the base device.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt "dm.mkfsarg=-O ^has_journal"
<add> ```bash
<add> $ sudo dockerd --storage-opt "dm.mkfsarg=-O ^has_journal"
<add> ```
<ide>
<ide> * `dm.mountopt`
<ide>
<ide> Specifies extra mount options used when mounting the thin devices.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt dm.mountopt=nodiscard
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.mountopt=nodiscard
<add> ```
<ide>
<ide> * `dm.datadev`
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd \
<del> --storage-opt dm.datadev=/dev/sdb1 \
<del> --storage-opt dm.metadatadev=/dev/sdc1
<add> ```bash
<add> $ sudo dockerd \
<add> --storage-opt dm.datadev=/dev/sdb1 \
<add> --storage-opt dm.metadatadev=/dev/sdc1
<add> ```
<ide>
<ide> * `dm.metadatadev`
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide> If setting up a new metadata pool it is required to be valid. This can be
<ide> achieved by zeroing the first 4k to indicate empty metadata, like this:
<ide>
<del> $ dd if=/dev/zero of=$metadata_dev bs=4096 count=1
<add> ```bash
<add> $ dd if=/dev/zero of=$metadata_dev bs=4096 count=1
<add> ```
<ide>
<ide> Example use:
<ide>
<del> $ dockerd \
<del> --storage-opt dm.datadev=/dev/sdb1 \
<del> --storage-opt dm.metadatadev=/dev/sdc1
<add> ```bash
<add> $ sudo dockerd \
<add> --storage-opt dm.datadev=/dev/sdb1 \
<add> --storage-opt dm.metadatadev=/dev/sdc1
<add> ```
<ide>
<ide> * `dm.blocksize`
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt dm.blocksize=512K
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.blocksize=512K
<add> ```
<ide>
<ide> * `dm.blkdiscard`
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt dm.blkdiscard=false
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.blkdiscard=false
<add> ```
<ide>
<ide> * `dm.override_udev_sync_check`
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide> To view the `udev` sync support of a Docker daemon that is using the
<ide> `devicemapper` driver, run:
<ide>
<del> $ docker info
<del> [...]
<del> Udev Sync Supported: true
<del> [...]
<add> ```bash
<add> $ docker info
<add> [...]
<add> Udev Sync Supported: true
<add> [...]
<add> ```
<ide>
<ide> When `udev` sync support is `true`, then `devicemapper` and udev can
<ide> coordinate the activation and deactivation of devices for containers.
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide> To allow the `docker` daemon to start, regardless of `udev` sync not being
<ide> supported, set `dm.override_udev_sync_check` to true:
<ide>
<del> $ dockerd --storage-opt dm.override_udev_sync_check=true
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.override_udev_sync_check=true
<add> ```
<ide>
<ide> When this value is `true`, the `devicemapper` continues and simply warns
<ide> you the errors are happening.
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd --storage-opt dm.use_deferred_removal=true
<add> ```bash
<add> $ sudo dockerd --storage-opt dm.use_deferred_removal=true
<add> ```
<ide>
<ide> * `dm.use_deferred_deletion`
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide> To avoid this failure, enable both deferred device deletion and deferred
<ide> device removal on the daemon.
<ide>
<del> $ dockerd \
<del> --storage-opt dm.use_deferred_deletion=true \
<del> --storage-opt dm.use_deferred_removal=true
<add> ```bash
<add> $ sudo dockerd \
<add> --storage-opt dm.use_deferred_deletion=true \
<add> --storage-opt dm.use_deferred_removal=true
<add> ```
<ide>
<ide> With these two options enabled, if a device is busy when the driver is
<ide> deleting a container, the driver marks the device as deleted. Later, when
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide> Example use:
<ide>
<ide> ```bash
<del> $ dockerd --storage-opt dm.min_free_space=10%
<add> $ sudo dockerd --storage-opt dm.min_free_space=10%
<ide> ```
<ide>
<ide> * `dm.xfs_nospace_max_retries`
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide> Example use:
<ide>
<ide> ```bash
<del> $ dockerd --storage-opt dm.xfs_nospace_max_retries=0
<add> $ sudo dockerd --storage-opt dm.xfs_nospace_max_retries=0
<ide> ```
<ide>
<ide> #### ZFS options
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide>
<ide> Example use:
<ide>
<del> $ dockerd -s zfs --storage-opt zfs.fsname=zroot/docker
<add> ```bash
<add> $ sudo dockerd -s zfs --storage-opt zfs.fsname=zroot/docker
<add> ```
<ide>
<ide> #### Btrfs options
<ide>
<ide> options for `zfs` start with `zfs` and options for `btrfs` start with `btrfs`.
<ide> **size** cannot be smaller than **btrfs.min_space**.
<ide>
<ide> Example use:
<del> $ dockerd -s btrfs --storage-opt btrfs.min_space=10G
<add>
<add> ```bash
<add> $ sudo dockerd -s btrfs --storage-opt btrfs.min_space=10G
<add> ```
<ide>
<ide> #### Overlay2 options
<ide>
<ide> control `containerd` startup, manually start `containerd` and pass the path to
<ide> the `containerd` socket using the `--containerd` flag. For example:
<ide>
<ide> ```bash
<del>$ dockerd --containerd /var/run/dev/docker-containerd.sock
<add>$ sudo dockerd --containerd /var/run/dev/docker-containerd.sock
<ide> ```
<ide>
<ide> Runtimes can be registered with the daemon either via the
<ide> The following is an example adding 2 runtimes via the configuration:
<ide>
<ide> This is the same example via the command line:
<ide>
<del> $ sudo dockerd --add-runtime runc=runc --add-runtime custom=/usr/local/bin/my-runc-replacement
<add>```bash
<add>$ sudo dockerd --add-runtime runc=runc --add-runtime custom=/usr/local/bin/my-runc-replacement
<add>```
<ide>
<del>**Note**: defining runtime arguments via the command line is not supported.
<add>> **Note**: defining runtime arguments via the command line is not supported.
<ide>
<ide> ## Options for the runtime
<ide>
<ide> cgroups. You can specify only specify `cgroupfs` or `systemd`. If you specify
<ide>
<ide> This example sets the `cgroupdriver` to `systemd`:
<ide>
<del> $ sudo dockerd --exec-opt native.cgroupdriver=systemd
<add>```bash
<add>$ sudo dockerd --exec-opt native.cgroupdriver=systemd
<add>```
<ide>
<ide> Setting this option applies to all containers the daemon launches.
<ide>
<ide> Also Windows Container makes use of `--exec-opt` for special purpose. Docker user
<ide> can specify default container isolation technology with this, for example:
<ide>
<del> $ dockerd --exec-opt isolation=hyperv
<add>```bash
<add>$ sudo dockerd --exec-opt isolation=hyperv
<add>```
<ide>
<ide> Will make `hyperv` the default isolation technology on Windows. If no isolation
<ide> value is specified on daemon start, on Windows client, the default is
<ide> `hyperv`, and on Windows server, the default is `process`.
<ide>
<ide> ## Daemon DNS options
<ide>
<del>To set the DNS server for all Docker containers, use
<del>`dockerd --dns 8.8.8.8`.
<add>To set the DNS server for all Docker containers, use:
<add>
<add>```bash
<add>$ sudo dockerd --dns 8.8.8.8
<add>```
<add>
<add>
<add>To set the DNS search domain for all Docker containers, use:
<add>
<add>```bash
<add>$ sudo dockerd --dns-search example.com
<add>```
<ide>
<del>To set the DNS search domain for all Docker containers, use
<del>`dockerd --dns-search example.com`.
<ide>
<ide> ## Insecure registries
<ide>
<ide> using the `--cluster-store-opt` flag, specifying the paths to PEM encoded
<ide> files. For example:
<ide>
<ide> ```bash
<del>dockerd \
<add>$ sudo dockerd \
<ide> --cluster-advertise 192.168.1.2:2376 \
<ide> --cluster-store etcd://192.168.1.2:2379 \
<ide> --cluster-store-opt kv.cacertfile=/path/to/ca.pem \
<ide> authorization plugins when you start the Docker `daemon` using the
<ide> `--authorization-plugin=PLUGIN_ID` option.
<ide>
<ide> ```bash
<del>dockerd --authorization-plugin=plugin1 --authorization-plugin=plugin2,...
<add>$ sudo dockerd --authorization-plugin=plugin1 --authorization-plugin=plugin2,...
<ide> ```
<ide>
<ide> The `PLUGIN_ID` value is either the plugin's name or a path to its specification
<ide> startup will fail with an error message.
<ide> > *before* the `--userns-remap` option is enabled. Once these files exist, the
<ide> > daemon can be (re)started and range assignment on user creation works properly.
<ide>
<del>*Example: starting with default Docker user management:*
<add>**Example: starting with default Docker user management:**
<ide>
<ide> ```bash
<del>$ dockerd --userns-remap=default
<add>$ sudo dockerd --userns-remap=default
<ide> ```
<ide>
<ide> When `default` is provided, Docker will create - or find the existing - user and group
<ide> The `--tls*` options enable use of specific certificates for individual daemons.
<ide> Example script for a separate “bootstrap” instance of the Docker daemon without network:
<ide>
<ide> ```bash
<del>$ dockerd \
<add>$ sudo dockerd \
<ide> -H unix:///var/run/docker-bootstrap.sock \
<ide> -p /var/run/docker-bootstrap.pid \
<ide> --iptables=false \ | 1 |
Text | Text | add chalker as collaborator | 428526544cdd388d0dc837ac68e56348bce0fc9a | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Oleg Elifantiev** ([@Olegas](https://github.com/Olegas)) <oleg@elifantiev.ru>
<ide> * **Domenic Denicola** ([@domenic](https://github.com/domenic)) <d@domenic.me>
<ide> * **Rich Trott** ([@Trott](https://github.com/Trott)) <rtrott@gmail.com>
<add>* **Сковорода Никита Андреевич** ([@ChALkeR](https://github.com/ChALkeR)) <chalkerx@gmail.com>
<ide>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the io.js project. | 1 |
Text | Text | use serial comma in pull request doc | 93d10d62d9d7b75aee4c12ad1eb0c48f6fe8788a | <ide><path>doc/contributing/pull-requests.md
<ide> Node.js has many channels on the
<ide> [OpenJS Foundation Slack](https://slack-invite.openjsf.org/). Interesting
<ide> channels are:
<ide> [#nodejs](https://openjs-foundation.slack.com/archives/CK9Q4MB53) for general
<del>help, questions and discussions.
<add>help, questions, and discussions.
<ide> [#nodejs-dev](https://openjs-foundation.slack.com/archives/C019Y2T6STH) for
<ide> development of Node.js core specifically.
<ide>
<ide> A good commit message should describe what changed and why.
<ide>
<ide> 5. If your commit introduces a breaking change (`semver-major`), it should
<ide> contain an explanation about the reason of the breaking change, which
<del> situation would trigger the breaking change and what is the exact change.
<add> situation would trigger the breaking change, and what is the exact change.
<ide>
<ide> Sample complete commit message:
<ide>
<ide> say so, or contact one of the other contributors in the project and seek their
<ide> input. Often such comments are the result of the reviewer having only taken a
<ide> short amount of time to review and are not ill-intended. Such issues can often
<ide> be resolved with a bit of patience. That said, reviewers should be expected to
<del>be helpful in their feedback, and feedback that is simply vague, dismissive and
<add>be helpful in their feedback, and feedback that is simply vague, dismissive, and
<ide> unhelpful is likely safe to ignore.
<ide>
<ide> ### Step 10: Landing
<ide> Focus first on the most significant aspects of the change:
<ide> When changes are necessary, _request_ them, do not _demand_ them, and do not
<ide> assume that the submitter already knows how to add a test or run a benchmark.
<ide>
<del>Specific performance optimization techniques, coding styles and conventions
<add>Specific performance optimization techniques, coding styles, and conventions
<ide> change over time. The first impression you give to a new contributor never does.
<ide>
<ide> Nits (requests for small changes that are not essential) are fine, but try to | 1 |
Javascript | Javascript | expose less internals for testutils | 3c1dcd349a8e4205322c296b1db8c313ed06b5ce | <ide><path>packages/events/__tests__/ResponderEventPlugin-test.internal.js
<ide> describe('ResponderEventPlugin', () => {
<ide> beforeEach(() => {
<ide> jest.resetModules();
<ide>
<del> const ReactDOM = require('react-dom');
<ide> const ReactDOMUnstableNativeDependencies = require('react-dom/unstable-native-dependencies');
<del> EventPluginHub =
<del> ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
<del> .EventPluginHub;
<add> EventPluginHub = require('events/EventPluginHub');
<ide> const injectComponentTree =
<ide> ReactDOMUnstableNativeDependencies.injectComponentTree;
<ide> ResponderEventPlugin =
<ide><path>packages/react-dom/src/client/ReactDOM.js
<ide> const ReactDOM: Object = {
<ide> unstable_flushControlled: DOMRenderer.flushControlled,
<ide>
<ide> __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
<del> // For TapEventPlugin which is popular in open source
<del> EventPluginHub,
<del> // Used by test-utils
<del> EventPluginRegistry,
<del> EventPropagators,
<del> ReactControlledComponent,
<del> ReactDOMComponentTree,
<del> ReactDOMEventListener,
<add> // Keep in sync with ReactDOMUnstableNativeDependencies.js
<add> // and ReactTestUtils.js. This is an array for better minification.
<add> Events: [
<add> ReactDOMComponentTree.getInstanceFromNode,
<add> ReactDOMComponentTree.getNodeFromInstance,
<add> ReactDOMComponentTree.getFiberCurrentPropsFromNode,
<add> EventPluginRegistry.eventNameDispatchConfigs,
<add> EventPropagators.accumulateTwoPhaseDispatches,
<add> EventPropagators.accumulateDirectDispatches,
<add> ReactControlledComponent.enqueueStateRestore,
<add> ReactControlledComponent.restoreStateIfNeeded,
<add> ReactDOMEventListener.dispatchEvent,
<add> EventPluginHub.runEventsInBatch,
<add> ],
<ide> },
<ide> };
<ide>
<ide><path>packages/react-dom/src/client/ReactDOMFB.js
<ide> * @flow
<ide> */
<ide>
<add>import * as EventPluginHub from 'events/EventPluginHub';
<ide> import * as ReactFiberTreeReflection from 'react-reconciler/reflection';
<ide> import * as ReactInstanceMap from 'shared/ReactInstanceMap';
<ide> import {addUserTimingListener} from 'shared/ReactFeatureFlags';
<ide> Object.assign(
<ide> ReactDOMComponentTree,
<ide> ReactInstanceMap,
<ide> // Used by www msite:
<add> EventPluginHub,
<ide> TapEventPlugin,
<ide> // Perf experiment
<ide> addUserTimingListener,
<ide><path>packages/react-dom/src/test-utils/ReactTestUtils.js
<ide> import {ELEMENT_NODE} from '../shared/HTMLNodeType';
<ide> import * as DOMTopLevelEventTypes from '../events/DOMTopLevelEventTypes';
<ide>
<ide> const {findDOMNode} = ReactDOM;
<del>const {
<del> EventPluginHub,
<del> EventPluginRegistry,
<del> EventPropagators,
<del> ReactControlledComponent,
<del> ReactDOMComponentTree,
<del> ReactDOMEventListener,
<del>} = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
<add>// Keep in sync with ReactDOMUnstableNativeDependencies.js
<add>// and ReactDOM.js:
<add>const [
<add> getInstanceFromNode,
<add> /* eslint-disable no-unused-vars */
<add> getNodeFromInstance,
<add> getFiberCurrentPropsFromNode,
<add> /* eslint-enable no-unused-vars */
<add> eventNameDispatchConfigs,
<add> accumulateTwoPhaseDispatches,
<add> accumulateDirectDispatches,
<add> enqueueStateRestore,
<add> restoreStateIfNeeded,
<add> dispatchEvent,
<add> runEventsInBatch,
<add>] = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events;
<ide>
<ide> function Event(suffix) {}
<ide>
<ide> let hasWarnedAboutDeprecatedMockComponent = false;
<ide> */
<ide> function simulateNativeEventOnNode(topLevelType, node, fakeNativeEvent) {
<ide> fakeNativeEvent.target = node;
<del> ReactDOMEventListener.dispatchEvent(topLevelType, fakeNativeEvent);
<add> dispatchEvent(topLevelType, fakeNativeEvent);
<ide> }
<ide>
<ide> /**
<ide> function makeSimulator(eventType) {
<ide> 'a component instance. Pass the DOM node you wish to simulate the event on instead.',
<ide> );
<ide>
<del> const dispatchConfig =
<del> EventPluginRegistry.eventNameDispatchConfigs[eventType];
<add> const dispatchConfig = eventNameDispatchConfigs[eventType];
<ide>
<ide> const fakeNativeEvent = new Event();
<ide> fakeNativeEvent.target = domNode;
<ide> fakeNativeEvent.type = eventType.toLowerCase();
<ide>
<ide> // We don't use SyntheticEvent.getPooled in order to not have to worry about
<ide> // properly destroying any properties assigned from `eventData` upon release
<del> const targetInst = ReactDOMComponentTree.getInstanceFromNode(domNode);
<add> const targetInst = getInstanceFromNode(domNode);
<ide> const event = new SyntheticEvent(
<ide> dispatchConfig,
<ide> targetInst,
<ide> function makeSimulator(eventType) {
<ide> Object.assign(event, eventData);
<ide>
<ide> if (dispatchConfig.phasedRegistrationNames) {
<del> EventPropagators.accumulateTwoPhaseDispatches(event);
<add> accumulateTwoPhaseDispatches(event);
<ide> } else {
<del> EventPropagators.accumulateDirectDispatches(event);
<add> accumulateDirectDispatches(event);
<ide> }
<ide>
<ide> ReactDOM.unstable_batchedUpdates(function() {
<ide> // Normally extractEvent enqueues a state restore, but we'll just always
<ide> // do that since we we're by-passing it here.
<del> ReactControlledComponent.enqueueStateRestore(domNode);
<del> EventPluginHub.runEventsInBatch(event, true);
<add> enqueueStateRestore(domNode);
<add> runEventsInBatch(event, true);
<ide> });
<del> ReactControlledComponent.restoreStateIfNeeded();
<add> restoreStateIfNeeded();
<ide> };
<ide> }
<ide>
<ide> function buildSimulators() {
<ide> ReactTestUtils.Simulate = {};
<ide>
<ide> let eventType;
<del> for (eventType in EventPluginRegistry.eventNameDispatchConfigs) {
<add> for (eventType in eventNameDispatchConfigs) {
<ide> /**
<ide> * @param {!Element|ReactDOMComponent} domComponentOrNode
<ide> * @param {?object} eventData Fake event data to use in SyntheticEvent.
<ide> function buildSimulators() {
<ide> }
<ide> }
<ide>
<del>// Rebuild ReactTestUtils.Simulate whenever event plugins are injected
<del>const oldInjectEventPluginOrder =
<del> EventPluginHub.injection.injectEventPluginOrder;
<del>EventPluginHub.injection.injectEventPluginOrder = function() {
<del> oldInjectEventPluginOrder.apply(this, arguments);
<del> buildSimulators();
<del>};
<del>const oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName;
<del>EventPluginHub.injection.injectEventPluginsByName = function() {
<del> oldInjectEventPlugins.apply(this, arguments);
<del> buildSimulators();
<del>};
<del>
<ide> buildSimulators();
<ide>
<ide> /**
<ide><path>packages/react-dom/src/unstable-native-dependencies/ReactDOMUnstableNativeDependencies.js
<ide> export function injectComponentTree(ComponentTree) {
<ide> export {ResponderEventPlugin, ResponderTouchHistoryStore};
<ide>
<ide> // Inject react-dom's ComponentTree into this module.
<del>const {
<del> ReactDOMComponentTree,
<del>} = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
<add>// Keep in sync with ReactDOM.js and ReactTestUtils.js:
<add>const [
<add> getInstanceFromNode,
<add> getNodeFromInstance,
<add> getFiberCurrentPropsFromNode,
<add>] = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events;
<ide> EventPluginUtils.setComponentTree(
<del> ReactDOMComponentTree.getFiberCurrentPropsFromNode,
<del> ReactDOMComponentTree.getInstanceFromNode,
<del> ReactDOMComponentTree.getNodeFromInstance,
<add> getFiberCurrentPropsFromNode,
<add> getInstanceFromNode,
<add> getNodeFromInstance,
<ide> ); | 5 |
PHP | PHP | apply fixes from styleci | 9e5226ecc28f960cba1bd38b6d1d82a52e072dc3 | <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphToMany.php
<ide>
<ide> use Illuminate\Database\Eloquent\Builder;
<ide> use Illuminate\Database\Eloquent\Model;
<del>use Illuminate\Database\Eloquent\Relations\MorphPivot;
<ide> use Illuminate\Support\Arr;
<ide>
<ide> class MorphToMany extends BelongsToMany | 1 |
PHP | PHP | add test for savemany + validate=false | 3b867a048ec8887da13365ed8d0c7882a42700fe | <ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php
<ide> public function testSaveMany() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Test SaveMany with validate=false.
<add> *
<add> * @return void
<add> */
<add> public function testSaveManyValidateFalse() {
<add> $this->loadFixtures('Post');
<add> $TestModel = new Post();
<add> $TestModel->deleteAll(true);
<add> $data = array(
<add> array('id' => 1, 'author_id' => 1, 'title' => 'hi'),
<add> array('id' => 2, 'author_id' => 1, 'title' => 'bye')
<add> );
<add> $result = $TestModel->saveAll($data, array('validate' => false));
<add> $this->assertTrue($result);
<add> }
<add>
<ide> /**
<ide> * Test SaveAssociated with Habtm relations
<ide> * | 1 |
Ruby | Ruby | freeze columns only once per result | da400fbb0ba6a130237d17cdd58c860be02294ad | <ide><path>activerecord/lib/active_record/result.rb
<ide> def initialize_copy(other)
<ide>
<ide> private
<ide> def hash_rows
<del> @hash_rows ||= @rows.map { |row|
<del> # We freeze the strings to prevent them getting duped when
<del> # used as keys in ActiveRecord::Model's @attributes hash
<del> columns = @columns.map { |c| c.freeze }
<del> Hash[columns.zip(row)]
<del> }
<add> @hash_rows ||=
<add> begin
<add> # We freeze the strings to prevent them getting duped when
<add> # used as keys in ActiveRecord::Model's @attributes hash
<add> columns = @columns.map { |c| c.dup.freeze }
<add> @rows.map { |row|
<add> Hash[columns.zip(row)]
<add> }
<add> end
<ide> end
<ide> end
<ide> end | 1 |
Go | Go | fix wrong template value passed to lxc conf | 7b4f73ee6c2a06532124e77ec5f4972f078a7d5c | <ide><path>daemon/execdriver/lxc/lxc_template.go
<ide> lxc.cgroup.memory.soft_limit_in_bytes = {{.Resources.Memory}}
<ide> lxc.cgroup.memory.memsw.limit_in_bytes = {{$memSwap}}
<ide> {{end}}
<ide> {{end}}
<del>{{if .Resources.KernelMemory}}
<del>lxc.cgroup.memory.kmem.limit_in_bytes = {{.Resources.Memory}}
<add>{{if gt .Resources.KernelMemory 0}}
<add>lxc.cgroup.memory.kmem.limit_in_bytes = {{.Resources.KernelMemory}}
<ide> {{end}}
<ide> {{if .Resources.CPUShares}}
<ide> lxc.cgroup.cpu.shares = {{.Resources.CPUShares}} | 1 |
Javascript | Javascript | make safe primordials safe to iterate | 0a5969c62a75ace6edafd3f7226e96c0d8ba24a6 | <ide><path>lib/internal/per_context/primordials.js
<ide> function copyPrototype(src, dest, prefix) {
<ide> }
<ide> }
<ide>
<add>const createSafeIterator = (factory, next) => {
<add> class SafeIterator {
<add> constructor(iterable) {
<add> this._iterator = factory(iterable);
<add> }
<add> next() {
<add> return next(this._iterator);
<add> }
<add> [Symbol.iterator]() {
<add> return this;
<add> }
<add> }
<add> Object.setPrototypeOf(SafeIterator.prototype, null);
<add> Object.freeze(SafeIterator.prototype);
<add> Object.freeze(SafeIterator);
<add> return SafeIterator;
<add>};
<add>
<ide> function makeSafe(unsafe, safe) {
<del> copyProps(unsafe.prototype, safe.prototype);
<add> if (Symbol.iterator in unsafe.prototype) {
<add> const dummy = new unsafe();
<add> let next; // We can reuse the same `next` method.
<add>
<add> for (const key of Reflect.ownKeys(unsafe.prototype)) {
<add> if (!Reflect.getOwnPropertyDescriptor(safe.prototype, key)) {
<add> const desc = Reflect.getOwnPropertyDescriptor(unsafe.prototype, key);
<add> if (
<add> typeof desc.value === 'function' &&
<add> desc.value.length === 0 &&
<add> Symbol.iterator in (desc.value.call(dummy) ?? {})
<add> ) {
<add> const createIterator = uncurryThis(desc.value);
<add> next ??= uncurryThis(createIterator(dummy).next);
<add> const SafeIterator = createSafeIterator(createIterator, next);
<add> desc.value = function() {
<add> return new SafeIterator(this);
<add> };
<add> }
<add> Reflect.defineProperty(safe.prototype, key, desc);
<add> }
<add> }
<add> } else {
<add> copyProps(unsafe.prototype, safe.prototype);
<add> }
<ide> copyProps(unsafe, safe);
<add>
<ide> Object.setPrototypeOf(safe.prototype, null);
<ide> Object.freeze(safe.prototype);
<ide> Object.freeze(safe);
<ide><path>lib/internal/source_map/source_map_cache.js
<ide> const {
<ide> ObjectKeys,
<ide> ObjectGetOwnPropertyDescriptor,
<ide> ObjectPrototypeHasOwnProperty,
<del> Map,
<del> MapPrototypeEntries,
<ide> RegExpPrototypeTest,
<ide> SafeMap,
<ide> StringPrototypeMatch,
<ide> StringPrototypeSplit,
<del> uncurryThis,
<ide> } = primordials;
<ide>
<del>const MapIteratorNext = uncurryThis(MapPrototypeEntries(new Map()).next);
<del>
<ide> function ObjectGetValueSafe(obj, key) {
<ide> const desc = ObjectGetOwnPropertyDescriptor(obj, key);
<ide> return ObjectPrototypeHasOwnProperty(desc, 'value') ? desc.value : undefined;
<ide> function rekeySourceMap(cjsModuleInstance, newInstance) {
<ide> function sourceMapCacheToObject() {
<ide> const obj = ObjectCreate(null);
<ide>
<del> const it = MapPrototypeEntries(esmSourceMapCache);
<del> let entry;
<del> while (!(entry = MapIteratorNext(it)).done) {
<del> const k = entry.value[0];
<del> const v = entry.value[1];
<add> for (const { 0: k, 1: v } of esmSourceMapCache) {
<ide> obj[k] = v;
<ide> }
<ide>
<ide><path>lib/internal/worker/io.js
<ide> 'use strict';
<ide>
<ide> const {
<add> ArrayPrototypeForEach,
<ide> ArrayPrototypeMap,
<ide> ArrayPrototypePush,
<ide> FunctionPrototypeBind,
<ide> class WritableWorkerStdio extends Writable {
<ide> [kStdioWantsMoreDataCallback]() {
<ide> const cbs = this[kWritableCallbacks];
<ide> this[kWritableCallbacks] = [];
<del> for (const cb of cbs)
<del> cb();
<add> ArrayPrototypeForEach(cbs, (cb) => cb());
<ide> if ((this[kPort][kWaitingStreams] -= cbs.length) === 0)
<ide> this[kPort].unref();
<ide> }
<ide><path>test/parallel/test-worker-terminate-source-map.js
<ide> const { callCount } = workerData;
<ide> function increaseCallCount() { callCount[0]++; }
<ide>
<ide> // Increase the call count when a forbidden method is called.
<del>Object.getPrototypeOf((new Map()).entries()).next = increaseCallCount;
<del>Map.prototype.entries = increaseCallCount;
<del>Object.keys = increaseCallCount;
<del>Object.create = increaseCallCount;
<del>Object.hasOwnProperty = increaseCallCount;
<ide> for (const property of ['_cache', 'lineLengths', 'url']) {
<ide> Object.defineProperty(Object.prototype, property, {
<ide> get: increaseCallCount,
<ide> set: increaseCallCount
<ide> });
<ide> }
<add>Object.getPrototypeOf([][Symbol.iterator]()).next = increaseCallCount;
<add>Object.getPrototypeOf((new Map()).entries()).next = increaseCallCount;
<add>Array.prototype[Symbol.iterator] = increaseCallCount;
<add>Map.prototype[Symbol.iterator] = increaseCallCount;
<add>Map.prototype.entries = increaseCallCount;
<add>Object.keys = increaseCallCount;
<add>Object.create = increaseCallCount;
<add>Object.hasOwnProperty = increaseCallCount;
<ide>
<ide> parentPort.postMessage('done'); | 4 |
Go | Go | improve last log output | 2a20e852032339b4c91a01748119701c7ada234d | <ide><path>buildfile.go
<ide> func (b *buildFile) Build(context io.Reader) (string, error) {
<ide> defer func() {
<ide> // If we have an error and a container, the display the logs
<ide> if b.lastContainer != nil {
<del> fmt.Fprintf(b.out, "Logs from last container (%s):\n", b.lastContainer.ShortID())
<add> fmt.Fprintf(b.out, "******** Logs from last container (%s) *******\n", b.lastContainer.ShortID())
<ide>
<ide> cLog, err := b.lastContainer.ReadLog("stdout")
<ide> if err != nil {
<ide> func (b *buildFile) Build(context io.Reader) (string, error) {
<ide> if _, err := io.Copy(b.out, cLog); err != nil {
<ide> utils.Debugf("Error streaming logs (stderr): %s", err)
<ide> }
<del> fmt.Fprintf(b.out, "End of logs for %s\n", b.lastContainer.ShortID())
<add> fmt.Fprintf(b.out, "************* End of logs for %s *************\n", b.lastContainer.ShortID())
<ide> }
<ide> }()
<ide> | 1 |
Python | Python | use exceptions intead of returning tuple | 43e9a462b66c768e8e88905f42affe34f17c392b | <ide><path>airflow/hooks/hive_hooks.py
<ide> def __init__(
<ide> self.use_beeline = conn.extra_dejson.get('use_beeline', False)
<ide> self.conn = conn
<ide>
<del> def run_cli(self, hql, schema=None, test=False):
<add> def run_cli(self, hql, schema=None, verbose=True):
<ide> """
<ide> Run an hql statement using the hive cli
<ide>
<ide> def run_cli(self, hql, schema=None, test=False):
<ide> if self.hive_cli_params:
<ide> hive_params_list = self.hive_cli_params.split()
<ide> hive_cmd.extend(hive_params_list)
<del> if not test:
<add> if verbose:
<ide> logging.info(" ".join(hive_cmd))
<ide> sp = subprocess.Popen(
<ide> hive_cmd,
<ide> stdout=subprocess.PIPE,
<ide> stderr=subprocess.STDOUT,
<ide> cwd=tmp_dir)
<del> all_err = ''
<ide> self.sp = sp
<ide> stdout = ''
<ide> for line in iter(sp.stdout.readline, ''):
<ide> stdout += line
<del> if not test:
<add> if verbose:
<ide> logging.info(line.strip())
<ide> sp.wait()
<ide>
<ide> if sp.returncode:
<del> if not test:
<del> raise AirflowException(all_err)
<del> else:
<del> return (False, stdout)
<add> raise AirflowException(stdout)
<add>
<add> return stdout
<ide>
<del> if not test:
<del> return stdout
<del> else:
<del> return (True, stdout)
<ide>
<ide> def test_hql(self, hql):
<ide> """
<ide> def test_hql(self, hql):
<ide> query = query.lower().strip()
<ide> if query.startswith('create table'):
<ide> create.append(query)
<del> elif query.startswith(('set', 'add jar', 'temporary')):
<add> elif query.startswith(('set ', 'add jar ', 'temporary ')):
<ide> other.append(query)
<ide> elif query.startswith('insert'):
<ide> insert.append(query)
<ide> def test_hql(self, hql):
<ide> query = other + '; explain ' + query
<ide> else:
<ide> query = 'explain ' + query
<del> success, output = self.run_cli(query, test=True)
<del> if success:
<del> logging.info("SUCCESS")
<del> else:
<del> failure_message = output.split('\n')[-2]
<del> logging.info(failure_message)
<del> line_number = re.search('(\d+):(\d+)', failure_message).group(1)
<del> if line_number.isdigit():
<del> l = int(line_number)
<del> begin = max(l-2, 0)
<del> end = min(l+3, len(query.split('\n')))
<del> context = '\n'.join(query.split('\n')[begin:end])
<del> logging.info("Context :\n {0}".format(context))
<add> try:
<add> self.run_cli(query, verbose=False)
<add> except AirflowException as e:
<add> failure_message = e.args[0].split('\n')[-2]
<add> logging.info(failure_message)
<add> line_number = re.search('(\d+):(\d+)', failure_message).group(1)
<add> if line_number.isdigit():
<add> l = int(line_number)
<add> begin = max(l-2, 0)
<add> end = min(l+3, len(query.split('\n')))
<add> context = '\n'.join(query.split('\n')[begin:end])
<add> logging.info("Context :\n {0}".format(context))
<add> else:
<add> logging.info("SUCCESS")
<ide>
<ide>
<ide> def load_file( | 1 |
PHP | PHP | make env variables for aws | 7cf27b2146ff3b8fb7e643fd83e932bb61801fbd | <ide><path>config/filesystems.php
<ide>
<ide> 's3' => [
<ide> 'driver' => 's3',
<del> 'key' => 'your-key',
<del> 'secret' => 'your-secret',
<del> 'region' => 'your-region',
<del> 'bucket' => 'your-bucket',
<add> 'key' => env('AWS_KEY'),
<add> 'secret' => env('AWS_SECRET'),
<add> 'region' => env('AWS_REGION'),
<add> 'bucket' => env('AWS_BUCKET'),
<ide> ],
<ide>
<ide> ], | 1 |
Javascript | Javascript | mitigate regex exceeding 80 chars | ad664eae7d7a222ae49f97cd5344f3b6be2b4d7b | <ide><path>test/addons-napi/test_properties/test.js
<ide> 'use strict';
<ide> const common = require('../../common');
<ide> const assert = require('assert');
<del>const readonlyErrorRE = /^TypeError: Cannot assign to read only property '.*' of object '#<Object>'$/;
<add>const readonlyErrorRE =
<add> /^TypeError: Cannot assign to read only property '.*' of object '#<Object>'$/;
<ide>
<ide> // Testing api calls for defining properties
<ide> const test_object = require(`./build/${common.buildType}/test_properties`);
<ide><path>test/parallel/test-process-versions.js
<ide> assert(commonTemplate.test(process.versions.node));
<ide> assert(commonTemplate.test(process.versions.uv));
<ide> assert(commonTemplate.test(process.versions.zlib));
<ide>
<del>assert(/^\d+\.\d+\.\d+(?:\.\d+)?(?: \(candidate\))?$/.test(process.versions.v8));
<add>assert(/^\d+\.\d+\.\d+(?:\.\d+)?(?: \(candidate\))?$/
<add> .test(process.versions.v8));
<ide> assert(/^\d+$/.test(process.versions.modules));
<ide><path>test/parallel/test-repl.js
<ide> function error_test() {
<ide> expect: prompt_unix },
<ide> // But passing the same string to eval() should throw
<ide> { client: client_unix, send: 'eval("function test_func() {")',
<del> expect: /\bSyntaxError: Unexpected end of input/ },
<add> expect: /^SyntaxError: Unexpected end of input/ },
<ide> // Can handle multiline template literals
<ide> { client: client_unix, send: '`io.js',
<ide> expect: prompt_multiline },
<ide> function error_test() {
<ide> // invalid input to JSON.parse error is special case of syntax error,
<ide> // should throw
<ide> { client: client_unix, send: 'JSON.parse(\'{invalid: \\\'json\\\'}\');',
<del> expect: /\bSyntaxError: Unexpected token i/ },
<add> expect: /^SyntaxError: Unexpected token i/ },
<ide> // end of input to JSON.parse error is special case of syntax error,
<ide> // should throw
<ide> { client: client_unix, send: 'JSON.parse(\'066\');',
<del> expect: /\bSyntaxError: Unexpected number/ },
<add> expect: /^SyntaxError: Unexpected number/ },
<ide> // should throw
<ide> { client: client_unix, send: 'JSON.parse(\'{\');',
<del> expect: /\bSyntaxError: Unexpected end of JSON input/ },
<add> expect: /^SyntaxError: Unexpected end of JSON input/ },
<ide> // invalid RegExps are a special case of syntax error,
<ide> // should throw
<ide> { client: client_unix, send: '/(/;',
<del> expect: /\bSyntaxError: Invalid regular expression:/ },
<add> expect: /^SyntaxError: Invalid regular expression:/ },
<ide> // invalid RegExp modifiers are a special case of syntax error,
<ide> // should throw (GH-4012)
<ide> { client: client_unix, send: 'new RegExp("foo", "wrong modifier");',
<del> expect: /\bSyntaxError: Invalid flags supplied to RegExp constructor/ },
<add> expect: /^SyntaxError: Invalid flags supplied to RegExp constructor/ },
<ide> // strict mode syntax errors should be caught (GH-5178)
<ide> { client: client_unix,
<ide> send: '(function() { "use strict"; return 0755; })()',
<ide> expect: /\bSyntaxError: Octal literals are not allowed in strict mode/ },
<ide> {
<ide> client: client_unix,
<ide> send: '(function(a, a, b) { "use strict"; return a + b + c; })()',
<del> expect: /\bSyntaxError: Duplicate parameter name not allowed in this context/
<add> expect:
<add> /\bSyntaxError: Duplicate parameter name not allowed in this context/
<ide> },
<ide> {
<ide> client: client_unix,
<ide> function error_test() {
<ide> {
<ide> client: client_unix,
<ide> send: '(function() { "use strict"; var x; delete x; })()',
<del> expect: /\bSyntaxError: Delete of an unqualified identifier in strict mode/
<add> expect:
<add> /\bSyntaxError: Delete of an unqualified identifier in strict mode/
<ide> },
<ide> { client: client_unix,
<ide> send: '(function() { "use strict"; eval = 17; })()',
<ide> expect: /\bSyntaxError: Unexpected eval or arguments in strict mode/ },
<ide> {
<ide> client: client_unix,
<ide> send: '(function() { "use strict"; if (true) function f() { } })()',
<del> expect: /\bSyntaxError: In strict mode code, functions can only be declared at top level or inside a block\./
<add> expect:
<add> /\bSyntaxError: In strict mode code, functions can only be declared at top level or inside a block\./
<ide> },
<ide> // Named functions can be used:
<ide> { client: client_unix, send: 'function blah() { return 1; }',
<ide><path>test/parallel/test-v8-serdes.js
<ide> const objects = [
<ide> circular
<ide> ];
<ide>
<add>const serializerTypeError =
<add> /^TypeError: Class constructor Serializer cannot be invoked without 'new'$/;
<add>const deserializerTypeError =
<add> /^TypeError: Class constructor Deserializer cannot be invoked without 'new'$/;
<add>
<ide> {
<ide> const ser = new v8.DefaultSerializer();
<ide> ser.writeHeader();
<ide> const objects = [
<ide> }
<ide>
<ide> {
<del> assert.throws(
<del> () => { v8.Serializer(); },
<del> /^TypeError: Class constructor Serializer cannot be invoked without 'new'$/
<del> );
<del>
<del> assert.throws(
<del> () => { v8.Deserializer(); },
<del> /^TypeError: Class constructor Deserializer cannot be invoked without 'new'$/
<del> );
<add> assert.throws(v8.Serializer, serializerTypeError);
<add> assert.throws(v8.Deserializer, deserializerTypeError);
<ide> }
<ide><path>test/parallel/test-whatwg-url-properties.js
<ide> assert.strictEqual(url.searchParams, oldParams); // [SameObject]
<ide> // searchParams is readonly. Under strict mode setting a
<ide> // non-writable property should throw.
<ide> // Note: this error message is subject to change in V8 updates
<del>assert.throws(() => url.origin = 'http://foo.bar.com:22',
<del> /TypeError: Cannot set property origin of \[object URL\] which has only a getter$/);
<add>assert.throws(
<add> () => url.origin = 'http://foo.bar.com:22',
<add> /^TypeError: Cannot set property origin of \[object URL\] which has only a getter$/
<add>);
<ide> assert.strictEqual(url.origin, 'http://foo.bar.com:21');
<ide> assert.strictEqual(url.toString(),
<ide> 'http://user:pass@foo.bar.com:21/aaa/zzz?l=25#test');
<ide> assert.strictEqual(url.hash, '#abcd');
<ide> // searchParams is readonly. Under strict mode setting a
<ide> // non-writable property should throw.
<ide> // Note: this error message is subject to change in V8 updates
<del>assert.throws(() => url.searchParams = '?k=88',
<del> /^TypeError: Cannot set property searchParams of \[object URL\] which has only a getter$/);
<add>assert.throws(
<add> () => url.searchParams = '?k=88',
<add> /^TypeError: Cannot set property searchParams of \[object URL\] which has only a getter$/
<add>);
<ide> assert.strictEqual(url.searchParams, oldParams);
<ide> assert.strictEqual(url.toString(),
<ide> 'https://user2:pass2@foo.bar.org:23/aaa/bbb?k=99#abcd');
<ide><path>test/parallel/test-zlib-not-string-or-buffer.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide> const zlib = require('zlib');
<ide>
<del>const expected = /^TypeError: "buffer" argument must be a string, Buffer, TypedArray, or DataView$/;
<add>const expected =
<add> /^TypeError: "buffer" argument must be a string, Buffer, TypedArray, or DataView$/;
<ide>
<ide> assert.throws(() => { zlib.deflateSync(undefined); }, expected);
<ide> assert.throws(() => { zlib.deflateSync(null); }, expected); | 6 |
Javascript | Javascript | remove unused dependency on reactmount | 74cfc9c2741a0e3a4fe42d54d34018b6e272c507 | <ide><path>src/core/ReactComponent.js
<ide> var ReactCurrentOwner = require('ReactCurrentOwner');
<ide> var ReactDOMIDOperations = require('ReactDOMIDOperations');
<ide> var ReactID = require('ReactID');
<del>var ReactMount = require('ReactMount');
<ide> var ReactOwner = require('ReactOwner');
<ide> var ReactReconcileTransaction = require('ReactReconcileTransaction');
<ide> var ReactUpdates = require('ReactUpdates');
<ide> var ReactComponent = {
<ide> container && container.nodeType === 1,
<ide> 'mountComponentIntoNode(...): Target container is not a DOM element.'
<ide> );
<del> var renderStart = Date.now();
<ide> var markup = this.mountComponent(rootID, transaction);
<del> ReactMount.totalInstantiationTime += (Date.now() - renderStart);
<ide>
<ide> if (shouldReuseMarkup) {
<ide> return;
<ide> }
<ide>
<del> var injectionStart = Date.now();
<ide> // Asynchronously inject markup by ensuring that the container is not in
<ide> // the document when settings its `innerHTML`.
<ide> var parent = container.parentNode;
<ide> var ReactComponent = {
<ide> } else {
<ide> container.innerHTML = markup;
<ide> }
<del> ReactMount.totalInjectionTime += (Date.now() - injectionStart);
<ide> },
<ide>
<ide> /** | 1 |
Javascript | Javascript | replace var with let/const | 03bb272c5adcfcc5257faf17ff49282877bbf5cb | <ide><path>lib/events.js
<ide> const {
<ide> ReflectOwnKeys,
<ide> } = primordials;
<ide>
<del>var spliceOne;
<add>let spliceOne;
<ide>
<ide> const {
<ide> kEnhanceStackBeforeInspector,
<ide> EventEmitter.prototype._maxListeners = undefined;
<ide>
<ide> // By default EventEmitters will print a warning if more than 10 listeners are
<ide> // added to it. This is a useful default which helps finding memory leaks.
<del>var defaultMaxListeners = 10;
<add>let defaultMaxListeners = 10;
<ide>
<ide> function checkListener(listener) {
<ide> if (typeof listener !== 'function') {
<ide> EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
<ide> // Returns the length and line number of the first sequence of `a` that fully
<ide> // appears in `b` with a length of at least 4.
<ide> function identicalSequenceRange(a, b) {
<del> for (var i = 0; i < a.length - 3; i++) {
<add> for (let i = 0; i < a.length - 3; i++) {
<ide> // Find the first entry of b that matches the current entry of a.
<ide> const pos = b.indexOf(a[i]);
<ide> if (pos !== -1) {
<ide> EventEmitter.prototype.emit = function emit(type, ...args) {
<ide> } else {
<ide> const len = handler.length;
<ide> const listeners = arrayClone(handler, len);
<del> for (var i = 0; i < len; ++i)
<add> for (let i = 0; i < len; ++i)
<ide> ReflectApply(listeners[i], this, args);
<ide> }
<ide>
<ide> return true;
<ide> };
<ide>
<ide> function _addListener(target, type, listener, prepend) {
<del> var m;
<del> var events;
<del> var existing;
<add> let m;
<add> let events;
<add> let existing;
<ide>
<ide> checkListener(listener);
<ide>
<ide> EventEmitter.prototype.removeListener =
<ide> } else if (typeof list !== 'function') {
<ide> let position = -1;
<ide>
<del> for (var i = list.length - 1; i >= 0; i--) {
<add> for (let i = list.length - 1; i >= 0; i--) {
<ide> if (list[i] === listener || list[i].listener === listener) {
<ide> originalListener = list[i].listener;
<ide> position = i;
<ide> EventEmitter.prototype.removeAllListeners =
<ide> this.removeListener(type, listeners);
<ide> } else if (listeners !== undefined) {
<ide> // LIFO order
<del> for (var i = listeners.length - 1; i >= 0; i--) {
<add> for (let i = listeners.length - 1; i >= 0; i--) {
<ide> this.removeListener(type, listeners[i]);
<ide> }
<ide> }
<ide> EventEmitter.prototype.eventNames = function eventNames() {
<ide>
<ide> function arrayClone(arr, n) {
<ide> const copy = new Array(n);
<del> for (var i = 0; i < n; ++i)
<add> for (let i = 0; i < n; ++i)
<ide> copy[i] = arr[i];
<ide> return copy;
<ide> }
<ide>
<ide> function unwrapListeners(arr) {
<ide> const ret = new Array(arr.length);
<del> for (var i = 0; i < ret.length; ++i) {
<add> for (let i = 0; i < ret.length; ++i) {
<ide> ret[i] = arr[i].listener || arr[i];
<ide> }
<ide> return ret;
<ide><path>lib/internal/process/task_queues.js
<ide> function nextTick(callback) {
<ide> if (process._exiting)
<ide> return;
<ide>
<del> var args;
<add> let args;
<ide> switch (arguments.length) {
<ide> case 1: break;
<ide> case 2: args = [arguments[1]]; break;
<ide> case 3: args = [arguments[1], arguments[2]]; break;
<ide> case 4: args = [arguments[1], arguments[2], arguments[3]]; break;
<ide> default:
<ide> args = new Array(arguments.length - 1);
<del> for (var i = 1; i < arguments.length; i++)
<add> for (let i = 1; i < arguments.length; i++)
<ide> args[i - 1] = arguments[i];
<ide> }
<ide> | 2 |
Go | Go | fix external volume error to pass validation | 72366869875f986fb0b22bcd66ce0fa5ed6288f9 | <ide><path>cli/compose/loader/loader.go
<ide> import (
<ide> units "github.com/docker/go-units"
<ide> shellwords "github.com/mattn/go-shellwords"
<ide> "github.com/mitchellh/mapstructure"
<add> "github.com/pkg/errors"
<ide> yaml "gopkg.in/yaml.v2"
<ide> )
<ide>
<ide> func LoadNetworks(source map[string]interface{}) (map[string]types.NetworkConfig
<ide> return networks, nil
<ide> }
<ide>
<add>func externalVolumeError(volume, key string) error {
<add> return errors.Errorf(
<add> "conflicting parameters \"external\" and %q specified for volume %q",
<add> key, volume)
<add>}
<add>
<ide> // LoadVolumes produces a VolumeConfig map from a compose file Dict
<ide> // the source Dict is not validated if directly used. Use Load() to enable validation
<ide> func LoadVolumes(source map[string]interface{}) (map[string]types.VolumeConfig, error) {
<ide> func LoadVolumes(source map[string]interface{}) (map[string]types.VolumeConfig,
<ide> }
<ide> for name, volume := range volumes {
<ide> if volume.External.External {
<del> template := "conflicting parameters \"external\" and %q specified for volume %q"
<ide> if volume.Driver != "" {
<del> return nil, fmt.Errorf(template, "driver", name)
<add> return nil, externalVolumeError(name, "driver")
<ide> }
<ide> if len(volume.DriverOpts) > 0 {
<del> return nil, fmt.Errorf(template, "driver_opts", name)
<add> return nil, externalVolumeError(name, "driver_opts")
<ide> }
<ide> if len(volume.Labels) > 0 {
<del> return nil, fmt.Errorf(template, "labels", name)
<add> return nil, externalVolumeError(name, "labels")
<ide> }
<ide> if volume.External.Name == "" {
<ide> volume.External.Name = name | 1 |
Python | Python | force use_cache to be false in pytorch | 6a5472a8e1d75e95e8fb4d0bdf8ddf9b237bac03 | <ide><path>src/transformers/models/bart/modeling_bart.py
<ide> def forward(
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<ide> if labels is not None:
<add> if use_cache:
<add> logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
<add> use_cache = False
<ide> if decoder_input_ids is None and decoder_inputs_embeds is None:
<ide> decoder_input_ids = shift_tokens_right(
<ide> labels, self.config.pad_token_id, self.config.decoder_start_token_id
<ide><path>src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py
<ide> def forward(
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<ide> if labels is not None:
<add> if use_cache:
<add> logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
<add> use_cache = False
<ide> if decoder_input_ids is None and decoder_inputs_embeds is None:
<ide> decoder_input_ids = shift_tokens_right(
<ide> labels, self.config.pad_token_id, self.config.decoder_start_token_id
<ide><path>src/transformers/models/blenderbot/modeling_blenderbot.py
<ide> def forward(
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<ide> if labels is not None:
<add> if use_cache:
<add> logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
<add> use_cache = False
<ide> if decoder_input_ids is None:
<ide> decoder_input_ids = shift_tokens_right(
<ide> labels, self.config.pad_token_id, self.config.decoder_start_token_id
<ide><path>src/transformers/models/blenderbot_small/modeling_blenderbot_small.py
<ide> def forward(
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<ide> if labels is not None:
<add> if use_cache:
<add> logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
<add> use_cache = False
<ide> if decoder_input_ids is None:
<ide> decoder_input_ids = shift_tokens_right(
<ide> labels, self.config.pad_token_id, self.config.decoder_start_token_id
<ide><path>src/transformers/models/led/modeling_led.py
<ide> def forward(
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<ide> if labels is not None:
<add> if use_cache:
<add> logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
<add> use_cache = False
<ide> if decoder_input_ids is None:
<ide> decoder_input_ids = shift_tokens_right(
<ide> labels, self.config.pad_token_id, self.config.decoder_start_token_id
<ide><path>src/transformers/models/marian/modeling_marian.py
<ide> def forward(
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<ide> if labels is not None:
<add> if use_cache:
<add> logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
<add> use_cache = False
<ide> if decoder_input_ids is None:
<ide> decoder_input_ids = shift_tokens_right(
<ide> labels, self.config.pad_token_id, self.config.decoder_start_token_id
<ide><path>src/transformers/models/mbart/modeling_mbart.py
<ide> def forward(
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<ide> if labels is not None:
<add> if use_cache:
<add> logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
<add> use_cache = False
<ide> if decoder_input_ids is None:
<ide> decoder_input_ids = shift_tokens_right(labels, self.config.pad_token_id)
<ide>
<ide><path>src/transformers/models/pegasus/modeling_pegasus.py
<ide> def forward(
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<ide> if labels is not None:
<add> if use_cache:
<add> logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
<add> use_cache = False
<ide> if decoder_input_ids is None:
<ide> decoder_input_ids = shift_tokens_right(
<ide> labels, self.config.pad_token_id, self.config.decoder_start_token_id
<ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py
<ide> def forward(
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide>
<ide> if labels is not None:
<add> if use_cache:
<add> logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
<add> use_cache = False
<ide> if decoder_input_ids is None:
<ide> decoder_input_ids = shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
<ide> | 9 |
Python | Python | remove debugging code | bcaa1793226b8dab929d8ccc786c23854f5886e0 | <ide><path>numpy/testing/noseclasses.py
<ide> def loadTestsFromModule(self, module):
<ide> p2 = p[-1]
<ide> test.globs[p2] = __import__(pkg_name, test.globs, {}, [p2])
<ide>
<del> print 'additional import for %s: from %s import %s' % (test.filename, p1, p2)
<del> print ' (%s): %r' % (pkg_name, test.globs[p2])
<del>
<ide> # always use whitespace and ellipsis options
<ide> optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
<ide> | 1 |
Java | Java | deprecate mutable methods of methodparameter | 62a3e414734b24d1801b34223df5faaae9e32b5f | <ide><path>spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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> private GenericTypeResolver() {
<ide> * @param methodParameter the method parameter specification
<ide> * @param implementationClass the class to resolve type variables against
<ide> * @return the corresponding generic parameter or return type
<add> * @deprecated since 5.2 in favor of {@code methodParameter.withContainingClass(implementationClass).getParameterType()}
<ide> */
<add> @Deprecated
<ide> public static Class<?> resolveParameterType(MethodParameter methodParameter, Class<?> implementationClass) {
<ide> Assert.notNull(methodParameter, "MethodParameter must not be null");
<ide> Assert.notNull(implementationClass, "Class must not be null");
<ide> methodParameter.setContainingClass(implementationClass);
<del> ResolvableType.resolveMethodParameter(methodParameter);
<ide> return methodParameter.getParameterType();
<ide> }
<ide>
<ide><path>spring-core/src/main/java/org/springframework/core/MethodParameter.java
<ide> * @author Andy Clement
<ide> * @author Sam Brannen
<ide> * @author Sebastien Deleuze
<add> * @author Phillip Webb
<ide> * @since 2.0
<ide> * @see org.springframework.core.annotation.SynthesizingMethodParameter
<ide> */
<ide> public class MethodParameter {
<ide> @Nullable
<ide> Map<Integer, Integer> typeIndexesPerLevel;
<ide>
<add> /** The containing class. Could also be supplied by overriding {@link #getContainingClass()} */
<ide> @Nullable
<ide> private volatile Class<?> containingClass;
<ide>
<ide> public MethodParameter(Constructor<?> constructor, int parameterIndex, int nesti
<ide> this.nestingLevel = nestingLevel;
<ide> }
<ide>
<add> /**
<add> * Internal constructor used to create a {@link MethodParameter} with a
<add> * containing class already set.
<add> * @param executable the Executable to specify a parameter for
<add> * @param parameterIndex the index of the parameter
<add> * @param containingClass the containing class
<add> * @since 5.2
<add> */
<add> MethodParameter(Executable executable, int parameterIndex,
<add> @Nullable Class<?> containingClass) {
<add>
<add> Assert.notNull(executable, "Executable must not be null");
<add> this.executable = executable;
<add> this.parameterIndex = validateIndex(executable, parameterIndex);
<add> this.nestingLevel = 1;
<add> this.containingClass = containingClass;
<add> }
<add>
<ide> /**
<ide> * Copy constructor, resulting in an independent MethodParameter object
<ide> * based on the same metadata and cache state that the original object was in.
<ide> public int getParameterIndex() {
<ide> /**
<ide> * Increase this parameter's nesting level.
<ide> * @see #getNestingLevel()
<add> * @deprecated since 5.2 in favor of {@link #nested(Integer)}
<ide> */
<add> @Deprecated
<ide> public void increaseNestingLevel() {
<ide> this.nestingLevel++;
<ide> }
<ide>
<ide> /**
<ide> * Decrease this parameter's nesting level.
<ide> * @see #getNestingLevel()
<add> * @deprecated since 5.2 in favor of retaining the original MethodParameter and
<add> * using {@link #nested(Integer)} if nesting is required
<ide> */
<add> @Deprecated
<ide> public void decreaseNestingLevel() {
<ide> getTypeIndexesPerLevel().remove(this.nestingLevel);
<ide> this.nestingLevel--;
<ide> public int getNestingLevel() {
<ide> * @param typeIndex the corresponding type index
<ide> * (or {@code null} for the default type index)
<ide> * @see #getNestingLevel()
<add> * @deprecated since 5.2 in favor of {@link #withTypeIndex}
<ide> */
<add> @Deprecated
<ide> public void setTypeIndexForCurrentLevel(int typeIndex) {
<ide> getTypeIndexesPerLevel().put(this.nestingLevel, typeIndex);
<ide> }
<ide>
<add> /**
<add> * Return a variant of this {@code MethodParameter} with the type for the current
<add> * level set to the specified value.
<add> * @param typeIndex the new type index
<add> */
<add> public MethodParameter withTypeIndex(int typeIndex) {
<add> return nested(this.nestingLevel, typeIndex);
<add> }
<add>
<ide> /**
<ide> * Return the type index for the current nesting level.
<ide> * @return the corresponding type index, or {@code null}
<ide> private Map<Integer, Integer> getTypeIndexesPerLevel() {
<ide>
<ide> /**
<ide> * Return a variant of this {@code MethodParameter} which points to the
<del> * same parameter but one nesting level deeper. This is effectively the
<del> * same as {@link #increaseNestingLevel()}, just with an independent
<del> * {@code MethodParameter} object (e.g. in case of the original being cached).
<add> * same parameter but one nesting level deeper.
<ide> * @since 4.3
<ide> */
<ide> public MethodParameter nested() {
<add> return nested(null);
<add> }
<add>
<add> /**
<add> * Return a variant of this {@code MethodParameter} which points to the
<add> * same parameter but one nesting level deeper.
<add> * @param typeIndex the type index for the new nesting level
<add> * @since 5.2
<add> */
<add> public MethodParameter nested(@Nullable Integer typeIndex) {
<ide> MethodParameter nestedParam = this.nestedMethodParameter;
<del> if (nestedParam != null) {
<add> if (nestedParam != null && typeIndex == null) {
<ide> return nestedParam;
<ide> }
<del> nestedParam = clone();
<del> nestedParam.nestingLevel = this.nestingLevel + 1;
<del> this.nestedMethodParameter = nestedParam;
<add> nestedParam = nested(this.nestingLevel + 1, typeIndex);
<add> if (typeIndex == null) {
<add> this.nestedMethodParameter = nestedParam;
<add> }
<ide> return nestedParam;
<ide> }
<ide>
<add> private MethodParameter nested(int nestingLevel, @Nullable Integer typeIndex) {
<add> MethodParameter copy = clone();
<add> copy.nestingLevel = nestingLevel;
<add> if (this.typeIndexesPerLevel != null) {
<add> copy.typeIndexesPerLevel = new HashMap<>(this.typeIndexesPerLevel);
<add> }
<add> if (typeIndex != null) {
<add> copy.getTypeIndexesPerLevel().put(copy.nestingLevel, typeIndex);
<add> }
<add> copy.parameterType = null;
<add> copy.genericParameterType = null;
<add> return copy;
<add> }
<add>
<ide> /**
<ide> * Return whether this method indicates a parameter which is not required:
<ide> * either in the form of Java 8's {@link java.util.Optional}, any variant
<ide> public MethodParameter nestedIfOptional() {
<ide> return (getParameterType() == Optional.class ? nested() : this);
<ide> }
<ide>
<del> /**
<del> * Set a containing class to resolve the parameter type against.
<del> */
<add> public Class<?> getContainingClass() {
<add> Class<?> containingClass = this.containingClass;
<add> return (containingClass != null ? containingClass : getDeclaringClass());
<add> }
<add>
<add> @Deprecated
<ide> void setContainingClass(Class<?> containingClass) {
<ide> this.containingClass = containingClass;
<add> this.parameterType = null;
<ide> }
<ide>
<del> public Class<?> getContainingClass() {
<del> Class<?> containingClass = this.containingClass;
<del> return (containingClass != null ? containingClass : getDeclaringClass());
<add> public MethodParameter withContainingClass(@Nullable Class<?> containingClass) {
<add> MethodParameter result = clone();
<add> result.containingClass = containingClass;
<add> result.parameterType = null;
<add> return result;
<ide> }
<ide>
<ide> /**
<ide> * Set a resolved (generic) parameter type.
<ide> */
<add> @Deprecated
<ide> void setParameterType(@Nullable Class<?> parameterType) {
<ide> this.parameterType = parameterType;
<ide> }
<ide> void setParameterType(@Nullable Class<?> parameterType) {
<ide> */
<ide> public Class<?> getParameterType() {
<ide> Class<?> paramType = this.parameterType;
<add> if (paramType != null) {
<add> return paramType;
<add> }
<add> if (getContainingClass() != null) {
<add> paramType = ResolvableType.forMethodParameter(this, null, 1, null).resolve();
<add> }
<ide> if (paramType == null) {
<del> if (this.parameterIndex < 0) {
<del> Method method = getMethod();
<del> paramType = (method != null ?
<del> (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(getContainingClass()) ?
<del> KotlinDelegate.getReturnType(method) : method.getReturnType()) : void.class);
<del> }
<del> else {
<del> paramType = this.executable.getParameterTypes()[this.parameterIndex];
<del> }
<del> this.parameterType = paramType;
<add> paramType = computeParameterType();
<ide> }
<add> this.parameterType = paramType;
<ide> return paramType;
<ide> }
<ide>
<ide> public Type getGenericParameterType() {
<ide> index = this.parameterIndex - 1;
<ide> }
<ide> paramType = (index >= 0 && index < genericParameterTypes.length ?
<del> genericParameterTypes[index] : getParameterType());
<add> genericParameterTypes[index] : computeParameterType());
<ide> }
<ide> this.genericParameterType = paramType;
<ide> }
<ide> return paramType;
<ide> }
<ide>
<add> private Class<?> computeParameterType() {
<add> if (this.parameterIndex < 0) {
<add> Method method = getMethod();
<add> if (method == null) {
<add> return void.class;
<add> }
<add> if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(getContainingClass())) {
<add> return KotlinDelegate.getReturnType(method);
<add> }
<add> return method.getReturnType();
<add> }
<add> return this.executable.getParameterTypes()[this.parameterIndex];
<add> }
<add>
<ide> /**
<ide> * Return the nested type of the method/constructor parameter.
<ide> * @return the parameter type (never {@code null})
<ide> public MethodParameter clone() {
<ide> return new MethodParameter(this);
<ide> }
<ide>
<del>
<ide> /**
<ide> * Create a new MethodParameter for the given method or constructor.
<ide> * <p>This is a convenience factory method for scenarios where a
<ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.java
<ide> public static ResolvableType forConstructorParameter(Constructor<?> constructor,
<ide> Class<?> implementationClass) {
<ide>
<ide> Assert.notNull(constructor, "Constructor must not be null");
<del> MethodParameter methodParameter = new MethodParameter(constructor, parameterIndex);
<del> methodParameter.setContainingClass(implementationClass);
<add> MethodParameter methodParameter = new MethodParameter(constructor, parameterIndex, implementationClass);
<ide> return forMethodParameter(methodParameter);
<ide> }
<ide>
<ide> public static ResolvableType forMethodReturnType(Method method) {
<ide> */
<ide> public static ResolvableType forMethodReturnType(Method method, Class<?> implementationClass) {
<ide> Assert.notNull(method, "Method must not be null");
<del> MethodParameter methodParameter = new MethodParameter(method, -1);
<del> methodParameter.setContainingClass(implementationClass);
<add> MethodParameter methodParameter = new MethodParameter(method, -1, implementationClass);
<ide> return forMethodParameter(methodParameter);
<ide> }
<ide>
<ide> public static ResolvableType forMethodParameter(Method method, int parameterInde
<ide> */
<ide> public static ResolvableType forMethodParameter(Method method, int parameterIndex, Class<?> implementationClass) {
<ide> Assert.notNull(method, "Method must not be null");
<del> MethodParameter methodParameter = new MethodParameter(method, parameterIndex);
<del> methodParameter.setContainingClass(implementationClass);
<add> MethodParameter methodParameter = new MethodParameter(method, parameterIndex, implementationClass);
<ide> return forMethodParameter(methodParameter);
<ide> }
<ide>
<ide> public static ResolvableType forMethodParameter(MethodParameter methodParameter,
<ide> */
<ide> public static ResolvableType forMethodParameter(MethodParameter methodParameter, @Nullable Type targetType) {
<ide> Assert.notNull(methodParameter, "MethodParameter must not be null");
<del> ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass());
<del> return forType(targetType, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()).
<del> getNested(methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel);
<add> int nestingLevel = methodParameter.getNestingLevel();
<add> Map<Integer, Integer> typeIndexesPerLevel = methodParameter.typeIndexesPerLevel;
<add> return forMethodParameter(methodParameter, targetType, nestingLevel,
<add> typeIndexesPerLevel);
<ide> }
<ide>
<ide> /**
<del> * Resolve the top-level parameter type of the given {@code MethodParameter}.
<del> * @param methodParameter the method parameter to resolve
<del> * @since 4.1.9
<del> * @see MethodParameter#setParameterType
<add> * Return a {@link ResolvableType} for the specified {@link MethodParameter} at
<add> * a specific nesting level, overriding the target type to resolve with a specific
<add> * given type.
<add> * @param methodParameter the source method parameter (must not be {@code null})
<add> * @param targetType the type to resolve (a part of the method parameter's type)
<add> * @param nestingLevel the nesting level to use
<add> * @param typeIndexesPerLevel the type indexes per nesting level
<add> * @return a {@link ResolvableType} for the specified method parameter
<add> * @since 5.2
<add> * @see #forMethodParameter(Method, int)
<ide> */
<del> static void resolveMethodParameter(MethodParameter methodParameter) {
<del> Assert.notNull(methodParameter, "MethodParameter must not be null");
<add> static ResolvableType forMethodParameter(MethodParameter methodParameter, @Nullable Type targetType,
<add> int nestingLevel, @Nullable Map<Integer, Integer> typeIndexesPerLevel) {
<ide> ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass());
<del> methodParameter.setParameterType(
<del> forType(null, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()).resolve());
<add> return forType(targetType, new MethodParameterTypeProvider(methodParameter), owner.asVariableResolver()).
<add> getNested(nestingLevel, typeIndexesPerLevel);
<ide> }
<ide>
<ide> /**
<ide><path>spring-core/src/main/java/org/springframework/core/convert/Property.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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 java.util.LinkedHashMap;
<ide> import java.util.Map;
<ide>
<del>import org.springframework.core.GenericTypeResolver;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ConcurrentReferenceHashMap;
<ide> private MethodParameter resolveReadMethodParameter() {
<ide> if (getReadMethod() == null) {
<ide> return null;
<ide> }
<del> return resolveParameterType(new MethodParameter(getReadMethod(), -1));
<add> return new MethodParameter(getReadMethod(), -1).withContainingClass(getObjectType());
<ide> }
<ide>
<ide> @Nullable
<ide> private MethodParameter resolveWriteMethodParameter() {
<ide> if (getWriteMethod() == null) {
<ide> return null;
<ide> }
<del> return resolveParameterType(new MethodParameter(getWriteMethod(), 0));
<del> }
<del>
<del> private MethodParameter resolveParameterType(MethodParameter parameter) {
<del> // needed to resolve generic property types that parameterized by sub-classes e.g. T getFoo();
<del> GenericTypeResolver.resolveParameterType(parameter, getObjectType());
<del> return parameter;
<add> return new MethodParameter(getWriteMethod(), 0).withContainingClass(getObjectType());
<ide> }
<ide>
<ide> private Annotation[] resolveAnnotations() {
<ide><path>spring-core/src/test/java/org/springframework/core/MethodParameterTests.java
<ide> import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<ide>
<ide> /**
<add> * Tests for {@link MethodParameter}.
<add> *
<ide> * @author Arjen Poutsma
<ide> * @author Juergen Hoeller
<ide> * @author Sam Brannen
<add> * @author Phillip Webb
<ide> */
<ide> public class MethodParameterTests {
<ide>
<ide> public void genericConstructorParameterInInnerClass() throws Exception {
<ide> }
<ide>
<ide> @Test
<add> @Deprecated
<ide> public void multipleResolveParameterTypeCalls() throws Exception {
<ide> Method method = ArrayList.class.getMethod("get", int.class);
<ide> MethodParameter methodParameter = MethodParameter.forExecutable(method, -1);
<ide> public void equalsAndHashCodeConsidersContainingClass() throws Exception {
<ide> @Test
<ide> public void equalsAndHashCodeConsidersNesting() throws Exception {
<ide> Method method = ArrayList.class.getMethod("get", int.class);
<del> MethodParameter m1 = MethodParameter.forExecutable(method, -1);
<del> GenericTypeResolver.resolveParameterType(m1, StringList.class);
<del> MethodParameter m2 = MethodParameter.forExecutable(method, -1);
<del> GenericTypeResolver.resolveParameterType(m2, StringList.class);
<del> MethodParameter m3 = MethodParameter.forExecutable(method, -1);
<del> GenericTypeResolver.resolveParameterType(m3, IntegerList.class);
<add> MethodParameter m1 = MethodParameter.forExecutable(method, -1)
<add> .withContainingClass(StringList.class);
<add> MethodParameter m2 = MethodParameter.forExecutable(method, -1)
<add> .withContainingClass(StringList.class);
<add> MethodParameter m3 = MethodParameter.forExecutable(method, -1)
<add> .withContainingClass(IntegerList.class);
<ide> MethodParameter m4 = MethodParameter.forExecutable(method, -1);
<ide> assertThat(m1).isEqualTo(m2).isNotEqualTo(m3).isNotEqualTo(m4);
<ide> assertThat(m1.hashCode()).isEqualTo(m2.hashCode());
<ide> }
<ide>
<add> public void withContainingClassReturnsNewInstance() throws Exception {
<add> Method method = ArrayList.class.getMethod("get", int.class);
<add> MethodParameter m1 = MethodParameter.forExecutable(method, -1);
<add> MethodParameter m2 = m1.withContainingClass(StringList.class);
<add> MethodParameter m3 = m1.withContainingClass(IntegerList.class);
<add> assertThat(m1).isNotSameAs(m2).isNotSameAs(m3);
<add> assertThat(m1.getParameterType()).isEqualTo(Object.class);
<add> assertThat(m2.getParameterType()).isEqualTo(String.class);
<add> assertThat(m3.getParameterType()).isEqualTo(Integer.class);
<add> }
<add>
<add> @Test
<add> public void withTypeIndexReturnsNewInstance() throws Exception {
<add> Method method = ArrayList.class.getMethod("get", int.class);
<add> MethodParameter m1 = MethodParameter.forExecutable(method, -1);
<add> MethodParameter m2 = m1.withTypeIndex(2);
<add> MethodParameter m3 = m1.withTypeIndex(3);
<add> assertThat(m1).isNotSameAs(m2).isNotSameAs(m3);
<add> assertThat(m1.getTypeIndexForCurrentLevel()).isNull();
<add> assertThat(m2.getTypeIndexForCurrentLevel()).isEqualTo(2);
<add> assertThat(m3.getTypeIndexForCurrentLevel()).isEqualTo(3);
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("deprecation")
<add> public void mutatingNestingLevelShouldNotChangeNewInstance() throws Exception {
<add> Method method = ArrayList.class.getMethod("get", int.class);
<add> MethodParameter m1 = MethodParameter.forExecutable(method, -1);
<add> MethodParameter m2 = m1.withTypeIndex(2);
<add> assertThat(m2.getTypeIndexForCurrentLevel()).isEqualTo(2);
<add> m1.setTypeIndexForCurrentLevel(1);
<add> m2.decreaseNestingLevel();
<add> assertThat(m2.getTypeIndexForCurrentLevel()).isNull();
<add> }
<add>
<add> @Test
<add> public void nestedWithTypeIndexReturnsNewInstance() throws Exception {
<add> Method method = ArrayList.class.getMethod("get", int.class);
<add> MethodParameter m1 = MethodParameter.forExecutable(method, -1);
<add> MethodParameter m2 = m1.nested(2);
<add> MethodParameter m3 = m1.nested(3);
<add> assertThat(m1).isNotSameAs(m2).isNotSameAs(m3);
<add> assertThat(m1.getTypeIndexForCurrentLevel()).isNull();
<add> assertThat(m2.getTypeIndexForCurrentLevel()).isEqualTo(2);
<add> assertThat(m3.getTypeIndexForCurrentLevel()).isEqualTo(3);
<add> }
<ide>
<ide> public int method(String p1, long p2) {
<ide> return 42;
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/HandlerMethod.java
<ide>
<ide> import org.springframework.beans.factory.BeanFactory;
<ide> import org.springframework.core.BridgeMethodResolver;
<del>import org.springframework.core.GenericTypeResolver;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.annotation.AnnotatedElementUtils;
<ide> import org.springframework.core.annotation.SynthesizingMethodParameter;
<ide> private MethodParameter[] initMethodParameters() {
<ide> int count = this.bridgedMethod.getParameterCount();
<ide> MethodParameter[] result = new MethodParameter[count];
<ide> for (int i = 0; i < count; i++) {
<del> HandlerMethodParameter parameter = new HandlerMethodParameter(i);
<del> GenericTypeResolver.resolveParameterType(parameter, this.beanType);
<del> result[i] = parameter;
<add> result[i] = new HandlerMethodParameter(i);
<ide> }
<ide> return result;
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java
<ide>
<ide> import org.springframework.beans.factory.BeanFactory;
<ide> import org.springframework.core.BridgeMethodResolver;
<del>import org.springframework.core.GenericTypeResolver;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.annotation.AnnotatedElementUtils;
<ide> private MethodParameter[] initMethodParameters() {
<ide> int count = this.bridgedMethod.getParameterCount();
<ide> MethodParameter[] result = new MethodParameter[count];
<ide> for (int i = 0; i < count; i++) {
<del> HandlerMethodParameter parameter = new HandlerMethodParameter(i);
<del> GenericTypeResolver.resolveParameterType(parameter, this.beanType);
<del> result[i] = parameter;
<add> result[i] = new HandlerMethodParameter(i);
<ide> }
<ide> return result;
<ide> } | 7 |
Javascript | Javascript | improve `unlink` on rnpm | 4969f26252bb8774bfefb7f3b3bd63e7f5415edd | <ide><path>local-cli/link/unlink.js
<ide> function unlink(args, config) {
<ide>
<ide> const allDependencies = getDependencyConfig(config, getProjectDependencies());
<ide> const otherDependencies = filter(allDependencies, d => d.name !== packageName);
<del> const thisDependency = find(allDependencies, d => d.name === packageName);
<ide> const iOSDependencies = compact(otherDependencies.map(d => d.config.ios));
<ide>
<ide> const tasks = [
<del> () => promisify(thisDependency.config.commands.preunlink || commandStub),
<add> () => promisify(dependency.commands.preunlink || commandStub),
<ide> () => unlinkDependencyAndroid(project.android, dependency, packageName),
<ide> () => unlinkDependencyIOS(project.ios, dependency, packageName, iOSDependencies),
<ide> () => unlinkDependencyWindows(project.windows, dependency, packageName),
<del> () => promisify(thisDependency.config.commands.postunlink || commandStub)
<add> () => promisify(dependency.commands.postunlink || commandStub)
<ide> ];
<ide>
<ide> return promiseWaterfall(tasks)
<ide> .then(() => {
<add> // @todo move all these to `tasks` array, just like in
<add> // link
<ide> const assets = difference(
<ide> dependency.assets,
<ide> flatten(allDependencies, d => d.assets) | 1 |
Python | Python | fix issue #253 | f560f52c4c4aa00d84e9c4dfd0eed545c7577074 | <ide><path>setup.py
<ide> ('share/man/man1', ['docs/man/glances.1'])
<ide> ]
<ide>
<del>if hasattr(sys, 'real_prefix') or ('bsd' or 'darwin' in sys.platform):
<add>if hasattr(sys, 'real_prefix') or (sys.platform in ('bsd', 'darwin')):
<ide> etc_path = os.path.join(sys.prefix, 'etc', 'glances')
<ide> if not hasattr(sys, 'real_prefix') and 'linux' in sys.platform:
<ide> etc_path = os.path.join('/etc', 'glances') | 1 |
Python | Python | add joyent testing | cb213b9f737e40a89c7670aa8d3d8fafe84bb9ad | <ide><path>libcloud/test/container/test_joyent.py
<add># Licensed to the Apache Software Foundation (ASF) under one or more
<add># contributor license agreements. See the NOTICE file distributed with
<add># this work for additional information regarding copyright ownership.
<add># The ASF licenses this file to You under the Apache License, Version 2.0
<add># (the "License"); you may not use this file except in compliance with
<add># the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<add>from libcloud.test import unittest
<add>
<add>from libcloud.container.drivers.joyent import JoyentContainerDriver
<add>from libcloud.test.secrets import CONTAINER_PARAMS_DOCKER
<add>
<add>
<add>from libcloud.test.container.test_docker import DockerContainerDriverTestCase, DockerMockHttp
<add>
<add>
<add>class JoyentContainerDriverTestCase(DockerContainerDriverTestCase, unittest.TestCase):
<add>
<add> def setUp(self):
<add> # Create a test driver for each version
<add> versions = ('linux_124', 'mac_124')
<add> self.drivers = []
<add> for version in versions:
<add> JoyentContainerDriver.connectionCls.conn_class = \
<add> DockerMockHttp
<add> DockerMockHttp.type = None
<add> DockerMockHttp.use_param = 'a'
<add> driver = JoyentContainerDriver(*CONTAINER_PARAMS_DOCKER)
<add> driver.version = version
<add> self.drivers.append(driver) | 1 |
PHP | PHP | move unlocked field resetting to end() | f2bc2a172895adfd43bd5ce519ec359f983c6b90 | <ide><path>src/View/Helper/FormHelper.php
<ide> public function create($model = null, array $options = [])
<ide> $htmlAttributes += $options;
<ide>
<ide> $this->fields = [];
<del> $this->_unlockedFields = [];
<ide> if ($this->requestType !== 'get') {
<ide> $append .= $this->_csrfField();
<ide> }
<ide> public function end(array $secureAttributes = [])
<ide> ) {
<ide> $out .= $this->secure($this->fields, $secureAttributes);
<ide> $this->fields = [];
<add> $this->_unlockedFields = [];
<ide> }
<ide> $out .= $this->formatTemplate('formEnd', []);
<ide>
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testResetUnlockFields()
<ide> 'unlockedFields' => []
<ide> ];
<ide>
<del> $this->Form->create('Contact');
<ide> $this->Form->unlockField('Contact.id');
<add> $this->Form->create('Contact');
<add> $this->Form->hidden('Contact.id', ['value' => 1]);
<add> $this->assertEmpty($this->Form->fields, 'Field should be unlocked');
<ide> $this->Form->end();
<ide>
<ide> $this->Form->create('Contact'); | 2 |
Javascript | Javascript | use ast builders in each/with transforms | af8a39c6220d678e037b74acbc574586fb7f30be | <ide><path>packages/ember-htmlbars/lib/plugins/transform-each-in-to-hash.js
<ide> import Walker from "htmlbars-syntax/walker";
<add>import b from "htmlbars-syntax/builders";
<ide>
<ide> /**
<ide> An HTMLBars AST transformation that replaces all instances of
<ide> export default function(ast) {
<ide> if (validate(node)) {
<ide> var removedParams = node.sexpr.params.splice(0, 2);
<ide> var keyword = removedParams[0].original;
<del> var stringNode = {
<del> type: 'StringLiteral',
<del> value: keyword,
<del> original: keyword
<del> };
<ide>
<add> // TODO: This may not be necessary.
<ide> if (!node.sexpr.hash) {
<del> node.sexpr.hash = {
<del> type: 'Hash',
<del> pairs: []
<del> };
<add> node.sexpr.hash = b.hash();
<ide> }
<ide>
<del> var hashPair = {
<del> type: 'HashPair',
<del> key: 'keyword',
<del> value: stringNode
<del> };
<del>
<del> node.sexpr.hash.pairs.push(hashPair);
<add> node.sexpr.hash.pairs.push(b.pair(
<add> 'keyword',
<add> b.string(keyword)
<add> ));
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-htmlbars/lib/plugins/transform-with-as-to-hash.js
<ide> import Walker from "htmlbars-syntax/walker";
<add>import b from "htmlbars-syntax/builders";
<ide>
<ide> /**
<ide> An HTMLBars AST transformation that replaces all instances of
<ide> export default function(ast) {
<ide> if (validate(node)) {
<ide> var removedParams = node.sexpr.params.splice(1, 2);
<ide> var keyword = removedParams[1].original;
<del> var stringNode = {
<del> type: 'StringLiteral',
<del> value: keyword,
<del> original: keyword
<del> };
<ide>
<add> // TODO: This may not be necessary.
<ide> if (!node.sexpr.hash) {
<del> node.sexpr.hash = {
<del> type: 'Hash',
<del> pairs: []
<del> };
<add> node.sexpr.hash = b.hash();
<ide> }
<ide>
<del> var hashPair = {
<del> type: 'HashPair',
<del> key: 'keywordName',
<del> value: stringNode
<del> };
<del>
<del> node.sexpr.hash.pairs.push(hashPair);
<add> node.sexpr.hash.pairs.push(b.pair(
<add> 'keywordName',
<add> b.string(keyword)
<add> ));
<ide> }
<ide> });
<ide> | 2 |
Ruby | Ruby | remove unused method `namespaced_file_path` | a0d4d78884a6e7c89b582e9555ed2bb30db9d438 | <ide><path>railties/lib/rails/generators/named_base.rb
<ide> def regular_class_path
<ide> @class_path
<ide> end
<ide>
<del> def namespaced_file_path
<del> @namespaced_file_path ||= namespaced_class_path.join("/")
<del> end
<del>
<ide> def namespaced_class_path
<ide> @namespaced_class_path ||= [namespaced_path] + @class_path
<ide> end | 1 |
Python | Python | add triu_indices and tril_indices | 2951e733d9ffa03276d6859721b57209234bea12 | <ide><path>benchmarks/benchmarks/bench_core.py
<ide> def time_triu_l10x10(self):
<ide> def time_tril_l10x10(self):
<ide> np.tril(self.l10x10)
<ide>
<add> def time_triu_indices_500(self):
<add> np.triu_indices(500)
<add>
<add> def time_tril_indices_500(self):
<add> np.tril_indices(500)
<add>
<ide>
<ide> class Temporaries(Benchmark):
<ide> def setup(self): | 1 |
Go | Go | use server.url() instead of server.url | 40c8e78757a75a9e251223f563fc5adb2bc9bf99 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func TestBuildLastModified(t *testing.T) {
<ide> ADD %s/file /
<ide> RUN ls -le /file`
<ide>
<del> dockerfile := fmt.Sprintf(dFmt, server.URL)
<add> dockerfile := fmt.Sprintf(dFmt, server.URL())
<ide>
<ide> if _, out, err = buildImageWithOut(name, dockerfile, false); err != nil {
<ide> t.Fatal(err)
<ide> RUN ls -le /file`
<ide> }
<ide> defer server.Close()
<ide>
<del> dockerfile = fmt.Sprintf(dFmt, server.URL)
<add> dockerfile = fmt.Sprintf(dFmt, server.URL())
<ide>
<ide> if _, out2, err = buildImageWithOut(name, dockerfile, false); err != nil {
<ide> t.Fatal(err) | 1 |
Python | Python | add __repr__ to paramsdict class | df388a3d5364b748993e61b522d0b68ff8b8124a | <ide><path>airflow/models/param.py
<ide> def __delitem__(self, v: str) -> None:
<ide> def __iter__(self):
<ide> return iter(self.__dict)
<ide>
<add> def __repr__(self):
<add> return repr(self.dump())
<add>
<ide> def __setitem__(self, key: str, value: Any) -> None:
<ide> """
<ide> Override for dictionary's ``setitem`` method. This method make sure that all values are of
<ide><path>tests/models/test_param.py
<ide> def test_update(self):
<ide> with pytest.raises(ParamValidationError, match=r'Invalid input for param key: 1 is not'):
<ide> pd.update({'key': 1})
<ide>
<add> def test_repr(self):
<add> pd = ParamsDict({'key': Param('value', type='string')})
<add> assert repr(pd) == "{'key': 'value'}"
<add>
<ide>
<ide> class TestDagParamRuntime:
<ide> VALUE = 42 | 2 |
PHP | PHP | fix broken transaction logic when pdo changes | d2b1bfbbe17bd06c5af8385d1c9e336bfabc834b | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function getReadPdo()
<ide> */
<ide> public function setPdo($pdo)
<ide> {
<add> if ($this->transactions >= 1) throw new \RuntimeException("Attempt to change PDO inside running transaction");
<add>
<ide> $this->pdo = $pdo;
<ide>
<ide> return $this; | 1 |
Python | Python | fix typo in code documentation | 0224ee0e9da2849ea587a5f5303605d62b0eb765 | <ide><path>slim/nets/mobilenet_v1.py
<ide> def mobilenet_v1_base(inputs,
<ide> inputs: a tensor of shape [batch_size, height, width, channels].
<ide> final_endpoint: specifies the endpoint to construct the network up to. It
<ide> can be one of ['Conv2d_0', 'Conv2d_1_pointwise', 'Conv2d_2_pointwise',
<del> 'Conv2d_3_pointwise', 'Conv2d_4_pointwise', 'Conv2d_5'_pointwise,
<add> 'Conv2d_3_pointwise', 'Conv2d_4_pointwise', 'Conv2d_5_pointwise',
<ide> 'Conv2d_6_pointwise', 'Conv2d_7_pointwise', 'Conv2d_8_pointwise',
<ide> 'Conv2d_9_pointwise', 'Conv2d_10_pointwise', 'Conv2d_11_pointwise',
<ide> 'Conv2d_12_pointwise', 'Conv2d_13_pointwise']. | 1 |
Python | Python | add more extension methods to the vsphere driver | a0150609d13f13a14bb3a5bfd029e581e6a0ae31 | <ide><path>libcloud/compute/drivers/vsphere.py
<ide> def ex_get_resource_pool_name(self, node):
<ide> vm = self._get_vm_for_node(node=node)
<ide> return vm.get_resource_pool_name()
<ide>
<add> @wrap_non_libcloud_exceptions
<add> def ex_get_hosts(self):
<add> """
<add> Retrurn all the available hosts.
<add>
<add> :rtype: ``dict``
<add> """
<add> result = self.connection.client.get_hosts()
<add> return result
<add>
<add> @wrap_non_libcloud_exceptions
<add> def ex_get_datastores(self):
<add> """
<add> Return all the available datastores.
<add>
<add> :rtype: ``dict``
<add> """
<add> result = self.connection.client.get_datastores()
<add> return result
<add>
<ide> @wrap_non_libcloud_exceptions
<ide> def ex_get_node_by_path(self, path):
<ide> """ | 1 |
Text | Text | add pipeline badges | 5318c87b08b4bf3a55ed53340ca3a0fcc074e61c | <ide><path>README.md
<ide> 
<del>[](https://travis-ci.org/freeCodeCamp/freeCodeCamp)
<add>
<ide> [](http://makeapullrequest.com)
<ide> [](http://www.firsttimersonly.com/)
<ide> [](https://www.codetriage.com/freecodecamp/freecodecamp)
<ide> Please don't create GitHub issues for security issues. Instead, please send an e
<ide>
<ide> ### Contributing
<ide>
<del>#### [Please follow these steps to contribute.](CONTRIBUTING.md)
<add>> ### [Please follow these steps to contribute.](CONTRIBUTING.md)
<add>
<add>#### Build Status:
<add>
<add>| Platform | Type | Status |
<add>| :-------------- | :--------- | :---------: |
<add>| Travis CI | Unit Tests | [](https://travis-ci.org/freeCodeCamp/freeCodeCamp) |
<add>| Azure Pipelines | Artifacts | [](https://dev.azure.com/freeCodeCamp-org/freeCodeCamp/_build) |
<add>
<add>#### Deployment Status:
<add>
<add>| Application | Version | Status |
<add>| :----------- | :--------- | :---------: |
<add>| Client | Beta/Next | [](https://dev.azure.com/freeCodeCamp-org/freeCodeCamp/_release) |
<add>| API | Beta/Next | [](https://dev.azure.com/freeCodeCamp-org/freeCodeCamp/_release) |
<add>| Client | Production | [](https://dev.azure.com/freeCodeCamp-org/freeCodeCamp/_release) |
<add>| API | Production | [](https://dev.azure.com/freeCodeCamp-org/freeCodeCamp/_release) |
<ide>
<ide> ### License
<ide> | 1 |
Javascript | Javascript | convert the text layer builder to es6 syntax | 19f56ec5c18aa8c161df9b718faf62d831f67657 | <ide><path>web/text_layer_builder.js
<ide> import { getGlobalEventBus } from './dom_events';
<ide> import { renderTextLayer } from 'pdfjs-lib';
<ide>
<del>var EXPAND_DIVS_TIMEOUT = 300; // ms
<add>const EXPAND_DIVS_TIMEOUT = 300; // ms
<ide>
<ide> /**
<ide> * @typedef {Object} TextLayerBuilderOptions
<ide> var EXPAND_DIVS_TIMEOUT = 300; // ms
<ide> */
<ide>
<ide> /**
<del> * TextLayerBuilder provides text-selection functionality for the PDF.
<del> * It does this by creating overlay divs over the PDF text. These divs
<add> * The text layer builder provides text selection functionality for the PDF.
<add> * It does this by creating overlay divs over the PDF's text. These divs
<ide> * contain text that matches the PDF text they are overlaying. This object
<ide> * also provides a way to highlight text that is being searched for.
<del> * @class
<ide> */
<del>var TextLayerBuilder = (function TextLayerBuilderClosure() {
<del> function TextLayerBuilder(options) {
<del> this.textLayerDiv = options.textLayerDiv;
<del> this.eventBus = options.eventBus || getGlobalEventBus();
<add>class TextLayerBuilder {
<add> constructor({ textLayerDiv, eventBus, pageIndex, viewport,
<add> findController = null, enhanceTextSelection = false, }) {
<add> this.textLayerDiv = textLayerDiv;
<add> this.eventBus = eventBus || getGlobalEventBus();
<ide> this.textContent = null;
<ide> this.textContentItemsStr = [];
<ide> this.textContentStream = null;
<ide> this.renderingDone = false;
<del> this.pageIdx = options.pageIndex;
<add> this.pageIdx = pageIndex;
<ide> this.pageNumber = this.pageIdx + 1;
<ide> this.matches = [];
<del> this.viewport = options.viewport;
<add> this.viewport = viewport;
<ide> this.textDivs = [];
<del> this.findController = options.findController || null;
<add> this.findController = findController;
<ide> this.textLayerRenderTask = null;
<del> this.enhanceTextSelection = options.enhanceTextSelection;
<add> this.enhanceTextSelection = enhanceTextSelection;
<add>
<ide> this._bindMouse();
<ide> }
<ide>
<del> TextLayerBuilder.prototype = {
<del> /**
<del> * @private
<del> */
<del> _finishRendering: function TextLayerBuilder_finishRendering() {
<del> this.renderingDone = true;
<del>
<del> if (!this.enhanceTextSelection) {
<del> var endOfContent = document.createElement('div');
<del> endOfContent.className = 'endOfContent';
<del> this.textLayerDiv.appendChild(endOfContent);
<del> }
<add> /**
<add> * @private
<add> */
<add> _finishRendering() {
<add> this.renderingDone = true;
<add>
<add> if (!this.enhanceTextSelection) {
<add> let endOfContent = document.createElement('div');
<add> endOfContent.className = 'endOfContent';
<add> this.textLayerDiv.appendChild(endOfContent);
<add> }
<add>
<add> this.eventBus.dispatch('textlayerrendered', {
<add> source: this,
<add> pageNumber: this.pageNumber,
<add> numTextDivs: this.textDivs.length,
<add> });
<add> }
<ide>
<del> this.eventBus.dispatch('textlayerrendered', {
<del> source: this,
<del> pageNumber: this.pageNumber,
<del> numTextDivs: this.textDivs.length,
<del> });
<del> },
<del>
<del> /**
<del> * Renders the text layer.
<del> * @param {number} timeout (optional) if specified, the rendering waits
<del> * for specified amount of ms.
<del> */
<del> render: function TextLayerBuilder_render(timeout) {
<del> if (!(this.textContent || this.textContentStream) || this.renderingDone) {
<del> return;
<del> }
<del> this.cancel();
<del>
<del> this.textDivs = [];
<del> var textLayerFrag = document.createDocumentFragment();
<del> this.textLayerRenderTask = renderTextLayer({
<del> textContent: this.textContent,
<del> textContentStream: this.textContentStream,
<del> container: textLayerFrag,
<del> viewport: this.viewport,
<del> textDivs: this.textDivs,
<del> textContentItemsStr: this.textContentItemsStr,
<del> timeout,
<del> enhanceTextSelection: this.enhanceTextSelection,
<del> });
<del> this.textLayerRenderTask.promise.then(() => {
<del> this.textLayerDiv.appendChild(textLayerFrag);
<del> this._finishRendering();
<del> this.updateMatches();
<del> }, function (reason) {
<del> // cancelled or failed to render text layer -- skipping errors
<del> });
<del> },
<del>
<del> /**
<del> * Cancels rendering of the text layer.
<del> */
<del> cancel: function TextLayerBuilder_cancel() {
<del> if (this.textLayerRenderTask) {
<del> this.textLayerRenderTask.cancel();
<del> this.textLayerRenderTask = null;
<del> }
<del> },
<del>
<del> setTextContentStream(readableStream) {
<del> this.cancel();
<del> this.textContentStream = readableStream;
<del> },
<del>
<del> setTextContent: function TextLayerBuilder_setTextContent(textContent) {
<del> this.cancel();
<del> this.textContent = textContent;
<del> },
<del>
<del> convertMatches: function TextLayerBuilder_convertMatches(matches,
<del> matchesLength) {
<del> var i = 0;
<del> var iIndex = 0;
<del> let textContentItemsStr = this.textContentItemsStr;
<del> var end = textContentItemsStr.length - 1;
<del> var queryLen = (this.findController === null ?
<del> 0 : this.findController.state.query.length);
<del> var ret = [];
<del> if (!matches) {
<del> return ret;
<del> }
<del> for (var m = 0, len = matches.length; m < len; m++) {
<del> // Calculate the start position.
<del> var matchIdx = matches[m];
<del>
<del> // Loop over the divIdxs.
<del> while (i !== end && matchIdx >=
<del> (iIndex + textContentItemsStr[i].length)) {
<del> iIndex += textContentItemsStr[i].length;
<del> i++;
<del> }
<add> /**
<add> * Renders the text layer.
<add> *
<add> * @param {number} timeout - (optional) wait for a specified amount of
<add> * milliseconds before rendering
<add> */
<add> render(timeout = 0) {
<add> if (!(this.textContent || this.textContentStream) || this.renderingDone) {
<add> return;
<add> }
<add> this.cancel();
<ide>
<del> if (i === textContentItemsStr.length) {
<del> console.error('Could not find a matching mapping');
<del> }
<add> this.textDivs = [];
<add> let textLayerFrag = document.createDocumentFragment();
<add> this.textLayerRenderTask = renderTextLayer({
<add> textContent: this.textContent,
<add> textContentStream: this.textContentStream,
<add> container: textLayerFrag,
<add> viewport: this.viewport,
<add> textDivs: this.textDivs,
<add> textContentItemsStr: this.textContentItemsStr,
<add> timeout,
<add> enhanceTextSelection: this.enhanceTextSelection,
<add> });
<add> this.textLayerRenderTask.promise.then(() => {
<add> this.textLayerDiv.appendChild(textLayerFrag);
<add> this._finishRendering();
<add> this.updateMatches();
<add> }, function (reason) {
<add> // Cancelled or failed to render text layer; skipping errors.
<add> });
<add> }
<ide>
<del> var match = {
<del> begin: {
<del> divIdx: i,
<del> offset: matchIdx - iIndex,
<del> },
<del> };
<del>
<del> // Calculate the end position.
<del> if (matchesLength) { // multiterm search
<del> matchIdx += matchesLength[m];
<del> } else { // phrase search
<del> matchIdx += queryLen;
<del> }
<add> /**
<add> * Cancel rendering of the text layer.
<add> */
<add> cancel() {
<add> if (this.textLayerRenderTask) {
<add> this.textLayerRenderTask.cancel();
<add> this.textLayerRenderTask = null;
<add> }
<add> }
<ide>
<del> // Somewhat the same array as above, but use > instead of >= to get
<del> // the end position right.
<del> while (i !== end && matchIdx >
<del> (iIndex + textContentItemsStr[i].length)) {
<del> iIndex += textContentItemsStr[i].length;
<del> i++;
<del> }
<add> setTextContentStream(readableStream) {
<add> this.cancel();
<add> this.textContentStream = readableStream;
<add> }
<ide>
<del> match.end = {
<del> divIdx: i,
<del> offset: matchIdx - iIndex,
<del> };
<del> ret.push(match);
<del> }
<add> setTextContent(textContent) {
<add> this.cancel();
<add> this.textContent = textContent;
<add> }
<ide>
<add> convertMatches(matches, matchesLength) {
<add> let i = 0;
<add> let iIndex = 0;
<add> let textContentItemsStr = this.textContentItemsStr;
<add> let end = textContentItemsStr.length - 1;
<add> let queryLen = (this.findController === null ?
<add> 0 : this.findController.state.query.length);
<add> let ret = [];
<add> if (!matches) {
<ide> return ret;
<del> },
<add> }
<add> for (let m = 0, len = matches.length; m < len; m++) {
<add> // Calculate the start position.
<add> let matchIdx = matches[m];
<add>
<add> // Loop over the divIdxs.
<add> while (i !== end && matchIdx >=
<add> (iIndex + textContentItemsStr[i].length)) {
<add> iIndex += textContentItemsStr[i].length;
<add> i++;
<add> }
<ide>
<del> renderMatches: function TextLayerBuilder_renderMatches(matches) {
<del> // Early exit if there is nothing to render.
<del> if (matches.length === 0) {
<del> return;
<add> if (i === textContentItemsStr.length) {
<add> console.error('Could not find a matching mapping');
<ide> }
<ide>
<del> let textContentItemsStr = this.textContentItemsStr;
<del> var textDivs = this.textDivs;
<del> var prevEnd = null;
<del> var pageIdx = this.pageIdx;
<del> var isSelectedPage = (this.findController === null ?
<del> false : (pageIdx === this.findController.selected.pageIdx));
<del> var selectedMatchIdx = (this.findController === null ?
<del> -1 : this.findController.selected.matchIdx);
<del> var highlightAll = (this.findController === null ?
<del> false : this.findController.state.highlightAll);
<del> var infinity = {
<del> divIdx: -1,
<del> offset: undefined,
<add> let match = {
<add> begin: {
<add> divIdx: i,
<add> offset: matchIdx - iIndex,
<add> },
<ide> };
<ide>
<del> function beginText(begin, className) {
<del> var divIdx = begin.divIdx;
<del> textDivs[divIdx].textContent = '';
<del> appendTextToDiv(divIdx, 0, begin.offset, className);
<add> // Calculate the end position.
<add> if (matchesLength) { // Multiterm search.
<add> matchIdx += matchesLength[m];
<add> } else { // Phrase search.
<add> matchIdx += queryLen;
<ide> }
<ide>
<del> function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
<del> var div = textDivs[divIdx];
<del> var content =
<del> textContentItemsStr[divIdx].substring(fromOffset, toOffset);
<del> var node = document.createTextNode(content);
<del> if (className) {
<del> var span = document.createElement('span');
<del> span.className = className;
<del> span.appendChild(node);
<del> div.appendChild(span);
<del> return;
<del> }
<del> div.appendChild(node);
<add> // Somewhat the same array as above, but use > instead of >= to get
<add> // the end position right.
<add> while (i !== end && matchIdx >
<add> (iIndex + textContentItemsStr[i].length)) {
<add> iIndex += textContentItemsStr[i].length;
<add> i++;
<ide> }
<ide>
<del> var i0 = selectedMatchIdx, i1 = i0 + 1;
<del> if (highlightAll) {
<del> i0 = 0;
<del> i1 = matches.length;
<del> } else if (!isSelectedPage) {
<del> // Not highlighting all and this isn't the selected page, so do nothing.
<del> return;
<del> }
<add> match.end = {
<add> divIdx: i,
<add> offset: matchIdx - iIndex,
<add> };
<add> ret.push(match);
<add> }
<ide>
<del> for (var i = i0; i < i1; i++) {
<del> var match = matches[i];
<del> var begin = match.begin;
<del> var end = match.end;
<del> var isSelected = (isSelectedPage && i === selectedMatchIdx);
<del> var highlightSuffix = (isSelected ? ' selected' : '');
<add> return ret;
<add> }
<ide>
<del> if (this.findController) {
<del> this.findController.updateMatchPosition(pageIdx, i, textDivs,
<del> begin.divIdx);
<del> }
<add> renderMatches(matches) {
<add> // Early exit if there is nothing to render.
<add> if (matches.length === 0) {
<add> return;
<add> }
<add>
<add> let textContentItemsStr = this.textContentItemsStr;
<add> let textDivs = this.textDivs;
<add> let prevEnd = null;
<add> let pageIdx = this.pageIdx;
<add> let isSelectedPage = (this.findController === null ?
<add> false : (pageIdx === this.findController.selected.pageIdx));
<add> let selectedMatchIdx = (this.findController === null ?
<add> -1 : this.findController.selected.matchIdx);
<add> let highlightAll = (this.findController === null ?
<add> false : this.findController.state.highlightAll);
<add> let infinity = {
<add> divIdx: -1,
<add> offset: undefined,
<add> };
<add>
<add> function beginText(begin, className) {
<add> let divIdx = begin.divIdx;
<add> textDivs[divIdx].textContent = '';
<add> appendTextToDiv(divIdx, 0, begin.offset, className);
<add> }
<add>
<add> function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
<add> let div = textDivs[divIdx];
<add> let content = textContentItemsStr[divIdx].substring(fromOffset, toOffset);
<add> let node = document.createTextNode(content);
<add> if (className) {
<add> let span = document.createElement('span');
<add> span.className = className;
<add> span.appendChild(node);
<add> div.appendChild(span);
<add> return;
<add> }
<add> div.appendChild(node);
<add> }
<add>
<add> let i0 = selectedMatchIdx, i1 = i0 + 1;
<add> if (highlightAll) {
<add> i0 = 0;
<add> i1 = matches.length;
<add> } else if (!isSelectedPage) {
<add> // Not highlighting all and this isn't the selected page, so do nothing.
<add> return;
<add> }
<add>
<add> for (let i = i0; i < i1; i++) {
<add> let match = matches[i];
<add> let begin = match.begin;
<add> let end = match.end;
<add> let isSelected = (isSelectedPage && i === selectedMatchIdx);
<add> let highlightSuffix = (isSelected ? ' selected' : '');
<add>
<add> if (this.findController) {
<add> this.findController.updateMatchPosition(pageIdx, i, textDivs,
<add> begin.divIdx);
<add> }
<ide>
<del> // Match inside new div.
<del> if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
<del> // If there was a previous div, then add the text at the end.
<del> if (prevEnd !== null) {
<del> appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
<del> }
<del> // Clear the divs and set the content until the starting point.
<del> beginText(begin);
<del> } else {
<del> appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
<add> // Match inside new div.
<add> if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
<add> // If there was a previous div, then add the text at the end.
<add> if (prevEnd !== null) {
<add> appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
<ide> }
<add> // Clear the divs and set the content until the starting point.
<add> beginText(begin);
<add> } else {
<add> appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
<add> }
<ide>
<del> if (begin.divIdx === end.divIdx) {
<del> appendTextToDiv(begin.divIdx, begin.offset, end.offset,
<del> 'highlight' + highlightSuffix);
<del> } else {
<del> appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
<del> 'highlight begin' + highlightSuffix);
<del> for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
<del> textDivs[n0].className = 'highlight middle' + highlightSuffix;
<del> }
<del> beginText(end, 'highlight end' + highlightSuffix);
<add> if (begin.divIdx === end.divIdx) {
<add> appendTextToDiv(begin.divIdx, begin.offset, end.offset,
<add> 'highlight' + highlightSuffix);
<add> } else {
<add> appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
<add> 'highlight begin' + highlightSuffix);
<add> for (let n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
<add> textDivs[n0].className = 'highlight middle' + highlightSuffix;
<ide> }
<del> prevEnd = end;
<add> beginText(end, 'highlight end' + highlightSuffix);
<ide> }
<add> prevEnd = end;
<add> }
<ide>
<del> if (prevEnd) {
<del> appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
<del> }
<del> },
<add> if (prevEnd) {
<add> appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
<add> }
<add> }
<ide>
<del> updateMatches: function TextLayerBuilder_updateMatches() {
<del> // Only show matches when all rendering is done.
<del> if (!this.renderingDone) {
<del> return;
<add> updateMatches() {
<add> // Only show matches when all rendering is done.
<add> if (!this.renderingDone) {
<add> return;
<add> }
<add>
<add> // Clear all matches.
<add> let matches = this.matches;
<add> let textDivs = this.textDivs;
<add> let textContentItemsStr = this.textContentItemsStr;
<add> let clearedUntilDivIdx = -1;
<add>
<add> // Clear all current matches.
<add> for (let i = 0, len = matches.length; i < len; i++) {
<add> let match = matches[i];
<add> let begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
<add> for (let n = begin, end = match.end.divIdx; n <= end; n++) {
<add> let div = textDivs[n];
<add> div.textContent = textContentItemsStr[n];
<add> div.className = '';
<ide> }
<add> clearedUntilDivIdx = match.end.divIdx + 1;
<add> }
<add>
<add> if (this.findController === null || !this.findController.active) {
<add> return;
<add> }
<add>
<add> // Convert the matches on the page controller into the match format
<add> // used for the textLayer.
<add> let pageMatches, pageMatchesLength;
<add> if (this.findController !== null) {
<add> pageMatches = this.findController.pageMatches[this.pageIdx] || null;
<add> pageMatchesLength = (this.findController.pageMatchesLength) ?
<add> this.findController.pageMatchesLength[this.pageIdx] || null : null;
<add> }
<add>
<add> this.matches = this.convertMatches(pageMatches, pageMatchesLength);
<add> this.renderMatches(this.matches);
<add> }
<ide>
<del> // Clear all matches.
<del> var matches = this.matches;
<del> var textDivs = this.textDivs;
<del> let textContentItemsStr = this.textContentItemsStr;
<del> var clearedUntilDivIdx = -1;
<del>
<del> // Clear all current matches.
<del> for (var i = 0, len = matches.length; i < len; i++) {
<del> var match = matches[i];
<del> var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
<del> for (var n = begin, end = match.end.divIdx; n <= end; n++) {
<del> var div = textDivs[n];
<del> div.textContent = textContentItemsStr[n];
<del> div.className = '';
<add> /**
<add> * Improves text selection by adding an additional div where the mouse was
<add> * clicked. This reduces flickering of the content if the mouse is slowly
<add> * dragged up or down.
<add> *
<add> * @private
<add> */
<add> _bindMouse() {
<add> let div = this.textLayerDiv;
<add> let expandDivsTimer = null;
<add>
<add> div.addEventListener('mousedown', (evt) => {
<add> if (this.enhanceTextSelection && this.textLayerRenderTask) {
<add> this.textLayerRenderTask.expandTextDivs(true);
<add> if ((typeof PDFJSDev === 'undefined' ||
<add> !PDFJSDev.test('FIREFOX || MOZCENTRAL')) &&
<add> expandDivsTimer) {
<add> clearTimeout(expandDivsTimer);
<add> expandDivsTimer = null;
<ide> }
<del> clearedUntilDivIdx = match.end.divIdx + 1;
<del> }
<del>
<del> if (this.findController === null || !this.findController.active) {
<ide> return;
<ide> }
<ide>
<del> // Convert the matches on the page controller into the match format
<del> // used for the textLayer.
<del> var pageMatches, pageMatchesLength;
<del> if (this.findController !== null) {
<del> pageMatches = this.findController.pageMatches[this.pageIdx] || null;
<del> pageMatchesLength = (this.findController.pageMatchesLength) ?
<del> this.findController.pageMatchesLength[this.pageIdx] || null : null;
<add> let end = div.querySelector('.endOfContent');
<add> if (!end) {
<add> return;
<ide> }
<del>
<del> this.matches = this.convertMatches(pageMatches, pageMatchesLength);
<del> this.renderMatches(this.matches);
<del> },
<del>
<del> /**
<del> * Fixes text selection: adds additional div where mouse was clicked.
<del> * This reduces flickering of the content if mouse slowly dragged down/up.
<del> * @private
<del> */
<del> _bindMouse: function TextLayerBuilder_bindMouse() {
<del> var div = this.textLayerDiv;
<del> var self = this;
<del> var expandDivsTimer = null;
<del>
<del> div.addEventListener('mousedown', function (e) {
<del> if (self.enhanceTextSelection && self.textLayerRenderTask) {
<del> self.textLayerRenderTask.expandTextDivs(true);
<del> if ((typeof PDFJSDev === 'undefined' ||
<del> !PDFJSDev.test('FIREFOX || MOZCENTRAL')) &&
<del> expandDivsTimer) {
<del> clearTimeout(expandDivsTimer);
<del> expandDivsTimer = null;
<del> }
<del> return;
<del> }
<del> var end = div.querySelector('.endOfContent');
<del> if (!end) {
<del> return;
<del> }
<del> if (typeof PDFJSDev === 'undefined' ||
<del> !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
<add> if (typeof PDFJSDev === 'undefined' ||
<add> !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
<ide> // On non-Firefox browsers, the selection will feel better if the height
<del> // of the endOfContent div will be adjusted to start at mouse click
<del> // location -- this will avoid flickering when selections moves up.
<del> // However it does not work when selection started on empty space.
<del> var adjustTop = e.target !== div;
<add> // of the `endOfContent` div is adjusted to start at mouse click
<add> // location. This avoids flickering when the selection moves up.
<add> // However it does not work when selection is started on empty space.
<add> let adjustTop = evt.target !== div;
<ide> if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) {
<ide> adjustTop = adjustTop && window.getComputedStyle(end).
<ide> getPropertyValue('-moz-user-select') !== 'none';
<ide> }
<ide> if (adjustTop) {
<del> var divBounds = div.getBoundingClientRect();
<del> var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
<add> let divBounds = div.getBoundingClientRect();
<add> let r = Math.max(0, (evt.pageY - divBounds.top) / divBounds.height);
<ide> end.style.top = (r * 100).toFixed(2) + '%';
<ide> }
<del> }
<del> end.classList.add('active');
<del> });
<del>
<del> div.addEventListener('mouseup', function (e) {
<del> if (self.enhanceTextSelection && self.textLayerRenderTask) {
<del> if (typeof PDFJSDev === 'undefined' ||
<del> !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
<del> expandDivsTimer = setTimeout(function() {
<del> if (self.textLayerRenderTask) {
<del> self.textLayerRenderTask.expandTextDivs(false);
<del> }
<del> expandDivsTimer = null;
<del> }, EXPAND_DIVS_TIMEOUT);
<del> } else {
<del> self.textLayerRenderTask.expandTextDivs(false);
<del> }
<del> return;
<del> }
<del> var end = div.querySelector('.endOfContent');
<del> if (!end) {
<del> return;
<del> }
<add> }
<add> end.classList.add('active');
<add> });
<add>
<add> div.addEventListener('mouseup', () => {
<add> if (this.enhanceTextSelection && this.textLayerRenderTask) {
<ide> if (typeof PDFJSDev === 'undefined' ||
<ide> !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
<del> end.style.top = '';
<add> expandDivsTimer = setTimeout(() => {
<add> if (this.textLayerRenderTask) {
<add> this.textLayerRenderTask.expandTextDivs(false);
<add> }
<add> expandDivsTimer = null;
<add> }, EXPAND_DIVS_TIMEOUT);
<add> } else {
<add> this.textLayerRenderTask.expandTextDivs(false);
<ide> }
<del> end.classList.remove('active');
<del> });
<del> },
<del> };
<del> return TextLayerBuilder;
<del>})();
<add> return;
<add> }
<add>
<add> let end = div.querySelector('.endOfContent');
<add> if (!end) {
<add> return;
<add> }
<add> if (typeof PDFJSDev === 'undefined' ||
<add> !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
<add> end.style.top = '';
<add> }
<add> end.classList.remove('active');
<add> });
<add> }
<add>}
<ide>
<ide> /**
<del> * @constructor
<ide> * @implements IPDFTextLayerFactory
<ide> */
<del>function DefaultTextLayerFactory() {}
<del>DefaultTextLayerFactory.prototype = {
<add>class DefaultTextLayerFactory {
<ide> /**
<ide> * @param {HTMLDivElement} textLayerDiv
<ide> * @param {number} pageIndex
<ide> DefaultTextLayerFactory.prototype = {
<ide> viewport,
<ide> enhanceTextSelection,
<ide> });
<del> },
<del>};
<add> }
<add>}
<ide>
<ide> export {
<ide> TextLayerBuilder, | 1 |
Ruby | Ruby | call #to_trix_html on rich_text_area_tag value | adc5eb66f861a98da32f7c682155360d5b9a4a52 | <ide><path>actiontext/app/helpers/action_text/tag_helper.rb
<ide> def rich_text_area_tag(name, value = nil, options = {})
<ide> options[:data][:blob_url_template] = main_app.rails_service_blob_url(":signed_id", ":filename")
<ide>
<ide> editor_tag = content_tag("trix-editor", "", options)
<del> input_tag = hidden_field_tag(name, value, id: options[:input])
<add> input_tag = hidden_field_tag(name, value.try(:to_trix_html) || value, id: options[:input])
<ide>
<ide> input_tag + editor_tag
<ide> end
<ide> def render
<ide> options = @options.stringify_keys
<ide> add_default_name_and_id(options)
<ide> options["input"] ||= dom_id(object, [options["id"], :trix_input].compact.join("_")) if object
<del> @template_object.rich_text_area_tag(options.delete("name"), options.fetch("value") { editable_value }, options.except("value"))
<del> end
<del>
<del> def editable_value
<del> value&.body.try(:to_trix_html)
<add> @template_object.rich_text_area_tag(options.delete("name"), options.fetch("value") { value }, options.except("value"))
<ide> end
<ide> end
<ide>
<ide><path>actiontext/app/models/action_text/rich_text.rb
<ide> def to_plain_text
<ide> body&.to_plain_text.to_s
<ide> end
<ide>
<add> def to_trix_html
<add> body&.to_trix_html
<add> end
<add>
<ide> delegate :blank?, :empty?, :present?, to: :to_plain_text
<ide> end
<ide> end
<ide><path>actiontext/test/template/form_helper_test.rb
<ide> def form_with(*, **)
<ide> )
<ide> end
<ide>
<add> test "rich text area tag" do
<add> message = Message.new
<add>
<add> form_with model: message, scope: :message do |form|
<add> rich_text_area_tag :content, message.content, { input: "trix_input_1" }
<add> end
<add>
<add> assert_dom_equal \
<add> '<form action="/messages" accept-charset="UTF-8" data-remote="true" method="post">' \
<add> '<input type="hidden" name="content" id="trix_input_1" />' \
<add> '<trix-editor input="trix_input_1" class="trix-content" data-direct-upload-url="http://test.host/rails/active_storage/direct_uploads" data-blob-url-template="http://test.host/rails/active_storage/blobs/redirect/:signed_id/:filename">' \
<add> "</trix-editor>" \
<add> "</form>",
<add> output_buffer
<add> end
<add>
<ide> test "form with rich text area" do
<ide> form_with model: Message.new, scope: :message do |form|
<ide> form.rich_text_area :content
<ide> def form_with(*, **)
<ide>
<ide> test "modelless form with rich text area" do
<ide> form_with url: "/messages", scope: :message do |form|
<del> form.rich_text_area :content
<add> form.rich_text_area :content, { input: "trix_input_2" }
<ide> end
<ide>
<ide> assert_dom_equal \
<ide> '<form action="/messages" accept-charset="UTF-8" data-remote="true" method="post">' \
<del> '<input type="hidden" name="message[content]" id="trix_input_1" />' \
<del> '<trix-editor id="message_content" input="trix_input_1" class="trix-content" data-direct-upload-url="http://test.host/rails/active_storage/direct_uploads" data-blob-url-template="http://test.host/rails/active_storage/blobs/redirect/:signed_id/:filename">' \
<add> '<input type="hidden" name="message[content]" id="trix_input_2" />' \
<add> '<trix-editor id="message_content" input="trix_input_2" class="trix-content" data-direct-upload-url="http://test.host/rails/active_storage/direct_uploads" data-blob-url-template="http://test.host/rails/active_storage/blobs/redirect/:signed_id/:filename">' \
<ide> "</trix-editor>" \
<ide> "</form>",
<ide> output_buffer | 3 |
Javascript | Javascript | remove outdated unittests | ef7f142fb363c289b00cbe22810902600f575e99 | <ide><path>test/ExternalModule.unittest.js
<ide> module.exports = some/request;`;
<ide> hashedText += text;
<ide> }
<ide> };
<del> externalModule.optional = true;
<ide> externalModule.id = 12345678;
<ide> externalModule.updateHash(hash);
<ide> });
<ide> module.exports = some/request;`;
<ide> it("updates hash with type", function() {
<ide> hashedText.should.containEql("some-type");
<ide> });
<del> it("updates hash with optional flag", function() {
<del> hashedText.should.containEql("true");
<del> });
<ide> it("updates hash with module id", function() {
<ide> hashedText.should.containEql("12345678");
<ide> });
<ide><path>test/RequireJsStuffPlugin.unittest.js
<del>"use strict";
<del>
<del>const should = require("should");
<del>const sinon = require("sinon");
<del>const RequireJsStuffPlugin = require("../lib/RequireJsStuffPlugin");
<del>const applyPluginWithOptions = require("./helpers/applyPluginWithOptions");
<del>const PluginEnvironment = require("./helpers/PluginEnvironment");
<del>
<del>describe("RequireJsStuffPlugin", () => {
<del> it("has apply function", () => (new RequireJsStuffPlugin()).apply.should.be.a.Function());
<del>
<del> describe("when applied", () => {
<del> let eventBindings;
<del> let eventBinding;
<del>
<del> beforeEach(() => eventBindings = applyPluginWithOptions(RequireJsStuffPlugin));
<del>
<del> it("binds one event handler", () => eventBindings.length.should.be.exactly(1));
<del>
<del> describe("compilation handler", () => {
<del> beforeEach(() => eventBinding = eventBindings[0]);
<del>
<del> it("binds to compilation event", () => eventBinding.name.should.be.exactly("compilation"));
<del>
<del> describe("when called", () => {
<del> let pluginEnvironment;
<del> let compilationEventBindings;
<del> let compilation;
<del>
<del> beforeEach(() => {
<del> pluginEnvironment = new PluginEnvironment();
<del> compilation = {
<del> dependencyFactories: {
<del> set: sinon.spy()
<del> },
<del> dependencyTemplates: {
<del> set: sinon.spy()
<del> }
<del> };
<del> const params = {
<del> normalModuleFactory: pluginEnvironment.getEnvironmentStub()
<del> };
<del> eventBinding.handler(compilation, params);
<del> compilationEventBindings = pluginEnvironment.getEventBindings();
<del> });
<del>
<del> it("sets the dependency factory", () =>
<del> compilation.dependencyFactories.set.callCount.should.be.exactly(1));
<del>
<del> it("sets the dependency template", () =>
<del> compilation.dependencyTemplates.set.callCount.should.be.exactly(1));
<del>
<del> it("binds one event handler", () => compilationEventBindings.length.should.be.exactly(1));
<del>
<del> describe("parser handler", () => {
<del> let parser;
<del> let parserEventBindings;
<del> let compilationEventBinding;
<del>
<del> beforeEach(() => {
<del> compilationEventBinding = compilationEventBindings[0];
<del> pluginEnvironment = new PluginEnvironment();
<del> parser = pluginEnvironment.getEnvironmentStub();
<del> });
<del>
<del> it("binds to parser event", () => compilationEventBinding.name.should.be.exactly("parser"));
<del>
<del> describe("when called with parser options of requirejs as false", () => {
<del> beforeEach(() => {
<del> compilationEventBinding.handler(parser, {
<del> requireJs: false
<del> });
<del> parserEventBindings = pluginEnvironment.getEventBindings();
<del> });
<del>
<del> it("binds no event handlers", () => parserEventBindings.length.should.be.exactly(0));
<del> });
<del>
<del> describe("when called with empty parser options", () => {
<del> let parserEventBinding;
<del> let parserEventContext;
<del> let expressionMock;
<del>
<del> beforeEach(() => {
<del> parserEventContext = {
<del> state: {
<del> current: {
<del> addDependency: sinon.spy()
<del> }
<del> }
<del> };
<del> expressionMock = {
<del> range: 10,
<del> loc: 5
<del> };
<del> compilationEventBinding.handler(parser, {});
<del> parserEventBindings = pluginEnvironment.getEventBindings();
<del> });
<del>
<del> it("binds four event handlers", () => parserEventBindings.length.should.be.exactly(4));
<del>
<del> describe("'call require.config' handler", () => {
<del> beforeEach(() => parserEventBinding = parserEventBindings[0]);
<del>
<del> it("binds to 'call require.config' event", () =>
<del> parserEventBinding.name.should.be.exactly("call require.config"));
<del>
<del> describe("when called", () => {
<del> beforeEach(() =>
<del> parserEventBinding.handler.call(parserEventContext, expressionMock));
<del>
<del> it("adds dependency to current state", () => {
<del> const addDependencySpy = parserEventContext.state.current.addDependency;
<del> const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<del> addDependencySpy.callCount.should.be.exactly(1);
<del> addedDependency.should.be.exactly('{"module":null,"weak":false,"expression":"undefined","range":10,"loc":5}');
<del> });
<del> });
<del> });
<del>
<del> describe("'call requirejs.config' handler", () => {
<del> beforeEach(() => parserEventBinding = parserEventBindings[1]);
<del>
<del> it("binds to 'call requirejs.config' event", () =>
<del> parserEventBinding.name.should.be.exactly("call requirejs.config"));
<del>
<del> describe("when called", () => {
<del> beforeEach(() =>
<del> parserEventBinding.handler.call(parserEventContext, expressionMock));
<del>
<del> it("adds dependency to current state", () => {
<del> const addDependencySpy = parserEventContext.state.current.addDependency;
<del> const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<del> addDependencySpy.callCount.should.be.exactly(1);
<del> addedDependency.should.be.exactly('{"module":null,"weak":false,"expression":"undefined","range":10,"loc":5}');
<del> });
<del> });
<del> });
<del>
<del> describe("'expression require.version' handler", () => {
<del> beforeEach(() => parserEventBinding = parserEventBindings[2]);
<del>
<del> it("binds to 'expression require.version' event", () =>
<del> parserEventBinding.name.should.be.exactly("expression require.version"));
<del>
<del> describe("when called", () => {
<del> beforeEach(() =>
<del> parserEventBinding.handler.call(parserEventContext, expressionMock));
<del>
<del> it("adds dependency to current state", () => {
<del> const addDependencySpy = parserEventContext.state.current.addDependency;
<del> const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<del> addDependencySpy.callCount.should.be.exactly(1);
<del> addedDependency.should.be.exactly('{"module":null,"weak":false,"expression":"\\"0.0.0\\"","range":10,"loc":5}');
<del> });
<del> });
<del> });
<del>
<del> describe("'expression requirejs.onError' handler", () => {
<del> beforeEach(() => parserEventBinding = parserEventBindings[3]);
<del>
<del> it("binds to 'expression requirejs.onError' event", () =>
<del> parserEventBinding.name.should.be.exactly("expression requirejs.onError"));
<del>
<del> describe("when called", () => {
<del> beforeEach(() =>
<del> parserEventBinding.handler.call(parserEventContext, expressionMock));
<del>
<del> it("adds dependency to current state", () => {
<del> const addDependencySpy = parserEventContext.state.current.addDependency;
<del> const addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<del> addDependencySpy.callCount.should.be.exactly(1);
<del> addedDependency.should.be.exactly('{"module":null,"weak":false,"expression":"__webpack_require__.oe","range":10,"loc":5}');
<del> });
<del> });
<del> });
<del> });
<del> });
<del> });
<del> });
<del> });
<del>}); | 2 |
Text | Text | clarify sti acronym | c18d522642b2570104ed2a58336ea2966e7a58b7 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> While applications should stick to that interface, the actual Zeitwerk loader ob
<ide> Rails.autoloaders.main
<ide> ```
<ide>
<del>That may be handy if you need to preload STIs or configure a custom inflector, for example.
<add>That may be handy if you need to preload Single Table Inheritance (STI) classes or configure a custom inflector, for example.
<ide>
<ide> #### Project Structure
<ide>
<ide> All is good!
<ide>
<ide> All known use cases of `require_dependency` have been eliminated, you should grep the project and delete them.
<ide>
<del>If your application has STIs, please check their section in the guide [Autoloading and Reloading Constants (Zeitwerk Mode)](autoloading_and_reloading_constants.html#single-table-inheritance).
<add>If your application uses Single Table Inheritance, please see the [Single Table Inheritance section](autoloading_and_reloading_constants.html#single-table-inheritance) of the Autoloading and Reloading Constants (Zeitwerk Mode) guide.
<ide>
<ide> #### Qualified names in class and module definitions
<ide> | 1 |
Javascript | Javascript | extract ember.isempty into ember-metal | d232a68ead674ce5a507a5ab6e86d8499a5ba3c1 | <ide><path>packages/ember-metal/lib/computed.js
<ide> Ember.computed.not = function(dependentKey) {
<ide> Ember.computed.empty = function(dependentKey) {
<ide> return Ember.computed(dependentKey, function(key) {
<ide> var val = get(this, dependentKey);
<del> return val === undefined || val === null || val === '' || (Ember.isArray(val) && get(val, 'length') === 0);
<add> return Ember.isEmpty(val);
<ide> });
<ide> };
<ide>
<ide><path>packages/ember-metal/lib/core.js
<ide> Ember.merge = function(original, updates) {
<ide> original[prop] = updates[prop];
<ide> }
<ide> };
<add>/**
<add> Verifies that a value is `null` or an empty string, empty array,
<add> or empty function.
<add>
<add> Constrains the rules on `Ember.isNone` by returning false for empty
<add> string and empty arrays.
<add>
<add> ```javascript
<add> Ember.isEmpty(); // true
<add> Ember.isEmpty(null); // true
<add> Ember.isEmpty(undefined); // true
<add> Ember.isEmpty(''); // true
<add> Ember.isEmpty([]); // true
<add> Ember.isEmpty('Adam Hawkins'); // false
<add> Ember.isEmpty([0,1,2]); // false
<add> ```
<add>
<add> @method isEmpty
<add> @for Ember
<add> @param {Object} obj Value to test
<add> @return {Boolean}
<add>*/
<add>Ember.isEmpty = function(obj) {
<add> return obj === null || obj === undefined || (obj.length === 0 && typeof obj !== 'function') || (typeof obj === 'object' && Ember.get(obj, 'length') === 0);
<add>};
<add>Ember.empty = Ember.deprecateFunc("Ember.empty is deprecated. Please use Ember.isEmpty instead.", Ember.isEmpty) ;
<add>
<add><path>packages/ember-metal/tests/core/is_empty_test.js
<del><path>packages/ember-runtime/tests/core/isEmpty_test.js
<ide> module("Ember.isEmpty");
<ide>
<ide> test("Ember.isEmpty", function() {
<ide> var string = "string", fn = function() {},
<del> object = {length: 0},
<del> arrayProxy = Ember.ArrayProxy.create({ content: Ember.A([]) });
<add> object = {length: 0};
<ide>
<ide> equal(true, Ember.isEmpty(null), "for null");
<ide> equal(true, Ember.isEmpty(undefined), "for undefined");
<ide> test("Ember.isEmpty", function() {
<ide> equal(true, Ember.isEmpty([]), "for an empty Array");
<ide> equal(false, Ember.isEmpty({}), "for an empty Object");
<ide> equal(true, Ember.isEmpty(object), "for an Object that has zero 'length'");
<del> equal(true, Ember.isEmpty(arrayProxy), "for an ArrayProxy that has empty content");
<ide> });
<ide><path>packages/ember-runtime/lib/core.js
<ide> Ember.isNone = function(obj) {
<ide> };
<ide> Ember.none = Ember.deprecateFunc("Ember.none is deprecated. Please use Ember.isNone instead.", Ember.isNone);
<ide>
<del>/**
<del> Verifies that a value is `null` or an empty string, empty array,
<del> or empty function.
<del>
<del> Constrains the rules on `Ember.isNone` by returning false for empty
<del> string and empty arrays.
<del>
<del> ```javascript
<del> Ember.isEmpty(); // true
<del> Ember.isEmpty(null); // true
<del> Ember.isEmpty(undefined); // true
<del> Ember.isEmpty(''); // true
<del> Ember.isEmpty([]); // true
<del> Ember.isEmpty('Adam Hawkins'); // false
<del> Ember.isEmpty([0,1,2]); // false
<del> ```
<del>
<del> @method isEmpty
<del> @for Ember
<del> @param {Object} obj Value to test
<del> @return {Boolean}
<del>*/
<del>Ember.isEmpty = function(obj) {
<del> return obj === null || obj === undefined || (obj.length === 0 && typeof obj !== 'function') || (typeof obj === 'object' && Ember.get(obj, 'length') === 0);
<del>};
<del>Ember.empty = Ember.deprecateFunc("Ember.empty is deprecated. Please use Ember.isEmpty instead.", Ember.isEmpty) ;
<del>
<del>/**
<ide> This will compare two javascript values of possibly different types.
<ide> It will tell you which one is greater than the other by returning:
<ide>
<ide><path>packages/ember-runtime/tests/core/is_empty_test.js
<add>require('ember-metal/core');
<add>module("Ember.isEmpty");
<add>
<add>test("Ember.isEmpty", function() {
<add> var arrayProxy = Ember.ArrayProxy.create({ content: Ember.A([]) });
<add>
<add> equal(true, Ember.isEmpty(arrayProxy), "for an ArrayProxy that has empty content");
<add>}); | 5 |
Text | Text | move forrest norvell to collaborator emeriti list | d33fddb7f43fffedb4f33f62e3d7b2af8a40f60b | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Ali Ijaz Sheikh** <ofrobots@google.com> (he/him)
<ide> * [orangemocha](https://github.com/orangemocha) -
<ide> **Alexis Campailla** <orangemocha@nodejs.org>
<del>* [othiym23](https://github.com/othiym23) -
<del>**Forrest L Norvell** <ogd@aoaioxxysz.net> (he/him)
<ide> * [oyyd](https://github.com/oyyd) -
<ide> **Ouyang Yadong** <oyydoibh@gmail.com> (he/him)
<ide> * [pmq20](https://github.com/pmq20) -
<ide> For information about the governance of the Node.js project, see
<ide> **Christopher Monsanto** <chris@monsan.to>
<ide> * [Olegas](https://github.com/Olegas) -
<ide> **Oleg Elifantiev** <oleg@elifantiev.ru>
<add>* [othiym23](https://github.com/othiym23) -
<add>**Forrest L Norvell** <ogd@aoaioxxysz.net> (he/him)
<ide> * [petkaantonov](https://github.com/petkaantonov) -
<ide> **Petka Antonov** <petka_antonov@hotmail.com>
<ide> * [phillipj](https://github.com/phillipj) - | 1 |
Javascript | Javascript | fix bug when codemirror return function object | 856874a7272e2ec2f2eadd307664fb3c9b585409 | <ide><path>client/commonFramework/output-display.js
<ide> window.common = (function(global) {
<ide> codeOutput.setSize('100%', '100%');
<ide>
<ide> common.updateOutputDisplay = function updateOutputDisplay(str = '') {
<add> if (typeof str === 'function') {
<add> str = str.toString();
<add> }
<ide> if (typeof str !== 'string') {
<ide> str = JSON.stringify(str);
<ide> } | 1 |
Python | Python | create spiralprint.py (#844) | be4150c720187391488786053ac7a13eeb965446 | <ide><path>matrix/spiralPrint.py
<add>"""
<add>This program print the matix in spiral form.
<add>This problem has been solved through recursive way.
<add>
<add> Matrix must satisfy below conditions
<add> i) matrix should be only one or two dimensional
<add> ii)column of all the row should be equal
<add>"""
<add>def checkMatrix(a):
<add> # must be
<add> if type(a) == list and len(a) > 0:
<add> if type(a[0]) == list:
<add> prevLen = 0
<add> for i in a:
<add> if prevLen == 0:
<add> prevLen = len(i)
<add> result = True
<add> elif prevLen == len(i):
<add> result = True
<add> else:
<add> result = False
<add> else:
<add> result = True
<add> else:
<add> result = False
<add> return result
<add>
<add>
<add>def spiralPrint(a):
<add>
<add> if checkMatrix(a) and len(a) > 0:
<add>
<add> matRow = len(a)
<add> if type(a[0]) == list:
<add> matCol = len(a[0])
<add> else:
<add> for dat in a:
<add> print(dat),
<add> return
<add>
<add> # horizotal printing increasing
<add> for i in range(0, matCol):
<add> print(a[0][i]),
<add> # vertical printing down
<add> for i in range(1, matRow):
<add> print(a[i][matCol - 1]),
<add> # horizotal printing decreasing
<add> if matRow > 1:
<add> for i in range(matCol - 2, -1, -1):
<add> print(a[matRow - 1][i]),
<add> # vertical printing up
<add> for i in range(matRow - 2, 0, -1):
<add> print(a[i][0]),
<add> remainMat = [row[1:matCol - 1] for row in a[1:matRow - 1]]
<add> if len(remainMat) > 0:
<add> spiralPrint(remainMat)
<add> else:
<add> return
<add> else:
<add> print("Not a valid matrix")
<add> return
<add>
<add>
<add># driver code
<add>a = [[1 , 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
<add>spiralPrint(a) | 1 |
Javascript | Javascript | use the english json as the schema | e7aa1c5d626f606bbe47769d8383b452daf31834 | <ide><path>client/i18n/intro-schema.js
<del>/* eslint-disable camelcase */
<del>/* This is used for testing. If an intro.json file doesn't match the
<del> * structure here exactly, the tests will fail.
<del> */
<del>const introSchema = {
<del> 'responsive-web-design': {
<del> title: 'Responsive Web Design',
<del> intro: [
<del> "In this Responsive Web Design Certification, you'll learn the languages that developers use to build webpages: HTML (Hypertext Markup Language) for content, and CSS (Cascading Style Sheets) for design.",
<del> "First, you'll build a cat photo app to learn the basics of HTML and CSS. Later, you'll learn modern techniques like CSS variables by building a penguin, and best practices for accessibility by building a web form.",
<del> "Finally, you'll learn how to make webpages that respond to different screen sizes by building a Twitter card with Flexbox, and a complex blog layout with CSS Grid."
<del> ],
<del> blocks: {
<del> 'basic-html-and-html5': {
<del> title: 'Basic HTML and HTML5',
<del> intro: [
<del> 'HTML is a markup language that uses a special syntax or notation to describe the structure of a webpage to the browser. HTML elements usually have opening and closing tags that surround and give meaning to content. For example, different elements can describe text as a heading, paragraph, or list item.',
<del> "In this course, you'll build a cat photo app to learn some of the most common HTML elements — the building blocks of any webpage."
<del> ]
<del> },
<del> 'basic-css': {
<del> title: 'Basic CSS',
<del> intro: [
<del> 'CSS, or Cascading Style Sheets, tell the browser how to display the text and other content that you write in HTML. With CSS, you can control the color, font, size, spacing, and many other aspects of HTML elements.',
<del> "Now that you've described the structure of your cat photo app, give it some style with CSS."
<del> ]
<del> },
<del> 'applied-visual-design': {
<del> title: 'Applied Visual Design',
<del> intro: [
<del> 'Visual design is a combination of typography, color theory, graphics, animation, page layout, and more to help deliver your unique message.',
<del> "In this course, you'll learn how to apply these different elements of visual design to your webpages."
<del> ]
<del> },
<del> 'applied-accessibility': {
<del> title: 'Applied Accessibility',
<del> intro: [
<del> 'In web development, accessibility refers to web content and a UI (user interface) that can be understood, navigated, and interacted with by a broad audience. This includes people with visual, auditory, mobility, or cognitive disabilities.',
<del> "In this course, you'll learn best practices for building webpages that are accessible to everyone."
<del> ]
<del> },
<del> 'responsive-web-design-principles': {
<del> title: 'Responsive Web Design Principles',
<del> intro: [
<del> 'There are many devices that can access the web, and they come in all shapes and sizes. Responsive web design is the practice of designing flexible websites that can respond to different screen sizes, orientations, and resolutions.',
<del> "In this course, you'll learn how to use CSS to make your webpages look good, no matter what device they're viewed on."
<del> ]
<del> },
<del> 'css-flexbox': {
<del> title: 'CSS Flexbox',
<del> intro: [
<del> "Flexbox is a powerful, well-supported layout method that was introduced with the latest version of CSS, CSS3. With flexbox, it's easy to center elements on the page and create dynamic user interfaces that shrink and expand automatically.",
<del> "In this course, you'll learn the fundamentals of flexbox and dynamic layouts by building a Twitter card."
<del> ]
<del> },
<del> 'css-grid': {
<del> title: 'CSS Grid',
<del> intro: [
<del> 'The CSS grid is a newer standard that makes it easy to build complex responsive layouts. It works by turning an HTML element into a grid, and lets you place child elements anywhere within.',
<del> "In this course, you'll learn the fundamentals of CSS grid by building different complex layouts, including a blog."
<del> ]
<del> },
<del> 'responsive-web-design-projects': {
<del> title: 'Responsive Web Design Projects',
<del> intro: [
<del> 'Time to put your newly learnt skills to work. By working on these projects, you will get a chance to apply all of the skills, principles, and concepts you have learned so far: HTML, CSS, Visual Design, Accessibility, and more.',
<del> 'Complete the five web programming projects below to earn your Responsive Web Design certification.'
<del> ]
<del> },
<del> 'basic-html-cat-photo-app': {
<del> title: 'Basic HTML Cat Photo App',
<del> intro: ['placeholder', 'placeholder']
<del> },
<del> 'basic-css-cafe-menu': {
<del> title: 'Basic CSS Cafe Menu',
<del> intro: ['placeholder', 'placeholder']
<del> },
<del> 'css-variables-skyline': {
<del> title: 'CSS Variables Skyline',
<del> intro: ['placeholder', 'placeholder']
<del> }
<del> }
<del> },
<del> 'javascript-algorithms-and-data-structures': {
<del> title: 'JavaScript Algorithms and Data Structures',
<del> intro: [
<del> "While HTML and CSS control the content and styling of a page, JavaScript is used to make it interactive. In the JavaScript Algorithm and Data Structures Certification, you'll learn the fundamentals of JavaScript including variables, arrays, objects, loops, and functions.",
<del> "Once you have the fundamentals down, you'll apply that knowledge by creating algorithms to manipulate strings, factorialize numbers, and even calculate the orbit of the International Space Station.",
<del> "Along the way, you'll also learn two important programing styles or paradigms: Object Oriented Programing (OOP), and Functional Programing (FP)."
<del> ],
<del> blocks: {
<del> 'basic-javascript': {
<del> title: 'Basic JavaScript',
<del> intro: [
<del> 'JavaScript is a scripting language you can use to make web pages interactive. It is one of the core technologies of the web, along with HTML and CSS, and is supported by all modern browsers.',
<del> "In this course, you'll learn fundamental programming concepts in JavaScript. You'll start with basic data structures like numbers and strings. Then you'll learn to work with arrays, objects, functions, loops, if/else statements, and more."
<del> ]
<del> },
<del> es6: {
<del> title: 'ES6',
<del> intro: [
<del> 'ECMAScript, or ES, is a standardized version of JavaScript. Because all major browsers follow this specification, the terms ECMAScript and JavaScript are interchangeable.',
<del> "Most of the JavaScript you've learned up to this point was in ES5 (ECMAScript 5), which was finalized in 2009. While you can still write programs in ES5, JavaScript is always evolving, and new features are released every year.",
<del> "ES6, released in 2015, added many powerful new features to the language. In this course, you'll learn these new features, including <code>let</code> and <code>const</code>, arrow functions, classes, promises, and modules."
<del> ]
<del> },
<del> 'regular-expressions': {
<del> title: 'Regular Expressions',
<del> intro: [
<del> 'Regular expressions, often shortened to "regex" or "regexp", are patterns that help programmers match, search, and replace text. Regular expressions are very powerful, but can be hard to read because they use special characters to make more complex, flexible matches.',
<del> "In this course, you'll learn how to use special characters, capture groups, positive and negative lookaheads, and other techniques to match any text you want."
<del> ]
<del> },
<del> debugging: {
<del> title: 'Debugging',
<del> intro: [
<del> 'Debugging is the process of going through your code, finding any issues, and fixing them.',
<del> "Issues in code generally come in three forms: syntax errors that prevent your program from running, runtime errors where your code has unexpected behavior, or logical errors where your code doesn't do what you intended.",
<del> "In this course, you'll learn how to use the JavaScript console to debug programs and prevent common issues before they happen."
<del> ]
<del> },
<del> 'basic-data-structures': {
<del> title: 'Basic Data Structures',
<del> intro: [
<del> 'Data can be stored and accessed in many ways. You already know some common JavaScript data structures — arrays and objects.',
<del> "In this Basic Data Structures course, you'll learn more about the differences between arrays and objects, and which to use in different situations. You'll also learn how to use helpful JS methods like <code>splice()</code> and <code>Object.keys()</code> to access and manipulate data."
<del> ]
<del> },
<del> 'basic-algorithm-scripting': {
<del> title: 'Basic Algorithm Scripting',
<del> intro: [
<del> 'An algorithm is a series of step-by-step instructions that describe how to do something.',
<del> 'To write an effective algorithm, it helps to break a problem down into smaller parts, and think carefully about how to solve each part with code.',
<del> "In this course, you'll learn the fundamentals of algorithmic thinking by writing algorithms that do everything from converting temperatures to handling complex 2D arrays."
<del> ]
<del> },
<del> 'object-oriented-programming': {
<del> title: 'Object Oriented Programming',
<del> intro: [
<del> 'OOP, or Object Oriented Programming, is one of the major approaches to the software development process. In OOP, objects and classes are used to organize code to describe things and what they can do.',
<del> "In this course, you'll learn the basic principles of OOP in JavaScript including the <code>this</code> keyword, prototype chains, constructors, and inheritance."
<del> ]
<del> },
<del> 'functional-programming': {
<del> title: 'Functional Programming',
<del> intro: [
<del> 'Functional Programming is another popular approach to software development. In Functional Programming, code is organized into smaller, basic functions that can be combined to build complex programs.',
<del> "In this course, you'll learn the core concepts of Functional Programming including pure functions, how to avoid mutations, and how write cleaner code with methods like <code>.map()</code> and <code>.filter()</code>."
<del> ]
<del> },
<del> 'intermediate-algorithm-scripting': {
<del> title: 'Intermediate Algorithm Scripting',
<del> intro: [
<del> 'Now that you know the basics of algorithmic thinking, along with OOP and Functional Programming, test your skills with the Intermediate Algorithm Scripting challenges.'
<del> ]
<del> },
<del> 'javascript-algorithms-and-data-structures-projects': {
<del> title: 'JavaScript Algorithms and Data Structures Projects',
<del> intro: [
<del> "This is it — time to put your new JavaScript skills to work. These projects are similar to the algorithm scripting challenges you've done before – just much more difficult.",
<del> 'Complete these 5 JavaScript projects to earn the JavaScript Algorithms and Data Structures certification.'
<del> ]
<del> },
<del> 'basic-javascript-rpg-game': {
<del> title: 'Basic JavaScript RPG Game',
<del> intro: ['placeholder', 'placeholder']
<del> },
<del> 'intermediate-javascript-calorie-counter': {
<del> title: 'Intermediate JavaScript Calorie Counter',
<del> intro: ['placeholder', 'placeholder']
<del> },
<del> 'functional-programming-spreadsheet': {
<del> title: 'Functional Programming Spreadsheet',
<del> intro: ['placeholder', 'placeholder']
<del> }
<del> }
<del> },
<del> 'front-end-libraries': {
<del> title: 'Front End Development Libraries',
<del> intro: [
<del> "Now that you're familiar with HTML, CSS, and JavaScript, level up your skills by learning some of the most popular front end libraries in the industry.",
<del> "In the Front End Libraries Certification, you'll learn how to style your site quickly with Bootstrap. You'll also learn how add logic to your CSS styles and extend them with Sass.",
<del> "Later, you'll build a shopping cart and other applications to learn how to create powerful Single Page Applications (SPAs) with React and Redux."
<del> ],
<del> blocks: {
<del> bootstrap: {
<del> title: 'Bootstrap',
<del> intro: [
<del> 'Bootstrap is a front end framework used to design responsive web pages and applications. It takes a mobile-fist approach to web development, and includes pre-built CSS styles and classes, plus some JavaScript functionality.',
<del> "In this course, you'll learn how to build responsive websites with Bootstrap, and use its included classes to style buttons, images, forms, navigation, and other common elements."
<del> ]
<del> },
<del> jquery: {
<del> title: 'jQuery',
<del> intro: [
<del> 'jQuery is one of the most widely used JavaScript libraries in the world.',
<del> 'In 2006 when it was released, all major browsers handled JavaScript slightly differently. jQuery simplified the process of writing client-side JavaScript, and also ensured that your code worked the same way in all browsers.',
<del> "In this course, you'll learn how to use jQuery to select, remove, clone, and modify different elements on the page."
<del> ]
<del> },
<del> sass: {
<del> title: 'SASS',
<del> intro: [
<del> 'Sass, or "Syntactically Awesome StyleSheets", is a language extension of CSS. It adds features that aren\'t available in basic CSS, which make it easier for you to simplify and maintain the style sheets for your projects.',
<del> "In this Sass course, you'll learn how to store data in variables, nest CSS, create reusable styles with mixins, add logic and loops to your styles, and more."
<del> ]
<del> },
<del> react: {
<del> title: 'React',
<del> intro: [
<del> 'React is a popular JavaScript library for building reusable, component-driven user interfaces for web pages or applications.',
<del> 'React combines HTML with JavaScript functionality into its own markup language called JSX. React also makes it easy to manage the flow of data throughout the application.',
<del> "In this course, you'll learn how to create different React components, manage data in the form of state props, use different lifecycle methods like <code>componentDidMount</code>, and much more."
<del> ]
<del> },
<del> redux: {
<del> title: 'Redux',
<del> intro: [
<del> 'As applications grow in size and scope, managing shared data becomes much more difficult. Redux is defined as a "predictable state container for JavaScript apps" that helps ensure your apps work predictably, and are easier to test.',
<del> 'While you can use Redux with any view library, we introduce Redux here before combining it with React in the next set of courses.',
<del> "In this course, you'll learn the fundamentals of Redux stores, actions, reducers and middleware to manage data throughout your application."
<del> ]
<del> },
<del> 'react-and-redux': {
<del> title: 'React and Redux',
<del> intro: [
<del> 'React and Redux are often mentioned together, and with good reason. The developer who created Redux was a React developer who wanted to make it easier to share data across different components.',
<del> "Now that you know how to manage the flow of shared data with Redux, it's time to combine that knowledge with React. In the React and Redux courses, you'll build a React component and learn how to manage state locally at the component level, and throughout the entire application with Redux."
<del> ]
<del> },
<del> 'front-end-libraries-projects': {
<del> title: 'Front End Development Libraries Projects',
<del> intro: [
<del> "It's time to put your front end development libraries skills to the test. Use Bootstrap, jQuery, Sass, React, and Redux to build 5 projects that will test everything you've learned up to this point.",
<del> "Complete all 5 projects, and you'll earn the Front End Development Libraries certification."
<del> ]
<del> }
<del> }
<del> },
<del> 'data-visualization': {
<del> title: 'Data Visualization',
<del> intro: [
<del> "Data is all around us, but it doesn't mean much without shape or context.",
<del> "In the Data Visualization Certification, you'll build charts, graphs, and maps to present different types of data with the D3.js library.",
<del> "You'll also learn about JSON (JavaScript Object Notation), and how to work with data online using an API (Application Programing Interface)."
<del> ],
<del> blocks: {
<del> 'data-visualization-with-d3': {
<del> title: 'Data Visualization with D3',
<del> intro: [
<del> "D3, or D3.js, stands for Data Driven Documents. It's a JavaScript library for creating dynamic and interactive data visualizations in the browser.",
<del> 'D3 is built to work with common web standards – namely HTML, CSS, and Scalable Vector Graphics (SVG).',
<del> 'D3 supports many different kinds of input data formats. Then, using its powerful built-in methods, you can transform those data into different charts, graphs, and maps.',
<del> "In the Data Visualization with D3 courses, you'll learn how to work with data to create different charts, graphs, hover elements, and other ingredients to create dynamic and attractive data visualizations."
<del> ]
<del> },
<del> 'json-apis-and-ajax': {
<del> title: 'JSON APIs and AJAX',
<del> intro: [
<del> 'Similar to how UIs help people use programs, APIs (Application Programming Interfaces) help programs interact with other programs. APIs are tools that computers use to communicate with one another, in part to send and receive data.',
<del> 'Programmers often use AJAX (Asynchronous JavaScript and XML) when working with APIs. AJAX refers to a group of technologies that make asynchronous requests to a server to transfer data, then load any returned data into the page. And the data transferred between the browser and server is often in a format called JSON (JavaScript Object Notation).',
<del> 'This course will teach you the basics about working with APIs and different AJAX technologies in the browser.'
<del> ]
<del> },
<del> 'data-visualization-projects': {
<del> title: 'Data Visualization Projects',
<del> intro: [
<del> 'Now that you learned how to work with D3, APIs, and AJAX technologies, put your skills to the test with these 5 Data Visualization projects.',
<del> "In these projects, you'll need to fetch data and parse a dataset, then use D3 to create different data visualizations. Finish them all to earn your Data Visualization certification."
<del> ]
<del> },
<del> 'd3-dashboard': {
<del> title: 'D3 Dashboard',
<del> intro: ['placeholder', 'placeholder']
<del> }
<del> }
<del> },
<del> 'apis-and-microservices': {
<del> title: 'APIs and Microservices',
<del> intro: [
<del> "Until this point, you've only used JavaScript on the front end to add interactivity to a page, solve algorithm challenges, or build an SPA. But JavaScript can also be used on the back end, or server, to build entire web applications.",
<del> 'Today, one of the popular ways to build applications is through microservices, which are small, modular applications that work together to form a larger whole.',
<del> "In the APIs and Microservices Certification, you'll learn how to write back end-ready with Node.js and npm (Node Package Manager). You'll also build web applications with the Express framework, and build a People Finder microservice with MongoDB and the Mongoose library."
<del> ],
<del> blocks: {
<del> 'managing-packages-with-npm': {
<del> title: 'Managing Packages with NPM',
<del> intro: [
<del> "npm (Node Package Manager), is a command line tool to install, create, and share packages of JavaScript code written for Node.js. There are many open source packages available on npm, so before starting a project, take some time to explore so you don't end up recreating the wheel for things like working with dates or fetching data from an API.",
<del> "In this course, you'll learn the basics of using npm, including how to work with the <code>package.json</code> and how to manage your installed dependencies."
<del> ]
<del> },
<del> 'basic-node-and-express': {
<del> title: 'Basic Node and Express',
<del> intro: [
<del> 'Node.js is a JavaScript runtime that allows developers to write backend (server-side) programs in JavaScript. Node.js comes with a handful of built-in modules — small, independent programs — that help with this. Some of the core modules include HTTP, which acts like a server, and File System, a module to read and modify files.',
<del> 'In the last set of courses you learned to install and manage packages from npm, which are collections of smaller modules. These packages can help you build larger, more complex applications.',
<del> 'Express is a lightweight web application framework, and is one of the most popular packages on npm. Express makes it much easier to create a server and handle routing the routing for your application, which handles things like direct people to the correct page when they visit a certain endpoint like <pre>/blog</pre>.',
<del> "In this course, you'll learn the basics of Node and Express including how to create a server, serve different files, and handle different requests from the browser."
<del> ]
<del> },
<del> 'mongodb-and-mongoose': {
<del> title: 'MongoDB and Mongoose',
<del> intro: [
<del> 'MongoDB is a database application that stores JSON documents (or records) that you can use in your application. Unlike SQL, another type of database, Mongo is a non-relational or "NoSQL" database. This means Mongo stores all associated data within one record, instead of storing it across many preset tables as in a SQL database.',
<del> "Mongoose is a popular npm package that is often installed alongside Mongo. With Mongoose, you can use plain JavaScript objects instead of JSON, which makes it easier to work with Mongo. Also, it allows you to create blueprints for your documents called schemas, so you don't accidentally save the wrong type of data and cause bugs later.",
<del> "In the MongoDB and Mongoose courses, you'll learn the fundamentals of working with persistent data including how to set up a model, and save, delete, and find documents in the database."
<del> ]
<del> },
<del> 'apis-and-microservices-projects': {
<del> title: 'APIs and Microservices Projects',
<del> intro: [
<del> "You've worked with APIs before, but now that you know npm, Node, Express, MongoDB, and Mongoose, it's time to build your own. Draw on everything you've learned up to this point to create 5 different microservices, which are smaller applications that are limited in scope.",
<del> "After creating these, you'll have 5 cool microservice APIs you can show of to friends, family, and potential employers. Oh, and you'll have a shiny new APIs and Microservices Certification, too."
<del> ]
<del> }
<del> }
<del> },
<del> 'quality-assurance': {
<del> title: 'Quality Assurance',
<del> intro: [
<del> "As your programs or web applications become more complex, you'll want to test them to make sure that new changes don't break their original functionality.",
<del> "In the Quality Assurance Certification, you'll learn how to write to write tests with Chai to ensure your applications work the way you expect them to.",
<del> "Then you'll build a chat application to learn advanced Node and Express concepts. You'll also use Pug as a template engine, Passport for authentication, and Socket.io for real-time communication between the server and connected clients."
<del> ],
<del> blocks: {
<del> 'quality-assurance-and-testing-with-chai': {
<del> title: 'Quality Assurance and Testing with Chai',
<del> intro: [
<del> 'Chai is a JavaScript testing library that helps you confirm that your program still behaves the way you expect it to after you make changes to your code.',
<del> "Using Chai, you can write tests that describe your program's requirements and see if your program meets them.",
<del> "In this course, you'll learn about assertions, deep equality, truthiness, testing APIs, and other fundamentals for testing JavaScript applications."
<del> ]
<del> },
<del> 'advanced-node-and-express': {
<del> title: 'Advanced Node and Express',
<del> intro: [
<del> "Now it's time to take a deep dive into Node.js and Express.js by building a chat application with a sign-in system.",
<del> "To implement the sign-in system safely, you'll need to learn about authentication. This is the act of verifying the identity of a person or process.",
<del> "In this course, you'll learn how to use Passport to manage authentication, Pug to create reusable templates for quickly building the front end, and web sockets for real-time communication between the clients and server."
<del> ]
<del> },
<del> 'quality-assurance-projects': {
<del> title: 'Quality Assurance Projects',
<del> intro: [
<del> "Now that you're well versed in both the front end and back end, it's time to apply all the skills and concepts you've learned up to this point. You'll build 5 different web applications, and write tests for each one to make sure they're working and can handle different edge cases.",
<del> "After completing these Quality Assurance projects, you'll have 5 more projects under your belt, and a new certification to show off on your portfolio."
<del> ]
<del> }
<del> }
<del> },
<del> 'scientific-computing-with-python': {
<del> title: 'Scientific Computing with Python',
<del> intro: [
<del> 'Python is one of the most popular, flexible programming languages today. You can use it for everything from basic scripting to machine learning.',
<del> "In the Scientific Computing with Python Certification, you'll Python fundamentals like variables, loops, conditionals, and functions. Then you'll quickly ramp up to complex data structures, networking, relational databases, and data visualization."
<del> ],
<del> blocks: {
<del> 'python-for-everybody': {
<del> title: 'Python for Everybody',
<del> intro: [
<del> 'Python for everybody is a free video course series that teach the basics of using Python 3.',
<del> 'The courses were created by Dr. Charles Severance (also known as Dr. Chuck). He is a Clinical Professor at the University of Michigan School of Information, where he teaches various technology-oriented courses including programming, database design, and web development.'
<del> ]
<del> },
<del> 'scientific-computing-with-python-projects': {
<del> title: 'Scientific Computing with Python Projects',
<del> intro: [
<del> 'Time to put your Python skills to the test. By completing these projects, you will demonstrate that you have a good foundational knowledge of Python and qualify for the Scientific Computing with Python Certification.'
<del> ]
<del> }
<del> }
<del> },
<del> 'data-analysis-with-python': {
<del> title: 'Data Analysis with Python',
<del> intro: [
<del> 'Data Analysis has been around for a long time. But up until a few years ago, developers practiced it using expensive, closed-source tools like Tableau. But recently, Python, SQL, and other open libraries have changed Data Analysis forever.',
<del> "In the Data Analysis with Python Certification, you'll learn the fundamentals of data analysis with Python. By the end of this certification, you'll know how to read data from sources like CSVs and SQL, and how to use libraries like Numpy, Pandas, Matplotlib, and Seaborn to process and visualize data."
<del> ],
<del> blocks: {
<del> 'data-analysis-with-python-course': {
<del> title: 'Data Analysis with Python',
<del> intro: [
<del> "In these comprehensive video courses, created by Santiago Basulto, you will learn the whole process of data analysis. You'll reading data from multiple sources (CSV, SQL, Excel), process those data using NumPy and Pandas, and visualize them using Matplotlib and Seaborn,",
<del> "Additionally, we've included a thorough Jupyter Notebook course, and a quick Python reference to refresh your programming skills."
<del> ]
<del> },
<del> numpy: {
<del> title: 'Numpy',
<del> intro: [
<del> 'Learn the basics of the NumPy library in the following video course created by Keith Galli.',
<del> "In this course, you'll learn how NumPy works and how it compares to Python's built-in lists. You'll also learn how to write code with NumPy, indexing, reshaping, applied statistics, and much more."
<del> ]
<del> },
<del> 'data-analysis-with-python-projects': {
<del> title: 'Data Analysis with Python Projects',
<del> intro: [
<del> 'There are many ways to analyze data with Python. By completing these projects, you will demonstrate that you have a good foundational knowledge of data analysis with Python.',
<del> 'Finish them all to claim your Data Analysis with Python certification.'
<del> ]
<del> }
<del> }
<del> },
<del> 'information-security': {
<del> title: 'Information Security',
<del> intro: [
<del> "With everything we do online, there's a vast amount of sensitive information at risk: email addresses, passwords, phone numbers, and much more.",
<del> "With the Information Security Certification, you'll build a secure web app with HelmetJS to learn the fundamentals of protecting people's information online.",
<del> "You'll also build a TCP client, and an Nmap and port scanner in Python. This will help you learn the basics of penetration testing — an important component of good information security."
<del> ],
<del> blocks: {
<del> 'information-security-with-helmetjs': {
<del> title: 'Information Security with HelmetJS',
<del> intro: [
<del> 'This programming course focuses on HelmetJS, a type of middleware for Express-based applications that automatically sets HTTP headers. This way it can prevent sensitive information from unintentionally being passed between the server and client.',
<del> 'Completing the courses below will help you understand how to protect your website from malicious behavior.'
<del> ]
<del> },
<del> 'python-for-penetration-testing': {
<del> title: 'Python for Penetration Testing',
<del> intro: [
<del> 'These video courses teach you penetration testing with Python. Also known as a pen test, penetration testing is a simulated attack against a system to check for vulnerabilities.',
<del> "In this course, you'll learn about sockets, create a TCP server and client, build an Nmap scanner, and other tools and techniques that pen testers use daily."
<del> ]
<del> },
<del> 'information-security-projects': {
<del> title: 'Information Security Projects',
<del> intro: [
<del> "Now it’s time to put your new information security skills to work. These projects will give you a chance to apply the infosec skills, principles, and concepts you've learned.",
<del> 'When you are done, you will have plenty of information security projects under your belt, along with a certification that you can show off to friends, family, and employers.'
<del> ]
<del> }
<del> }
<del> },
<del> 'machine-learning-with-python': {
<del> title: 'Machine Learning with Python',
<del> intro: [
<del> 'Machine learning has many practical applications that you can use in your projects or on the job.',
<del> "In the Machine Learning with Python Certification, you'll use the TensorFlow framework to build several neural networks. A you'll explore more advanced techniques like natural language processing and reinforcement learning.",
<del> "You'll also dive into neural networks, and learn the principles behind how deep, recurrent, and convolutional neural networks work."
<del> ],
<del> blocks: {
<del> tensorflow: {
<del> title: 'Tensorflow',
<del> intro: [
<del> 'TensorFlow is an open source framework that makes machine learning and neural networking easier to use.',
<del> 'The following video course was created by Tim Ruscica, also known as “Tech With Tim”. It will help you to understand TensorFlow and some of its powerful capabilities.'
<del> ]
<del> },
<del> 'how-neural-networks-work': {
<del> title: 'How Neural Networks Work',
<del> intro: [
<del> "Neural networks are at the core of what we call artificial intelligence today. But historically they've been hard to understand. Especially for beginners in the machine learning field.",
<del> 'Even if you are completely new to neural networks, these video courses by Brandon Rohrer will get you comfortable with the concepts and the math behind them.'
<del> ]
<del> },
<del> 'machine-learning-with-python-projects': {
<del> title: 'Machine Learning with Python Projects',
<del> intro: [
<del> 'Machine learning has many practical applications. By completing these free and challenging coding projects, you will demonstrate that you have a good foundational knowledge of machine learning, and qualify for your Machine Learning with Python certification.'
<del> ]
<del> }
<del> }
<del> },
<del> 'coding-interview-prep': {
<del> title: 'Coding Interview Prep',
<del> intro: [
<del> "If you're looking for free coding exercises to prepare for your next job interview, we've got you covered.",
<del> 'This section contains hundreds of coding challenges that test your knowledge of algorithms, data structures, and mathematics. It also has a number of take-home projects you can use to strengthen your skills, or add to your portfolio.'
<del> ],
<del> blocks: {
<del> algorithms: {
<del> title: 'Algorithms',
<del> intro: [
<del> 'These free programming exercises will teach you about some common algorithms that you will likely encounter in real life. They are a great opportunity to improve your logic and programming skills.',
<del> "These algorithms are frequently used in job interviews to test a candidate's skills. We'll give you clear and concise explanations of how these different algorithms work so you can implement a solution for each one."
<del> ]
<del> },
<del> 'data-structures': {
<del> title: 'Data Structures',
<del> intro: [
<del> 'These free programming courses are meant to help you deal with large and complex data structures that you may not yet be familiar with.',
<del> 'Working through the courses below, you will learn about each type of data structure, and implement algorithms to reinforce your understanding of them.'
<del> ]
<del> },
<del> 'take-home-projects': {
<del> title: 'Take Home Projects',
<del> intro: [
<del> "Programming interviews have always been stressful. Job applicants are sometimes given a take home project to be completed outside of the interview. These types of interviews usually require a lot of work, but they're a great way for employers to see how you might perform on the job.",
<del> 'Build the bonus coding projects below for extra practice. Take your time, make them great, and put them on your resume or portfolio to show potential employers.'
<del> ]
<del> },
<del> 'rosetta-code': {
<del> title: 'Rosetta Code',
<del> intro: [
<del> 'Level up your creative problem solving skills with these free programming tasks from the classic Rosetta Code library.',
<del> 'These challenges can prove to be difficult, but they will push your algorithm logic to new heights.'
<del> ]
<del> },
<del> 'project-euler': {
<del> title: 'Project Euler',
<del> intro: [
<del> 'Complete the programming challenges below, from the massive Project Euler archives. These will harden your algorithm and mathematics knowledge.',
<del> 'These problems range in difficulty and, for many, the experience is inductive chain learning. That is, by solving one problem, it will expose you to a new concept that allows you to undertake a previously inaccessible problem. Can you finish them all?'
<del> ]
<del> }
<del> }
<del> },
<del> 'misc-text': {
<del> certification: '{{cert}} Certification',
<del> 'browse-other':
<del> 'Browse our other free certifications\n(we recommend doing these in order)',
<del> courses: 'Courses',
<del> expand: 'Expand',
<del> collapse: 'Collapse'
<del> }
<del>};
<del>exports.introSchema = introSchema;
<ide><path>client/i18n/meta-tags-schema.js
<del>const metaTagsSchema = {
<del> title: 'Learn to Code — For Free — Coding Courses for Busy People',
<del> description: 'Learn to Code — For Free',
<del> 'social-description': 'Learn to Code — For Free',
<del> keywords: [
<del> 'javascript',
<del> 'js',
<del> 'website',
<del> 'web',
<del> 'development',
<del> 'free',
<del> 'code',
<del> 'camp',
<del> 'course',
<del> 'courses',
<del> 'html',
<del> 'css',
<del> 'react',
<del> 'redux',
<del> 'api',
<del> 'front',
<del> 'back',
<del> 'end',
<del> 'learn',
<del> 'tutorial',
<del> 'programming'
<del> ],
<del> 'youre-unsubscribed': 'You have been unsubscribed'
<del>};
<del>
<del>exports.metaTagsSchema = metaTagsSchema;
<ide><path>client/i18n/motivation-schema.js
<del>/* eslint-disable camelcase */
<del>/* This is used for testing. If a motivation.json file doesn't match the
<del> * structure here exactly, the tests will fail.
<del> */
<del>const motivationSchema = {
<del> compliments: ['yes'],
<del> motivationalQuotes: ['woohoo']
<del>};
<del>
<del>exports.motivationSchema = motivationSchema;
<ide><path>client/i18n/schema-validation.js
<ide> const path = require('path');
<del>const fs = require('fs');
<del>const { translationsSchema } = require('./translations-schema');
<ide> const { availableLangs } = require('./allLangs');
<del>const { trendingSchema } = require('./trending-schema');
<del>const { motivationSchema } = require('./motivation-schema');
<del>const { introSchema } = require('./intro-schema');
<del>const { metaTagsSchema } = require('./meta-tags-schema');
<add>const translationsSchema = require('./locales/english/translations.json');
<add>const trendingSchema = require('./locales/english/trending.json');
<add>const motivationSchema = require('./locales/english/motivation.json');
<add>const introSchema = require('./locales/english/intro.json');
<add>const metaTagsSchema = require('./locales/english/meta-tags.json');
<ide>
<ide> /**
<ide> * Flattens a nested object structure into a single
<ide> const translationSchemaValidation = languages => {
<ide> __dirname,
<ide> `/locales/${language}/translations.json`
<ide> );
<del> const fileData = fs.readFileSync(filePath);
<del> const fileJson = JSON.parse(fileData);
<add> const fileJson = require(filePath);
<ide> const fileKeys = Object.keys(flattenAnObject(fileJson));
<ide> findMissingKeys(
<ide> fileKeys,
<ide> const translationSchemaValidation = languages => {
<ide> const trendingSchemaValidation = languages => {
<ide> languages.forEach(language => {
<ide> const filePath = path.join(__dirname, `/locales/${language}/trending.json`);
<del> const fileData = fs.readFileSync(filePath);
<del> const fileJson = JSON.parse(fileData);
<add> const fileJson = require(filePath);
<ide> const fileKeys = Object.keys(flattenAnObject(fileJson));
<ide> findMissingKeys(fileKeys, trendingSchemaKeys, `${language}/trending.json`);
<ide> findExtraneousKeys(
<ide> const motivationSchemaValidation = languages => {
<ide> __dirname,
<ide> `/locales/${language}/motivation.json`
<ide> );
<del> const fileData = fs.readFileSync(filePath);
<del> const fileJson = JSON.parse(fileData);
<add> const fileJson = require(filePath);
<ide> const fileKeys = Object.keys(flattenAnObject(fileJson));
<ide> findMissingKeys(
<ide> fileKeys,
<ide> const motivationSchemaValidation = languages => {
<ide> const introSchemaValidation = languages => {
<ide> languages.forEach(language => {
<ide> const filePath = path.join(__dirname, `/locales/${language}/intro.json`);
<del> const fileData = fs.readFileSync(filePath);
<del> const fileJson = JSON.parse(fileData);
<add> const fileJson = require(filePath);
<ide> const fileKeys = Object.keys(flattenAnObject(fileJson));
<ide> findMissingKeys(fileKeys, introSchemaKeys, `${language}/intro.json`);
<ide> findExtraneousKeys(fileKeys, introSchemaKeys, `${language}/intro.json`);
<ide> const metaTagsSchemaValidation = languages => {
<ide> __dirname,
<ide> `/locales/${language}/meta-tags.json`
<ide> );
<del> const fileData = fs.readFileSync(filePath);
<del> const fileJson = JSON.parse(fileData);
<add> const fileJson = require(filePath);
<ide> const fileKeys = Object.keys(flattenAnObject(fileJson));
<ide> findMissingKeys(fileKeys, metaTagsSchemaKeys, `${language}/meta-tags.json`);
<ide> findExtraneousKeys(
<ide> const metaTagsSchemaValidation = languages => {
<ide> });
<ide> };
<ide>
<del>translationSchemaValidation(availableLangs.client);
<del>trendingSchemaValidation(availableLangs.client);
<del>motivationSchemaValidation(availableLangs.client);
<del>introSchemaValidation(availableLangs.client);
<del>metaTagsSchemaValidation(availableLangs.client);
<add>const translatedLangs = availableLangs.client.filter(x => x !== 'english');
<add>
<add>translationSchemaValidation(translatedLangs);
<add>trendingSchemaValidation(translatedLangs);
<add>motivationSchemaValidation(translatedLangs);
<add>introSchemaValidation(translatedLangs);
<add>metaTagsSchemaValidation(translatedLangs);
<ide><path>client/i18n/translations-schema.js
<del>/* eslint-disable camelcase */
<del>/* This is used for testing. If a translations.json file doesn't match the
<del> * structure here exactly, the tests will fail.
<del> */
<del>const translationsSchema = {
<del> buttons: {
<del> 'logged-in-cta-btn': "Get started (it's free)",
<del> 'logged-out-cta-btn': "Sign in to save your progress (it's free)",
<del> 'view-curriculum': 'View the Curriculum',
<del> 'first-lesson': 'Go to the first lesson',
<del> close: 'Close',
<del> edit: 'Edit',
<del> 'show-code': 'Show Code',
<del> 'show-solution': 'Show Solution',
<del> frontend: 'Front End',
<del> backend: 'Back End',
<del> view: 'View',
<del> 'show-cert': 'Show Certification',
<del> 'claim-cert': 'Claim Certification',
<del> 'save-progress': 'Save Progress',
<del> 'accepted-honesty': 'You have accepted our Academic Honesty Policy.',
<del> agree: 'Agree',
<del> 'save-portfolio': 'Save this portfolio item',
<del> 'remove-portfolio': 'Remove this portfolio item',
<del> 'add-portfolio': 'Add a new portfolio Item',
<del> 'download-data': 'Download your data',
<del> public: 'Public',
<del> private: 'Private',
<del> off: 'Off',
<del> on: 'On',
<del> 'sign-in': 'Sign in',
<del> 'sign-out': 'Sign out',
<del> curriculum: 'Curriculum',
<del> forum: 'Forum',
<del> radio: 'Radio',
<del> profile: 'Profile',
<del> news: 'News',
<del> donate: 'Donate',
<del> 'update-settings': 'Update my account settings',
<del> 'sign-me-out': 'Sign me out of freeCodeCamp',
<del> 'flag-user': "Flag This User's Account for Abuse",
<del> 'current-challenge': 'Go to current challenge',
<del> 'try-again': 'Try again',
<del> menu: 'Menu',
<del> settings: 'Settings',
<del> 'take-me': 'Take me to the Challenges',
<del> 'check-answer': 'Check your answer',
<del> 'get-hint': 'Get a Hint',
<del> 'ask-for-help': 'Ask for Help',
<del> 'create-post': 'Create a help post on the forum',
<del> cancel: 'Cancel',
<del> 'reset-lesson': 'Reset this lesson',
<del> run: 'Run',
<del> 'run-test': 'Run the Tests',
<del> reset: 'Reset',
<del> 'reset-code': 'Reset All Code',
<del> help: 'Help',
<del> 'get-help': 'Get Help',
<del> 'watch-video': 'Watch a Video',
<del> resubscribe: 'You can click here to resubscribe',
<del> 'click-here': 'Click here to sign in',
<del> save: 'Save',
<del> 'no-thanks': 'No thanks',
<del> 'yes-please': 'Yes please',
<del> 'update-email': 'Update my Email',
<del> 'verify-email': 'Verify Email',
<del> 'submit-and-go': 'Submit and go to next challenge',
<del> 'go-to-next': 'Go to next challenge',
<del> 'ask-later': 'Ask me later'
<del> },
<del> landing: {
<del> 'big-heading-1': 'Learn to code — for free.',
<del> 'big-heading-2': 'Build projects.',
<del> 'big-heading-3': 'Earn certifications.',
<del> 'h2-heading':
<del> 'Since 2014, more than 40,000 freeCodeCamp.org graduates have gotten jobs at tech companies including:',
<del> 'hero-img-description':
<del> 'freeCodeCamp students at a local study group in South Korea.',
<del> 'as-seen-in': 'As seen in:',
<del> testimonials: {
<del> heading: 'Here is what our alumni say about freeCodeCamp:',
<del> shawn: {
<del> location: '<strong>Shawn Wang</strong> in Singapore',
<del> occupation: 'Software Engineer at <strong>Amazon</strong>',
<del> testimony:
<del> '"It\'s scary to change careers. I only gained confidence that I could code by working through the hundreds of hours of free lessons on freeCodeCamp. Within a year I had a six-figure job as a Software Engineer. <strong>freeCodeCamp changed my life.</strong>"'
<del> },
<del> sarah: {
<del> location: '<strong>Sarah Chima</strong> in Nigeria',
<del> occupation: 'Software Engineer at <strong>ChatDesk</strong>',
<del> testimony:
<del> '"<strong>freeCodeCamp was the gateway to my career</strong> as a software developer. The well-structured curriculum took my coding knowledge from a total beginner level to a very confident level. It was everything I needed to land my first dev job at an amazing company."'
<del> },
<del> emma: {
<del> location: '<strong>Emma Bostian</strong> in Sweden',
<del> occupation: 'Software Engineer at <strong>Spotify</strong>',
<del> testimony:
<del> "\"I've always struggled with learning JavaScript. I've taken many courses but freeCodeCamp's course was the one which stuck. Studying JavaScript as well as data structures and algorithms on <strong>freeCodeCamp gave me the skills</strong> and confidence I needed to land my dream job as a software engineer at Spotify.\""
<del> }
<del> },
<del> 'certification-heading': 'Earn free verified certifications in:'
<del> },
<del> settings: {
<del> 'share-projects':
<del> 'Share your non-freeCodeCamp projects, articles or accepted pull requests.',
<del> privacy:
<del> 'The settings in this section enable you to control what is shown on your freeCodeCamp public portfolio.',
<del> data:
<del> 'To see what data we hold on your account, click the "Download your data" button below',
<del> disabled: 'Your certifications will be disabled, if set to private.',
<del> 'claim-legacy':
<del> "Once you've earned the following freeCodeCamp certifications, you'll be able to claim the {{cert}}:",
<del> for: 'Account Settings for {{username}}',
<del> username: {
<del> 'contains invalid characters':
<del> 'Username "{{username}}" contains invalid characters',
<del> 'is too short': 'Username "{{username}}" is too short',
<del> 'is a reserved error code':
<del> 'Username "{{username}}" is a reserved error code',
<del> unavailable: 'Username not available',
<del> validating: 'Validating username...',
<del> available: 'Username is available',
<del> change:
<del> 'Please note, changing your username will also change the URL to your profile and your certifications.'
<del> },
<del> labels: {
<del> username: 'Username',
<del> name: 'Name',
<del> location: 'Location',
<del> picture: 'Picture',
<del> about: 'About',
<del> personal: 'Personal Website',
<del> title: 'Title',
<del> url: 'URL',
<del> image: 'Image',
<del> description: 'Description',
<del> 'project-name': 'Project Name',
<del> solution: 'Solution',
<del> 'solution-for': 'Solution for {{projectTitle}}',
<del> 'my-profile': 'My profile',
<del> 'my-name': 'My name',
<del> 'my-location': 'My location',
<del> 'my-about': 'My about',
<del> 'my-points': 'My points',
<del> 'my-heatmap': 'My heatmap',
<del> 'my-certs': 'My certifications',
<del> 'my-portfolio': 'My portfolio',
<del> 'my-timeline': 'My timeline',
<del> 'my-donations': 'My donations',
<del> 'night-mode': 'Night Mode'
<del> },
<del> headings: {
<del> certs: 'Certifications',
<del> 'legacy-certs': 'Legacy Certifications',
<del> honesty: 'Academic Honesty Policy',
<del> internet: 'Your Internet Presence',
<del> portfolio: 'Portfolio Settings',
<del> privacy: 'Privacy Settings'
<del> },
<del> danger: {
<del> heading: 'Danger Zone',
<del> 'be-careful': 'Please be careful. Changes in this section are permanent.',
<del> reset: 'Reset all of my progress',
<del> delete: 'Delete my account',
<del> 'delete-title': 'Delete My Account',
<del> 'delete-p1':
<del> 'This will really delete all your data, including all your progress and account information.',
<del> 'delete-p2':
<del> "We won't be able to recover any of it for you later, even if you change your mind.",
<del> 'delete-p3':
<del> "If there's something we could do better, send us an email instead and we'll do our best: <0>{{email}}</0>",
<del> nevermind: "Nevermind, I don't want to delete my account",
<del> certain: 'I am 100% certain. Delete everything related to this account',
<del> 'reset-heading': 'Reset My Progress',
<del> 'reset-p1':
<del> 'This will really delete all of your progress, points, completed challenges, our records of your projects, any certifications you have, everything.',
<del> 'reset-p2':
<del> "We won't be able to recover any of it for you later, even if you change your mind.",
<del> 'nevermind-2': "Nevermind, I don't want to delete all of my progress",
<del> 'reset-confirm': 'Reset everything. I want to start from the beginning'
<del> },
<del> email: {
<del> missing: 'You do not have an email associated with this account.',
<del> heading: 'Email Settings',
<del> 'not-verified': 'Your email has not been verified.',
<del> check:
<del> 'Please check your email, or <0>request a new verification email here</0>.',
<del> current: 'Current Email',
<del> new: 'New Email',
<del> confirm: 'Confirm New Email',
<del> weekly: "Send me Quincy's weekly email"
<del> },
<del> honesty: {
<del> p1:
<del> 'Before you can claim a verified certification, you must accept our Academic Honesty Pledge, which reads:',
<del> p2:
<del> '"I understand that plagiarism means copying someone else’s work and presenting the work as if it were my own, without clearly attributing the original author."',
<del> p3:
<del> '"I understand that plagiarism is an act of intellectual dishonesty, and that people usually get kicked out of university or fired from their jobs if they get caught plagiarizing."',
<del> p4:
<del> '"Aside from using open source libraries such as jQuery and Bootstrap, and short snippets of code which are clearly attributed to their original author, 100% of the code in my projects was written by me, or along with another person going through the freeCodeCamp curriculum with whom I was pair programming in real time."',
<del> p5:
<del> '"I pledge that I did not plagiarize any of my freeCodeCamp.org work. I understand that freeCodeCamp.org’s team will audit my projects to confirm this."',
<del> p6:
<del> 'In the situations where we discover instances of unambiguous plagiarism, we will replace the person in question’s certification with a message that "Upon review, this account has been flagged for academic dishonesty."',
<del> p7:
<del> 'As an academic institution that grants achievement-based certifications, we take academic honesty very seriously. If you have any questions about this policy, or suspect that someone has violated it, you can email <0>{{email}}</0> and we will investigate.'
<del> }
<del> },
<del> profile: {
<del> 'you-not-public': 'You have not made your portfolio public.',
<del> 'username-not-public': '{{username}} has not made their portfolio public.',
<del> 'you-change-privacy':
<del> 'You need to change your privacy setting in order for your portfolio to be seen by others. This is a preview of how your portfolio will look when made public.',
<del> 'username-change-privacy':
<del> '{{username}} needs to change their privacy setting in order for you to view their portfolio.',
<del> supporter: 'Supporter',
<del> contributor: 'Top Contributor',
<del> 'no-certs':
<del> 'No certifications have been earned under the current curriculum',
<del> 'fcc-certs': 'freeCodeCamp Certifications',
<del> 'longest-streak': 'Longest Streak:',
<del> 'current-streak': 'Current Streak:',
<del> portfolio: 'Portfolio',
<del> timeline: 'Timeline',
<del> 'none-completed': 'No challenges have been completed yet.',
<del> 'get-started': 'Get started here.',
<del> challenge: 'Challenge',
<del> completed: 'Completed',
<del> 'add-linkedin': 'Add this certification to my LinkedIn profile',
<del> 'add-twitter': 'Share this certification on Twitter',
<del> tweet:
<del> 'I just earned the {{certTitle}} certification @freeCodeCamp! Check it out here: {{certURL}}',
<del> avatar: "{{username}}'s avatar",
<del> joined: 'Joined {{date}}',
<del> 'total-points': '{{count}} total point',
<del> 'total-points_plural': '{{count}} total points',
<del> points: '{{count}} point on {{date}}',
<del> points_plural: '{{count}} points on {{date}}',
<del> 'screen-shot': 'A screen shot of {{title}}',
<del> 'page-number': '{{pageNumber}} of {{totalPages}}'
<del> },
<del> footer: {
<del> 'tax-exempt-status':
<del> 'freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)',
<del> 'mission-statement':
<del> 'Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.',
<del> 'donation-initiatives':
<del> 'Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.',
<del> 'donate-text': 'You can',
<del> 'donate-link': 'make a tax-deductible donation here',
<del> 'trending-guides': 'Trending Guides',
<del> 'our-nonprofit': 'Our Nonprofit',
<del> links: {
<del> about: 'About',
<del> 'about-url': 'https://www.freecodecamp.org/news/about/',
<del> alumni: 'Alumni Network',
<del> 'open-source': 'Open Source',
<del> shop: 'Shop',
<del> 'shop-url': 'https://www.freecodecamp.org/shop/',
<del> support: 'Support',
<del> 'support-url': 'https://www.freecodecamp.org/news/support/',
<del> sponsors: 'Sponsors',
<del> 'sponsors-url': 'https://www.freecodecamp.org/news/sponsors/',
<del> honesty: 'Academic Honesty',
<del> 'honesty-url':
<del> 'https://www.freecodecamp.org/news/academic-honesty-policy/',
<del> coc: 'Code of Conduct',
<del> 'coc-url': 'https://www.freecodecamp.org/news/code-of-conduct/',
<del> privacy: 'Privacy Policy',
<del> 'privacy-url': 'https://www.freecodecamp.org/news/privacy-policy/',
<del> tos: 'Terms of Service',
<del> 'tos-url': 'https://www.freecodecamp.org/news/terms-of-service/',
<del> copyright: 'Copyright Policy',
<del> 'copyright-url': 'https://www.freecodecamp.org/news/copyright-policy/'
<del> },
<del> language: 'Language:'
<del> },
<del> learn: {
<del> heading: "Welcome to freeCodeCamp's curriculum.",
<del> 'welcome-1': 'Welcome back, {{name}}.',
<del> 'welcome-2': 'Welcome to freeCodeCamp.org',
<del> 'start-at-beginning':
<del> 'If you are new to coding, we recommend you <0>start at the beginning</0>.',
<del> 'read-this': {
<del> heading: 'Please slow down and read this.',
<del> p1: 'freeCodeCamp is a proven path to your first software developer job.',
<del> p2:
<del> 'More than 40,000 people have gotten developer jobs after completing this – including at big companies like Google and Microsoft.',
<del> p3:
<del> 'If you are new to programming, we recommend you start at the beginning and earn these certifications in order.',
<del> p4:
<del> 'To earn each certification, build its 5 required projects and get all their tests to pass.',
<del> p5:
<del> 'You can add these certifications to your résumé or LinkedIn. But more important than the certifications is the practice you get along the way.',
<del> p6: 'If you feel overwhelmed, that is normal. Programming is hard.',
<del> p7: 'Practice is the key. Practice, practice, practice.',
<del> p8:
<del> 'And this curriculum will give you thousands of hours of hands-on programming practice.',
<del> p9:
<del> "And if you want to learn more math and computer science theory, we also have thousands of hours of video courses on <0>freeCodeCamp's YouTube channel</0>.",
<del> p10:
<del> 'If you want to get a developer job or freelance clients, programming skills will be just part of the puzzle. You also need to build your personal network and your reputation as a developer.',
<del> p11:
<del> 'You can do this on Twitter and GitHub, and also on <0>the freeCodeCamp forum</0>.',
<del> p12: 'Happy coding!'
<del> },
<del> 'upcoming-lessons': 'Upcoming Lessons',
<del> learn: 'Learn',
<del> 'add-subtitles': 'Help improve or add subtitles',
<del> 'wrong-answer': "Sorry, that's not the right answer. Give it another try?",
<del> 'check-answer': 'Click the button below to check your answer.',
<del> 'solution-link': 'Solution Link',
<del> 'github-link': 'GitHub Link',
<del> 'submit-and-go': 'Submit and go to my next challenge',
<del> 'i-completed': "I've completed this challenge",
<del> 'test-output': 'Your test output will go here',
<del> 'running-tests': '// running tests',
<del> 'tests-completed': '// tests completed',
<del> 'console-output': '// console output',
<del> 'sign-in-save': 'Sign in to save your progress',
<del> 'download-solution': 'Download my solution',
<del> 'percent-complete': '{{percent}}% complete',
<del> 'tried-rsa':
<del> "If you've already tried the <0>Read-Search-Ask</0> method, then you can ask for help on the freeCodeCamp forum.",
<del> rsa: 'Read, search, ask',
<del> reset: 'Reset this lesson?',
<del> 'reset-warn':
<del> 'Are you sure you wish to reset this lesson? The editors and tests will be reset.',
<del> 'reset-warn-2': 'This cannot be undone',
<del> 'scrimba-tip':
<del> 'Tip: If the mini-browser is covering the code, click and drag to move it. Also, feel free to stop and edit the code in the video at any time.',
<del> 'chal-preview': 'Challenge Preview',
<del> 'cert-map-estimates': {
<del> certs: 'Certification (300\u00A0hours)',
<del> 'coding-prep': '(Thousands of hours of challenges)'
<del> },
<del> 'editor-tabs': {
<del> info: 'Info',
<del> code: 'Code',
<del> tests: 'Tests',
<del> preview: 'Preview'
<del> },
<del> 'help-translate': 'We are still translating the following certifications.',
<del> 'help-translate-link': 'Help us translate.'
<del> },
<del> donate: {
<del> title: 'Support our nonprofit',
<del> processing: 'We are processing your donation.',
<del> thanks: 'Thanks for donating',
<del> 'thank-you': 'Thank you for being a supporter.',
<del> 'thank-you-2':
<del> 'Thank you for being a supporter of freeCodeCamp. You currently have a recurring donation.',
<del> additional:
<del> 'You can make an additional one-time donation of any amount using this link: <0>{{url}}</0>',
<del> 'help-more': 'Help us do more',
<del> error: 'Something went wrong with your donation.',
<del> 'free-tech':
<del> 'Your donations will support free technology education for people all over the world.',
<del> 'gift-frequency': 'Select gift frequency:',
<del> 'gift-amount': 'Select gift amount:',
<del> confirm: 'Confirm your donation',
<del> 'confirm-2': 'Confirm your one-time donation of ${{usd}}',
<del> 'confirm-3': 'Confirm your donation of ${{usd}} / month',
<del> 'confirm-4': 'Confirm your donation of ${{usd}} / year',
<del> 'your-donation':
<del> 'Your ${{usd}} donation will provide {{hours}} hours of learning to people around the world.',
<del> 'your-donation-2':
<del> 'Your ${{usd}} donation will provide {{hours}} hours of learning to people around the world each month.',
<del> 'your-donation-3':
<del> 'Your ${{usd}} donation will provide {{hours}} hours of learning to people around the world each year.',
<del> duration: 'Become a one-time supporter of our nonprofit.',
<del> 'duration-2': 'Become a monthly supporter of our nonprofit.',
<del> 'duration-3': 'Become an annual supporter of our nonprofit',
<del> 'duration-4': 'Become a supporter of our nonprofit',
<del> 'nicely-done': 'Nicely done. You just completed {{block}}.',
<del> 'credit-card': 'Credit Card',
<del> 'credit-card-2': 'Or donate with a credit card:',
<del> paypal: 'with PayPal:',
<del> 'need-email':
<del> 'We need a valid email address to which we can send your donation tax receipt.',
<del> 'went-wrong':
<del> 'Something went wrong processing your donation. Your card has not been charged.',
<del> 'valid-info':
<del> 'Please enter valid email address, credit card number, and expiration date.',
<del> 'valid-email': 'Please enter a valid email address.',
<del> 'valid-card': 'Please enter valid credit card number and expiration date.',
<del> 'email-receipt':
<del> "Email (we'll send you a tax-deductible donation receipt):",
<del> 'need-help': 'Need help with your current or past donations?',
<del> 'forward-receipt':
<del> 'Forward a copy of your donation receipt to donors@freecodecamp.org and tell us how we can help.',
<del> efficiency: 'freeCodeCamp is a highly efficient education nonprofit.',
<del> 'why-donate-1':
<del> 'When you donate to freeCodeCamp, you help people learn new skills and provide for their families.',
<del> 'why-donate-2':
<del> 'You also help us create new resources for you to use to expand your own technology skills.',
<del> 'bigger-donation':
<del> 'Want to make a bigger one-time donation, mail us a check, or give in other ways?',
<del> 'other-ways':
<del> "Here are many <0>other ways you can support our non-profit's mission</0>.",
<del> 'other-ways-url':
<del> 'https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp',
<del> 'failed-pay':
<del> "Uh - oh. It looks like your transaction didn't go through. Could you please try again?",
<del> 'try-again': 'Please try again.',
<del> 'card-number': 'Your Card Number:',
<del> expiration: 'Expiration Date:',
<del> 'only-you':
<del> 'Only you can see this message. Congratulations on earning this certification. It’s no easy task. Running freeCodeCamp isn’t easy either. Nor is it cheap. Help us help you and many other people around the world. Make a tax-deductible supporting donation to our nonprofit today.'
<del> },
<del> report: {
<del> 'sign-in': 'You need to be signed in to report a user',
<del> details:
<del> 'Please provide as much detail as possible about the account or behavior you are reporting.',
<del> portfolio: 'Report a users portfolio',
<del> 'portfolio-2': "Do you want to report {{username}}'s portfolio for abuse?",
<del> 'notify-1':
<del> "We will notify the community moderators' team, and a send copy of this report to your email: <strong>{{email}}</strong>",
<del> 'notify-2': 'We may get back to you for more information, if required.',
<del> what: 'What would you like to report?',
<del> submit: 'Submit the report'
<del> },
<del> '404': {
<del> 'page-not-found': 'Page not found',
<del> 'not-found': '404 Not Found:',
<del> 'heres-a-quote':
<del> "We couldn't find what you were looking for, but here is a quote:"
<del> },
<del> search: {
<del> label: 'Search',
<del> placeholder: 'Search 6,000+ tutorials',
<del> 'see-results': 'See all results for {{searchQuery}}',
<del> 'no-tutorials': 'No tutorials found',
<del> try: 'Looking for something? Try the search bar on this page.',
<del> 'no-results': 'We could not find anything relating to <0>{{query}}</0>'
<del> },
<del> misc: {
<del> offline: 'You appear to be offline, your progress may not be saved',
<del> unsubscribed: 'You have successfully been unsubscribed',
<del> 'keep-coding': 'Whatever you go on to, keep coding!',
<del> 'email-signup': 'Email Sign Up',
<del> quincy: '- Quincy Larson, the teacher who founded freeCodeCamp.org',
<del> 'email-blast':
<del> 'By the way, each Friday I send an email with 5 links about programming and computer science. I send these to about 4 million people. Would you like me to send this to you, too?',
<del> 'update-email-1': 'Update your email address',
<del> 'update-email-2': 'Update your email address here:',
<del> email: 'Email',
<del> and: 'and',
<del> 'change-theme': 'Sign in to change theme.',
<del> 'translation-pending': 'Help us translate'
<del> },
<del> icons: {
<del> 'gold-cup': 'Gold Cup',
<del> avatar: 'Default Avatar',
<del> 'avatar-2': 'An avatar coding with a laptop',
<del> donate: 'Donate with PayPal',
<del> fail: 'Test Failed',
<del> 'not-passed': 'Not Passed',
<del> passed: 'Passed',
<del> heart: 'Heart',
<del> initial: 'Initial',
<del> info: 'Intro Information',
<del> spacer: 'Spacer',
<del> toggle: 'Toggle Checkmark',
<del> 'responsive-design': 'Laptop and mobile phone icon',
<del> javascript: 'JavaScript icon',
<del> react: 'React icon',
<del> d3: 'D3 icon',
<del> api: 'A stack of servers',
<del> clipboard: 'A clipboard with a checkmark',
<del> python: 'Python icon',
<del> analytics: 'A bar chart and line graph',
<del> shield: 'A shield with a checkmark',
<del> tensorflow: 'Tensorflow icon',
<del> algorithm: 'Branching nodes'
<del> },
<del> aria: {
<del> 'fcc-logo': 'freeCodeCamp Logo',
<del> answer: 'Answer',
<del> linkedin: "Link to {{username}}'s LinkedIn",
<del> github: "Link to {{username}}'s GitHub",
<del> website: "Link to {{username}}'s website",
<del> twitter: "Link to {{username}}'s Twitter",
<del> 'first-page': 'Go to first page',
<del> 'previous-page': 'Go to previous page',
<del> 'next-page': 'Go to next page',
<del> 'last-page': 'Go to last page'
<del> },
<del> flash: {
<del> 'honest-first':
<del> 'To claim a certification, you must first accept our academic honesty policy',
<del> 'really-weird':
<del> 'Something really weird happened, if it happens again, please consider raising an issue on https://github.com/freeCodeCamp/freeCodeCamp/issues/new',
<del> 'not-right':
<del> 'Something is not quite right. A report has been generated and the freeCodeCamp.org team have been notified',
<del> 'went-wrong': 'Something went wrong, please check and try again',
<del> 'account-deleted': 'Your account has been successfully deleted',
<del> 'progress-reset': 'Your progress has been reset',
<del> 'not-authorized': 'You are not authorized to continue on this route',
<del> 'could-not-find':
<del> "We couldn't find what you were looking for. Please check and try again",
<del> 'wrong-updating':
<del> 'Something went wrong updating your account. Please check and try again',
<del> 'updated-preferences': 'We have updated your preferences',
<del> 'email-invalid': 'Email format is invalid',
<del> 'bad-challengeId': 'currentChallengeId is not a valid challenge ID',
<del> 'theme-invalid': 'Theme is invalid',
<del> 'theme-set': 'Theme already set',
<del> 'theme-updated': 'Your theme has been updated!',
<del> 'username-used': 'Username is already associated with this account',
<del> 'username-taken': 'Username is already associated with a different account',
<del> 'username-updated': 'We have updated your username to {{username}}',
<del> 'could-not-logout':
<del> 'We could not log you out, please try again in a moment',
<del> 'email-encoded-wrong':
<del> 'The email encoded in the link is incorrectly formatted',
<del> 'oops-not-right':
<del> 'Oops, something is not right, please request a fresh link to sign in / sign up',
<del> 'expired-link':
<del> 'Looks like the link you clicked has expired, please request a fresh link, to sign in',
<del> 'signin-success':
<del> 'Success! You have signed in to your account. Happy Coding!',
<del> 'social-auth-gone':
<del> 'We are moving away from social authentication for privacy reasons. Next time we recommend using your email address: {{email}} to sign in instead.',
<del> 'name-needed':
<del> 'We need your name so we can put it on your certification. Add your name to your account settings and click the save button. Then we can issue your certification.',
<del> 'incomplete-steps':
<del> 'It looks like you have not completed the necessary steps. Please complete the required projects to claim the {{name}} Certification.',
<del> 'already-claimed':
<del> 'It looks like you already have claimed the {{name}} Certification',
<del> 'cert-claim-success':
<del> '@{{username}}, you have successfully claimed the {{name}} Certification! Congratulations on behalf of the freeCodeCamp.org team!',
<del> 'wrong-name':
<del> 'Something went wrong with the verification of {{name}}, please try again. If you continue to receive this error, you can send a message to support@freeCodeCamp.org to get help.',
<del> 'error-claiming': 'Error claiming {{certName}}',
<del> 'username-not-found':
<del> 'We could not find a user with the username "{{username}}"',
<del> 'add-name':
<del> 'This user needs to add their name to their account in order for others to be able to view their certification.',
<del> 'not-eligible':
<del> 'This user is not eligible for freeCodeCamp.org certifications at this time.',
<del> 'profile-private':
<del> '{{username}} has chosen to make their portfolio private. They will need to make their portfolio public in order for others to be able to view their certification.',
<del> 'certs-private':
<del> '{{username}} has chosen to make their certifications private. They will need to make their certifications public in order for others to be able to view them.',
<del> 'not-honest':
<del> '{{username}} has not yet agreed to our Academic Honesty Pledge.',
<del> 'user-not-certified':
<del> 'It looks like user {{username}} is not {{cert}} certified',
<del> 'invalid-challenge':
<del> 'That does not appear to be a valid challenge submission',
<del> 'no-links-provided':
<del> 'You have not provided the valid links for us to inspect your work.',
<del> 'no-social': 'No social account found',
<del> 'invalid-social': 'Invalid social account',
<del> 'no-account': 'No {{website}} account associated',
<del> 'unlink-success': "You've successfully unlinked your {{website}}",
<del> 'provide-username': 'Check if you have provided a username and a report',
<del> 'report-sent': 'A report was sent to the team with {{email}} in copy'
<del> },
<del> validation: {
<del> 'max-characters':
<del> 'There is a maximum limit of 288 characters, you have {{charsLeft}} left',
<del> 'same-email': 'This email is the same as your current email',
<del> 'invalid-email':
<del> 'We could not validate your email correctly, please ensure it is correct',
<del> 'email-mismatch': 'Both new email addresses must be the same',
<del> 'title-required': 'A title is required',
<del> 'title-short': 'Title is too short',
<del> 'title-long': 'Title is too long',
<del> 'invalid-url':
<del> 'We could not validate your URL correctly, please ensure it is correct',
<del> 'invalid-protocol': 'URL must start with http or https',
<del> 'url-not-image': 'URL must link directly to an image file',
<del> 'use-valid-url': 'Please use a valid URL'
<del> },
<del> certification: {
<del> executive: 'Executive Director, freeCodeCamp.org',
<del> verify: 'Verify this certification at {{certURL}}',
<del> issued: 'Issued',
<del> fulltext:
<del> '<0>This certifies that</0> <1>{{user}}</1> <2>has successfully completed the freeCodeCamp.org</2> <3>{{title}}</3> <4>Developer Certification, representing approximately {{time}} hours of coursework.</4>'
<del> }
<del>};
<del>
<del>exports.translationsSchema = translationsSchema;
<ide><path>client/i18n/trending-schema.js
<del>/* eslint-disable camelcase */
<del>/* This is used for testing. If a trending.json file doesn't match the
<del> * structure here exactly, the tests will fail.
<del> */
<del>
<del>const trendingSchema = {
<del> article0title: 'What is Docker?',
<del> article0link:
<del> 'https://www.freecodecamp.org/news/what-is-docker-used-for-a-docker-container-tutorial-for-beginners/',
<del> article1title: 'TCP/IP Model',
<del> article1link:
<del> 'https://www.freecodecamp.org/news/what-is-tcp-ip-layers-and-protocols-explained/',
<del> article2title: 'RTF File',
<del> article2link:
<del> 'https://www.freecodecamp.org/news/rtf-file-what-is-the-rich-text-format/',
<del> article3title: 'CSS Transition',
<del> article3link: 'https://www.freecodecamp.org/news/css-transition-examples/',
<del> article4title: 'How to Use Instagram?',
<del> article4link:
<del> 'https://www.freecodecamp.org/news/how-to-use-instagram-like-a-pro/',
<del> article5title: 'MBR VS GPT',
<del> article5link:
<del> 'https://www.freecodecamp.org/news/mbr-vs-gpt-whats-the-difference-between-an-mbr-partition-and-a-gpt-partition-solved/',
<del> article6title: 'FAT32 Format',
<del> article6link:
<del> 'https://www.freecodecamp.org/news/how-to-format-a-usb-drive-to-fat32-on-windows-10/',
<del> article7title: 'Error 503 Code',
<del> article7link:
<del> 'https://www.freecodecamp.org/news/http-error-503-service-unavailable-explained-what-the-503-error-code-means/',
<del> article8title: 'Windows Hosts File',
<del> article8link:
<del> 'https://www.freecodecamp.org/news/how-to-find-and-edit-a-windows-hosts-file/',
<del> article9title: 'Mobi to PDF',
<del> article9link:
<del> 'https://www.freecodecamp.org/news/mobi-to-pdf-how-to-convert-to-and-from-a-mobi-file/',
<del> article10title: 'What is STEM?',
<del> article10link:
<del> 'https://www.freecodecamp.org/news/what-is-stem-the-meaning-of-an-acronym-youll-hear-a-lot-in-school/',
<del> article11title: 'JavaScript Void 0',
<del> article11link:
<del> 'https://www.freecodecamp.org/news/javascript-void-keyword-explained/',
<del> article12title: 'SQL Delete Row',
<del> article12link:
<del> 'https://www.freecodecamp.org/news/sql-delete-row-statement-examples/',
<del> article13title: 'JavaScript Replace',
<del> article13link:
<del> 'https://www.freecodecamp.org/news/javascript-string-replace-example-with-regex/',
<del> article14title: 'Python JSON Parser',
<del> article14link:
<del> 'https://www.freecodecamp.org/news/python-read-json-file-how-to-load-json-from-a-file-and-parse-dumps/',
<del> article15title: 'cmd Delete Folder',
<del> article15link:
<del> 'https://www.freecodecamp.org/news/cmd-delete-folder-how-to-remove-files-and-folders-in-windows/',
<del> article16title: 'What is NFC?',
<del> article16link:
<del> 'https://www.freecodecamp.org/news/what-is-nfc-near-field-communication-uses-chips-tags-and-readers-explained/',
<del> article17title: 'Content Type JSON',
<del> article17link:
<del> 'https://www.freecodecamp.org/news/what-is-the-correct-content-type-for-json-request-header-mime-type-explained/',
<del> article18title: 'Convert HEIC to JPG',
<del> article18link:
<del> 'https://www.freecodecamp.org/news/heic-to-jpg-how-to-convert-images-on-a-mac/',
<del> article19title: 'Math Random Java',
<del> article19link:
<del> 'https://www.freecodecamp.org/news/generate-random-numbers-java/',
<del> article20title: 'WordPress for Beginners',
<del> article20link:
<del> 'https://www.freecodecamp.org/news/how-to-start-a-blog-with-wordpress/',
<del> article21title: 'Qualitative VS Quantitative',
<del> article21link:
<del> 'https://www.freecodecamp.org/news/qualitative-vs-quantitative-definition-research-methods-and-data/',
<del> article22title: 'JavaScript Split String',
<del> article22link:
<del> 'https://www.freecodecamp.org/news/javascript-split-string-example/',
<del> article23title: 'Accented Letters on Mac',
<del> article23link:
<del> 'https://www.freecodecamp.org/news/how-to-type-letters-with-accents-on-mac/',
<del> article24title: 'Windows 10 Product Key',
<del> article24link:
<del> 'https://www.freecodecamp.org/news/how-to-find-a-windows-10-product-key/',
<del> article25title: 'Google Docs Landscape',
<del> article25link:
<del> 'https://www.freecodecamp.org/news/google-docs-landscape-tutorial-how-to-make-a-google-doc-landscape-orientation/',
<del> article26title: 'Antimalware Executable',
<del> article26link:
<del> 'https://www.freecodecamp.org/news/antimalware-service-executable-what-is-msmpeng-exe-and-why-is-it-running-in-windows-10/',
<del> article27title: 'Windows 10 Start Menu',
<del> article27link:
<del> 'https://www.freecodecamp.org/news/windows-10-start-menu-not-working-solved/',
<del> article28title: 'Windows 10 Command Line',
<del> article28link:
<del> 'https://www.freecodecamp.org/news/how-to-open-the-command-prompt-in-windows-10/',
<del> article29title: 'Google Account Recovery',
<del> article29link:
<del> 'https://www.freecodecamp.org/news/google-account-recovery-change-gmail-password/'
<del>};
<del>
<del>exports.trendingSchema = trendingSchema;
<ide><path>client/i18n/validate-keys.js
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide> const translationsObject = require('./locales/english/translations.json');
<add>const introObject = require('./locales/english/intro.json');
<add>const metaObject = require('./locales/english/meta-tags.json');
<add>const motivationObject = require('./locales/english/motivation.json');
<add>const trendingObject = require('./locales/english/trending.json');
<ide>
<ide> /**
<ide> * Function to flatten a nested object. Written specifically for
<ide> const flattenAnObject = (obj, namespace = '') => {
<ide> return flattened;
<ide> };
<ide>
<del>const flattenedSchema = flattenAnObject(translationsObject);
<del>
<del>const keyStrings = Object.keys(flattenedSchema);
<add>const translationKeys = Object.keys(flattenAnObject(translationsObject));
<add>const metaKeys = Object.keys(flattenAnObject(metaObject));
<add>const motivationKeys = Object.keys(flattenAnObject(motivationObject));
<add>const introKeys = Object.keys(flattenAnObject(introObject));
<add>const trendingKeys = Object.keys(flattenAnObject(trendingObject));
<ide>
<ide> /**
<ide> * Recursively read through the directory, grabbing .js files
<ide> const serverCodebase = readComponentCode(
<ide> path.join(process.cwd() + '/../api-server/server')
<ide> );
<ide>
<del>for (const key of keyStrings) {
<add>for (const key of translationKeys) {
<ide> if (!clientCodebase.includes(key) && !serverCodebase.includes(key)) {
<ide> console.warn(`The translation key '${key}' appears to be unused.`);
<ide> }
<ide> }
<add>for (const key of motivationKeys) {
<add> if (!clientCodebase.includes(key) && !serverCodebase.includes(key)) {
<add> console.warn(`The motivation key '${key}' appears to be unused.`);
<add> }
<add>}
<add>for (const key of metaKeys) {
<add> if (!clientCodebase.includes(key) && !serverCodebase.includes(key)) {
<add> console.warn(`The meta key '${key}' appears to be unused.`);
<add> }
<add>}
<add>for (const key of introKeys) {
<add> if (!clientCodebase.includes(key) && !serverCodebase.includes(key)) {
<add> console.warn(`The intro key '${key}' appears to be unused.`);
<add> }
<add>}
<add>for (const key of trendingKeys) {
<add> if (!clientCodebase.includes(key) && !serverCodebase.includes(key)) {
<add> console.warn(`The trending key '${key}' appears to be unused.`);
<add> }
<add>} | 7 |
Java | Java | add processexternalentities support to oxm | edba32b3093703d5e9ed42b5b8ec23ecc1998398 | <ide><path>spring-oxm/src/main/java/org/springframework/oxm/castor/CastorMarshaller.java
<ide> public void setEncoding(String encoding) {
<ide> this.encoding = encoding;
<ide> }
<ide>
<add> @Override
<add> protected String getDefaultEncoding() {
<add> return this.encoding;
<add> }
<add>
<ide> /**
<ide> * Set the locations of the Castor XML mapping files.
<ide> */
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java
<ide> public void setProcessExternalEntities(boolean processExternalEntities) {
<ide> this.processExternalEntities = processExternalEntities;
<ide> }
<ide>
<add> /**
<add> * @return the configured value for whether XML external entities are allowed.
<add> */
<add> public boolean isProcessExternalEntities() {
<add> return this.processExternalEntities;
<add> }
<add>
<ide> @Override
<ide> public void setBeanClassLoader(ClassLoader classLoader) {
<ide> this.beanClassLoader = classLoader;
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/jibx/JibxMarshaller.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 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 javax.xml.stream.XMLStreamException;
<ide> import javax.xml.stream.XMLStreamReader;
<ide> import javax.xml.stream.XMLStreamWriter;
<add>import javax.xml.transform.OutputKeys;
<ide> import javax.xml.transform.Result;
<ide> import javax.xml.transform.Source;
<ide> import javax.xml.transform.Transformer;
<ide> public void setEncoding(String encoding) {
<ide> this.encoding = encoding;
<ide> }
<ide>
<add> @Override
<add> protected String getDefaultEncoding() {
<add> return this.encoding;
<add> }
<add>
<ide> /**
<ide> * Set the document standalone flag for marshalling. By default, this flag is not present.
<ide> */
<ide> private void transformAndMarshal(Object graph, Result result) throws IOException
<ide> }
<ide> catch (TransformerException ex) {
<ide> throw new MarshallingFailureException(
<del> "Could not transform to [" + ClassUtils.getShortName(result.getClass()) + "]");
<add> "Could not transform to [" + ClassUtils.getShortName(result.getClass()) + "]", ex);
<ide> }
<ide>
<ide> }
<ide> protected Object unmarshalReader(Reader reader) throws XmlMappingException, IOEx
<ide> @Override
<ide> protected Object unmarshalDomNode(Node node) throws XmlMappingException {
<ide> try {
<del> return transformAndUnmarshal(new DOMSource(node));
<add> return transformAndUnmarshal(new DOMSource(node), null);
<ide> }
<ide> catch (IOException ex) {
<ide> throw new UnmarshallingFailureException("JiBX unmarshalling exception", ex);
<ide> protected Object unmarshalDomNode(Node node) throws XmlMappingException {
<ide> protected Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource)
<ide> throws XmlMappingException, IOException {
<ide>
<del> return transformAndUnmarshal(new SAXSource(xmlReader, inputSource));
<add> return transformAndUnmarshal(new SAXSource(xmlReader, inputSource), inputSource.getEncoding());
<ide> }
<ide>
<del> private Object transformAndUnmarshal(Source source) throws IOException {
<add> private Object transformAndUnmarshal(Source source, String encoding) throws IOException {
<ide> try {
<ide> Transformer transformer = this.transformerFactory.newTransformer();
<add> if (encoding != null) {
<add> transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
<add> }
<ide> ByteArrayOutputStream os = new ByteArrayOutputStream();
<ide> transformer.transform(source, new StreamResult(os));
<ide> ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
<ide> return unmarshalInputStream(is);
<ide> }
<ide> catch (TransformerException ex) {
<ide> throw new MarshallingFailureException(
<del> "Could not transform from [" + ClassUtils.getShortName(source.getClass()) + "]");
<add> "Could not transform from [" + ClassUtils.getShortName(source.getClass()) + "]", ex);
<ide> }
<ide> }
<ide>
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/support/AbstractMarshaller.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public abstract class AbstractMarshaller implements Marshaller, Unmarshaller {
<ide>
<ide> private final Object documentBuilderFactoryMonitor = new Object();
<ide>
<add> private boolean processExternalEntities = false;
<add>
<add>
<add> /**
<add> * Indicates whether external XML entities are processed when unmarshalling.
<add> * <p>Default is {@code false}, meaning that external entities are not resolved.
<add> * Note that processing of external entities will only be enabled/disabled when the
<add> * {@code Source} passed to {@link #unmarshal(Source)} is a {@link SAXSource} or
<add> * {@link StreamSource}. It has no effect for {@link DOMSource} or {@link StAXSource}
<add> * instances.
<add> */
<add> public void setProcessExternalEntities(boolean processExternalEntities) {
<add> this.processExternalEntities = processExternalEntities;
<add> }
<add>
<add> /**
<add> * @return the configured value for whether XML external entities are allowed.
<add> */
<add> public boolean isProcessExternalEntities() {
<add> return this.processExternalEntities;
<add> }
<add>
<add> /**
<add> * @return the default encoding to use for marshalling or unmarshalling from
<add> * a byte stream, or {@code null}.
<add> */
<add> abstract protected String getDefaultEncoding();
<add>
<ide>
<ide> /**
<ide> * Marshals the object graph with the given root into the provided {@code javax.xml.transform.Result}.
<ide> else if (source instanceof SAXSource) {
<ide> return unmarshalSaxSource((SAXSource) source);
<ide> }
<ide> else if (source instanceof StreamSource) {
<del> return unmarshalStreamSource((StreamSource) source);
<add> return unmarshalStreamSourceNoExternalEntitities((StreamSource) source);
<ide> }
<ide> else {
<ide> throw new IllegalArgumentException("Unknown Source type: " + source.getClass());
<ide> protected DocumentBuilderFactory createDocumentBuilderFactory() throws ParserCon
<ide> * @throws SAXException if thrown by JAXP methods
<ide> */
<ide> protected XMLReader createXmlReader() throws SAXException {
<del> return XMLReaderFactory.createXMLReader();
<add> XMLReader xmlReader = XMLReaderFactory.createXMLReader();
<add> xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities());
<add> return xmlReader;
<ide> }
<ide>
<ide>
<ide> protected Object unmarshalSaxSource(SAXSource saxSource) throws XmlMappingExcept
<ide> return unmarshalSaxReader(saxSource.getXMLReader(), saxSource.getInputSource());
<ide> }
<ide>
<add> /**
<add> * Template method for handling {@code StreamSource}s with protection against
<add> * the XML External Entity (XXE) processing vulnerability taking into account
<add> * the value of the {@link #setProcessExternalEntities(boolean)} property.
<add> * <p>
<add> * The default implementation wraps the StreamSource as a SAXSource and delegates
<add> * to {@link #unmarshalSaxSource(javax.xml.transform.sax.SAXSource)}.
<add> *
<add> * @param streamSource the {@code StreamSource}
<add> * @return the object graph
<add> * @throws IOException if an I/O exception occurs
<add> * @throws XmlMappingException if the given source cannot be mapped to an object
<add> *
<add> * @see <a href="https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing">XML_External_Entity_(XXE)_Processing</a>
<add> */
<add> protected Object unmarshalStreamSourceNoExternalEntitities(StreamSource streamSource) throws XmlMappingException, IOException {
<add> InputSource inputSource;
<add> if (streamSource.getInputStream() != null) {
<add> inputSource = new InputSource(streamSource.getInputStream());
<add> inputSource.setEncoding(getDefaultEncoding());
<add> }
<add> else if (streamSource.getReader() != null) {
<add> inputSource = new InputSource(streamSource.getReader());
<add> }
<add> else {
<add> inputSource = new InputSource(streamSource.getSystemId());
<add> }
<add> return unmarshalSaxSource(new SAXSource(inputSource));
<add> }
<add>
<ide> /**
<ide> * Template method for handling {@code StreamSource}s.
<ide> * <p>This implementation defers to {@code unmarshalInputStream} or {@code unmarshalReader}.
<add> * <p>As of 3.2.8 and 4.0.2 this method is no longer invoked from
<add> * {@link #unmarshal(javax.xml.transform.Source)}. The method invoked instead is
<add> * {@link #unmarshalStreamSourceNoExternalEntitities(javax.xml.transform.stream.StreamSource)}.
<add> *
<ide> * @param streamSource the {@code StreamSource}
<ide> * @return the object graph
<ide> * @throws IOException if an I/O exception occurs
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/xmlbeans/XmlBeansMarshaller.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public boolean isValidating() {
<ide> return this.validating;
<ide> }
<ide>
<add> @Override
<add> protected String getDefaultEncoding() {
<add> return null;
<add> }
<ide>
<ide> /**
<ide> * This implementation returns true if the given class is an implementation of {@link XmlObject}.
<ide><path>spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<del>import javax.xml.stream.XMLEventReader;
<del>import javax.xml.stream.XMLEventWriter;
<del>import javax.xml.stream.XMLStreamException;
<del>import javax.xml.stream.XMLStreamReader;
<del>import javax.xml.stream.XMLStreamWriter;
<add>import javax.xml.stream.*;
<add>import javax.xml.transform.stax.StAXSource;
<add>import javax.xml.transform.stream.StreamSource;
<ide>
<ide> import com.thoughtworks.xstream.MarshallingStrategy;
<ide> import com.thoughtworks.xstream.XStream;
<ide> public void setEncoding(String encoding) {
<ide> this.encoding = encoding;
<ide> }
<ide>
<add> @Override
<add> protected String getDefaultEncoding() {
<add> return this.encoding;
<add> }
<add>
<ide> /**
<ide> * Set the classes supported by this marshaller.
<ide> * <p>If this property is empty (the default), all classes are supported.
<ide> private void doMarshal(Object graph, HierarchicalStreamWriter streamWriter, Data
<ide>
<ide> // Unmarshalling
<ide>
<add> @Override
<add> protected Object unmarshalStreamSourceNoExternalEntitities(StreamSource streamSource)
<add> throws XmlMappingException, IOException {
<add>
<add> return super.unmarshalStreamSource(streamSource);
<add> }
<add>
<ide> @Override
<ide> protected Object unmarshalDomNode(Node node) throws XmlMappingException {
<ide> HierarchicalStreamReader streamReader;
<ide><path>spring-oxm/src/test/java/org/springframework/oxm/castor/CastorUnmarshallerTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 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 java.io.ByteArrayInputStream;
<ide> import java.io.IOException;
<ide> import java.io.StringReader;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>import javax.xml.transform.sax.SAXSource;
<ide> import javax.xml.transform.stream.StreamSource;
<ide>
<ide> import org.junit.Ignore;
<ide> import org.springframework.oxm.AbstractUnmarshallerTests;
<ide> import org.springframework.oxm.MarshallingException;
<ide> import org.springframework.oxm.Unmarshaller;
<add>import org.xml.sax.InputSource;
<add>import org.xml.sax.XMLReader;
<ide>
<add>import static junit.framework.Assert.assertNotNull;
<ide> import static org.hamcrest.CoreMatchers.*;
<ide> import static org.junit.Assert.*;
<add>import static org.junit.Assert.assertEquals;
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<ide> private Object unmarshal(String xml) throws Exception {
<ide> StreamSource source = new StreamSource(new StringReader(xml));
<ide> return unmarshaller.unmarshal(source);
<ide> }
<add>
<add> @Test
<add> public void unmarshalStreamSourceExternalEntities() throws Exception {
<add>
<add> final AtomicReference<XMLReader> result = new AtomicReference<XMLReader>();
<add> CastorMarshaller marshaller = new CastorMarshaller() {
<add> @Override
<add> protected Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource) {
<add> result.set(xmlReader);
<add> return null;
<add> }
<add> };
<add>
<add> // 1. external-general-entities disabled (default)
<add>
<add> marshaller.unmarshal(new StreamSource("1"));
<add> assertNotNull(result.get());
<add> assertEquals(false, result.get().getFeature("http://xml.org/sax/features/external-general-entities"));
<add>
<add> // 2. external-general-entities disabled (default)
<add>
<add> result.set(null);
<add> marshaller.setProcessExternalEntities(true);
<add> marshaller.unmarshal(new StreamSource("1"));
<add> assertNotNull(result.get());
<add> assertEquals(true, result.get().getFeature("http://xml.org/sax/features/external-general-entities"));
<add> }
<add>
<add> @Test
<add> public void unmarshalSaxSourceExternalEntities() throws Exception {
<add>
<add> final AtomicReference<XMLReader> result = new AtomicReference<XMLReader>();
<add> CastorMarshaller marshaller = new CastorMarshaller() {
<add> @Override
<add> protected Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource) {
<add> result.set(xmlReader);
<add> return null;
<add> }
<add> };
<add>
<add> // 1. external-general-entities disabled (default)
<add>
<add> marshaller.unmarshal(new SAXSource(new InputSource("1")));
<add> assertNotNull(result.get());
<add> assertEquals(false, result.get().getFeature("http://xml.org/sax/features/external-general-entities"));
<add>
<add> // 2. external-general-entities disabled (default)
<add>
<add> result.set(null);
<add> marshaller.setProcessExternalEntities(true);
<add> marshaller.unmarshal(new SAXSource(new InputSource("1")));
<add> assertNotNull(result.get());
<add> assertEquals(true, result.get().getFeature("http://xml.org/sax/features/external-general-entities"));
<add> }
<add>
<ide> }
<ide><path>spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 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 javax.xml.namespace.QName;
<ide> import javax.xml.transform.Result;
<ide> import javax.xml.transform.sax.SAXResult;
<add>import javax.xml.transform.sax.SAXSource;
<ide> import javax.xml.transform.stream.StreamResult;
<add>import javax.xml.transform.stream.StreamSource;
<ide>
<ide> import org.junit.Test;
<add>import org.mockito.ArgumentCaptor;
<ide> import org.mockito.InOrder;
<ide> import org.springframework.core.io.ClassPathResource;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.oxm.mime.MimeContainer;
<ide> import org.springframework.util.FileCopyUtils;
<ide> import org.springframework.util.ReflectionUtils;
<del>import org.xml.sax.Attributes;
<del>import org.xml.sax.ContentHandler;
<del>import org.xml.sax.Locator;
<add>import org.xml.sax.*;
<ide>
<ide> import static org.junit.Assert.*;
<ide> import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
<ide> public void marshalAttachments() throws Exception {
<ide> public void marshalAWrappedObjectHoldingAnXmlElementDeclElement() throws Exception {
<ide> // SPR-10714
<ide> marshaller = new Jaxb2Marshaller();
<del> marshaller.setPackagesToScan(new String[] { "org.springframework.oxm.jaxb" });
<add> marshaller.setPackagesToScan(new String[]{"org.springframework.oxm.jaxb"});
<ide> marshaller.afterPropertiesSet();
<ide> Airplane airplane = new Airplane();
<ide> airplane.setName("test");
<ide> public void marshalAWrappedObjectHoldingAnXmlElementDeclElement() throws Excepti
<ide> writer.toString(), "<airplane><name>test</name></airplane>");
<ide> }
<ide>
<add> // SPR-10806
<add>
<add> @Test
<add> public void unmarshalStreamSourceExternalEntities() throws Exception {
<add>
<add> final javax.xml.bind.Unmarshaller unmarshaller = mock(javax.xml.bind.Unmarshaller.class);
<add> Jaxb2Marshaller marshaller = new Jaxb2Marshaller() {
<add> @Override
<add> protected javax.xml.bind.Unmarshaller createUnmarshaller() {
<add> return unmarshaller;
<add> }
<add> };
<add>
<add> // 1. external-general-entities disabled (default)
<add>
<add> marshaller.unmarshal(new StreamSource("1"));
<add> ArgumentCaptor<SAXSource> sourceCaptor = ArgumentCaptor.forClass(SAXSource.class);
<add> verify(unmarshaller).unmarshal(sourceCaptor.capture());
<add>
<add> SAXSource result = sourceCaptor.getValue();
<add> assertEquals(false, result.getXMLReader().getFeature("http://xml.org/sax/features/external-general-entities"));
<add>
<add> // 2. external-general-entities enabled
<add>
<add> reset(unmarshaller);
<add> marshaller.setProcessExternalEntities(true);
<add>
<add> marshaller.unmarshal(new StreamSource("1"));
<add> verify(unmarshaller).unmarshal(sourceCaptor.capture());
<add>
<add> result = sourceCaptor.getValue();
<add> assertEquals(true, result.getXMLReader().getFeature("http://xml.org/sax/features/external-general-entities"));
<add> }
<add>
<add> // SPR-10806
<add>
<add> @Test
<add> public void unmarshalSaxSourceExternalEntities() throws Exception {
<add>
<add> final javax.xml.bind.Unmarshaller unmarshaller = mock(javax.xml.bind.Unmarshaller.class);
<add> Jaxb2Marshaller marshaller = new Jaxb2Marshaller() {
<add> @Override
<add> protected javax.xml.bind.Unmarshaller createUnmarshaller() {
<add> return unmarshaller;
<add> }
<add> };
<add>
<add> // 1. external-general-entities disabled (default)
<add>
<add> marshaller.unmarshal(new SAXSource(new InputSource("1")));
<add> ArgumentCaptor<SAXSource> sourceCaptor = ArgumentCaptor.forClass(SAXSource.class);
<add> verify(unmarshaller).unmarshal(sourceCaptor.capture());
<add>
<add> SAXSource result = sourceCaptor.getValue();
<add> assertEquals(false, result.getXMLReader().getFeature("http://xml.org/sax/features/external-general-entities"));
<add>
<add> // 2. external-general-entities enabled
<add>
<add> reset(unmarshaller);
<add> marshaller.setProcessExternalEntities(true);
<add>
<add> marshaller.unmarshal(new SAXSource(new InputSource("1")));
<add> verify(unmarshaller).unmarshal(sourceCaptor.capture());
<add>
<add> result = sourceCaptor.getValue();
<add> assertEquals(true, result.getXMLReader().getFeature("http://xml.org/sax/features/external-general-entities"));
<add> }
<add>
<add>
<ide> @XmlRootElement
<ide> @SuppressWarnings("unused")
<ide> public static class DummyRootElement {
<ide><path>spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java
<ide>
<ide> package org.springframework.oxm.jibx;
<ide>
<add>import java.io.IOException;
<ide> import java.io.StringWriter;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>import javax.xml.transform.sax.SAXSource;
<ide> import javax.xml.transform.stream.StreamResult;
<add>import javax.xml.transform.stream.StreamSource;
<ide>
<ide> import org.custommonkey.xmlunit.XMLUnit;
<ide> import org.junit.BeforeClass;
<ide> import org.junit.Test;
<ide>
<add>import org.mockito.ArgumentCaptor;
<ide> import org.springframework.oxm.AbstractMarshallerTests;
<ide> import org.springframework.oxm.Marshaller;
<add>import org.springframework.oxm.XmlMappingException;
<add>import org.springframework.oxm.jaxb.Jaxb2Marshaller;
<ide> import org.springframework.tests.Assume;
<ide> import org.springframework.tests.TestGroup;
<add>import org.xml.sax.InputSource;
<add>import org.xml.sax.XMLReader;
<ide>
<ide> import static org.custommonkey.xmlunit.XMLAssert.*;
<add>import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertFalse;
<ide> import static org.junit.Assert.assertTrue;
<add>import static org.mockito.Mockito.mock;
<add>import static org.mockito.Mockito.reset;
<add>import static org.mockito.Mockito.verify;
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<ide> public void testSupports() throws Exception {
<ide> assertFalse("JibxMarshaller supports illegal type", marshaller.supports(getClass()));
<ide> }
<ide>
<del>
<ide> }
<ide><path>spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxUnmarshallerTests.java
<ide> import org.springframework.tests.Assume;
<ide> import org.springframework.tests.TestGroup;
<ide>
<del>import static org.junit.Assert.*;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertNotNull;
<add>
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<ide><path>spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2014 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 javax.xml.bind.annotation.XmlType;
<ide> import javax.xml.transform.Result;
<ide> import javax.xml.transform.Source;
<add>import javax.xml.transform.dom.DOMSource;
<add>import javax.xml.transform.sax.SAXSource;
<add>import javax.xml.transform.stream.StreamSource;
<ide>
<ide> import org.springframework.core.annotation.AnnotationUtils;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.converter.HttpMessageNotReadableException;
<ide> import org.springframework.http.converter.HttpMessageNotWritableException;
<ide> import org.springframework.util.ClassUtils;
<add>import org.springframework.util.xml.StaxUtils;
<add>import org.xml.sax.InputSource;
<add>import org.xml.sax.SAXException;
<add>import org.xml.sax.XMLReader;
<add>import org.xml.sax.helpers.XMLReaderFactory;
<ide>
<ide> /**
<ide> * Implementation of {@link org.springframework.http.converter.HttpMessageConverter HttpMessageConverter} that can read
<ide> */
<ide> public class Jaxb2RootElementHttpMessageConverter extends AbstractJaxb2HttpMessageConverter<Object> {
<ide>
<add> private boolean processExternalEntities = false;
<add>
<add>
<add> /**
<add> * Indicates whether external XML entities are processed when converting to a Source.
<add> * <p>Default is {@code false}, meaning that external entities are not resolved.
<add> */
<add> public void setProcessExternalEntities(boolean processExternalEntities) {
<add> this.processExternalEntities = processExternalEntities;
<add> }
<add>
<ide> @Override
<ide> public boolean canRead(Class<?> clazz, MediaType mediaType) {
<ide> return (clazz.isAnnotationPresent(XmlRootElement.class) || clazz.isAnnotationPresent(XmlType.class)) &&
<ide> protected boolean supports(Class<?> clazz) {
<ide> @Override
<ide> protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
<ide> try {
<add> source = processSource(source);
<ide> Unmarshaller unmarshaller = createUnmarshaller(clazz);
<ide> if (clazz.isAnnotationPresent(XmlRootElement.class)) {
<ide> return unmarshaller.unmarshal(source);
<ide> protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source sour
<ide> }
<ide> }
<ide>
<add> protected Source processSource(Source source) {
<add> if (source instanceof StreamSource) {
<add> StreamSource streamSource = (StreamSource) source;
<add> InputSource inputSource = new InputSource(streamSource.getInputStream());
<add> try {
<add> XMLReader xmlReader = XMLReaderFactory.createXMLReader();
<add> String featureName = "http://xml.org/sax/features/external-general-entities";
<add> xmlReader.setFeature(featureName, this.processExternalEntities);
<add> return new SAXSource(xmlReader, inputSource);
<add> }
<add> catch (SAXException ex) {
<add> logger.warn("Processing of external entities could not be disabled", ex);
<add> return source;
<add> }
<add> }
<add> else {
<add> return source;
<add> }
<add> }
<add>
<ide> @Override
<ide> protected void writeToResult(Object o, HttpHeaders headers, Result result) throws IOException {
<ide> try {
<ide><path>spring-web/src/main/java/org/springframework/http/converter/xml/SourceHttpMessageConverter.java
<ide> public void setProcessExternalEntities(boolean processExternalEntities) {
<ide> this.processExternalEntities = processExternalEntities;
<ide> }
<ide>
<add> /**
<add> * @return the configured value for whether XML external entities are allowed.
<add> */
<add> public boolean isProcessExternalEntities() {
<add> return this.processExternalEntities;
<add> }
<ide>
<ide> @Override
<ide> public boolean supports(Class<?> clazz) {
<ide> private SAXSource readSAXSource(InputStream body) throws IOException {
<ide> private Source readStAXSource(InputStream body) {
<ide> try {
<ide> XMLInputFactory inputFactory = XMLInputFactory.newFactory();
<del> inputFactory.setProperty(
<del> "javax.xml.stream.isSupportingExternalEntities", this.processExternalEntities);
<add> inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, this.processExternalEntities);
<ide> XMLStreamReader streamReader = inputFactory.createXMLStreamReader(body);
<ide> return new StAXSource(streamReader);
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverterTests.java
<ide> import org.springframework.aop.framework.AdvisedSupport;
<ide> import org.springframework.aop.framework.AopProxy;
<ide> import org.springframework.aop.framework.DefaultAopProxyFactory;
<add>import org.springframework.core.io.ClassPathResource;
<add>import org.springframework.core.io.Resource;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.MockHttpInputMessage;
<ide> import org.springframework.http.MockHttpOutputMessage;
<add>import org.springframework.http.converter.HttpMessageNotReadableException;
<add>import org.xml.sax.SAXParseException;
<ide>
<ide> /** @author Arjen Poutsma */
<ide> public class Jaxb2RootElementHttpMessageConverterTests {
<ide> public void readXmlType() throws Exception {
<ide> assertEquals("Invalid result", "Hello World", result.s);
<ide> }
<ide>
<add> @Test
<add> public void readXmlRootElementExternalEntityDisabled() throws Exception {
<add> Resource external = new ClassPathResource("external.txt", getClass());
<add> String content = "<!DOCTYPE root [" +
<add> " <!ELEMENT external ANY >\n" +
<add> " <!ENTITY ext SYSTEM \"" + external.getURI() + "\" >]>" +
<add> " <rootElement><external>&ext;</external></rootElement>";
<add> MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8"));
<add> RootElement rootElement = (RootElement) converter.read(RootElement.class, inputMessage);
<add>
<add> assertEquals("", rootElement.external);
<add> }
<add>
<add> @Test
<add> public void readXmlRootElementExternalEntityEnabled() throws Exception {
<add> Resource external = new ClassPathResource("external.txt", getClass());
<add> String content = "<!DOCTYPE root [" +
<add> " <!ELEMENT external ANY >\n" +
<add> " <!ENTITY ext SYSTEM \"" + external.getURI() + "\" >]>" +
<add> " <rootElement><external>&ext;</external></rootElement>";
<add> MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8"));
<add> this.converter.setProcessExternalEntities(true);
<add> RootElement rootElement = (RootElement) converter.read(RootElement.class, inputMessage);
<add>
<add> assertEquals("Foo Bar", rootElement.external);
<add> }
<add>
<ide> @Test
<ide> public void writeXmlRootElement() throws Exception {
<ide> MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
<ide> public static class RootElement {
<ide>
<ide> private Type type = new Type();
<ide>
<add> @XmlElement(required=false)
<add> public String external;
<add>
<ide> public Type getType() {
<ide> return this.type;
<ide> } | 13 |
Javascript | Javascript | use graceful-fs directly | 36dbe86208cbf89c68921bdbb3f2d2acd9281162 | <ide><path>packager/react-packager/src/DependencyResolver/Cache/__tests__/Cache-test.js
<ide> jest
<ide> });
<ide>
<ide> var Promise = require('promise');
<del>var fs = require('fs');
<add>var fs = require('graceful-fs');
<ide>
<ide> var Cache = require('../');
<ide>
<ide><path>packager/react-packager/src/DependencyResolver/Cache/index.js
<ide> 'use strict';
<ide>
<ide> const Promise = require('promise');
<del>const fs = require('fs');
<add>const fs = require('graceful-fs');
<ide> const getCacheFilePath = require('./lib/getCacheFilePath');
<ide> const isAbsolutePath = require('absolute-path');
<ide> const loadCacheSync = require('./lib/loadCacheSync');
<ide><path>packager/react-packager/src/DependencyResolver/Cache/lib/loadCacheSync.js
<ide> */
<ide> 'use strict';
<ide>
<del>const fs = require('fs');
<add>const fs = require('graceful-fs');
<ide>
<ide> function loadCacheSync(cachePath) {
<ide> if (!fs.existsSync(cachePath)) {
<ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/__tests__/DependencyGraph-test.js
<ide> jest
<ide> .mock('fs');
<ide>
<ide> var DependencyGraph = require('../index');
<del>var fs = require('fs');
<add>var fs = require('graceful-fs');
<ide>
<ide> describe('DependencyGraph', function() {
<ide> let defaults;
<ide><path>packager/react-packager/src/DependencyResolver/__tests__/Module-test.js
<ide> const Module = require('../Module');
<ide> const ModuleCache = require('../ModuleCache');
<ide> const DependencyGraphHelpers = require('../DependencyGraph/DependencyGraphHelpers');
<ide> const Promise = require('promise');
<del>const fs = require('fs');
<add>const fs = require('graceful-fs');
<ide>
<ide> describe('Module', () => {
<ide> const fileWatcher = {
<ide><path>packager/react-packager/src/DependencyResolver/crawlers/node.js
<ide>
<ide> const Promise = require('promise');
<ide> const debug = require('debug')('ReactNativePackager:DependencyGraph');
<del>const fs = require('fs');
<add>const fs = require('graceful-fs');
<ide> const path = require('path');
<ide>
<ide> const readDir = Promise.denodeify(fs.readdir);
<ide><path>packager/react-packager/src/DependencyResolver/fastfs.js
<ide> const Promise = require('promise');
<ide> const {EventEmitter} = require('events');
<ide>
<del>const fs = require('fs');
<add>const fs = require('graceful-fs');
<ide> const path = require('path');
<ide>
<ide> const readFile = Promise.denodeify(fs.readFile);
<ide><path>packager/react-packager/src/__mocks__/graceful-fs.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>module.exports = require('fs'); | 8 |
Javascript | Javascript | improve the sorting algorithm for routing | 2d26a36f4119ffa0f8b41157dbb2856f27a33420 | <ide><path>packages/ember-routing/lib/routable.js
<ide> Ember.Routable = Ember.Mixin.create({
<ide> var childStates = get(this, 'childStates'), match;
<ide>
<ide> childStates = childStates.sort(function(a, b) {
<add> var aDynamicSegments = getPath(a, 'routeMatcher.identifiers.length'),
<add> bDynamicSegments = getPath(b, 'routeMatcher.identifiers.length'),
<add> aRoute = get(a, 'route'),
<add> bRoute = get(b, 'route');
<add>
<add> if (aRoute.indexOf(bRoute) === 0) {
<add> return -1;
<add> } else if (bRoute.indexOf(aRoute) === 0) {
<add> return 1;
<add> }
<add>
<add> if (aDynamicSegments !== bDynamicSegments) {
<add> return aDynamicSegments - bDynamicSegments;
<add> }
<add>
<ide> return getPath(b, 'route.length') - getPath(a, 'route.length');
<ide> });
<ide> | 1 |
Text | Text | remove reference to the obsolete chrome extension | cafde93a407ea0a3c6d712b9373bb2c9bb800234 | <ide><path>TRIAGING.md
<ide> The labels are used later on for planning releases.
<ide>
<ide> ## Tips ##
<ide>
<del>* install [github pr helper extension](https://github.com/petebacondarwin/github-pr-helper) and become 356% more productive
<ide> * Label "resolution:*"
<ide> * these tags can be used for labeling a closed issue/PR with a reason why it was closed. (we can add reasons as we need them, right there are only a few rejection reasons. it doesn't make sense to label issues that were fixed or prs that were merged)
<ide> | 1 |
Javascript | Javascript | add falback redirects for external paths | 764d0405532ebe2646133b570c351f1963367d66 | <ide><path>server/component-passport.js
<ide> export default function setupPassport(app) {
<ide> Object.keys(passportProviders).map(function(strategy) {
<ide> var config = passportProviders[strategy];
<ide> config.session = config.session !== false;
<add>
<add> // https://stackoverflow.com/q/37430452
<add> let successRedirect = (req) => {
<add> if (!!req && req.session && req.session.returnTo) {
<add> var returnTo = req.session.returnTo;
<add> delete req.session.returnTo;
<add> return returnTo;
<add> }
<add> return config.successRedirect || '';
<add> };
<add> config.customCallback = !config.redirectWithToken
<add> ? null
<add> : function(req, res, next) {
<add> var url = require('url');
<add> passport.authenticate(
<add> strategy,
<add> {session: false},
<add> function(err, user, info) {
<add> if (err) {
<add> return next(err);
<add> }
<add>
<add> if (!user) {
<add> return res.redirect(config.failureRedirect);
<add> }
<add> var redirect = url.parse(successRedirect(req), true);
<add>
<add> delete redirect.search;
<add>
<add> redirect.query = {
<add> /* eslint-disable camelcase */
<add> access_token: info.accessToken.id,
<add> /* eslint-enable camelcase */
<add> userId: user.id.toString()
<add> };
<add> redirect = url.format(redirect);
<add> return res.redirect(redirect);
<add> }
<add> )(req, res, next);
<add> };
<add>
<ide> configurator.configureProvider(
<ide> strategy,
<ide> {
<ide><path>server/passport-providers.js
<ide> const successRedirect = '/settings';
<del>const failureRedirect = '/signin';
<add>const failureRedirect = '/';
<ide> const linkSuccessRedirect = '/settings';
<ide> const linkFailureRedirect = '/settings';
<ide>
<ide> export default {
<ide> callbackURL: '/auth/auth0/callback',
<ide> authPath: '/auth/auth0',
<ide> callbackPath: '/auth/auth0/callback',
<add> redirectWithToken: false,
<ide> successRedirect: successRedirect,
<ide> failureRedirect: failureRedirect,
<ide> scope: ['openid email'], | 2 |
Text | Text | update the dev requirements in readme | 2048354c8b72feb35eaa53dcc29e78a111e69cfb | <ide><path>README.md
<ide> Is is a great building block for automating distributed systems: large-scale web
<ide>
<ide> * *Any server*: docker can run on any x64 machine with a modern linux kernel - whether it's a laptop, a bare metal server or a VM. This makes it perfect for multi-cloud deployments.
<ide>
<del>* *Isolation*: docker isolates processes from each other and from the underlying host, using lightweight containers.
<add>* *Isolation*: docker isolates processes from each other and from the underlying host, using lightweight containers.
<ide>
<ide> * *Repeatability*: because containers are isolated in their own filesystem, they behave the same regardless of where, when, and alongside what they run.
<ide>
<ide> Setting up a dev environment
<ide> Instructions that is verified to work on Ubuntu 12.10,
<ide>
<ide> ```
<del>sudo apt-get -y install lxc wget bsdtar curl libsqlite3-dev golang
<add>sudo apt-get -y install lxc wget bsdtar curl libsqlite3-dev golang git pkg-config
<ide>
<ide> export GOPATH=~/go/
<ide> export PATH=$GOPATH/bin:$PATH | 1 |
Text | Text | fix typo in n-api.md | 12b3e0c1acb937d919fe03f27499a9775ef05bbf | <ide><path>doc/api/n-api.md
<ide> Native addons may need to allocate global state of which they make use during
<ide> their entire life cycle such that the state must be unique to each instance of
<ide> the addon.
<ide>
<del>To this env, N-API provides a way to allocate data such that its life cycle is
<add>To this end, N-API provides a way to allocate data such that its life cycle is
<ide> tied to the life cycle of the Agent.
<ide>
<ide> ### napi_set_instance_data | 1 |
Text | Text | fix the milestone link again | 75acdc93bc837b6f7a724c0cec081e8faf36cbfa | <ide><path>docs/topics/release-notes.md
<ide> You can determine your currently installed version using `pip freeze`:
<ide>
<ide> ### 3.0.1
<ide>
<del>**Date**: [December 2014][3.0.1][3.0.1-milestone]:
<add>**Date**: [December 2014][3.0.1-milestone].
<ide>
<ide> * More helpful error message when the default Serializer `create()` fails. ([#2013](https://github.com/tomchristie/django-rest-framework/issues/2013))
<ide> * Raise error when attempting to save serializer if data is not valid. ([#2098](https://github.com/tomchristie/django-rest-framework/issues/2098)) | 1 |
PHP | PHP | remove stripe config settings | 83d2ecc0e9cca7ae6989134dede4a5653a19430b | <ide><path>config/services.php
<ide> |--------------------------------------------------------------------------
<ide> |
<ide> | This file is for storing the credentials for third party services such
<del> | as Stripe, Mailgun, SparkPost and others. This file provides a sane
<add> | as Mailgun, SparkPost and others. This file provides a sane
<ide> | default location for this type of information, allowing packages
<ide> | to have a conventional place to find your various credentials.
<ide> |
<ide> 'secret' => env('SPARKPOST_SECRET'),
<ide> ],
<ide>
<del> 'stripe' => [
<del> 'model' => App\User::class,
<del> 'key' => env('STRIPE_KEY'),
<del> 'secret' => env('STRIPE_SECRET'),
<del> 'webhook' => [
<del> 'secret' => env('STRIPE_WEBHOOK_SECRET'),
<del> 'tolerance' => env('STRIPE_WEBHOOK_TOLERANCE', 300),
<del> ],
<del> ],
<del>
<ide> ]; | 1 |
Java | Java | use single executor for all tests | 2144fe465b58d788b889cf650feaf27df07c786b | <ide><path>rxjava-core/src/test/java/rx/schedulers/ExecutorSchedulerTest.java
<ide> import rx.Scheduler;
<ide> import rx.internal.util.RxThreadFactory;
<ide>
<add>import java.util.concurrent.Executor;
<ide> import java.util.concurrent.Executors;
<ide>
<ide> public class ExecutorSchedulerTest extends AbstractSchedulerConcurrencyTests {
<ide>
<add> final static Executor executor = Executors.newFixedThreadPool(2, new RxThreadFactory("TestCustomPool-"));
<add>
<ide> @Override
<ide> protected Scheduler getScheduler() {
<del> return Schedulers.from(Executors.newFixedThreadPool(2, new RxThreadFactory("TestCustomPool-")));
<add> return Schedulers.from(executor);
<ide> }
<ide>
<ide> } | 1 |
Text | Text | update readme to use the latest version of vjs | 167b7d874c705a504c092e0ccbc79ba19e8cc5f3 | <ide><path>README.md
<ide> Thanks to the awesome folks over at [Fastly][fastly], there's a free, CDN hosted version of Video.js that anyone can use. Add these tags to your document's `<head>`:
<ide>
<ide> ```html
<del><link href="//vjs.zencdn.net/5.19/video-js.min.css" rel="stylesheet">
<del><script src="//vjs.zencdn.net/5.19/video.min.js"></script>
<add><link href="//vjs.zencdn.net/6.7/video-js.min.css" rel="stylesheet">
<add><script src="//vjs.zencdn.net/6.7/video.min.js"></script>
<ide> ```
<ide> > For the latest version of video.js and URLs to use, check out the [Getting Started][getting-started] page on our website.
<ide>
<ide> Thanks to the awesome folks over at [Fastly][fastly], there's a free, CDN hosted
<ide> > <script src="https://unpkg.com/video.js/dist/video.js"></script>
<ide> >
<ide> > <!-- cdnjs -->
<del>> <link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/6.3.3/video-js.css" rel="stylesheet">
<del>> <script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/6.3.3/video.js"></script>
<add>> <link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/6.7.3/video-js.css" rel="stylesheet">
<add>> <script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/6.7.3/video.js"></script>
<ide> > ```
<ide>
<ide> Next, using Video.js is as simple as creating a `<video>` element, but with an additional `data-setup` attribute. At a minimum, this attribute must have a value of `'{}'`, but it can include any Video.js [options][options] - just make sure it contains valid JSON! | 1 |
Javascript | Javascript | upgrade basicevaluatedexpression to es6 | b1c7d5c8cf09d89b600d42f0d0c522714cd395b0 | <ide><path>lib/BasicEvaluatedExpression.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>function BasicEvaluatedExpression() {
<del> this.range = null;
<del>}
<del>module.exports = BasicEvaluatedExpression;
<ide>
<del>BasicEvaluatedExpression.prototype.isNull = function() {
<del> return !!this.null;
<del>};
<del>BasicEvaluatedExpression.prototype.isString = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "string");
<del>};
<del>BasicEvaluatedExpression.prototype.isNumber = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "number");
<del>};
<del>BasicEvaluatedExpression.prototype.isBoolean = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "bool");
<del>};
<del>BasicEvaluatedExpression.prototype.isRegExp = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "regExp");
<del>};
<del>BasicEvaluatedExpression.prototype.isConditional = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "options");
<del>};
<del>BasicEvaluatedExpression.prototype.isArray = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "items");
<del>};
<del>BasicEvaluatedExpression.prototype.isConstArray = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "array");
<del>};
<del>BasicEvaluatedExpression.prototype.isIdentifier = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "identifier");
<del>};
<del>BasicEvaluatedExpression.prototype.isWrapped = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "prefix") || Object.prototype.hasOwnProperty.call(this, "postfix");
<del>};
<del>BasicEvaluatedExpression.prototype.isTemplateString = function() {
<del> return Object.prototype.hasOwnProperty.call(this, "quasis");
<del>}
<del>BasicEvaluatedExpression.prototype.asBool = function() {
<del> if(this.isBoolean()) return this.bool;
<del> else if(this.isNull()) return false;
<del> else if(this.isString()) return !!this.string;
<del> else if(this.isNumber()) return !!this.number;
<del> else if(this.isRegExp()) return true;
<del> else if(this.isArray()) return true;
<del> else if(this.isConstArray()) return true;
<del> else if(this.isWrapped()) return this.prefix && this.prefix.asBool() || this.postfix && this.postfix.asBool() ? true : undefined;
<del> else if(this.isTemplateString()) {
<del> if(this.quasis.length === 1) return this.quasis[0].asBool();
<del> for(var i = 0; i < this.quasis.length; i++) {
<del> if(this.quasis[i].asBool()) return true;
<add>"use strict";
<add>
<add>class BasicEvaluatedExpression {
<add>
<add> constructor() {
<add> this.range = null;
<add> }
<add>
<add> isNull() {
<add> return !!this.null;
<add> }
<add>
<add> isString() {
<add> return Object.prototype.hasOwnProperty.call(this, "string");
<add> }
<add>
<add> isNumber() {
<add> return Object.prototype.hasOwnProperty.call(this, "number");
<add> }
<add>
<add> isBoolean() {
<add> return Object.prototype.hasOwnProperty.call(this, "bool");
<add> }
<add>
<add> isRegExp() {
<add> return Object.prototype.hasOwnProperty.call(this, "regExp");
<add> }
<add>
<add> isConditional() {
<add> return Object.prototype.hasOwnProperty.call(this, "options");
<add> }
<add>
<add> isArray() {
<add> return Object.prototype.hasOwnProperty.call(this, "items");
<add> }
<add>
<add> isConstArray() {
<add> return Object.prototype.hasOwnProperty.call(this, "array");
<add> }
<add>
<add> isIdentifier() {
<add> return Object.prototype.hasOwnProperty.call(this, "identifier");
<add> }
<add>
<add> isWrapped() {
<add> return Object.prototype.hasOwnProperty.call(this, "prefix") || Object.prototype.hasOwnProperty.call(this, "postfix");
<add> }
<add>
<add> isTemplateString() {
<add> return Object.prototype.hasOwnProperty.call(this, "quasis");
<add> }
<add>
<add> asBool() {
<add> if(this.isBoolean()) return this.bool;
<add> else if(this.isNull()) return false;
<add> else if(this.isString()) return !!this.string;
<add> else if(this.isNumber()) return !!this.number;
<add> else if(this.isRegExp()) return true;
<add> else if(this.isArray()) return true;
<add> else if(this.isConstArray()) return true;
<add> else if(this.isWrapped()) return this.prefix && this.prefix.asBool() || this.postfix && this.postfix.asBool() ? true : undefined;
<add> else if(this.isTemplateString()) {
<add> if(this.quasis.length === 1) return this.quasis[0].asBool();
<add> for(var i = 0; i < this.quasis.length; i++) {
<add> if(this.quasis[i].asBool()) return true;
<add> }
<add> // can't tell if string will be empty without executing
<ide> }
<del> // can't tell if string will be empty without executing
<del> }
<del> return undefined;
<del>};
<del>BasicEvaluatedExpression.prototype.set = function(value) {
<del> if(typeof value === "string") return this.setString(value);
<del> if(typeof value === "number") return this.setNumber(value);
<del> if(typeof value === "boolean") return this.setBoolean(value);
<del> if(value === null) return this.setNull();
<del> if(value instanceof RegExp) return this.setRegExp(value);
<del> if(Array.isArray(value)) return this.setArray(value);
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setString = function(str) {
<del> if(str === null)
<del> delete this.string;
<del> else
<del> this.string = str;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setNull = function() {
<del> this.null = true;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setNumber = function(num) {
<del> if(num === null)
<del> delete this.number;
<del> else
<del> this.number = num;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setBoolean = function(bool) {
<del> if(bool === null)
<del> delete this.bool;
<del> else
<del> this.bool = bool;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setRegExp = function(regExp) {
<del> if(regExp === null)
<del> delete this.regExp;
<del> else
<del> this.regExp = regExp;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setIdentifier = function(identifier) {
<del> if(identifier === null)
<del> delete this.identifier;
<del> else
<del> this.identifier = identifier;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setWrapped = function(prefix, postfix) {
<del> this.prefix = prefix;
<del> this.postfix = postfix;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.unsetWrapped = function() {
<del> delete this.prefix;
<del> delete this.postfix;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setOptions = function(options) {
<del> if(options === null)
<del> delete this.options;
<del> else
<del> this.options = options;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setItems = function(items) {
<del> if(items === null)
<del> delete this.items;
<del> else
<del> this.items = items;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setArray = function(array) {
<del> if(array === null)
<del> delete this.array;
<del> else
<del> this.array = array;
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setTemplateString = function(quasis) {
<del> if(quasis === null)
<del> delete this.quasis;
<del> else
<del> this.quasis = quasis;
<del> return this;
<add> return undefined;
<add> }
<add>
<add> setString(str) {
<add> if(str === null)
<add> delete this.string;
<add> else
<add> this.string = str;
<add> return this;
<add> }
<add>
<add> setNull() {
<add> this.null = true;
<add> return this;
<add> }
<add>
<add> setNumber(num) {
<add> if(num === null)
<add> delete this.number;
<add> else
<add> this.number = num;
<add> return this;
<add> }
<add>
<add> setBoolean(bool) {
<add> if(bool === null)
<add> delete this.bool;
<add> else
<add> this.bool = bool;
<add> return this;
<add> }
<add>
<add> setRegExp(regExp) {
<add> if(regExp === null)
<add> delete this.regExp;
<add> else
<add> this.regExp = regExp;
<add> return this;
<add> }
<add>
<add> setIdentifier(identifier) {
<add> if(identifier === null)
<add> delete this.identifier;
<add> else
<add> this.identifier = identifier;
<add> return this;
<add> }
<add>
<add> setWrapped(prefix, postfix) {
<add> this.prefix = prefix;
<add> this.postfix = postfix;
<add> return this;
<add> }
<add>
<add> unsetWrapped() {
<add> delete this.prefix;
<add> delete this.postfix;
<add> return this;
<add> }
<add>
<add> setOptions(options) {
<add> if(options === null)
<add> delete this.options;
<add> else
<add> this.options = options;
<add> return this;
<add> }
<add>
<add> setItems(items) {
<add> if(items === null)
<add> delete this.items;
<add> else
<add> this.items = items;
<add> return this;
<add> }
<add>
<add> setArray(array) {
<add> if(array === null)
<add> delete this.array;
<add> else
<add> this.array = array;
<add> return this;
<add> }
<add>
<add> setTemplateString(quasis) {
<add> if(quasis === null)
<add> delete this.quasis;
<add> else
<add> this.quasis = quasis;
<add> return this;
<add> }
<add>
<add> addOptions(options) {
<add> if(!this.options) this.options = [];
<add> options.forEach(item => {
<add> this.options.push(item);
<add> }, this);
<add> return this;
<add> }
<add>
<add> setRange(range) {
<add> this.range = range;
<add> return this;
<add> }
<add>
<ide> }
<del>BasicEvaluatedExpression.prototype.addOptions = function(options) {
<del> if(!this.options) this.options = [];
<del> options.forEach(function(item) {
<del> this.options.push(item);
<del> }, this);
<del> return this;
<del>};
<del>BasicEvaluatedExpression.prototype.setRange = function(range) {
<del> this.range = range;
<del> return this;
<del>};
<add>
<add>module.exports = BasicEvaluatedExpression; | 1 |
Python | Python | add gated-silu to t5 | 607acd4fbd175feb458eda7317419cdee5d443fe | <ide><path>src/transformers/models/t5/configuration_t5.py
<ide> def __init__(
<ide> self.initializer_factor = initializer_factor
<ide> self.feed_forward_proj = feed_forward_proj
<ide> self.use_cache = use_cache
<add>
<add> act_info = self.feed_forward_proj.split("-")
<add> self.dense_act_fn = act_info[-1]
<add> self.is_gated_act = act_info[0] == "gated"
<add>
<add> if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
<add> raise ValueError(
<add> f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
<add> "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
<add> "'gated-gelu' or 'relu'"
<add> )
<add>
<add> # for backwards compatibility
<add> if feed_forward_proj == "gated-gelu":
<add> self.dense_act_fn = "gelu_new"
<add>
<ide> super().__init__(
<ide> pad_token_id=pad_token_id,
<ide> eos_token_id=eos_token_id,
<ide><path>src/transformers/models/t5/modeling_flax_t5.py
<ide> def __call__(self, hidden_states):
<ide> return self.weight * hidden_states
<ide>
<ide>
<del>class FlaxT5DenseReluDense(nn.Module):
<add>class FlaxT5DenseActDense(nn.Module):
<ide> config: T5Config
<ide> dtype: jnp.dtype = jnp.float32
<ide>
<ide> def setup(self):
<ide> dtype=self.dtype,
<ide> )
<ide> self.dropout = nn.Dropout(self.config.dropout_rate)
<add> self.act = ACT2FN[self.config.dense_act_fn]
<ide>
<ide> def __call__(self, hidden_states, deterministic=True):
<ide> hidden_states = self.wi(hidden_states)
<del> hidden_states = jax.nn.relu(hidden_states)
<add> hidden_states = self.act(hidden_states)
<ide> hidden_states = self.dropout(hidden_states, deterministic=deterministic)
<ide> hidden_states = self.wo(hidden_states)
<ide> return hidden_states
<ide>
<ide>
<del>class FlaxT5DenseGatedGeluDense(nn.Module):
<add>class FlaxT5DenseGatedActDense(nn.Module):
<ide> config: T5Config
<ide> dtype: jnp.dtype = jnp.float32 # the dtype of the computation
<ide>
<ide> def setup(self):
<ide> dtype=self.dtype,
<ide> )
<ide> self.dropout = nn.Dropout(self.config.dropout_rate)
<del> self.gelu_act = ACT2FN["gelu_new"]
<add> self.act = ACT2FN[self.config.dense_act_fn]
<ide>
<ide> def __call__(self, hidden_states, deterministic):
<del> hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
<add> hidden_gelu = self.act(self.wi_0(hidden_states))
<ide> hidden_linear = self.wi_1(hidden_states)
<ide> hidden_states = hidden_gelu * hidden_linear
<ide> hidden_states = self.dropout(hidden_states, deterministic=deterministic)
<ide> class FlaxT5LayerFF(nn.Module):
<ide> dtype: jnp.dtype = jnp.float32 # the dtype of the computation
<ide>
<ide> def setup(self):
<del> if self.config.feed_forward_proj == "relu":
<del> self.DenseReluDense = FlaxT5DenseReluDense(self.config, dtype=self.dtype)
<del> elif self.config.feed_forward_proj == "gated-gelu":
<del> self.DenseReluDense = FlaxT5DenseGatedGeluDense(self.config, dtype=self.dtype)
<add> if self.config.is_gated_act:
<add> self.DenseReluDense = FlaxT5DenseGatedActDense(self.config, dtype=self.dtype)
<ide> else:
<del> raise ValueError(
<del> f"{self.config.feed_forward_proj} is not supported. Choose between `relu` and `gated-gelu`"
<del> )
<add> self.DenseReluDense = FlaxT5DenseActDense(self.config, dtype=self.dtype)
<ide>
<ide> self.layer_norm = FlaxT5LayerNorm(self.config.d_model, eps=self.config.layer_norm_epsilon, dtype=self.dtype)
<ide> self.dropout = nn.Dropout(self.config.dropout_rate)
<ide><path>src/transformers/models/t5/modeling_t5.py
<ide> def forward(self, hidden_states):
<ide> pass
<ide>
<ide>
<del>class T5DenseReluDense(nn.Module):
<add>class T5DenseActDense(nn.Module):
<ide> def __init__(self, config: T5Config):
<ide> super().__init__()
<ide> self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)
<ide> self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
<ide> self.dropout = nn.Dropout(config.dropout_rate)
<del> self.relu_act = ACT2FN["relu"]
<add> self.act = ACT2FN[config.dense_act_fn]
<ide>
<ide> def forward(self, hidden_states):
<ide> hidden_states = self.wi(hidden_states)
<del> hidden_states = self.relu_act(hidden_states)
<add> hidden_states = self.act(hidden_states)
<ide> hidden_states = self.dropout(hidden_states)
<ide> hidden_states = self.wo(hidden_states)
<ide> return hidden_states
<ide>
<ide>
<del>class T5DenseGatedGeluDense(nn.Module):
<add>class T5DenseGatedActDense(nn.Module):
<ide> def __init__(self, config: T5Config):
<ide> super().__init__()
<ide> self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
<ide> self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
<ide> self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
<ide> self.dropout = nn.Dropout(config.dropout_rate)
<del> self.gelu_act = ACT2FN["gelu_new"]
<add> self.act = ACT2FN[config.dense_act_fn]
<ide>
<ide> def forward(self, hidden_states):
<del> hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
<add> hidden_gelu = self.act(self.wi_0(hidden_states))
<ide> hidden_linear = self.wi_1(hidden_states)
<ide> hidden_states = hidden_gelu * hidden_linear
<ide> hidden_states = self.dropout(hidden_states)
<ide> def forward(self, hidden_states):
<ide> class T5LayerFF(nn.Module):
<ide> def __init__(self, config: T5Config):
<ide> super().__init__()
<del> if config.feed_forward_proj == "relu":
<del> self.DenseReluDense = T5DenseReluDense(config)
<del> elif config.feed_forward_proj == "gated-gelu":
<del> self.DenseReluDense = T5DenseGatedGeluDense(config)
<add> if config.is_gated_act:
<add> self.DenseReluDense = T5DenseGatedActDense(config)
<ide> else:
<del> raise ValueError(
<del> f"{self.config.feed_forward_proj} is not supported. Choose between `relu` and `gated-gelu`"
<del> )
<add> self.DenseReluDense = T5DenseActDense(config)
<ide>
<ide> self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
<ide> self.dropout = nn.Dropout(config.dropout_rate)
<ide> def _init_weights(self, module):
<ide> module.shared.weight.data.normal_(mean=0.0, std=factor * 1.0)
<ide> if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
<ide> module.lm_head.weight.data.normal_(mean=0.0, std=factor * 1.0)
<del> elif isinstance(module, T5DenseReluDense):
<add> elif isinstance(module, T5DenseActDense):
<ide> # Mesh TensorFlow FF initialization
<ide> # See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
<ide> # and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
<ide> def _init_weights(self, module):
<ide> module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
<ide> if hasattr(module.wo, "bias") and module.wo.bias is not None:
<ide> module.wo.bias.data.zero_()
<del> elif isinstance(module, T5DenseGatedGeluDense):
<add> elif isinstance(module, T5DenseGatedActDense):
<ide> module.wi_0.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
<ide> if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
<ide> module.wi_0.bias.data.zero_()
<ide><path>src/transformers/models/t5/modeling_tf_t5.py
<ide> def call(self, hidden_states):
<ide> return self.weight * hidden_states
<ide>
<ide>
<del>class TFT5DenseReluDense(tf.keras.layers.Layer):
<add>class TFT5DenseActDense(tf.keras.layers.Layer):
<ide> def __init__(self, config, **kwargs):
<ide> super().__init__(**kwargs)
<ide> wi_initializer = tf.keras.initializers.RandomNormal(
<ide> def __init__(self, config, **kwargs):
<ide> config.d_model, use_bias=False, name="wo", kernel_initializer=wo_initializer
<ide> ) # Update init weights as in flax
<ide> self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
<del> self.act = tf.keras.activations.relu
<add> self.act = get_tf_activation(config.dense_act_fn)
<ide>
<ide> def call(self, hidden_states, training=False):
<ide> hidden_states = self.wi(hidden_states)
<ide> def call(self, hidden_states, training=False):
<ide> return hidden_states
<ide>
<ide>
<del>class TFT5GatedGeluDense(tf.keras.layers.Layer):
<add>class TFT5DenseGatedActDense(tf.keras.layers.Layer):
<ide> def __init__(self, config, **kwargs):
<ide> super().__init__(**kwargs)
<ide> wi_initializer = tf.keras.initializers.RandomNormal(
<ide> def __init__(self, config, **kwargs):
<ide> config.d_model, use_bias=False, name="wo", kernel_initializer=wo_initializer
<ide> ) # Update init weights as in flax
<ide> self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
<del> self.act = get_tf_activation("gelu_new")
<add> self.act = get_tf_activation(config.dense_act_fn)
<ide>
<ide> def call(self, hidden_states, training=False):
<ide> hidden_gelu = self.act(self.wi_0(hidden_states))
<ide> def call(self, hidden_states, training=False):
<ide> class TFT5LayerFF(tf.keras.layers.Layer):
<ide> def __init__(self, config, **kwargs):
<ide> super().__init__(**kwargs)
<del> if config.feed_forward_proj == "relu":
<del> self.DenseReluDense = TFT5DenseReluDense(config, name="DenseReluDense")
<del> elif config.feed_forward_proj == "gated-gelu":
<del> self.DenseReluDense = TFT5GatedGeluDense(config, name="DenseReluDense")
<add> if config.is_gated_act:
<add> self.DenseReluDense = TFT5DenseGatedActDense(config, name="DenseReluDense")
<ide> else:
<del> raise ValueError(
<del> f"{self.config.feed_forward_proj} is not supported. Choose between `relu` and `gated-gelu`"
<del> )
<add> self.DenseReluDense = TFT5DenseActDense(config, name="DenseReluDense")
<add>
<ide> self.layer_norm = TFT5LayerNorm(epsilon=config.layer_norm_epsilon, name="layer_norm")
<ide> self.dropout = tf.keras.layers.Dropout(config.dropout_rate)
<ide>
<ide><path>tests/models/t5/test_modeling_t5.py
<ide> def test_model_v1_1(self):
<ide> config.feed_forward_proj = "gated-gelu"
<ide> self.model_tester.create_and_check_model(config, *config_and_inputs[1:])
<ide>
<add> def test_config_and_model_silu_gated(self):
<add> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<add> config = config_and_inputs[0]
<add> config.feed_forward_proj = "gated-silu"
<add> self.model_tester.create_and_check_model(*config_and_inputs)
<add>
<ide> def test_with_lm_head(self):
<ide> config_and_inputs = self.model_tester.prepare_config_and_inputs()
<ide> self.model_tester.create_and_check_with_lm_head(*config_and_inputs) | 5 |
Python | Python | add auto models and auto tokenizer | ac42049c0877104632cff44d52ddb0a06d927ee0 | <ide><path>pytorch_transformers/modeling_auto.py
<add># coding=utf-8
<add># Copyright 2018 The HuggingFace Inc. team.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>""" Auto Model class. """
<add>
<add>from __future__ import absolute_import, division, print_function, unicode_literals
<add>
<add>import logging
<add>
<add>from .modeling_bert import BertConfig, BertModel
<add>from .modeling_openai import OpenAIGPTConfig, OpenAIGPTModel
<add>from .modeling_gpt2 import GPT2Config, GPT2Model
<add>from .modeling_transfo_xl import TransfoXLConfig, TransfoXLModel
<add>from .modeling_xlnet import XLNetConfig, XLNetModel
<add>from .modeling_xlm import XLMConfig, XLMModel
<add>
<add>logger = logging.getLogger(__name__)
<add>
<add>class AutoConfig(object):
<add> r""":class:`~pytorch_transformers.AutoConfig` is a generic configuration class
<add> that will be instantiated as one of the configuration classes of the library
<add> when created with the `AutoConfig.from_pretrained(pretrained_model_name_or_path)`
<add> class method.
<add>
<add> The `from_pretrained()` method take care of returning the correct model class instance
<add> using pattern matching on the `pretrained_model_name_or_path` string.
<add>
<add> The base model class to instantiate is selected as the first pattern matching
<add> in the `pretrained_model_name_or_path` string (in the following order):
<add> - contains `bert`: BertConfig (Bert model)
<add> - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model)
<add> - contains `gpt2`: GPT2Config (OpenAI GPT-2 model)
<add> - contains `transfo-xl`: TransfoXLConfig (Transformer-XL model)
<add> - contains `xlnet`: XLNetConfig (XLNet model)
<add> - contains `xlm`: XLMConfig (XLM model)
<add>
<add> This class cannot be instantiated using `__init__()` (throw an error).
<add> """
<add> def __init__(self):
<add> raise EnvironmentError("AutoConfig is designed to be instantiated "
<add> "using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method.")
<add>
<add> @classmethod
<add> def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
<add> r""" Instantiate a one of the configuration classes of the library
<add> from a pre-trained model configuration.
<add>
<add> The configuration class to instantiate is selected as the first pattern matching
<add> in the `pretrained_model_name_or_path` string (in the following order):
<add> - contains `bert`: BertConfig (Bert model)
<add> - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model)
<add> - contains `gpt2`: GPT2Config (OpenAI GPT-2 model)
<add> - contains `transfo-xl`: TransfoXLConfig (Transformer-XL model)
<add> - contains `xlnet`: XLNetConfig (XLNet model)
<add> - contains `xlm`: XLMConfig (XLM model)
<add>
<add> Params:
<add> **pretrained_model_name_or_path**: either:
<add> - a string with the `shortcut name` of a pre-trained model configuration to load from cache
<add> or download and cache if not already stored in cache (e.g. 'bert-base-uncased').
<add> - a path to a `directory` containing a configuration file saved
<add> using the `save_pretrained(save_directory)` method.
<add> - a path or url to a saved configuration `file`.
<add> **cache_dir**: (`optional`) string:
<add> Path to a directory in which a downloaded pre-trained model
<add> configuration should be cached if the standard cache should not be used.
<add> **return_unused_kwargs**: (`optional`) bool:
<add> - If False, then this function returns just the final configuration object.
<add> - If True, then this functions returns a tuple `(config, unused_kwargs)` where `unused_kwargs`
<add> is a dictionary consisting of the key/value pairs whose keys are not configuration attributes:
<add> ie the part of kwargs which has not been used to update `config` and is otherwise ignored.
<add> **kwargs**: (`optional`) dict:
<add> Dictionary of key/value pairs with which to update the configuration object after loading.
<add> - The values in kwargs of any keys which are configuration attributes will be used
<add> to override the loaded values.
<add> - Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled
<add> by the `return_unused_kwargs` keyword parameter.
<add>
<add> Examples::
<add>
<add> >>> config = AutoConfig.from_pretrained('bert-base-uncased') # Download configuration from S3 and cache.
<add> >>> config = AutoConfig.from_pretrained('./test/bert_saved_model/') # E.g. config (or model) was saved using `save_pretrained('./test/saved_model/')`
<add> >>> config = AutoConfig.from_pretrained('./test/bert_saved_model/my_configuration.json')
<add> >>> config = AutoConfig.from_pretrained('bert-base-uncased', output_attention=True, foo=False)
<add> >>> assert config.output_attention == True
<add> >>> config, unused_kwargs = AutoConfig.from_pretrained('bert-base-uncased', output_attention=True,
<add> >>> foo=False, return_unused_kwargs=True)
<add> >>> assert config.output_attention == True
<add> >>> assert unused_kwargs == {'foo': False}
<add>
<add> """
<add> if 'bert' in pretrained_model_name_or_path:
<add> return BertConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
<add> elif 'openai-gpt' in pretrained_model_name_or_path:
<add> return OpenAIGPTConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
<add> elif 'gpt2' in pretrained_model_name_or_path:
<add> return GPT2Config.from_pretrained(pretrained_model_name_or_path, **kwargs)
<add> elif 'transfo-xl' in pretrained_model_name_or_path:
<add> return TransfoXLConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
<add> elif 'xlnet' in pretrained_model_name_or_path:
<add> return XLNetConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
<add> elif 'xlm' in pretrained_model_name_or_path:
<add> return XLMConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
<add>
<add> raise ValueError("Unrecognized model identifier in {}. Should contains one of "
<add> "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', "
<add> "'xlm'".format(pretrained_model_name_or_path))
<add>
<add>
<add>class AutoModel(object):
<add> r"""
<add> :class:`~pytorch_transformers.AutoModel` is a generic model class
<add> that will be instantiated as one of the base model classes of the library
<add> when created with the `AutoModel.from_pretrained(pretrained_model_name_or_path)`
<add> class method.
<add>
<add> The `from_pretrained()` method take care of returning the correct model class instance
<add> using pattern matching on the `pretrained_model_name_or_path` string.
<add>
<add> The base model class to instantiate is selected as the first pattern matching
<add> in the `pretrained_model_name_or_path` string (in the following order):
<add> - contains `bert`: BertConfig (Bert model)
<add> - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model)
<add> - contains `gpt2`: GPT2Config (OpenAI GPT-2 model)
<add> - contains `transfo-xl`: TransfoXLConfig (Transformer-XL model)
<add> - contains `xlnet`: XLNetConfig (XLNet model)
<add> - contains `xlm`: XLMConfig (XLM model)
<add>
<add> This class cannot be instantiated using `__init__()` (throw an error).
<add> """
<add> def __init__(self):
<add> raise EnvironmentError("AutoModel is designed to be instantiated "
<add> "using the `AutoModel.from_pretrained(pretrained_model_name_or_path)` method.")
<add>
<add> @classmethod
<add> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<add> r""" Instantiate a one of the base model classes of the library
<add> from a pre-trained model configuration.
<add>
<add> The base model class to instantiate is selected as the first pattern matching
<add> in the `pretrained_model_name_or_path` string (in the following order):
<add> - contains `bert`: BertConfig (Bert model)
<add> - contains `openai-gpt`: OpenAIGPTConfig (OpenAI GPT model)
<add> - contains `gpt2`: GPT2Config (OpenAI GPT-2 model)
<add> - contains `transfo-xl`: TransfoXLConfig (Transformer-XL model)
<add> - contains `xlnet`: XLNetConfig (XLNet model)
<add> - contains `xlm`: XLMConfig (XLM model)
<add>
<add> The model is set in evaluation mode by default using `model.eval()` (Dropout modules are desactivated)
<add> To train the model, you should first set it back in training mode with `model.train()`
<add>
<add> Params:
<add> **pretrained_model_name_or_path**: either:
<add> - a string with the `shortcut name` of a pre-trained model to load from cache
<add> or download and cache if not already stored in cache (e.g. 'bert-base-uncased').
<add> - a path to a `directory` containing a configuration file saved
<add> using the `save_pretrained(save_directory)` method.
<add> - a path or url to a tensorflow index checkpoint `file` (e.g. `./tf_model/model.ckpt.index`).
<add> In this case, ``from_tf`` should be set to True and a configuration object should be
<add> provided as `config` argument. This loading option is slower than converting the TensorFlow
<add> checkpoint in a PyTorch model using the provided conversion scripts and loading
<add> the PyTorch model afterwards.
<add> **model_args**: (`optional`) Sequence:
<add> All remaning positional arguments will be passed to the underlying model's __init__ function
<add> **config**: an optional configuration for the model to use instead of an automatically loaded configuation.
<add> Configuration can be automatically loaded when:
<add> - the model is a model provided by the library (loaded with a `shortcut name` of a pre-trained model), or
<add> - the model was saved using the `save_pretrained(save_directory)` (loaded by suppling the save directory).
<add> **state_dict**: an optional state dictionnary for the model to use instead of a state dictionary loaded
<add> from saved weights file.
<add> This option can be used if you want to create a model from a pretrained configuraton but load your own weights.
<add> In this case though, you should check if using `save_pretrained(dir)` and `from_pretrained(save_directory)` is not
<add> a simpler option.
<add> **cache_dir**: (`optional`) string:
<add> Path to a directory in which a downloaded pre-trained model
<add> configuration should be cached if the standard cache should not be used.
<add> **output_loading_info**: (`optional`) boolean:
<add> Set to ``True`` to also return a dictionnary containing missing keys, unexpected keys and error messages.
<add> **kwargs**: (`optional`) dict:
<add> Dictionary of key, values to update the configuration object after loading.
<add> Can be used to override selected configuration parameters. E.g. ``output_attention=True``.
<add>
<add> - If a configuration is provided with `config`, **kwargs will be directly passed
<add> to the underlying model's __init__ method.
<add> - If a configuration is not provided, **kwargs will be first passed to the pretrained
<add> model configuration class loading function (`PretrainedConfig.from_pretrained`).
<add> Each key of **kwargs that corresponds to a configuration attribute
<add> will be used to override said attribute with the supplied **kwargs value.
<add> Remaining keys that do not correspond to any configuration attribute will
<add> be passed to the underlying model's __init__ function.
<add>
<add> Examples::
<add>
<add> >>> model = AutoModel.from_pretrained('bert-base-uncased') # Download model and configuration from S3 and cache.
<add> >>> model = AutoModel.from_pretrained('./test/bert_model/') # E.g. model was saved using `save_pretrained('./test/saved_model/')`
<add> >>> model = AutoModel.from_pretrained('bert-base-uncased', output_attention=True) # Update configuration during loading
<add> >>> assert model.config.output_attention == True
<add> >>> # Loading from a TF checkpoint file instead of a PyTorch model (slower)
<add> >>> config = AutoConfig.from_json_file('./tf_model/bert_tf_model_config.json')
<add> >>> model = AutoModel.from_pretrained('./tf_model/bert_tf_checkpoint.ckpt.index', from_tf=True, config=config)
<add>
<add> """
<add> if 'bert' in pretrained_model_name_or_path:
<add> return BertModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
<add> elif 'openai-gpt' in pretrained_model_name_or_path:
<add> return OpenAIGPTModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
<add> elif 'gpt2' in pretrained_model_name_or_path:
<add> return GPT2Model.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
<add> elif 'transfo-xl' in pretrained_model_name_or_path:
<add> return TransfoXLModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
<add> elif 'xlnet' in pretrained_model_name_or_path:
<add> return XLNetModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
<add> elif 'xlm' in pretrained_model_name_or_path:
<add> return XLMModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
<add>
<add> raise ValueError("Unrecognized model identifier in {}. Should contains one of "
<add> "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', "
<add> "'xlm'".format(pretrained_model_name_or_path))
<add>
<ide><path>pytorch_transformers/tokenization_auto.py
<add># coding=utf-8
<add># Copyright 2018 The HuggingFace Inc. team.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>""" Auto Model class. """
<add>
<add>from __future__ import absolute_import, division, print_function, unicode_literals
<add>
<add>import logging
<add>
<add>from .tokenization_bert import BertTokenizer
<add>from .tokenization_openai import OpenAIGPTTokenizer
<add>from .tokenization_gpt2 import GPT2Tokenizer
<add>from .tokenization_transfo_xl import TransfoXLTokenizer
<add>from .tokenization_xlnet import XLNetTokenizer
<add>from .tokenization_xlm import XLMTokenizer
<add>
<add>logger = logging.getLogger(__name__)
<add>
<add>class AutoTokenizer(object):
<add> r""":class:`~pytorch_transformers.AutoTokenizer` is a generic tokenizer class
<add> that will be instantiated as one of the tokenizer classes of the library
<add> when created with the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)`
<add> class method.
<add>
<add> The `from_pretrained()` method take care of returning the correct tokenizer class instance
<add> using pattern matching on the `pretrained_model_name_or_path` string.
<add>
<add> The tokenizer class to instantiate is selected as the first pattern matching
<add> in the `pretrained_model_name_or_path` string (in the following order):
<add> - contains `bert`: BertTokenizer (Bert model)
<add> - contains `openai-gpt`: OpenAIGPTTokenizer (OpenAI GPT model)
<add> - contains `gpt2`: GPT2Tokenizer (OpenAI GPT-2 model)
<add> - contains `transfo-xl`: TransfoXLTokenizer (Transformer-XL model)
<add> - contains `xlnet`: XLNetTokenizer (XLNet model)
<add> - contains `xlm`: XLMTokenizer (XLM model)
<add>
<add> This class cannot be instantiated using `__init__()` (throw an error).
<add> """
<add> def __init__(self):
<add> raise EnvironmentError("AutoTokenizer is designed to be instantiated "
<add> "using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method.")
<add>
<add> @classmethod
<add> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
<add> r""" Instantiate a one of the tokenizer classes of the library
<add> from a pre-trained model vocabulary.
<add>
<add> The tokenizer class to instantiate is selected as the first pattern matching
<add> in the `pretrained_model_name_or_path` string (in the following order):
<add> - contains `bert`: BertTokenizer (Bert model)
<add> - contains `openai-gpt`: OpenAIGPTTokenizer (OpenAI GPT model)
<add> - contains `gpt2`: GPT2Tokenizer (OpenAI GPT-2 model)
<add> - contains `transfo-xl`: TransfoXLTokenizer (Transformer-XL model)
<add> - contains `xlnet`: XLNetTokenizer (XLNet model)
<add> - contains `xlm`: XLMTokenizer (XLM model)
<add>
<add> Params:
<add> **pretrained_model_name_or_path**: either:
<add> - a string with the `shortcut name` of a pre-trained model configuration to load from cache
<add> or download and cache if not already stored in cache (e.g. 'bert-base-uncased').
<add> - a path to a `directory` containing a configuration file saved
<add> using the `save_pretrained(save_directory)` method.
<add> - a path or url to a saved configuration `file`.
<add> **cache_dir**: (`optional`) string:
<add> Path to a directory in which a downloaded pre-trained model
<add> configuration should be cached if the standard cache should not be used.
<add>
<add> Examples::
<add>
<add> >>> config = AutoTokenizer.from_pretrained('bert-base-uncased') # Download vocabulary from S3 and cache.
<add> >>> config = AutoTokenizer.from_pretrained('./test/bert_saved_model/') # E.g. tokenizer was saved using `save_pretrained('./test/saved_model/')`
<add>
<add> """
<add> if 'bert' in pretrained_model_name_or_path:
<add> return BertTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
<add> elif 'openai-gpt' in pretrained_model_name_or_path:
<add> return OpenAIGPTTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
<add> elif 'gpt2' in pretrained_model_name_or_path:
<add> return GPT2Tokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
<add> elif 'transfo-xl' in pretrained_model_name_or_path:
<add> return TransfoXLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
<add> elif 'xlnet' in pretrained_model_name_or_path:
<add> return XLNetTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
<add> elif 'xlm' in pretrained_model_name_or_path:
<add> return XLMTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
<add>
<add> raise ValueError("Unrecognized model identifier in {}. Should contains one of "
<add> "'bert', 'openai-gpt', 'gpt2', 'transfo-xl', 'xlnet', "
<add> "'xlm'".format(pretrained_model_name_or_path)) | 2 |
Text | Text | simplify minitest sample in autoloading guide | 1140f2926414e7baf5dc8805d02aa47ae4510b9d | <ide><path>guides/source/classic_to_zeitwerk_howto.md
<ide> require "test_helper"
<ide>
<ide> class ZeitwerkComplianceTest < ActiveSupport::TestCase
<ide> test "eager loads all files without errors" do
<del> Rails.application.eager_load!
<del> rescue => e
<del> flunk(e.message)
<del> else
<del> pass
<add> assert_nothing_raised { Rails.application.eager_load! }
<ide> end
<ide> end
<ide> ``` | 1 |
Python | Python | fix string formatting | aa8af10a160845df30a8b28470e866e02c68bdf5 | <ide><path>keras/backend.py
<ide> def resize_images(x, height_factor, width_factor, data_format,
<ide> height_factor: Positive integer.
<ide> width_factor: Positive integer.
<ide> data_format: One of `"channels_first"`, `"channels_last"`.
<del> interpolation: A string, one of `area`, `bicubic`, `bilinear`,
<del> `gaussian`, `lanczos3`, `lanczos5`, `mitchellcubic`, `nearest`.
<add> interpolation: A string, one of `"area"`, `"bicubic"`, `"bilinear"`,
<add> `"gaussian"`, `"lanczos3"`, `"lanczos5"`, `"mitchellcubic"`,
<add> `"nearest"`.
<ide>
<ide> Returns:
<ide> A tensor.
<ide> def resize_images(x, height_factor, width_factor, data_format,
<ide> 'mitchellcubic': tf.image.ResizeMethod.MITCHELLCUBIC,
<ide> 'nearest': tf.image.ResizeMethod.NEAREST_NEIGHBOR,
<ide> }
<del> interploations_list = '`' + '`, `'.join(interpolations.keys()) + '`'
<add> interploations_list = '"' + '", "'.join(interpolations.keys()) + '"'
<ide> if interpolation in interpolations:
<ide> x = tf.image.resize(x, new_shape, method=interpolations[interpolation])
<ide> else:
<ide><path>keras/layers/reshaping/up_sampling2d.py
<ide> class UpSampling2D(Layer):
<ide> It defaults to the `image_data_format` value found in your
<ide> Keras config file at `~/.keras/keras.json`.
<ide> If you never set it, then it will be "channels_last".
<del> interpolation: A string, one of `area`, `bicubic`, `bilinear`, `gaussian`,
<del> `lanczos3`, `lanczos5`, `mitchellcubic`, `nearest`.
<add> interpolation: A string, one of `"area"`, `"bicubic"`, `"bilinear"`,
<add> `"gaussian"`, `"lanczos3"`, `"lanczos5"`, `"mitchellcubic"`, `"nearest"`.
<ide>
<ide> Input shape:
<ide> 4D tensor with shape:
<ide> def __init__(self,
<ide> 'mitchellcubic': tf.image.ResizeMethod.MITCHELLCUBIC,
<ide> 'nearest': tf.image.ResizeMethod.NEAREST_NEIGHBOR,
<ide> }
<del> interploations_list = '`' + '`, `'.join(interpolations.keys()) + '`'
<add> interploations_list = '"' + '", "'.join(interpolations.keys()) + '"'
<ide> if interpolation not in interpolations:
<ide> raise ValueError('`interpolation` argument should be one of: '
<ide> f'{interploations_list}. Received: "{interpolation}".') | 2 |
Javascript | Javascript | fix ukrainian version when build relative time | 96a1ede9913ef3aac7b39909b63df917d41cff6a | <ide><path>src/locale/uk.js
<ide> function plural(word, num) {
<ide> }
<ide> function relativeTimeWithPlural(number, withoutSuffix, key) {
<ide> var format = {
<del> 'mm': 'хвилина_хвилини_хвилин',
<del> 'hh': 'година_години_годин',
<add> 'mm': withoutSuffix ? 'хвилина_хвилини_хвилин' : 'хвилину_хвилини_хвилин',
<add> 'hh': withoutSuffix ? 'година_години_годин' : 'годину_години_годин',
<ide> 'dd': 'день_дні_днів',
<ide> 'MM': 'місяць_місяці_місяців',
<ide> 'yy': 'рік_роки_років' | 1 |
Javascript | Javascript | add test cases | 11e71ed26b8d0aca31d782c91588612f0e59b020 | <ide><path>test/WatchDetection.test.js
<ide> describe("WatchDetection", () => {
<ide>
<ide> jest.setTimeout(10000);
<ide>
<add> createTestCase(100, true);
<add> createTestCase(10, true);
<add> createTestCase(600, true);
<ide> for (let changeTimeout = 10; changeTimeout < 100; changeTimeout += 10) {
<ide> createTestCase(changeTimeout);
<ide> }
<ide> for (let changeTimeout = 200; changeTimeout <= 2000; changeTimeout += 200) {
<ide> createTestCase(changeTimeout);
<ide> }
<ide>
<del> function createTestCase(changeTimeout) {
<del> describe(`time between changes ${changeTimeout}ms`, () => {
<add> function createTestCase(changeTimeout, invalidate) {
<add> describe(`time between changes ${changeTimeout}ms${
<add> invalidate ? " with invalidate call" : ""
<add> }`, () => {
<ide> const fixturePath = path.join(
<ide> __dirname,
<ide> "fixtures",
<ide> describe("WatchDetection", () => {
<ide> }
<ide>
<ide> function step2() {
<del> onChange = null;
<add> onChange = () => {
<add> expect(compiler.modifiedFiles).not.toBe(undefined);
<add> expect(compiler.removedFiles).not.toBe(undefined);
<add> };
<ide>
<ide> fs.writeFile(
<ide> filePath,
<ide> describe("WatchDetection", () => {
<ide> }
<ide>
<ide> function step3() {
<del> onChange = null;
<del>
<add> if (invalidate) watcher.invalidate();
<ide> fs.writeFile(file2Path, "wrong", "utf-8", handleError);
<ide>
<ide> setTimeout(step4, changeTimeout);
<ide> }
<ide>
<ide> function step4() {
<ide> onChange = () => {
<add> expect(compiler.modifiedFiles).not.toBe(undefined);
<add> expect(compiler.removedFiles).not.toBe(undefined);
<ide> if (
<ide> memfs
<ide> .readFileSync("/directory/bundle.js") | 1 |
Javascript | Javascript | enable linter on spec/ folder | 8daaf3834eaa09e1b962d42984930e1bc8a357a8 | <ide><path>script/lib/lint-java-script-paths.js
<ide> const path = require('path')
<ide>
<ide> const CONFIG = require('../config')
<ide>
<del>module.exports = function () {
<add>module.exports = async function () {
<ide> const globPathsToLint = [
<ide> path.join(CONFIG.repositoryRootPath, 'exports', '**', '*.js'),
<ide> path.join(CONFIG.repositoryRootPath, 'packages', '**', '*.js'),
<ide> path.join(CONFIG.repositoryRootPath, 'script', '**', '*.js'),
<add> path.join(CONFIG.repositoryRootPath, 'spec', '**', '*.js'),
<ide> path.join(CONFIG.repositoryRootPath, 'src', '**', '*.js'),
<ide> path.join(CONFIG.repositoryRootPath, 'static', '*.js')
<ide> ]
<del> return expandGlobPaths(globPathsToLint).then((paths) => {
<del> return new Promise((resolve, reject) => {
<del> standard.lintFiles(paths, (error, lintOutput) => {
<del> if (error) {
<del> reject(error)
<del> } else {
<del> const errors = []
<del> for (let result of lintOutput.results) {
<del> for (let message of result.messages) {
<del> errors.push({path: result.filePath, lineNumber: message.line, message: message.message, rule: message.ruleId})
<del> }
<add> const globPathsToIgnore = [
<add> path.join(CONFIG.repositoryRootPath, 'spec', 'fixtures', '**', '*.js')
<add> ]
<add>
<add> const [includePaths, excludePaths] = await Promise.all([
<add> expandGlobPaths(globPathsToLint),
<add> expandGlobPaths(globPathsToIgnore)
<add> ])
<add>
<add> const paths = includePaths.filter(
<add> myPath => excludePaths.indexOf(myPath) === -1
<add> )
<add>
<add> return new Promise((resolve, reject) => {
<add> standard.lintFiles(paths, (error, lintOutput) => {
<add> if (error) {
<add> reject(error)
<add> } else {
<add> const errors = []
<add> for (let result of lintOutput.results) {
<add> for (let message of result.messages) {
<add> errors.push({
<add> path: result.filePath,
<add> lineNumber: message.line,
<add> message: message.message,
<add> rule: message.ruleId
<add> })
<ide> }
<del> resolve(errors)
<ide> }
<del> })
<add> resolve(errors)
<add> }
<ide> })
<ide> })
<ide> } | 1 |
Javascript | Javascript | flow autofix animatedimplementation.js | e6b850871b44169ef071e63213c0383777634340 | <ide><path>Libraries/Animated/src/AnimatedImplementation.js
<ide> class Animated {
<ide> }
<ide>
<ide> type AnimationConfig = {
<del> isInteraction?: bool;
<del> useNativeDriver?: bool;
<add> isInteraction?: bool,
<add> useNativeDriver?: bool,
<ide> };
<ide>
<ide> // Important note: start() and stop() will only be called at most once.
<ide> function _flush(rootNode: AnimatedValue): void {
<ide> }
<ide>
<ide> type TimingAnimationConfig = AnimationConfig & {
<del> toValue: number | AnimatedValue | {x: number, y: number} | AnimatedValueXY;
<del> easing?: (value: number) => number;
<del> duration?: number;
<del> delay?: number;
<add> toValue: number | AnimatedValue | {x: number, y: number} | AnimatedValueXY,
<add> easing?: (value: number) => number,
<add> duration?: number,
<add> delay?: number,
<ide> };
<ide>
<ide> type TimingAnimationConfigSingle = AnimationConfig & {
<del> toValue: number | AnimatedValue;
<del> easing?: (value: number) => number;
<del> duration?: number;
<del> delay?: number;
<add> toValue: number | AnimatedValue,
<add> easing?: (value: number) => number,
<add> duration?: number,
<add> delay?: number,
<ide> };
<ide>
<ide> let _easeInOut;
<ide> class TimingAnimation extends Animation {
<ide> }
<ide>
<ide> type DecayAnimationConfig = AnimationConfig & {
<del> velocity: number | {x: number, y: number};
<del> deceleration?: number;
<add> velocity: number | {x: number, y: number},
<add> deceleration?: number,
<ide> };
<ide>
<ide> type DecayAnimationConfigSingle = AnimationConfig & {
<del> velocity: number;
<del> deceleration?: number;
<add> velocity: number,
<add> deceleration?: number,
<ide> };
<ide>
<ide> class DecayAnimation extends Animation {
<ide> class DecayAnimation extends Animation {
<ide> }
<ide>
<ide> type SpringAnimationConfig = AnimationConfig & {
<del> toValue: number | AnimatedValue | {x: number, y: number} | AnimatedValueXY;
<del> overshootClamping?: bool;
<del> restDisplacementThreshold?: number;
<del> restSpeedThreshold?: number;
<del> velocity?: number | {x: number, y: number};
<del> bounciness?: number;
<del> speed?: number;
<del> tension?: number;
<del> friction?: number;
<add> toValue: number | AnimatedValue | {x: number, y: number} | AnimatedValueXY,
<add> overshootClamping?: bool,
<add> restDisplacementThreshold?: number,
<add> restSpeedThreshold?: number,
<add> velocity?: number | {x: number, y: number},
<add> bounciness?: number,
<add> speed?: number,
<add> tension?: number,
<add> friction?: number,
<ide> };
<ide>
<ide> type SpringAnimationConfigSingle = AnimationConfig & {
<del> toValue: number | AnimatedValue;
<del> overshootClamping?: bool;
<del> restDisplacementThreshold?: number;
<del> restSpeedThreshold?: number;
<del> velocity?: number;
<del> bounciness?: number;
<del> speed?: number;
<del> tension?: number;
<del> friction?: number;
<add> toValue: number | AnimatedValue,
<add> overshootClamping?: bool,
<add> restDisplacementThreshold?: number,
<add> restSpeedThreshold?: number,
<add> velocity?: number,
<add> bounciness?: number,
<add> speed?: number,
<add> tension?: number,
<add> friction?: number,
<ide> };
<ide>
<ide> function withDefault<T>(value: ?T, defaultValue: T): T {
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> }
<ide> }
<ide>
<del>type ValueXYListenerCallback = (value: {x: number; y: number}) => void;
<add>type ValueXYListenerCallback = (value: {x: number, y: number}) => void;
<ide>
<ide> /**
<ide> * 2D Value for driving 2D animations, such as pan gestures. Almost identical
<ide> type ValueXYListenerCallback = (value: {x: number; y: number}) => void;
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> x: AnimatedValue;
<ide> y: AnimatedValue;
<del> _listeners: {[key: string]: {x: string; y: string}};
<add> _listeners: {[key: string]: {x: string, y: string}};
<ide>
<del> constructor(valueIn?: ?{x: number | AnimatedValue; y: number | AnimatedValue}) {
<add> constructor(valueIn?: ?{x: number | AnimatedValue, y: number | AnimatedValue}) {
<ide> super();
<ide> var value: any = valueIn || {x: 0, y: 0}; // @flowfixme: shouldn't need `: any`
<ide> if (typeof value.x === 'number' && typeof value.y === 'number') {
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> this._listeners = {};
<ide> }
<ide>
<del> setValue(value: {x: number; y: number}) {
<add> setValue(value: {x: number, y: number}) {
<ide> this.x.setValue(value.x);
<ide> this.y.setValue(value.y);
<ide> }
<ide>
<del> setOffset(offset: {x: number; y: number}) {
<add> setOffset(offset: {x: number, y: number}) {
<ide> this.x.setOffset(offset.x);
<ide> this.y.setOffset(offset.y);
<ide> }
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> this.y.flattenOffset();
<ide> }
<ide>
<del> __getValue(): {x: number; y: number} {
<add> __getValue(): {x: number, y: number} {
<ide> return {
<ide> x: this.x.__getValue(),
<ide> y: this.y.__getValue(),
<ide> class AnimatedTracking extends Animated {
<ide> }
<ide>
<ide> type CompositeAnimation = {
<del> start: (callback?: ?EndCallback) => void;
<del> stop: () => void;
<add> start: (callback?: ?EndCallback) => void,
<add> stop: () => void,
<ide> };
<ide>
<ide> var add = function(
<ide> var sequence = function(
<ide> };
<ide>
<ide> type ParallelConfig = {
<del> stopTogether?: bool; // If one is stopped, stop all. default: true
<add> stopTogether?: bool, // If one is stopped, stop all. default: true
<ide> }
<ide> var parallel = function(
<ide> animations: Array<CompositeAnimation>, | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.